blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 7
332
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
50
| license_type
stringclasses 2
values | repo_name
stringlengths 7
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 557
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
684M
โ | star_events_count
int64 0
77.7k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 82
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
5.41M
| extension
stringclasses 11
values | content
stringlengths 7
5.41M
| authors
listlengths 1
1
| author
stringlengths 0
161
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
605e19b22cba013f8a1830819a37b490b6c7e50b | 22b1fe6a0af8ab3c662551185967bf2a6034a5d2 | /experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_4754.java | 7d6c815663aefad486825b4aa87593b3d0c22a2d | [
"Apache-2.0"
]
| permissive | lesaint/experimenting-annotation-processing | b64ed2182570007cb65e9b62bb2b1b3f69d168d6 | 1e9692ceb0d3d2cda709e06ccc13290262f51b39 | refs/heads/master | 2021-01-23T11:20:19.836331 | 2014-11-13T10:37:14 | 2014-11-13T10:37:14 | 26,336,984 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 151 | java | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_4754 {
}
| [
"[email protected]"
]
| |
3f3d658175a12c64b4fb24749b4e1e63264e0c75 | a8d6ffeddc091c05d3413b7857f7f960a25c77f2 | /src/davinDBMS/entity/Column.java | 00d229b59a23db1b2cdf75b8c467aba2551b38f0 | []
| no_license | davin111/myOwnDBMS | d06f3994bf404796e3eb484c6ffd96cfbb6ec808 | 9390393e463e7a98ea1c6ceadb32a3f42cef94a6 | refs/heads/master | 2020-05-16T08:03:07.570733 | 2019-05-16T15:58:33 | 2019-05-16T15:58:33 | 182,896,569 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,375 | java | package davinDBMS.entity;
import java.io.Serializable;
import java.util.ArrayList;
public class Column implements Serializable {
public enum DataType{
INT, CHAR, DATE
}
private String name;
private DataType dataType;
private int charLength;
private boolean canBeNull = true;
private boolean isPri = false;
private boolean isFor = false;
private Table belongToTable = null;
private Table referToTable = null;
private Column referToColumn = null;
private ArrayList<Table> referredByTables = new ArrayList<Table>();
//constructors
public Column(){
name = "";
}
public Column(String name){
this.name = name;
}
//basic accessors and mutators
public String getName(){
return name;
}
public DataType getType() {
return dataType;
}
public boolean isPrimaryKey() {
return isPri;
}
public boolean isForeignKey() {
return isFor;
}
public int getCharLength() {
return charLength;
}
public boolean canBeNull() {
return canBeNull;
}
public void setPrimaryKey() {
isPri = true;
canBeNull = false;
}
public void setForeignKey() {
isFor = true;
}
public void setNotNull() {
canBeNull = false;
}
public void setType(DataType datatype) {
this.dataType = datatype;
}
public void setCharLength(int n) {
charLength = n;
}
public void setBelongToTable(Table table) {
belongToTable = table;
}
public void setReferToTable(Table table) {
referToTable = table;
}
public void setReferToColumn(Column column) {
referToColumn = column;
}
public Table getBelongToTable() {
return belongToTable;
}
public Table getReferToTable() {
return referToTable;
}
public Column getReferToColumn() {
return referToColumn;
}
public ArrayList<Table> getReferredByTables() {
return referredByTables;
}
//methods for desc query
public String getTypeToString() {
String typeInfo = "" + dataType;
if(dataType == DataType.CHAR) {
typeInfo += "(" + charLength + ")";
}
return typeInfo.toLowerCase();
}
public String getKeyTypeToString() {
String keyInfo = "";
if(isPri) {
keyInfo += "PRI";
if(isFor) {
keyInfo += "/FOR";
}
}
else if(isFor){
keyInfo += "FOR";
}
return keyInfo;
}
}
| [
"[email protected]"
]
| |
2234daa1754ff39ed55f64d7ee31c0f892ecd0d7 | 8476ab7f210b2165c59a31e271566923d6598c4e | /app/src/main/java/mx/itesm/acmjscb/metodosnumericos/ActGauss.java | 37abc974137afe6f554328a22cc269c02975305b | []
| no_license | AlejandroCamara/MetodosNumericos2 | fbc33355f4a33776fa6847fde238b287c9b65e4f | 558fcedbd0c867ecc2402a5d428af5c8261e6045 | refs/heads/master | 2021-03-30T16:17:20.087167 | 2017-05-09T18:31:13 | 2017-05-09T18:31:13 | 90,763,807 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 347 | java | package mx.itesm.acmjscb.metodosnumericos;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class ActGauss extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act_gauss);
}
}
| [
"[email protected]"
]
| |
d0a71b59cb8c08d9fa45efba9eb9a8dd6c603f9f | 99bec3de28390ea0ed4fd83d2ee34f26de528c66 | /src/main/java/demo/rest/EmployeeRestController.java | 61d4b8af6116eb0d8d446a98a51f5d7905fb79c3 | [
"MIT"
]
| permissive | samallenqing/compositeApps | 1e2e66c2e11d1df76f030bbe492cb2de9acfb826 | 28bc45245af2e58a3dd322b7f8ae8a332c3d10b4 | refs/heads/master | 2021-07-16T15:53:11.332887 | 2017-10-23T19:33:58 | 2017-10-23T19:33:58 | 108,028,199 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,070 | java | package demo.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import demo.model.Employee;
import demo.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(value = "/api")
@Slf4j
public class EmployeeRestController {
private EmployeeService employeeService;
@Autowired
public EmployeeRestController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@RequestMapping(value = "employees", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.CREATED)
public void uplodeEmployees(@RequestBody List<Employee> employees) {
employeeService.saveAll(employees);
}
@RequestMapping(value = "employees", method = RequestMethod.GET)
public List<Employee> showAll() {
return employeeService.findAllEmployee();
}
@RequestMapping(value = "employee", method = RequestMethod.GET)
public List<Employee> findEmployeesByName(@RequestParam(value = "name") String name) {
return employeeService.findEmployeeByName(name);
}
@RequestMapping(value = "employees", method = RequestMethod.DELETE)
public void deletAll() {
employeeService.deleteAll();
}
@RequestMapping(value = "employee", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.CREATED)
public void addEmployee(@RequestBody Employee employee) {
log.info("The employee info is:" + employee.getName()+"\n"+employee.getPhoneNumber()+"\n"+employee.getSupervisors());
employeeService.addEmployee(employee);
}
@RequestMapping(value = "employees/{id}", method = RequestMethod.DELETE)
public List<Employee> deleteById(@PathVariable(value = "id") String id) {
log.info("The id info is:" + id);
employeeService.removeEmployeById(id);
return employeeService.findAllEmployee();
}
}
| [
"[email protected]"
]
| |
f1567fddb3fa6cbf45cc5d2742e1ab6d8f431d85 | 9f98b84222647b099c7537e29ef1b8b678943fe6 | /src/FindOccurences.java | e9975ff4375e90f7acbf85fb58b1710fabb9cb41 | []
| no_license | Harshiiitha/JavaPractiseExcercise4 | efdadbff2e06690779796c686869771a4dd5fd95 | e0ceceebd946425e377f0c40a8cfebc892cf4b12 | refs/heads/master | 2020-05-24T08:41:16.483451 | 2019-05-17T09:33:29 | 2019-05-17T09:33:29 | 187,188,527 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 507 | java | import java.util.ArrayList;
import java.util.List;
import java.util.regex.*;
import java.io.*;
public class FindOccurences
{
public List<String> findOccurences(String input,String find)
{
List<String> result=new ArrayList<String>();
Pattern p=Pattern.compile(find);
Matcher m=p.matcher(input);
while(m.find())
{
result.add("Found at:"+m.start()+"-"+m.end());//finding start and end inndex of given string
}
return result;
}
}
| [
"[email protected]"
]
| |
e623309d0c43f15c4dacfa1be9c2901ff84ed5ed | 2b3f710b24da35d381897669955198dd5236148d | /homework11/src/main/java/ru/otus/spring/web/GenreController.java | 303de2abb1bf6c50cdf3485bf2df2f8f202a1831 | []
| no_license | EvgenyBagdasaryan/2020-05-otus-spring-Bagdasaryan | d6eeeb8d962b7d94d58e6aad0f3fc493c67feb3f | 8111980598a47bea18198171040f8690ff78e45c | refs/heads/master | 2023-07-07T16:40:09.500150 | 2021-08-24T11:58:59 | 2021-08-24T11:58:59 | 268,648,303 | 0 | 0 | null | 2021-08-24T11:59:00 | 2020-06-01T22:42:04 | Java | UTF-8 | Java | false | false | 1,429 | java | package ru.otus.spring.web;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import ru.otus.spring.domain.Genre;
import ru.otus.spring.repository.GenreRepository;
@CrossOrigin(origins = {"http://localhost:8080"})
@RestController
@RequiredArgsConstructor
@Slf4j
class GenreController {
private final GenreRepository genreRepository;
@GetMapping(value = "/genres")
public Flux<Genre> getAll() {
log.info("getAll");
return genreRepository.findAll();
}
@GetMapping(value = "/genres/{id}")
public Mono<Genre> getById(@PathVariable("id") String id) {
log.info("getById");
return genreRepository.findById(id);
}
@PostMapping(value = "/genres")
public Mono<Genre> create(@RequestBody Genre newGenre) {
log.info("create: {}", newGenre);
return genreRepository.save(newGenre);
}
@PutMapping(value = "/genres/{id}")
public Mono<Genre> update(@PathVariable("id") String id, @RequestBody Genre forUpdate) {
log.info("update: {}", forUpdate);
return genreRepository.save(forUpdate);
}
@DeleteMapping(value = "/genres/{id}")
public Mono<Void> delete(@PathVariable("id") String id) {
log.info("delete");
return genreRepository.deleteById(id);
}
}
| [
"[email protected]"
]
| |
b0055100bfae478e032091064417f6055c7d9b8d | ba44e8867d176d74a6ca0a681a4f454ca0b53cad | /testscript/Workflow/Controls/Validate_Message_Android.java | 965a7c74cfccdff6e1fdc9324c412c336910a49b | []
| no_license | eric2323223/FATPUS | 1879e2fa105c7e7683afd269965d8b59a7e40894 | 989d2cf49127d88fdf787da5ca6650e2abd5a00e | refs/heads/master | 2016-09-15T19:10:35.317021 | 2012-06-29T02:32:36 | 2012-06-29T02:32:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,524 | java | package testscript.Workflow.Controls;
import resources.testscript.Workflow.Controls.Validate_Message_AndroidHelper;
import testscript.Workflow.cfg.Cfg;
import com.rational.test.ft.*;
import com.rational.test.ft.object.interfaces.*;
import com.rational.test.ft.object.interfaces.SAP.*;
import com.rational.test.ft.object.interfaces.WPF.*;
import com.rational.test.ft.object.interfaces.dojo.*;
import com.rational.test.ft.object.interfaces.siebel.*;
import com.rational.test.ft.object.interfaces.flex.*;
import com.rational.test.ft.script.*;
import com.rational.test.ft.value.*;
import com.rational.test.ft.vp.*;
import component.entity.EE;
import component.entity.WN;
import component.entity.WorkFlow;
import component.entity.WorkFlowEditor;
import component.entity.model.DeployOption;
import component.entity.model.DeployedMbo;
import component.entity.model.Relationship;
import component.entity.model.WFEditBox;
import component.entity.model.WFScreenMenuItem;
import component.entity.model.WFSlider;
import component.entity.model.WorkFlowPackage;
import component.entity.tplan.Robot;
import component.entity.tplan.TestResult;
/**
* Description : Functional Test Script
* @author eric
*/
public class Validate_Message_Android extends Validate_Message_AndroidHelper
{
/**
* Script Name : <b>Validate_Message_Android</b>
* Generated : <b>Aug 31, 2011 2:10:59 PM</b>
* Description : Functional Test Script
* Original Host : WinNT Version 5.1 Build 2600 (S)
*
* @since 2011/08/31
* @author FANFEI
*/
public void testMain(Object[] args)
{
// TODO Insert code here
WN.useProject(Cfg.projectName);
EE.dnd(EE.parseResourcePath("Database Connections->My Sample Database->sampledb->Tables->department (dba)"), 10, 10);
WN.deployProject(new DeployOption().startParameter(Cfg.projectName)
.server("My Unwired Server")
.serverConnectionMapping("My Sample Database,simpledb"));
vpManual("deploy", true, EE.ifMboDeployed(new DeployedMbo()
.connectionProfile("My Unwired Server")
.domain("default")
.name("Department")
.pkg(Cfg.projectName+":1.0"))).performTest();
WN.createWorkFlow(new WorkFlow().startParameter(Cfg.projectName)
.name("wfmbocreate")
.option(WorkFlow.SP_CLIENT_INIT));
WorkFlowEditor.addWidget(Cfg.projectName, "wfmbocreate.xbw", "Start Screen", new WFSlider().label("id:")
.labelPosition("LEFT")
.newKey("key1,int")
.maxValue("20")
.minValue("0"));
WorkFlowEditor.addWidget(Cfg.projectName, "wfmbocreate.xbw", "Start Screen", new WFSlider().label("head:")
.labelPosition("LEFT")
.newKey("key2,int")
.maxValue("30")
.minValue("0"));
WorkFlowEditor.addWidget(Cfg.projectName, "wfmbocreate.xbw", "Start Screen", new WFEditBox().label("name:")
.labelPosition("LEFT")
.newKey("key3,string"));
String[] parameter={"dept_id,key1","dept_head_id,key2","dept_name,key3"};
WorkFlowEditor.addMenuItem("Start Screen", new WFScreenMenuItem()
.name("create")
.type("Online Request")
.mbo("wf/Department")
.operation("create")
.parametermapping(parameter));
WN.createWorkFlowPackage(new WorkFlowPackage()
.startParameter(WN.wfPath(Cfg.projectName, "wfmbocreate.xbw"))
.unwiredServer("My Unwired Server")
.assignToUser("DeviceTest")
.verifyResult("Successfully deployed the workflow", true));
// only need to input invalide value in android
// TestResult result = Robot.run(this);
// vpManual("DeviceTest", true, result.isPass()).performTest();
}
}
| [
"[email protected]"
]
| |
3a4704475e4a9d26eeee93196d87004b52e743c2 | 4fa09a1d83edc635337d9f42ea277ada042c3fa7 | /steam_test/src/test/java/project/enums/SortBy.java | f98aff1da2c7679e6d66c79b105037daca9c6f4a | []
| no_license | g-kozinets/aqua_self_edu | e24b5f71ece11175d1eeb71e3a93d244f26f422b | 5b99f88da49d72e0e74e9de14e4d67631e388169 | refs/heads/g.kozinets_Web_automation_test_framework_(Steam) | 2023-05-11T09:28:46.310859 | 2019-11-22T11:52:08 | 2019-11-22T11:52:08 | 222,713,037 | 0 | 0 | null | 2023-05-09T18:16:02 | 2019-11-19T14:19:05 | Java | UTF-8 | Java | false | false | 65 | java | package project.enums;
public enum SortBy {
MAX,
MIN,
}
| [
"[email protected]"
]
| |
d78680cd964abe22c6d308dd9619b9e6d3ed0b45 | efa7f485da689e78de8d1c264d32a96754f9293d | /core/src/main/java/com/yztc/core/image/ImageLoader.java | 1f93caa8572aeb9339043a6a19ab89761af7d429 | []
| no_license | 1426657363/damai | 148633ff4a79165e1a67d57bf197f2f3c664cddb | 03f264c19fa185054211e9e6d0149a2a21bd88f9 | refs/heads/master | 2021-01-12T07:46:48.128737 | 2016-12-20T13:03:01 | 2016-12-20T13:03:01 | 77,013,413 | 1 | 0 | null | 2016-12-21T03:43:07 | 2016-12-21T03:43:07 | null | UTF-8 | Java | false | false | 12,280 | java | package com.yztc.core.image;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.LruCache;
import android.view.View;
import android.widget.ImageView;
import com.yztc.core.utils.AppUtils;
import com.yztc.core.utils.DiskLruCache;
import com.yztc.core.utils.FileUtils;
import com.yztc.core.utils.MD5Utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by wanggang on 2016/12/12.
*/
//UIL Picasso Glide Fresco
public class ImageLoader {
private static final int SOFT_CACHE_SIZE = 20;
private static final int DISK_CACHE_SIZE = 20 * 1024 * 1024;
private static final int MAX_THREAD_NUM = 10;
private LruCache<String, Bitmap> mLruCache;
private LinkedHashMap<String, SoftReference<Bitmap>> mSoftCache;
private DiskLruCache mDiskCache;
//ไธ่ฝฝ้ๅ
private Set<ImageDownloadTask> loadingQueue;
// ็ญๅพ
ไธ่ฝฝ้ๅ
private List<ImageDownloadTask> waitingQueue;
//ๆญฃๅจ่ฟ่กไธ่ฝฝไปปๅก็imageview
private LinkedHashMap<String, View> imageViewManager;
private ExecutorService executorService;
private static ImageLoader instance = null;
public static ImageLoader getInstance() {
if (instance == null) {
synchronized (ImageLoader.class) {
if (instance == null)
instance = new ImageLoader();
}
}
return instance;
}
/**
* ๅ ่ฝฝๅพ็
*
* @param imgView View
* @param imageUrl ๅพ็ๅฐๅ
* @param priority ไผๅ
็บง
*/
public void loadImages(ImageView imgView, String imageUrl, boolean priority) {
Bitmap bitmap = getBitmapFromCache(imageUrl);
if (bitmap == null) {
imageViewManager.put(imageUrl, imgView);
imgView.setTag(imageUrl);
ImageDownloadTask task = new ImageDownloadTask(imageUrl);
addTaskToQueue(task, priority);
} else {
if (imgView != null && bitmap != null) {
imgView.setImageBitmap(bitmap);
}
}
}
private void addTaskToQueue(ImageDownloadTask task, boolean priority) {
if (loadingQueue.size() < MAX_THREAD_NUM) {
//ๆทปๅ ๅฐไธ่ฝฝ้ๅ
loadingQueue.add(task);
task.executeOnExecutor(executorService);;
} else {
//ๆทปๅ ๅฐ็ญๅพ
้ๅ
if (priority)
waitingQueue.add(0, task);
else
waitingQueue.add(task);
}
}
private Bitmap getBitmapFromCache(String imageUrl) {
if(TextUtils.isEmpty(imageUrl)){
return null;
}
Bitmap bitmap = mLruCache.get(imageUrl);
if (bitmap != null) {
return bitmap;
}
SoftReference<Bitmap> softReference =
mSoftCache.get(imageUrl);
if (softReference != null) {
bitmap = softReference.get();
if (bitmap != null) {
mLruCache.put(imageUrl, bitmap);
mSoftCache.remove(imageUrl);
return bitmap;
} else {
mSoftCache.remove(imageUrl);
}
}
return null;
}
private ImageLoader() {
//Lru
initLruCache();
//Soft
initSoftCache();
//disk
initLocalCache();
//ๆญฃๅจไธ่ฝฝ็้ๅ ๅช่ฝๅญๅจไธ้ๅค็ๅฏน่ฑก
loadingQueue = new HashSet<>();
//็ญๅพ
ไธ่ฝฝ็้ๅ
waitingQueue = new ArrayList<>();
//imageView url ็ปๅฎ
imageViewManager = new LinkedHashMap<>();
//็บฟ็จๆฑ
executorService = Executors.newFixedThreadPool(MAX_THREAD_NUM);
}
private void initLocalCache() {
try {
//1 ็ผๅญ่ทฏๅพ
//2 app็ๆฌ ๅฝ็ๆฌๅๅๆถ๏ผไผๆธ
้คไนๅ็ๆฐๆฎ
//3 key-value 1 1keyๅฏนๅบ1valueไธชๅผ
//4 ็ผๅญ็ฉบ้ดๅคงๅฐ
mDiskCache = DiskLruCache.open(
FileUtils.getImageCacheFloder(),
AppUtils.getAppVersion(),
1,
DISK_CACHE_SIZE
);
} catch (IOException e) {
e.printStackTrace();
}
}
//SoftCache
private void initSoftCache() {
//true LRU็ฎๆณ
mSoftCache = new LinkedHashMap<String, SoftReference<Bitmap>>(
SOFT_CACHE_SIZE, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Entry eldest) {
//้ๅถ ้พ่กจ็้ฟๅบฆ
if (size() > SOFT_CACHE_SIZE) {
//ๅจๆทปๅ ๆฐ itemๆถ๏ผ็งป้คๆไธๅธธ็จ็ item
return true;
}
return false;
}
};
}
//LruCache
private void initLruCache() {
//็ณป็ปไธบApp ๅ้
็ๆๅคงๅ
ๅญ
long maxMemory = Runtime.getRuntime().maxMemory();
mLruCache = new LruCache<String, Bitmap>((int) (maxMemory / 8)) {
//่ฎก็ฎๆฏไธชๅ
็ด ๅ ็จ็ฉบ้ด็ๅคงๅฐ
@Override
protected int sizeOf(String key, Bitmap value) {
//png ๅฎฝ*้ซ*32
if (value != null)
return value.getRowBytes() * value.getHeight();
return 0;
}
//ๅฝ็ฉบ้ดๆปก็ๆถๅ๏ผๅ
็ด ่ขซๆคๅบๆฅ
@Override
protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
super.entryRemoved(evicted, key, oldValue, newValue);
if (oldValue != null) {
mSoftCache.put(key, new SoftReference<Bitmap>(oldValue));
}
}
};
}
/**
* ๅ ่ฝฝๆฌๅฐๅพ็
* ็ฝ็ปๅพ็
*/
class ImageDownloadTask extends AsyncTask<String, Void, Bitmap> {
private String imageUrl;
public ImageDownloadTask(String imageUrl) {
this.imageUrl = imageUrl;
}
@Override
protected Bitmap doInBackground(String... strings) {
InputStream inputStream = null;
DiskLruCache.Snapshot snapShot = null;
//ๆไปถๅๅญ
String key = MD5Utils.hashKeyForDisk(imageUrl);
try {
//ไปๆฌๅฐๅๅพ็
snapShot = mDiskCache.get(key);
//ๆฒกๆ็ผๅญ่ฟๅพ็๏ผไป็ฝไธไธ่ฝฝๅพ็
if (snapShot == null) {
DiskLruCache.Editor edit = mDiskCache.edit(key);
if (edit != null) {
OutputStream outputStream = edit.newOutputStream(0);
if (downloadImageToStream(imageUrl, outputStream)) {
//ไฟๅญๅพ็ๅฐๆฌๅฐ๏ผๆไปถ็ๅ็งฐๆฏkey
edit.commit();
} else {
edit.abort();
}
}
//ๅๆฌกๅ ่ฝฝ
snapShot = mDiskCache.get(key);
}
if (snapShot != null) {
inputStream = snapShot.getInputStream(0);
Bitmap bitmap = null;
if (inputStream != null) {
//RGB565 ๆนๅผๅ ่ฝฝๅพ็
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
bitmap = BitmapFactory.decodeStream(inputStream,null,options);
}
if (bitmap != null) {
mLruCache.put(imageUrl, bitmap);
}
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
ImageView view = (ImageView)
imageViewManager.get(imageUrl);
if (view != null && bitmap != null
&& view.getTag().equals(imageUrl)) {
//่งฃๅณๅพ็้ไฝ
view.setImageBitmap(bitmap);
}
if (loadingQueue != null)
loadingQueue.remove(this);
waitToLoadStrategy();
//ๅฐ็ผๅญ่ฎฐๅฝๅๆญฅๅฐjournalๆไปถไธญใ
if (mDiskCache != null) {
try {
mDiskCache.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//ไป็ญๅพ
้ๅไธญๅไปปๅก็ปง็ปญๆง่ก
private synchronized void waitToLoadStrategy() {
//ๅฏไปฅ็ปง็ปญๆง่กไปปๅก็ไธชๆฐ
int index = MAX_THREAD_NUM - loadingQueue.size();
for (int i = 0; i < index; i++) {
if (waitingQueue.size() > 0) {
ImageDownloadTask task = waitingQueue.get(0);
waitingQueue.remove(task);
loadingQueue.add(task);
task.executeOnExecutor(executorService);
} else {
break;
}
}
}
private boolean downloadImageToStream(String imageUrl, OutputStream outputStream) {
HttpURLConnection urlConnection = null;
BufferedOutputStream out = null;
BufferedInputStream in = null;
try {
final URL url = new URL(imageUrl);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream(),
8 * 1024);
out = new BufferedOutputStream(outputStream, 8 * 1024);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
return true;
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (final IOException e) {
e.printStackTrace();
}
}
return false;
}
/**
* ๆธ
็็ผๅญ
*/
public void onDestroy() {
cancelAllTasks();
mLruCache = null;
if (mSoftCache != null) {
mSoftCache.clear();
mSoftCache = null;
}
loadingQueue = null;
waitingQueue = null;
imageViewManager = null;
instance = null;
try {
mDiskCache.close();
mDiskCache = null;
} catch (IOException e) {
}
}
/**
* ๅๆถๆๆๆญฃๅจไธ่ฝฝๆ็ญๅพ
ไธ่ฝฝ็ไปปๅกใ
*/
public void cancelAllTasks() {
if (loadingQueue != null) {
for (ImageDownloadTask task : loadingQueue) {
task.cancel(false);
}
loadingQueue.clear();
}
if (waitingQueue != null) {
for (ImageDownloadTask task : waitingQueue) {
task.cancel(false);
}
waitingQueue.clear();
}
if (imageViewManager != null) {
imageViewManager.clear();
}
}
}
| [
"[email protected]"
]
| |
86af8d00e4e6f896e93b2e99084e4fbb78158268 | ab838f4c4678b8b7ff7f399e5f580073091814ea | /src/main/java/com/mindera/school/mindgesment/services/impl/UserChangeServiceImpl.java | cf8f84f142024d961235c40dec15de61073c60a5 | []
| no_license | MariaPereira1/be_mindgesment | e3bd20559b71c35a6e0f8a132980abd071e45252 | e5ef87765da7851a4243428f0a62d94212adcfb4 | refs/heads/master | 2022-11-05T00:15:34.351667 | 2020-06-22T17:50:48 | 2020-06-22T17:50:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,686 | java | package com.mindera.school.mindgesment.services.impl;
import com.mindera.school.mindgesment.data.entities.CoinEntity;
import com.mindera.school.mindgesment.data.entities.UserEntity;
import com.mindera.school.mindgesment.data.repositories.UserRepository;
import com.mindera.school.mindgesment.exceptions.EditError;
import com.mindera.school.mindgesment.exceptions.InvalidParameter;
import com.mindera.school.mindgesment.exceptions.UserNotExists;
import com.mindera.school.mindgesment.http.models.Coin;
import com.mindera.school.mindgesment.http.models.User;
import com.mindera.school.mindgesment.services.UserChangeService;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import java.util.Arrays;
@Service
public class UserChangeServiceImpl implements UserChangeService {
private final UserRepository userRepository;
private final MapperFacade mapper;
@Autowired
public UserChangeServiceImpl(UserRepository userRepository, MapperFacade mapper) {
this.userRepository = userRepository;
this.mapper = mapper;
}
@Override
public User changeUsername(String username, String usernameChange) {
var userChange = findUserEntity(username);
userChange.setUsername(usernameChange);
try {
return mapper.map(userRepository.save(userChange), User.class);
} catch (DataIntegrityViolationException e) {
throw new EditError("username of user", null);
}
}
@Override
public User changeCoin(String username, String coin) {
var userChange = findUserEntity(username);
if (Arrays.stream(Coin.values())
.noneMatch(coins -> coins.toString()
.equals(coin)))
throw new InvalidParameter("coin", Arrays.toString(Coin.values()));
userChange.setCoin(mapper.map(coin, CoinEntity.class));
try {
return mapper.map(userRepository.save(userChange), User.class);
} catch (DataIntegrityViolationException e) {
throw new EditError("coin of user", e);
}
}
@Override
public User changeEarnings(String username, Double earnings) {
var userChange = findUserEntity(username);
userChange.setEarnings(earnings);
try {
return mapper.map(userRepository.save(userChange), User.class);
} catch (DataIntegrityViolationException e) {
throw new EditError("earnings of user", e);
}
}
@Override
public User changeExpenses(String username, Double expenses) {
var userChange = findUserEntity(username);
userChange.setExpenses(expenses);
try {
return mapper.map(userRepository.save(userChange), User.class);
} catch (DataIntegrityViolationException e) {
throw new EditError("expenses of user", e);
}
}
@Override
public User changeMonthlyPeriod(String username, Integer monthlyPeriod) {
var user = findUserEntity(username);
user.setMonthlyPeriod(monthlyPeriod);
try {
return mapper.map(userRepository.save(user), User.class);
} catch (DataIntegrityViolationException e) {
throw new EditError("monthly period of user", e);
}
}
private UserEntity findUserEntity(String username) {
return userRepository.findByUsername(username)
.map(userEntity -> mapper.map(userEntity, UserEntity.class))
.orElseThrow(() -> new UserNotExists(username));
}
}
| [
"[email protected]"
]
| |
7e1e3b7b0a0c94305036cd6f1f5b41127135700d | de5c19f2c35866f56b9afe70cc536969425db7f9 | /src/main/java/br/com/letscode/service/ProfessorService.java | e001b37850e13a33d6ded814cd5c6c530b5dbff2 | []
| no_license | thiagomag/EscolaLetsCodeGradle | 4e9ebbb395a5be2529194269184c8093bcd376b0 | 5ad58380302ba2549b1b2a72892540225f839e80 | refs/heads/master | 2023-07-08T14:41:41.919301 | 2021-08-11T16:28:54 | 2021-08-11T16:28:54 | 394,487,442 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,441 | java | package br.com.letscode.service;
import br.com.letscode.exception.IdDoProfessorNaoExisteException;
import br.com.letscode.repository.ProfessorRepository;
import br.com.letscode.request.update.ProfessorReqAtualizar;
import br.com.letscode.request.ProfessorRequest;
import br.com.letscode.response.ProfessorResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.List;
@Service
@RequiredArgsConstructor
public class ProfessorService {
private final ProfessorRepository professorRepository;
public List<ProfessorResponse> buscarProfessores() {
var professor = professorRepository.findAll();
return ProfessorResponse.convert(professor);
}
public ProfessorResponse buscarPorId(Integer registroProfessor) {
var professor = professorRepository.findById(registroProfessor)
.orElseThrow(() -> new IdDoProfessorNaoExisteException(registroProfessor));
return new ProfessorResponse(professor);
}
public ResponseEntity<ProfessorResponse> adicionarProfessor(ProfessorRequest professorRequest,
UriComponentsBuilder uriComponentsBuilder) {
var professor = professorRequest.convert();
professorRepository.save(professor);
var uri = uriComponentsBuilder.path("/buscarProfessor/{registroProfessor}").buildAndExpand(
professor.getRegistroProfessor()).toUri();
return ResponseEntity.created(uri).body(new ProfessorResponse(professor));
}
public ResponseEntity<?> deletarProfessor(Integer registroProfessor) {
if(professorRepository.findById(registroProfessor).isPresent()) {
professorRepository.deleteById(registroProfessor);
return ResponseEntity.ok().build();
} else {
throw new IdDoProfessorNaoExisteException(registroProfessor);
}
}
public ResponseEntity<ProfessorResponse> atualizarProfessor(ProfessorReqAtualizar professorReqAtualizar,
Integer registroProfessor) {
var professor = professorReqAtualizar.convert(registroProfessor);
professorRepository.save(professor);
return ResponseEntity.ok(new ProfessorResponse(professor));
}
} | [
"[email protected]"
]
| |
02186d66a31188929c56b09a9b87d3fbcbca2f9a | 6e2ef31076da9e06a60b9c4494dc8e73f464b809 | /src/partie/Editeur.java | 463e9a34d501670a696689447d9efa0e13a33a98 | []
| no_license | seawarteam/SeaWar | 3803ed5ec9ca69cca3f5fcd95541060b5519e2b3 | 78399beb348099218669a3b88a30bb99a64ba674 | refs/heads/TheNewSeaWar | 2021-09-10T14:11:44.240024 | 2018-03-27T15:16:27 | 2018-03-27T15:16:27 | 111,335,530 | 0 | 0 | null | 2018-02-05T21:51:43 | 2017-11-19T22:00:21 | Java | UTF-8 | Java | false | false | 1,437 | java | package partie;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import erreur.FichierExistant;
public class Editeur extends Observable {
Plateau map;
Canons canonP;
Navire navire;
private int nbJoueurs;
public int nX, nY;
private Observer obs;
public Editeur(int nX, int nY, Observer obs) {
navire = new Navire("", 0, 0, "", Orientation.N, new Position(0, 0),
obs);
canonP = new Canons("", 0, 0, new LinkedList<Position>(), navire);
// canonS = new Canons("", 0, 0, new LinkedList<Position>(), navire);
addObserver(obs);
map = new Plateau(nX, nY, 0, 0, obs);
this.nX = nX;
this.nY = nY;
this.obs = obs;
nbJoueurs = 0;
}
public int getNbJoueurs() {
return nbJoueurs;
}
public Plateau getMap() {
return map;
}
public Canons getCanonP() {
return canonP;
}
public Navire getNavire() {
return navire;
}
/*
* public Canons getCanonS(){ return canonS; }
*/
public void resetPlateau() {
map = new Plateau(nX, nY, 0, 0, obs);
map.ResetCouleur();
}
public void resetCanon() {
List<Position> zone = canonP.getZoneTire();
zone.clear();
}
/*
public void resetNavire() {
String nom = navire.getNom();
nom = "";
int depMax = navire.getDepMax();
depMax = 5;
}*/
}
| [
"[email protected]"
]
| |
fc3e70285ed0c12ee6b15ba61930e6740c152169 | c7e905f05ce926e4e07852dd1dbc9d4ef3ffa63c | /Unit06Loiko/src/com/epam/unit06/task03/Main3.java | abe062c4e96e4a385b772614eb4fddbadfb37a55 | []
| no_license | VictorLoiko/Unit06Loiko | c85019c14304f7baaaad3b20a0b1c9276716fa03 | e2c56ff084c49d4d6b2e1493df9407e5f10e9bb3 | refs/heads/main | 2023-06-01T20:14:26.882524 | 2021-06-21T17:36:28 | 2021-06-21T17:36:28 | 379,013,773 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 938 | java | package com.epam.unit06.task03;
public class Main3 {
public static void main(String[] args){
BookAggregator library = new BookAggregator();
library.addBook(new Book(1, "title", "authors1", "publisher", 1956, 674, 158.24,"hard"));
library.addBook(new Book(2, "title", "authors2", "publisher", 2011, 425, 154.33,"soft"));
library.addBook(new Book(3, "title", "authors3", "publisher", 1976, 453, 54674.43,"hard"));
library.addBook(new Book(4, "title", "authors3", "publisher", 1957, 42324, 678.43,"soft"));
library.addBook(new Book(5, "title", "authors4", "publisher", 2021, 694, 23.5,"soft"));
System.out.println("ะัะตะผ ะฟะพ ะฐะฒัะพัั 'authors3'");
System.out.println(library.searchByAuthor("authors3"));
System.out.println("ะัะตะผ ะบะฝะธะณะธ ััะฐััะต 2000 ะณะพะดะฐ");
System.out.println(library.searchByYear(2000));
}
}
| [
"[email protected]"
]
| |
509e56ed55ece970341f6ab711868be8eb012677 | 183f640b0ab6a6da85da1b09290965618083d874 | /itest/references-collection/src/main/java/crawler/impl/CrawlerImpl.java | 0224d7750e7d628f022fc1a4a47d4c7159f05247 | []
| no_license | apache/tuscany-sca-1.x | 8543e4434f4d8650630bddf26b040d48aee789e9 | 3eb5a6521521398d167f32da995c868ac545163b | refs/heads/trunk | 2023-09-04T10:37:39.056392 | 2011-12-14T12:09:11 | 2011-12-14T12:09:11 | 390,001 | 4 | 18 | null | 2023-08-29T21:44:23 | 2009-11-30T09:00:10 | Java | UTF-8 | Java | false | false | 1,950 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package crawler.impl;
import crawler.Crawler;
import org.osoa.sca.ComponentContext;
import org.osoa.sca.annotations.AllowsPassByReference;
import org.osoa.sca.annotations.Context;
import org.osoa.sca.annotations.ConversationID;
import org.osoa.sca.annotations.Property;
import org.osoa.sca.annotations.Scope;
import org.osoa.sca.annotations.Service;
@Service(Crawler.class)
@AllowsPassByReference
@Scope("CONVERSATION")
public class CrawlerImpl implements Crawler
{
@ConversationID
protected String conversationId;
@Property
protected String crawlerId;
@Context
protected ComponentContext componentContext;
/**
* @see Crawler#getCrawlerId()
*/
public String getCrawlerId()
{
return crawlerId;
}
/**
* @see Crawler#crawl()
*/
public String crawl()
{
System.out.println("started crawl with conversation " + conversationId);
return "started crawl with id " + getCrawlerId();
}
/**
* @see Crawler#close()
*/
public String close()
{
return "ended conversation with id " + getCrawlerId();
}
} | [
"[email protected]"
]
| |
d47a4166cf25c5d58ec1d2d2640c4ed2c554e042 | 83e3e1d8f71ccc7b51e253b8ffbe96a0af0de87f | /src/main/java/com/nixsolutions/usermanagement/web/EditServlet.java | 9401ba930a92218a9e5f2375f3f8a3ba713f62fb | []
| no_license | NUREKN14-JAVA/dmytro.horkovliuk | 5b9c48ff555785ab7187d6f58cc237561968d025 | 9978ea8d51a08a09c671ae71ecb5fb3ec1444d5d | refs/heads/master | 2021-01-24T09:28:27.804344 | 2016-12-26T04:25:25 | 2016-12-26T04:25:25 | 69,860,291 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,031 | java | package main.java.com.nixsolutions.usermanagement.web;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.nixsolutions.usermanagement.User;
import com.nixsolutions.usermanagement.db.DaoFactory;
import com.nixsolutions.usermanagement.db.DatabaseException;
public class EditServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (req.getParameter("okButton") != null) {
doOk(req, resp);
} else if (req.getParameter("cancelButton") != null) {
doCancel(req, resp);
} else {
showPage(req, resp);
}
}
protected void showPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/edit.jsp").forward(req, resp);
}
private void doCancel(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/browse").forward(req, resp);
}
private void doOk(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
User user = null;
try {
user = getUser(req);
} catch (ValidationException e1) {
req.setAttribute("error", e1.getMessage());
showPage(req, resp);
return;
}
try {
processUser(user);
} catch (DatabaseException e) {
e.printStackTrace();
new ServletException(e);
}
req.getRequestDispatcher("/browse").forward(req, resp);
}
private User getUser(HttpServletRequest req) throws ValidationException {
User user = new User();
String idStr = req.getParameter("id");
String firstName = req.getParameter("firstName");
String lastName = req.getParameter("lastName");
String dateStr = req.getParameter("date");
if (firstName == null) {
throw new ValidationException("First name is empty");
}
if (lastName == null) {
throw new ValidationException("Last name is empty");
}
if (dateStr == null) {
throw new ValidationException("Date is empty");
}
if (idStr != null) {
user.setId(new Long(idStr));
}
user.setFirstName(firstName);
user.setLastName(lastName);
try {
user.setDateOfBirth(DateFormat.getDateInstance().parse(dateStr));
} catch (ParseException e) {
throw new ValidationException("Date format is incorrect");
}
return user;
}
protected void processUser(User user) throws DatabaseException {
DaoFactory.getInstance().getUserDao().update(user);
}
} | [
"Dmitry Gorkovluk"
]
| Dmitry Gorkovluk |
75fdb06c498113a7bbc60148aece4f6d63825030 | fbe844b7000235c6264c27618dcfed1494b6247a | /bridge/src/main/java/com/afollestad/bridge/Pipe.java | f208dcacae5d1af7c389540df1687fc3843cc013 | [
"Apache-2.0"
]
| permissive | hoseinhamzei/bridge | 47e59c4db3f3095173eba24bdaae23ebddec2900 | 0d26ec59c0e3988c3e11e37e7a3ac331947d931a | refs/heads/master | 2021-05-31T14:23:05.939797 | 2016-05-28T04:29:55 | 2016-05-28T04:29:55 | 61,481,206 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,354 | java | package com.afollestad.bridge;
import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
/**
* @author Aidan Follestad (afollestad)
*/
public abstract class Pipe implements Serializable {
public Pipe() {
}
public abstract void writeTo(@NonNull OutputStream os, @Nullable ProgressCallback progressListener) throws IOException;
@NonNull
public abstract String contentType();
public abstract int contentLength() throws IOException;
/**
* Creates a Pipe that reads a Uri (file:// or content://) into the Pipe.
*/
public static Pipe forUri(@NonNull Context context, @NonNull Uri uri) {
return new UriPipe(context, uri);
}
/**
* Creates a Pipe that reads the contents of a File into the Pipe.
*/
public static Pipe forFile(@NonNull File file) {
return new UriPipe(null, Uri.fromFile(file));
}
/**
* Creates a Pipe that reads an InputStream and transfers the content into the Pipe.
*/
public static Pipe forStream(@NonNull InputStream is, @NonNull String contentType) {
return new TransferPipe(is, contentType);
}
} | [
"[email protected]"
]
| |
93e4d5539dce157887883737d8a909ad61195721 | 6fef7045d88e4d368db62c9e8e1998c9f114cab2 | /src/main/java/org/liuzhugu/javastudy/sourcecode/spring/ConfigBeanDefinitionParser.java | aaec683888bb1e302ed8154884975e52da0a9979 | []
| no_license | liuzhugu/study | 02a7a104b31507858dc8f91c1e852f6bbc83a68f | 22f3fadf08b2c0a881a701a09e31c77b6907f113 | refs/heads/master | 2023-08-30T09:29:27.410391 | 2023-08-29T22:35:49 | 2023-08-29T22:35:49 | 151,524,422 | 0 | 0 | null | 2022-12-16T09:44:31 | 2018-10-04T05:47:49 | Java | UTF-8 | Java | false | false | 18,848 | java | package org.liuzhugu.javastudy.sourcecode.spring;
import org.springframework.aop.aspectj.*;
import org.springframework.aop.config.*;
import org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor;
import org.springframework.beans.factory.config.BeanReference;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.RuntimeBeanNameReference;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.parsing.ParseState;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
class ConfigBeanDefinitionParser implements BeanDefinitionParser {
private static final String ASPECT = "aspect";
private static final String EXPRESSION = "expression";
private static final String ID = "id";
private static final String POINTCUT = "pointcut";
private static final String ADVICE_BEAN_NAME = "adviceBeanName";
private static final String ADVISOR = "advisor";
private static final String ADVICE_REF = "advice-ref";
private static final String POINTCUT_REF = "pointcut-ref";
private static final String REF = "ref";
private static final String BEFORE = "before";
private static final String DECLARE_PARENTS = "declare-parents";
private static final String TYPE_PATTERN = "types-matching";
private static final String DEFAULT_IMPL = "default-impl";
private static final String DELEGATE_REF = "delegate-ref";
private static final String IMPLEMENT_INTERFACE = "implement-interface";
private static final String AFTER = "after";
private static final String AFTER_RETURNING_ELEMENT = "after-returning";
private static final String AFTER_THROWING_ELEMENT = "after-throwing";
private static final String AROUND = "around";
private static final String RETURNING = "returning";
private static final String RETURNING_PROPERTY = "returningName";
private static final String THROWING = "throwing";
private static final String THROWING_PROPERTY = "throwingName";
private static final String ARG_NAMES = "arg-names";
private static final String ARG_NAMES_PROPERTY = "argumentNames";
private static final String ASPECT_NAME_PROPERTY = "aspectName";
private static final String DECLARATION_ORDER_PROPERTY = "declarationOrder";
private static final String ORDER_PROPERTY = "order";
private static final int METHOD_INDEX = 0;
private static final int POINTCUT_INDEX = 1;
private static final int ASPECT_INSTANCE_FACTORY_INDEX = 2;
private ParseState parseState = new ParseState();
ConfigBeanDefinitionParser() {
}
public BeanDefinition parse(Element element, ParserContext parserContext) {
CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element));
parserContext.pushContainingComponent(compositeDef);
this.configureAutoProxyCreator(parserContext, element);
List<Element> childElts = DomUtils.getChildElements(element);
Iterator var5 = childElts.iterator();
while(var5.hasNext()) {
Element elt = (Element)var5.next();
String localName = parserContext.getDelegate().getLocalName(elt);
if ("pointcut".equals(localName)) {
this.parsePointcut(elt, parserContext);
} else if ("advisor".equals(localName)) {
this.parseAdvisor(elt, parserContext);
} else if ("aspect".equals(localName)) {
this.parseAspect(elt, parserContext);
}
}
parserContext.popAndRegisterContainingComponent();
return null;
}
private void configureAutoProxyCreator(ParserContext parserContext, Element element) {
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(parserContext, element);
}
private void parseAdvisor(Element advisorElement, ParserContext parserContext) {
AbstractBeanDefinition advisorDef = this.createAdvisorBeanDefinition(advisorElement, parserContext);
String id = advisorElement.getAttribute("id");
try {
this.parseState.push(new AdvisorEntry(id));
String advisorBeanName = id;
if (StringUtils.hasText(id)) {
parserContext.getRegistry().registerBeanDefinition(id, advisorDef);
} else {
advisorBeanName = parserContext.getReaderContext().registerWithGeneratedName(advisorDef);
}
Object pointcut = this.parsePointcutProperty(advisorElement, parserContext);
if (pointcut instanceof BeanDefinition) {
advisorDef.getPropertyValues().add("pointcut", pointcut);
parserContext.registerComponent(new AdvisorComponentDefinition(advisorBeanName, advisorDef, (BeanDefinition)pointcut));
} else if (pointcut instanceof String) {
advisorDef.getPropertyValues().add("pointcut", new RuntimeBeanReference((String)pointcut));
parserContext.registerComponent(new AdvisorComponentDefinition(advisorBeanName, advisorDef));
}
} finally {
this.parseState.pop();
}
}
private AbstractBeanDefinition createAdvisorBeanDefinition(Element advisorElement, ParserContext parserContext) {
RootBeanDefinition advisorDefinition = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class);
advisorDefinition.setSource(parserContext.extractSource(advisorElement));
String adviceRef = advisorElement.getAttribute("advice-ref");
if (!StringUtils.hasText(adviceRef)) {
parserContext.getReaderContext().error("'advice-ref' attribute contains empty value.", advisorElement, this.parseState.snapshot());
} else {
advisorDefinition.getPropertyValues().add("adviceBeanName", new RuntimeBeanNameReference(adviceRef));
}
if (advisorElement.hasAttribute("order")) {
advisorDefinition.getPropertyValues().add("order", advisorElement.getAttribute("order"));
}
return advisorDefinition;
}
private void parseAspect(Element aspectElement, ParserContext parserContext) {
String aspectId = aspectElement.getAttribute("id");
String aspectName = aspectElement.getAttribute("ref");
try {
this.parseState.push(new AspectEntry(aspectId, aspectName));
List<BeanDefinition> beanDefinitions = new ArrayList();
List<BeanReference> beanReferences = new ArrayList();
List<Element> declareParents = DomUtils.getChildElementsByTagName(aspectElement, "declare-parents");
for(int i = 0; i < declareParents.size(); ++i) {
Element declareParentsElement = (Element)declareParents.get(i);
beanDefinitions.add(this.parseDeclareParents(declareParentsElement, parserContext));
}
NodeList nodeList = aspectElement.getChildNodes();
boolean adviceFoundAlready = false;
for(int i = 0; i < nodeList.getLength(); ++i) {
Node node = nodeList.item(i);
if (this.isAdviceNode(node, parserContext)) {
if (!adviceFoundAlready) {
adviceFoundAlready = true;
if (!StringUtils.hasText(aspectName)) {
parserContext.getReaderContext().error("<aspect> tag needs aspect bean reference via 'ref' attribute when declaring advices.", aspectElement, this.parseState.snapshot());
return;
}
beanReferences.add(new RuntimeBeanReference(aspectName));
}
AbstractBeanDefinition advisorDefinition = this.parseAdvice(aspectName, i, aspectElement, (Element)node, parserContext, beanDefinitions, beanReferences);
beanDefinitions.add(advisorDefinition);
}
}
AspectComponentDefinition aspectComponentDefinition = this.createAspectComponentDefinition(aspectElement, aspectId, beanDefinitions, beanReferences, parserContext);
parserContext.pushContainingComponent(aspectComponentDefinition);
List<Element> pointcuts = DomUtils.getChildElementsByTagName(aspectElement, "pointcut");
Iterator var21 = pointcuts.iterator();
while(var21.hasNext()) {
Element pointcutElement = (Element)var21.next();
this.parsePointcut(pointcutElement, parserContext);
}
parserContext.popAndRegisterContainingComponent();
} finally {
this.parseState.pop();
}
}
private AspectComponentDefinition createAspectComponentDefinition(Element aspectElement, String aspectId, List<BeanDefinition> beanDefs, List<BeanReference> beanRefs, ParserContext parserContext) {
BeanDefinition[] beanDefArray = (BeanDefinition[])beanDefs.toArray(new BeanDefinition[beanDefs.size()]);
BeanReference[] beanRefArray = (BeanReference[])beanRefs.toArray(new BeanReference[beanRefs.size()]);
Object source = parserContext.extractSource(aspectElement);
return new AspectComponentDefinition(aspectId, beanDefArray, beanRefArray, source);
}
private boolean isAdviceNode(Node aNode, ParserContext parserContext) {
if (!(aNode instanceof Element)) {
return false;
} else {
String name = parserContext.getDelegate().getLocalName(aNode);
return "before".equals(name) || "after".equals(name) || "after-returning".equals(name) || "after-throwing".equals(name) || "around".equals(name);
}
}
private AbstractBeanDefinition parseDeclareParents(Element declareParentsElement, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(DeclareParentsAdvisor.class);
builder.addConstructorArgValue(declareParentsElement.getAttribute("implement-interface"));
builder.addConstructorArgValue(declareParentsElement.getAttribute("types-matching"));
String defaultImpl = declareParentsElement.getAttribute("default-impl");
String delegateRef = declareParentsElement.getAttribute("delegate-ref");
if (StringUtils.hasText(defaultImpl) && !StringUtils.hasText(delegateRef)) {
builder.addConstructorArgValue(defaultImpl);
} else if (StringUtils.hasText(delegateRef) && !StringUtils.hasText(defaultImpl)) {
builder.addConstructorArgReference(delegateRef);
} else {
parserContext.getReaderContext().error("Exactly one of the default-impl or delegate-ref attributes must be specified", declareParentsElement, this.parseState.snapshot());
}
AbstractBeanDefinition definition = builder.getBeanDefinition();
definition.setSource(parserContext.extractSource(declareParentsElement));
parserContext.getReaderContext().registerWithGeneratedName(definition);
return definition;
}
private AbstractBeanDefinition parseAdvice(String aspectName, int order, Element aspectElement, Element adviceElement, ParserContext parserContext, List<BeanDefinition> beanDefinitions, List<BeanReference> beanReferences) {
RootBeanDefinition var12;
try {
this.parseState.push(new AdviceEntry(parserContext.getDelegate().getLocalName(adviceElement)));
RootBeanDefinition methodDefinition = new RootBeanDefinition(MethodLocatingFactoryBean.class);
methodDefinition.getPropertyValues().add("targetBeanName", aspectName);
methodDefinition.getPropertyValues().add("methodName", adviceElement.getAttribute("method"));
methodDefinition.setSynthetic(true);
RootBeanDefinition aspectFactoryDef = new RootBeanDefinition(SimpleBeanFactoryAwareAspectInstanceFactory.class);
aspectFactoryDef.getPropertyValues().add("aspectBeanName", aspectName);
aspectFactoryDef.setSynthetic(true);
AbstractBeanDefinition adviceDef = this.createAdviceDefinition(adviceElement, parserContext, aspectName, order, methodDefinition, aspectFactoryDef, beanDefinitions, beanReferences);
RootBeanDefinition advisorDefinition = new RootBeanDefinition(AspectJPointcutAdvisor.class);
advisorDefinition.setSource(parserContext.extractSource(adviceElement));
advisorDefinition.getConstructorArgumentValues().addGenericArgumentValue(adviceDef);
if (aspectElement.hasAttribute("order")) {
advisorDefinition.getPropertyValues().add("order", aspectElement.getAttribute("order"));
}
parserContext.getReaderContext().registerWithGeneratedName(advisorDefinition);
var12 = advisorDefinition;
} finally {
this.parseState.pop();
}
return var12;
}
private AbstractBeanDefinition createAdviceDefinition(Element adviceElement, ParserContext parserContext, String aspectName, int order, RootBeanDefinition methodDef, RootBeanDefinition aspectFactoryDef, List<BeanDefinition> beanDefinitions, List<BeanReference> beanReferences) {
RootBeanDefinition adviceDefinition = new RootBeanDefinition(this.getAdviceClass(adviceElement, parserContext));
adviceDefinition.setSource(parserContext.extractSource(adviceElement));
adviceDefinition.getPropertyValues().add("aspectName", aspectName);
adviceDefinition.getPropertyValues().add("declarationOrder", order);
if (adviceElement.hasAttribute("returning")) {
adviceDefinition.getPropertyValues().add("returningName", adviceElement.getAttribute("returning"));
}
if (adviceElement.hasAttribute("throwing")) {
adviceDefinition.getPropertyValues().add("throwingName", adviceElement.getAttribute("throwing"));
}
if (adviceElement.hasAttribute("arg-names")) {
adviceDefinition.getPropertyValues().add("argumentNames", adviceElement.getAttribute("arg-names"));
}
ConstructorArgumentValues cav = adviceDefinition.getConstructorArgumentValues();
cav.addIndexedArgumentValue(0, methodDef);
Object pointcut = this.parsePointcutProperty(adviceElement, parserContext);
if (pointcut instanceof BeanDefinition) {
cav.addIndexedArgumentValue(1, pointcut);
beanDefinitions.add((BeanDefinition)pointcut);
} else if (pointcut instanceof String) {
RuntimeBeanReference pointcutRef = new RuntimeBeanReference((String)pointcut);
cav.addIndexedArgumentValue(1, pointcutRef);
beanReferences.add(pointcutRef);
}
cav.addIndexedArgumentValue(2, aspectFactoryDef);
return adviceDefinition;
}
private Class<?> getAdviceClass(Element adviceElement, ParserContext parserContext) {
String elementName = parserContext.getDelegate().getLocalName(adviceElement);
if ("before".equals(elementName)) {
return AspectJMethodBeforeAdvice.class;
} else if ("after".equals(elementName)) {
return AspectJAfterAdvice.class;
} else if ("after-returning".equals(elementName)) {
return AspectJAfterReturningAdvice.class;
} else if ("after-throwing".equals(elementName)) {
return AspectJAfterThrowingAdvice.class;
} else if ("around".equals(elementName)) {
return AspectJAroundAdvice.class;
} else {
throw new IllegalArgumentException("Unknown advice kind [" + elementName + "].");
}
}
private AbstractBeanDefinition parsePointcut(Element pointcutElement, ParserContext parserContext) {
String id = pointcutElement.getAttribute("id");
String expression = pointcutElement.getAttribute("expression");
AbstractBeanDefinition pointcutDefinition = null;
try {
this.parseState.push(new PointcutEntry(id));
pointcutDefinition = this.createPointcutDefinition(expression);
pointcutDefinition.setSource(parserContext.extractSource(pointcutElement));
String pointcutBeanName = id;
if (StringUtils.hasText(id)) {
parserContext.getRegistry().registerBeanDefinition(id, pointcutDefinition);
} else {
pointcutBeanName = parserContext.getReaderContext().registerWithGeneratedName(pointcutDefinition);
}
parserContext.registerComponent(new PointcutComponentDefinition(pointcutBeanName, pointcutDefinition, expression));
} finally {
this.parseState.pop();
}
return pointcutDefinition;
}
private Object parsePointcutProperty(Element element, ParserContext parserContext) {
if (element.hasAttribute("pointcut") && element.hasAttribute("pointcut-ref")) {
parserContext.getReaderContext().error("Cannot define both 'pointcut' and 'pointcut-ref' on <advisor> tag.", element, this.parseState.snapshot());
return null;
} else {
String pointcutRef;
if (element.hasAttribute("pointcut")) {
pointcutRef = element.getAttribute("pointcut");
AbstractBeanDefinition pointcutDefinition = this.createPointcutDefinition(pointcutRef);
pointcutDefinition.setSource(parserContext.extractSource(element));
return pointcutDefinition;
} else if (element.hasAttribute("pointcut-ref")) {
pointcutRef = element.getAttribute("pointcut-ref");
if (!StringUtils.hasText(pointcutRef)) {
parserContext.getReaderContext().error("'pointcut-ref' attribute contains empty value.", element, this.parseState.snapshot());
return null;
} else {
return pointcutRef;
}
} else {
parserContext.getReaderContext().error("Must define one of 'pointcut' or 'pointcut-ref' on <advisor> tag.", element, this.parseState.snapshot());
return null;
}
}
}
protected AbstractBeanDefinition createPointcutDefinition(String expression) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(AspectJExpressionPointcut.class);
beanDefinition.setScope("prototype");
beanDefinition.setSynthetic(true);
beanDefinition.getPropertyValues().add("expression", expression);
return beanDefinition;
}
}
| [
"[email protected]"
]
| |
bd7129cc93d9acb5487d0a654944e09f541a506e | 2e693552fb4e90c6bbf61750e74964e1796135d5 | /nb-master/nb-weixin/src/main/java/com/nb/fastweixin/message/req/BaseReq.java | d5dd5cde95f24e290afeae206d4cc72ab8714ae3 | []
| no_license | wilyquan/nb | 579c5688f63b08a5923afc9eb7631313d72d0e84 | f89de707f7d560ad0864b8e06d2a946e62ebeaaa | refs/heads/master | 2021-04-06T04:22:40.926818 | 2018-03-18T07:12:12 | 2018-03-18T07:12:12 | 124,499,700 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 812 | java | package com.nb.fastweixin.message.req;
public class BaseReq {
String toUserName;
String fromUserName;
long createTime;
String msgType;
public String getToUserName() {
return toUserName;
}
public void setToUserName(String toUserName) {
this.toUserName = toUserName;
}
public String getFromUserName() {
return fromUserName;
}
public void setFromUserName(String fromUserName) {
this.fromUserName = fromUserName;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
}
| [
"[email protected]"
]
| |
695ee6e4773e105bb13c18630bb9f9df199e495e | 81bf3d58f64fcccefc2d27c0682753b0b93f6d18 | /com.equalize.xpi.af.modules.ejb/ejbModule/com/equalize/xpi/af/modules/deepfcc/parameters/RecordTypeParametersPlain2XMLFixed.java | 852a7a926f0b71d580e00f6a72c11f7eb9da0d63 | [
"MIT"
]
| permissive | engswee/equalize-xpi-modules | 76b61fcfef805850a9bc7e5d4c0ae6c2b1e1aea2 | 95847bc7491089cfa8f52519c72e4e3575aef35f | refs/heads/master | 2021-07-11T03:54:53.883607 | 2019-01-24T06:23:29 | 2019-01-24T06:23:29 | 30,345,340 | 27 | 24 | MIT | 2023-09-08T11:10:24 | 2015-02-05T08:24:58 | Java | UTF-8 | Java | false | false | 3,365 | java | package com.equalize.xpi.af.modules.deepfcc.parameters;
import java.util.ArrayList;
import com.equalize.xpi.af.modules.util.ParameterHelper;
import com.equalize.xpi.util.converter.Field;
import com.sap.aii.af.lib.mp.module.ModuleException;
public class RecordTypeParametersPlain2XMLFixed extends RecordTypeParametersPlain2XML {
public RecordTypeParametersPlain2XMLFixed(String fieldSeparator, String[] fixedLengths) {
super(fieldSeparator, fixedLengths);
}
public void setAdditionalParameters(String recordTypeName, String[] recordsetList, ParameterHelper param) throws ModuleException {
super.setAdditionalParameters(recordTypeName, recordsetList, param);
if(this.fieldNames.length != this.fixedLengths.length) {
throw new ModuleException("No. of fields in 'fieldNames' and 'fieldFixedLengths' does not match for record type = '" + recordTypeName + "'");
}
setKeyFieldParameters(recordTypeName, param, false);
}
public String parseKeyFieldValue(String lineInput) {
String currentLineKeyFieldValue = null;
String valueAtKeyFieldPosition = dynamicSubstring(lineInput, this.keyFieldStartPosition, this.keyFieldLength);
if (valueAtKeyFieldPosition.trim().equals(this.keyFieldValue)) {
currentLineKeyFieldValue = this.keyFieldValue;
}
return currentLineKeyFieldValue;
}
public Field[] extractLineContents(String lineInput, boolean trim, int lineIndex)throws ModuleException {
ArrayList<Field> fields = new ArrayList<Field>();
int start = 0;
for(int i = 0; i < this.fieldNames.length; i++) {
int length = Integer.parseInt(this.fixedLengths[i]);
String content = dynamicSubstring(lineInput, start, length);
if(lineInput.length() < start) {
if(this.missingLastFields.equalsIgnoreCase("error")) {
throw new ModuleException("Line " + (lineIndex+1) + " has less fields than configured");
} else if(this.missingLastFields.equalsIgnoreCase("add")) {
fields.add(createNewField(this.fieldNames[i], content, trim));
}
} else {
fields.add(createNewField(this.fieldNames[i], content, trim));
}
// Set start location for next field
start += length;
// After the last configured field, check if there are any more content in the input
if(i == this.fieldNames.length - 1 && lineInput.length() > start &&
this.additionalLastFields.equalsIgnoreCase("error")) {
throw new ModuleException("Line " + (lineIndex+1) + " has more fields than configured");
}
}
return fields.toArray(new Field[fields.size()]);
}
private String dynamicSubstring(String input, int start, int length) {
int startPos = start;
int endPos = start + length - 1;
String output = "";
if ( startPos < 0 ) {
// (1) Start position is before start of input, return empty string
} else if ( startPos >= 0 && startPos < input.length() ) {
if ( endPos < input.length() ) {
// (2) Start & end positions are before end of input, return the partial substring
output = input.substring( startPos, endPos + 1 );
} else if ( endPos >= input.length() ) {
// (3) Start position is before start of input but end position is after end of input, return from start till end of input
output = input.substring( startPos, input.length() );
}
} else if ( startPos >= input.length() ) {
// (4) Start position is after end of input, return empty string
}
return output;
}
}
| [
"[email protected]"
]
| |
4dab8dc4c1e99ef8d1c839bef2dc86e8452ceb2d | 8f946ff8248dcd2256a980c0918d2e69597ccc0f | /src/Board.java | e9e3ec6431dca088ad668a277054147fd6921536 | []
| no_license | frostde/MultiTicTacToe | b162229e77cd2a473f332a54626f39a8cf2d72a6 | 2530914cd5cb9bdb58d61a3b1b577ca56ccc9bc1 | refs/heads/master | 2021-08-14T05:59:03.217667 | 2017-11-14T17:40:51 | 2017-11-14T17:40:51 | 110,723,815 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,550 | java | import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/*Didnt have time to comment this class before the deadline, but the methods are pretty self explanatory. They
* include all of the methods for the AI and the actual game logic.*/
public class Board {
List<Point> availablePoints;
int[][] board = new int[3][3];
List<PointsAndScores> rootsChildrenScores;
private int lastColumn, lastRow;
private BufferedReader reader;
private PrintWriter writer;
private DataInputStream inStream;
private DataOutputStream outStream;
int numMoves = 0;
private Socket sock;
private Random rand = new Random();
public Board(Socket c) {
this.sock = c;
}
public boolean hasXWon() {
if ((board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] == 1) || (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] == 1)) {
//System.out.println("X Diagonal Win");
return true;
}
for (int i = 0; i < 3; ++i) {
if (((board[i][0] == board[i][1] && board[i][0] == board[i][2] && board[i][0] == 1)
|| (board[0][i] == board[1][i] && board[0][i] == board[2][i] && board[0][i] == 1))) {
// System.out.println("X Row or Column win");
return true;
}
}
return false;
}
public boolean hasOWon() {
if ((board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] == 2) || (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] == 2)) {
// System.out.println("O Diagonal Win");
return true;
}
for (int i = 0; i < 3; ++i) {
if ((board[i][0] == board[i][1] && board[i][0] == board[i][2] && board[i][0] == 2)
|| (board[0][i] == board[1][i] && board[0][i] == board[2][i] && board[0][i] == 2)) {
// System.out.println("O Row or Column win");
return true;
}
}
return false;
}
public List<Point> getAvailableStates() {
availablePoints = new ArrayList<>();
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (board[i][j] == 0) {
availablePoints.add(new Point(i, j));
}
}
}
return availablePoints;
}
public void placeAMove(Point point, int player) {
board[point.x][point.y] = player; //player = 1 for X, 2 for O
}
public Point returnBestMove() {
int MAX = -100000;
int best = -1;
for (int i = 0; i < rootsChildrenScores.size(); ++i) {
if (MAX < rootsChildrenScores.get(i).score) {
MAX = rootsChildrenScores.get(i).score;
best = i;
}
}
return rootsChildrenScores.get(best).point;
}
public int returnMin(List<Integer> list) {
int min = Integer.MAX_VALUE;
int index = -1;
for (int i = 0; i < list.size(); ++i) {
if (list.get(i) < min) {
min = list.get(i);
index = i;
}
}
return list.get(index);
}
public int returnMax(List<Integer> list) {
int max = Integer.MIN_VALUE;
int index = -1;
for (int i = 0; i < list.size(); ++i) {
if (list.get(i) > max) {
max = list.get(i);
index = i;
}
}
return list.get(index);
}
public void callMinimax(int depth, int turn){
rootsChildrenScores = new ArrayList<>();
minimax(depth, turn);
}
public int minimax(int depth, int turn) {
if (hasXWon()) return +1;
if (hasOWon()) return -1;
List<Point> pointsAvailable = getAvailableStates();
if (pointsAvailable.isEmpty()) return 0;
List<Integer> scores = new ArrayList<>();
for (int i = 0; i < pointsAvailable.size(); ++i) {
Point point = pointsAvailable.get(i);
if (turn == 1) { //X's turn select the highest from below minimax() call
placeAMove(point, 1);
int currentScore = minimax(depth + 1, 2);
scores.add(currentScore);
if (depth == 0)
rootsChildrenScores.add(new PointsAndScores(currentScore, point));
} else if (turn == 2) {//O's turn select the lowest from below minimax() call
placeAMove(point, 2);
scores.add(minimax(depth + 1, 1));
}
board[point.x][point.y] = 0; //Reset this point
}
return turn == 1 ? returnMax(scores) : returnMin(scores);
}
public void playGame() {
Random rand = new Random();
try {
inStream = new DataInputStream(sock.getInputStream());
outStream = new DataOutputStream(sock.getOutputStream());
writer = new PrintWriter(outStream, true);
reader = new BufferedReader(new InputStreamReader(inStream));
} catch (IOException ex) {}
try {
//generate turn order, if 1; computer, if 2; player
int turn = rand.nextInt(2) + 1;
System.out.println("Wins: " + ScoreBoard.wins + " Ties: " + ScoreBoard.ties + " Losses: " + ScoreBoard.losses);
writer.println(ScoreBoard.wins + " " + ScoreBoard.ties + " " + ScoreBoard.losses);
while (true) {
switch(turn) {
case 1: {
getComputerMove();
if (hasXWon()) {
writer.println("MOVE" + " #" + lastRow + " #" + lastColumn + " LOSS");
ScoreBoard.incrementLosses();
break;
}
if (numMoves == 9) {
writer.println("MOVE" + " #" + lastRow + " #" + lastColumn + " TIE");
ScoreBoard.incrementTies();
break;
}
writer.println("MOVE" + " #" + lastRow + " #" + lastColumn);
numMoves++;
turn = 2;
break;
}
case 2: {
if (numMoves == 0) {
writer.println("NONE");
getPlayerMove();
numMoves++;
turn = 1;
break;
} else {
getPlayerMove();
numMoves++;
turn = 1;
if (hasOWon()) {
writer.println("MOVE 0 0 WIN");
ScoreBoard.incrementWins();
break;
}
}
if (numMoves == 9) {
writer.println("MOVE 0 0 TIE");
ScoreBoard.incrementTies();
break;
}
break;
}
}
}
} catch (Exception ex) {}
}
public void getComputerMove() {
if (numMoves == 0) {
Point p = new Point(rand.nextInt(3), rand.nextInt(3));
placeAMove(p, 1);
lastRow = p.x;
lastColumn = p.y;
} else {
callMinimax(0, 1);
Point computerMove = returnBestMove();
lastRow = computerMove.x;
lastColumn = computerMove.y;
placeAMove(computerMove, 1);
}
}
public void getPlayerMove() {
String line;
try {
if ((line = reader.readLine()) != null) {
String[] playerMoveArray = line.split(" ");
String[] playerRowArray = playerMoveArray[1].split("#");
String[] playerColumnArray = playerMoveArray[2].split("#");
board[Integer.parseInt(playerRowArray[1])][Integer.parseInt(playerColumnArray[1])] = 'O';
lastRow = Integer.parseInt(playerRowArray[1]);
lastColumn = Integer.parseInt(playerColumnArray[1]);
}
} catch (IOException e) {}
}
}
| [
"[email protected]"
]
| |
ba36f256f5c803e2bbefac9a2b1f9805e6f09529 | ab3999feb5e8fb75ddb70b4a133a7b32b45bb004 | /src/main/java/pages/WebInfoclinic.java | addad88ecc786d3bbe2fd9313f8aa62c9b58f5c8 | []
| no_license | Vityalimbaev/selenium | d8da15e906c12286ea8c9232c4c03f5def8ffa2d | 55266ab9940bdb75072f3a4fe539d7cba681a6d8 | refs/heads/master | 2023-04-22T05:58:52.937121 | 2021-05-08T08:26:27 | 2021-05-08T08:26:27 | 365,460,483 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,640 | java | package pages;
import models.wrappers.XpathWrapper;
public class WebInfoclinic {
public XpathWrapper input_login = new XpathWrapper("//input[contains(@name,'username')]","ะฟะพะปะต ะปะพะณะธะฝะฐ");
public XpathWrapper input_password = new XpathWrapper("//input[@type='password']","ะฟะพะปะต ะฟะฐัะพะปั");
public XpathWrapper input_liveSearch = new XpathWrapper("//*[@name='SEARCH_LIVE']","ะฟะพะปะต ะฟะพะธัะบะฐ ะฟะพ ัะธะพ");
public XpathWrapper input_firstName = new XpathWrapper("//*[@name='SEARCH_FIRSTNAME']","ะฟะพะปะต ะฟะพะธัะบะฐ ะฟะพ ะธะผะตะฝะธ");
public XpathWrapper input_lastName = new XpathWrapper("//*[@name='SEARCH_LASTNAME']","ะฟะพะปะต ะฟะพะธัะบะฐ ัะฐะผะธะปะธะธ");
public XpathWrapper input_midName = new XpathWrapper("//*[@name='SEARCH_MIDNAME']","ะฟะพะปะต ะฟะพะธัะบะฐ ะฟะพ ะพััะตััะฒั");
public XpathWrapper input_requisites = new XpathWrapper("//*[contains(text(),'ะะฑัะธะต ัะตะบะฒะธะทะธัั')]//ancestor::fieldset//input","ะฟะพะปะต ะพะฑัะธั
ัะตะบะฒะธะทะธัะพะฒ");
public XpathWrapper input_address = new XpathWrapper("//*[contains(text(),'ะะดัะตั ัะตะณะธัััะฐัะธะธ')]//ancestor::fieldset//input","ะฟะพะปะต ะพะฑัะธั
ัะตะบะฒะธะทะธัะพะฒ");
public XpathWrapper input_comment = new XpathWrapper("//*[contains(@name,'COMMENT')]","ะฟะพะปะต ะดะปั ะบะพะผะผะตะฝัะฐัะธั ะบ ะฝะฐะทะฝะฐัะตะฝะธั");
public XpathWrapper input_codesearch = new XpathWrapper("//*[contains(@name,'codesearch')]","ะฟะพะปะต ะดะปั ะฟะพะธัะบะฐ ะฟะพ ะบะพะดั");
public XpathWrapper elementToPrint = new XpathWrapper("//div[contains(@class,'x-menu-item')]", "ัะปะตะผะตะฝั ะดะปั ะฟะตัะฐัะธ");
public XpathWrapper btn_searchFilial = new XpathWrapper("//div[@id='filialId-trigger-open']", "ะบะฝะพะฟะบะฐ ะฟะพะธัะบะฐ ัะธะปะธะฐะปะพะฒ");
public XpathWrapper btn_search = new XpathWrapper("//*[contains(@class,'x-form-search-trigger')]", "ะบะฝะพะฟะบะฐ ั ะปัะฟะพะน");
public XpathWrapper btn_filial = new XpathWrapper("//span[contains(text(),'?')]", "ะบะฝะพะฟะบะฐ ั ะฝะฐะทะฒะฝะธะตะผ ัะธะปะธะฐะปะฐ");
public XpathWrapper btn_moveService = new XpathWrapper("//*[contains(@id,'services-controls')]//*[contains(@class,'x-btn')]","ะบะฝะพะฟะบะฐ ะดะพะฑะฐะฒะปะตะฝะธั ััะปัะณะธ ะฒ ัะฟะธัะพะบ ัะฟัะฐะฒะฐ");
public XpathWrapper spinner = new XpathWrapper("//*[contains(@class,'spinner-wrapper')]", "ัะฟะธะฝะฝะตั");
public XpathWrapper preloader = new XpathWrapper("//*[contains(text(),'ะะฐะณััะทะบะฐ...')]","ะฟัะตะปะพะฐะดะตั");
public XpathWrapper loadmask = new XpathWrapper("//*[contains(@style,'pointer-events: none')]","ะฟัะตะปะพะฐะดะตั");
}
| [
"[email protected]"
]
| |
4cad25303080a20f16047458a2ff815c33c758f7 | e2a2313f2790628202315b004c81d6ae6f4fcbe4 | /app/src/main/java/sudarshan/bhatt/recycling/GenerateData.java | b9fecd596429c0bc33f95dcf8976f1177400c3cb | []
| no_license | sudarshan14/RecyclingLatest | 2784d4568beb028825e30af673f56d94af42f3b8 | ec777b75f4b35be6176ebb6fc8da3b9b20e5206c | refs/heads/master | 2020-03-13T00:36:00.926808 | 2018-04-27T09:53:02 | 2018-04-27T09:53:02 | 130,890,017 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,420 | java | package sudarshan.bhatt.recycling;
import java.util.ArrayList;
/**
* Created by 10608780 on 03-04-2018.
*/
public class GenerateData {
protected ArrayList<MyCarsDataModel> carDetails() {
ArrayList<MyCarsDataModel> carList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
MyCarsDataModel carsDataModel = new MyCarsDataModel();
carsDataModel.setCarName("Car : " + i);
carsDataModel.setCarModel("Model " + i);
carsDataModel.setCarPrice("Price" + (i + 10) * 8796);
carList.add(carsDataModel);
}
return carList;
}
protected ArrayList<MyLocationDataModel> myLocationDetails() {
ArrayList<MyLocationDataModel> locationList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
MyLocationDataModel locationDataModel = new MyLocationDataModel();
locationDataModel.setHomeLocation("Home " + i);
locationDataModel.setOfficeLocation("Office " + i);
locationDataModel.setPartyLocation("Party " + i);
locationList.add(locationDataModel);
}
return locationList;
}
protected ArrayList<String> stringArrayListData(){
ArrayList<String> stringArrayList = new ArrayList<>();
for(int i= 0; i<5; i++){
stringArrayList.add("item :"+i);
}
return stringArrayList;
}
}
| [
"[email protected]"
]
| |
1f934b5402edf33ffe586786741668696ea1c63c | 524617132295bac686e283eaf356f8e6584bbf00 | /src/main/java/com/man/girl/properties/GirlPropertie.java | 8b9e437a7a148516138d41ba47ee0fbb24229e4a | []
| no_license | 1009798402/girl | b1c6885bc4b3f9b80d9650b06e35ced2131a4030 | b199427747c165912a80b6b0a7669383d879f566 | refs/heads/master | 2020-03-22T20:06:11.128201 | 2018-07-11T12:36:48 | 2018-07-11T12:36:48 | 140,572,862 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 448 | java | package com.man.girl.properties;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Author: jc
* @Date: 2018/6/28/028 16:39
* @Description:
*/
@Component
@NoArgsConstructor
@ConfigurationProperties(prefix = "girl")
public class GirlPropertie {
private String name;
private Integer age;
private String cupSize;
}
| [
"[email protected]"
]
| |
fbcae20ea7f1c1fd75dcab80e48e98197228fa4d | 8717f97ed1fb5c22d38d65caf046280bb638ee16 | /core/src/main/java/org/axonframework/commandhandling/disruptor/DisruptorCommandBus.java | 2e66ec3b3af10d24051ef855e5d47774971f7176 | [
"Apache-2.0"
]
| permissive | danielcor/AxonFramework-1 | e5fd9b7603f27c22987471729181dbaf6c0b17ce | d8153bbbc7f558747b06a2d3d8bba57a7280875b | refs/heads/master | 2021-01-18T14:54:32.353219 | 2013-03-07T10:11:41 | 2013-03-07T10:12:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19,142 | java | /*
* Copyright (c) 2010-2012. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.axonframework.commandhandling.disruptor;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.EventHandlerGroup;
import org.axonframework.commandhandling.CommandBus;
import org.axonframework.commandhandling.CommandCallback;
import org.axonframework.commandhandling.CommandDispatchInterceptor;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.CommandHandlerInterceptor;
import org.axonframework.commandhandling.CommandMessage;
import org.axonframework.commandhandling.CommandTargetResolver;
import org.axonframework.commandhandling.interceptors.SerializationOptimizingInterceptor;
import org.axonframework.common.Assert;
import org.axonframework.common.AxonThreadFactory;
import org.axonframework.eventhandling.EventBus;
import org.axonframework.eventsourcing.AggregateFactory;
import org.axonframework.eventsourcing.EventSourcedAggregateRoot;
import org.axonframework.eventstore.EventStore;
import org.axonframework.repository.Repository;
import org.axonframework.serializer.Serializer;
import org.axonframework.unitofwork.TransactionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Asynchronous CommandBus implementation with very high performance characteristics. It divides the command handling
* process in two steps, which can be executed in different threads. The CommandBus is backed by a {@link Disruptor},
* which ensures that two steps are executed sequentially in these threads, while minimizing locking and inter-thread
* communication.
* <p/>
* The process is split into two separate steps, each of which is executed in a different thread:
* <ol>
* <li><em>Command Handler execution</em><br/>This process invokes the command handler with the incoming command. The
* result and changes to the aggregate are recorded for the next step.</li>
* <li><em>Event storage and publication</em><br/>This process stores all generated domain events and publishes them
* (with any optional application events) to the event bus. Finally, an asynchronous task is scheduled to invoke the
* command handler callback with the result of the command handling result.</li>
* </ol>
* <p/>
* <em>Exceptions and recovery</em>
* <p/>
* This separation of process steps makes this implementation very efficient and highly performing. However, it does
* not cope with exceptions very well. When an exception occurs, an Aggregate that has been loaded is potentially
* corrupt. That means that an aggregate does not represent a state that can be reproduced by replaying its committed
* events. Although this implementation will recover from this corrupt state, it may result in a number of commands
* being rejected in the meantime. These command may be retried if the cause of the {@link
* AggregateStateCorruptedException} does not indicate a non-transient error.
* <p/>
* Commands that have been executed against a potentially corrupt Aggregate will result in a {@link
* AggregateStateCorruptedException} exception. These commands are automatically rescheduled for processing by
* default. Use {@link DisruptorConfiguration#setRescheduleCommandsOnCorruptState(boolean)} disable this feature. Note
* that the order in which commands are executed is not fully guaranteed when this feature is enabled (default).
* <p/>
* <em>Limitations of this implementation</em>
* <p/>
* Although this implementation allows applications to achieve extreme performance (over 1M commands on commodity
* hardware), it does have some limitations. It only allows a single aggregate to be invoked during command processing.
* <p/>
* This implementation can only work with Event Sourced Aggregates.
* <p/>
* <em>Infrastructure considerations</em>
* <p/>
* This CommandBus implementation has special requirements for the Repositories being used during Command Processing.
* Therefore, the Repository instance to use in the Command Handler must be created using {@link
* #createRepository(org.axonframework.eventsourcing.AggregateFactory)}.
* Using another repository will most likely result in undefined behavior.
* <p/>
* The DisruptorCommandBus must have access to at least 3 threads, two of which are permanently used while the
* DisruptorCommandBus is operational. At least one additional thread is required to invoke callbacks and initiate a
* recovery process in the case of exceptions.
* <p/>
* Consider providing an alternative {@link org.axonframework.domain.IdentifierFactory} implementation. The default
* implementation used {@link java.util.UUID#randomUUID()} to generated identifier for Events. The poor performance of
* this method severely impacts overall performance of the DisruptorCommandBus. A better performing alternative is, for
* example, <a href="http://johannburkard.de/software/uuid/" target="_blank"><code>com.eaio.uuid.UUID</code></a>
*
* @author Allard Buijze
* @since 2.0
*/
public class DisruptorCommandBus implements CommandBus {
private static final Logger logger = LoggerFactory.getLogger(DisruptorCommandBus.class);
private static final ThreadGroup DISRUPTOR_THREAD_GROUP = new ThreadGroup("DisruptorCommandBus");
private final ConcurrentMap<String, CommandHandler<?>> commandHandlers =
new ConcurrentHashMap<String, CommandHandler<?>>();
private final Disruptor<CommandHandlingEntry> disruptor;
private final CommandHandlerInvoker[] commandHandlerInvokers;
private final List<CommandDispatchInterceptor> dispatchInterceptors;
private final List<CommandHandlerInterceptor> invokerInterceptors;
private final List<CommandHandlerInterceptor> publisherInterceptors;
private final ExecutorService executorService;
private final boolean rescheduleOnCorruptState;
private volatile boolean started = true;
private volatile boolean disruptorShutDown = false;
private final long coolingDownPeriod;
private final CommandTargetResolver commandTargetResolver;
private final int publisherCount;
private final int serializerCount;
/**
* Initialize the DisruptorCommandBus with given resources, using default configuration settings. Uses a Blocking
* WaitStrategy on a RingBuffer of size 4096. The (2) Threads required for command execution are created
* immediately. Additional threads are used to invoke response callbacks and to initialize a recovery process in
* the case of errors.
*
* @param eventStore The EventStore where generated events must be stored
* @param eventBus The EventBus where generated events must be published
*/
public DisruptorCommandBus(EventStore eventStore, EventBus eventBus) {
this(eventStore, eventBus, new DisruptorConfiguration());
}
/**
* Initialize the DisruptorCommandBus with given resources and settings. The Threads required for command
* execution are immediately requested from the Configuration's Executor, if any. Otherwise, they are created.
*
* @param eventStore The EventStore where generated events must be stored
* @param eventBus The EventBus where generated events must be published
* @param configuration The configuration for the command bus
*/
@SuppressWarnings("unchecked")
public DisruptorCommandBus(EventStore eventStore, EventBus eventBus,
DisruptorConfiguration configuration) {
Executor executor = configuration.getExecutor();
if (executor == null) {
executorService = Executors.newCachedThreadPool(
new AxonThreadFactory(DISRUPTOR_THREAD_GROUP));
executor = executorService;
} else {
executorService = null;
}
rescheduleOnCorruptState = configuration.getRescheduleCommandsOnCorruptState();
invokerInterceptors = new ArrayList<CommandHandlerInterceptor>(configuration.getInvokerInterceptors());
publisherInterceptors = new ArrayList<CommandHandlerInterceptor>(configuration.getPublisherInterceptors());
dispatchInterceptors = new ArrayList<CommandDispatchInterceptor>(configuration.getDispatchInterceptors());
TransactionManager transactionManager = configuration.getTransactionManager();
disruptor = new Disruptor<CommandHandlingEntry>(
new CommandHandlingEntry.Factory(configuration.getTransactionManager() != null),
executor,
configuration.getClaimStrategy(),
configuration.getWaitStrategy());
commandTargetResolver = configuration.getCommandTargetResolver();
// configure invoker Threads
commandHandlerInvokers = initializeInvokerThreads(eventStore, configuration);
// configure serializer Threads
SerializerHandler[] serializerThreads = initializeSerializerThreads(configuration);
serializerCount = serializerThreads.length;
// configure publisher Threads
EventPublisher[] publishers = initializePublisherThreads(eventStore, eventBus, configuration, executor,
transactionManager);
publisherCount = publishers.length;
disruptor.handleExceptionsWith(new ExceptionHandler());
EventHandlerGroup<CommandHandlingEntry> eventHandlerGroup = disruptor.handleEventsWith(commandHandlerInvokers);
if (serializerThreads.length > 0) {
eventHandlerGroup = eventHandlerGroup.then(serializerThreads);
invokerInterceptors.add(new SerializationOptimizingInterceptor());
}
eventHandlerGroup.then(publishers);
coolingDownPeriod = configuration.getCoolingDownPeriod();
disruptor.start();
}
private EventPublisher[] initializePublisherThreads(EventStore eventStore, EventBus eventBus,
DisruptorConfiguration configuration, Executor executor,
TransactionManager transactionManager) {
EventPublisher[] publishers = new EventPublisher[configuration.getPublisherThreadCount()];
for (int t = 0; t < publishers.length; t++) {
publishers[t] = new EventPublisher(eventStore, eventBus, executor, transactionManager,
configuration.getRollbackConfiguration(), t);
}
return publishers;
}
private SerializerHandler[] initializeSerializerThreads(DisruptorConfiguration configuration) {
if (!configuration.isPreSerializationConfigured()) {
return new SerializerHandler[0];
}
Serializer serializer = configuration.getSerializer();
SerializerHandler[] serializerThreads = new SerializerHandler[configuration.getSerializerThreadCount()];
for (int t = 0; t < serializerThreads.length; t++) {
serializerThreads[t] = new SerializerHandler(serializer, t, configuration.getSerializedRepresentation());
}
return serializerThreads;
}
private CommandHandlerInvoker[] initializeInvokerThreads(EventStore eventStore,
DisruptorConfiguration configuration) {
CommandHandlerInvoker[] invokers;
invokers = new CommandHandlerInvoker[configuration.getInvokerThreadCount()];
for (int t = 0; t < invokers.length; t++) {
invokers[t] = new CommandHandlerInvoker(eventStore, configuration.getCache(), t);
}
return invokers;
}
@Override
public void dispatch(final CommandMessage<?> command) {
dispatch(command, null);
}
@Override
public <R> void dispatch(CommandMessage<?> command, CommandCallback<R> callback) {
Assert.state(started, "CommandBus has been shut down. It is not accepting any Commands");
CommandMessage<?> commandToDispatch = command;
for (CommandDispatchInterceptor interceptor : dispatchInterceptors) {
commandToDispatch = interceptor.handle(commandToDispatch);
}
doDispatch(commandToDispatch, callback);
}
/**
* Forces a dispatch of a command. This method should be used with caution. It allows commands to be retried during
* the cooling down period of the disruptor.
*
* @param command The command to dispatch
* @param callback The callback to notify when command handling is completed
* @param <R> The expected return type of the command
*/
public <R> void doDispatch(CommandMessage command, CommandCallback<R> callback) {
Assert.state(!disruptorShutDown, "Disruptor has been shut down. Cannot dispatch or re-dispatch commands");
RingBuffer<CommandHandlingEntry> ringBuffer = disruptor.getRingBuffer();
int invokerSegment = 0;
int publisherSegment = 0;
int serializerSegment = 0;
if ((commandHandlerInvokers.length > 1 || publisherCount > 1 || serializerCount > 0)) {
Object aggregateIdentifier = commandTargetResolver.resolveTarget(command).getIdentifier();
if (aggregateIdentifier != null) {
int idHash = aggregateIdentifier.hashCode() & Integer.MAX_VALUE;
if (commandHandlerInvokers.length > 1) {
invokerSegment = idHash % commandHandlerInvokers.length;
}
if (serializerCount > 1) {
serializerSegment = idHash % serializerCount;
}
if (publisherCount > 1) {
publisherSegment = idHash % publisherCount;
}
}
}
long sequence = ringBuffer.next();
CommandHandlingEntry event = ringBuffer.get(sequence);
event.reset(command, commandHandlers.get(command.getCommandName()), invokerSegment, publisherSegment,
serializerSegment, new BlacklistDetectingCallback<R>(callback, command, disruptor.getRingBuffer(),
this, rescheduleOnCorruptState),
invokerInterceptors, publisherInterceptors);
ringBuffer.publish(sequence);
}
/**
* Creates a repository instance for an Event Sourced aggregate that is created by the given
* <code>aggregateFactory</code>.
* <p/>
* The repository returned must be used by Command Handlers subscribed to this Command Bus for loading aggregate
* instances. Using any other repository instance may result in undefined outcome (a.k.a. concurrency problems).
*
* @param aggregateFactory The factory creating uninitialized instances of the Aggregate
* @param <T> The type of aggregate to create the repository for
* @return the repository that provides access to stored aggregates
*/
public <T extends EventSourcedAggregateRoot> Repository<T> createRepository(AggregateFactory<T> aggregateFactory) {
for (CommandHandlerInvoker invoker : commandHandlerInvokers) {
invoker.createRepository(aggregateFactory);
}
return new DisruptorRepository<T>(aggregateFactory.getTypeIdentifier());
}
@Override
public <C> void subscribe(String commandName, CommandHandler<? super C> handler) {
commandHandlers.put(commandName, handler);
}
@Override
public <C> boolean unsubscribe(String commandName, CommandHandler<? super C> handler) {
return commandHandlers.remove(commandName, handler);
}
/**
* Shuts down the command bus. It no longer accepts new commands, and finishes processing commands that have
* already been published. This method will not shut down any executor that has been provided as part of the
* Configuration.
*/
public void stop() {
if (!started) {
return;
}
started = false;
long lastChangeDetected = System.currentTimeMillis();
long lastKnownCursor = disruptor.getRingBuffer().getCursor();
while (System.currentTimeMillis() - lastChangeDetected < coolingDownPeriod && !Thread.interrupted()) {
if (disruptor.getRingBuffer().getCursor() != lastKnownCursor) {
lastChangeDetected = System.currentTimeMillis();
lastKnownCursor = disruptor.getRingBuffer().getCursor();
}
}
disruptorShutDown = true;
disruptor.shutdown();
if (executorService != null) {
executorService.shutdown();
}
}
private class ExceptionHandler implements com.lmax.disruptor.ExceptionHandler {
@Override
public void handleEventException(Throwable ex, long sequence, Object event) {
logger.error("Exception occurred while processing a {}.",
((CommandHandlingEntry) event).getCommand().getPayloadType().getSimpleName(),
ex);
}
@Override
public void handleOnStartException(Throwable ex) {
logger.error("Failed to start the DisruptorCommandBus.", ex);
disruptor.shutdown();
}
@Override
public void handleOnShutdownException(Throwable ex) {
logger.error("Error while shutting down the DisruptorCommandBus", ex);
}
}
private static class DisruptorRepository<T extends EventSourcedAggregateRoot> implements Repository<T> {
private final String typeIdentifier;
public DisruptorRepository(String typeIdentifier) {
this.typeIdentifier = typeIdentifier;
}
@SuppressWarnings("unchecked")
@Override
public T load(Object aggregateIdentifier, Long expectedVersion) {
return (T) CommandHandlerInvoker.getRepository(typeIdentifier).load(aggregateIdentifier, expectedVersion);
}
@SuppressWarnings("unchecked")
@Override
public T load(Object aggregateIdentifier) {
return (T) CommandHandlerInvoker.getRepository(typeIdentifier).load(aggregateIdentifier);
}
@Override
public void add(T aggregate) {
CommandHandlerInvoker.getRepository(typeIdentifier).add(aggregate);
}
}
}
| [
"[email protected]"
]
| |
418d24ccf8ca1f46bf5fd04699820af8b69a7ea9 | bf9538f069202abc100ae637bd6484e02e08fba0 | /ANDROID/CRIArdApp2/app/src/main/java/app/criard/criardapp/Informe_temperatura.java | c79384cb8626f9a78e062e0b78f2bc3087ec7dc8 | []
| no_license | CRIARD/CRIARD | 73bfffe4e3c52f67f16bb5fd5551e5331816c2ff | 63e28fd255f9a6a773301a6e9524d1c8efdeee65 | refs/heads/master | 2020-03-30T05:37:34.849826 | 2018-12-04T22:59:59 | 2018-12-04T22:59:59 | 150,809,999 | 0 | 0 | null | 2018-11-28T23:15:19 | 2018-09-29T01:11:05 | Java | UTF-8 | Java | false | false | 8,614 | java | package app.criard.criardapp;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class Informe_temperatura extends Activity {
TextView temp;
boolean temperatura;
Messenger mService = null;
boolean mBound;
private int contador = 0;
private HandlerActivity handler;
private ActualizarTemperatura actualizarTemperatura;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_informe_temperatura);
temperatura = true;
temp = (TextView) findViewById(R.id.temp);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
//se asocia un listener al boton cancelar para la ventana de dialogo ue busca los dispositivos bluethoot
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
navigation.setSelectedItemId(R.id.navigation_home);
actualizarTemperatura = new ActualizarTemperatura();
handler = HandlerActivity.getInstance();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); //Cambia el estado del Bluethoot (Acrtivado /Desactivado)
//se define (registra) el handler que captura los broadcast anterirmente mencionados.
registerReceiver(mReceiver, filter);
actualizarTemperatura.execute();
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
return true;
case R.id.navigation_cuna:
Intent intent = new Intent(Informe_temperatura.this,CRIArdMainActivity.class);
startActivity(intent);
finish();
return true;
}
return false;
}
};
@Override
protected void onDestroy()
{
super.onDestroy();
unbindService(mConnection);
unregisterReceiver(mReceiver);
temperatura = false;
actualizarTemperatura.cancel(true);
}
@Override
protected void onResume() {
super.onResume();
new Thread(new Runnable() {
@Override
public void run() {
try {
while(temperatura) {
Thread.sleep(4000);
Message msg = Message.obtain(null, ServicioBT.GET_INFO_TEMP, 0, 0);
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
mBound = true;
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
mBound = false;
}
};
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,BluetoothAdapter.ERROR);
if(state == BluetoothAdapter.STATE_DISCONNECTED || state == BluetoothAdapter.STATE_OFF){
Toast.makeText(Informe_temperatura.this,"Se ha perdido la conexion..",Toast.LENGTH_SHORT).show();
unbindService(mConnection);
unregisterReceiver(mReceiver);
temperatura = false;
actualizarTemperatura.cancel(true);
AlertDialog alerta = createSimpleDialog();
alerta.show();
}
}
}
};
public AlertDialog createSimpleDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Error")
.setMessage("Se ha perdido la conexion.")
.setNegativeButton("Aceptar",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Informe_temperatura.this,ServicioBT.class);
stopService(intent);
finish();
}
});
return builder.create();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(getApplicationContext(), ServicioBT.class);
Messenger messenger = new Messenger(handler);
intent.putExtra("MESSENGER", messenger);
intent.putExtra("CLIENTE",ServicioBT.ACTIVITY_TEMP);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
public void onBackPressed() {
if(contador == 0){
Toast.makeText(getApplicationContext(),"Presione nuevamente para salir",Toast.LENGTH_SHORT).show();
contador++;
}else{
Intent intent = new Intent(Informe_temperatura.this,ServicioBT.class);
stopService(intent);
finish();
}
new CountDownTimer(3000,1000){
@Override
public void onTick(long millisUntilFinished) { }
@Override
public void onFinish() {
contador=0;
}
}.start();
}
public class ActualizarTemperatura extends AsyncTask<Void, String, String> {
@Override
protected String doInBackground(Void... strings) {
Log.i("Async","Empieza a ejecutar el hilo");
publishProgress(handler.getDato_temp());
while (!isCancelled()){
try {
//Simula el tiempo aleatorio de descargar una imagen, al dormir unos milisegundos aleatorios al hilo en segundo plano
Thread.sleep(200);
} catch (InterruptedException e) {
cancel(true); //Cancelamos si entramos al catch porque algo ha ido mal
e.printStackTrace();
}
publishProgress(handler.getDato_temp());
}
return null;
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(String... temperatura) {
progressBar.setVisibility(View.INVISIBLE);
temp.setText(temperatura[0]);
}
@Override
protected void onPostExecute(String cantidadProcesados) {
}
}
}
| [
"[email protected]"
]
| |
d0ece94d6b52338520a5762f18b2d284e4f50df9 | f662526b79170f8eeee8a78840dd454b1ea8048c | /org/apache/logging/log4j/core/filter/AbstractFilter.java | c4f7af02fd09c0e2c565df6840a6eca9c64d206a | []
| no_license | jason920612/Minecraft | 5d3cd1eb90726efda60a61e8ff9e057059f9a484 | 5bd5fb4dac36e23a2c16576118da15c4890a2dff | refs/heads/master | 2023-01-12T17:04:25.208957 | 2020-11-26T08:51:21 | 2020-11-26T08:51:21 | 316,170,984 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,428 | java | /* */ package org.apache.logging.log4j.core.filter;
/* */
/* */ import org.apache.logging.log4j.Level;
/* */ import org.apache.logging.log4j.Marker;
/* */ import org.apache.logging.log4j.core.AbstractLifeCycle;
/* */ import org.apache.logging.log4j.core.Filter;
/* */ import org.apache.logging.log4j.core.LogEvent;
/* */ import org.apache.logging.log4j.core.Logger;
/* */ import org.apache.logging.log4j.message.Message;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public abstract class AbstractFilter
/* */ extends AbstractLifeCycle
/* */ implements Filter
/* */ {
/* */ protected final Filter.Result onMatch;
/* */ protected final Filter.Result onMismatch;
/* */
/* */ protected AbstractFilter() {
/* 54 */ this(null, null);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ protected AbstractFilter(Filter.Result onMatch, Filter.Result onMismatch) {
/* 63 */ this.onMatch = (onMatch == null) ? Filter.Result.NEUTRAL : onMatch;
/* 64 */ this.onMismatch = (onMismatch == null) ? Filter.Result.DENY : onMismatch;
/* */ }
/* */
/* */
/* */ protected boolean equalsImpl(Object obj) {
/* 69 */ if (this == obj) {
/* 70 */ return true;
/* */ }
/* 72 */ if (!super.equalsImpl(obj)) {
/* 73 */ return false;
/* */ }
/* 75 */ if (getClass() != obj.getClass()) {
/* 76 */ return false;
/* */ }
/* 78 */ AbstractFilter other = (AbstractFilter)obj;
/* 79 */ if (this.onMatch != other.onMatch) {
/* 80 */ return false;
/* */ }
/* 82 */ if (this.onMismatch != other.onMismatch) {
/* 83 */ return false;
/* */ }
/* 85 */ return true;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(LogEvent event) {
/* 95 */ return Filter.Result.NEUTRAL;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) {
/* 110 */ return Filter.Result.NEUTRAL;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) {
/* 125 */ return Filter.Result.NEUTRAL;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(Logger logger, Level level, Marker marker, String msg, Object... params) {
/* 140 */ return Filter.Result.NEUTRAL;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(Logger logger, Level level, Marker marker, String msg, Object p0) {
/* 156 */ return filter(logger, level, marker, msg, new Object[] { p0 });
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1) {
/* 173 */ return filter(logger, level, marker, msg, new Object[] { p0, p1 });
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2) {
/* 191 */ return filter(logger, level, marker, msg, new Object[] { p0, p1, p2 });
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3) {
/* 210 */ return filter(logger, level, marker, msg, new Object[] { p0, p1, p2, p3 });
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3, Object p4) {
/* 231 */ return filter(logger, level, marker, msg, new Object[] { p0, p1, p2, p3, p4 });
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5) {
/* 253 */ return filter(logger, level, marker, msg, new Object[] { p0, p1, p2, p3, p4, p5 });
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6) {
/* 276 */ return filter(logger, level, marker, msg, new Object[] { p0, p1, p2, p3, p4, p5, p6 });
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7) {
/* 301 */ return filter(logger, level, marker, msg, new Object[] { p0, p1, p2, p3, p4, p5, p6, p7 });
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7, Object p8) {
/* 327 */ return filter(logger, level, marker, msg, new Object[] { p0, p1, p2, p3, p4, p5, p6, p7, p8 });
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public Filter.Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7, Object p8, Object p9) {
/* 354 */ return filter(logger, level, marker, msg, new Object[] { p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 });
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public final Filter.Result getOnMatch() {
/* 363 */ return this.onMatch;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public final Filter.Result getOnMismatch() {
/* 372 */ return this.onMismatch;
/* */ }
/* */
/* */
/* */ protected int hashCodeImpl() {
/* 377 */ int prime = 31;
/* 378 */ int result = super.hashCodeImpl();
/* 379 */ result = 31 * result + ((this.onMatch == null) ? 0 : this.onMatch.hashCode());
/* 380 */ result = 31 * result + ((this.onMismatch == null) ? 0 : this.onMismatch.hashCode());
/* 381 */ return result;
/* */ }
/* */
/* */
/* */ public String toString() {
/* 386 */ return getClass().getSimpleName();
/* */ }
/* */ }
/* Location: F:\dw\server.jar!\org\apache\logging\log4j\core\filter\AbstractFilter.class
* Java compiler version: 7 (51.0)
* JD-Core Version: 1.1.3
*/ | [
"[email protected]"
]
| |
c69dd7cd3dc75441ca7349a6c278f05c24f64ddb | 7e22355b1cb3686f63f62bd2f43b3e89d7ccf118 | /workspace/Phone/gen/com/example/phone/R.java | 973bc409ad17a023c5f5ae3f046e6097c0e30d25 | []
| no_license | tacketra/AndroidWorkspace | 8669f696aa813cbc113b19f956919bacb4d1fdd7 | 712e62c2d1250f04974053ad4cf261acd269a880 | refs/heads/master | 2021-01-21T12:03:31.666097 | 2014-07-21T21:29:31 | 2014-07-21T21:29:31 | 18,478,279 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,580 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.phone;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int action_settings=0x7f080001;
public static final int status=0x7f080000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
public static final int main=0x7f070000;
}
public static final class string {
public static final int _18888=0x7f050004;
public static final int _429e51c8=0x7f050003;
public static final int action_settings=0x7f050001;
public static final int app_name=0x7f050000;
public static final int hello_world=0x7f050002;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f060000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}
| [
"[email protected]"
]
| |
9bd50ab1af7017d28ac98bb28bb64a895af719ee | d5c60f3e5b7eb6c8b2a675d655ff17eb93f5e451 | /src/server/log/LogType.java | 02382e713446e74f293e8f44b19acf5e4ef4372b | []
| no_license | LeTrongNghiaHUYNH/Traders | 1d2f4bfea9dfa52d3ad8376d3b66470d9eb76e78 | f3503a7c360913d8e180a51e7e7a9ac2774ce492 | refs/heads/master | 2021-01-10T16:52:02.253782 | 2016-03-04T12:15:39 | 2016-03-04T12:15:39 | 52,794,744 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 147 | java | package server.log;
/**
* Created by elfaus on 29/02/2016.
*/
public enum LogType {
notice,
warning,
error,
normal,
debug
}
| [
"[email protected]"
]
| |
6142bc5472a91ee0f8eb0628c813edfb058ee037 | 7166b710ccbbe379c3d0d8a2a2968cc8952cd257 | /motorapido/src/br/com/motorapido/dao/ISituacaoChamadaDAO.java | c84130c4b1e6595e63a62a44af39a4fb6e504462 | []
| no_license | JHCalasans/motorapidoweb | a392854a157a30e7f486f31cf018fc5396abb3e3 | ad8247c606f478080d967d916c17227d1c4f993f | refs/heads/master | 2021-07-05T19:47:00.481491 | 2020-07-29T21:27:18 | 2020-07-29T21:27:18 | 133,732,943 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 215 | java | package br.com.motorapido.dao;
import br.com.minhaLib.dao.GenericDAO;
import br.com.motorapido.entity.SituacaoChamada;
public interface ISituacaoChamadaDAO extends GenericDAO<SituacaoChamada, Integer>{
}
| [
"[email protected]"
]
| |
8b34fded0e22307a12aa48992bfb2b888ed663f8 | 96fa68789cb6b3fe82dd892864747bce29642829 | /JUC/src/main/java/com/doer/readwrite/ReadWriteLockDemo.java | 5f6b7be178e7188a33766c328593ba28a8961eeb | []
| no_license | sinimal-hit/sinamal | a1a556579d528aac99afbbe682a089f441512071 | c90a712376cb349cb8e5c4697d1f126747a74ef0 | refs/heads/master | 2023-07-03T06:31:42.248017 | 2021-08-05T23:47:16 | 2021-08-05T23:47:16 | 317,568,434 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,830 | java | package com.doer.readwrite;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* ReadWriteLock
* ็ฌๅ ้(ๅ้) ไธๆฌกๅช่ฝ่ขซไธไธช็บฟ็จๅ ๆ
* ๅ
ฑไบซ้(่ฏป้) ๅคไธช็บฟ็จๅฏไปฅๅๆถๅ ๆ
* ่ฏป-่ฏป ๅฏไปฅๅ
ฑๅญ
* ่ฏปๅ ไธๅฏไปฅๅ
ฑๅญ
* ๅ ๅไธๅฏไปฅๅ
ฑๅญ
*
*/
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyCacheLock myCache = new MyCacheLock();
//่ฟ5ไธช็บฟ็จๅถไฝๅๅ
ฅ็ๆไฝ
for (int i =1; i <= 5;i++) {
final int temp = i;
new Thread(()->{
myCache.put(temp+"",temp+"");
},"Thread-"+i).start();
}
for (int i =1; i <= 5;i++) {
final int temp = i;
new Thread(()->{
myCache.get(temp+"");
},"Thread-"+i).start();
}
}
}
/*
่ชๅฎไน็ผๅญ,ๆฒกๆๆท้
*/
class MyCache{
private volatile Map<String ,Object> map = new HashMap<>();
//ๅญ,ๅ
public void put(String key,Object value){
System.out.println(Thread.currentThread().getName()+"ๅๅ
ฅ"+key);
map.put(key,value);
System.out.println(Thread.currentThread().getName()+"ๅๅ
ฅๅฎๆฏ");
}
//ๅ,่ฏป
public void get(String key){
System.out.println(Thread.currentThread().getName()+"่ฏปๅ"+key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName()+"่ฏปๅๅฎๆฏ");
}
}
class MyCacheLock{
private volatile Map<String ,Object> map = new HashMap<>();
//่ฏปๅ้,ๆดๅ ็ป็ฒๅบฆ็ๆงๅถ
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
//ๅญ,ๅ,ๅๅ
ฅ็ๆถๅ,ๅชๅธๆๅๆถๅชๆไธไธช็บฟ็จๅ
public void put(String key,Object value){
readWriteLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName()+"ๅๅ
ฅ"+key);
map.put(key,value);
System.out.println(Thread.currentThread().getName()+"ๅๅ
ฅๅฎๆฏ");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();
}
}
//ๅ,่ฏป,ๆๆไบบ้ฝๅฏไปฅ่ฏป
public void get(String key){
readWriteLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName()+"่ฏปๅ"+key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName()+"่ฏปๅๅฎๆฏ");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock();
}
}
}
| [
"[email protected]"
]
| |
e8bbed5ac2f2a888ed87127cafa22e46684dc0bd | 0da41d657c90622397e0710bccd26dba30a4007a | /practice/MakeChage/MakeChage.java | fbe8a462e7fb836c2304fa868e2a8197c59bd23d | []
| no_license | liubo1985/Leetcode | c12d786cac44b282481e897ece674ca125a01a60 | 116648d70f3e46e8d3f091f84a042b4ee92fee10 | refs/heads/master | 2021-01-21T04:46:50.133343 | 2020-01-14T18:42:50 | 2020-01-14T18:42:50 | 55,921,789 | 1 | 0 | null | 2020-01-14T18:42:52 | 2016-04-10T20:48:46 | Java | UTF-8 | Java | false | false | 1,331 | java | package com.practice.MakeChage;
/**
* Created by bliu on 11/10/15.
* Gievn an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents) and pennies (1 cents),
* write code to calculate the number of ways of representing n cents.
*/
public class MakeChage {
public static void makeChange(String tsoln, int startIndex, int remainTarget, CoinChangeAnswer answer)
{
for(int i = startIndex; i < answer.denoms.length; i++)
{
int temp = remainTarget - answer.denoms[i];
String temp_tsoln = tsoln + answer.denoms[i] + ",";
if(temp < 0)
break;
if (temp == 0)
{
answer.answer.add(temp_tsoln);
break;
}
else
{
makeChange(temp_tsoln, i, temp, answer);
}
}
}
public static void main(String[] args)
{
String tsoln = new String();
int startIndex = 0;
int target = 10;
CoinChangeAnswer answer = new CoinChangeAnswer();
answer.denoms = new int[]{1,2,5};
makeChange(tsoln, startIndex, target, answer);
System.out.println("Solution is: ");
for(String str : answer.answer)
{
System.out.println(str);
}
}
}
| [
"[email protected]"
]
| |
d8cf13502b816fb5802ebdd1c09133939f3faddd | 433a40d9eacc16e30216aacbc92e3beaef57b49e | /mall/src/main/java/com/zhuyj/mall/mapper/UmsAdminRoleRelationMapper.java | cd6cb4b380c9dd3a5b789ebeb5ab64bf41dd5a18 | []
| no_license | zhuYJ-0/mall | 03e9658b61bd68d538a378a2362d7068643f595e | 953b8ca5db0424f5e666ee81c1087190008195d4 | refs/heads/master | 2023-08-29T07:27:12.681074 | 2021-10-14T06:47:14 | 2021-10-14T06:47:14 | 416,645,037 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,046 | java | package com.zhuyj.mall.mapper;
import com.zhuyj.mall.model.UmsAdminRoleRelation;
import com.zhuyj.mall.model.UmsAdminRoleRelationExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UmsAdminRoleRelationMapper {
int countByExample(UmsAdminRoleRelationExample example);
int deleteByExample(UmsAdminRoleRelationExample example);
int deleteByPrimaryKey(Long id);
int insert(UmsAdminRoleRelation record);
int insertSelective(UmsAdminRoleRelation record);
List<UmsAdminRoleRelation> selectByExample(UmsAdminRoleRelationExample example);
UmsAdminRoleRelation selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") UmsAdminRoleRelation record, @Param("example") UmsAdminRoleRelationExample example);
int updateByExample(@Param("record") UmsAdminRoleRelation record, @Param("example") UmsAdminRoleRelationExample example);
int updateByPrimaryKeySelective(UmsAdminRoleRelation record);
int updateByPrimaryKey(UmsAdminRoleRelation record);
} | [
"[email protected]"
]
| |
953a8f145c129c7753e7b7a4241d89bd961ff0b7 | 86ea7ebda3d5da37f3c935fb8399d693f49c7aad | /Riwayat_Penyakit.java | d82fe362f0bdd65e5b16f8b688a0d21e9c61fef4 | []
| no_license | kertayasaiks/E_KTP_sys | 0d98f42ce0c55cacb12a3e48f570c0326571cdc2 | 99f4327456ad178275269827c33b4fd21a74accb | refs/heads/master | 2021-01-19T18:33:19.543259 | 2017-04-15T19:25:57 | 2017-04-15T19:25:57 | 88,364,738 | 0 | 0 | null | 2017-04-15T17:57:18 | 2017-04-15T17:57:17 | null | UTF-8 | Java | false | false | 696 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package e_ktp_system;
/**
*
* @author 0xiRiz
*/
public class Riwayat_Penyakit {
private String Nama_penyakit;
private String tgl;
public void setNama_Penyakit(String Nama_Penyakit){
this.Nama_Penyakit = Nama_Penyakit;
}
public String getNamaPenyakit(){
return Nama_Penyakit;
}
public void SetTanggal(String Tanggal){
this.Tanggal = Tanggal;
}
public getTanggal(){
return Tanggal;
}
}
| [
"[email protected]"
]
| |
e0715d15b439d2c006383a4aa4e02e8424819f08 | e268ea2f27b92a8c895dd1865c9a6fab1b37a1e1 | /src/se/kth/ssvl/tslab/bytewalla/androiddtn/servlib/bundling/BundleProtocol.java | 5d59dc8dbbcb8d8c1aaef83afe1efc0ca84433f7 | []
| no_license | rerngvit/Bytewalla | 0c05a480c6b048984d700123e8c19a8800f71665 | 0b61c161ec3de922d46eafe42542315f44bf9da4 | refs/heads/master | 2016-09-05T23:57:35.298000 | 2013-07-09T14:29:27 | 2013-07-09T14:29:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 30,109 | java | /*
* This file is part of the Bytewalla Project
* More information can be found at "http://www.tslab.ssvl.kth.se/csd/projects/092106/".
*
* Copyright 2009 Telecommunication Systems Laboratory (TSLab), Royal Institute of Technology, Sweden.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package se.kth.ssvl.tslab.bytewalla.androiddtn.servlib.bundling;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import android.util.Log;
import se.kth.ssvl.tslab.bytewalla.androiddtn.servlib.contacts.Link;
import se.kth.ssvl.tslab.bytewalla.androiddtn.systemlib.util.IByteBuffer;
import se.kth.ssvl.tslab.bytewalla.androiddtn.systemlib.util.List;
import se.kth.ssvl.tslab.bytewalla.androiddtn.systemlib.util.SerializableByteBuffer;
/**
* The main class for converting a Java object from/to binary representation. The convergence layer uses this
* class for sending/receiving data from the lower layer. This class relies heavily on the registered BlockProcessors to actually generate or consume data.
*
* @see BlockProcessor
* @author Rerngvit Yanggratoke ([email protected])
*/
public class BundleProtocol {
private final static String TAG = "BundleProtocol";
/**
* "Register a new BlockProcessor handler to handle the given block type code
* when received off the wire." [DTN2]
*/
public static void register_processor(BlockProcessor bp) {
boolean already_registered = processors_.contains(bp);
if (!already_registered)
{
processors_.add(bp);
}
}
/**
* "Find the appropriate BlockProcessor for the given block type code." [DTN2]
*/
public static BlockProcessor find_processor(bundle_block_type_t type) {
Iterator<BlockProcessor> iter = processors_.iterator();
while (iter.hasNext())
{
BlockProcessor bp = iter.next();
if(bp.block_type() == type)
{
return bp;
}
}
return null;
}
/**
* "Initialize the default set of block processors." [DTN2]
*/
public static void init_default_processors() {
register_processor(new PrimaryBlockProcessor());
register_processor(new PayloadBlockProcessor());
}
/**
* "Give the processors a chance to chew on the bundle after reloading from
* disk." [DTN2]
*/
public static void reload_post_process(Bundle bundle) {
BlockInfoVec recv_blocks = bundle.recv_blocks();
Iterator<BlockInfo> iter = recv_blocks.iterator();
while (iter.hasNext())
{
// "allow BlockProcessors [and Ciphersuites] a chance to re-do
// things needed after a load-from-store" [DTN2]
BlockInfo block = iter.next();
block.owner().reload_post_process(bundle, recv_blocks, block);
}
}
/**
* Bundle Processing Status Report Flags
*/
public static enum bundle_processing_report_flag_t {
REQUEST_STATUS_RECEIVED(1 << 14),
REQUEST_STATUS_CUSTODY_ACCEPTED(1 << 15),
REQUEST_STATUS_FORWARDED(1 << 16),
REQUEST_STATUS_DELIVERED(1 << 17),
REQUEST_STATUS_DELETED(1 << 18);
private static final Map<Integer, bundle_processing_report_flag_t> lookup = new HashMap<Integer, bundle_processing_report_flag_t>();
static {
for (bundle_processing_report_flag_t s : EnumSet
.allOf(bundle_processing_report_flag_t.class))
lookup.put(s.getCode(), s);
}
private int code_;
private bundle_processing_report_flag_t(int code) {
this.code_ = code;
}
public int getCode() {
return code_;
}
public static bundle_processing_report_flag_t get(int code) {
return lookup.get(code);
}
}
/**
* "Generate a BlockInfoVec for the outgoing link and put it into
* xmit_blocks_." [DTN2]
*
* @return a list of new BLockInfo
*/
public static BlockInfoVec prepare_blocks(Bundle bundle, final Link link) {
// "create a new block list for the outgoing link by first calling
// prepare on all the BlockProcessor classes for the blocks that
// arrived on the link" [DTN2]
BlockInfoVec xmit_blocks = bundle.xmit_link_block_set().create_blocks(link);
BlockInfoVec recv_blocks = bundle.recv_blocks();
if (recv_blocks.size() > 0) {
// "if there is a received block, the first one better be the primary" [DTN2]
assert(recv_blocks.front().type() == bundle_block_type_t.PRIMARY_BLOCK);
Iterator<BlockInfo> iter = recv_blocks.iterator();
while(iter.hasNext())
{
BlockInfo block = iter.next();
if (bundle.fragmented_incoming()
&& xmit_blocks.find_block(BundleProtocol.bundle_block_type_t.PAYLOAD_BLOCK) != null) {
continue;
}
block.owner().prepare(bundle, xmit_blocks, block, link,
BlockInfo.list_owner_t.LIST_RECEIVED);
}
}
else {
Log.d(TAG, "adding primary and payload block");
BlockProcessor bp = find_processor(BundleProtocol.bundle_block_type_t.PRIMARY_BLOCK);
bp.prepare(bundle, xmit_blocks, null, link, BlockInfo.list_owner_t.LIST_NONE);
bp = find_processor(bundle_block_type_t.PAYLOAD_BLOCK);
bp.prepare(bundle, xmit_blocks, null, link, BlockInfo.list_owner_t.LIST_NONE);
}
// "now we also make sure to prepare() on any registered processors
// that don't already have a block in the output list. this
// handles the case where we have a locally generated block with
// nothing in the recv_blocks vector" [DTN2]
Iterator<BlockProcessor> itr = processors_.iterator();
while(itr.hasNext())
{
BlockProcessor bp = itr.next();
if (! xmit_blocks.has_block(bp.block_type())) {
bp.prepare(bundle, xmit_blocks, null, link, BlockInfo.list_owner_t.LIST_NONE);
}
}
return xmit_blocks;
}
/**
* "Generate contents for the given BlockInfoVec on the given Link." [DTN2]
*
* @return "the total length of the formatted blocks for this bundle." [DTN2]
*/
public static int generate_blocks(Bundle bundle, BlockInfoVec blocks,
final Link link) {
// "now assert there's at least 2 blocks (primary + payload) and
// that the primary is first" [DTN2]
assert(blocks.size() >= 2);
assert(blocks.front().type() == bundle_block_type_t.PRIMARY_BLOCK);
// "now we make a pass through the list and call generate on
// each block processor" [DTN2]
for (int i=0; i < blocks.size(); i++)
{
boolean last = i == blocks.size() - 1;
BlockInfo iter = blocks.get(i);
iter.owner().generate(bundle, blocks, iter, link, last);
Log.d(TAG, String.format("generated block (owner %s type %s) "+
"data_offset %d data_length %d , contents_length %d",
iter.owner().block_type(),
iter.type(),
iter.data_offset(),
iter.data_length(),
iter.contents().position()));
if (last) {
assert((iter.flags() & BundleProtocol.block_flag_t.BLOCK_FLAG_LAST_BLOCK.getCode()) != 0);
} else {
assert((iter.flags() & BundleProtocol.block_flag_t.BLOCK_FLAG_LAST_BLOCK.getCode()) == 0);
}
}
// "Now that all the EID references are added to the dictionary,
// generate the primary block." [DTN2]
PrimaryBlockProcessor pbp = (PrimaryBlockProcessor)find_processor(BundleProtocol.bundle_block_type_t.PRIMARY_BLOCK);
assert(blocks.front().owner() == pbp);
pbp.generate_primary(bundle, blocks, blocks.front());
// "make a final pass through, calling finalize() and extracting
// the block length" [DTN2]
int total_len = 0;
for (int i=blocks.size() -1; i >= 0; i--)
{
BlockInfo iter = blocks.get(i);
iter.owner().finalize(bundle, blocks, iter, link);
total_len += iter.full_length();
}
return total_len;
}
/**
* "Remove blocks for the Bundle from the given link." [DTN2]
* @param bundle
* @param link
*/
public static void delete_blocks(Bundle bundle, final Link link) {
assert(bundle != null);
bundle.xmit_link_block_set().delete_blocks(link);
}
/**
* "Return the total length of the formatted bundle block data." [DTN2]
*/
public static int total_length(final BlockInfoVec blocks) {
int ret = 0;
Iterator<BlockInfo> itr = blocks.iterator();
while(itr.hasNext())
{
BlockInfo block = itr.next();
ret += block.full_length();
}
return ret;
}
/**
* "Temporary helper function to find the offset of the first byte of the
* payload in a BlockInfoVec." [DTN2]
*/
public static int payload_offset(final BlockInfoVec blocks) {
int ret = 0;
Iterator<BlockInfo> itr = blocks.iterator();
while(itr.hasNext())
{
BlockInfo block = itr.next();
if (block.type() == BundleProtocol.bundle_block_type_t.PAYLOAD_BLOCK) {
ret += block.data_offset();
return ret;
}
ret += block.full_length();
}
return ret;
}
/**
* "Copies out a chunk of formatted bundle data at a specified offset from
* the provided BlockInfoVec." [DTN2]
*
* @return "the length of the chunk produced (up to the supplied length) and
* sets last to true if the bundle is complete." [DTN2]
*/
public static int produce(final Bundle bundle, final BlockInfoVec blocks,
IByteBuffer data, int offset, int len, boolean[] last) {
int old_position = data.position();
int origlen = len;
last[0] = false;
if (len == 0)
return 0;
assert(!blocks.isEmpty());
Iterator<BlockInfo> iter = blocks.iterator();
BlockInfo current_block = iter.next();
// "advance past any blocks that are skipped by the given offset."[DTN2]
while (offset >= current_block.full_length()) {
Log.d(TAG, String.format("BundleProtocol::produce skipping block type %s " +
"since offset %d >= block length %d",
current_block.type().toString(),
offset,
current_block.full_length()));
offset -= current_block.full_length();
current_block = iter.next();
}
// "the offset value now should be within the current block" [DTN2]
while (true) {
// The first time remainder will be minus from leftover offset above
// but later on it will be the full content of the block
int remainder = current_block.full_length() - offset;
int tocopy = Math.min(len, remainder);
Log.d(TAG, String.format("BundleProtocol::produce copying %d/%d bytes from " +
"block type %s at offset %d",
tocopy,
remainder,
current_block.type().toString(),
offset
));
current_block.owner().produce(bundle, current_block, data, offset, tocopy);
len -= tocopy;
// move the position of IByteBuffer
data.position(data.position() + tocopy);
// "if we've copied out the full amount the user asked for,
// we're done. note that we need to check the corner case
// where we completed the block exactly to properly set the
// last bit" [DTN2]
if (len == 0) {
if ((tocopy == remainder) &&
((current_block.flags() & BundleProtocol.block_flag_t.BLOCK_FLAG_LAST_BLOCK.getCode()) > 0))
{
last[0] = true;
}
break;
}
// "we completed the current block, so we're done if this
// is the last block, even if there's space in the user buffer" [DTN2]
assert(tocopy == remainder);
if ((current_block.flags() & BundleProtocol.block_flag_t.BLOCK_FLAG_LAST_BLOCK.getCode()) > 0) {
last[0] = true;
break;
}
// advance to next block
current_block = iter.next();
offset = 0;
}
Log.d(TAG, String.format("BundleProtocol::produce complete: " +
"produced %d bytes, bundle id %d, status is %s",
origlen - len,
bundle.bundleid(),
last[0] ? "complete" : "not complete"));
data.position(old_position);
return origlen - len;
}
/**
* "Parse the supplied chunk of arriving data and append it to the
* rcvd_blocks_ list in the given bundle, finding the appropriate
* BlockProcessor element and calling its receive() handler.
*
* When called repeatedly for arriving chunks of data, this properly fills
* in the entire bundle, including the in_blocks_ record of the arriving
* blocks and the payload (which is stored externally)." [DTN2]
*
* @return "the length of data consumed or -1 on protocol error, plus sets
* last to true if the bundle is complete." [DTN2]
*/
public static int consume(Bundle bundle, IByteBuffer data, int len,
boolean []last) {
int old_position = data.position();
int origlen = len;
last[0] = false;
BlockInfoVec recv_blocks = bundle.recv_blocks();
// "special case for first time we get called, since we need to
// create a BlockInfo struct for the primary block without knowing
// the typecode or the length" [DTN2]
if (recv_blocks.isEmpty()) {
Log.d(TAG, "consume: got first block... " +
"creating primary block info");
recv_blocks.append_block(find_processor(bundle_block_type_t.PRIMARY_BLOCK), null);
}
// "loop as long as there is data left to process" [DTN2]
while (len != 0) {
Log.d(TAG, String.format("consume: %d bytes left to process", len));
BlockInfo info = recv_blocks.back();
// "if the last received block is complete, create a new one
// and push it onto the vector. at this stage we consume all
// blocks, even if there's no BlockProcessor that understands
// how to parse it" [DTN2]
if (info.complete()) {
data.mark();
byte bundle_block_type_byte = data.get();
bundle_block_type_t type = bundle_block_type_t.get(bundle_block_type_byte);
data.reset();
info = recv_blocks.append_block(find_processor( type) , null);
Log.d(TAG, String.format("consume: previous block complete, " +
"created new BlockInfo type %s",
info.owner().block_type()));
}
// "now we know that the block isn't complete, so we tell it to
// consume a chunk of data" [DTN2]
Log.d(TAG, String.format("consume: block processor %s type %s incomplete, " +
"calling consume (%d bytes already buffered)",
info.owner().block_type(),
info.type(),
info.contents().position()));
int cc = info.owner().consume(bundle, info, data, len);
if (cc < 0) {
Log.e(TAG, String.format("consume: protocol error handling block %s",
info.type()));
return -1;
}
// "decrement the amount that was just handled from the overall
// total. verify that the block was either completed or
// consumed all the data that was passed in." [DTN2]
len -= cc;
data.position(data.position() + cc);
Log.d(TAG, String.format("consume: consumed %d bytes of block type %s (%s)",
cc, info.type(),
info.complete() ? "complete" : "not complete"));
if (info.complete()) {
// check if we're done with the bundle
if ( (info.flags() & block_flag_t.BLOCK_FLAG_LAST_BLOCK.getCode()) > 0) {
last[0] = true;
break;
}
} else {
assert(len == 0);
}
}
Log.d(TAG, String.format("bundle id %d consume completed, %d/%d bytes consumed %s",
bundle.bundleid(),
origlen - len,
origlen,
last[0] ? "(completed bundle)" : ""
));
data.position( old_position);
return origlen - len;
}
/**
* "Bundle Status Report "Reason Code" flags" [DTN2]
*/
public static enum status_report_reason_t {
REASON_NO_ADDTL_INFO("no additional information",(byte)0x00),
REASON_LIFETIME_EXPIRED("lifetime expired", (byte)0x01),
REASON_FORWARDED_UNIDIR_LINK("forwarded over unidirectional link", (byte)0x02),
REASON_TRANSMISSION_CANCELLED("transmission cancelled", (byte)0x03),
REASON_DEPLETED_STORAGE("depleted storage", (byte)0x04),
REASON_ENDPOINT_ID_UNINTELLIGIBLE("endpoint id unintelligible", (byte)0x05),
REASON_NO_ROUTE_TO_DEST("no known route to destination", (byte)0x06),
REASON_NO_TIMELY_CONTACT("no timely contact", (byte)0x07),
REASON_BLOCK_UNINTELLIGIBLE("block unintelligible", (byte)0x08),
;
private static final Map<Byte, status_report_reason_t> lookupCode = new HashMap<Byte, status_report_reason_t>();
private static final Map<String, status_report_reason_t> lookupCaption = new HashMap<String, status_report_reason_t>();
static {
for (status_report_reason_t s : EnumSet
.allOf(status_report_reason_t.class))
{
lookupCode.put(s.getCode(), s);
lookupCaption.put(s.getCaption(), s);
}
}
private byte code;
private String caption;
private status_report_reason_t(String caption, byte code) {
this.code = code;
this.caption = caption;
}
public byte getCode() {
return code;
}
public String getCaption() {
return caption;
}
public static status_report_reason_t get(byte code) {
return lookupCode.get(code);
}
}
/**
* "Loop through the bundle's received block list to validate each entry." [DTN2]
*
* @return "true if the bundle is valid, false if it should be deleted." [DTN2]
*/
public static boolean validate(Bundle bundle,
status_report_reason_t[] reception_reason,
status_report_reason_t[] deletion_reason) {
int primary_blocks = 0, payload_blocks = 0;
BlockInfoVec recv_blocks = bundle.recv_blocks();
// "a bundle must include at least two blocks (primary and payload)" [DTN2]
if (recv_blocks.size() < 2) {
Log.e(TAG, "bundle fails to contain at least two blocks");
deletion_reason[0] = BundleProtocol.status_report_reason_t.REASON_BLOCK_UNINTELLIGIBLE;
return false;
}
// "the first block of a bundle must be a primary block" [DTN2]
if (recv_blocks.front().type() != BundleProtocol.bundle_block_type_t.PRIMARY_BLOCK) {
Log.e(TAG, "bundle fails to contain a primary block");
deletion_reason[0] = BundleProtocol.status_report_reason_t.REASON_BLOCK_UNINTELLIGIBLE;
return false;
}
// "validate each individual block" [DTN2]
int last_block_index = recv_blocks.size() - 1;
for(int i=0; i < recv_blocks.size(); i++)
{
BlockInfo current_block = recv_blocks.get(i);
// "a block may not have enough data for the preamble" [DTN2]
if (current_block.data_offset() == 0) {
// "either the block is not the last one and something went
// badly wrong, or it is the last block present" [DTN2]
if (i != last_block_index) {
Log.e(TAG, "bundle block too short for the preamble");
deletion_reason[0] = BundleProtocol.status_report_reason_t.REASON_BLOCK_UNINTELLIGIBLE;
return false;
}
// "this is the last block, so drop it" [DTN2]
Log.d(TAG, "forgetting preamble-starved last block");
recv_blocks.remove(current_block);
if (recv_blocks.size() < 2) {
Log.e(TAG, "bundle fails to contain at least two blocks");
deletion_reason[0] = BundleProtocol.status_report_reason_t.REASON_BLOCK_UNINTELLIGIBLE;
return false;
}
// "continue with the tests; results may have changed now that
// a different block is last" [DTN2]
return false;
}
else {
if (current_block.type() == BundleProtocol.bundle_block_type_t.PRIMARY_BLOCK) {
primary_blocks++;
}
if (current_block.type() == BundleProtocol.bundle_block_type_t.PAYLOAD_BLOCK) {
payload_blocks++;
}
}
if (!current_block.owner().validate(bundle, recv_blocks, current_block,
reception_reason, deletion_reason)) {
return false;
}
// "a bundle's last block must be flagged as such,
// and all other blocks should not be flagged" [DTN2]
if (i == last_block_index) {
if (!current_block.last_block()) {
if (!bundle.fragmented_incoming()) {
Log.e(TAG, "bundle's last block not flagged");
deletion_reason[0] = BundleProtocol.status_report_reason_t.REASON_BLOCK_UNINTELLIGIBLE;
return false;
}
else {
Log.d(TAG, "bundle's last block not flagged, but " +
"it is a reactive fragment");
}
}
} else {
if (current_block.last_block()) {
Log.e(TAG, "bundle block incorrectly flagged as last");
deletion_reason[0] = BundleProtocol.status_report_reason_t.REASON_BLOCK_UNINTELLIGIBLE;
return false;
}
}
}
// "a bundle must contain one, and only one, primary block" [DTN2]
if (primary_blocks != 1) {
Log.e(TAG, String.format("bundle contains %d primary blocks", primary_blocks));
deletion_reason[0] = BundleProtocol.status_report_reason_t.REASON_BLOCK_UNINTELLIGIBLE;
return false;
}
// "a bundle must not contain more than one payload block" [DTN2]
if (payload_blocks > 1) {
Log.e(TAG, String.format("bundle contains %d payload blocks", payload_blocks));
deletion_reason[0] = BundleProtocol.status_report_reason_t.REASON_BLOCK_UNINTELLIGIBLE;
return false;
}
return true;
}
/**
* "The current version of the bundling protocol." [DTN2]
*/
static final int CURRENT_VERSION = 0x06;
static final int PREAMBLE_FIXED_LENGTH = 1;
/**
* "Valid type codes for bundle blocks." [DTN2]
*/
public static enum bundle_block_type_t {
PRIMARY_BLOCK((byte) 0), // /< "INTERNAL ONLY -- NOT IN SPEC" [DTN2]
PAYLOAD_BLOCK((byte) 1),
UNKNOWN_BLOCK((byte) 90) // /< "INTERNAL ONLY -- NOT IN SPEC" [DTN2]
;
private static final Map<Byte, bundle_block_type_t> lookup = new HashMap<Byte, bundle_block_type_t>();
static {
for (bundle_block_type_t s : EnumSet
.allOf(bundle_block_type_t.class))
lookup.put(s.getCode(), s);
}
private byte code;
private bundle_block_type_t(byte code) {
this.code = code;
}
public byte getCode() {
return code;
}
public static bundle_block_type_t get(byte code) {
return lookup.get(code);
}
}
/**
* "Values for block processing flags that appear in all blocks except the
* primary block." [DTN2]
*/
public static enum block_flag_t {
BLOCK_FLAG_REPLICATE((1 << 0)), BLOCK_FLAG_REPORT_ONERROR((1 << 1)), BLOCK_FLAG_DISCARD_BUNDLE_ONERROR(
(1 << 2)), BLOCK_FLAG_LAST_BLOCK((1 << 3)), BLOCK_FLAG_DISCARD_BLOCK_ONERROR(
(1 << 4)), BLOCK_FLAG_FORWARDED_UNPROCESSED((1 << 5)), BLOCK_FLAG_EID_REFS(
(1 << 6));
private static final Map<Integer, block_flag_t> lookup = new HashMap<Integer, block_flag_t>();
static {
for (block_flag_t s : EnumSet.allOf(block_flag_t.class))
lookup.put(s.getCode(), s);
}
private int code;
private block_flag_t(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static block_flag_t get(int code) {
return lookup.get(code);
}
}
/**
* "The basic block preamble that's common to all blocks (including the
* payload block but not the primary block)." [DTN2]
*/
class BlockPreamble {
byte type;
byte flags;
byte length; // SDNV
};
/**
* "Administrative Record Type Codes" [DTN2]
*/
public static enum admin_record_type_t {
ADMIN_STATUS_REPORT((byte) 0x01), ADMIN_CUSTODY_SIGNAL((byte) 0x02), ADMIN_ANNOUNCE(
(byte) 0x05) // "NOT IN BUNDLE SPEC" [DTN2]
;
private static final Map<Byte, admin_record_type_t> lookup = new HashMap<Byte, admin_record_type_t>();
static {
for (admin_record_type_t s : EnumSet
.allOf(admin_record_type_t.class))
lookup.put(s.getCode(), s);
}
private byte code;
private admin_record_type_t(byte code) {
this.code = code;
}
public byte getCode() {
return code;
}
public static admin_record_type_t get(byte code) {
return lookup.get(code);
}
}
/**
* "Administrative Record Flags." [DTN2]
*/
public static enum admin_record_flags_t {
ADMIN_IS_FRAGMENT((byte) 0x01);
private static final Map<Byte, admin_record_flags_t> lookup = new HashMap<Byte, admin_record_flags_t>();
static {
for (admin_record_flags_t s : EnumSet
.allOf(admin_record_flags_t.class))
lookup.put(s.getCode(), s);
}
private byte code;
private admin_record_flags_t(byte code) {
this.code = code;
}
public byte getCode() {
return code;
}
public static admin_record_flags_t get(byte code) {
return lookup.get(code);
}
}
/**
* Custody Signal Reason Codes
*/
public static enum custody_signal_reason_t {
CUSTODY_NO_ADDTL_INFO("no additional info", (byte) 0x00),
CUSTODY_REDUNDANT_RECEPTION("redundant reception", (byte) 0x03),
CUSTODY_DEPLETED_STORAGE("depleted storage", (byte) 0x04),
CUSTODY_ENDPOINT_ID_UNINTELLIGIBLE("eid unintelligible", (byte) 0x05),
CUSTODY_NO_ROUTE_TO_DEST("no route to dest", (byte) 0x06),
CUSTODY_NO_TIMELY_CONTACT("no timely contact", (byte) 0x07),
CUSTODY_BLOCK_UNINTELLIGIBLE("block unintelligible", (byte) 0x08);
private static final Map<Byte, custody_signal_reason_t> lookup = new HashMap<Byte, custody_signal_reason_t>();
private static final Map<String, custody_signal_reason_t> caption_map = new HashMap<String, custody_signal_reason_t>();
static {
for (custody_signal_reason_t s : EnumSet
.allOf(custody_signal_reason_t.class))
{
lookup.put(s.getCode(), s);
caption_map.put(s.getCaption(), s);
}
}
private byte code_;
private String caption_;
private custody_signal_reason_t(String caption, byte code) {
this.caption_ = caption;
this.code_ = code;
}
public byte getCode() {
return code_;
}
public String getCaption() {
return caption_;
}
public static custody_signal_reason_t get(byte code) {
return lookup.get(code);
}
}
/**
* "Assuming the given bundle is an administrative bundle, extract the admin
* bundle type code from the bundle's payload." [DTN2]
*
* @return true if successful
*/
public static boolean get_admin_type(final Bundle bundle,
admin_record_type_t[] type) {
if (! bundle.is_admin()) {
return false;
}
IByteBuffer buf = new SerializableByteBuffer(16);
bundle.payload().read_data(0, 1, buf);
admin_record_type_t admin_record_type = admin_record_type_t.get((byte)(buf.get(0) >> 4));
switch (admin_record_type)
{
case ADMIN_STATUS_REPORT:
case ADMIN_CUSTODY_SIGNAL:
case ADMIN_ANNOUNCE:
type[0] = admin_record_type;
return true;
default:
return false; // unknown type
}
}
/**
* List of registered processors to this BundleProtocol class
*/
private static List< BlockProcessor> processors_ = new List<BlockProcessor>();
};
| [
"[email protected]"
]
| |
1837ea40ab2ba64a0fd0ddc18a15f1d7cdc54d4b | a0815f014cc6a5c31f50a48107ad3efff1a678a3 | /Main.java | 9ae2d2099bb7aa5d881b002573e0ff088af3d1ae | []
| no_license | BudnikovaNastiya/Java-1.1-1 | a8e3750f2449b7f81e54d5f2cb3949982cb220e1 | 20f115a7ef4f6f67171a584ce184d6a6bf8efa68 | refs/heads/master | 2023-04-25T18:02:01.722202 | 2021-05-18T10:49:44 | 2021-05-18T10:49:44 | 366,725,178 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,105 | java | public class Main {
public static void main(String[] args) {
// TODO: ะฟะพะดััะฐะฒะปััั ะฝะพะผะตั ะบะฐััั ะฝัะถะฝะพ ััะดะฐ ะผะตะถะดั ะดะฒะพะนะฝัะผะธ ะบะฐะฒััะบะฐะผะธ, ะฑะตะท ะฟัะพะฑะตะปะพะฒ
String number = "63049263156801909";
System.out.println(String.format("Result is %s", isValidCardNumber(number) ? "OK" : "FAIL"));
}
public static boolean isValidCardNumber(String number) {
if (number == null) {
return false;
}
if (number.length() != 16) {
return false;
}
long result = 0;
for (int i = 0; i < number.length(); i++) {
int digit;
try {
digit = Integer.parseInt(number.charAt(i) + "");
} catch (NumberFormatException e) {
return false;
}
if (i % 2 == 0) {
digit *= 2;
if (digit > 9) {
digit -= 9;
}
}
result += digit;
}
return (result != 0) && (result % 10 == 0);
}
} | [
"[email protected]"
]
| |
860a030dc0ec18d73c23e76a35531b5b16e5a3df | 7d0fb5b75180a1d083ac08fcc65bb340e0176ed1 | /mobilephone-shop-portal/src/main/java/net/hycollege/protal/services/OrderService.java | ea7018fccb11a5e84190afa840cead46b3ed32e6 | []
| no_license | luozili/mobilephone-shop | b29adf4f77d4f81d8b16544602c28d55291c7bba | bd4b48339984b9e635500160874469cb2a8f7a92 | refs/heads/master | 2022-12-10T10:57:17.281913 | 2020-06-04T07:36:11 | 2020-06-04T07:36:11 | 223,581,308 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 377 | java | package net.hycollege.protal.services;
import com.alipay.api.response.AlipayTradePayResponse;
import net.hycollege.message.bean.layui.LayUITableMessage;
public interface OrderService {
public LayUITableMessage getOrder(String token);
public void updateOrder(AlipayTradePayResponse alipayTradePayResponse);
public LayUITableMessage getOrderProduct(String out_trade_no);
}
| [
"[email protected]"
]
| |
70de17ad695674279b5bfd6ab3e7977590f1d1fe | 077f81916b719a57435ae579628977c3ebbc1478 | /trinidad-api/src/main/java/org/apache/myfaces/trinidad/validator/RegExpValidator.java | 7f3a188e257992454a0da14d70cf0866448347d8 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
]
| permissive | m-y-mo/myfaces-trinidad_20165019 | e9f2da811aaa07160b8b660fa13743750c5932d4 | 43125e45e1c56fab0cc56e32d079be787209d3b4 | refs/heads/master | 2020-03-07T10:27:37.758086 | 2018-03-30T13:34:10 | 2018-03-30T13:34:10 | 127,431,966 | 0 | 1 | Apache-2.0 | 2020-02-11T14:23:38 | 2018-03-30T13:35:24 | Java | UTF-8 | Java | false | false | 11,852 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.myfaces.trinidad.validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.faces.application.FacesMessage;
import javax.faces.component.StateHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import org.apache.myfaces.trinidad.bean.FacesBean;
import org.apache.myfaces.trinidad.bean.PropertyKey;
import org.apache.myfaces.trinidad.util.ComponentUtils;
import org.apache.myfaces.trinidad.util.MessageFactory;
import org.apache.myfaces.trinidad.logging.TrinidadLogger;
/**
<p><strong>RegExpValidator</strong> is a {@link javax.faces.validator.Validator} that checks
* the value of the corresponding component against specified pattern
* using Java regular expression syntax.
*
* The regular expression syntax accepted by the RegExpValidator class is
* same as mentioned in class {@link java.util.regex.Pattern} in package
* <code>java.util.regex</code>. The following algorithm is implemented:</p>
*
* <ul>
* <li>If the passed value is <code>null</code>, exit immediately.</li>
*
* <li>If a <code>pattern</code> property has been configured on this
* {@link javax.faces.validator.Validator}, check the component value against this pattern.
* If value does not match pattern throw a {@link ValidatorException}
* containing a NO_MATCH_MESSAGE_ID message.
* If <code>noMatchMessageDetail</code> is set, it is used for constructing faces
* message. The message can contain placeholders which will be replaced as
* specified in {@link #NO_MATCH_MESSAGE_ID}</li>
* </ul>
* @see #setMessageDetailNoMatch(String)
*
* @version $Name: $ ($Revision: adfrt/faces/adf-faces-api/src/main/java/oracle/adf/view/faces/validator/RegExpValidator.java#0 $) $Date: 10-nov-2005.19:08:34 $
*/
public class RegExpValidator implements StateHolder, Validator
{
/**
* <p>Standard validator id for this validator.</p>
*/
public static final String VALIDATOR_ID = "org.apache.myfaces.trinidad.RegExp";
/**
* <p>The message identifier of the {@link FacesMessage}
* to be created if the match fails. The message format
* string for this message may optionally include a <code>{0}</code>,
* <code>{1}</code> and <code>{4}</code> placeholders, which will be replaced
* input value, label associated with the component and pattern respectively.</p>
*/
public static final String NO_MATCH_MESSAGE_ID
= "org.apache.myfaces.trinidad.validator.RegExpValidator.NO_MATCH";
/**
* <p>Construct a RegExpValidator with no preconfigured pattern.</p>
*/
public RegExpValidator()
{
super();
}
/**
* <p>Construct a RegExpValidator with preconfigured pattern.</p>
*/
public RegExpValidator(String pattern)
{
setPattern(pattern);
}
/**
* @exception ValidatorException if validation fails
* @exception NullPointerException if <code>context</code>
* or <code>component</code> or <code>pattern</code> is <code>null</code>
* @exception IllegalArgumentException if <code>value</code> is not of type
* {@link java.lang.String}
*/
public void validate(
FacesContext context,
UIComponent component,
Object value
) throws ValidatorException
{
if ((context == null) || (component == null))
{
throw new NullPointerException(_LOG.getMessage(
"NULL_FACESCONTEXT_OR_UICOMPONENT"));
}
if ( value != null)
{
ValidatorUtils.assertIsString(value,
"'value' is not of type java.lang.String.");
if (getPattern() == null)
throw new NullPointerException(_LOG.getMessage(
"NULL_REGEXP_PATTERN"));
// compile the regular expression if we haven't already.
// we cache the compiled regular expression because we can't cache
// the RE object, as it isn't thread safe.
if (_compiled == null)
{
try
{
_compiled = Pattern.compile(getPattern());
}
catch (PatternSyntaxException pse)
{
// compilation choked
throw pse;
}
}
String theValue = (String)value;
Matcher matcher = _compiled.matcher(theValue);
// the matched string has to be the same as the input
if (! matcher.matches())
{
throw new ValidatorException(_getNoMatchFoundMessage(context,
component,
theValue));
}
}
}
public boolean isTransient()
{
return (_isTransient);
}
public void setTransient(boolean transientValue)
{
_isTransient = transientValue;
}
public Object saveState(FacesContext context)
{
return _facesBean.saveState(context);
}
public void restoreState(FacesContext context, Object state)
{
_facesBean.restoreState(context, state);
}
/**
* <p>Set the {@link ValueBinding} used to calculate the value for the
* specified attribute if any.</p>
*
* @param name Name of the attribute for which to set a {@link ValueBinding}
* @param binding The {@link ValueBinding} to set, or <code>null</code>
* to remove any currently set {@link ValueBinding}
*
* @exception NullPointerException if <code>name</code>
* is <code>null</code>
* @exception IllegalArgumentException if <code>name</code> is not a valid
* attribute of this validator
*/
public void setValueBinding(String name, ValueBinding binding)
{
ValidatorUtils.setValueBinding(_facesBean, name, binding) ;
}
/**
* <p>Return the {@link ValueBinding} used to calculate the value for the
* specified attribute name, if any.</p>
*
* @param name Name of the attribute or property for which to retrieve a
* {@link ValueBinding}
*
* @exception NullPointerException if <code>name</code>
* is <code>null</code>
* @exception IllegalArgumentException if <code>name</code> is not a valid
* attribute of this validator
*/
public ValueBinding getValueBinding(String name)
{
return ValidatorUtils.getValueBinding(_facesBean, name);
}
/**
* <p>Compares this PatternValidator with the specified Object for
* equality.</p>
* @param object Object to which this PatternValidator is to be compared.
* @return true if and only if the specified Object is a PatternValidator
* and if the values pattern and transient are equal.
*/
@Override
public boolean equals(Object object)
{
if (this == object)
return true;
if ( object instanceof RegExpValidator )
{
RegExpValidator other = (RegExpValidator) object;
if ( this.isTransient() == other.isTransient() &&
ValidatorUtils.equals(getPattern(), other.getPattern()) &&
ValidatorUtils.equals(getMessageDetailNoMatch(),
other.getMessageDetailNoMatch())
)
{
return true;
}
}
return false;
}
/**
* <p>Returns the hash code for this Validator.</p>
* @return a hash code value for this object.
*/
@Override
public int hashCode()
{
int result = 17;
String pattern = getPattern();
String noMesgDetail = getMessageDetailNoMatch();
result = 37 * result + (pattern == null? 0 : pattern.hashCode());
result = 37 * result + (isTransient() ? 0 : 1);
result = 37 * result + (noMesgDetail == null ? 0 : noMesgDetail.hashCode());
return result;
}
/**
* <p>Custom hint message.</p>
* Overrides default hint message
* @param hintPattern Custom hint message.
*/
public void setHint(String hintPattern)
{
_facesBean.setProperty(_HINT_PATTERN_KEY, hintPattern);
}
/**
* <p>Return custom hint message.</p>
* @return Custom hint message.
* @see #setHint(String)
*/
public String getHint()
{
Object obj = _facesBean.getProperty(_HINT_PATTERN_KEY);
return ComponentUtils.resolveString(obj);
}
/**
* <p>Set the pattern value to be enforced by this {@link
* Validator}
* @param pattern to be enforced.
*/
public void setPattern(String pattern)
{
String prevPattern = getPattern();
if ((prevPattern != null) && prevPattern.equals(pattern))
return;
if ((prevPattern == null) && (pattern == null))
return;
_facesBean.setProperty(_PATTERN_KEY, pattern);
_compiled = null;
}
/**
* <p>Return the pattern value to be enforced by this {@link
* Validator}
*/
public String getPattern()
{
Object obj = _facesBean.getProperty(_PATTERN_KEY);
return ComponentUtils.resolveString(obj);
}
/**
* <p>Custom error message to be used, for creating detail part of the
* {@link FacesMessage}, when value does not match the specified pattern.</p>
* Overrides detail message identified by message id {@link #NO_MATCH_MESSAGE_ID}
* @param noMatchMessageDetail
*/
public void setMessageDetailNoMatch(String noMatchMessageDetail)
{
_facesBean.setProperty(_NO_MATCH_MESSAGE_DETAIL_KEY, noMatchMessageDetail);
}
/**
* <p>Return custom detail error message that was set for creating faces message,
* for values that do not match the specified pattern.</p>
* @return Custom error message
* @see #setMessageDetailNoMatch(String)
*/
public String getMessageDetailNoMatch()
{
Object obj = _facesBean.getProperty(_NO_MATCH_MESSAGE_DETAIL_KEY);
return ComponentUtils.resolveString(obj);
}
/**
* @todo custom message should be evaluated lazily and then be used for
* displaying message.
*/
private FacesMessage _getNoMatchFoundMessage(
FacesContext context,
UIComponent component,
String value)
{
Object noMatchMsgDet = _getRawNoMatchMessageDetail();
Object label = ValidatorUtils.getComponentLabel(component);
Object[] params = {label, value, getPattern()};
FacesMessage msg =
MessageFactory.getMessage(context, NO_MATCH_MESSAGE_ID,
noMatchMsgDet, params, label);
return msg;
}
private Object _getRawNoMatchMessageDetail()
{
return _facesBean.getRawProperty(_NO_MATCH_MESSAGE_DETAIL_KEY);
}
private static final FacesBean.Type _TYPE = new FacesBean.Type();
private static final PropertyKey _PATTERN_KEY
= _TYPE.registerKey("pattern", String.class);
private static final PropertyKey _NO_MATCH_MESSAGE_DETAIL_KEY
= _TYPE.registerKey("messageDetailNoMatch", String.class);
private static final PropertyKey _HINT_PATTERN_KEY =
_TYPE.registerKey("hint", String.class);
private FacesBean _facesBean = ValidatorUtils.getFacesBean(_TYPE);
private transient Pattern _compiled;
private boolean _isTransient = false;
private static final TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger(
RegExpValidator.class);
}
| [
"[email protected]"
]
| |
f4428e365ba76f97fc8407b4235e1d447b381e3e | b49f538d0ab1f81435feb30d7864d69d51a7c509 | /dspace-core/src/main/java/org/dspace/orm/entity/ResourcePolicy.java | d7cb071e1886f555263f6dbe3a064e7d67d4575f | []
| no_license | lyncode/DSpace-Spring | c599a80e7b62593ff88ef38e5e10f5996ee8b3d2 | 9417f788ee80ec696805aa1463631f59be03ccdb | refs/heads/master | 2020-06-04T15:21:22.231077 | 2013-07-02T22:01:35 | 2013-07-02T22:01:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,916 | java | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.orm.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.dspace.orm.dao.content.DSpaceObjectType;
import org.dspace.orm.dao.content.ResourcePolicyType;
import org.springframework.beans.factory.annotation.Configurable;
/**
* @author Miguel Pinto <[email protected]>
* @version $Revision$
*/
@Entity
@Table(name = "resourcepolicy")
@SequenceGenerator(name="resourcepolicy_gen", sequenceName="resourcepolicy_seq")
@Configurable
public class ResourcePolicy extends DSpaceObject{
private Integer resourceType;
private Integer resource;
private Integer action;
private Eperson eperson;
private EpersonGroup epersongroup;
private Date startDate;
private Date endDate;
private String rpName;
private String rpType;
private String rpDescription;
@Id
@Column(name = "policy_id")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="resourcepolicy_gen")
public int getID() {
return id;
}
@Override
@Transient
public DSpaceObjectType getType()
{
return DSpaceObjectType.RESOURCE_POLICY;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "epersongroup_id", nullable = true)
public EpersonGroup getEpersonGroup() {
return epersongroup;
}
public void setEpersonGroup(EpersonGroup epersongroup) {
this.epersongroup = epersongroup;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "eperson_id", nullable = true)
public Eperson getEperson() {
return eperson;
}
public void setEperson(Eperson owner) {
this.eperson = owner;
}
@Column(name = "resource_type_id", nullable = true)
public Integer getResourceType() {
return resourceType;
}
public void setResourceType(Integer resourceType) {
this.resourceType = resourceType;
}
@Column(name = "resource_id", nullable = true)
public Integer getResourceId() {
return resource;
}
public void setResourceId(Integer resource) {
this.resource = resource;
}
@Column(name = "action_id", nullable = true)
public Integer getAction() {
return action;
}
public void setAction(Integer action) {
this.action = action;
}
@Column(name = "start_date", nullable = true)
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
@Column(name = "end_date", nullable = true)
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@Column(name = "rpname", nullable = true)
public String getRpName() {
return rpName;
}
public void setRpName(String rpname) {
this.rpName = rpname;
}
@Column(name = "rptype", nullable = true)
public String getRpType() {
return rpType;
}
public void setRpType(String rptype) {
this.rpType = rptype;
}
@Column(name = "rpdescription", nullable = true)
public String getRpDescription() {
return rpDescription;
}
public void setRpDescription(String rpdescription) {
this.rpDescription = rpdescription;
}
@Transient
public ResourcePolicyType getResourcePolicyType () {
return ResourcePolicyType.valueOf(this.getRpType());
}
@Transient
public DSpaceObjectType getDSpaceObjectType () {
return DSpaceObjectType.RESOURCE_POLICY;
}
@Transient
public boolean isDateValid () {
Date sd = getStartDate();
Date ed = getEndDate();
// if no dates set, return true (most common case)
if ((sd == null) && (ed == null))
{
return true;
}
// one is set, now need to do some date math
Date now = new Date();
// check start date first
if (sd != null && now.before(sd))
{
// start date is set, return false if we're before it
return false;
}
// now expiration date
if (ed != null && now.after(ed))
{
// end date is set, return false if we're after it
return false;
}
// if we made it this far, start < now < end
return true; // date must be okay
}
}
| [
"[email protected]"
]
| |
e1e42a78b3a92c739c749f2238d9077bdf9f90bf | fa5dc7ffe9880d219217554fb9f0167efafb8cce | /src/main/java/reporting/ExtentsReports/ExtentManager.java | 1f339112ee8f1f431336a13f61530a50ad4b75f5 | []
| no_license | mdashrafkhanqa/SeleniumPagefactoryFramework | e3643d2a046c582c58dfe5d8779e7e25c7e5d789 | e95d8a512f7ff9c359d8aabaff38d90b78731e68 | refs/heads/master | 2022-03-08T23:32:38.264971 | 2019-11-09T18:57:05 | 2019-11-09T18:57:05 | 197,931,883 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 451 | java | package reporting.ExtentsReports;
import com.relevantcodes.extentreports.ExtentReports;
public class ExtentManager {
private static ExtentReports extent;
public synchronized static ExtentReports getReporter(){
if (extent == null){
String workingDir = System.getProperty("user.dir");
extent=new ExtentReports(workingDir+"/ExtentReports/ExtentReportResults.htm",true);
}
return extent;
}
}
| [
"[email protected]"
]
| |
0f2011d5c12cc07f7d73cf8873b05449a27bb5e6 | c258eafb67a638df06d1cf4050aa971491cec393 | /app/src/main/java/com/github/vase4kin/teamcityapp/runningbuilds/tracker/RunningBuildsViewTrackerImpl.java | 7a969119183fab1c9cea99da04b26dd7f1a8b0ad | [
"Apache-2.0"
]
| permissive | FrankNT/TeamCityApp | 54b3a0bf830db98e64effeb4051965ceffdef131 | e6ed96ca35d14c1b7ac89d2fc7ae2f044c00bf3d | refs/heads/master | 2021-01-13T09:17:11.724537 | 2016-09-13T13:40:23 | 2016-09-13T13:40:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,312 | java | /*
* Copyright 2016 Andrey Tolpeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.vase4kin.teamcityapp.runningbuilds.tracker;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.ContentViewEvent;
import com.github.vase4kin.teamcityapp.navigation.tracker.ViewTracker;
import io.fabric.sdk.android.Fabric;
/**
* {@link com.github.vase4kin.teamcityapp.runningbuilds.view.RunningBuildsListActivity} tracking
*/
public class RunningBuildsViewTrackerImpl implements ViewTracker {
/**
* {@inheritDoc}
*/
@Override
public void trackView() {
if (!Fabric.isInitialized()) return;
Answers.getInstance().logContentView(new ContentViewEvent()
.putContentName("Running build list"));
}
}
| [
"[email protected]"
]
| |
d3c90cfccda96e749171d92212c35bf60b582601 | 175ed275611570019cf18abec2bd728561fa7df1 | /hazelcast/src/main/java/com/hazelcast/config/DeviceConfig.java | 59350af2e036c5aff7d161596b26844d868d2c4b | [
"LicenseRef-scancode-hazelcast-community-1.0",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | pveentjer/hazelcast | 9b1640b9e965bd1eb42297549fb95269024e6c1f | b4bc2529cee9b3468b722721a0c89697a301ad2f | refs/heads/master | 2023-08-17T18:52:04.712622 | 2023-03-08T22:01:22 | 2023-03-08T22:01:22 | 10,990,111 | 1 | 4 | Apache-2.0 | 2019-10-09T09:10:25 | 2013-06-27T07:15:08 | Java | UTF-8 | Java | false | false | 1,106 | java | /*
* Copyright (c) 2008-2023, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.config;
import com.hazelcast.memory.Capacity;
/**
* Device configuration for the Tiered-Store
*
* @since 5.1
*/
public interface DeviceConfig extends NamedConfig {
/**
* Returns {@code true} if the device configuration is for a local device,
* otherwise, returns {@code false} if this configuration is for a remote device.
*/
boolean isLocal();
/**
* Returns the device capacity.
*/
Capacity getCapacity();
}
| [
"[email protected]"
]
| |
fb9f4504b356821d77d8eb473678434bb9bcfafa | 5e9441ab06fe5866b6cb772f0c5fdb76a4490a18 | /SoloBiciDidactico/app/src/main/java/com/example/anaguz/solobicididactico/Juego.java | 4ffb96fd259a5a249541c07ae8db73b54ad80a55 | []
| no_license | carolinajg66/PMM | 9a776d006ec36706c15bbad7471f243d630a022a | a2172fb6a762996752e71abe8a234d4649c5fae1 | refs/heads/master | 2021-09-07T03:03:02.679001 | 2018-02-16T11:25:43 | 2018-02-16T11:25:43 | 106,396,383 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 330 | java | package com.example.anaguz.solobicididactico;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by anaguz on 5/12/17.
*/
public class Juego extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.juego);
}
}
| [
"[email protected]"
]
| |
24227f11ad054045a030894118cad23e65585e0c | 975fa4d67d6d6e1e9cf5c074a542f695ca123100 | /data/src/main/java/com/piotrkostecki/smarttravelpoznan/data/database/datasource/SearchesDataSource.java | e8a162f1711eb98f4fbcb7b700d9495af4f4ae14 | []
| no_license | piotrkst/SmartTravelPoznan | c35372add4e67a0e9b938d38c1cbb53be8ea1c38 | d4e98b747728aa33af6e6b65f94359f4f504d565 | refs/heads/master | 2021-01-13T15:46:39.401287 | 2017-02-23T00:58:34 | 2017-02-23T00:58:34 | 76,879,088 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,474 | java | package com.piotrkostecki.smarttravelpoznan.data.database.datasource;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.piotrkostecki.smarttravelpoznan.data.database.MySQLiteHelper;
import com.piotrkostecki.smarttravelpoznan.data.entity.SearchEntity;
import com.piotrkostecki.smarttravelpoznan.domain.executor.ThreadExecutor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;
public class SearchesDataSource {
private ThreadExecutor threadExecutor;
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = {
MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_SEARCH,
MySQLiteHelper.COLUMN_QUANTITY
};
@Inject
public SearchesDataSource(Context context, ThreadExecutor threadExecutor) {
dbHelper = new MySQLiteHelper(context);
this.threadExecutor = threadExecutor;
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
database.close();
}
public void createSearch(String search) {
this.executeAsynchronously(() -> {
SearchEntity searchEntity = checkIfSearchExists(search);
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_SEARCH, search);
if (searchEntity == null) {
values.put(MySQLiteHelper.COLUMN_QUANTITY, 1);
database.insert(MySQLiteHelper.TABLE_SEARCHES, null,
values);
} else {
values.put(MySQLiteHelper.COLUMN_QUANTITY, searchEntity.getQuantity() + 1);
database.update(MySQLiteHelper.TABLE_SEARCHES, values, "_id =" + searchEntity.getId(), null);
}
this.close();
});
}
private Callable<List<SearchEntity>> getAllSearches() {
return () -> {
List<SearchEntity> searches = new ArrayList<>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_SEARCHES,
allColumns, null, null, null, null, MySQLiteHelper.COLUMN_QUANTITY + " DESC");
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
SearchEntity search = cursorToSearch(cursor);
searches.add(search);
Log.i("TEST", "getAllSearches: " + search.getName() + search.getQuantity());
cursor.moveToNext();
}
cursor.close();
return searches;
};
}
public SearchEntity checkIfSearchExists(String fieldValue) {
String query = "SELECT * FROM " + MySQLiteHelper.TABLE_SEARCHES + " WHERE " + MySQLiteHelper.COLUMN_SEARCH + "= '" + fieldValue + "'";
Cursor cursor = database.rawQuery(query, null);
if (cursor.getCount() <= 0) {
cursor.close();
return null;
}
cursor.moveToFirst();
SearchEntity search = cursorToSearch(cursor);
cursor.close();
return search;
}
private SearchEntity cursorToSearch(Cursor cursor) {
SearchEntity search = new SearchEntity();
search.setId(cursor.getLong(0));
search.setName(cursor.getString(1));
search.setQuantity(cursor.getInt(2));
return search;
}
public Observable<List<SearchEntity>> getSearches() {
return makeObservable(getAllSearches())
.subscribeOn(Schedulers.computation());
}
private static <T> Observable<T> makeObservable(final Callable<T> func) {
return Observable.create(
new Observable.OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> subscriber) {
try {
subscriber.onNext(func.call());
} catch(Exception ex) {
Log.e("Error", "Error reading from the database", ex);
}
}
});
}
private void executeAsynchronously(Runnable runnable) {
this.threadExecutor.execute(runnable);
}
}
| [
"[email protected]"
]
| |
056986969c99e22b1c35a1fee2d7b0bd3464c408 | 7208758de38cb70e70acffacec96a64aed2d77be | /AppointmentController.java | 2f4243f3f4d358ee7beb99120cb9a5aa6c73740b | []
| no_license | naresh14097/2021-08-13_Naresh | cf5ee6a625e7142f772a280ab85f943c2f679cef | 7c9ade656aea807cd54c6741d7ccc68f3f1feabe | refs/heads/main | 2023-07-08T15:14:15.673952 | 2021-08-13T07:40:01 | 2021-08-13T07:40:01 | 395,559,395 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 21,234 | java | package com.weserve.appointment.service.controller;
import com.weserve.appointment.service.exception.BusinessValidationException;
import com.weserve.appointment.service.model.dto.*;
import com.weserve.appointment.service.model.entity.AppointmentEntity;
import com.weserve.appointment.service.model.entity.AppointmentEntity_;
import com.weserve.appointment.service.model.entity.AppointmentTimeSlotEntity;
import com.weserve.appointment.service.model.entity.TruckVisitAppointment;
import com.weserve.appointment.service.model.entity.UnitEntity;
import com.weserve.appointment.service.services.AppointmentService;
import com.weserve.appointment.service.services.ApptStatusUpdateService;
import com.weserve.framework.base.model.entity.UserEntity;
import com.weserve.framework.hibernate.common.PersistenceInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import javax.xml.bind.JAXBException;
import javax.xml.datatype.DatatypeConfigurationException;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
@RestController
@RequestMapping("/api")
public class AppointmentController implements ApplicationContextAware {
@Autowired
AppointmentService appointmentService;
@Autowired
private ApptStatusUpdateService apptStatusUpdateService;
protected ApplicationContext applicationContext;
//For Hone Integration
/*@GetMapping(path = "getHoneApptTimeSlot")
public List<AppointmentTimeSlotEntity> fetchHoneApptTimeSlot(@RequestBody List<AppointmentTimeSlotEntity> apptslotlists) throws ParseException {
return appointmentService.findOrEnquireHoneAppointmentTimeSlot(apptslotlists);
}*/
@GetMapping(path = "getDeletedAppt")
public List<AppointmentEntity> fetchAllDeletedTranAppointment() {
return appointmentService.findAllDeletedAppointments();
}
@GetMapping(path = "getApptTimeSlot")
public List<AppointmentTimeSlotEntity> fetchApptTimeSlot(@RequestParam String date, String trantype) throws ParseException {
logger.debug("Current date to be processed recieved :: " + date + " :: Along with the tran type :: " + trantype);
/* List<AppointmentTimeSlotEntity> appointmentTimeSlotEntityList = new ArrayList<>();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-MMM-dd");
date = "20" + date;*/
logger.debug("Current date to be processed recieved :: modified :: " + date);
return appointmentService.findOrEnquireAppointmentTimeSlot(date, trantype);
}
@PostMapping(path = "updateAppointmentStatus")
public void updateAppointmentStatus(@RequestBody AppointmentStatusDTO appointmentStatusDTO) {
apptStatusUpdateService.updateAppointmentStatus(appointmentStatusDTO);
}
@ResponseBody
@RequestMapping(value = "getHoneApptTimeSlots", method = RequestMethod.POST)
public List<AppointmentTimeSlotEntity> getHoneApptTimeSlot(@RequestBody List<AppointmentTimeSlotEntity> apptslotlist) {
return appointmentService.getHoneApptTimeSlots(apptslotlist);
}
@GetMapping(path = "getTranAppt")
public List<AppointmentEntity> fetchAppointmentForSpecificSlot(@RequestParam Long slotId) {
return appointmentService.findAppointmentForSpecificSlot(slotId);
}
@PostMapping(path = "getTransactionAppt")
public AppointmentListDto FetchAllTransactionAppointments(@RequestBody FetchRequestDto fetchRequestDto) {
Pageable pageable = PageRequest.of(fetchRequestDto.getPage(), fetchRequestDto.getSize(), Sort.by(AppointmentEntity_.APPT_NBR).descending());
return appointmentService.findAllActiveAppointments(pageable, fetchRequestDto.getSortOrder(),
fetchRequestDto.getSortColumn(), fetchRequestDto.getFilterDtoList());
}
@GetMapping(path = "fetchApptByTrkVisit")
public List<AppointmentEntity> fetchApptByTrkVisit(@RequestParam String truckVisitApptKey) {
UserEntity userEntity = (UserEntity) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getAttribute("user_id", RequestAttributes.SCOPE_REQUEST);
TruckVisitAppointment truckVisitAppointment = (TruckVisitAppointment) PersistenceInterface.getInstance().
findById(TruckVisitAppointment.class, Long.valueOf(truckVisitApptKey));
return appointmentService.findApptByTruckVisitAppt(truckVisitAppointment, userEntity);
}
@GetMapping(path = "fetchUnit")
public UnitDetailsDTO fetchUnit(@RequestParam String unitId, @RequestParam String transactionType, @RequestParam String date) throws ExecutionException, InterruptedException {
CompletableFuture<UnitEntity> responseMsgComplete;
CompletableFuture<List<AppointmentTimeSlotEntity>> responseMsgComplete1;
UnitDetailsDTO unitDetailsDTO = new UnitDetailsDTO();
try {
responseMsgComplete = appointmentService.findOrEnquireUnitDetailsAsync(unitId, transactionType, true);
Date tempDate = new Date();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd HHmm");
LocalDateTime now = LocalDateTime.now();
String formattedDate = dtf.format(now);
if (transactionType.equalsIgnoreCase("DI")) {
responseMsgComplete1 = appointmentService.findOrEnquireHoneAppointmentTimeSlotAsync(unitId, transactionType);
/*if (responseMsgComplete1.get() == null || responseMsgComplete1.get().size() == 0) {
responseMsgComplete1 = appointmentService.findOrEnquireTOSAppointmentTimeSlotAsync(formattedDate, transactionType);
}*/
} else if (transactionType.equalsIgnoreCase("RE") || transactionType.equalsIgnoreCase("RM")) {
responseMsgComplete1 = appointmentService.findOrEnquireLocalAppointmentTimeSlotAsync(unitId, transactionType);
} else {
responseMsgComplete1 = appointmentService.findOrEnquireTOSAppointmentTimeSlotAsync(formattedDate, transactionType);
}
CompletableFuture.allOf(responseMsgComplete, responseMsgComplete1).join();
try {
UnitEntity unitEntity = Objects.requireNonNull(responseMsgComplete).get();
List<AppointmentTimeSlotEntity> appointmentTimeSlotEntityList = responseMsgComplete1.get();
if (unitEntity != null) {
unitDetailsDTO.setResponseMessage("Success");
unitDetailsDTO.setUnitEntity(unitEntity);
unitDetailsDTO.setAppointmentTimeSlotEntities(appointmentTimeSlotEntityList);
UserEntity userEntity = (UserEntity) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getAttribute("user_id", RequestAttributes.SCOPE_REQUEST);
unitDetailsDTO.setUserEntity(userEntity);
} else {
unitDetailsDTO.setResponseMessage("Unable to find Container Details in TOS");
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} catch (BusinessValidationException bve) {
unitDetailsDTO.setResponseMessage(bve.getErrorMessage());
}
return unitDetailsDTO;
}
@PostMapping(value = "createAppointment")
public ResponseEntity<String> createTranAppt(@RequestBody List<AppointmentEntity> appointmentList) throws ParseException, DatatypeConfigurationException, JAXBException {
String responseMsg = null;
List<AppointmentEntity> appointmentEntityList = new ArrayList<>();
CompletableFuture<String> responseMsgComplete;
UserEntity userEntity = (UserEntity) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getAttribute("user_id", RequestAttributes.SCOPE_REQUEST);
for (AppointmentEntity appointmentEntity : appointmentList) {
responseMsgComplete = appointmentService.findOrCreateAppointment(appointmentEntity, userEntity);
CompletableFuture.allOf(responseMsgComplete).join();
try {
responseMsg = responseMsgComplete.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
return new ResponseEntity<String>(responseMsg, HttpStatus.OK);
}
@PostMapping(value = "createExportEmptyAppointment")
public ResponseEntity<String> createExportEmptyAppointment(@RequestBody List<DualAppointmentDTO> appointmentDTOList) {
String responseMsg = null;
UserEntity userEntity = (UserEntity) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getAttribute("user_id", RequestAttributes.SCOPE_REQUEST);
CompletableFuture<String> responseMsgComplete;
for (DualAppointmentDTO dualAppointmentDTO : appointmentDTOList) {
try {
responseMsgComplete = appointmentService.findOrCreateExportEmptyAppointment(dualAppointmentDTO, userEntity);
CompletableFuture.allOf(responseMsgComplete).join();
try {
responseMsg = responseMsgComplete.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} catch (BusinessValidationException e) {
responseMsg = e.getErrorMessage();
return new ResponseEntity<String>(responseMsg, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
return new ResponseEntity<String>(responseMsg, HttpStatus.OK);
}
@PostMapping("/createBulkAppointmnets")
public @ResponseBody
ResponseEntity<String> createBulkAppointmnets(@RequestBody List<BulkAppointmentDTO> bulkAppointmentDTOS) {
StringBuilder responseMsg = new StringBuilder();
// List<BulkAppointmentDTO> appointmentDTOList = validateDTo(bulkAppointmentDTOS, responseMsg);
Map<String, Map<String, List<BulkAppointmentDTO>>> dateWiseBulkAppointmentDTO = new HashMap<>();
UserEntity userEntity = (UserEntity) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getAttribute("user_id", RequestAttributes.SCOPE_REQUEST);
//todo: Need to check with Keerthi whether to add the validating dto condtion in the existing for loop or write a separate method
// List<BulkAppointmentDTO> appointmentDTOList = validateDTo(bulkAppointmentDTOS, responseMsg);
for (BulkAppointmentDTO bulkAppointmentDTO : bulkAppointmentDTOS) {
// validate the dto
if (null == bulkAppointmentDTO.getApptDate() || null == bulkAppointmentDTO.getSlot()
|| null == bulkAppointmentDTO.getTranType1() || null == bulkAppointmentDTO.getContainerNumber1()) {
responseMsg.append(" Null value is provided for container::").append(bulkAppointmentDTO.getContainerNumber1()).append(" or ApptDate::").append(bulkAppointmentDTO.getApptDate())
.append(" ").append("or slot::").append(bulkAppointmentDTO.getSlot()).append(" ").append("or tranType::").append(bulkAppointmentDTO.getTranType1()).append("\n");
continue;
}
if ((!"RE".equalsIgnoreCase(bulkAppointmentDTO.getTranType1())) && (!"DI".equalsIgnoreCase(bulkAppointmentDTO.getTranType1())) &&
(!"RM".equalsIgnoreCase(bulkAppointmentDTO.getTranType1()))) {
responseMsg.append(" In valid Trantype ::").append(bulkAppointmentDTO.getTranType1()).append("is provided for the container ::").append(bulkAppointmentDTO.getContainerNumber1()).append("\n");
continue;
}
if ("DI".equalsIgnoreCase(bulkAppointmentDTO.getTranType1())) {
if (null == bulkAppointmentDTO.getPin()) {
responseMsg.append(" pin number is null for the container ::" + bulkAppointmentDTO.getContainerNumber1()).append("\n");
continue;
}
}
try {
LocalDateTime.of(LocalDate.parse((CharSequence) bulkAppointmentDTO.getApptDate(), localDateFormat),
LocalTime.parse(bulkAppointmentDTO.getSlot()));
} catch (Exception e) {
responseMsg.append(" Invalid data format is provided for ApptDate::").append(bulkAppointmentDTO.getApptDate()).append(" ").append("or SlotTime ::").append(bulkAppointmentDTO.getSlot()).append("\n");
logger.debug("Exception::" + e.getMessage());
continue;
}
//
if (dateWiseBulkAppointmentDTO.get(bulkAppointmentDTO.getApptDate()) == null) {
Map<String, List<BulkAppointmentDTO>> bulkAppointmentDTOMap = new HashMap<>();
List<BulkAppointmentDTO> bulkAppointmentDTOList = new ArrayList<>();
bulkAppointmentDTOList.add(bulkAppointmentDTO);
bulkAppointmentDTOMap.put(bulkAppointmentDTO.getSlot(), bulkAppointmentDTOList);
dateWiseBulkAppointmentDTO.put(bulkAppointmentDTO.getApptDate(), bulkAppointmentDTOMap);
} else {
if (dateWiseBulkAppointmentDTO.get(bulkAppointmentDTO.getApptDate()).get(bulkAppointmentDTO.getSlot()) == null) {
List<BulkAppointmentDTO> bulkAppointmentDTOList = new ArrayList<>();
bulkAppointmentDTOList.add(bulkAppointmentDTO);
dateWiseBulkAppointmentDTO.get(bulkAppointmentDTO.getApptDate()).put(bulkAppointmentDTO.getSlot(), bulkAppointmentDTOList);
} else {
dateWiseBulkAppointmentDTO.get(bulkAppointmentDTO.getApptDate()).get(bulkAppointmentDTO.getSlot()).add(bulkAppointmentDTO);
}
}
}
for (Map.Entry<String, Map<String, List<BulkAppointmentDTO>>> entry : dateWiseBulkAppointmentDTO.entrySet()) {
String currentDate = entry.getKey();
Map<String, List<BulkAppointmentDTO>> timeSlotWiseMap = entry.getValue();
CompletableFuture<String> responseMsgComplete;
for (Map.Entry<String, List<BulkAppointmentDTO>> timeSlotWiseMapEntry : timeSlotWiseMap.entrySet()) {
List<BulkAppointmentDTO> bulkAppointmentDTOList = timeSlotWiseMapEntry.getValue();
try {
responseMsgComplete = appointmentService.createBulkAppointment(currentDate, timeSlotWiseMapEntry.getKey(), bulkAppointmentDTOList, userEntity);
CompletableFuture.allOf(responseMsgComplete).join();
try {
responseMsg.append(responseMsgComplete.get()).append("\n");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} catch (BusinessValidationException e) {
e.printStackTrace();
}
}
}
return new ResponseEntity<>(responseMsg.toString(), HttpStatus.OK);
}
private List<BulkAppointmentDTO> validateDTo(List<BulkAppointmentDTO> bulkAppointmentDTOS, StringBuilder responseMsg) {
List<BulkAppointmentDTO> validData = new ArrayList<>();
for (BulkAppointmentDTO bulkAppointmentDTO : bulkAppointmentDTOS) {
if (null == bulkAppointmentDTO.getApptDate() || null == bulkAppointmentDTO.getSlot()
|| null == bulkAppointmentDTO.getTranType1() || null == bulkAppointmentDTO.getContainerNumber1()) {
responseMsg.append(" null value is provided for container::").append(bulkAppointmentDTO.getContainerNumber1()).append(" or ApptDate::").append(bulkAppointmentDTO.getApptDate())
.append(" ").append("or slot::").append(bulkAppointmentDTO.getSlot()).append(" ").append("or tranType::").append(bulkAppointmentDTO.getTranType1()).append("\n");
continue;
}
if ((!"RE".equalsIgnoreCase(bulkAppointmentDTO.getTranType1())) && (!"DI".equalsIgnoreCase(bulkAppointmentDTO.getTranType1())) &&
(!"RM".equalsIgnoreCase(bulkAppointmentDTO.getTranType1()))) {
responseMsg.append(" In valid Trantype ::").append(bulkAppointmentDTO.getTranType1()).append("is provided for the container ::").append(bulkAppointmentDTO.getContainerNumber1()).append("\n");
continue;
}
if ("DI".equalsIgnoreCase(bulkAppointmentDTO.getTranType1())) {
if (null == bulkAppointmentDTO.getPin()) {
responseMsg.append(" pin number is null for the container ::" + bulkAppointmentDTO.getPin());
continue;
}
}
try {
LocalDateTime.of(LocalDate.parse((CharSequence) bulkAppointmentDTO.getApptDate(), localDateFormat),
LocalTime.parse(bulkAppointmentDTO.getSlot()));
} catch (Exception e) {
responseMsg.append(" Invalid data format is provided for ApptDate::").append(bulkAppointmentDTO.getApptDate()).append(" ").append("or SlotTime ::").append(bulkAppointmentDTO.getSlot()).append("\n");
logger.debug("Exception::" + e.getMessage());
continue;
}
validData.add(bulkAppointmentDTO);
}
return validData;
}
@PostMapping(path = "disassociateAppt")
public ResponseEntity<String> disassociateAppointment(@RequestBody AppointmentEntity appointmentEntity) {
UserEntity userEntity = (UserEntity) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getAttribute("user_id", RequestAttributes.SCOPE_REQUEST);
boolean isDisassociatedSuccessful = appointmentService.disassociateAppointment(appointmentEntity, userEntity);
if (!isDisassociatedSuccessful) {
return new ResponseEntity<String>("Disassociated Un Successful..!", HttpStatus.OK);
}
return new ResponseEntity<String>("Disassociated sucessfully..!", HttpStatus.OK);
}
@PostMapping(path = "apptbulkdel")
public void deleteTranAppt(@RequestBody List<Long> tranApptList) {
UserEntity userEntity = (UserEntity) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getAttribute("user_id", RequestAttributes.SCOPE_REQUEST);
for (Long id : tranApptList) {
appointmentService.deleteTranAppointment(id, userEntity);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@GetMapping(path = "getDashboardAppt")
public DashboardResponseDto FetchAllDashboardTransAppointments() {
return appointmentService.findAllActiveDashboardAppointments();
}
@ResponseBody
@GetMapping(path = "seedAppointmentData")
public String seedData() {
return appointmentService.seedAppointmentData();
}
@GetMapping(path = "fetchAppointment")
public List<AppointmentEntity> findAppointment(@RequestParam String searcStringLiteral) {
UserEntity userEntity = (UserEntity) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getAttribute("user_id", RequestAttributes.SCOPE_REQUEST);
return appointmentService.findAppointmentUsingSearchLiteral(searcStringLiteral, userEntity);
}
@GetMapping(path = "getFutureDaysAppointment")
public List<AppointmentCountDTO> getFutureDaysAppointment(@RequestParam String finalDate) {
return appointmentService.getFutureDaysAppointment(finalDate);
}
@GetMapping(path = "getImportAppointmentForDual")
public @ResponseBody
ResponseEntity<List<AppointmentDTO>> getImportAppointmentForDual() {
return new ResponseEntity<>(appointmentService.getImportAppointmentForDual(), HttpStatus.OK);
}
private static final Logger logger = LoggerFactory.getLogger(AppointmentController.class);
private static DateTimeFormatter localDateFormat = DateTimeFormatter.ofPattern("yy-MMM-dd");
}
| [
"[email protected]"
]
| |
034f75246f67f7dbd79367048b1dd65840cf3991 | 279f8a5fd6bc7cf985e0f9166fb87d63bdd08e67 | /mavenModule/src/main/java/stringBuffer/TestReadFile.java | f76a7dd14410d5b37eb0b7dc27528d53c3d55682 | []
| no_license | sticky1/Asim | de807556343cf765bd44d7924599837ebd934774 | d16145cb7852d878ebc136852e3b4f5f624aa14a | refs/heads/master | 2020-05-15T12:25:01.229618 | 2013-10-24T15:18:53 | 2013-10-24T15:18:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 186 | java | package stringBuffer;
public class TestReadFile {
public static void main(String[] args) {
ReadFile readFileObject = new ReadFile();
readFileObject.read();
}
}
| [
"[email protected]"
]
| |
412ff6ca5bbafe2f0b9f97c8e3b990df5e32d5ce | a8b36e526364eca8dfcf5bf022d4ec177f8f1770 | /josecaos/02_category_widget/task_02_category_widget/android/app/src/main/java/com/yourcompany/task02categorywidget/MainActivity.java | 326db443ff717596951f37c7b6b696516981847e | [
"MIT",
"BSD-3-Clause"
]
| permissive | josecaos/StudyJam-Flutter | 00cf2fc25719afce95c1dafb11ed9fe893ea51ee | 9c541685fb877dba95683ee08e919a9d1f896a67 | refs/heads/master | 2020-03-22T18:43:57.854185 | 2018-09-18T05:43:49 | 2018-09-18T05:43:49 | 140,479,116 | 1 | 0 | MIT | 2018-07-10T19:36:44 | 2018-07-10T19:36:43 | null | UTF-8 | Java | false | false | 382 | java | package com.yourcompany.task02categorywidget;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
}
}
| [
"[email protected]"
]
| |
60d1b96fb44e3da4cef1ec40f192efa896f182d0 | dff3522a00fa7b81f1a5d9e21529f23fc7099ed8 | /src/main/java/com/yhy/lin/app/entity/AppStationInfoEntity.java | ea646901d54a5ad6d09b42d09a0151aa22c9ff0f | []
| no_license | Time-Boat/gwcx | 3fcf93b30c70389492bea06d23437bd9c45ff30a | 9eb064526179c3dd057052c41f55eadb675f6b8b | refs/heads/master | 2020-12-30T14:12:15.876820 | 2018-02-17T14:53:05 | 2018-02-17T14:53:05 | 91,282,633 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,275 | java | package com.yhy.lin.app.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.GenericGenerator;
/**
* ็ซ็นไฟกๆฏๅบ็ก่กจ
* @author linj
*
*/
@Entity
@Table(name="app_station_info_view")
public class AppStationInfoEntity implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**ไธป้ฎid*/
private String id;
/**็ซ็นๅ็งฐ*/
private String name;
/**็ซ็น็็ปๅบฆ๏ผ็จไบๅ้ขๅฐๅพๅฎ็ฐ๏ผ*/
private String x;
/**็ซ็น็็บฌๅบฆ๏ผ็จไบๅ้ขๅฐๅพๅฎ็ฐ๏ผ*/
private String y;
/**็ซ็นๅฐๅ*/
private String stopLocation;
/**็บฟ่ทฏid*/
private String lineId;
// /**ๅบๅ็ซ็น่ทฏๅพ ๅชๆๆธ ้ๅๆๆ็ๅญๆฎต*/
// private String[][] path;
//
// @Transient
// public String[][] getPath() {
// return path;
// }
// public void setPath(String[][] path) {
// this.path = path;
// }
@Column(name ="LINEID",nullable=true,length=50)
public String getLineId() {
return lineId;
}
public void setLineId(String lineId) {
this.lineId = lineId;
}
//ไธป้ฎ็ๆ็ญ็ฅ๏ผuuid ้็จ128ไฝ็uuid็ฎๆณ็ๆไธป้ฎ๏ผuuid่ขซ็ผ็ ไธบไธไธช32ไฝ16่ฟๅถๆฐๅญ็ๅญ็ฌฆไธฒใๅ ็จ็ฉบ้ดๅคง๏ผๅญ็ฌฆไธฒ็ฑปๅ๏ผใ
@Id
@GeneratedValue(generator = "paymentableGenerator")
@GenericGenerator(name = "paymentableGenerator", strategy = "uuid")
@Column(name ="id",nullable=false,length=32)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(name ="name",nullable=true,length=50)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="x",nullable=true,length=100)
public String getX() {
return x;
}
public void setX(String x) {
this.x = x;
}
@Column(name="y",nullable=true,length=100)
public String getY() {
return y;
}
public void setY(String y) {
this.y = y;
}
@Column(name="stopLocation",nullable=true,length=200)
public String getStopLocation() {
return stopLocation;
}
public void setStopLocation(String stopLocation) {
this.stopLocation = stopLocation;
}
}
| [
"[email protected]"
]
| |
fb6dc7cebfe9061b4284cd16305c66835e19476a | aa7dd19b7eee95825a0af6cd4f4207e6d5a92c7b | /src/main/java/br/edu/ifma/csp/timetable/model/Professor.java | b918d875d738276e8021f4781f0266c0a50822f9 | []
| no_license | ThuriyaThwin/AIMA-TimeTable | 45a3a3c1d715c6a167a7938acb54c5f32f8767fd | c91fb9db0e60a57c97eddf117ea12a809efd1f1a | refs/heads/master | 2020-04-26T18:25:34.747285 | 2016-09-27T15:53:12 | 2016-09-27T15:53:12 | 173,744,574 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,842 | java | package br.edu.ifma.csp.timetable.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name="PROFESSOR")
public class Professor extends Entidade {
private static final long serialVersionUID = -6331342046688981121L;
@Id
@NotNull
@Column(name="ID_PROFESSOR")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@NotNull
@Column(name="NOME")
private String nome;
@NotNull
@Column(name="ENDERECO")
private String endereco;
@OneToMany(fetch=FetchType.LAZY, mappedBy="professor")
private Set<Aula> aulas = new HashSet<Aula>();
@OneToMany(fetch=FetchType.LAZY, mappedBy="professor")
private Set<PreferenciaDisciplinaProfessor> preferencias = new HashSet<PreferenciaDisciplinaProfessor>();
public Professor() {
}
@Override
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public Set<Aula> getAulas() {
return aulas;
}
public void setAulas(Set<Aula> aulas) {
this.aulas = aulas;
}
public Set<PreferenciaDisciplinaProfessor> getPreferencias() {
return preferencias;
}
public void setPreferencias(Set<PreferenciaDisciplinaProfessor> preferencias) {
this.preferencias = preferencias;
}
@Override
public String toString() {
return this.getNome();
}
} | [
"[email protected]"
]
| |
3375bab2298dcbe46b35b902586f32eee67d2ccd | 200940b622a8b613ab53595a03fa298f4fa331b8 | /src/main/java/com/service/person/aop/PeopleServiceExceptionHandler.java | 45edaedbd9bdde05e3b90b4a4388dd8dda829861 | []
| no_license | nageshnkt2007/person-service | be9e7742b91ac19e35b6cc64aeb0e44130f0b028 | 9e4685c9b1fa29290ac70c7101db368674b84822 | refs/heads/main | 2023-02-28T18:11:15.437145 | 2021-02-13T18:19:21 | 2021-02-13T18:19:21 | 338,619,627 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,891 | java | package com.service.person.aop;
import com.service.person.dto.ApiError;
import com.service.person.exception.BadRequestException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
@RestControllerAdvice
@Component
public class PeopleServiceExceptionHandler {
private final Logger LOG = LoggerFactory.getLogger(ExceptionHandler.class);
/**
* handle controller methods parameter validation exceptions
*
* @param exception ex
* @return ResponseEntity with appropriate htttp status
*/
@ExceptionHandler
public ResponseEntity<?> handle(MethodArgumentNotValidException exception) {
ApiError apiError = new ApiError();
apiError.setStatus(HttpStatus.PRECONDITION_FAILED.value());
apiError.setError(HttpStatus.PRECONDITION_FAILED.getReasonPhrase());
apiError.setMessage(
exception.getAllErrors().get(0).getDefaultMessage());
return new ResponseEntity<>(apiError, HttpStatus.PRECONDITION_FAILED);
}
/**
* handle invalid person data in update requests.
*
* @param exception ex
* @return ResponseEntity with appropriate htttp status
*/
@ExceptionHandler
public ResponseEntity<?> handle(BadRequestException exception) {
ApiError apiError = new ApiError();
apiError.setStatus(HttpStatus.BAD_REQUEST.value());
apiError.setError(HttpStatus.BAD_REQUEST.getReasonPhrase());
apiError.setMessage(exception.getMessage());
return new ResponseEntity<>(apiError, HttpStatus.BAD_REQUEST);
}
/**
* handle controller methods parameter validation exceptions
*
* @param exception ex
* @return wrapped result
*/
@ExceptionHandler
public ResponseEntity<?> handle(ConstraintViolationException exception) {
Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
LOG.error("Validation exception occured :: {}", exception);
StringBuilder builder = new StringBuilder();
for (ConstraintViolation<?> violation : violations) {
builder.append(violation.getMessage());
break;
}
ApiError apiError = new ApiError();
apiError.setStatus(HttpStatus.PRECONDITION_FAILED.value());
apiError.setError(HttpStatus.PRECONDITION_FAILED.getReasonPhrase());
apiError.setMessage(
builder.toString());
return new ResponseEntity<>(apiError, HttpStatus.PRECONDITION_FAILED);
}
}
| [
"[email protected]"
]
| |
1a694207731d49c5625320a1c125f515dfa33069 | 20ffb61078a0e730caa70fdb42b06ef0bfa09339 | /src/test/java/lv/javaguru/junit/workshop/section1/SequentialSearchTest.java | d52d225eba256474873d7fdb9e24530a2ead4bbc | []
| no_license | whoismaikl/LearningJUnit | 6593b395bf30c63b100187daf04bb0e764ef378c | d3d57265dee18ab599d4a35c456135fcf0f4dda2 | refs/heads/master | 2023-08-23T11:21:40.365848 | 2017-02-12T22:07:30 | 2017-02-12T22:07:30 | 81,760,710 | 0 | 0 | null | 2023-08-10T07:19:36 | 2017-02-12T22:02:44 | Java | UTF-8 | Java | false | false | 1,153 | java | package lv.javaguru.junit.workshop.section1;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Created by xh on 12.02.2017.
*/
public class SequentialSearchTest {
private SequentialSearch sequensialSearch;
@Before
public void setUp() {
sequensialSearch = new SequentialSearch();
}
@Test
public void checkIsFindsCorrectIndexInSortedArray() {
int[] elementArray = {1, 2, 3, 4, 5, 6, 7};
int key = 3;
int position = sequensialSearch.search(elementArray, key);
assertThat(position, is(2));
}
@Test
public void checkIsFindsCorrectIndexInUnsortedArray() {
int[] elementArray = {13, 2, 3, 5, 5, 6, 9};
int key = 9;
int position = sequensialSearch.search(elementArray, key);
assertThat(position, is(6));
}
@Test
public void checkItFindsFirstElement() {
int[] elementArray = {1, 1, 1, 5, 5, 6, 9};
int key = 1;
int position = sequensialSearch.search(elementArray, key);
assertThat(position, is(0));
}
} | [
"[email protected]"
]
| |
b2cfe6af12a997a86458e4879a1ffe388ed8944d | b77be0b0e6b3ea59e8208a5980601729a198f4d1 | /app/src/main/java/com/google/android/gms/internal/ms.java | 8b3d45d2a66b6319fb693c03e84adfc92b8daa4d | []
| no_license | jotaxed/Final | 72bece24fb2e59ee5d604b6aca5d90656d2a7170 | f625eb81e99a23e959c9d0ec6b0419a3b795977a | refs/heads/master | 2020-04-13T11:50:14.498334 | 2018-12-26T13:46:17 | 2018-12-26T13:46:17 | 163,185,048 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 914 | java | package com.google.android.gms.internal;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.google.android.gms.common.internal.safeparcel.SafeParcelable;
import com.google.android.gms.fitness.data.DataSource;
public class ms implements SafeParcelable {
public static final Creator<ms> CREATOR = new mt();
private final int CK;
private final DataSource TN;
ms(int i, DataSource dataSource) {
this.CK = i;
this.TN = dataSource;
}
public int describeContents() {
return 0;
}
public DataSource getDataSource() {
return this.TN;
}
int getVersionCode() {
return this.CK;
}
public String toString() {
return String.format("ApplicationUnregistrationRequest{%s}", new Object[]{this.TN});
}
public void writeToParcel(Parcel parcel, int flags) {
mt.a(this, parcel, flags);
}
}
| [
"[email protected]"
]
| |
7c925f506a8ffc951e4d53dfb4a9f0d7a390a06a | db3158f66b2de3353626d42b354e679f38ed6e53 | /code/ButtonEventHandler.java | 9b6956634720fe600a245410b27e70cc983c04d3 | []
| no_license | jacondel/Scrabble-Clone | e4141bb92093587a0fc0a6fb52ed0a8d1c6705e7 | defd259586a09de2d81e77f4ea15af61aaacf701 | refs/heads/master | 2021-01-10T22:08:54.777614 | 2015-03-09T20:26:10 | 2015-03-09T20:26:10 | 31,920,580 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 562 | java | package code;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
/**
*
* @author jacondel
* @author brandanj
* @author djviggia
* @author nrwheele
*/
public class ButtonEventHandler implements ActionListener{
private GUI _gui;
public ButtonEventHandler(GUI gui) {
_gui=gui;
}
@Override
public void actionPerformed(ActionEvent e) {
JButton _lastClicked =(JButton)e.getSource();
_gui.setLastClickedRackIndex(Integer.parseInt(_lastClicked.getName()));
}
}
| [
"[email protected]"
]
| |
f5225cf0aa6e30ce00582275eec14f9c3f8c3196 | 597b3f0bb37e17b512d7482792f9168fd76d4ed5 | /Java-Spring-Car/MyApp/src/main/java/edu/ming/dao/impl/EngineDaoImpl.java | 6431791c29c14f10f30fb2c13b93e11e09df8b60 | []
| no_license | snmnmin12/Web-Design | 6b199d295d8ffc04808a8095ac7273092669f224 | c554edc10d52a70cb42933d5c1c655eec66092da | refs/heads/master | 2021-01-01T06:42:31.847926 | 2017-09-20T18:00:43 | 2017-09-20T18:00:43 | 97,491,039 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 951 | java | package edu.ming.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import edu.ming.dao.EngineDao;
import edu.ming.model.Engine;
@Repository
@Transactional
public class EngineDaoImpl implements EngineDao{
@PersistenceContext
private EntityManager entityManager;
public void add(Engine e) {
entityManager.merge(e);
}
public List<Engine> findAll()
{
String hql = "FROM engines";
return entityManager.createQuery(hql, Engine.class).getResultList();
}
public Engine find(int id)
{
return (Engine) entityManager.find(Engine.class, id);
}
public void edit(Engine engine)
{
entityManager.merge(engine);
}
public void delete(int id)
{
entityManager.remove(find(id));
}
}
| [
"[email protected]"
]
| |
6a43badd3825939c98eb8d0c44e935d605ffd035 | 1e8837412022974fd7ef277dfbb177a9ef86adfc | /Point2GPX/src/ku/ign/mapmatcher/JSON2PostGISCSV.java | 8e9574bfd89e3ac5169e2497aab29eb862fbb69a | []
| no_license | bsnizek/gisMapMatching | fd607b6cc41e7337b7aa98f8114c167465d8bbd9 | d712d249ec1bc2e0ee4287a14a1870ce8510c5c4 | refs/heads/master | 2020-04-18T11:54:03.016880 | 2014-09-15T08:46:14 | 2014-09-15T08:46:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,086 | java | package ku.ign.mapmatcher;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JSON2PostGISCSV {
String inDir = "json";
String wKTLinesFile = "wkt.csv";
public ArrayList<String> getJsonFiles(String dir) {
ArrayList<String> fileNames = new ArrayList<String>();
File f = new File(dir);
ArrayList<File> files = new ArrayList<File>(Arrays.asList(f.listFiles()));
for (File file : files) {
String[] tokens = file.getName().split("\\.(?=[^\\.]+$)");
if (tokens[1].equals("json")) {
fileNames.add(tokens[0]);
}
}
return fileNames;
}
private void build() throws IOException, ParseException {
ArrayList<String> jsonFileNames = this.getJsonFiles(inDir);
FileWriter fw = new FileWriter(wKTLinesFile);
fw.write("id;wkt\n");
for (String filename : jsonFileNames) {
String id = "null";
System.out.println(filename);
String wkTString = "LINESTRING(";
BufferedReader br = null;
br = new BufferedReader(new FileReader(inDir + File.separatorChar + filename + ".json"));
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(br);
JSONObject diary = (JSONObject) jsonObject.get("diary");
JSONArray entries = (JSONArray) diary.get("entries");
for (Object entry : entries) {
JSONObject jEntry = (JSONObject) entry;
JSONObject route = (JSONObject) jEntry.get("route");
JSONArray links = (JSONArray) route.get("links");
for (Object link : links) {
JSONObject jLink = (JSONObject) link;
JSONArray wpts = (JSONArray) jLink.get("wpts");
// System.out.println(wpts);
if (wpts != null) {
id = (String) ((JSONObject) wpts.get(0)).get("id");
}
String geometry = (String) jLink.get("geometry");
JSONObject jSGeometry = (JSONObject) jsonParser.parse(geometry);
JSONArray coordinates = (JSONArray) jSGeometry.get("coordinates");
for (Object coord : coordinates) {
String c = coord.toString();
String[] cc = c.split(",");
String lat = cc[0].substring(1,cc[0].length());
String lon = cc[1].substring(0,cc[1].length()-1);
// wkTString = wkTString + lon + " " + lat + ",";
wkTString = wkTString + lat + " " + lon + ",";
}
}
}
wkTString = wkTString.substring(0, wkTString.length()-1) + ")";
fw.write(filename + ";" + wkTString + ";" + id + "\n");
}
fw.close();
}
public static void main(String[] args) {
JSON2PostGISCSV j2PG = new JSON2PostGISCSV();
try {
j2PG.build();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| [
"[email protected]"
]
| |
bea6a74649e8d768651f4ce853c95fe30848d8bc | 16c286845f9a0cb829e69299737753f19b73e0cb | /nueva iteracion/presentation_tier/src/main/java/com/abs/siif/ppp/planning/uihelpers/ObjectiveLevelDataModel.java | d6a5e7e2d949e2c27e9cb2d76b2c917572e26d35 | []
| no_license | erickone/ABSnewRepository | f06ab47970dac7c1553765c5b8de51b024b24c62 | cf3edf1ac6d0d646e2666c553f426dc682f5a0ed | refs/heads/master | 2020-05-17T20:06:31.193230 | 2012-09-20T15:25:13 | 2012-09-20T15:25:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,295 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.abs.siif.ppp.planning.uihelpers;
import com.abs.siif.planning.entities.ObjectiveLevelEntity;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;
/**
*
* @author Juan Antonio Zavala Aguilar
*/
public class ObjectiveLevelDataModel extends ListDataModel<ObjectiveLevelEntity>
implements Serializable, SelectableDataModel<ObjectiveLevelEntity> {
public ObjectiveLevelDataModel() {
}
public ObjectiveLevelDataModel(List<ObjectiveLevelEntity> aDataModel) {
super(aDataModel);
}
@Override
public Object getRowKey(ObjectiveLevelEntity anEntity) {
return anEntity.getObjectiveLevelId();
}
@Override
public ObjectiveLevelEntity getRowData(String arowKey) {
List<ObjectiveLevelEntity> myObjectives = (List<ObjectiveLevelEntity>) getWrappedData();
ObjectiveLevelEntity myEntity = new ObjectiveLevelEntity();
myEntity.setObjectiveLevelId(Long.parseLong(arowKey));
int myIndex = myObjectives.indexOf(myEntity);
return myObjectives.get(myIndex);
}
}
| [
"[email protected]"
]
| |
9417383855c8e359c4bff042f044f46c56e4dea7 | 93050e4d0fb069985ef6ab0ff957809b73b56353 | /slow-donkey-server/src/main/java/io/bumble/slowdonkey/server/model/network/leader2oth/DataSyncRequest.java | f52d7086fe09aec51cfc025f6e643f4ae226eb95 | [
"Apache-2.0"
]
| permissive | xiaobei1009/slow-donkey | 980acdeff4687bfe0e57b0766dfeea8171ecafbc | effac0989f6591419297c8454c572c89916999ea | refs/heads/master | 2021-05-22T01:39:08.156882 | 2020-04-04T04:49:01 | 2020-04-04T04:49:01 | 252,996,867 | 0 | 0 | Apache-2.0 | 2020-04-04T12:56:02 | 2020-04-04T12:56:01 | null | UTF-8 | Java | false | false | 1,488 | java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.bumble.slowdonkey.server.model.network.leader2oth;
import io.bumble.slowdonkey.common.model.network.base.Request;
import io.bumble.slowdonkey.server.persistence.CommitLogEntry;
/**
* @author shenxiangyu on 2020/03/31
*/
public class DataSyncRequest extends Request {
private CommitLogEntry commitLogEntry;
public DataSyncRequest() {}
public DataSyncRequest(CommitLogEntry commitLogEntry) {
this.commitLogEntry = commitLogEntry;
}
public CommitLogEntry getCommitLogEntry() {
return commitLogEntry;
}
public void setCommitLogEntry(CommitLogEntry commitLogEntry) {
this.commitLogEntry = commitLogEntry;
}
}
| [
"[email protected]"
]
| |
8def06d2c26d8f9ff9457179c1044e7097bc2efd | c4813df4f1d948530cd7ef42e0d5ba002b95f8c1 | /src/main/java/org/standard/project/common/UploadUtilProductLong.java | c569900c8a2f2931ba3984e7fdbd683822e3a0c1 | []
| no_license | vinocturne/standard-project | caef79febffc573b3f8e81ef9d84dddf2eaa41c6 | f5783922a43b7512bd69bb6f1161a1fb397703a7 | refs/heads/master | 2023-03-24T11:16:16.218187 | 2021-03-21T05:12:55 | 2021-03-21T05:12:55 | 345,986,044 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,990 | java | package org.standard.project.common;
import java.util.UUID;
import org.springframework.util.FileCopyUtils;
import net.coobird.thumbnailator.Thumbnails;
import java.io.File;
import java.text.DecimalFormat;
import java.util.Calendar;
public class UploadUtilProductLong {
static final int THUMB_WIDTH = 300;
static final int THUMB_HEIGHT = 300;
//ํ์ผ ์
๋ก๋ ๋ฉ์๋
public static String fileUpload(String uploadPath, String fileName, byte[] fileData, String ymdPath)
throws Exception {
//๋ฌด์์ uuid์์ฑ
UUID uid = UUID.randomUUID();
//์
๋ก๋๋๋ ํ์ผ ์ด๋ฆ์ ๋ฌด์์uid+ํ์ผ์ด๋ฆ์ผ๋ก ๊ฒน์น๊ธฐ ํ๋ค๋๋ก ์์ฑ
String newFileName = "long_" + uid + "_" + fileName;
//์ด๋ฏธ์ง ํจ์ค ์ค์
String imgPath = uploadPath + ymdPath;
File target = new File(imgPath, newFileName);
FileCopyUtils.copy(fileData, target);
//์ธ๋ค์ผ ์์ฑ๋ถ๋ถ, ์ธ๋ค์ผ ์ด๋ฆ์ s_(uid)_(์
๋ก๋ํ์ผ์ด๋ฆ)
File image = new File(imgPath + File.separator + newFileName);
//์ด๋ฏธ์ง๊ฐ ์ ์ฅ๋๋ฉด ์ธ๋ค์ผ ์์ฑ.
if (image.exists()) {
}
return newFileName;
}
//ํ์ฌ ๋ ์ง ๊ธฐ์ค์ผ๋ก ํด๋๋ฅผ ๋ง๋ค์ด์ฃผ๋ ๋ฉ์๋.
public static String calcPath(String uploadPath) {
Calendar cal = Calendar.getInstance();
String yearPath = File.separator + cal.get(Calendar.YEAR);
String monthPath = yearPath + File.separator + new DecimalFormat("00").format(cal.get(Calendar.MONTH) + 1);
String datePath = monthPath + File.separator + new DecimalFormat("00").format(cal.get(Calendar.DATE));
makeDir(uploadPath, yearPath, monthPath, datePath);
makeDir(uploadPath, yearPath, monthPath, datePath + "\\s");
return datePath;
}
//ํด๋ ์์ฑ
private static void makeDir(String uploadPath, String... paths) {
if (new File(paths[paths.length - 1]).exists()) {
return;
}
for (String path : paths) {
File dirPath = new File(uploadPath + path);
if (!dirPath.exists()) {
dirPath.mkdir();
}
}
}
}
| [
"[email protected]"
]
| |
6c8b1c7fce8bd1ce185824b135d78a6cf2a46a6e | 2774144464ef36b056a4df8860a0bccdc07bcf47 | /Codes9/src/Player.java | 9b26ebce7819405cbcb5784ec16279781a54bbeb | []
| no_license | senseihimanshu/JavaAugReg4 | b52f4f9b99cd8a794a3553a776d8a144c1761690 | 532ad457a1779e2aadeb2d7707bdddcb94fc843c | refs/heads/master | 2021-08-18T17:19:20.412248 | 2017-11-23T12:23:57 | 2017-11-23T12:23:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 798 | java | import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Player implements GameConstants {
private int x;
private int y;
private int w;
private int h;
BufferedImage spriteSheet;
private final int FLOOR = GAME_HEIGHT - 50;
public Player(){
loadSpriteSheet();
x = 100;
h = 100;
w = 80;
y = FLOOR - h;
}
private void loadSpriteSheet(){
try {
spriteSheet = ImageIO.read(Player.class.getResource("player.gif"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public BufferedImage defaultImage(){
return spriteSheet.getSubimage(5, 110, 37, 84);
}
public void drawPlayer(Graphics g){
g.drawImage(defaultImage(), x, y, w, h, null);
}
}
| [
"[email protected]"
]
| |
8aa608f7e05749632bc07922efff26f30e00175c | 7c35723c1dbe116c3734a7cbf222b583c046c5f2 | /src/main/java/org/reactivestreams/HotPublisher.java | 1f9138011d130de62eb451600f922ae782e4d25e | [
"Apache-2.0"
]
| permissive | alexvictoor/MarbleTest4J | 44b1d4880f6f1de8a6902f4fc4315c880bae185d | cfe4647f006c7084256356d3a872f1bffb390cba | refs/heads/master | 2020-04-15T12:45:13.339143 | 2017-05-01T13:04:52 | 2017-05-01T13:04:52 | 60,415,664 | 15 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,756 | java | package org.reactivestreams;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Created by Alexandre Victoor on 18/04/2017.
*/
public class HotPublisher<T> implements Publisher<T>, TestablePublisher<T> {
private final List<Recorded<T>> notifications;
private final List<Subscriber<? super T>> observers = new ArrayList<>();
private final Scheduler scheduler;
List<SubscriptionLog> subscriptions = new ArrayList<>();
public HotPublisher(Scheduler scheduler, List<Recorded<T>> notifications) {
this.scheduler = scheduler;
this.notifications = notifications;
scheduleNotifications();
}
private void scheduleNotifications() {
for (final Recorded<T> event : notifications) {
scheduler.schedule(new Runnable() {
@Override
public void run() {
for (Subscriber<? super T> observer : new ArrayList<>(observers)){
event.value.accept(observer);
if (!event.value.isOnNext()) {
endSubscriptions(event.time);
}
}
}
}, event.time, TimeUnit.MILLISECONDS);
}
}
private void endSubscriptions(long time) {
for (int i = 0; i < subscriptions.size(); i++) {
SubscriptionLog subscription = subscriptions.get(i);
if (subscription.doesNeverEnd()) {
subscriptions.set(i, new SubscriptionLog(subscription.subscribe, time));
}
}
}
@Override
public void subscribe(final Subscriber<? super T> subscriber) {
observers.add(subscriber);
final SubscriptionLog subscriptionLog = new SubscriptionLog(scheduler.now(TimeUnit.MILLISECONDS));
subscriptions.add(subscriptionLog);
final int subscriptionIndex = subscriptions.size() - 1;
subscriber.onSubscribe(new Subscription() {
@Override
public void request(long l) {
// TODO check if useful
}
@Override
public void cancel() {
observers.remove(subscriber);
subscriptions.set(
subscriptionIndex,
new SubscriptionLog(subscriptionLog.subscribe, scheduler.now(TimeUnit.MILLISECONDS))
);
}
});
}
@Override
public List<SubscriptionLog> getSubscriptions() {
return Collections.unmodifiableList(subscriptions);
}
@Override
public List<Recorded<T>> getMessages() {
return Collections.unmodifiableList(notifications);
}
}
| [
"[email protected]"
]
| |
574076a72f8357f20d684af72f71e4ebc23e1bd0 | 02a0f27d67f36ab05619359660b798ae0c80aa88 | /tokoBaju.java | 3c82d256ac1f9799848ed5fd5f72d41f964d1800 | []
| no_license | naufalasad/Pertemuan-1 | e078b9101ce15da99020bbb9332cfb428352005c | 563b8075ab3e4ca3d0bb0e142dc05f5b153c6237 | refs/heads/master | 2021-01-18T16:30:16.134689 | 2015-04-08T12:25:32 | 2015-04-08T12:25:32 | 33,603,885 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 797 | java | import java.util.* ;
public class tokoBaju{
public static void main (String [] args)
{
Scanner sc=new Scanner (System.in);
int hargaBaju=50000;
int jumlahBajuDibeli;
int totalBonus;
int totalHarga;
int jumlahBajuBayar;
System.out.print("masukkan jumlah baju yang dibeli: ");
jumlahBajuDibeli=Integer.parseInt(sc.nextLine());
totalBonus=jumlahBajuDibeli / 3;
jumlahBajuBayar=jumlahBajuDibeli - totalBonus;
totalHarga=jumlahBajuBayar * hargaBaju;
System.out.println("Harga per baju = " + hargaBaju);
System.out.println("Total baju = " + jumlahBajuDibeli);
System.out.println("Jumlah bonus =" + totalBonus);
System.out.println("Jumlah baju yang harus di bayar = " + jumlahBajuBayar);
System.out.println("Total yg harus di bayar = " + totalHarga);
}
}
| [
"[email protected]"
]
| |
95d1eb3e5434db9b782478ffa14e95e712a34738 | 9784700094fe92e6cc540355022cdfb83a465ab5 | /src/com/yc/demo/dao/ClassInfoDao.java | 632a6fd9ce061ba9d3458a1faa5d55f44dc4b32d | []
| no_license | xsm-yt/-tomcat | 8a546a8dc4655e36959a726e66e59e6759555f2b | 563fdd6513a9037988f810e409001deb6fdc3ac0 | refs/heads/master | 2022-12-05T02:16:40.497867 | 2020-08-28T05:53:10 | 2020-08-28T05:53:10 | 290,965,504 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 248 | java | package com.yc.demo.dao;
import java.util.List;
import java.util.Map;
public class ClassInfoDao {
public List<Map<String,String>> finds(){
DBHelper db=new DBHelper();
String sql="select cid,cname from classinfo";
return db.gets(sql);
}
}
| [
"Administrator@PC-20170721DBXJ"
]
| Administrator@PC-20170721DBXJ |
7f1aba74206c08c00ae1db872574b121f581c358 | fc663c648144e1135dcfd737a9c52fd536f064ce | /app/src/main/java/com/example/a5e025799h/next_genshopping/ResultsActivity.java | 366682dc6f480fa2507d3fc03b6c52e128f295ab | []
| no_license | phaniaditya/AndroidApp | 74685e10b0492b2388d2f15b4e2faa39b50a64b7 | 9d7d85c6bc8239d35aadbbadf7f833774294614c | refs/heads/master | 2021-01-22T22:34:40.139992 | 2017-04-29T22:32:24 | 2017-04-29T22:32:24 | 85,554,100 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,905 | java | package com.example.a5e025799h.next_genshopping;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.google.firebase.auth.FirebaseAuth;
import java.util.ArrayList;
public class ResultsActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
ListView listView;
ArrayList<Results> results;
ProgressBar progressBar;
private FirebaseAuth auth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
listView = (ListView) findViewById(R.id.listView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
hideProgressBar();
String searchTerm = getIntent().getStringExtra("searchTerm");
String postalCode = getIntent().getStringExtra("postalCode");
Downloader downloader = new Downloader(this);
downloader.execute(searchTerm, postalCode);
auth = FirebaseAuth.getInstance();
}
public void displayProgressBar(){
progressBar.setVisibility(View.VISIBLE);
}
public void setProgressBarProgress(int progress){
progressBar.setProgress(progress);
if(progress==100){
hideProgressBar();
}
}
public void hideProgressBar(){
progressBar.setVisibility(View.GONE);
}
public void drawListView(ArrayList<Results> resultsArray){
results = new ArrayList<Results>();
results = resultsArray;
ResultsAdapter adapter = new ResultsAdapter(this, resultsArray);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Results result = results.get(position);
Intent intent = new Intent(this, DetailsActivity.class);
intent.putExtra("result", result);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.logoutMenu:
logoutUser();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void logoutUser(){
auth.signOut();
if(auth.getCurrentUser()==null){
startActivity(new Intent(ResultsActivity.this, MainActivity.class));
finish();
}
}
} | [
"[email protected]"
]
| |
50ccf032ee7194e5a2d23f31105ff502b1ac575d | 383b85101fd2df1cfbbb92c6d47c6aaa73d521cf | /asn1/axdr-compiler/src/main/java/org/bn/compiler/parser/model/AsnChoice.java | efd0521016aa3b5fc5d725f426db0857980ea376 | []
| no_license | xdom/jdlms | 9cb46589f4819ab241c92226f454461eab897200 | 968f7232a0876df39cc05209fce7850ec9c1beca | refs/heads/master | 2022-03-19T08:07:55.165320 | 2022-03-03T12:17:13 | 2022-03-03T12:25:00 | 101,627,683 | 4 | 4 | null | null | null | null | UTF-8 | Java | false | false | 1,044 | java | package org.bn.compiler.parser.model;
//~--- JDK imports ------------------------------------------------------------
import java.util.Iterator;
//~--- classes ----------------------------------------------------------------
//
//DefinitionofChoice
//
public class AsnChoice {
final String BUILTINTYPE = "CHOICE";
public AsnElementTypeList elementTypeList;
public String name;
public final boolean isChoice = true;
// ~--- constructors -------------------------------------------------------
// Default Constructor
public AsnChoice() {
name = "";
}
// ~--- methods ------------------------------------------------------------
@Override
public String toString() {
String ts = "";
ts += name + "\t::=\t" + BUILTINTYPE + "\t {";
if (elementTypeList != null) {
Iterator e = elementTypeList.elements.iterator();
while (e.hasNext()) {
ts += e.next();
}
}
ts += "}";
return ts;
}
}
| [
"[email protected]"
]
| |
e0f7479de4301b3b6f1301a7f67f44fffa6a938e | 5c6467fb564f532a7f51678e15acecc883a48a79 | /src/test/java/gov/fda/web/controller/WelcomeConrollerTest.java | 01ec5786b475c9b21393fdc03576ad11e068748b | [
"MIT"
]
| permissive | TechnikInc/openFDA-DevelopmentPrototype | 9f7ead223bb9ac708f6d7e6d3e455ef6be86f66e | b7261fdb634753cfe3695aefe58ce4838112c516 | refs/heads/master | 2020-07-21T19:45:47.748161 | 2016-02-15T20:59:35 | 2016-02-15T20:59:35 | 38,250,845 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 591 | java | package gov.fda.web.controller;
import static junit.framework.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
public class WelcomeConrollerTest {
private WelcomeController controller;
@Before
public void setUp() {
controller = new WelcomeController();
}
@Test
public void showHomePage() {
Map<String, Object> model = new HashMap<String, Object>();
String view = controller.index(model);
assertEquals(WelcomeController.START_PAGE, view);
}
}
| [
"[email protected]"
]
| |
ffb2fb93c26786453faa675945d28d78202152cf | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_feb6dde029ba7684e1133852da9eeb97e603f511/Pinger/2_feb6dde029ba7684e1133852da9eeb97e603f511_Pinger_t.java | 46fb8d91331da12ba7c03460b317b6fcec2e9b11 | []
| no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 715 | java | package com.vaguehope.chiaki.service;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.camel.ProducerTemplate;
public class Pinger extends TimerTask {
private static final long DELAY = 10L * 1000L; // 10 seconds.
private final Timer timer = new Timer();
private final ProducerTemplate producerTemplate;
public Pinger (ProducerTemplate producerTemplate) {
this.producerTemplate = producerTemplate;
}
public void start () {
this.timer.scheduleAtFixedRate(this, DELAY, DELAY);
}
public void dispose () {
this.timer.cancel();
}
@Override
public void run () {
this.producerTemplate.sendBody("activemq:topic:example.foo", "desu~");
}
}
| [
"[email protected]"
]
| |
7fa9e5483a8be384bd2488a2471cfa2adc5fb071 | ed0684ed7d0132c43c134a0394618101f7a1c447 | /app/src/main/java/freijo/castro/diego/tareapmdm07_practicafinal/clientes/ClientesFm.java | 0b692642814964243856caa37a37e06d7b91e039 | []
| no_license | DiegoPereiro/TareaPMDM07_PracticaFinal | 9e55dfe3c8fead1edd4b50ebb5b5485773d7a5b6 | a17582129da785997f91acde81031922b660dcad | refs/heads/master | 2020-05-19T14:52:01.731562 | 2019-05-26T20:34:48 | 2019-05-26T20:34:48 | 185,069,910 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,369 | java | package freijo.castro.diego.tareapmdm07_practicafinal.clientes;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import freijo.castro.diego.tareapmdm07_practicafinal.MainActivity;
import freijo.castro.diego.tareapmdm07_practicafinal.R;
import freijo.castro.diego.tareapmdm07_practicafinal.basedatos.BaseDatos;
public class ClientesFm extends Fragment {
private View vista;
private EditText etBuscar;
private ListView lvClientes;
private FloatingActionButton btnNuevo;
private SQLiteDatabase baseDatos;
private Cliente cliente;
private ArrayList<Cliente> list=new ArrayList<>();
private ClientesAdaptador adapter;
private OnFragmentInteractionListener mListener;
public ClientesFm() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
vista = inflater.inflate(R.layout.clientes_fm, container, false);
etBuscar=(EditText) vista.findViewById(R.id.etBuscar);
lvClientes=(ListView) vista.findViewById(R.id.lvClientes);
btnNuevo=(FloatingActionButton) vista.findViewById(R.id.btnNuevoPendiente);
BaseDatos dbatos = new BaseDatos(getContext(), "bdPmdm", null, MainActivity.version);
baseDatos = dbatos.getReadableDatabase();
btnNuevo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.lyInicio, new EditarClienteFm()).addToBackStack(null).commit();
}
});
cargarDatos("%");
return vista;
}
private void cargarDatos(String buscar) {
list.clear();
Cursor csClientes=baseDatos.rawQuery("SELECT * FROM clientes where clientes.nombre like '"+buscar+"' ORDER BY nombre", null);
while (csClientes.moveToNext()){
cliente = new Cliente(csClientes.getInt(0), csClientes.getString(1), csClientes.getString(2), csClientes.getString(3), csClientes.getString(4),
csClientes.getString(5), csClientes.getString(6), csClientes.getString(7), csClientes.getString(8), csClientes.getString(9), csClientes.getString(10),
csClientes.getString(11), csClientes.getString(12), csClientes.getString(13), csClientes.getString(14), csClientes.getString(15), csClientes.getString(16),
csClientes.getString(17));
list.add(cliente);
}
adapter=new ClientesAdaptador(getContext(), list);
lvClientes.setAdapter(adapter);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| [
"[email protected]"
]
| |
77a2b8c5b9035879be1a43fee23b8d321297a395 | cefd4b37e1c2d8cc2183ff203ba904e8f7d732ac | /src/test/java/com/mycompany/test/SelTestCase.java | 467685b5cc0c9cb01ed3674317a0f4555de6ed1f | []
| no_license | shwethap/my-app | c9c3b549658f57a8a47264fd24f00af9f0823986 | 05edbc25c7374a35944a511b6e131fc9738d0e79 | refs/heads/master | 2021-01-20T11:25:04.230267 | 2014-10-11T19:00:09 | 2014-10-11T19:00:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,643 | java | package com.mycompany.test;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.IReporter;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import com.gargoylesoftware.htmlunit.javascript.host.geo.Geolocation;
public class SelTestCase {
protected WebDriver driver;
@BeforeMethod
@Parameters({"Browser"})
public void openbrowser(char Browser)
{
switch(Browser)
{ case 'c': System.setProperty("webdriver.chrome.driver", "C:/selenium-2.43.0/drivers/chromedriver.exe");
driver=new ChromeDriver();
break;
case 'f' :driver=new FirefoxDriver();
}
}
public void openpage(String url)
{
driver.get(url);
}
@AfterMethod
public void closebrowser(ITestResult result) throws IOException
{
if(!result.isSuccess())
{
File imagefile= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String failureImageFileName=result.getMethod().getMethodName()+new SimpleDateFormat("MM-dd-yy_HH-ss")
.format(new GregorianCalendar().getTime()) +".png";
File failureimagefile= new File(failureImageFileName);
FileUtils.moveFile(imagefile, failureimagefile);
}
driver.close();
driver.quit();
}
}
| [
"[email protected]"
]
| |
37920e218b42f288fef1a489f8b9881687385c26 | d668ceae4e0811f821e4dcf1c970750d09e8e978 | /ir/LabelAllocator.java | 8e7f3d5b9b25e4cf8c6ea41bebf37784fa73dea9 | [
"MIT"
]
| permissive | julianrocha/csc435-compiler-construction | 3573f0c5ae5a4f0ac42bd359feb32a29b3124037 | 7213ae82d2119d2b61cc45254fec01080b05dcaa | refs/heads/main | 2023-07-02T10:42:28.960867 | 2021-08-04T22:31:23 | 2021-08-04T22:31:23 | 366,512,694 | 2 | 0 | MIT | 2021-08-04T22:31:24 | 2021-05-11T21:04:14 | Java | UTF-8 | Java | false | false | 321 | java | package ir;
import java.util.ArrayList;
import java.util.List;
public class LabelAllocator {
public List<Label> labels;
public int next;
public LabelAllocator() {
labels = new ArrayList<Label>();
next = 0;
}
public Label allocate() {
Label l = new Label(next);
labels.add(l);
next++;
return l;
}
}
| [
"[email protected]"
]
| |
902e8b6d669ea05c0decc87806884514beedab10 | cb6193d6fa01431ec4220d9114f38f90a6ec324f | /src/main/java/com/javaman/concurrency/book/detail/chapter4/Mutex.java | 86b07ec022df64db637bcf717bbefdf393c7f6b5 | []
| no_license | suansuan08/Learning-Concurrency | 686a6ffbd8c942e7388ce78d3e2d709459eed75e | 28245858a81e161949e7fb202c12c31abae7b6e6 | refs/heads/master | 2020-04-25T08:35:47.246804 | 2019-02-24T14:53:26 | 2019-02-24T14:53:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 853 | java | package com.javaman.concurrency.book.detail.chapter4;
import java.util.concurrent.TimeUnit;
/**
* @author pengzhe
* @date 2018-11-24 20:44
* @description
*/
public class Mutex {
private final static Object MUTEX = new Object();
public void access() {
synchronized (MUTEX) {
try {
TimeUnit.MINUTES.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
final Mutex mutex = new Mutex();
for (int i = 0; i < 5; i++) {
// new Thread(mutex::access).start();
new Thread(new Runnable() {
@Override
public void run() {
mutex.access();
}
}).start();
}
}
}
| [
"[email protected]"
]
| |
169c278c24eb1e06253a13b5ba83d62b5516244c | cea1b8f8ecdc7234c8a25b31c7041cafb0455478 | /src/actividadespropuestasColecciones/Alumno2.java | 4ec994c7fd720db8fd01874814638da12282125e | []
| no_license | IvanTS1991/DAW | 928e7e3cfe598cbf1917f243bae5d41972035b5a | 3ec71ddf707641cdc9c93b4b7bea37c9edb247db | refs/heads/master | 2020-08-29T18:03:49.952633 | 2020-05-10T20:43:08 | 2020-05-10T20:43:08 | 218,121,488 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,315 | java | package actividadespropuestasColecciones;
import java.util.Comparator;
public class Alumno2 extends Alumno implements Comparable, Comparator<Alumno2> {
private int id;
public Alumno2(String nombre, int nota, int id) {
super(nombre, nota);
this.id = id;
}
protected int getId() {
return id;
}
protected void setId(int id) {
this.id = id;
}
@Override
public int compare(Alumno2 o1, Alumno2 o2) {
return 0;
}
// ************* COMPARETO POR NOMBRE CRECIENTE *************
@Override
public int compareTo(Object o) {
Alumno2 al = (Alumno2) o;
return this.getNombre().compareTo(al.getNombre());
}
// ************* COMPARETO POR ORDEN NOMBRE DECRECIENTE *************
/*@Override
public int compareTo(Object o) {
Alumno2 al = (Alumno2) o;
return al.getNombre().compareTo(this.getNombre());
}*/
// ************* COMPARETO POR NOTA CRECIENTE *************
/*@Override
public int compareTo(Object o) {
Alumno2 al = (Alumno2) o;
return this.getNota()-al.getNota();
}*/
// ************* COMPARETO POR NOTA DECRECIENTE *************
/* @Override
public int compareTo(Object o) {
Alumno2 al = (Alumno2) o;
return al.getNota() - this.getNota();
}*/
}
| [
"[email protected]"
]
| |
a2492fbcb7350a530b8b724c7b2434e03094c279 | a0151d8e0a1b4c647671f04dd35be8a01220d94b | /app/src/androidTest/java/com/example/lenovo/l_storage/ExampleInstrumentedTest.java | 412d005e91af326c359ad33c07a6a9f2683dfc2c | []
| no_license | jccjd/L_Storage | 70c8304286e7d9587985aaaf695bd9e952ab5071 | e7955fb0f48802ad8eded0307e00f694f1dc0ad8 | refs/heads/master | 2021-09-03T03:46:16.084083 | 2018-01-05T09:17:13 | 2018-01-05T09:17:13 | 115,861,483 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 760 | java | package com.example.lenovo.l_storage;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.lenovo.l_storage", appContext.getPackageName());
}
}
| [
"[email protected]"
]
| |
e5c027a1c47032d7064cda3d1d12f7dbb535ff03 | f561fa7d3a2ccdf8398b68b0fbd53a5bf508a108 | /src/EX17.java | fb42e67b1e20db5d6d41be714502ff3e5522806a | [
"Apache-2.0"
]
| permissive | cs-fullstack-fall-2018/java-day2-homework-myiahm | 2548c6a309a4cb130186138414de1e95b2141f80 | 5f44ae81b9300672bb2e0c4ba9e4c17889cce8d6 | refs/heads/master | 2020-03-23T21:12:03.502865 | 2018-07-24T02:38:51 | 2018-07-24T02:38:51 | 142,088,958 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 372 | java | public class EX17 {
public static void main(String[] args) {
int printNumbers = 20;
print(printNumbers);
}
public static void print(int printNumber) {
System.out.println(printNumber);
int counter = -25;
while (counter < printNumber) {
System.out.println(counter);
counter++;
}
}
}
| [
"[email protected]"
]
| |
d494bcd8f30fdcd3bad3cc270076483672963af4 | 1d1a19f81b95083d412f9aa033ce4d6bc9c19cb5 | /MysticDropsLib/MythicDrops-master/src/main/java/com/tealcube/minecraft/bukkit/mythicdrops/commands/MythicDropsCommand.java | 5728995e01aa4d5213a12977c45129cc7ec6b717 | [
"MIT"
]
| permissive | Murit1997/MinecraftAlpha | ec97c425ac8add59885de9c5469baf4ae7a7b2ac | be07786801991a3ea852eecd276d997cb7386c1c | refs/heads/master | 2020-03-20T22:04:46.021050 | 2018-06-21T16:08:50 | 2018-06-21T16:08:50 | 137,777,989 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 35,229 | java | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2013 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.commands;
import com.tealcube.minecraft.bukkit.mythicdrops.MythicDropsPlugin;
import com.tealcube.minecraft.bukkit.mythicdrops.api.MythicDrops;
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.CustomItem;
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.ItemGenerationReason;
import com.tealcube.minecraft.bukkit.mythicdrops.api.tiers.Tier;
import com.tealcube.minecraft.bukkit.mythicdrops.identification.IdentityTome;
import com.tealcube.minecraft.bukkit.mythicdrops.identification.UnidentifiedItem;
import com.tealcube.minecraft.bukkit.mythicdrops.items.CustomItemBuilder;
import com.tealcube.minecraft.bukkit.mythicdrops.items.CustomItemMap;
import com.tealcube.minecraft.bukkit.mythicdrops.logging.MythicLoggerFactory;
import com.tealcube.minecraft.bukkit.mythicdrops.socketting.SocketGem;
import com.tealcube.minecraft.bukkit.mythicdrops.socketting.SocketItem;
import com.tealcube.minecraft.bukkit.mythicdrops.tiers.TierMap;
import com.tealcube.minecraft.bukkit.mythicdrops.utils.EntityUtil;
import com.tealcube.minecraft.bukkit.mythicdrops.utils.GsonUtil;
import com.tealcube.minecraft.bukkit.mythicdrops.utils.ItemStackUtil;
import com.tealcube.minecraft.bukkit.mythicdrops.utils.ItemUtil;
import com.tealcube.minecraft.bukkit.mythicdrops.utils.SocketGemUtil;
import com.tealcube.minecraft.bukkit.mythicdrops.utils.StringListUtil;
import com.tealcube.minecraft.bukkit.mythicdrops.utils.TierUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import se.ranzdo.bukkit.methodcommand.Arg;
import se.ranzdo.bukkit.methodcommand.Command;
import se.ranzdo.bukkit.methodcommand.FlagArg;
import se.ranzdo.bukkit.methodcommand.Flags;
import se.ranzdo.bukkit.methodcommand.Wildcard;
public final class MythicDropsCommand {
private static final Logger LOGGER = MythicLoggerFactory.getLogger(MythicDropsCommand.class);
private MythicDrops plugin;
public MythicDropsCommand(MythicDropsPlugin plugin) {
this.plugin = plugin;
}
@Command(identifier = "mythicdrops debug", description = "Prints a bunch of debug messages",
permissions = "mythicdrops.command.debug")
public void debugCommand(CommandSender sender) {
LOGGER.info("server package: " + Bukkit.getServer().getClass().getPackage().toString());
LOGGER.info("number of tiers: " + TierMap.getInstance().size());
LOGGER.info("number of custom items: " + CustomItemMap.getInstance().size());
LOGGER.info("config settings: " + GsonUtil.toJson(this.plugin.getConfigSettings()));
LOGGER.info("creature spawning settings: " + GsonUtil.toJson(this.plugin.getCreatureSpawningSettings()));
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.debug"));
}
@Command(identifier = "mythicdrops reload", description = "Reloads the configuration files",
permissions = "mythicdrops.command.reload")
public void reloadCommand(CommandSender sender) {
LOGGER.info("Reloading the configuration files");
plugin.reloadConfigurationFiles();
// Lord help us all
plugin.reloadTiers();
plugin.reloadNames();
plugin.reloadCustomItems();
plugin.reloadRepairCosts();
plugin.reloadSettings();
LOGGER.info("Done reloading the configuration files");
sender.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.reload"));
}
@Command(identifier = "mythicdrops spawn", description = "Spawns in MythicDrops items",
permissions = "mythicdrops.command.spawn")
@Flags(identifier = {"a", "t", "mind", "maxd"}, description = {"Amount to spawn", "Tier to spawn",
"Minimum durability",
"Maximum durability"})
public void spawnSubcommand(CommandSender sender, @Arg(name = "amount", def = "1")
@FlagArg("a") int amount, @Arg(name = "tier", def = "*") @FlagArg("t") String tierName,
@Arg(name = "mindurability", def = "1.0",
verifiers = "min[0.0]|max[1.0]") @FlagArg
("mind") double minDura,
@Arg(name = "maxdurability", def = "1.0",
verifiers = "min[0.0]|max[1.0]") @FlagArg
("maxd") double maxDura) {
if (!(sender instanceof Player)) {
sender.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.only-players"));
return;
}
Player player = (Player) sender;
if (tierName.equalsIgnoreCase("*") && !player.hasPermission("mythicdrops.command.spawn.wildcard")) {
player.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
if (TierMap.getInstance().size() <= 0) {
sender.sendMessage(plugin.getConfigSettings().getFormattedLanguageString(
"command.spawn-random-failure", new String[][]{
{"%amount%", String.valueOf(amount)}
})
);
return;
}
Tier tier = TierUtil.getTier(tierName);
if (!player.hasPermission("mythicdrops.command.spawn.wildcard")) {
if (tier == null) {
player.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.tier-does-not-exist"));
return;
} else if (!player.hasPermission("mythicdrops.command.spawn." + tier.getName())) {
player.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
}
int amountGiven = 0;
while (amountGiven < amount) {
ItemStack mis = MythicDropsPlugin.getNewDropBuilder().useDurability(false)
.withItemGenerationReason(ItemGenerationReason.COMMAND).withTier(tier)
.build();
if (mis != null) {
mis.setDurability(ItemStackUtil.getDurabilityForMaterial(mis.getType(), minDura, maxDura));
player.getInventory().addItem(mis);
amountGiven++;
}
}
player.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.spawn-random",
new String[][]{
{"%amount%", String
.valueOf(
amountGiven)}}
));
}
@Command(identifier = "mythicdrops drop", description = "Drops in MythicDrops items",
permissions = "mythicdrops.command.drop")
@Flags(identifier = {"a", "t", "w", "mind", "maxd"},
description = {"Amount to drop", "Tier to drop", "World",
"Minimum durability", "Maximum durability"})
public void dropSubcommand(CommandSender sender, @Arg(name = "amount", def = "1")
@FlagArg("a") int amount, @Arg(name = "tier", def = "*") @FlagArg("t") String tierName,
@Arg(name = "world", def = "") @FlagArg("w") String worldName,
@Arg(name = "x") double x, @Arg(name = "y") double y,
@Arg(name = "z") double z,
@Arg(name = "mindurability", def = "1.0",
verifiers = "min[0.0]|max[1.0]") @FlagArg
("mind") double minDura,
@Arg(name = "maxdurability", def = "1.0",
verifiers = "min[0.0]|max[1.0]") @FlagArg
("maxd") double maxDura) {
if (!(sender instanceof Player) && "".equals(worldName)) {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.only-players"));
return;
}
if (tierName.equalsIgnoreCase("*") && !sender
.hasPermission("mythicdrops.command.spawn.wildcard")) {
sender
.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
String worldN = sender instanceof Player ? ((Player) sender).getWorld().getName() : worldName;
if (TierMap.getInstance().size() <= 0) {
sender.sendMessage(plugin.getConfigSettings().getFormattedLanguageString(
"command.drop-random-failure", new String[][]{
{"%amount%", String.valueOf(amount)}
})
);
return;
}
Tier tier = TierUtil.getTier(tierName);
if (!sender.hasPermission("mythicdrops.command.spawn.wildcard")) {
if (tier == null) {
sender.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command" +
".tier-does-not-exist"));
return;
} else if (!sender.hasPermission("mythicdrops.command.spawn." + tier.getName())) {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
}
World w = Bukkit.getWorld(worldN);
if (w == null) {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.world-does-not-exist"));
return;
}
Location l = new Location(w, x, y, z);
Entity e = EntityUtil.getEntityAtLocation(l);
int amountGiven = 0;
while (amountGiven < amount) {
ItemStack mis = MythicDropsPlugin.getNewDropBuilder().useDurability(false)
.withItemGenerationReason(ItemGenerationReason.COMMAND).withTier(tier)
.build();
if (mis != null) {
mis.setDurability(ItemStackUtil.getDurabilityForMaterial(mis.getType(), minDura, maxDura));
if (e instanceof InventoryHolder) {
((InventoryHolder) e).getInventory().addItem(mis);
} else if (l.getBlock().getState() instanceof InventoryHolder) {
((InventoryHolder) l.getBlock().getState()).getInventory().addItem(mis);
} else {
w.dropItem(l, mis);
}
amountGiven++;
}
}
sender.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.drop-random",
new String[][]{
{"%amount%", String
.valueOf(
amountGiven)}}
));
}
@Command(identifier = "mythicdrops give", description = "Gives MythicDrops items",
permissions = "mythicdrops.command.give")
@Flags(identifier = {"a", "t", "mind", "maxd"}, description = {"Amount to spawn", "Tier to spawn",
"Minimum durability",
"Maximum durability"})
public void giveSubcommand(CommandSender sender, @Arg(name = "player") Player player,
@Arg(name = "amount",
def = "1")
@FlagArg("a") int amount,
@Arg(name = "tier", def = "*") @FlagArg("t") String tierName,
@Arg(name = "mindurability", def = "1.0",
verifiers = "min[0.0]|max[1.0]") @FlagArg
("mind") double minDura,
@Arg(name = "maxdurability", def = "1.0",
verifiers = "min[0.0]|max[1.0]") @FlagArg
("maxd") double maxDura) {
if (tierName.equalsIgnoreCase("*") && !sender
.hasPermission("mythicdrops.command.give.wildcard")) {
sender
.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
if (TierMap.getInstance().size() <= 0) {
sender.sendMessage(plugin.getConfigSettings().getFormattedLanguageString(
"command.give-random-sender-failure", new String[][]{
{"%amount%", String.valueOf(amount)},
{"%receiver%", player.getName()}
})
);
return;
}
Tier tier = TierUtil.getTier(tierName);
if (!sender.hasPermission("mythicdrops.command.give.wildcard")) {
if (tier == null) {
sender.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command" +
".tier-does-not-exist"));
return;
} else if (!sender.hasPermission("mythicdrops.command.give." + tier.getName())) {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
}
int amountGiven = 0;
while (amountGiven < amount) {
ItemStack mis = MythicDropsPlugin.getNewDropBuilder().useDurability(true)
.withItemGenerationReason(ItemGenerationReason.COMMAND).withTier(tier)
.build();
if (mis != null) {
mis.setDurability(ItemStackUtil.getDurabilityForMaterial(mis.getType(), minDura, maxDura));
player.getInventory().addItem(mis);
amountGiven++;
}
}
player.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.give-random-receiver",
new String[][]{{"%amount%", String
.valueOf(amountGiven)}}
)
);
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.give-random-sender",
new String[][]{{"%amount%", String
.valueOf(amountGiven)},
{"%receiver%",
player.getName()}}
)
);
}
@Command(identifier = "mythicdrops customcreate",
description = "Creates a custom item from the item in the " +
"user's hand", permissions = "mythicdrops.command.customcreate")
public void customCreateSubcommand(CommandSender sender,
@Arg(name = "chance to spawn") double chanceToSpawn,
@Arg(name = "chance to drop") double chanceToDrop) {
if (!(sender instanceof Player)) {
sender
.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
Player p = (Player) sender;
ItemStack itemInHand = p.getEquipment().getItemInMainHand();
if (!itemInHand.hasItemMeta()) {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.customcreate-failure"));
return;
}
ItemMeta im = itemInHand.getItemMeta();
if (!im.hasDisplayName() || !im.hasLore()) {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.customcreate-failure"));
return;
}
String displayName;
String name;
if (im.hasDisplayName()) {
displayName = im.getDisplayName().replace('\u00A7', '&');
name = ChatColor.stripColor(im.getDisplayName()).replaceAll("\\s+", "");
} else {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.customcreate-failure"));
return;
}
List<String> itemLore = new ArrayList<>();
if (im.hasLore()) {
itemLore = im.getLore();
}
List<String> lore = new ArrayList<>();
for (String s : itemLore) {
lore.add(s.replace('\u00A7', '&'));
}
Map<Enchantment, Integer> enchantments = new HashMap<>();
if (im.hasEnchants()) {
enchantments = im.getEnchants();
}
CustomItem ci = new CustomItemBuilder(name)
.withDisplayName(displayName)
.withLore(lore)
.withEnchantments(enchantments)
.withMaterial(itemInHand.getType())
.withChanceToBeGivenToMonster(chanceToSpawn)
.withChanceToDropOnDeath(chanceToDrop)
.withDurability(itemInHand.getDurability())
.build();
CustomItemMap.getInstance().put(name, ci);
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.customcreate-success",
new String[][]{{"%name%", name}})
);
plugin.getCustomItemYAML().set(name + ".displayName", ci.getDisplayName());
plugin.getCustomItemYAML().set(name + ".lore", ci.getLore());
plugin.getCustomItemYAML()
.set(name + ".spawnOnMonsterWeight", ci.getChanceToBeGivenToAMonster());
plugin.getCustomItemYAML()
.set(name + ".chanceToDropOnMonsterDeath", ci.getChanceToDropOnDeath());
plugin.getCustomItemYAML().set(name + ".materialName", ci.getMaterial().name());
for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) {
plugin.getCustomItemYAML()
.set(name + ".enchantments." + entry.getKey().getName(), entry.getValue());
}
plugin.getCustomItemYAML().save();
}
@Command(identifier = "mythicdrops custom", description = "Gives custom MythicDrops items",
permissions = "mythicdrops.command.custom")
@Flags(identifier = {"a", "c", "mind", "maxd"},
description = {"Amount to spawn", "Custom Item to spawn",
"Minimum durability", "Maximum durability"})
public void customSubcommand(CommandSender sender,
@Arg(name = "player", def = "self") String playerName,
@Arg(name = "amount", def = "1")
@FlagArg("a") int amount,
@Arg(name = "item", def = "*") @FlagArg("c") String itemName,
@Arg(name = "mindurability", def = "1.0",
verifiers = "min[0.0]|max[1.0]") @FlagArg
("mind") double minDura,
@Arg(name = "maxdurability", def = "1.0",
verifiers = "min[0.0]|max[1.0]") @FlagArg
("maxd") double maxDura) {
Player player;
if (playerName.equalsIgnoreCase("self")) {
if (sender instanceof Player) {
player = (Player) sender;
} else {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
} else {
player = Bukkit.getPlayer(playerName);
}
if (player == null) {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.player-does-not-exist"));
return;
}
CustomItem customItem = null;
if (!itemName.equalsIgnoreCase("*")) {
try {
customItem = CustomItemMap.getInstance().get(itemName);
} catch (NullPointerException e) {
sender.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command" +
".custom-item-does-not-exist"));
return;
}
}
int amountGiven = 0;
for (int i = 0; i < amount; i++) {
try {
ItemStack itemStack;
if (customItem == null) {
itemStack = CustomItemMap.getInstance().getRandomWithChance().toItemStack();
} else {
itemStack = customItem.toItemStack();
}
if (itemStack == null) {
continue;
}
itemStack.setDurability(ItemStackUtil.getDurabilityForMaterial(itemStack.getType(), minDura,
maxDura));
player.getInventory().addItem(itemStack);
amountGiven++;
} catch (Exception ignored) {
ignored.printStackTrace();
}
}
player.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.give-custom-receiver",
new String[][]{{"%amount%", String
.valueOf(amountGiven)}}
)
);
if (!player.equals(sender)) {
sender.sendMessage(plugin.getConfigSettings()
.getFormattedLanguageString("command.give-custom-sender",
new String[][]{{"%amount%",
String
.valueOf(amountGiven)},
{"%receiver%",
player.getName()}}
));
}
}
@Command(identifier = "mythicdrops gem", description = "Gives MythicDrops gems",
permissions = "mythicdrops.command.gem")
@Flags(identifier = {"a", "g"}, description = {"Amount to spawn", "Socket Gem to spawn"})
public void gemSubcommand(CommandSender sender,
@Arg(name = "player", def = "self") String playerName,
@Arg(name = "amount", def = "1")
@FlagArg("a") int amount,
@Arg(name = "item", def = "*") @FlagArg("g") String
itemName) {
Player player;
if (playerName.equalsIgnoreCase("self")) {
if (sender instanceof Player) {
player = (Player) sender;
} else {
sender
.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.no-access",
new String[][]{}));
return;
}
} else {
player = Bukkit.getPlayer(playerName);
}
if (player == null) {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.player-does-not-exist",
new String[][]{})
);
return;
}
SocketGem socketGem = null;
if (!itemName.equalsIgnoreCase("*")) {
try {
socketGem = SocketGemUtil.getSocketGemFromName(itemName);
} catch (NullPointerException e) {
sender.sendMessage(plugin.getConfigSettings()
.getFormattedLanguageString("command.socket-gem-does-not-exist",
new String[][]{}));
return;
}
}
int amountGiven = 0;
for (int i = 0; i < amount; i++) {
try {
ItemStack itemStack;
if (socketGem == null) {
Material material = SocketGemUtil.getRandomSocketGemMaterial();
itemStack = new SocketItem(material, SocketGemUtil.getRandomSocketGemWithChance());
} else {
itemStack = new SocketItem(SocketGemUtil.getRandomSocketGemMaterial(), socketGem);
}
itemStack.setDurability((short) 0);
player.getInventory().addItem(itemStack);
amountGiven++;
} catch (Exception ignored) {
ignored.printStackTrace();
}
}
player.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.give-gem-receiver",
new String[][]{{"%amount%", String
.valueOf(amountGiven)}}
)
);
if (!sender.equals(player)) {
sender.sendMessage(plugin.getConfigSettings()
.getFormattedLanguageString("command.give-gem-sender",
new String[][]{{"%amount%",
String
.valueOf(amountGiven)},
{"%receiver%",
player.getName()}}
));
}
}
@Command(identifier = "mythicdrops unidentified", description = "Gives Unidentified Item",
permissions = "mythicdrops.command.unidentified")
@Flags(identifier = {"a"}, description = {"Amount to spawn"})
public void unidentifiedSubcommand(CommandSender sender,
@Arg(name = "player", def = "self") String playerName,
@Arg(name = "amount", def = "1") @FlagArg("a") int amount) {
Player player;
if (playerName.equalsIgnoreCase("self")) {
if (sender instanceof Player) {
player = (Player) sender;
} else {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
} else {
player = Bukkit.getPlayer(playerName);
}
if (player == null) {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.player-does-not-exist"));
return;
}
int amountGiven = 0;
for (int i = 0; i < amount; i++) {
Tier t = TierMap.getInstance().getRandomWithChance();
if (t == null) {
continue;
}
Collection<Material> materials = ItemUtil.getMaterialsFromTier(t);
Material material = ItemUtil.getRandomMaterialFromCollection(materials);
player.getInventory().addItem(new UnidentifiedItem(material));
amountGiven++;
}
player.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.give-unidentified-receiver",
new String[][]{{"%amount%", String
.valueOf(amountGiven)}}
)
);
if (!player.equals(sender)) {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.give-unidentified-sender",
new String[][]{{"%amount%", String
.valueOf(amountGiven)},
{"%receiver%", player
.getName()}}
)
);
}
}
@Command(identifier = "mythicdrops tome", description = "Gives Identity Tome",
permissions = "mythicdrops.command.tome")
@Flags(identifier = {"a"}, description = {"Amount to spawn"})
public void tomeSubcommand(CommandSender sender,
@Arg(name = "player", def = "self") String playerName,
@Arg(name = "amount", def = "1") @FlagArg("a") int amount) {
Player player;
if (playerName.equalsIgnoreCase("self")) {
if (sender instanceof Player) {
player = (Player) sender;
} else {
sender.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
} else {
player = Bukkit.getPlayer(playerName);
}
if (player == null) {
sender.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command" +
".player-does-not-exist"));
return;
}
int amountGiven = 0;
for (int i = 0; i < amount; i++) {
player.getInventory().addItem(new IdentityTome());
amountGiven++;
}
player.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command" +
".give-tome-receiver",
new String[][]{
{"%amount%", String
.valueOf(
amountGiven)}}
));
if (player != sender) {
sender.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command" +
".give-tome-sender",
new String[][]{
{"%amount%",
String.valueOf(
amountGiven)},
{"%receiver%",
player
.getName()}}
));
}
}
@Command(identifier = "mythicdrops tiers", description = "Lists all Tiers",
permissions = "mythicdrops.command.tiers")
public void tiersCommand(CommandSender sender) {
List<String> loadedTierNames = new ArrayList<>();
for (Tier t : TierMap.getInstance().values()) {
loadedTierNames.add(t.getName());
}
sender.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.tier-list",
new String[][]{
{"%tiers%",
loadedTierNames
.toString()
.replace("[",
"")
.replace("]",
"")}}
));
}
@Command(identifier = "mythicdrops modify name", description = "Adds a name to the item in hand",
permissions = "mythicdrops.command.modify.name")
public void modifyNameCommand(CommandSender sender,
@Wildcard @Arg(name = "item name") String name) {
if (!(sender instanceof Player)) {
sender
.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
Player p = (Player) sender;
ItemStack itemInHand = p.getEquipment().getItemInMainHand();
if (itemInHand.getType() == Material.AIR) {
p.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.cannot-modify"));
return;
}
String newName = name.replace('&', '\u00A7').replace("\u00A7\u00A7", "&");
ItemMeta
im =
itemInHand.hasItemMeta() ? itemInHand.getItemMeta() : Bukkit.getItemFactory().getItemMeta
(itemInHand.getType());
im.setDisplayName(newName);
itemInHand.setItemMeta(im);
p.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.modify-name"));
}
@Command(identifier = "mythicdrops modify lore add",
description = "Adds a line of lore to the item in hand",
permissions = "mythicdrops.command.modify.lore")
public void modifyLoreAddCommand(CommandSender sender,
@Wildcard @Arg(name = "lore line") String line) {
if (!(sender instanceof Player)) {
sender
.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
Player p = (Player) sender;
ItemStack itemInHand = p.getEquipment().getItemInMainHand();
if (itemInHand.getType() == Material.AIR) {
p.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.cannot-modify"));
return;
}
String newLine = line.replace('&', '\u00A7').replace("\u00A7\u00A7", "&");
ItemMeta
im =
itemInHand.hasItemMeta() ? itemInHand.getItemMeta() : Bukkit.getItemFactory().getItemMeta
(itemInHand.getType());
List<String> lore = im.hasLore() ? im.getLore() : new ArrayList<String>();
lore.add(newLine);
im.setLore(lore);
itemInHand.setItemMeta(im);
p.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.add-lore"));
}
@Command(identifier = "mythicdrops modify lore remove",
description = "Removes a line of lore to the item in hand",
permissions = "mythicdrops.command.modify.lore")
public void modifyLoreAddCommand(CommandSender sender,
@Arg(name = "line to remove") int lineNumber) {
if (!(sender instanceof Player)) {
sender
.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
Player p = (Player) sender;
ItemStack itemInHand = p.getEquipment().getItemInMainHand();
if (itemInHand.getType() == Material.AIR) {
p.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.cannot-modify"));
return;
}
ItemMeta
im =
itemInHand.hasItemMeta() ? itemInHand.getItemMeta() : Bukkit.getItemFactory().getItemMeta
(itemInHand.getType());
List<String> lore = im.hasLore() ? im.getLore() : new ArrayList<String>();
lore.remove(Math.max(Math.min(lineNumber - 1, lore.size()), 0));
im.setLore(lore);
itemInHand.setItemMeta(im);
p.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.remove-lore"));
}
@Command(identifier = "mythicdrops modify lore insert",
description = "Adds a line of lore to the item in hand",
permissions = "mythicdrops.command.modify.lore")
public void modifyLoreAddCommand(CommandSender sender, @Arg(name = "index") int index,
@Wildcard @Arg(name = "lore line") String line) {
if (!(sender instanceof Player)) {
sender
.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
Player p = (Player) sender;
ItemStack itemInHand = p.getEquipment().getItemInMainHand();
if (itemInHand.getType() == Material.AIR) {
p.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.cannot-modify"));
return;
}
String newLine = line.replace('&', '\u00A7').replace("\u00A7\u00A7", "&");
ItemMeta
im =
itemInHand.hasItemMeta() ? itemInHand.getItemMeta() : Bukkit.getItemFactory().getItemMeta
(itemInHand.getType());
List<String> lore = im.hasLore() ? im.getLore() : new ArrayList<String>();
lore = StringListUtil.addString(lore, index, newLine, false);
im.setLore(lore);
itemInHand.setItemMeta(im);
p.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.insert-lore"));
}
@Command(identifier = "mythicdrops modify lore modify",
description = "Modifies a line of lore to the item in " +
"hand", permissions = "mythicdrops.command.modify.lore")
public void modifyLoreModifyCommand(CommandSender sender, @Arg(name = "index") int index,
@Wildcard @Arg(name = "lore line") String line) {
if (!(sender instanceof Player)) {
sender
.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
Player p = (Player) sender;
ItemStack itemInHand = p.getEquipment().getItemInMainHand();
if (itemInHand.getType() == Material.AIR) {
p.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.cannot-modify"));
return;
}
String newLine = line.replace('&', '\u00A7').replace("\u00A7\u00A7", "&");
ItemMeta
im =
itemInHand.hasItemMeta() ? itemInHand.getItemMeta() : Bukkit.getItemFactory().getItemMeta
(itemInHand.getType());
List<String> lore = im.hasLore() ? im.getLore() : new ArrayList<String>();
if (lore.size() >= index) {
lore.remove(index);
}
lore = StringListUtil.addString(lore, index, newLine, false);
im.setLore(lore);
itemInHand.setItemMeta(im);
p.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.insert-lore"));
}
@Command(identifier = "mythicdrops modify enchantment add",
description = "Adds an enchantment to the item in " +
"hand", permissions = "mythicdrops.command.modify.enchantments")
public void modifyEnchantmentAddCommand(CommandSender sender,
@Arg(name = "enchantment") Enchantment enchantment,
@Arg(name = "level", def = "1") int level) {
if (!(sender instanceof Player)) {
sender
.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
Player p = (Player) sender;
ItemStack itemInHand = p.getEquipment().getItemInMainHand();
if (itemInHand.getType() == Material.AIR) {
p.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.cannot-modify"));
return;
}
itemInHand.addUnsafeEnchantment(enchantment, level);
p.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.add-enchantment"));
}
@Command(identifier = "mythicdrops modify enchantment remove",
description = "Adds an enchantment to the item in " +
"hand", permissions = "mythicdrops.command.modify.enchantments")
public void modifyEnchantmentRemoveCommand(CommandSender sender,
@Arg(name = "enchantment") Enchantment
enchantment) {
if (!(sender instanceof Player)) {
sender
.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.no-access"));
return;
}
Player p = (Player) sender;
ItemStack itemInHand = p.getEquipment().getItemInMainHand();
if (itemInHand.getType() == Material.AIR) {
p.sendMessage(plugin.getConfigSettings().getFormattedLanguageString("command.cannot-modify"));
return;
}
itemInHand.removeEnchantment(enchantment);
p.sendMessage(
plugin.getConfigSettings().getFormattedLanguageString("command.remove-enchantment"));
}
}
| [
"[email protected]"
]
| |
36ed316bf4fa76fb166e23403f2ac3838e78dca2 | 8abf8a769ee20b34b03f5de2e62b5ca9697050d1 | /app/src/main/res/layout-sw600dp/utils/ShowToast.java | 7196c55902e084a746b98633492a33622c765c4c | []
| no_license | guddu2710/QRBarcodeScanner-master | 62c25ce4866f399052c5ee6927fbd5a9eb6e9d04 | c6624fc76f2a1dc6621bd2a22b210528ec158fb6 | refs/heads/master | 2020-12-13T18:09:54.542659 | 2020-01-17T07:00:08 | 2020-01-17T07:00:08 | 234,490,442 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 258 | java | package com.pitangent.project.utils;
import android.content.Context;
import android.widget.Toast;
public class ShowToast {
public void showToast(Context context, String msg){
Toast.makeText(context, ""+msg, Toast.LENGTH_LONG).show();
}
}
| [
"[email protected]"
]
| |
c50277357a952f7111f5cba8f832a50f10e6cb00 | 4826abe00106efda0008d3d0fb0078472627fd86 | /src/main/java/hw20180102/Banana.java | 31d3ef8277ca89eaa3d0250cd8d481cd120f3d6c | []
| no_license | Dajingya/Dajingya_homeworks | 26952f2ae4c04069106eca7b09865af90d29fa6c | e47c054e1ecfd47f3affc127b37dd2da0d9b2700 | refs/heads/master | 2021-09-03T10:15:37.900553 | 2018-01-08T09:57:05 | 2018-01-08T09:57:05 | 114,863,127 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 608 | java | /**
* Project Name:dt59homework
* File Name:Banana.java
* Package Name:hw20180101
* Date:2018ๅนด1ๆ2ๆฅไธๅ2:03:56
* Copyright (c) 2018, bluemobi All Rights Reserved.
*
*/
package hw20180102;
/**
* Description: <br/>
* Date: 2018ๅนด1ๆ2ๆฅ ไธๅ2:03:56 <br/>
*
* @author wangJing
* @version
* @see
*/
public class Banana extends Fruit {
public Banana(String name, String taste) {
super(name, taste);
}
@Override
public void eatway(String zuofa) {
this.eatway("ๅ้ฃ้ฅผ");// ่ฟๆฏ็ฌฌไบ้ข--ๅฝขๅๅคๆ
};
}
| [
"wangJing@WangJing-PC"
]
| wangJing@WangJing-PC |
1381a0783833546b125015632ea420c2ccaed473 | 7007bac0d125e647f6d663ad075f217774dd2911 | /src/main/java/BoardGame/BoardException.java | e03c7f9ae7764317b5bf773e08fa58010dad6372 | []
| no_license | Liima-M/Jogo-Xadrez | b8fc0955b7ac6ce91aeb513560f303b8b143474a | 8ef152b0829d3eded54dcb9ae2d34b474102376d | refs/heads/master | 2023-07-12T12:14:02.702077 | 2021-08-16T21:24:35 | 2021-08-16T21:24:35 | 395,450,141 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 151 | java | package BoardGame;
public class BoardException extends RuntimeException{
public BoardException(String msg){
super(msg);
}
}
| [
"[email protected]"
]
| |
71157aeb8fb22d24663be6d8b0c6f3b18f72fbbd | 1e5e3ef9672d8689d22b936d2ca561afade5c731 | /src/frc/team871/tools/ILimitSwitch.java | d13b9baaf0a44b3160aba33844125d96af35f5bd | []
| no_license | t3pfaffe/Robot-Test | 7a2e6260a498e8b307cc44d3315e03584095a787 | b7dfae1af7bb44c84593fadd6ad7c1b7d3594ebe | refs/heads/master | 2021-09-06T05:50:18.768403 | 2018-01-28T03:38:50 | 2018-01-28T03:38:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 106 | java | package org.usfirst.frc.team871.tools;
public interface ILimitSwitch {
public boolean isAtLimit();
}
| [
"[email protected]"
]
| |
a1eb9995a203a4e417972abe13e27d6c87e8dcf8 | fa9f8679708cf9b30f31a5746e8c7e37421815ea | /src/main/java/com/user/notesapi/controller/CollaboratorController.java | ff6a64389a8a64efbe7911fccdf45bfe362bc757 | []
| no_license | himansh-23/noteservices | bf5f33b06a9f99ad285b8ede8390c9d236b6ea44 | 5dcc3bac7f2bf6d144fa70d847ab9981567acb8b | refs/heads/master | 2020-04-18T13:10:31.347458 | 2019-04-16T11:01:43 | 2019-04-16T11:01:43 | 167,555,908 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,470 | java | package com.user.notesapi.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.user.notesapi.exception.NoteException;
import com.user.notesapi.response.Response;
import com.user.notesapi.services.CollaboratorService;
@RestController
@RequestMapping("/api/collab")
@CrossOrigin(origins="http://localhost:4200",exposedHeaders= {"token"})
public class CollaboratorController {
@Autowired
private CollaboratorService collabservice;
@PostMapping
public ResponseEntity<Response> addCollabrator(@RequestHeader("token") String token,
@RequestParam long sharedUserId ,@RequestParam long sharedNoteId) throws NoteException
{
System.out.println(sharedNoteId+" "+sharedUserId);
long res=collabservice.addPersonToNote(token, sharedNoteId, sharedUserId);
Response response=new Response();
if(res==-1L)
{
response.setStatusCode(166);
response.setStatusMessage("Person Already Exists");
}
else
{
response.setStatusCode(200);
response.setStatusMessage("Shared Note added");
}
return new ResponseEntity<Response>(response,HttpStatus.OK);
}
/* @GetMapping
public ResponseEntity<List<Notes>> getCollaborateNotes(@RequestHeader("token")String token) throws NoteException
{
List<Notes> list=collabservice.getCollabNotes(token);
return new ResponseEntity<List<Notes>>(list,HttpStatus.OK);
}*/
@DeleteMapping
public ResponseEntity<Response> deleteCollabNote(@RequestHeader("token") String token,@RequestParam String noteId,@RequestParam String email) throws NoteException
{
System.out.println(noteId+" "+email);
boolean delete=collabservice.deleteCollabNote(token, Long.valueOf(noteId), email);
Response response=new Response();
response.setStatusCode(166);
response.setStatusMessage("You Can't remove");
if(delete==true)
{
response.setStatusMessage("Collaboration Removed");
}
return new ResponseEntity<Response>(response,HttpStatus.OK);
}
}
| [
"[email protected]"
]
| |
a3a3f5244180c8c0873ee89795df519f49130262 | 8f37e5a1d266c15deaf9ef071a1fab1fdef9fc85 | /GestionReservation/src/main/java/projet/controller/IndexController.java | 7e147f774bd5356cfef3c4f089e992ffd44c0d21 | []
| no_license | ameniRaddaoui/Docteur | a9afd4b8c39d25de3a05f13eff695d3a575f2528 | cbb40e9e05d1cdbda794818d1936b74b37213b4a | refs/heads/master | 2020-03-09T07:05:09.376367 | 2018-04-08T19:54:48 | 2018-04-08T19:54:48 | 128,656,484 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,179 | java | package projet.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import projet.entities.Personne;
import projet.repositories.personneRepositorie;
@Controller
@RequestMapping("/")
public class IndexController {
@Autowired
private personneRepositorie personneRepositorie;
@Autowired
@RequestMapping(value = "login")
public String login() {
return "login";
}
@RequestMapping(value = "index")
public String index(Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String login = auth.getName();
Personne p = personneRepositorie.getPersonneByLogin(login);
if (p.getRole().equals("ROLE_ADMIN")) {
return "redirect:/admin/personne/list";
} else {
return "redirect:/403";
}
}
@RequestMapping(value = "403")
public String NotAutho() {
return "403";
}
}
| [
"[email protected]"
]
| |
df3e925318af9f36aa8ee7336c0144dc78995a78 | 96db1df61b2ea81c5ca0b288ea86b9b5ff21bcb2 | /app/src/main/java/com/thecoffeecoders/chatex/EmailVerificationActivity.java | 90cf08004aa8be0ef17dae8c0c3dd82bb52c8ff5 | []
| no_license | theoctober19th/ChaTeX-v1.0 | bbd585aa90f6ebb9d59239a582297eb0c154f067 | c7dd28142b51612f758fc0e353bc47ec8a94ac98 | refs/heads/master | 2022-10-24T05:38:32.497982 | 2020-06-10T08:10:22 | 2020-06-10T08:10:22 | 164,103,139 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,803 | java | package com.thecoffeecoders.chatex;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import org.w3c.dom.Text;
public class EmailVerificationActivity extends AppCompatActivity {
FirebaseUser mCurrentUser;
FirebaseAuth mAuth;
Button loginButton;
Button resendVerificationButton;
TextView verificationMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_verification);
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
loginButton = (Button) findViewById(R.id.verification_button);
verificationMessage = (TextView) findViewById(R.id.verification_message);
resendVerificationButton = (Button) findViewById(R.id.resend_verfication_btn);
resendVerificationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentUser.sendEmailVerification();
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent loginIntent = new Intent(EmailVerificationActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
});
}
}
| [
"[email protected]"
]
| |
a719e40047b748f327239452d2c4adb35fcc31ac | 2e9cba81bb667d473fc24e42abb58c8349083517 | /card/card-game/src/main/java/com/fatiny/game/game/config/pojo/ConfigContestSale.java | ffe3ad6be4e5909cb75a582d6b58dc742a1dffbd | []
| no_license | f361600134/card | eb7f094e02227efdfc87fba39a35e4abf9df76eb | 803143a7eb0d7ab1a6581ee6583b0d6251020bc2 | refs/heads/master | 2022-12-09T07:35:31.465560 | 2019-08-11T08:49:52 | 2019-08-11T08:49:52 | 199,358,192 | 0 | 0 | null | 2022-12-06T00:43:41 | 2019-07-29T01:42:42 | Java | UTF-8 | Java | false | false | 645 | java | package com.fatiny.game.game.config.pojo;
public class ConfigContestSale {
private int ID;//่ดญไนฐๆฌกๆฐ
private int diamondConsume;//ๆถ่ๅ
ๅฎ
public int getID(){
return ID;
}
public void setID(int ID){
this.ID = ID;
}
public int getDiamondConsume(){
return diamondConsume;
}
public void setDiamondConsume(int diamondConsume){
this.diamondConsume = diamondConsume;
}
////////////////////// ็นๆฎๆฉๅฑ //////////////
public void parse(){
}
/////////UserDefine Begin///////////
/////////UserDefine End/////////////
} | [
"Administrator@cql-PC"
]
| Administrator@cql-PC |
e72e978eb13d09b6a76473a4b9422b69f8d41062 | ed3cb95dcc590e98d09117ea0b4768df18e8f99e | /project_1_3/src/f/a/j/Calc_1_3_5099.java | e8ca18214950e501f9177e51c21cd563d00d79c9 | []
| no_license | chalstrick/bigRepo1 | ac7fd5785d475b3c38f1328e370ba9a85a751cff | dad1852eef66fcec200df10083959c674fdcc55d | refs/heads/master | 2016-08-11T17:59:16.079541 | 2015-12-18T14:26:49 | 2015-12-18T14:26:49 | 48,244,030 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 131 | java | package f.a.j;
public class Calc_1_3_5099 {
/** @return the sum of a and b */
public int add(int a, int b) {
return a+b;
}
}
| [
"[email protected]"
]
| |
2a1ed5d391d7dccdd457e9ed48254b3c72bc1747 | df771ac9dd9acb2ce6a1121d67cf46ba8e12f5ab | /src/com/training/DoublyLinkedList.java | 36cc1262305fb490a4bb6e6357b994033d667016 | []
| no_license | johnpaulms/data-structure | ac622454e44e3de1247e69b0ae47d765f18a1d72 | 3d01dc5a25437d9496fc5e188c12b1ba3e3d1934 | refs/heads/master | 2023-01-13T09:08:17.799372 | 2020-11-11T05:29:21 | 2020-11-11T05:29:21 | 296,221,130 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,825 | java | package com.training;
/**
* Created by JohnPaul Manohar on 9/14/2020.
*/
public class DoublyLinkedList {
static Node head;
public static void main(String... args) {
insert(34);
insert(65);
insert(49);
insert(52);
insert(50);
insert(23);
insert(68);
insert(27);
insert(21);
insert(95);
show();
System.out.println(search(67));
System.out.println(search(52));
delete(50);
delete(68);
delete(95);
show();
}
static void insert(int data) {
Node curr = new Node(data);
curr.next = head;
if(head != null && head.prev != null) head.prev = curr;
head = curr;
}
static void delete(int data) {
Node curr = head;
if(head != null && head.data == data) head = head.next;
else {
while (curr.next != null) {
if (curr.next.data == data) {
curr.next = curr.next.next;
curr.next.prev = curr;
}
curr = curr.next;
}
}
}
static boolean search(int data) {
Node curr = head;
while (curr.next != null) {
if(curr.data == data) return true;
curr = curr.next;
}
return false;
}
static void show() {
Node curr = head;
while (curr.next != null) {
System.out.print(curr.data + " -> ");
curr = curr.next;
}
System.out.println(curr.data + " -> ");
}
static class Node {
public int data;
public Node prev;
public Node next;
public Node(int _data) {
data = _data;
next = prev = null;
}
}
}
| [
"[email protected]"
]
| |
3da57dc5b92c74921d879d8492d102a96b1c21bd | ebf14067131b8dba184aa7096c8ee38d46929cfe | /spring-boot-06-bill/src/main/java/com/example/springboot/config/MySpringMvcConfigurer.java | de3ba625b2f00951eb41655c14756a77c3f94691 | []
| no_license | 290437333/spring-boot-09-data-jpa | 06a108c373b6d0c6e09d5fc0ef41e9cfee624d3c | 9f154239ca19d0bf12dab1b767b60fa5c687269f | refs/heads/master | 2020-07-25T08:55:17.360409 | 2019-09-13T10:09:51 | 2019-09-13T10:09:51 | 208,237,247 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,105 | java | package com.example.springboot.config;
import com.example.springboot.component.MyLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MySpringMvcConfigurer {
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer(){
//ๆทปๅ ่งๅพๆงๅถ
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("main/login");
registry.addViewController("/index.html").setViewName("main/login");
registry.addViewController("/main.html").setViewName("main/index");
}
};
}
//ๅบๅ่งฃๆๅจ
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
| [
"[email protected]"
]
| |
f0fb85c484bcf8211978112d6fc1143e50627d2f | f66cc37011b5d30c791d84f4629d76f7e5e29170 | /src/main/java/com/work/dao/PurchaseDao.java | dab1eebec1a07c0e5868deb7b60ba44d695f797b | []
| no_license | moocLook/materialManagement | e6a4c4f1acd17acc54c59b2c5751ac7df8e8f58b | c73ba0b496e1d51b3f62537fae0f7d18cc885e5b | refs/heads/master | 2023-03-06T18:22:59.203870 | 2019-10-15T00:47:21 | 2019-10-15T00:47:21 | 214,203,151 | 1 | 1 | null | 2023-02-22T05:26:18 | 2019-10-10T14:23:35 | Java | UTF-8 | Java | false | false | 3,996 | java | package com.work.dao;
import com.work.bean.Purchase;
import com.work.bean.PurchaseInfo;
import com.work.bean.PurchaseSearch;
import com.work.bean.User;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* ้่ดญๅๆไน
ๅฑๆฅๅฃ
*/
@Repository
public interface PurchaseDao {
/**
* ๆฅ่ฏขๆๆ้่ดญๅ
* @return
*/
@Select("SELECT * FROM tb_user where position='้่ดญๅ'")
public List<User> findAllPurcher();
/**
* ๆทปๅ ่ฎขๅ
* @param purchase
*/
@Update("INSERT INTO tb_purchase (\n" +
"tb_purchase.user_id,\n" +
"tb_purchase.`name`,\n" +
"tb_purchase.create_time,\n" +
"tb_purchase.creator,\n" +
"tb_purchase.purchaser,\n" +
"tb_purchase.audit_order,\n" +
"tb_purchase.audit_state,\n" +
"tb_purchase.purchase_state,\n" +
"tb_purchase.end_time,\n" +
"tb_purchase.remark \n" +
")\n" +
"VALUES\n" +
"\t( #{user_id},\n" +
"#{name},\n" +
"#{create_time},\n" +
"#{creator},\n" +
"#{purchaser},\n" +
"#{audit_order},\n" +
"#{audit_state},\n" +
"#{purchase_state},\n" +
"#{end_time},\n" +
"#{remark}\n" +
"\t)")
public int addPurchase(Purchase purchase);
/**
* ่ทๅ่ฎขๅ็id
* @param purchase
* @return
*/
@Select("select id from tb_purchase WHERE tb_purchase.`name`=#{name} and tb_purchase.create_time=#{create_time};")
public int getPurchaseId(Purchase purchase);
/**
* ๆทปๅ ่ฎขๅ็ๅ
ทไฝไฟกๆฏ
* @param purchaseInfo
*/
@Update("INSERT INTO tb_purchase_info ( tb_purchase_info.purchase, tb_purchase_info.type, tb_purchase_info.company, plan_number, number )\n" +
"VALUES\n" +
"\t(#{purchase},#{type},#{company},#{plan_number},#{number} )")
public int addPurchaseInfo(PurchaseInfo purchaseInfo);
/**
* ๆฅ่ฏขๆๆๅฎกๆ ธ้่ฟ็้่ดญๅ็ไฟกๆฏ
* @return
*/
@Select("SELECT p.* FROM tb_audit a join tb_purchase p on p.id=a" +
".purchase_id WHERE a.result=1")
public List<Purchase> findallPurchase();
/**
* ๆฅ่ฏขๆๆ้่ดญๅๅๅปบ่
็ไฟกๆฏ
* @return
*/
@Select("select u.* FROM tb_user u,tb_purchase p WHERE p.user_id=u.id")
public List<User> findAllCreator();
/**
* ๆฅ่ฏข็ฌฆๅๆกไปถ็่ฎข่ดญๅ็ไฟกๆฏ
*/
@Select("SELECT\n" +
"\t* \n" +
"FROM\n" +
"\ttb_purchase p \n" +
"WHERE\n" +
"\taudit_state = 1 \n" +
"\tAND (\n" +
"\tp.`name` = #{name} or #{name}='' or ISNULL(#{name}))\n" +
"\t\n" +
"\tAND (\n" +
"\tpurchaser = #{purchaser} or #{purchaser}='' or ISNULL(#{purchaser})\t)\n" +
"\n" +
"AND (\n" +
"creator = #{creator} or #{creator}='' or ISNULL(#{creator}))" +
"and (user_id=#{userId}) or #{userId}='' or ISNULL(#{userId})")
public List<Purchase> findPurchaseBy(PurchaseSearch purchaseSearch);
/**
* ๆฅ่ฏขๅพ
ๅฝๅๅฎกๆ ธไบบๅๅฎกๆ ธ็่ฎขๅไฟกๆฏ
* @param user
* @return
*/
@Select("SELECT p.* FROM tb_audit a join tb_purchase p on p.id=a.purchase_id join tb_audit_info ai on a.id=ai.audit_id where a.`status`=ai.`order` and ai.user_id=#{id}")
public List<Purchase> findAuditPurchase(User user);
/**
* ๅ ้ค้่ดญๅ,้่ดญๅ็Infoไผ็บง่ๅ ้ค
* @param purchase
*/
@Select("DELETE from tb_purchase WHERE id=#{id}")
public void deletePurchase(Purchase purchase);
/**
* ไฟฎๆน้่ดญๅ็ๅฎกๆ ธ็ถๆ
* @param purchase
*/
public void AuditPurchase(Purchase purchase);
}
| [
"[email protected]"
]
| |
5cfa20dd974e4fb5ff3e5273dbe70d63e2ad38ed | 7cbb7be007f803c81bbc07046623b66080b200de | /src/main/java/helper/fisher/repository/SpeciesRepository.java | f1860e400c09f7e63c82a25785d62e49de6e3ff6 | []
| no_license | ArturMarcinkowski/FisherHelper | 924825e912b1f4ddff5d589435939c623c441578 | 547f85aa2d74110c97108e7a109d2fdc249ab946 | refs/heads/main | 2023-06-11T11:12:33.475687 | 2021-07-05T10:40:07 | 2021-07-05T10:40:07 | 379,243,377 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 308 | java | package helper.fisher.repository;
import helper.fisher.entity.Species;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface SpeciesRepository extends JpaRepository<Species, Integer> {
Species findById(int id);
} | [
"[email protected]"
]
| |
f78d641ef13ef84f18d9b15144456820202645bc | 5c7936d5216dc240e549a15e1a408dfbb11e24e5 | /src/main/java/io/ppatierno/kafka/connect/amqp/AmqpSinkConnector.java | e1c45ab89c422cd19ded959c536a481767607c80 | [
"Apache-2.0"
]
| permissive | cirobarradov/kafka-connect-amqp | 32ed7ed546fc5deaa93e2c92107d3295006953be | 588f7a6be895caa5e66ad5597b1bf3bc763b3991 | refs/heads/master | 2020-03-20T10:27:57.807831 | 2018-06-14T14:56:02 | 2018-06-14T14:56:02 | 137,372,431 | 0 | 0 | null | 2018-06-14T14:54:50 | 2018-06-14T14:54:49 | null | UTF-8 | Java | false | false | 2,764 | java | /*
* Copyright 2016 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.ppatierno.kafka.connect.amqp;
import io.ppatierno.kafka.connect.amqp.sink.AmqpSinkConnectorConfig;
import io.ppatierno.kafka.connect.amqp.sink.AmqpSinkTask;
import io.ppatierno.kafka.connect.amqp.util.Version;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigException;
import org.apache.kafka.connect.connector.Task;
import org.apache.kafka.connect.errors.ConnectException;
import org.apache.kafka.connect.sink.SinkConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* AmqpSinkConnector is a Kafka Connect connector that can get messages
* from Kafka topic and delivery them through AMQP protocol
*/
public class AmqpSinkConnector extends SinkConnector {
private static final Logger LOG = LoggerFactory.getLogger(AmqpSinkConnector.class);
private AmqpSinkConnectorConfig config;
private Map<String, String> configProperties;
@Override
public String version() {
return Version.getVersion();
}
@Override
public void start(Map<String, String> props) {
LOG.info("Start AMQP sink connector");
try {
this.configProperties = props;
this.config = new AmqpSinkConnectorConfig(props);
} catch (ConfigException e) {
throw new ConnectException("Couldn't start AmqpSinkConnector due to configuration error", e);
}
}
@Override
public Class<? extends Task> taskClass() {
return AmqpSinkTask.class;
}
@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
LOG.info("AMQP sink connector maxTasks = " + maxTasks);
List<Map<String, String>> taskConfigs = new ArrayList<>(1);
Map<String, String> taskProps = new HashMap<>(this.configProperties);
taskConfigs.add(taskProps);
return taskConfigs;
}
@Override
public void stop() {
LOG.info("Stop AMQP source connector");
}
@Override
public ConfigDef config() {
return AmqpSinkConnectorConfig.CONFIG_DEF;
}
}
| [
"[email protected]"
]
| |
2f7ff6e4bc980be1b55789a51281140211c7f3a6 | 1f7a8a0a76e05d096d3bd62735bc14562f4f071a | /NeverPuk/net/ns/f.java | 99691043ceef0e29c7c4fbd0af217729aa90fe6d | []
| no_license | yunusborazan/NeverPuk | b6b8910175634523ebd4d21d07a4eb4605477f46 | a0e58597858de2fcad3524daaea656362c20044d | refs/heads/main | 2023-05-10T09:08:02.183430 | 2021-06-13T17:17:50 | 2021-06-13T17:17:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,619 | java | package net.ns;
import java.util.Random;
import net.xn;
import net.ns.i;
import net.ns.i9;
import net.w.fb;
import net.y9.rv;
import net.y9.zu;
public class f extends i {
private static final net.w.t h = new net.w.t();
private static final net.w.h u = new net.w.h(false);
private static final net.w.c R = new net.w.c(false, false);
private static final net.w.c o = new net.w.c(false, true);
private static final net.w.z s = new net.w.z(net.nb.f.T9, 0);
private final f.r r;
public f(f.r var1, i.g var2) {
super(var2);
this.r = var1;
this.v.add(new i.w(net.yn.x.class, 8, 4, 4));
this.v.add(new i.w(net.yn.z.class, 4, 2, 3));
this.K.E = 10;
if(var1 != f.r.MEGA && var1 != f.r.MEGA_SPRUCE) {
this.K.N = 1;
this.K.z = 1;
} else {
this.K.N = 7;
this.K.P = 1;
this.K.z = 3;
}
}
public net.w.x q(Random var1) {
return (net.w.x)((this.r == f.r.MEGA || this.r == f.r.MEGA_SPRUCE) && var1.nextInt(3) == 0?(this.r != f.r.MEGA_SPRUCE && var1.nextInt(13) != 0?R:o):(var1.nextInt(3) == 0?h:u));
}
public net.w.f A(Random var1) {
return var1.nextInt(5) > 0?new fb(zu.i.FERN):new fb(zu.i.GRASS);
}
public void f(net.yv.r var1, Random var2, net.u.j var3) {
int[] var4 = i9.M();
if(this.r == f.r.MEGA || this.r == f.r.MEGA_SPRUCE) {
int var5 = var2.nextInt(3);
int var6 = 0;
if(var6 < var5) {
int var7 = var2.nextInt(16) + 8;
int var8 = var2.nextInt(16) + 8;
net.u.j var9 = var1.A(var3.F(var7, 0, var8));
s.K(var1, var2, var9);
++var6;
}
}
G.o(net.y9.y.FERN);
int var10 = 0;
int var13 = var2.nextInt(16) + 8;
int var14 = var2.nextInt(16) + 8;
int var15 = var2.nextInt(var1.A(var3.F(var13, 0, var14)).h() + 32);
G.K(var1, var2, var3.F(var13, var15, var14));
++var10;
super.f(var1, var2, var3);
}
public void y(net.yv.r var1, Random var2, net.l.o var3, int var4, int var5, double var6) {
if(this.r == f.r.MEGA || this.r == f.r.MEGA_SPRUCE) {
this.j = net.nb.f.p.p();
this.y = net.nb.f.dl.p();
if(var6 > 1.75D) {
this.j = net.nb.f.dl.p().s(rv.l, rv.m.COARSE_DIRT);
} else if(var6 > -0.95D) {
this.j = net.nb.f.dl.p().s(rv.l, rv.m.PODZOL);
}
}
this.B(var1, var2, var3, var4, var5, var6);
}
private static xn b(xn var0) {
return var0;
}
public static enum r {
NORMAL,
MEGA,
MEGA_SPRUCE;
}
}
| [
"[email protected]"
]
| |
4e1f078d32bb46e0e7614b4e37d09def36546465 | 2c93fa0b266d392a601fc4408135f2430c667a49 | /frontend/webadmin/modules/uicompat/src/main/java/org/ovirt/engine/ui/uicompat/IFrontendMultipleQueryAsyncCallback.java | 4b26aa7c67b8c9e1cd15ef373728101f221deeb0 | [
"Apache-2.0"
]
| permissive | jbeecham/ovirt-engine | 5d79080d2f5627229e6551fee78882f9f9a6e3bc | 3e76a8d3b970a963cedd84bcb3c7425b8484cf26 | refs/heads/master | 2021-01-01T17:15:29.961545 | 2012-10-25T14:41:57 | 2012-10-26T08:56:22 | 10,623,147 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 158 | java | package org.ovirt.engine.ui.uicompat;
public interface IFrontendMultipleQueryAsyncCallback {
void Executed(FrontendMultipleQueryAsyncResult result);
}
| [
"[email protected]"
]
| |
d2adb08e85be986df640dc74a9ebc52b61287cdd | dbedfbe279ecb0432ae342317bc6678e7a3e4063 | /app/src/main/java/com/first/fubao/oto/adapter/BusinessListItemHolder.java | 85e4dea33218609ce3d0ecf2bfe44d274b130f29 | []
| no_license | gongpan/OTO_Remodel | 9b9ff5e3e38d4188ab5c7e4fa8a7e97850a5aa5b | 7d9fdd32b92d51eb72299cca8a38a881ffe8828b | refs/heads/master | 2021-01-10T10:53:50.032925 | 2016-03-23T07:51:05 | 2016-03-23T07:51:05 | 54,525,881 | 0 | 0 | null | 2016-03-23T02:51:33 | 2016-03-23T02:51:31 | null | UTF-8 | Java | false | false | 2,082 | java | package com.first.fubao.oto.adapter;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.first.fubao.oto.R;
import com.first.fubao.oto.entity.BusinessEntity;
import com.first.fubao.oto.utils.UIUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
/**
* @ๅๅปบ่
๏ผๆจ้ฟ็ฆ
* @ๅๅปบๆถ้ด๏ผ2016/2/16
* @ๆ่ฟฐ๏ผTODO
*/
public class BusinessListItemHolder extends BaseHolder<BusinessEntity.StoreData> {
private ImageView mImageView;
private TextView mTvStoreTitle;
private RatingBar mRatingBar;
private TextView mTvPerMoney;
private TextView mTvZK;
private TextView mTvPlace;
private TextView mTvDistance;
@Override
protected View initView() {
View view = View.inflate(UIUtils.getContext(), R.layout.item_business_listview, null);
mImageView = (ImageView) view.findViewById(R.id.business_item_img);
mTvStoreTitle = (TextView) view.findViewById(R.id.business_item_title);
mRatingBar = (RatingBar) view.findViewById(R.id.business_item_ratingBar);
mTvPerMoney = (TextView) view.findViewById(R.id.business_item_per_money_tv);
mTvZK = (TextView) view.findViewById(R.id.business_item_zk);
mTvPlace = (TextView) view.findViewById(R.id.business_item_place);
mTvDistance = (TextView) view.findViewById(R.id.business_item_distance);
return view;
}
@Override
protected void refreshUI(BusinessEntity.StoreData data) {
ImageLoader.getInstance().displayImage(data.store_logo, mImageView, UIUtils.getImageLoadOptions());
mTvStoreTitle.setText(data.store_name);
mRatingBar.setRating(data.mark_all);
mTvPerMoney.setText(data.consum_avg);
if (TextUtils.isEmpty(data.store_disvalue)) {
mTvZK.setText("ไธๆๆ");
} else {
mTvZK.setText(data.store_disvalue + "ๆ");
}
mTvPlace.setText(data.address);
mTvDistance.setText(data.distance);
}
}
| [
"[email protected]"
]
| |
870ca9a967fffc0a1e4562b9eac8d4b9d9228c61 | 371fedd878dc1ae959fe7d6e2916c46a7f8c114f | /app/src/test/java/com/yosanai/blecommapp/ExampleUnitTest.java | eac87bfa1ce72acfbe1e574841ec97410f61e6a2 | [
"MIT"
]
| permissive | perusworld/BLECommApp | a34d0f84f8a7587371c13ea368169a978a9c1b69 | cd3f7dff04193b03ae78f10ad58293c1cee8a88b | refs/heads/master | 2021-01-01T04:20:38.667574 | 2018-03-07T17:05:50 | 2018-03-07T17:05:50 | 56,553,686 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 326 | java | package com.yosanai.blecommapp;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
]
| |
20c474d2ae48652c28022dbf444f74e790312878 | a9c86db57e2cb6b449429fc1e3fd561e79934272 | /src/OCP_SE8_1ZO_809_Book/Chapter1_Advanced_Class_Design/v8_2_1823/Book.java | 5eedf5e0ae8b68c5ee1ec2cc3c4f2297b65893a1 | []
| no_license | wolodey/zertifizierung_oracle | 3061e4a362d8d65a18a635854142e0e2210494f1 | 335e7d5adb8ae7d35d847e75b9857b8051eb94e1 | refs/heads/master | 2021-04-26T16:51:17.840235 | 2019-08-31T06:14:31 | 2019-08-31T06:14:31 | 123,976,973 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 253 | java | package OCP_SE8_1ZO_809_Book.Chapter1_Advanced_Class_Design.v8_2_1823;
/**
* Created by WSteinle on 17.08.2018.
*/
public class Book {
protected final int pages = 100;
final void mA() {
System.out.println("In B.ma " + pages);
}
}
| [
"[email protected]"
]
| |
296c0606fe7fa8a23cd1e9bb403d1c76566f2a6a | 52ae0daadd17fd831586b8b88d1f88a5c166b654 | /app/src/main/java/id/tech/astrid/SlidingTabs_InfoToko_Fragment.java | 3a827b1ac719f25472365d4c956f30e8bd5dd4c1 | []
| no_license | pagadentechnology/verificare_indosat | 8869e702a1d7f78b39f955c5a101fd1dd4f53f83 | 4c2e7855659a73c2599bffce8e20977700f3ddbb | refs/heads/master | 2022-09-24T01:45:44.025307 | 2016-06-30T05:41:46 | 2016-06-30T05:41:46 | 62,280,397 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,363 | java | package id.tech.astrid;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SlidingTabs_InfoToko_Fragment extends Fragment{
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
}
static class SamplePagerItem{
Fragment createFragment(int posisi){
return null;
}
}
private class Async_GetTokoInfo extends AsyncTask<Void, Void, Void>{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
}
| [
"[email protected]"
]
| |
633013b10f26a935864ccb0b94a669f8c02cf16f | e54442b2d3faa8765a8a91c51b0d64a81f51d1bf | /src/main/java/com/jf/shop/login/config/MyServer.java | 08e69cd415a5c516495920b8a9bef2219d858ad8 | []
| no_license | fengJA/fjTest | 4e6319c6c577da240a5c66c8f1b94cc345d5acce | 6c683f312d7e983acd3438c51013d2e5ec8c6e08 | refs/heads/master | 2022-06-24T09:24:53.802030 | 2019-10-15T04:24:29 | 2019-10-15T04:24:29 | 215,059,327 | 0 | 0 | null | 2022-06-21T02:02:25 | 2019-10-14T14:01:54 | Java | UTF-8 | Java | false | false | 4,574 | java | package com.jf.shop.login.config;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* @author fengj
* @date 2019/8/8 -8:03
*/
public class MyServer {
public static int DEFAULT_PORT = 8080;
public static boolean flages = true;
public static boolean userInfo = true;
public static String otherClientName;
public static HashMap<String,SocketChannel> serverSocketChannelHashMap;
public static Map<Integer,String> allClient;
public static void main(String[] args) {
int port = DEFAULT_PORT;
/* try {
port = Integer.parseInt(args[0]);
} catch (RuntimeException ex) {
port = DEFAULT_PORT;
}*/
System.out.println("Listening for connections on port " + port);
ServerSocketChannel serverChannel = null;
Selector selector;
serverSocketChannelHashMap = new HashMap<>();
allClient = new HashMap<>();
try {
serverChannel = ServerSocketChannel.open();
// int localPort = serverChannel.socket().getLocalPort();
// System.out.println("localPort is :" + localPort);
ServerSocket ss = serverChannel.socket();
InetSocketAddress address = new InetSocketAddress(port);
ss.bind(address);
serverChannel.configureBlocking(false);
selector = Selector.open();
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException ex) {
ex.printStackTrace();
return;
}
while (true) {
try {
selector.select();
} catch (IOException ex) {
ex.printStackTrace();
break;
}
Set<SelectionKey> readyKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = readyKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
try {
if (key.isAcceptable()) {
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel client = server.accept();
System.out.println("Accepted connection from "+ client);
client.configureBlocking(false);
SelectionKey clientKey = client.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ);
ByteBuffer buffer = ByteBuffer.allocate(100);
clientKey.attach(buffer);
System.out.println("bufferๆฏ๏ผ"+ buffer.toString().length());
}
if (key.isReadable()) {
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer output = (ByteBuffer) key.attachment();
int read = client.read(output);
if (read == -1){
client.close();
}else {
System.out.println("ๆถๅฐ็"+ new String( output.array()));
for(SelectionKey key1 : selector.keys())
{
Channel targetchannel = key1.channel();
if(targetchannel instanceof SocketChannel )
{
SocketChannel dest = (SocketChannel)targetchannel;
output.flip();
dest.write(output);
}
}
}
}
if (key.isWritable()) {
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer output = (ByteBuffer) key.attachment();
output.flip();
client.write(output);
output.compact();
}
} catch (IOException ex) {
key.cancel();
try {
key.channel().close();
} catch (IOException cex) {
}
}
}
}
}
}
| [
"[email protected]"
]
| |
ef2bb5e928194f5f9b36904ad1fd4e85fac0fc01 | 5f776b0fd157341a746a740fc5e1b09a7d55cdd1 | /miracom_edu/javaWorkspace/java14_Inheritance/src/com/edu/test/PersonTest1.java | 79de31bf54fea6bf3efeb2079f8508f2c6e0b216 | []
| no_license | JungGyu0920/miracom_javaEduSummary | 53d7d736a7d4e65cf9ba96a26f82b05cc739a7e0 | 1cdba2cd3628881df75aff96f4928cca7679f503 | refs/heads/master | 2023-09-06T08:17:34.799203 | 2021-10-27T08:00:38 | 2021-10-27T08:00:38 | null | 0 | 0 | null | null | null | null | UHC | Java | false | false | 508 | java | package com.edu.test;
import com.edu.child.Student;
import com.edu.child.Teacher;
public class PersonTest1 {
public static void main(String[] args) {
Student s = new Student("์์ด์ ", 28, "์ ์ฌ๋", 123);
Teacher t = new Teacher("๊ฐํธ๋", 45, "์ ๋ฆผ๋", "Java");
System.out.println(s.getDetails());
System.out.println(t.getDetails());
System.out.println("===============");
System.out.println(s); //toString() ์๋ต
System.out.println(t); //toString() ์๋ต
}
}
| [
"[email protected]"
]
| |
32900a62de2bfb37944f4974a595b5e76746e960 | 18c91b710f017b426e2586bb1814f947dbe78a8d | /model/InWorldProperties.java | e2f2d0f2a6051a37ac791c70803e6b1d9416fc0e | []
| no_license | aliounebfall/someweireBot | bb5034dbae589e247204f23eaae7a5113a08d4e2 | bd88668f00553700225f6b24b2d0e39096f0eb3e | refs/heads/master | 2023-03-17T12:34:13.043052 | 2021-03-16T23:26:48 | 2021-03-16T23:26:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 713 | java | package com.bot.someweire.model;
import org.neo4j.springframework.data.core.schema.GeneratedValue;
import org.neo4j.springframework.data.core.schema.Id;
import org.neo4j.springframework.data.core.schema.RelationshipProperties;
@RelationshipProperties
public class InWorldProperties {
@Id
@GeneratedValue
private Long id;
private String location;
public InWorldProperties (String location) {
this.id=null;
this.location = location;
}
public Long getId () {
return id;
}
public String getLocationInWorld () {
return location;
}
public void setLocationInWorld (String location) {
this.location = location;
}
public void setId (Long id) {
this.id = id;
}
}
| [
"[email protected]"
]
| |
43b3e0e2ca51164c3b477e71b1a2d869bf517d13 | d7674b46760ecaf5b3e358f3cdb767ecdfea7bf2 | /imageio/imageio-clippath/src/test/java/com/twelvemonkeys/imageio/path/AdobePathBuilderTest.java | 1e917a864ef66c21dfbda1df70daa88b8e100b92 | [
"BSD-3-Clause"
]
| permissive | jbobnar/TwelveMonkeys | 5e35bc62d7f97562f37bf8db4b76d9179077a5aa | 7b086317fd848725843e77260b3200cd6c735d88 | refs/heads/master | 2020-12-25T11:41:50.972434 | 2019-12-31T08:32:57 | 2019-12-31T08:32:57 | 52,418,237 | 0 | 0 | BSD-3-Clause | 2019-11-03T08:27:46 | 2016-02-24T05:56:50 | Java | UTF-8 | Java | false | false | 6,199 | java | /*
* Copyright (c) 2014, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.imageio.path;
import org.junit.Test;
import javax.imageio.IIOException;
import javax.imageio.stream.ImageInputStream;
import java.awt.geom.Path2D;
import java.io.DataInput;
import java.io.IOException;
import java.nio.ByteBuffer;
import static com.twelvemonkeys.imageio.path.PathsTest.assertPathEquals;
import static com.twelvemonkeys.imageio.path.PathsTest.readExpectedPath;
import static org.junit.Assert.assertNotNull;
public class AdobePathBuilderTest {
@Test(expected = IllegalArgumentException.class)
public void testCreateNullBytes() {
new AdobePathBuilder((byte[]) null);
}
@Test(expected = IllegalArgumentException.class)
public void testCreateNull() {
new AdobePathBuilder((DataInput) null);
}
@Test(expected = IllegalArgumentException.class)
public void testCreateEmpty() {
new AdobePathBuilder(new byte[0]);
}
@Test(expected = IllegalArgumentException.class)
public void testCreateShortPath() {
new AdobePathBuilder(new byte[3]);
}
@Test(expected = IllegalArgumentException.class)
public void testCreateImpossiblePath() {
new AdobePathBuilder(new byte[7]);
}
@Test
public void testCreate() {
new AdobePathBuilder(new byte[52]);
}
@Test
public void testNoPath() throws IOException {
Path2D path = new AdobePathBuilder(new byte[26]).path();
assertNotNull(path);
}
@Test(expected = IIOException.class)
public void testShortPath() throws IOException {
byte[] data = new byte[26];
ByteBuffer buffer = ByteBuffer.wrap(data);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_LENGTH_RECORD);
buffer.putShort((short) 1);
Path2D path = new AdobePathBuilder(data).path();
assertNotNull(path);
}
@Test(expected = IIOException.class)
public void testShortPathToo() throws IOException {
byte[] data = new byte[52];
ByteBuffer buffer = ByteBuffer.wrap(data);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_LENGTH_RECORD);
buffer.putShort((short) 2);
buffer.position(buffer.position() + 22);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED);
Path2D path = new AdobePathBuilder(data).path();
assertNotNull(path);
}
@Test(expected = IIOException.class)
public void testLongPath() throws IOException {
byte[] data = new byte[78];
ByteBuffer buffer = ByteBuffer.wrap(data);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_LENGTH_RECORD);
buffer.putShort((short) 1);
buffer.position(buffer.position() + 22);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED);
buffer.position(buffer.position() + 24);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED);
Path2D path = new AdobePathBuilder(data).path();
assertNotNull(path);
}
@Test(expected = IIOException.class)
public void testPathMissingLength() throws IOException {
byte[] data = new byte[26];
ByteBuffer buffer = ByteBuffer.wrap(data);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED);
Path2D path = new AdobePathBuilder(data).path();
assertNotNull(path);
}
@Test
public void testSimplePath() throws IOException {
// We'll read this from a real file, with hardcoded offsets for simplicity
// PSD IRB: offset: 34, length: 32598
// Clipping path: offset: 31146, length: 1248
ImageInputStream stream = PathsTest.resourceAsIIOStream("/psd/grape_with_path.psd");
stream.seek(34 + 31146);
byte[] data = new byte[1248];
stream.readFully(data);
Path2D path = new AdobePathBuilder(data).path();
assertNotNull(path);
assertPathEquals(path, readExpectedPath("/ser/grape-path.ser"));
}
@Test
public void testComplexPath() throws IOException {
// We'll read this from a real file, with hardcoded offsets for simplicity
// PSD IRB: offset: 16970, length: 11152
// Clipping path: offset: 9250, length: 1534
ImageInputStream stream = PathsTest.resourceAsIIOStream("/tiff/big-endian-multiple-clips.tif");
stream.seek(16970 + 9250);
byte[] data = new byte[1534];
stream.readFully(data);
Path2D path = new AdobePathBuilder(data).path();
assertNotNull(path);
assertPathEquals(path, readExpectedPath("/ser/multiple-clips.ser"));
}
} | [
"[email protected]"
]
| |
2c5a5b5f37c4ecce0d18f88a9e705167452e8eb4 | 4dace70a45bd53c0ae4e50db19f38e3f70648070 | /android/app/src/main/java/com/awesomeproject/MainApplication.java | 281f0e1e924ffe132de686cecd45e7f0d82ef216 | []
| no_license | marc-st/photo-sharing-react-native | adee767e9ce46141eb1a6cb6030889ec382644fd | b8905e3ba553f95d2bb67f7f0603685b262f6425 | refs/heads/master | 2020-12-03T08:11:39.380029 | 2017-08-04T11:46:45 | 2017-08-04T11:46:45 | 95,665,639 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,829 | java | package com.awesomeproject;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.oblador.vectoricons.VectorIconsPackage;
import com.facebook.reactnative.androidsdk.FBSDKPackage;
import com.RNFetchBlob.RNFetchBlobPackage;
import com.lwansbrough.RCTCamera.RCTCameraPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;
import com.facebook.reactnative.androidsdk.FBSDKPackage;
import com.facebook.appevents.AppEventsLogger;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private static CallbackManager mCallbackManager = CallbackManager.Factory.create();
protected static CallbackManager getCallbackManager() {
return mCallbackManager;
}
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new VectorIconsPackage(),
new FBSDKPackage(mCallbackManager),
new RNFetchBlobPackage(),
new RCTCameraPackage()
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
FacebookSdk.sdkInitialize(getApplicationContext());
// If you want to use AppEventsLogger to log events.
AppEventsLogger.activateApp(this);
SoLoader.init(this, /* native exopackage */ false);
}
}
| [
"[email protected]"
]
| |
fbbb632d05d17a0915b209abbe1edd634d49ca42 | 489f17055f538613ef37be653d26a3ca2d7c2671 | /Bicycle.java | 696232d412465ce261d69fe53484449b830d0ea1 | []
| no_license | yasuyamakyosuke/java.rsample | 6d4e3243b9379c8703c942da1ab908fe94bd9a0a | fc18e10d0b841a4325f7f8488e5c044d8bc4191c | refs/heads/master | 2023-01-01T18:26:55.149623 | 2020-10-20T13:25:42 | 2020-10-20T13:25:42 | 304,210,831 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 291 | java | class Bicycle extends Vehicle {
Bicycle(String name, String color) {
super(name, color);
}
public void run(int distance) {
System.out.println(distance + "km่ตฐใใพใ");
this.distance += distance;
System.out.println("่ตฐ่ก่ท้ข๏ผ" + this.distance + "km");
}
}
| [
"[email protected]"
]
| |
a24d2943c185e9632bbc319d2063ea55048afe81 | f3acdd6950aa6c3df52853e1a2845704cec5cbb6 | /PersonKontroll/app/src/main/java/politiet/no/personkontroll/mvp/header/HeaderComponent.java | 93e942889c3ccbc94fee1b1fd882ddd0f3a4b82c | []
| no_license | airien/workbits | 4872f6d7ceee82b7900501f0bdfacc029a3cdda6 | 53b35f5da9dfccce4c345e19221d27ea66862d86 | refs/heads/master | 2021-06-01T10:48:06.876043 | 2019-05-13T19:41:27 | 2019-05-13T19:41:27 | 15,254,475 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 839 | java | package politiet.no.personkontroll.mvp.header;
import android.app.Activity;
import politiet.no.personkontroll.mvp.PersonkontrollApplication;
import politiet.no.personkontroll.data.source.bruker.BrukerRepositoryComponent;
import politiet.no.personkontroll.mvp.util.FragmentScoped;
import dagger.Component;
/**
* This is a Dagger component. Refer to {@link PersonkontrollApplication} for the list of Dagger components
* used in this application.
* <P>
* Because this component depends on the {@link BrukerRepositoryComponent}, which is a singleton, a
* scope must be specified. All fragment components use a custom scope for this purpose.
*/
@FragmentScoped
@Component(dependencies = BrukerRepositoryComponent.class, modules = HeaderPresenterModule.class)
public interface HeaderComponent {
void inject(Activity fragment);
}
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.