blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|
40bd13ff540852259c7e7a1f5aee5c4b0b40bd73
|
Java
|
Archer21/Amaterasu2015
|
/app/src/main/java/com/archer/amaterasu/ui/adapter/TopSongsAdapter.java
|
UTF-8
| 4,916 | 2.4375 | 2 |
[] |
no_license
|
package com.archer.amaterasu.ui.adapter;
import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.archer.amaterasu.R;
import com.archer.amaterasu.domain.Song;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.ArrayList;
import butterknife.Bind;
import butterknife.ButterKnife;
public class TopSongsAdapter extends RecyclerView.Adapter<TopSongsAdapter.TopSongsViewHolder> {
ArrayList<Song> listSongs;
Context context;
OnItemClickListener listener;
public TopSongsAdapter(Context context, OnItemClickListener listener) {
this.context = context;
this.listSongs = new ArrayList<>();
this.listener = listener;
}
@Override
public TopSongsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_top_song_row, parent, false);
return new TopSongsViewHolder(view);
}
@Override
public void onBindViewHolder(TopSongsViewHolder holder, int position) {
Song currentSong = listSongs.get(position);
holder.setImage(context, currentSong.getSongImageSmall());
holder.setName(currentSong.getSongTitle());
holder.setTopSongRating(currentSong.getSongRating());
holder.setPlayCount(currentSong.getSongViews());
holder.bind(listSongs.get(position), listener);
}
@Override
public int getItemCount() {
return listSongs.size();
}
/**
* Add item in the last index
*
* @param song The item to be inserted
*/
public void addItem(Song song) {
if (song == null)
throw new NullPointerException("The item cannot be null");
listSongs.add(song);
notifyItemInserted(getItemCount() - 1);
}
/**
* Add item in determined index
*
* @param song The event to be inserted
* @param position Index for the new event
*/
public void addItem(Song song, int position) {
if (song == null)
throw new NullPointerException("The item cannot be null");
if (position < getItemCount() || position > getItemCount())
throw new IllegalArgumentException("The position must be between 0 and lastIndex + 1");
listSongs.add(position, song);
notifyItemInserted(position);
}
/**
* Add a bunch of items
*
* @param artists Collection to add
* */
public void addAll(ArrayList<Song> artists) {
if (artists == null)
throw new NullPointerException("The items cannot be null");
this.listSongs.addAll(artists);
notifyItemRangeInserted(getItemCount() - 1, artists.size());
}
public void replace(ArrayList<Song> artists){
this.listSongs = artists;
notifyDataSetChanged();
}
/**
* Delete all the items
* */
public void clear() {
if (!listSongs.isEmpty()) {
listSongs.clear();
notifyDataSetChanged();
}
}
public Song getItemAtPosition(int position){
return listSongs.get(position);
}
public interface OnItemClickListener {
void onItemClick(Song item);
}
public class TopSongsViewHolder extends RecyclerView.ViewHolder{
@Bind(R.id.top_song_image)
SimpleDraweeView topSongImage;
@Bind(R.id.top_song_name)
TextView topSongName;
@Bind(R.id.top_song_rating)
TextView topSongRating;
@Bind(R.id.top_song_playcount)
TextView topSongPlaycount;
// @Bind(R.id.top_song_listeners)
// TextView topSongListeners;
public TopSongsViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
// Drawable progress = topSongRating.getProgressDrawable();
// DrawableCompat.setTint(progress, Color.rgb(255,50,120));
}
public void setImage(Context context, String urlImage){
Uri uri = Uri.parse(urlImage);
topSongImage.setImageURI(uri);
}
public void setName(String name){
this.topSongName.setText(name);
}
public void setTopSongRating(float rating){
this.topSongRating.setText(rating + "");
}
public void setPlayCount(int playCount){
this.topSongPlaycount.setText(playCount + "");
}
public void bind(final Song item, final OnItemClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
listener.onItemClick(item);
}
});
}
}
}
| true |
9da2d53e62fad5bb9f27a0c22d7a673302150913
|
Java
|
zhanglianxin123/hat
|
/4.2-后端代码/hat/src/main/java/com/qrs/service/IPositioningService.java
|
UTF-8
| 665 | 1.875 | 2 |
[] |
no_license
|
package com.qrs.service;
import com.qrs.pojo.DTO.PointDTO;
import com.qrs.pojo.DTO.TimeDTO;
import com.qrs.pojo.Positioning;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author zlx
* @since 2021-06-17
*/
public interface IPositioningService extends IService<Positioning> {
/**
* 获得人员当天定位
* @param equipment_id
* @param time
* @return
*/
List<PointDTO> getPoint(Integer equipment_id, String time);
/**
* 获得历史定位
* @param equipment_id
* @return
*/
List<TimeDTO> getList(Integer equipment_id);
}
| true |
385c8bb038c22fdd20763db461320f7a52357af7
|
Java
|
451311677/vblog
|
/blog-server-8080/src/main/java/com/xaut/blog/controller/CareController.java
|
UTF-8
| 1,013 | 2.0625 | 2 |
[] |
no_license
|
package com.xaut.blog.controller;
import com.xaut.blog.entity.CommonResult;
import com.xaut.blog.entity.User;
import com.xaut.blog.service.CareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.UUID;
/**
* @author zxg
* @date 2021/4/28
* @description
*/
@Controller
@RequestMapping("/care")
public class CareController {
@Autowired
private CareService careService;
@GetMapping("/user/{id}")
public CommonResult<?> getCareList(@PathVariable("id") Long userId){
List<User> careList = careService.getCareList(userId);
if(careList!=null){
return new CommonResult<>(200, "查询成功", careList);
}
return new CommonResult<>(400,"查询失败");
}
}
| true |
db81b257447ebc21965994a93022cbb7fb9724c3
|
Java
|
nobezawa/JavaDesignPattern
|
/JavaAbstractFactory/src/MainClass.java
|
UTF-8
| 678 | 2.8125 | 3 |
[] |
no_license
|
/**
* AbstractFactory
*
* 元となるオブジェクト(今回はFactoryClass)を生成して、さまざまなオブジェクト生成できる。
* また、FactoryClassを変更することで、継承したオブジェクトを一気に変更することも可能。
*
*/
public class MainClass {
public static void main(String args[]){
HotPot hotPot = new HotPot(new Pot());
Factory factory = new MizutakiFactory();
hotPot.addSoup(factory.getSoup());
hotPot.addMain(factory.getProtein());
hotPot.addVegetables(factory.getVegetables());
hotPot.addOtherlngredients(factory.getOtherlngredients());
}
}
| true |
3a2f7218e0046c785fe0e847afb2d28f07208b32
|
Java
|
NorbertoTaveras/flixiago-java
|
/flixiago/app/src/main/java/com/norbertotaveras/flixiago/models/base/PersonImage.java
|
UTF-8
| 450 | 2.328125 | 2 |
[] |
no_license
|
package com.norbertotaveras.flixiago.models.base;
import com.norbertotaveras.flixiago.helpers.InternetImage;
import com.norbertotaveras.flixiago.helpers.TmdbUrls;
public class PersonImage implements InternetImage {
private String file_path;
@Override
public String getThumbnailUrl() {
return TmdbUrls.IMAGE_BASE_URL_342px + file_path;
}
@Override
public String getThumbnailCaption() {
return null;
}
}
| true |
37467ad4fe16207d09a7c07eedc9c1dc2105f3f3
|
Java
|
stephenedwardgit/OCR_Read
|
/java-data-structures/src/main/java/com/mani/sorting/algorithm/SelectionSort.java
|
UTF-8
| 1,984 | 3.796875 | 4 |
[] |
no_license
|
package com.mani.sorting.algorithm;
public class SelectionSort {
public void selectioSort(int array[]){
int n= array.length;
for (int i =0; i<n-1; i++){
int minIndex =i;
for(int j=i+1; j<n;j++){
if(array[j]<array[minIndex]){
minIndex =j;
int temp=array[minIndex];
array[minIndex] =array[i];
array[i] =temp;
}
}
}
}
public static void sortAscending(final int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minElementIndex = i; // Start with 0 position
for (int j = i + 1; j < arr.length; j++) { // start from 1st postion of the Array
if (arr[minElementIndex] > arr[j]) {
minElementIndex = j;
}
}
if (minElementIndex != i) {
int temp = arr[i];
arr[i] = arr[minElementIndex];
arr[minElementIndex] = temp;
}
}
}
public static void sortDescending(final int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int maxElementIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[maxElementIndex] < arr[j]) {
maxElementIndex = j;
}
}
if (maxElementIndex != i) {
int temp = arr[i];
arr[i] = arr[maxElementIndex];
arr[maxElementIndex] = temp;
}
}
}
}
// Time Complexity
//Best: ?(n^2)
// Average: ?(n^2)
// Worst: O(n^2)
// Space Complexity
// O(1)
// Selection Sort begins with the element in the 1st position of an unsorted array and scans through subsequent elements to find the smallest element.
// Once found, the smallest element is swapped with the element in the 1st position.
| true |
d4aa078570189942cea2b8219c599d9c36ffab07
|
Java
|
SparkleX/poc
|
/apps-service/src/main/java/com/next/apps/service/ServiceBase.java
|
UTF-8
| 1,776 | 2.265625 | 2 |
[] |
no_license
|
package com.next.apps.service;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.web.bind.annotation.RequestBody;
import com.querydsl.core.types.Predicate;
@SuppressWarnings("unchecked")
public class ServiceBase<T_Bean, T_Repo extends QuerydslPredicateExecutor<T_Bean>>
{
@Autowired
T_Repo repo;
public Iterable<T_Bean> findAll(Predicate predicate)
{
return repo.findAll(predicate);
}
public Optional<T_Bean> get(Integer id)
{
JpaRepository<T_Bean,Object> repoJpa = (JpaRepository<T_Bean,Object>)repo;
Optional<T_Bean> data = repoJpa.findById(id);
if (!data.isPresent())
throw new RuntimeException("no data found id:" + id);
return data;
}
public void create(@RequestBody T_Bean data) {
JpaRepository<T_Bean,Object> repoJpa = (JpaRepository<T_Bean,Object>)repo;
T_Bean savedData = repoJpa.save(data);
/* URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(100).toUri();
return ResponseEntity.created(location).build();*/
}
public void update(T_Bean data, Integer id) {
JpaRepository<T_Bean,Object> repoJpa = (JpaRepository<T_Bean,Object>)repo;
Optional<T_Bean> dataOptional = repoJpa.findById(id);
// if (!dataOptional.isPresent())
// return ResponseEntity.notFound().build();
repoJpa.save(data);
// return ResponseEntity.noContent().build();
}
public void delete(Integer id)
{
JpaRepository<T_Bean,Object> repoJpa = (JpaRepository<T_Bean,Object>)repo;
repoJpa.deleteById(id);
}
}
| true |
d31a111b30fb0b19ff44ae6409c4659fcb26ca27
|
Java
|
bernardwkw/LTPSPBTSystem
|
/app/src/main/java/hua/tung/spbt/ltp/ltpspbtsystem/ReadExcel.java
|
UTF-8
| 2,963 | 2.484375 | 2 |
[] |
no_license
|
package hua.tung.spbt.ltp.ltpspbtsystem;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
/**
* Created by User on 31/10/2017.
*/
public class ReadExcel {
private static final String EXCEL_FILE_LOCATION = Environment.getExternalStorageDirectory()+"/LTPSPBT/lars.xls";
private String dir;
public void setReadLocation(String dir){
this.dir = dir;
}
public void read() {
Workbook workbook = null;
try {
workbook = Workbook.getWorkbook(new File(this.dir));
Sheet sheet = workbook.getSheet(0);
boolean isLast = true;
int cellNumber = 0;
boolean afterStudentData = false;
do {
Cell cell1 = sheet.getCell(0, cellNumber);
System.out.print(cell1.getContents() + ":"); // Test Count + :
Cell cell2 = sheet.getCell(1, cellNumber);
System.out.println(cell2.getContents());
Cell cell3 = sheet.getCell(2, cellNumber);
System.out.println(cell3.getContents());
if(cell1.getContents().contains("No"))
afterStudentData = true;
if(afterStudentData){
if (cell1.getContents().equals("") ){
Log.e("nothing", "here");
isLast = false;
}
}
cellNumber++;
}while (isLast);
// 1
// Cell cell3 = sheet.getCell(2, 13);
// System.out.println(cell3.getContents());
// Cell cell4 = sheet.getCell(3, 13);
// System.out.println(cell4.getContents());
// Cell cell3 = sheet.getCell(1, 0);
// System.out.print(cell3.getContents() + ":"); // Result + :
// Cell cell4 = sheet.getCell(1, 1);
// System.out.println(cell4.getContents()); // Passed
//
// System.out.print(cell1.getContents() + ":"); // Test Count + :
// cell2 = sheet.getCell(0, 2);
// System.out.println(cell2.getContents()); // 2
//
// System.out.print(cell3.getContents() + ":"); // Result + :
// cell4 = sheet.getCell(1, 2);
// System.out.println(cell4.getContents()); // Passed 2
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} finally {
if (workbook != null) {
workbook.close();
}
}
}
public File[] getFolderFiles(String directory){
// ArrayList<String> files = new ArrayList<>();
// files.add();
File f = new File(directory);
File files[] = f.listFiles();
return files;
}
}
| true |
0a2d5d94e4472525c32e8836245dc335bc122653
|
Java
|
Rinori99/ScheduleAndPresence
|
/src/main/java/server/DTOs/TeacherPresenceTransport.java
|
UTF-8
| 1,221 | 2.375 | 2 |
[
"MIT"
] |
permissive
|
package server.DTOs;
import server.annotations.ApiEntity;
@ApiEntity
public class TeacherPresenceTransport {
private String id;
private String teacherId;
private String dtfiId;
private boolean held;
public TeacherPresenceTransport() {
}
public TeacherPresenceTransport(String teacherId, String dtfiId, boolean held) {
this.teacherId = teacherId;
this.dtfiId = dtfiId;
this.held = held;
}
public TeacherPresenceTransport(String id, String teacherId, String dtfiId, boolean held) {
this.id = id;
this.teacherId = teacherId;
this.dtfiId = dtfiId;
this.held = held;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTeacherId() {
return teacherId;
}
public void setTeacherId(String teacherId) {
this.teacherId = teacherId;
}
public String getDtfiId() {
return dtfiId;
}
public void setDtfiId(String dtfiId) {
this.dtfiId = dtfiId;
}
public boolean isHeld() {
return held;
}
public void setHeld(boolean held) {
this.held = held;
}
}
| true |
2918cc634dbdd77c3c3e478ee99839dd6a2dcc28
|
Java
|
TC-0120/tc_recruit
|
/tc_ats/src/main/java/jp/co/tc/recruit/controller/RecruitmentManagementController.java
|
UTF-8
| 11,492 | 1.835938 | 2 |
[] |
no_license
|
package jp.co.tc.recruit.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import jp.co.tc.recruit.entity.Candidate;
import jp.co.tc.recruit.entity.selection.Selection;
import jp.co.tc.recruit.entity.selection.Selection.SelectionPK;
import jp.co.tc.recruit.form.CandidateForm;
import jp.co.tc.recruit.form.ConditionsForm;
import jp.co.tc.recruit.repository.CandidateListRepository;
import jp.co.tc.recruit.service.AgentService;
import jp.co.tc.recruit.service.AptitudeService;
import jp.co.tc.recruit.service.CandidateService;
import jp.co.tc.recruit.service.CandidatesViewService;
import jp.co.tc.recruit.service.SelectionReferrerService;
import jp.co.tc.recruit.service.SelectionService;
import jp.co.tc.recruit.service.SelectionStatusDetailService;
import jp.co.tc.recruit.service.SelectionStatusService;
import jp.co.tc.recruit.service.educational.DepartmentService;
import jp.co.tc.recruit.service.educational.FacultyService;
import jp.co.tc.recruit.service.educational.UniversityRankService;
import jp.co.tc.recruit.service.educational.UniversityService;
import jp.co.tc.recruit.util.BeanCopy;
import jp.co.tc.recruit.util.DateFormatter;
/**
* 採用情報管理機能のコントローラー
*
* @author TC-0120
*
*/
@Controller
@RequestMapping("/recruit/candidates")
public class RecruitmentManagementController {
@Autowired
CandidatesViewService candidatesViewService;
@Autowired
CandidateListRepository candidateListRepository;
@Autowired
SelectionReferrerService selectionReferrerService;
@Autowired
SelectionStatusService slcStatusService;
@Autowired
SelectionStatusDetailService slcStatusDtlService;
@Autowired
AgentService agentService;
@Autowired
UniversityService universityService;
@Autowired
FacultyService facultyService;
@Autowired
DepartmentService departmentService;
@Autowired
UniversityRankService universityRankService;
@Autowired
AptitudeService aptitudeService;
@Autowired
CandidateService candidateService;
@Autowired
SelectionService selectionService;
//候補者画面マスタID(固定)
private final int candidateListId = 1;
/**
* 候補者一覧画面での候補者情報の検索、表示
*
* @param conditionsForm 検索条件
* @param model
* @return 一覧画面
*/
@GetMapping
public String index(@ModelAttribute("conditionsForm") ConditionsForm conditionsForm, Model model) {//
//入力された検索条件から候補者情報を取得、格納
model.addAttribute("candidates",
candidatesViewService.findBySlcStatusIdAndSlcStatudDtlIdAndSlcDate(conditionsForm));
//検索ドロップダウン用のリスト(選考ステータス、詳細)を格納
model.addAttribute("slcStatusList", slcStatusService.findAll());
model.addAttribute("slcStatusDtlList", slcStatusDtlService.findAll());
model.addAttribute("slcReferrerList", selectionReferrerService.findAll());
model.addAttribute("candidateList", candidateListRepository.getOne(candidateListId));
return "recruitment_management";
}
/**
* 候補者情報登録入力画面への遷移
*
* @param model
* @return 候補者情報登録入力画面
*/
@GetMapping("register")
public String transitionToCandidateRegisterInputScreen(Model model) {
//入力ドロップダウン用のリスト(採用エージェント、紹介元)を格納
model.addAttribute("agentList", agentService.findAll());
//入力ドロップダウン用のリスト(大学マスタ)を格納
model.addAttribute("universityList", universityService.findAll());
//入力ドロップダウン用のリスト(学部マスタ)を格納
model.addAttribute("facultyList", facultyService.findAll());
//入力ドロップダウン用のリスト(学科マスタ)を格納
model.addAttribute("departmentList", departmentService.findAll());
//入力ドロップダウン用のリスト(大学ランクマスタ)を格納
model.addAttribute("universityRankList", universityRankService.findAll());
//入力ドロップダウン用のリスト(適性検査)を格納
model.addAttribute("aptitudeList", aptitudeService.findAll());
return "candidate/register_input";
}
/**
* 候補者情報を登録
*07/14 鶴 フォームクラスの導入
*
* @param candidate 候補者情報
* @param slcDate 選考日程
* @return 候補者情報登録入力画面
*/
@PostMapping
public String registerCandidate(@ModelAttribute CandidateForm candidateForm,
@RequestParam("slcDate") String slcDate) {
//候補者情報をエンティティにコピー
Candidate candidate = BeanCopy.copyFormToEntity(candidateForm);
//候補者情報を登録
candidateService.register(candidate, slcDate);
//選考情報を登録
selectionService.register(candidate.getCandidateId(), candidate.getSlcStatus().getSlcStatusId(), slcDate);
return "redirect:/recruit/candidates/register";
}
/**
* 候補者情報変更入力画面への遷移
*
* @param id 候補者ID
* @param model
* @return 候補者情報変更入力画面
*/
@GetMapping("update/{candidateId}")
public String transitionToCandidateUpdateInputScreen(@PathVariable("candidateId") Integer cId, Model model) {
//候補者IDから候補者情報を取得、格納
model.addAttribute("candidate", candidateService.findById(cId));
//入力ドロップダウン用のリスト(採用エージェント、紹介元)を格納
model.addAttribute("agentList", agentService.findAll());
//入力ドロップダウン用のリスト(大学マスタ)を格納
model.addAttribute("universityList", universityService.findAll());
//入力ドロップダウン用のリスト(学部マスタ)を格納
model.addAttribute("facultyList", facultyService.findAll());
//入力ドロップダウン用のリスト(学科マスタ)を格納
model.addAttribute("departmentList", departmentService.findAll());
//入力ドロップダウン用のリスト(大学ランクマスタ)を格納
model.addAttribute("universityRankList", universityRankService.findAll());
//入力ドロップダウン用のリスト(適性検査)を格納
model.addAttribute("aptitudeList", aptitudeService.findAll());
//検索ドロップダウン用のリスト(選考ステータス、詳細)を格納
model.addAttribute("slcStatusList", slcStatusService.findAll());
model.addAttribute("slcStatusDtlList", slcStatusDtlService.findAll());
model.addAttribute("slcReferrerList", selectionReferrerService.findAll());
model.addAttribute("slcDate",
selectionService.updatePrepare(cId, candidateService.findById(cId).getSlcStatus().getSlcStatusId()));
model.addAttribute("selectionList", selectionService.findBycandidateId(cId));
//System.out.println("選考日程リスト" + selectionService.findBycandidateId(cId).size());
return "candidate/update_input";
}
/**
* 候補者情報を変更
*
*
* @param id 候補者ID
* @param candidate 候補者情報
* @return 候補者情報変更入力画面
*/
@PostMapping("update")
public String updateCandidate(@ModelAttribute CandidateForm candidateForm, @RequestParam("slcDate") String slcDate,
RedirectAttributes redirectAttributes) {
//候補者情報をエンティティにコピー
Candidate candidate = BeanCopy.copyFormToEntity(candidateForm);
//候補者情報を変更
candidateService.update(candidate);
//選考情報を登録
selectionService.update(candidate.getCandidateId(), candidate.getSlcStatus().getSlcStatusId(), slcDate);
redirectAttributes.addAttribute("candidateId", candidate.getCandidateId());
return "redirect:/recruit/candidates/update/" + candidate.getCandidateId();
}
/**
* 候補者情報を削除
*
* @param id 候補者ID
* @return 一覧画面
*/
@GetMapping("{id}/delete")
public String delete(@PathVariable Integer id) {
//候補者情報を削除
candidateService.delete(id);
//選考情報を削除
selectionService.deleteByCandidateId(id);
return "redirect:/recruit/candidates";
}
/**
* 選考情報変更画面への遷移
*
* @param cId 候補者ID
* @param model
* @return 選考情報変更画面
*/
@GetMapping("selection")
public String transitionToSlcInfoUpdateInputScreen(@RequestParam("candidateId") Integer cId, Model model) {
//候補者IDから候補者情報を取得
Candidate candidate = candidateService.findById(cId);
//候補者IDと選考ステータスIDから選考情報を取得
Integer sId = candidate.getSlcStatus().getSlcStatusId();
SelectionPK slcPK = new SelectionPK(cId, sId);
Selection slc = selectionService.findById(slcPK);
//候補者情報、選考情報を格納
model.addAttribute("candidate", candidate);
model.addAttribute("selection", slc);
//選考日程をDate型からString型に変換、格納
model.addAttribute("slcDateString", DateFormatter.toString(slc.getSlcDate()));
//選考結果を候補者情報から取得、格納
model.addAttribute("slcResult", candidate.getSlcStatusDtl().getSlcStatusDtlId());
//検索ドロップダウン用のリスト(選考ステータス、詳細)を格納
model.addAttribute("slcStatusList", slcStatusService.findAll());
model.addAttribute("slcStatusDtlList", slcStatusDtlService.findAll());
model.addAttribute("slcReferrerList", selectionReferrerService.findAll());
// 日程が登録された候補者情報を取得、格納
//model.addAttribute("candidatesHasSlcDate", candidatesViewService.findByIsRegisteredSlcDate());
return "selection/update_input";
}
/**
* 選考情報を変更
*
* @param slcResult 選考結果
* @param slc 選考情報
* @param slcDate 選考日程
* @return 一覧画面
*/
@PostMapping("selection")
public String updateSlcInfo(@RequestParam("slcResult") Integer slcResult, @ModelAttribute Selection slc,
@RequestParam("slcDateString") String slcDateString, RedirectAttributes redirectAttributes, Integer slcStatus) {
//System.out.println("登録ステータス:" + slcStatus);
//選考情報を変更
selectionService.update(slc.getSlcPK().getCandidateId(), slcStatus ,slcDateString);
//選考ステータスを変更
candidateService.updateSlcStatusDtl(slc.getSlcPK().getCandidateId(), slcResult, slcDateString);
redirectAttributes.addAttribute("candidateId", slc.getSlcPK().getCandidateId());
return "redirect:/recruit/candidates/selection";
}
/**
* 選考ステータスの繰り上げ
*
* @param cId 候補者ID
* @param redirectAttributes
* @return 選考情報変更画面
*/
@PostMapping("seleciton/nextStatus")
public String promoteSlcStatus(@RequestParam("candidateId") Integer cId, RedirectAttributes redirectAttributes) {
//選考ステータスを繰り上げる
candidateService.promoteSlcStatus(cId);
//選考情報変更画面に遷移
redirectAttributes.addAttribute("candidateId", cId);
return "redirect:/recruit/candidates/selection";
}
}
| true |
cf83420711aef6283c8b5e9f01ae1d9cbb6761c0
|
Java
|
Ren650119726/cloud
|
/cloud-uc/cloud-uc-biz/src/main/java/com/xxxJppp/cloud/uc/biz/service/impl/MemLoginServiceImpl.java
|
UTF-8
| 2,475 | 2.09375 | 2 |
[] |
no_license
|
package com.xxxJppp.cloud.uc.biz.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxJppp.cloud.common.model.SecurityUser;
import com.xxxJppp.cloud.uc.biz.dao.MemLoginMapper;
import com.xxxJppp.cloud.uc.api.entity.MemLogin;
import com.xxxJppp.cloud.uc.biz.service.IMemLoginService;
import com.xxxJppp.cloud.uc.biz.service.ISysMenuService;
import com.xxxJppp.cloud.uc.biz.service.ISysPermissionService;
import com.xxxJppp.cloud.uc.biz.service.ISysRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
import java.util.stream.Collectors;
/**
* <p>
* 会员登录账号 服务实现类
* </p>
*
* @author xxxJppp
* @since 2020-06-17
*/
@Service
public class MemLoginServiceImpl extends ServiceImpl<MemLoginMapper, MemLogin> implements IMemLoginService {
@Autowired
private ISysPermissionService permissionService;
@Override
public MemLogin findByUserName(String username) {
LambdaQueryWrapper<MemLogin> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(MemLogin::getLoginname,username);
return getOne(queryWrapper);
}
@Override
public MemLogin findUserByUserIdOrUserNameOrMobile(String userIdOrUserNameOrMobileOrEmail) {
LambdaQueryWrapper<MemLogin> select = Wrappers.<MemLogin>lambdaQuery()
.eq(MemLogin::getLoginname, userIdOrUserNameOrMobileOrEmail)
.or()
.eq(MemLogin::getId, userIdOrUserNameOrMobileOrEmail);
return baseMapper.selectOne(select);
}
@Override
public SecurityUser findUserInfo(MemLogin user) {
// 权限集合
// 角色集合
Set<String> roles = permissionService.getRolePermission(user.getId());
// 权限集合
Set<String> permissions = permissionService.getMenuPermission(user.getId());
SecurityUser securityUser = new SecurityUser(user.getId(), user.getLoginname(),
user.getPassword(), permissions, roles);
BeanUtil.copyProperties(user, securityUser);
securityUser.setAccno(user.getAccno());
return securityUser;
}
}
| true |
4b1ec0ea5a4fe0b3db39dfcaa593a70585283217
|
Java
|
Chaussure-org/eis-yq-plg
|
/eis-yqfs-parent/eis-yqfs-facade/src/main/java/com/prolog/eis/dto/hxdispatch/HxCengDto.java
|
UTF-8
| 525 | 1.921875 | 2 |
[] |
no_license
|
package com.prolog.eis.dto.hxdispatch;
public class HxCengDto {
private int ceng;
private int ckLxCount;//出库料箱数
private int rkLxCount;//入库料箱数
public int getCeng() {
return ceng;
}
public void setCeng(int ceng) {
this.ceng = ceng;
}
public int getCkLxCount() {
return ckLxCount;
}
public void setCkLxCount(int ckLxCount) {
this.ckLxCount = ckLxCount;
}
public int getRkLxCount() {
return rkLxCount;
}
public void setRkLxCount(int rkLxCount) {
this.rkLxCount = rkLxCount;
}
}
| true |
172cf7306ac5d633e711b19cc43c0a1cca342b45
|
Java
|
sarahsekkat/ProjetBigDataBinome
|
/microservices-api/spring-reactive-mongoapi/src/main/java/com/inti/formation/shop/api/repository/IProductRepository.java
|
UTF-8
| 651 | 1.84375 | 2 |
[] |
no_license
|
package com.inti.formation.shop.api.repository;
import com.inti.formation.shop.api.repository.model.Customer;
import com.inti.formation.shop.api.repository.model.Product;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
@Repository
public interface IProductRepository extends ReactiveMongoRepository<Product, Long> {
// Flux<Product> findByLibelle(String libelle);
//
// @Query(value = "{'origine': {$eq: 'France'}}")
// Flux<Customer> findByCustomerAge(final int age);
}
| true |
071db7c5b53403027429633f2051336033ecedb4
|
Java
|
xyzwc110120/object_practice
|
/src/dataStructure/linkedListDemo/LinkedListDemo.java
|
UTF-8
| 559 | 3.078125 | 3 |
[] |
no_license
|
package dataStructure.linkedListDemo;
public class LinkedListDemo {
public static void main(String[] args) {
MyLinkedList linkedList = new MyLinkedList();
linkedList.addLast("C");
System.out.println(linkedList);
linkedList.addFirst("B");
linkedList.addLast("D");
linkedList.remove("C");
linkedList.addFirst("A");
System.out.println(linkedList);
linkedList.update("D", "E");
System.out.println(linkedList);
System.out.println(linkedList.search("B").ele);
}
}
| true |
21acc97bf994b2ed699f026b143ac7f1bd33e788
|
Java
|
Antonasd/stream-processing
|
/src/main/java/KubeScale/Events/Serdes/MetaDataSerde.java
|
UTF-8
| 2,137 | 2.3125 | 2 |
[] |
no_license
|
package KubeScale.Events.Serdes;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.common.errors.SerializationException;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import KubeScale.Events.JsonPOJOSerializer;
import KubeScale.Events.MetaData;
public class MetaDataSerde<T> implements Serde<MetaData<T>>{
Serializer<MetaData<T>> serializer;
Deserializer<MetaData<T>> deserializer;
public MetaDataSerde(Class<T> contentType) {
deserializer = new MetaDataDeserializer<T>(contentType);
Map<String, Object> serdeProps = new HashMap<>();
serializer = new JsonPOJOSerializer<>();
serdeProps.put("JsonPOJOClass", MetaData.class);
serializer.configure(serdeProps, false);
}
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
// TODO Auto-generated method stub
}
@Override
public void close() {
// TODO Auto-generated method stub
}
@Override
public Serializer<MetaData<T>> serializer() {
return serializer;
}
@Override
public Deserializer<MetaData<T>> deserializer() {
return deserializer;
}
}
class MetaDataDeserializer<T> implements Deserializer<MetaData<T>> {
private final ObjectMapper objectMapper = new ObjectMapper();
private Class<T> contentType;
public MetaDataDeserializer (Class<T> contentType) {
this.contentType = contentType;
}
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
// TODO Auto-generated method stub
}
@Override
public MetaData<T> deserialize(String topic, byte[] data) {
MetaData<T> obj = null;
if (data == null)
return null;
try {
obj = objectMapper.readValue(data, objectMapper.getTypeFactory().constructParametricType(MetaData.class, contentType));
} catch (Exception e) {
throw new SerializationException(e);
}
return obj;
}
@Override
public void close() {
// TODO Auto-generated method stub
}
}
| true |
d4e926abc259e696376906c2bacf90de17f0721b
|
Java
|
zhouxianjun/payment
|
/src/main/java/com/gary/payment/service/impl/unionpay/DefaultUnionPayUPOP.java
|
UTF-8
| 5,131 | 2.125 | 2 |
[] |
no_license
|
package com.gary.payment.service.impl.unionpay;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import chinapay.PrivateKey;
import chinapay.SecureLink;
import com.gary.payment.dto.OrderRequest;
import com.gary.payment.dto.PayRequest;
import com.gary.payment.dto.PayResponse;
import com.gary.payment.PaymentException;
import com.gary.payment.account.unionpay.UnionPayUPOPThirdAccount;
import com.gary.payment.service.AbstractRechargeService;
import com.gary.payment.service.RechargeService;
import com.gary.payment.util.Utils;
/**
* 银联无卡支付
* @ClassName: UnionPayUPOP
* @Description:
* @author zhouxianjun(Gary)
* @date 2014-12-19 下午2:07:44
*
*/
public abstract class DefaultUnionPayUPOP extends AbstractRechargeService implements RechargeService {
@Autowired(required = false)
private UnionPayUPOPThirdAccount unionPayUPOPThirdAccount;
public OrderRequest payment(PayRequest request) throws PaymentException {
//订单号
String orderId = request.getOrderNo();
String money = Utils.parseMoney(request.getAmount(), 12);
String merId = unionPayUPOPThirdAccount.getMerId();
String curyId = unionPayUPOPThirdAccount.getCuryId();
String transDate = Utils.toYYYYMMDD(new Date());
String transType = unionPayUPOPThirdAccount.getTransType();
//封装银联支付的参数
Map<String, String> parmMap = new HashMap<String, String>();
parmMap.put("MerId", merId);
parmMap.put("OrdId", orderId);
parmMap.put("TransAmt", money); //订单交易金额,12位长度,左补0,单位为分
parmMap.put("TransDate", transDate); //订单交易日期,8位长度
parmMap.put("TransType", transType); //交易类型:0001支付
parmMap.put("CpVersion", unionPayUPOPThirdAccount.getVersion()); //接入版本号V4
parmMap.put("CuryId", curyId); //订单交易币种,3位长度,固定为人民币156
parmMap.put("GateId", ""); //支付网关号
parmMap.put("PageRetUrl", unionPayUPOPThirdAccount.getPageRetUrl()); //页面交易接收URL,长度不要超过80个字节
parmMap.put("BgRetUrl", unionPayUPOPThirdAccount.getBgRetUrl()); //后台交易接收URL,长度不要超过80个字节
String priv1 = "";
if(request.getData().get("priv1") != null){
priv1 = (String)request.getData().get("priv1");
}
parmMap.put("Priv1", priv1); //私有自定义字段,银联原封不动回传
String chk = new SecureLink(getPrivateKey(merId)).Sign(merId + orderId + money + curyId + transDate + transType + priv1);
parmMap.put("ChkValue", chk); //256字节长的ASCII码,为此次交易提交关键数据的数字签名
logger.info("银联支付请求参数:{}", parmMap);
OrderRequest orderRequest = new OrderRequest();
orderRequest.setOrderNo(request.getOrderNo());
orderRequest.setParamMap(parmMap);
orderRequest.setPayUrl(unionPayUPOPThirdAccount.getPayUrl());
return orderRequest;
}
public PayResponse response(String type, Map<String, String> response) {
logger.info("返回银联无卡支付信息:{}", response);
//支付订单数据准备
String MerId = response.get("merid");
String OrdId = response.get("orderno");
String TransAmt = response.get("amount");// 12
String CuryId = response.get("currencycode");// 3
String TransDate = response.get("transdate");// 8
String TransType = response.get("transtype");// 4
String Status = response.get("status");
String GateId = response.get("GateId");
String ChkValue = response.get("checkvalue");
boolean verify = new SecureLink(getPrivateKey()).verifyTransResponse(MerId, OrdId, TransAmt, CuryId, TransDate, TransType, Status, ChkValue);
BigDecimal parseMoney = Utils.parseMoney(TransAmt, 12);
PayResponse payResponse = new PayResponse();
payResponse.setOrderNo(OrdId);
payResponse.setAmount(parseMoney);
payResponse.setFee(fee());
if(verify && "1001".equals(Status)){
logger.info("银联无卡支付充值结果:充值订单号{},充值返回值{},支付网关{}", new Object[] { OrdId, Status, GateId});
payResponse.setSuccess(true);
return payResponse;
}
payResponse.setSuccess(false);
payResponse.setErrorMsg("支付失败");
return payResponse;
}
private PrivateKey getPrivateKey(String MerId) {
try {
boolean buildOK = false;
PrivateKey key = new PrivateKey();
String path = unionPayUPOPThirdAccount.getPrivateKey();
buildOK = key.buildKey(MerId, 0, path);
return buildOK ? key : null;
} catch (Exception e) {
logger.error("银联支付私钥KEY错误", e);
return null;
}
}
private PrivateKey getPrivateKey(){
try {
boolean buildOK = false;
PrivateKey key = new PrivateKey();
String path = unionPayUPOPThirdAccount.getPublicKey();
buildOK = key.buildKey("999999999999999", 0, path);
return buildOK ? key : null;
} catch (Exception e) {
logger.error("银联支付公钥KEY错误", e);
return null;
}
}
}
| true |
776ff51064928eaa45df8abe4c8b20dbf2db1bce
|
Java
|
huohehuo/DGJS-FzApp
|
/app/src/main/java/com/fangzuo/assist/Fragment/HomeOneFragment.java
|
UTF-8
| 5,560 | 1.71875 | 2 |
[] |
no_license
|
package com.fangzuo.assist.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.fangzuo.assist.ABase.BaseFragment;
import com.fangzuo.assist.Activity.DealPic2Activity;
import com.fangzuo.assist.Activity.DealPicActivity;
import com.fangzuo.assist.Activity.Pic4ServerActivity;
import com.fangzuo.assist.Activity.SignActivity;
import com.fangzuo.assist.Activity.SetActivity;
import com.fangzuo.assist.Adapter.HomeOneAdapter;
import com.fangzuo.assist.Beans.SettingList;
import com.fangzuo.assist.R;
import com.fangzuo.assist.Utils.Config;
import com.fangzuo.assist.Utils.GetSettingList;
import com.fangzuo.assist.Utils.Lg;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import java.io.File;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import static com.fangzuo.assist.Activity.DealPicActivity.baseLoc;
public class HomeOneFragment extends BaseFragment {
@BindView(R.id.ry_data)
EasyRecyclerView ryData;
HomeOneAdapter adapter;
Unbinder unbinder;
private FragmentActivity mContext;
public HomeOneFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_home_one, container, false);
unbinder = ButterKnife.bind(this, v);
return v;
}
@Override
public void initView() {
mContext = getActivity();
//生成文件夹
File f = new File(baseLoc+"fangzuo");
if (!f.exists()) {
f.mkdir();
}
}
@Override
protected void OnReceive(String barCode) {
}
// P1OneAdapter adapter;
@Override
protected void initData() {
// String getPermit=share.getString(ShareInfo.USER_PERMIT);
// String[] arylist = getPermit.split("\\-"); // 这样才能得到正确的结果
ryData.setAdapter(adapter = new HomeOneAdapter(mContext));
ryData.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL, false));
adapter.addAll(GetSettingList.getAppList());
}
// private AlertDialog.Builder builder;
// String[] items_sout = new String[]{"原单", "销售订单下推销售出库单","VMI销售订单下推销售出库单","退货通知单下推销售退货单"};
// String[] items_tb = new String[]{"挑板领料1", "挑板入库1"};
// String[] items_tb2 = new String[]{"挑板领料2", "挑板入库2"};
// String[] items_tb3 = new String[]{"挑板领料3", "挑板入库3"};
// String[] items_pk = new String[]{"盘亏入库", "VMI盘亏入库"};
// String[] items_gb = new String[]{"改板领料", "改板入库"};
// String[] items_dc = new String[]{"代存出库", "代存入库"};
//// String[] items_db = new String[]{"组织间调拨", "跨组织调拨", "调拨申请单下推直接调拨单", "VMI调拨申请单下推直接调拨单"};
// String[] items_db = new String[]{"组织间调拨", "跨组织调拨", "调拨申请单下推直接调拨单"};
//// String[] items_in_out = new String[]{"样板出库", "第三方货物入库","第三方货物出库","出库申请单下推其他出库单"};
// String[] items_in_out = new String[]{"样板出库", "第三方货物入库","第三方货物出库"};
@Override
protected void initListener() {
adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
SettingList tv = (SettingList) adapter.getAllData().get(position);
Lg.e("listitem", tv);
switch (tv.activity) {
case Config.SetActivity://服务器地址设置
SetActivity.start(mContext);
break;
case Config.SignActivity://设置签名
SignActivity.start(mContext);
break;
case Config.DealPicActivity://处理图片
DealPicActivity.start(mContext,"");
break;
case Config.PicFromServerActivity://服务器图片
Pic4ServerActivity.start(mContext);
break;
case Config.DealPic2Activity://箱码调拨单
DealPic2Activity.start(mContext,"");
break;
}
}
});
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
/* @OnClick({R.id.cv_sign, R.id.cv_deal_pic, R.id.cv_setting, R.id.cv_history_pic})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.cv_sign:
SignActivity.start(mContext);
break;
case R.id.cv_deal_pic:
DealPicActivity.start(mContext);
break;
case R.id.cv_setting:
SetActivity.start(mContext);
break;
case R.id.cv_history_pic:
Pic4ServerActivity.start(mContext);
break;
}
}*/
}
| true |
06bce6c578bc4de16cb9db54baa6bf18b4e6150f
|
Java
|
surajseth90/Line-Comparison-Problem
|
/PP1_Line_Comparision_Problem/src/Comparision_Of_Two_Lines.java
|
UTF-8
| 1,222 | 3.8125 | 4 |
[] |
no_license
|
import java.util.*;
public class Comparision_Of_Two_Lines {
void comparision() {
Scanner sc = new Scanner(System.in);
System.out.println("please entre x coordinates of first line ");
int x11 = sc.nextInt();
int x12 = sc.nextInt();
System.out.println("please entre y coordinates of first line ");
int y11 = sc.nextInt();
int y12 = sc.nextInt();
System.out.println("please entre x coordinates of second line ");
int x21 = sc.nextInt();
int x22 = sc.nextInt();
System.out.println("please entre y coordinates of second line ");
int y21 = sc.nextInt();
int y22 = sc.nextInt();
Double length_of_line1 = Math.sqrt(((x11-x12)*(x11-x12))+((y11-y12)*(y11-y12)));
Double length_of_line2 = Math.sqrt(((x21-x22)*(x21-x22))+((y11-y12)*(y21-y22)));
if(length_of_line1.compareTo(length_of_line2)==0)
{
System.out.println("Lines are equal");
}
else if(length_of_line1.compareTo(length_of_line2)>0)
{
System.out.println("First line is bigger than Second line ");
}
else if(length_of_line1.compareTo(length_of_line2)<0)
{
System.out.println("Second line is bigger than first line ");
}
}
}
| true |
e8a285e81b5baef8be48fe62328121d97896fae3
|
Java
|
FlyingDog265/NetologyDiploma
|
/src/test/java/ru/netology/helpers/CardHelper.java
|
UTF-8
| 2,324 | 2.6875 | 3 |
[] |
no_license
|
package ru.netology.helpers;
public class CardHelper {
private CardHelper() {
}
private static final String approvedCardNumber = "4444 4444 4444 4441";
private static final String declinedCardNumber = "4444 4444 4444 4442";
private static final String validCardMonth = "08";
private static final String validCardYear = "22";
private static final String validCardOwner = "Ivanov Ivan";
private static final String validCardCvcCvv = "999";
public static Card getCardInfoWithApprovedCardNumber() {
return new Card(
approvedCardNumber, validCardMonth, validCardYear, validCardOwner, validCardCvcCvv);
}
public static Card getCardInfoWithDeclinedCardNumber() {
return new Card(
declinedCardNumber, validCardMonth, validCardYear, validCardOwner, validCardCvcCvv);
}
public static Card getCardInfoWithUnknownCardNumber() {
return new Card(
"5555 5555 5555 5555", validCardMonth, validCardYear, validCardOwner, validCardCvcCvv);
}
public static Card getCardInfoWithTooSmallYear() {
return new Card(
approvedCardNumber, validCardMonth, "12", validCardOwner, validCardCvcCvv);
}
public static Card getCardInfoWithTooBigYear() {
return new Card(
approvedCardNumber, validCardMonth, "55", validCardOwner, validCardCvcCvv);
}
public static Card getCardInfoWithTooSmallMonth() {
return new Card(
approvedCardNumber, "00", validCardYear, validCardOwner, validCardCvcCvv);
}
public static Card getCardInfoWithTooBigMonth() {
return new Card(
approvedCardNumber, "13", validCardYear, validCardOwner, validCardCvcCvv);
}
public static Card getCardInfoWithIncorrectCardNumber() {
return new Card(
"5555 5555", validCardMonth, validCardYear, validCardOwner, validCardCvcCvv);
}
public static Card getCardInfoWithIncorrectCvc() {
return new Card(
approvedCardNumber, validCardMonth, validCardYear, validCardOwner, "0");
}
public static Card getCardInfoWithIncorrectOwnerByCyrillic() {
return new Card(
approvedCardNumber, validCardMonth, validCardYear, "Иванов Иван", validCardCvcCvv);
}
}
| true |
981979d52056d6f94511d8352038af95a56b550d
|
Java
|
xchromosome219/Portfolio
|
/Artificial Intelligence/Missionaries and Cannibals/Main.java
|
UTF-8
| 1,493 | 3.84375 | 4 |
[] |
no_license
|
package proj1;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
State state;
state = initialization();
state = start(state);
displayResult(state);
}
// Set up the initialized state function
public static State initialization() {
int stateArr[];
stateArr = new int [3];
stateArr[0] = 3; stateArr[1] = 3; stateArr[2] = 1;
State initialState = new State(stateArr);
return initialState;
}
// Set up the limit as 20 for Depth Limited Search Algorithm
public static State start(State state) {
DepthLimitedSearch search = new DepthLimitedSearch();
int limit = 11;
State solution = search.run(state, limit);
return solution;
}
// Display the result
private static void displayResult(State solution) {
if(solution != null) {
List<State> path = new ArrayList<State>();
State state = solution;
while(state != null) { // put all the states into the stack
path.add(state);
state = state.getParentNode();
}
int[] currentState;
int depth = path.size() - 1;
System.out.println("Format: all on the right side\nMissionary, Cannibal, Boat(1)");
for (int i = depth; i >= 0; i--) {
state = path.get(i);
currentState = state.getcurrentState();
for (int j = 0; j < 3; j ++) {
System.out.printf("%d ", currentState[j]);
}
System.out.println("");
}
System.out.printf("Total depth : %d", depth);
} else System.out.print("\nNo solution found.");
}
}
| true |
d6b5d71559e66e266d43a1fdfa052a3fef9009ac
|
Java
|
danpouma/recommendation-engine
|
/src/engine/BooksDataLoader.java
|
UTF-8
| 1,682 | 3.203125 | 3 |
[] |
no_license
|
package engine;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
*
* @author dpoumakis
*/
public class BooksDataLoader
{
File userRatingFile;
FileInputStream instream;
DataInputStream bookData;
String line;
StringTokenizer stringTok;
ArrayList<Book> books;
public BooksDataLoader()
{
books = new ArrayList();
try
{
userRatingFile = new File("./BookList.txt");
instream = new FileInputStream(userRatingFile);
bookData = new DataInputStream(instream);
while (instream.available() > 0)
{
line = (String) bookData.readLine();
Book book = new Book();
stringTok = new StringTokenizer(line);
// Get the authors name
book.setAuthor(stringTok.nextToken(","));
String title = stringTok.nextToken("\n");
title = title.replace(",", "");
book.setTitle(title);
// Bug where first elem is nothing
// this fixes it for now :P
//ratings.remove(0);
// Give ratings to user
//user.setRatings(ratings);
// Add book to books
books.add(book);
}
// Close the streams
instream.close();
bookData.close();
}
catch (Exception e)
{
System.out.println("Error");
}
}
public ArrayList<Book> getBooks()
{
return books;
}
}
| true |
220e5a0efdef15835fd802a025919fc6b36070a8
|
Java
|
sonikvvv/Hotel
|
/hotel-project/base-classes/src/main/java/base_classes/classes/Room.java
|
UTF-8
| 3,601 | 2.5625 | 3 |
[] |
no_license
|
package base_classes.classes;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.PreRemove;
import javax.persistence.SequenceGenerator;
import base_classes.classes.emuns.SE;
@Entity(name = "room")
public class Room {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "room_generator")
@SequenceGenerator(name = "room_generator", sequenceName = "room_seq", allocationSize = 1)
private int r_id;
private String r_number;
private String r_type;
@Column(columnDefinition = "Number(10,2)")
private double price;
@ManyToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "c_id")
private List<Clients> clients = new ArrayList<>();
@Enumerated(EnumType.STRING)
private SE r_status;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "hotel_id")
private Hotel hotel;
public Room() {
}
public Room(String r_number, String r_type, double price, SE r_status) {
this.r_number = r_number;
this.r_type = r_type;
this.price = price;
this.r_status = r_status;
}
public Room(String r_number, String r_type, double price, SE r_status, Hotel hotel) {
this.r_number = r_number;
this.r_type = r_type;
this.price = price;
this.r_status = r_status;
this.hotel = hotel;
}
public List<Clients> getClients() {
return clients;
}
public double getPrice() {
return price;
}
public int getR_id() {
return r_id;
}
public String getR_number() {
return r_number;
}
public SE getR_status() {
return r_status;
}
public String getR_type() {
return r_type;
}
public Hotel getHotel() {
return hotel;
}
public void setClients(List<Clients> clients) {
this.clients = clients;
this.r_status = SE.OCCUPIED;
}
public void setPrice(double price) {
this.price = price;
}
public void setR_id(int r_id) {
this.r_id = r_id;
}
public void setR_number(String r_number) {
this.r_number = r_number;
}
public void setR_status(SE r_status) {
this.r_status = r_status;
}
public void setR_type(String r_type) {
this.r_type = r_type;
}
public void setHotel(Hotel hotel) {
this.hotel = hotel;
}
public void addToClients(Clients client) {
this.clients.add(client);
this.r_status = SE.OCCUPIED;
}
@PreRemove
public void detach() {
this.clients.forEach(client -> client = null);
this.hotel = null;
}
public static List<String> getFields() {
List<String> ls = new ArrayList<>();
ls.add("r_id");
ls.add("r_number");
ls.add("r_type");
ls.add("r_status");
ls.add("hotel");
ls.add("rait");
return ls;
}
public static String getTableName() {
return "room";
}
@Override
public String toString() {
return "Room [ id = " + this.r_id + " number: " + this.r_number + " type: "
+ this.r_type + " status: " + this.r_status + " ]";
}
}
| true |
b402e0184b36d4dc785cc1f74f66f573929844b0
|
Java
|
aanyas72/reminder-app
|
/backend/src/main/java/com/aanya/reminderapp/controller/model/User.java
|
UTF-8
| 1,456 | 2.046875 | 2 |
[] |
no_license
|
package com.aanya.reminderapp.controller.model;
import java.util.List;
public class User {
private Integer id;
private String username;
private String password;
private String accountType;
private List<Recipient> recipients;
private List<Reminder> reminders;
private List<Classs> classses;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public List<Recipient> getRecipients() {
return recipients;
}
public void setRecipients(List<Recipient> recipients) {
this.recipients = recipients;
}
public List<Reminder> getReminders() {
return reminders;
}
public void setReminders(List<Reminder> reminders) {
this.reminders = reminders;
}
public List<Classs> getClassses() {
return classses;
}
public void setClassses(List<Classs> classses) {
this.classses = classses;
}
}
| true |
b298ce9a805ef38f5a521420ef47252a221151b7
|
Java
|
NeilBuison/Software-Development
|
/Person.java
|
UTF-8
| 881 | 3.265625 | 3 |
[] |
no_license
|
public class Person
{
private String Fname;
private String Lname;
public String getName(){
return Fname;
}
public String getName(){
return Lname:
}
public class Person {
String fname;
String lname;
public static void main (String[]args){
Person p = new Person();
p.setFname("Neil Patrick");
p.setLname("Buison");
System.out.println(p.getFname());
System.out.println(p.getLname());
p.printDetails();
}
public void setFname(String Fname){
this.fname=fname;
}
public void setlname(String lname){
this.Lname=Lname;
}
public String getFname(){
return this.Fname;
}
public String getLname(){
return this.Lname;
}
public void printDetails(){
System.out.println(getFname + " " + getLname);
}
}
| true |
00a2f60121fbd0d86cf9a55bbf998724e2f366a8
|
Java
|
KingsleyYau/LiveClient
|
/android/QNLiveShow/liveshowApp/src/main/java/com/qpidnetwork/livemodule/view/dialog/CommonMultipleBtnTipDialog.java
|
UTF-8
| 10,923 | 1.992188 | 2 |
[] |
no_license
|
package com.qpidnetwork.livemodule.view.dialog;
import android.content.Context;
import android.support.annotation.ColorRes;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.qpidnetwork.livemodule.R;
import com.qpidnetwork.livemodule.liveshow.adapter.BaseRecyclerViewAdapter;
import com.qpidnetwork.livemodule.liveshow.adapter.BaseViewHolder;
import static android.util.TypedValue.COMPLEX_UNIT_SP;
/**
* Created by Hardy on 2019/5/28.
* <p>
* 通用的带提示文案 + 3 个按钮事件的 dialog
*/
public class CommonMultipleBtnTipDialog extends BaseCommonDialog {
public interface OnDialogItemClickListener {
void onItemSelected(View v, int which);
}
private LinearLayout mllBg;
private ImageView mTvTitleIcon;
private TextView mTvTitle;
private TextView mTvMessage;
private TextView mTvSubTitle;
private Button mBtnDone;
private RecyclerView itemsView;
private DialogItemAdapter itemAdapter;
private OnDialogItemClickListener onDialogItemClickListener;
public CommonMultipleBtnTipDialog(Context context) {
super(context, R.layout.dialog_say_hi_tip_multiple_btn);
}
@Override
public void initView(View v) {
mllBg = v.findViewById(R.id.dialog_common_multiple_ll_bg);
mTvTitleIcon = v.findViewById(R.id.dialog_common_multiple_btn_title_icon);
mTvTitle = v.findViewById(R.id.dialog_common_multiple_btn_title);
mTvMessage = v.findViewById(R.id.dialog_common_multiple_btn_message);
mTvSubTitle = v.findViewById(R.id.dialog_common_multiple_btn_sub_title);
itemsView = v.findViewById(R.id.dialog_common_multiple_btn_items);
itemsView.setNestedScrollingEnabled(false);
LinearLayoutManager manager = new LinearLayoutManager(mContext);
manager.setOrientation(LinearLayoutManager.VERTICAL);
itemsView.setLayoutManager(manager);
mBtnDone = v.findViewById(R.id.dialog_common_multiple_btn_done);
mBtnDone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
itemAdapter = new DialogItemAdapter(mContext);
itemAdapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
@Override
public void onItemClick(View v, int position) {
if (onDialogItemClickListener != null) {
onDialogItemClickListener.onItemSelected(v, position);
}
DialogItem dialogItem = itemAdapter.getItemBean(position);
if(dialogItem != null && dialogItem.isDismiss){
dismiss();
}
}
});
itemsView.setAdapter(itemAdapter);
}
@Override
public void initDialogAttributes(WindowManager.LayoutParams params) {
params.gravity = Gravity.CENTER;
params.width = getDialogNormalWidth();
setDialogParams(params);
}
/**
* 设置选项监听回调
*
* @param itemClickListener
*/
public void setItemClickCallback(OnDialogItemClickListener itemClickListener) {
this.onDialogItemClickListener = itemClickListener;
}
/**
* 设置背景
* @param resId
*/
public void setBgDrawable(int resId){
mllBg.setBackgroundResource(resId);
}
/**
* 设置标题
*/
public void setTitle(String title) {
mTvTitle.setText(title);
}
/**
* 设置内容
*/
public void setMessage(String message) {
mTvMessage.setVisibility(View.VISIBLE);
mTvMessage.setText(message);
}
/**
* 设置副标题
*/
public void setSubTitle(String message) {
mTvSubTitle.setVisibility(View.VISIBLE);
mTvSubTitle.setText(message);
}
/**
* 设置标题id
*
* @param resId
*/
public void setTitleIcon(int resId) {
mTvTitleIcon.setVisibility(View.VISIBLE);
mTvTitleIcon.setImageResource(resId);
}
/**
* 设置标题字体大小
*
* @param size
*/
public void setTitleSize(float size) {
mTvTitle.setTextSize(COMPLEX_UNIT_SP, size);
}
/**
* 设置标题文字颜色
*/
public void setTitleTextColor(@ColorRes int textColor) {
mTvTitle.setTextColor(ContextCompat.getColor(mContext, textColor));
}
/**
* 设置副标题字体大小
*
* @param size
*/
public void setSubTitleSize(float size) {
mTvSubTitle.setTextSize(COMPLEX_UNIT_SP, size);
}
/**
* 设置副标题文字颜色
*/
public void setSubTitleTextColor(@ColorRes int textColor) {
mTvSubTitle.setTextColor(ContextCompat.getColor(mContext, textColor));
}
/**
* 设置内容字体大小
*
* @param size
*/
public void setMessageSize(float size) {
mTvMessage.setTextSize(COMPLEX_UNIT_SP, size);
}
/**
* 设置内容文字颜色
*/
public void setMessageTextColor(@ColorRes int textColor) {
mTvMessage.setTextColor(ContextCompat.getColor(mContext, textColor));
}
/**
* 设置done按钮的文字颜色
*/
public void setBtnDoneTextColor(@ColorRes int textColor) {
mBtnDone.setTextColor(ContextCompat.getColor(mContext, textColor));
}
public void addItem(
String title,
int iconId) {
addItem(title, iconId, -1);
}
public void addItem(
String tag,
String title,
int iconId) {
addItem(tag, title, iconId, -1, -1, true);
}
public void addItem(
String tag,
String title,
int iconId,
boolean isDismiss) {
addItem(tag, title, iconId, -1, -1, isDismiss);
}
public void addItem(
String title,
int iconId,
int titleColor) {
addItem("", title, iconId, titleColor, -1, true);
}
public DialogItem getItem(String tag){
DialogItem item = null;
for(DialogItem dialogItem:itemAdapter.mList){
if(dialogItem.tag.equals(tag)){
item = dialogItem;
}
}
return item;
}
public void refresh(){
itemAdapter.notifyDataSetChanged();
}
/**
* 添加选项
*
* @param title
* @param iconId
* @param titleColor
* @param titleSize
*/
public void addItem(
String tag,
String title,
int iconId,
int titleColor,
float titleSize,
boolean isDismiss) {
DialogItem item = new DialogItem();
item.tag = tag;
item.itemIconId = iconId;
item.itemTitle = title;
item.itemTitleColor = titleColor;
item.itemTitleSize = titleSize;
item.isDismiss = isDismiss;
itemAdapter.addData(item);
}
public static class DialogItem {
private String tag = "";
private int itemIconId = -1;
private String itemTitle = "";
private int itemTitleColor = -1;
private float itemTitleSize = -1f;
private boolean isDismiss = true;
public void setItemIconId(int itemIconId) {
this.itemIconId = itemIconId;
}
public void setItemTitle(String itemTitle) {
this.itemTitle = itemTitle;
}
public void setItemTitleColor(int itemTitleColor) {
this.itemTitleColor = itemTitleColor;
}
public void setItemTitleSize(float itemTitleSize) {
this.itemTitleSize = itemTitleSize;
}
}
private static class DialogItemAdapter extends BaseRecyclerViewAdapter<DialogItem, DialogItemAdapter.DialogItemHolder> {
public DialogItemAdapter(Context context) {
super(context);
}
@Override
public int getLayoutId(int viewType) {
return R.layout.adapter_dialog_item_view;
}
@Override
public DialogItemHolder getViewHolder(View itemView, int viewType) {
return new DialogItemHolder(itemView);
}
@Override
public void initViewHolder(final DialogItemHolder holder) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(v, getPosition(holder));
}
}
});
}
@Override
public void convertViewHolder(DialogItemHolder holder,
DialogItem data,
int position) {
holder.setData(data, position);
}
private static class DialogItemHolder extends BaseViewHolder<DialogItem> {
private ImageView itemIcon;
private TextView itemTitle;
public DialogItemHolder(View itemView) {
super(itemView);
}
@Override
public void bindItemView(View itemView) {
itemIcon = f(R.id.item_icon);
itemTitle = f(R.id.item_title);
}
@Override
public void setData(DialogItem data,
int position) {
itemView.setTag(data.tag);
if (data.itemIconId > 0) {
itemIcon.setImageResource(data.itemIconId);
}
if (!TextUtils.isEmpty(data.itemTitle)) {
itemTitle.setText(data.itemTitle);
}
if (data.itemTitleColor > 0) {
itemTitle.setTextColor(ContextCompat.getColor(context, data.itemTitleColor));
}
if (data.itemTitleSize > 0) {
itemTitle.setTextSize(COMPLEX_UNIT_SP, data.itemTitleSize);
}
}
}
}
}
| true |
d6218eff77d7f82b92d19bc854091e2faecf15ef
|
Java
|
MarianaGiraldo/MisionTIC2022-P_Basica
|
/S6-RetoCovidPruebas/src/main/java/controller/MunicipioController.java
|
UTF-8
| 2,194 | 2.796875 | 3 |
[] |
no_license
|
package controller;
import Models.Departamento;
import Models.Municipio;
import Models.GeneralModel;
import java.util.List;
public class MunicipioController {
public static List<Municipio> getMunicipioList(){
List<Municipio> munList;
munList = new GeneralModel().getMunicipioList();
return munList;
}
public static Integer deleteMunicipio(Integer id) throws Exception{
Municipio mun = (Municipio) new Municipio().get(id);
return mun.delete();
}
public static Integer saveMunicipio(Integer id, Departamento departamento, String name, String code) throws Exception{
int codigo = 0;
Municipio new_mun = null;
try {
if( name.equals("") ){
throw new Exception("El campo nombre no puede estar vacio.");
}
if( name.length() > 100 ){
throw new Exception("El campo nombre solo puede tener 100 caracteres.");
}
} catch (Exception e) {
return null;
}
try{
codigo = Integer.parseInt(code);
} catch(NumberFormatException e){
System.err.println("El campo codigo debe ser un numero");;
return null;
}
try {
if( id == null ){
Municipio validar_mun = (Municipio) new Municipio().getMunicipioByCode(codigo);
if( validar_mun != null){
throw new Exception("El municipio con el codigo " + codigo + " ya existe.");
}
new_mun = new Municipio();
} else {
new_mun = (Municipio) new Municipio().get(id);
}
} catch (Exception e) {
return null;
}
new_mun.setCodigo( codigo );
new_mun.setNombre(name);
new_mun.setDepartamento(departamento);
new_mun.save();
return new_mun.getId();
}
public static Integer getMunicipio(Integer id) throws Exception{
Municipio mun = (Municipio) new Municipio().get(id);
return mun.getId();
}
}
| true |
d00e4fd104ab1fe4a77dc6e8f7ef4b971e6cf650
|
Java
|
edwin9870/CineRD
|
/app/src/main/java/com/edwin/android/cinerd/entity/db/MovieTheaterDetail.java
|
UTF-8
| 4,590 | 2.453125 | 2 |
[] |
no_license
|
package com.edwin.android.cinerd.entity.db;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Date;
/**
* Created by Edwin Ramirez Ventura on 7/24/2017.
*/
public class MovieTheaterDetail implements Parcelable {
private Long movieId;
private Short roomId;
private Integer theaterId;
private Short subtitleId;
private Date availableDate;
private Short formatId;
private Short languageId;
public Long getMovieId() {
return movieId;
}
public void setMovieId(Long movieId) {
this.movieId = movieId;
}
public Short getRoomId() {
return roomId;
}
public void setRoomId(Short roomId) {
this.roomId = roomId;
}
public Integer getTheaterId() {
return theaterId;
}
public void setTheaterId(Integer theaterId) {
this.theaterId = theaterId;
}
public Short getSubtitleId() {
return subtitleId;
}
public void setSubtitleId(Short subtitleId) {
this.subtitleId = subtitleId;
}
public Short getFormatId() {
return formatId;
}
public void setFormatId(Short formatId) {
this.formatId = formatId;
}
public Short getLanguageId() {
return languageId;
}
public void setLanguageId(Short languageId) {
this.languageId = languageId;
}
public Date getAvailableDate() {
return availableDate;
}
public void setAvailableDate(Date availableDate) {
this.availableDate = availableDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MovieTheaterDetail that = (MovieTheaterDetail) o;
if (!movieId.equals(that.movieId)) return false;
if (!roomId.equals(that.roomId)) return false;
if (!theaterId.equals(that.theaterId)) return false;
if (subtitleId != null ? !subtitleId.equals(that.subtitleId) : that.subtitleId != null)
return false;
if (!formatId.equals(that.formatId)) return false;
return languageId.equals(that.languageId);
}
@Override
public int hashCode() {
int result = movieId.hashCode();
result = 31 * result + roomId.hashCode();
result = 31 * result + theaterId.hashCode();
result = 31 * result + (subtitleId != null ? subtitleId.hashCode() : 0);
result = 31 * result + formatId.hashCode();
result = 31 * result + languageId.hashCode();
return result;
}
@Override
public String toString() {
return "MovieTheaterDetail{" +
"movieId=" + movieId +
", roomId=" + roomId +
", theaterId=" + theaterId +
", subtitleId=" + subtitleId +
", availableDate=" + availableDate +
", formatId=" + formatId +
", languageId=" + languageId +
'}';
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(this.movieId);
dest.writeValue(this.roomId);
dest.writeValue(this.theaterId);
dest.writeValue(this.subtitleId);
dest.writeLong(this.availableDate != null ? this.availableDate.getTime() : -1);
dest.writeValue(this.formatId);
dest.writeValue(this.languageId);
}
public MovieTheaterDetail() {
}
protected MovieTheaterDetail(Parcel in) {
this.movieId = (Long) in.readValue(Long.class.getClassLoader());
this.roomId = (Short) in.readValue(Short.class.getClassLoader());
this.theaterId = (Integer) in.readValue(Integer.class.getClassLoader());
this.subtitleId = (Short) in.readValue(Short.class.getClassLoader());
long tmpAvailableDate = in.readLong();
this.availableDate = tmpAvailableDate == -1 ? null : new Date(tmpAvailableDate);
this.formatId = (Short) in.readValue(Short.class.getClassLoader());
this.languageId = (Short) in.readValue(Short.class.getClassLoader());
}
public static final Parcelable.Creator<MovieTheaterDetail> CREATOR = new Parcelable
.Creator<MovieTheaterDetail>() {
@Override
public MovieTheaterDetail createFromParcel(Parcel source) {
return new MovieTheaterDetail(source);
}
@Override
public MovieTheaterDetail[] newArray(int size) {
return new MovieTheaterDetail[size];
}
};
}
| true |
57ce56ea35019e9df6122c21b03cd515c4392985
|
Java
|
monodot/camel-demos
|
/simple-tests/src/test/java/com/cleverbuilder/cameldemos/scenarios/PGPEncryptionTest.java
|
UTF-8
| 1,633 | 2.21875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.cleverbuilder.cameldemos.scenarios;
import org.apache.camel.EndpointInject;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
/**
* https://stackoverflow.com/questions/50610962/camel-2-21-0-pgp-encryption-not-working
*
* Add dependencies:
*
*/
public class PGPEncryptionTest extends CamelTestSupport {
@EndpointInject(uri = "mock:output")
MockEndpoint mockOutput;
@Test
public void testEncryptsOK() throws Exception {
template.sendBody("direct:start", "My cleartext message");
mockOutput.expectedMessageCount(1);
mockOutput.assertIsSatisfied();
}
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
String encryptKeyFileName = "pubring.gpg";
String encryptKeyUserid = "[email protected]";
from("direct:start")
//.errorHandler(deadLetterChannel("file:source/dlc1").useOriginalMessage())
.process(exchange -> System.out.println( "1 >>> BEFORE:\n " + exchange.getIn().getBody(String.class)))
.marshal().pgp(encryptKeyFileName,encryptKeyUserid)
.process(exchange -> System.out.println( "1 >>> AFTER: \n" + exchange.getIn().getBody(String.class)))
.to("mock:output");
}
};
}
}
| true |
02a83891b178187dd313b23d5c07dcda3c765adf
|
Java
|
ybm0934/Workspace-Java
|
/src/Homework/No_4_Answer.java
|
UTF-8
| 758 | 3.8125 | 4 |
[] |
no_license
|
package Homework;
public class No_4_Answer {
public static void main(String[] args) {
// 7. 다음과 같은 과정을 적용하여 작은 수에서 큰 수 순으로 출력하는 프로그램(selection sort algorithm)
// 초기값 : 5 3 1 4 2
// 1 step : 1 5 3 4 2
// 2 step : 1 2 5 4 3
// 3 step : 1 2 3 5 4
// 4 step : 1 2 3 4 5
int[] arr = new int[] { 5, 3, 1, 4, 2 };
int i = 0;
int j = 0;
int temp = 0;
for (i = 0; i < arr.length; i++) {
for (int value : arr) {
System.out.printf("%5d", value);
}
System.out.println();
for (j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
}
| true |
e799b8cdc8f75c8675b1ebdd7868e334b89b196b
|
Java
|
ravivarmak/kaniganti
|
/Spring Boot/mongo/src/main/java/ravi/varma/repository/CustomerRepository.java
|
UTF-8
| 255 | 1.679688 | 2 |
[] |
no_license
|
package ravi.varma.repository;
import org.springframework.stereotype.Repository;
import ravi.varma.model.Customer;
@Repository
public interface CustomerRepository extends org.springframework.data.mongodb.repository.MongoRepository<Customer, Long> {
}
| true |
8c3d147d17d00fecc38f117ef0d219455cc5130f
|
Java
|
PRADIP-1596/Input-Output_Operations
|
/iooperations/src/main/java/com/bridgelabz/iooperations/ByteStreamsDemo.java
|
UTF-8
| 754 | 2.859375 | 3 |
[] |
no_license
|
package com.bridgelabz.iooperations;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamsDemo {
public static void main(String[] args) throws IOException {
FileInputStream fin =null;
FileOutputStream fout =null;
try {
fin=new FileInputStream("input.txt");
fout=new FileOutputStream("out.txt");
int c;
while((c=fin.read() )!= -1)
{
fout.write(c);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if(fin!=null) {
fin.close();
}if(fout!=null) {
fout.close();
}
}
}
}
| true |
828ccf64afac0ac9fd1bdc0e860ce825e429cf68
|
Java
|
piomin/sample-testing-microservices
|
/passenger-management/src/main/java/pl/piomin/services/passenger/controller/PassengerController.java
|
UTF-8
| 1,312 | 2.265625 | 2 |
[] |
no_license
|
package pl.piomin.services.passenger.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pl.piomin.services.passenger.model.Passenger;
import pl.piomin.services.passenger.model.PassengerInput;
import pl.piomin.services.passenger.repository.PassengerRepository;
import java.util.List;
@RestController
@RequestMapping("/passengers")
public class PassengerController {
@Autowired
private PassengerRepository repository;
@PostMapping
public Passenger create(@RequestBody Passenger passenger) {
return repository.add(passenger);
}
@PutMapping
public Passenger update(@RequestBody PassengerInput passengerInput) {
Passenger passenger = repository.findById(passengerInput.getId());
passenger.setBalance(passenger.getBalance() + passengerInput.getAmount());
return repository.update(passenger);
}
@GetMapping("/{id}")
public Passenger getById(@PathVariable Long id) {
return repository.findById(id);
}
@GetMapping("/login/{login}")
public Passenger getById(@PathVariable String login) {
return repository.findByLogin(login);
}
@GetMapping
public List<Passenger> getAll() {
return repository.findAll();
}
}
| true |
a0395cb1074510cbd5e57c40365ef7262bbd3c80
|
Java
|
chenyiAlone/LeetCode
|
/src/hard/BasicCalculator.java
|
UTF-8
| 4,309 | 4.09375 | 4 |
[] |
no_license
|
package hard;
import java.util.Stack;
/**
* ClassName: BasicCalculator.java
* Author: chenyiAlone
* Create Time: 2019/5/13 16:39
* Description: No.224
* 思路:
* 1. 思路就是处理优先级的问题
* 扫描到一个字符,就将 operate stack 中之前 连续的并且优先级相等或者更高的操作符 弹出并计算压入数组栈中
* `(` 的优先级最低
* `*` `/` 的优先级高于 `+` `-`
* 2. 递归写法
*
*
*
*
*
* Implement a basic calculator to evaluate a simple expression string.
*
* The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
*
* Example 1:
*
* Input: "1 + 1"
* Output: 2
* Example 2:
*
* Input: " 2-1 + 2 "
* Output: 3
* Example 3:
*
* Input: "(1+(4+5+2)-3)+(6+8)"
* Output: 23
* Note:
* You may assume that the given expression is always valid.
* Do not use the eval built-in library function.
*
*
*/
public class BasicCalculator {
private char[] str;
private int index;
// 2. 递归写法
private int cacul() {
int ret = 0, flag = 1;
while (index < str.length && str[index] != ')') {
if ('0' <= str[index] && str[index] <= '9') {
int num = 0;
while (index < str.length && '0' <= str[index] && str[index] <= '9') {
num = num * 10 + str[index] - '0';
index++;
}
ret += flag * num;
} else {
switch(str[index++]) {
case '+':
flag = 1;
break;
case '-':
flag = -1;
break;
case '(':
ret += flag * cacul();
break;
case ' ':
break;
}
}
}
if (index < str.length && str[index] == ')') {
index++;
}
return ret;
}
public int calculateByRec(String s) {
str = s.toCharArray();
return cacul();
}
// 1. 优先级递归
private Stack<Integer> numbers = new Stack<>();
private Stack<Character> operate = new Stack<>();
public int calculate(String s) {
char[] str = s.toCharArray();
int len = str.length;
for (int i = 0; i < len; i++) {
if (str[i] == ' ')
continue;
if (isNumber(str[i])) {
int N = str[i] - '0';
while (i + 1 < len && isNumber(str[i + 1])) {
N = N * 10 + (str[i + 1] - '0');
i++;
}
numbers.push(N);
} else {
if (str[i] == ')') {
while (!operate.isEmpty() && operate.peek() != '(')
pop_operate();
operate.pop(); // pop '('
} else {
if (str[i] == '+' || str[i] == '-') {
while (!operate.isEmpty() && operate.peek() != '(')
pop_operate();
operate.push(str[i]);
} else {
while (!operate.isEmpty() && (operate.peek() == '*' || operate.peek() == '/') && operate.peek() != '(')
pop_operate();
operate.push(str[i]);
}
}
}
}
while (!operate.isEmpty())
pop_operate();
return numbers.pop();
}
private boolean isNumber(Character c) {
return '0' <= c && c <= '9';
}
private void pop_operate() {
int a = numbers.pop();
int b = numbers.pop();
char c = operate.pop();
switch(c) {
case '+':
numbers.push(a + b);
break;
case '-':
numbers.push(b - a);
break;
case '*':
numbers.push(a * b);
break;
case '/':
numbers.push(b / a);
break;
default:
break;
}
}
}
| true |
18ce06bf724f867083af843ef6c8d71a1a717261
|
Java
|
flywind2/joeis
|
/src/irvine/oeis/a016/A016166.java
|
UTF-8
| 309 | 2.34375 | 2 |
[] |
no_license
|
package irvine.oeis.a016;
import irvine.oeis.LinearRecurrence;
/**
* A016166 Expansion of <code>1/((1-5x)(1-12x))</code>.
* @author Sean A. Irvine
*/
public class A016166 extends LinearRecurrence {
/** Construct the sequence. */
public A016166() {
super(new long[] {-60, 17}, new long[] {1, 17});
}
}
| true |
005e6afa67d68f81290dadc56debecdeb1641e59
|
Java
|
franck-romano/quarkus
|
/extensions/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/standalone/VertxOutput.java
|
UTF-8
| 207 | 1.601563 | 2 |
[
"Apache-2.0"
] |
permissive
|
package io.quarkus.resteasy.runtime.standalone;
import java.io.IOException;
import io.netty.buffer.ByteBuf;
public interface VertxOutput {
void write(ByteBuf data, boolean last) throws IOException;
}
| true |
11f4f2cd6d226542667b0499e4d369495c166f54
|
Java
|
bpaulon/OCP8-Workout
|
/src/ocp/lambda/MappingCollectorTests.java
|
UTF-8
| 3,827 | 2.8125 | 3 |
[] |
no_license
|
package ocp.lambda;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@SuppressWarnings("unused")
public class MappingCollectorTests {
@Rule
public ExceptionLoggingRule exLogger = new ExceptionLoggingRule();
@Rule
public ExpectedException thrown = ExpectedException.none();
Supplier<Stream<String>> supplier = () -> Arrays.asList("aa", "bb", "aa", "cc")
.stream();
@Test
public void duplicateKeysShouldThrowException() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Duplicate key");
supplier.get()
.collect(Collectors.toMap(k -> k, k -> k.length()));
}
@Test
public void duplicateKeysShouldBeMerged() {
AtomicInteger index = new AtomicInteger();
Map<String, Integer> map = supplier.get()
.collect(Collectors.toMap(Function.identity() /* k -> k */,
k -> index.incrementAndGet(),
(key1, key2) -> key1));
assertEquals(Arrays.asList("aa", "bb", "cc"), map.keySet()
.stream()
.sorted()
.collect(Collectors.toList()));
System.out.println(map);
}
@Test
public void duplicateKeysShouldBeGrouped() {
AtomicInteger index = new AtomicInteger();
// {cc=[4], bb=[2], aa=[1, 3]}
Map<String, List<Integer>> map = supplier.get()
.collect(Collectors.groupingBy(Function.identity(),
Collectors.mapping(k -> (Integer) index.incrementAndGet(), Collectors.toList())));
// [1, 2, 3, 4]
List<Integer> positions = map.keySet()
.stream()
.flatMap(k -> map.get(k).stream())
.sorted()
.collect(Collectors.toList());
assertEquals(Arrays.asList(1, 2, 3, 4), positions);
}
@Test
public void testMinBy() {
Map<String, Long> map = supplier.get()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(map);
}
@Test
public void testGroupingWithPartioning() {
Map<Integer, ?> m = Stream.of(56, 54, 1, 31, 98, 98, 16)
.collect(Collectors.groupingBy(i -> i % 10));
//{1=[1, 31], 4=[54], 6=[56, 16], 8=[98, 98]}
System.out.println(m);
m = Stream.of(56, 54, 1, 31, 98, 98, 16)
.collect(Collectors.groupingBy(i -> i % 10, Collectors.partitioningBy(s -> s %2 == 0)));
//{1={false=[1, 31], true=[]}, 4={false=[], true=[54]}, 6={false=[], true=[56, 16]}, 8={false=[], true=[98, 98]}}
System.out.println(m);
m = Stream.of(56, 54, 1, 31, 98, 98, 16)
.collect(Collectors.groupingBy(i -> i % 10, TreeMap::new, Collectors.partitioningBy(i -> i > 5)));
//{1={false=[1], true=[31]}, 4={false=[], true=[54]}, 6={false=[], true=[56, 16]}, 8={false=[], true=[98, 98]}}
System.out.println(m);
}
@Test
public void testGroupingByReturn() {
Supplier<Stream<Integer>> s = () -> Stream.of(1,1, 2,3,4, 13, 13);
//Supplier<Stream<?>> s = () -> Stream.empty();
Map<?,?> m1 = s.get().collect(Collectors.groupingBy(Object::toString));
System.out.println(m1);
ConcurrentMap<?,?> m2 = s.get().collect(Collectors.groupingByConcurrent(Object::toString));
System.out.println(m2);
ConcurrentMap<?,?> m3 = s.get().collect(Collectors.toConcurrentMap(Object::toString, Object::toString, (k, v) -> v));
System.out.println(m3);
Map<?,?> m4 = s.get().collect(Collectors.mapping(Object::toString, Collectors.toMap(Function.identity(), Function.identity(), (k, v) -> v)));
System.out.println(m4);
List<?> m5 = s.get().collect(Collectors.mapping(Object::toString, Collectors.toList()));
System.out.println(m5);
}
}
| true |
6ed2d3a86425a2d2daf104228a3c125233d1c0dc
|
Java
|
hmcts/cmc-claim-store
|
/domain-model/src/test/java/uk/gov/hmcts/cmc/domain/constraints/UserRoleConstraintValidatorTest.java
|
UTF-8
| 1,024 | 2.125 | 2 |
[
"MIT"
] |
permissive
|
package uk.gov.hmcts.cmc.domain.constraints;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import javax.validation.ConstraintValidatorContext;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(MockitoJUnitRunner.class)
public class UserRoleConstraintValidatorTest {
@Mock
private ConstraintValidatorContext validatorContext;
private final UserRoleConstraintValidator validator = new UserRoleConstraintValidator();
@Test
public void shouldReturnTrueForValidRole() {
assertThat(validator.isValid("cmc-new-features-consent-given", validatorContext)).isTrue();
}
@Test
public void shouldReturnFalseForInvalidRole() {
assertThat(validator.isValid("InvalidRole", validatorContext)).isFalse();
}
@Test
public void shouldReturnTrueForConsentNotGiven() {
assertThat(validator.isValid("cmc-new-features-consent-not-given", validatorContext)).isTrue();
}
}
| true |
80370406973eb5a86dab135c1be001783e3de4fd
|
Java
|
trinimorillas/gesaduan_online_git
|
/modules/gesaduan-war/src/main/java/es/mercadona/gesaduan/dto/excel/getexcel/v1/OutputExcelDTO.java
|
UTF-8
| 367 | 1.835938 | 2 |
[] |
no_license
|
package es.mercadona.gesaduan.dto.excel.getexcel.v1;
import es.mercadona.gesaduan.dto.common.AbstractDTO;
public class OutputExcelDTO extends AbstractDTO {
private static final long serialVersionUID = 1L;
private DatosExcelDTO datos;
public DatosExcelDTO getDatos() {
return datos;
}
public void setDatos(DatosExcelDTO datos) {
this.datos = datos;
}
}
| true |
99dda6f849de555db840827080c9adb7f9acee3d
|
Java
|
Jerry6574/CodeStepByStep-Java
|
/08-file-io/01-flipCoins/FlipCoins.java
|
UTF-8
| 2,263 | 3.9375 | 4 |
[] |
no_license
|
/* FlipCoins.java
Sollution to: https://www.codestepbystep.com/problem/view/java/fileio/flipCoins
Write a method named flipCoins that accepts as its parameter a Scanner for an input file.
Assume that the input file data represents results of sets of coin flips that are either
heads (H) or tails (T) in either upper or lower case, separated by at least one space.
Your method should consider each line to be a separate set of coin flips and should output
to the console the number of heads and the percentage of heads in that line,
rounded down to the nearest integer (truncated).
If this percentage is more than 50%,
you should print a "There were more heads!" message.
For example, consider the following input file:
H T H H T
T t t T h H
h
For the input above, your method should produce the following output:
3 heads (60%)
There were more heads!
2 heads (33%)
1 heads (100%)
There were more heads!
The format of your output must exactly match that shown above.
You may assume that the Scanner contains at least 1 line of input,
that each line contains at least one token, and that no tokens other than h, H, t, or T will be in the lines.
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
import acm.program.*;
public class FlipCoins extends ConsoleProgram {
public void run() {
try {
FileInputStream fileIn = new FileInputStream("flips.txt");
Scanner input = new Scanner(fileIn);
flipCoins(input);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void flipCoins(Scanner input) {
while(input.hasNextLine()) {
String line = input.nextLine();
int headCount = 0;
int tailCount = 0;
for(int i = 0; i < line.length(); i++) {
char token = line.charAt(i);
if(Character.toUpperCase(token) == 'T') {
tailCount++;
} else if(Character.toUpperCase(token) == 'H') {
headCount++;
}
}
println(headCount + String.format(" heads (%.0f", (double) headCount / (headCount + tailCount) * 100) + "%)");
if(headCount > tailCount) {
println("There were more heads!");
}
println();
}
}
}
| true |
1c1def2b41a02712b3e68e25728e8cac0a6b3a5b
|
Java
|
darshanhs90/Java-Coding
|
/src/Nov2020Leetcode/_0150EvaluateReversePolishNotation.java
|
UTF-8
| 1,204 | 3.59375 | 4 |
[
"MIT"
] |
permissive
|
package Nov2020Leetcode;
import java.util.Stack;
public class _0150EvaluateReversePolishNotation {
public static void main(String[] args) {
System.out.println(evalRPN(new String[] { "2", "1", "+", "3", "*" }));
System.out.println(evalRPN(new String[] { "4", "13", "5", "/", "+" }));
System.out
.println(evalRPN(new String[] { "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" }));
}
public static int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
String currString = tokens[i];
if (currString.contentEquals("+")) {
int val1 = stack.pop();
int val2 = stack.pop();
stack.push(val1 + val2);
} else if (currString.contentEquals("-")) {
int val1 = stack.pop();
int val2 = stack.pop();
stack.push(val2 - val1);
} else if (currString.contentEquals("*")) {
int val1 = stack.pop();
int val2 = stack.pop();
stack.push(val1 * val2);
} else if (currString.contentEquals("/")) {
int val1 = stack.pop();
int val2 = stack.pop();
stack.push(val2 / val1);
} else {
stack.push(Integer.parseInt(currString));
}
}
return stack.peek();
}
}
| true |
f8f5bdf1627c4c77bcf469fa94b4cbb6b303cf77
|
Java
|
ares2015/SemanticRelationsExtractorStanford
|
/src/main/java/com/semanticRelationsExtractorStanford/extraction/predicate/preposition/PrepositionPredicateExtractor.java
|
UTF-8
| 449 | 1.828125 | 2 |
[] |
no_license
|
package com.semanticRelationsExtractorStanford.extraction.predicate.preposition;
import com.semanticRelationsExtractorStanford.data.SemanticExtractionData;
import com.semanticRelationsExtractorStanford.data.SemanticPreprocessingData;
/**
* Created by Oliver on 6/1/2017.
*/
public interface PrepositionPredicateExtractor {
void extract(SemanticExtractionData semanticExtractionData, SemanticPreprocessingData semanticPreprocessingData);
}
| true |
7cedc04239c66b9ac82e7252e1c2a8ef215795bc
|
Java
|
abdelhedinizar/AndroidTalQuest
|
/app/src/main/java/com/forsyslab/talquest10/fragments/TimeLineFragment.java
|
UTF-8
| 5,149 | 1.796875 | 2 |
[] |
no_license
|
package com.forsyslab.talquest10.fragments;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.lang.reflect.Type;
import com.forsyslab.talquest10.R;
import com.forsyslab.talquest10.adapter.JobLeadsAdapter;
import com.forsyslab.talquest10.dagger.AndroidApplication;
import com.forsyslab.talquest10.dagger.GetJobLeads;
import com.forsyslab.talquest10.model.JobLeads;
import com.forsyslab.talquest10.storage.PreferencesStorageService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterException;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import retrofit2.Call;
import retrofit2.Retrofit;
import static com.facebook.FacebookSdk.getApplicationContext;
import static com.forsyslab.talquest10.constant.Const.BEARER;
import static com.forsyslab.talquest10.constant.Const.JOB_LEADS;
import static com.forsyslab.talquest10.constant.Const.PREFERENCES_TOKEN_KEY;
import static com.forsyslab.talquest10.constant.Const.TAG;
/**
* Created by LENOVO on 23/02/2017.
*/
public class TimeLineFragment extends Fragment {
public static final String A_NETWORK_ERROR_HAS_OCCURRED = "A network error has occurred";
JobLeadsAdapter jobLeadsAdapter;
@Inject
Retrofit retrofit;
private RecyclerView mRecyclerView;
SwipeRefreshLayout swipeRefreshLayout;
List<JobLeads> jobLeadsList = new ArrayList<>();
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_time_line, container, false);
((AndroidApplication) getApplicationContext()).getNetComponent().inject(this);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh);
jobLeadsAdapter = new JobLeadsAdapter(getContext(), getActivity());
jobLeadsAdapter.setJobList(jobLeadsList);
LinearLayoutManager mLinearLayoutManager;
mLinearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
getTimeLine();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
(new Handler()).postDelayed(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), "refresh", Toast.LENGTH_LONG).show();
getTimeLine();
swipeRefreshLayout.setRefreshing(false);
}
}, 1000);
}
});
return view;
}
private void getTimeLine() {
final Call<List<JobLeads>> jobLeadList = retrofit.create(GetJobLeads.class).getJobLeads(BEARER.concat(PreferencesStorageService.getDefaults(PREFERENCES_TOKEN_KEY, getApplicationContext())));
jobLeadList.enqueue(new Callback<List<JobLeads>>() {
@Override
public void success(Result<List<JobLeads>> result) {
jobLeadsList = result.data;
jobLeadsAdapter.setJobList(jobLeadsList);
mRecyclerView.setAdapter(jobLeadsAdapter);
Gson gson = new Gson();
String jobLeadsListString = gson.toJson(jobLeadsList);
Log.d("nizarjoblead",jobLeadsListString);
PreferencesStorageService.setDefaults(JOB_LEADS, jobLeadsListString, getApplicationContext());
}
@Override
public void failure(TwitterException exception) {
Toast.makeText(getApplicationContext(),A_NETWORK_ERROR_HAS_OCCURRED+"",Toast.LENGTH_LONG).show();
Log.d(TAG,exception.toString());
Gson gson = new Gson();
String jobLeadsListGetString = PreferencesStorageService.getDefaults(JOB_LEADS, getApplicationContext());
Type type = new TypeToken<List<JobLeads>>() {
}.getType();
List<JobLeads> jobs = gson.fromJson(jobLeadsListGetString, type);
if(jobs!=null){
jobLeadsAdapter.setJobList(jobs);
Log.d("nizarab",jobs.toString());
}
mRecyclerView.setAdapter(jobLeadsAdapter);
}
});
}
}
| true |
3598b5743381d4640366ab149d0a2c32e4ef1d98
|
Java
|
Raktim-1989/jenkinstekstac
|
/jenpro5/Main.java
|
UTF-8
| 3,848 | 3.21875 | 3 |
[] |
no_license
|
import java.io.*;
import java.util.*;
public class Main {
public static void loadRolesAndprivileges(List<Role> roles , List<Privilege> privileges) {
roles.add(new Role(1, "Manager", new ArrayList<Privilege>()));
roles.add(new Role(2, "Shipper", new ArrayList<Privilege>()));
roles.add(new Role(3, "Agent", new ArrayList<Privilege>()));
roles.add(new Role(4, "Customer", new ArrayList<Privilege>()));
privileges.add(new Privilege(1, "Process Shipment", new ArrayList<Role>()));
privileges.add(new Privilege(2, "Create Shipment", new ArrayList<Role>()));
privileges.add(new Privilege(3, "Schedule Shipment", new ArrayList<Role>()));
privileges.add(new Privilege(4, "Cancel Shipment", new ArrayList<Role>()));
}
public static void main(String[] args) throws IOException{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
List<Role> roles = new ArrayList<Role>();
List<Privilege> privileges = new ArrayList<Privilege>();
Main.loadRolesAndprivileges(roles, privileges);
String ch;
Integer roleId;
Integer privilegeId;
int i,j;
System.out.println("Available roles:");
System.out.println(String.format("%-15s%s", "Id","Name"));
for(Role role:roles){
System.out.println(String.format("%-15d%s", role.getId(),role.getName()));
}
System.out.println("Available privileges:");
System.out.println(String.format("%-15s%s", "Id","Name"));
for(Privilege privilege:privileges){
System.out.println(String.format("%-15d%s", privilege.getId(),privilege.getName()));
}
do{
System.out.println("1. Assign privilege\n2. Cancel privilege\n3. Search privilege by role\n4. Search role by privilege\nEnter the choice:");
Integer choice = Integer.parseInt(buf.readLine());
switch(choice){
case 1:System.out.println("Enter the id for role:");
roleId = Integer.parseInt(buf.readLine());
System.out.println("Enter the id for privilege:");
privilegeId = Integer.parseInt(buf.readLine());
for(i=0;i<roles.size();i++){
if(roles.get(i).getId() == roleId)
break;
}
for(j=0;j<privileges.size();j++){
if(privileges.get(j).getId() == privilegeId)
break;
}
roles.get(i).getPrivilegeList().add(privileges.get(j));
privileges.get(j).getRoleList().add(roles.get(i));break;
case 2:System.out.println("Enter the id for role:");
roleId = Integer.parseInt(buf.readLine());
System.out.println("Enter the id for privilege:");
privilegeId = Integer.parseInt(buf.readLine());
for(i=0;i<roles.size();i++){
if(roles.get(i).getId() == roleId)
break;
}
for(j=0;j<privileges.size();j++){
if(privileges.get(j).getId() == privilegeId)
break;
}
roles.get(i).getPrivilegeList().remove(privileges.get(j));
privileges.get(j).getRoleList().remove(roles.get(i));break;
case 3:System.out.println("Enter the role name:");
String roleName = buf.readLine();
for(Role role:roles){
if(role.getName().equals(roleName)){
for(Privilege privilege:role.getPrivilegeList())
System.out.println(""+privilege.getName());
}
}break;
case 4:System.out.println("Enter the privilege name:");
String privilegeName = buf.readLine();
for(Privilege privilege:privileges){
if(privilege.getName().equals(privilegeName)){
for(Role role:privilege.getRoleList())
System.out.println(""+role.getName());
}
}break;
default:System.out.println("Invalid Choice");
}
System.out.println("Do you want to process again?(yes/no)");
ch = buf.readLine();
}while(ch.equals("yes"));
}
}
| true |
6384088ca66dceeb128152bf26950a671bca454b
|
Java
|
yarosdam/Reto3LYD
|
/src/main/java/clases/Billete.java
|
UTF-8
| 3,644 | 2.6875 | 3 |
[] |
no_license
|
package clases;
import java.util.Date;
import interfaces.Ventana;
/**
* Clase billete con la informacion y metodos relacionados
* @author Yaros
*
*/
public class Billete {
public int codigoBillete, codAutobus;
public double precioTrayecto;
public Date fecha;
public Linea linea;
public Parada paradaInic, paradaFin;
/**
* Constructor vacio
*/
public Billete() {
}
/**
* Constructor con todos los parametros menos el codigo;
*
* @param precioTrayecto
* @param fecha
* @param linea
* @param paradaInic
* @param paradaFin
*/
public Billete(float precioTrayecto, Date fecha, Linea linea, Parada paradaInic, Parada paradaFin) {
this.precioTrayecto = precioTrayecto;
this.fecha = fecha;
this.linea = linea;
this.paradaInic = paradaInic;
this.paradaFin = paradaFin;
}
/**
* Constructor de informacion general
* @param linea Objeto Linea
* @param paradaInic Objeto Parada
* @param paradaFin Objeto Parada
*/
public Billete(Linea linea, Parada paradaInic, Parada paradaFin) {
this.linea = linea;
this.paradaInic = paradaInic;
this.paradaFin = paradaFin;
}
/**
* Sala la informacion general del trayecto y lo mete en un objeto Billete
* @param mod
* @param vis
*/
public void informacionGeneralBilletes(Modelo mod, Ventana vis) {
Linea linea = new Linea();
Parada paradaInic = new Parada(), paradaDest = new Parada();
for (int i = 0; i < mod.lineas.size(); i++) {
if (mod.lineas.get(i).codigo.equals(vis.panelLineas2.lblNombreLinea.getText().substring(0, 2))) {
linea = mod.lineas.get(i);
break;
}
}
String salida= vis.panelLineas2.lblSal.getText();
String destino = vis.panelLineas2.listaDestinos.getSelectedValue().toString();
for (int i = 0; i < mod.arrayParadas.size(); i++) {
if (mod.arrayParadas.get(i).nombreParada.equals(destino)) {
paradaDest = mod.arrayParadas.get(i);
break;
} else if (mod.arrayParadas.get(i).nombreParada.equals(salida)) {
paradaInic = mod.arrayParadas.get(i);
}
}
mod.billeteGeneralIda.linea=linea;
mod.billeteGeneralIda.paradaInic=paradaInic;
mod.billeteGeneralIda.paradaFin=paradaDest;
}
/**
* Saca las fechas del trayecto y lo mete en un objeto Billete
* @param mod
* @param vis
*/
public void fechasGeneralBilletes(Modelo mod, Ventana vis) {
Date fechaIda, fechaVuelta;
fechaIda = vis.panelLineas2.calendarioIda.getDate();
mod.billeteGeneralIda.fecha=fechaIda;
if (mod.isIdaYVuelta()) {
fechaVuelta = vis.panelLineas2.calendarioVuelta.getDate();
mod.billeteGeneralVuelta = mod.billeteGeneralIda;
mod.billeteGeneralVuelta.fecha = fechaVuelta;
}
}
public Date getFecha() {
return this.fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public int getCodigoBillete() {
return this.codigoBillete;
}
public void setCodigoBillete(int codigoBillete) {
this.codigoBillete = codigoBillete;
}
public int getCodAutobus() {
return this.codAutobus;
}
public void setCodAutobus(int codAutobus) {
this.codAutobus = codAutobus;
}
public double getPrecioTrayecto() {
return this.precioTrayecto;
}
public void setPrecioTrayecto(double precioTrayecto) {
this.precioTrayecto = precioTrayecto;
}
public Linea getLinea() {
return this.linea;
}
public void setLinea(Linea linea) {
this.linea = linea;
}
public Parada getParadaInic() {
return this.paradaInic;
}
public void setParadaInic(Parada paradaInic) {
this.paradaInic = paradaInic;
}
public Parada getParadaFin() {
return this.paradaFin;
}
public void setParadaFin(Parada paradaFin) {
this.paradaFin = paradaFin;
}
}
| true |
5489d1639bec3f246710819d55d6202b82f70683
|
Java
|
Zoe0709/CS2XB3
|
/ningh4_Lab9_1/src/search/SequentialSearchST.java
|
UTF-8
| 1,529 | 3.65625 | 4 |
[] |
no_license
|
package search;
import java.util.ArrayList;
import java.util.Queue;
public class SequentialSearchST<Key, Value> {
private Node first; // first node in the linked list
private class Node{ // linked-list node
Key key;
Value val;
Node next;
public Node(Key key, Value val, Node next){
this.key = key;
this.val = val;
this.next = next;
}
}
public Value get(Key key){ // Search for key, return associated value.
for (Node x = first; x != null; x = x.next)
if (key.equals(x.key))
return x.val; // search hit
return null; // search miss
}
public void put(Key key, Value val){ // Search for key. Update value if found; grow table if new.
for (Node x = first; x != null; x = x.next)
if (key.equals(x.key))
{ x.val = val; return; } // Search hit: update val.
first = new Node(key, val, first); // Search miss: add new node.
}
public int size() {
Node currentNode = first;
int count = 0;
while (currentNode != null) {
count++;
currentNode = first.next;
}
return count;
}
public Iterable<Key> keys() {
ArrayList<Key> allkeys = new ArrayList<Key>();
for (Node x = first; x != null; x = x.next)
allkeys.add(x.key);
return allkeys;
}
public void delete(Key key) {
Node prev = null;
Node now = first;
while (now != null) {
if (now.key == key) {
prev.next = now.next;
} else {
prev = now;
}
now = now.next;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| true |
ed16770f9e96f3282a5b0104b229c01f64264847
|
Java
|
kangjaesoon/STS_seok
|
/seokBook/src/main/java/com/sb/s1/purchase/PurchaseDAO.java
|
UTF-8
| 1,908 | 2.015625 | 2 |
[] |
no_license
|
package com.sb.s1.purchase;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sb.s1.branch.BranchPager;
import com.sb.s1.util.Pager;
@Repository
public class PurchaseDAO {
@Autowired
private SqlSession sqlSession;
private final String NAMESPACE="com.sb.s1.purchase.PurchaseDAO.";
public int setInsert(PurchaseDTO purchaseDTO) throws Exception {
return sqlSession.insert(NAMESPACE+"setInsert", purchaseDTO);
}
public int setDelete(PurchaseDTO purchaseDTO) throws Exception {
return sqlSession.delete(NAMESPACE+"setDelete", purchaseDTO);
}
public int setUpdate(PurchaseDTO purchaseDTO) throws Exception {
return sqlSession.update(NAMESPACE+"setUpdate", purchaseDTO);
}
public PurchaseDTO getSelect(PurchaseDTO purchaseDTO) throws Exception {
return sqlSession.selectOne(NAMESPACE+"getSelect", purchaseDTO);
}
public long getTotalCount(BranchPager branchPager) throws Exception {
return sqlSession.selectOne(NAMESPACE+"getTotalCount", branchPager);
}
public long getNum()throws Exception {
return sqlSession.selectOne(NAMESPACE+"getNum");
}
public List<PurchaseDTO> getSelectList() throws Exception {
return sqlSession.selectList(NAMESPACE+"getSelectList");
}
public List<PurchaseDTO> getList(BranchPager branchPager) throws Exception {
return sqlSession.selectList(NAMESPACE+"getList", branchPager);
}
public List<PurchaseDTO> userPurchase(Pager pager) throws Exception{
return sqlSession.selectList(NAMESPACE+"userPurchase",pager);
}
public long getTotalCount2(Pager pager)throws Exception{
return sqlSession.selectOne(NAMESPACE+"getTotalCount2",pager);
}
public long setPurchase(List<PurchaseDTO> list)throws Exception{
return sqlSession.insert(NAMESPACE+"setPurchase", list);
}
}
| true |
634a2e5d1277be7dc3443e4f468ca6f2bf035801
|
Java
|
06fs4dix/Cell
|
/java/CMath.java
|
UHC
| 42,426 | 2.484375 | 2 |
[
"MIT"
] |
permissive
|
package cell;
import java.util.Vector;
class s_FACE
{
public Vector<Integer> Tface=new Vector<Integer>();
public Vector<Integer> Cindex=new Vector<Integer>();//change Index
};
public class CMath
{
static int RayBoxRIGHT = 0;
static int RayBoxLEFT = 1;
static int RayBoxMIDDLE = 2;
static float d_EPSILON = 1e-6f;
static float d_MAX_FLOAT = 3.40282346638528860e+38f;
static float d_PI=3.141592f;
static float g_fEpsilon = 0.0001f;
static public int Min(int _a, int _b)
{
return _a > _b ? _b : _a;
}
static public int Max(int _a, int _b)
{
return _a > _b ? _a : _b;
}
static public float Min(float _a, float _b)
{
return _a > _b ? _b : _a;
}
static public float Max(float _a, float _b)
{
return _a > _b ? _a : _b;
}
static public float Abs(float _val)
{
return Math.abs(_val);
}
//Vec3=======================================================================
static public CVec3 Vec3PlusVec3(CVec3 _a, CVec3 _b)
{
return new CVec3(_a.x + _b.x, _a.y + _b.y, _a.z + _b.z);
}
static public CVec3 Vec3MinusVec3(CVec3 _a, CVec3 _b)
{
return new CVec3(_a.x - _b.x, _a.y - _b.y, _a.z - _b.z);
}
static public CVec3 Vec3MulFloat(CVec3 _a, float _b)
{
return new CVec3(_a.x*_b, _a.y*_b, _a.z*_b);
}
static public float Vec3Lenght(CVec3 _a)
{
return (float) Math.sqrt(_a.x*_a.x + _a.y*_a.y + _a.z*_a.z);
}
static public float PosAnPosLen(CVec3 _a,CVec3 _b)
{
return Vec3Lenght(Vec3MinusVec3(_a, _b));
}
static public CVec3 Vec3Normalize(CVec3 _a)
{
if (_a.IsZero())
return new CVec3(0, -1, 0);
float dummy = Vec3Lenght(_a);
return new CVec3(_a.x / dummy, _a.y / dummy, _a.z / dummy);
}
static public float Vec3Dot(CVec3 _a, CVec3 _b)
{
return _a.x*_b.x + _a.y*_b.y + _a.z*_b.z;
}
static public CVec3 Vec3Cross(CVec3 _a, CVec3 _b)
{
CVec3 rVal =new CVec3();
rVal.x = _a.y * _b.z - _a.z * _b.y;
rVal.y = _a.z * _b.x - _a.x * _b.z;
rVal.z = _a.x * _b.y - _a.y * _b.x;
return rVal;
}
//Mat=================================================================
static public CMat MatAxisToRotation(CVec3 axis, float radianAngle)
{
CMat rVal =new CMat();
float L_s = (float) Math.sin(radianAngle);
float L_c = (float) Math.cos(radianAngle);
float L_d = 1 - L_c;
rVal.arr[0][0] = (L_d*(axis.x*axis.x)) + L_c; rVal.arr[0][1] = (L_d*axis.x*axis.y) + (axis.z*L_s);
rVal.arr[0][2] = (L_d*axis.x*axis.z) - (axis.y*L_s); rVal.arr[0][3] = 0;
rVal.arr[1][0] = (L_d*axis.x*axis.y) - (axis.z*L_s); rVal.arr[1][1] = (L_d*(axis.y*axis.y)) + L_c;
rVal.arr[1][2] = (L_d*axis.y*axis.z) + (axis.x*L_s); rVal.arr[1][3] = 0;
rVal.arr[2][0] = (L_d*axis.x*axis.y) + (axis.y*L_s); rVal.arr[2][1] = (L_d*axis.y*axis.z) - (axis.x*L_s);
rVal.arr[2][2] = (L_d*(axis.z*axis.z)) + L_c; rVal.arr[2][3] = 0;
rVal.arr[3][0] = 0; rVal.arr[3][1] = 0; rVal.arr[3][2] = 0; rVal.arr[3][3] = 1;
return rVal;
}
static public CMat MatScale(CVec3 pa_vec)
{
CMat pa_out =new CMat();
pa_out.arr[0][0] = pa_vec.x; pa_out.arr[0][1] = 0; pa_out.arr[0][2] = 0; pa_out.arr[0][3] = 0;
pa_out.arr[1][0] = 0; pa_out.arr[1][1] = pa_vec.y; pa_out.arr[1][2] = 0; pa_out.arr[1][3] = 0;
pa_out.arr[2][0] = 0; pa_out.arr[2][1] = 0; pa_out.arr[2][2] = pa_vec.z; pa_out.arr[2][3] = 0;
pa_out.arr[3][0] = 0; pa_out.arr[3][1] = 0; pa_out.arr[3][2] = 0; pa_out.arr[3][3] = 1;
return pa_out;
}
static public CMat MatMul(CMat pa_val1, CMat pa_val2)
{
CMat L_matrix =new CMat();
L_matrix.arr[0][0] = 0;
L_matrix.arr[1][1] = 0;
L_matrix.arr[2][2] = 0;
L_matrix.arr[3][3] = 0;
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
for (int k = 0; k < 4; ++k)
{
L_matrix.arr[i][j] += pa_val1.arr[i][k] * pa_val2.arr[k][j];
}
}
}
return L_matrix;
}
static public CVec3 MatToVec3Normal(CVec3 pa_vec, CMat pa_mat)
{
CVec3 pa_out=new CVec3();
pa_out.x = (pa_mat.arr[0][0] * pa_vec.x) + (pa_mat.arr[1][0] * pa_vec.y) + (pa_mat.arr[2][0] * pa_vec.z);
pa_out.y = (pa_mat.arr[0][1] * pa_vec.x) + (pa_mat.arr[1][1] * pa_vec.y) + (pa_mat.arr[2][1] * pa_vec.z);
pa_out.z = (pa_mat.arr[0][2] * pa_vec.x) + (pa_mat.arr[1][2] * pa_vec.y) + (pa_mat.arr[2][2] * pa_vec.z);
return pa_out;
}
static public CVec3 MatToVec3Coordinate(CVec3 pa_vec, CMat pa_mat)
{
CVec3 rVal =new CVec3();
float x, y, z, w;
x = (pa_mat.arr[0][0] * pa_vec.x) + (pa_mat.arr[1][0] * pa_vec.y) + (pa_mat.arr[2][0] * pa_vec.z) + pa_mat.arr[3][0];
y = (pa_mat.arr[0][1] * pa_vec.x) + (pa_mat.arr[1][1] * pa_vec.y) + (pa_mat.arr[2][1] * pa_vec.z) + pa_mat.arr[3][1];
z = (pa_mat.arr[0][2] * pa_vec.x) + (pa_mat.arr[1][2] * pa_vec.y) + (pa_mat.arr[2][2] * pa_vec.z) + pa_mat.arr[3][2];
w = (pa_mat.arr[0][3] * pa_vec.x) + (pa_mat.arr[1][3] * pa_vec.y) + (pa_mat.arr[2][3] * pa_vec.z) + pa_mat.arr[3][3];
rVal.x = x / w;
rVal.y = y / w;
rVal.z = z / w;
return rVal;
}
static public CMat MatInvert(CMat pa_val1)
{
CMat pa_out=new CMat();
float tmp[]=new float[12];
float src[]=new float[16];
float det;
//float * dst = pa_out->ToPT();
//float * mat = L_temp.ToPT();
/* transpose matrix */
for (int i = 0; i < 4; i++) {
src[i] = pa_val1.arr[i][0];
src[i + 4] = pa_val1.arr[i][1];
src[i + 8] = pa_val1.arr[i][2];
src[i + 12] = pa_val1.arr[i][3];
}
/* calculate pairs for first 8 elements (cofactors) */
tmp[0] = src[10] * src[15];
tmp[1] = src[11] * src[14];
tmp[2] = src[9] * src[15];
tmp[3] = src[11] * src[13];
tmp[4] = src[9] * src[14];
tmp[5] = src[10] * src[13];
tmp[6] = src[8] * src[15];
tmp[7] = src[11] * src[12];
tmp[8] = src[8] * src[14];
tmp[9] = src[10] * src[12];
tmp[10] = src[8] * src[13];
tmp[11] = src[9] * src[12];
/* calculate first 8 elements (cofactors) */
pa_out.arr[0][0] = tmp[0] * src[5] + tmp[3] * src[6] + tmp[4] * src[7];
pa_out.arr[0][0] -= tmp[1] * src[5] + tmp[2] * src[6] + tmp[5] * src[7];
pa_out.arr[0][1] = tmp[1] * src[4] + tmp[6] * src[6] + tmp[9] * src[7];
pa_out.arr[0][1] -= tmp[0] * src[4] + tmp[7] * src[6] + tmp[8] * src[7];
pa_out.arr[0][2] = tmp[2] * src[4] + tmp[7] * src[5] + tmp[10] * src[7];
pa_out.arr[0][2] -= tmp[3] * src[4] + tmp[6] * src[5] + tmp[11] * src[7];
pa_out.arr[0][3] = tmp[5] * src[4] + tmp[8] * src[5] + tmp[11] * src[6];
pa_out.arr[0][3] -= tmp[4] * src[4] + tmp[9] * src[5] + tmp[10] * src[6];
pa_out.arr[1][0] = tmp[1] * src[1] + tmp[2] * src[2] + tmp[5] * src[3];
pa_out.arr[1][0] -= tmp[0] * src[1] + tmp[3] * src[2] + tmp[4] * src[3];
pa_out.arr[1][1] = tmp[0] * src[0] + tmp[7] * src[2] + tmp[8] * src[3];
pa_out.arr[1][1] -= tmp[1] * src[0] + tmp[6] * src[2] + tmp[9] * src[3];
pa_out.arr[1][2] = tmp[3] * src[0] + tmp[6] * src[1] + tmp[11] * src[3];
pa_out.arr[1][2] -= tmp[2] * src[0] + tmp[7] * src[1] + tmp[10] * src[3];
pa_out.arr[1][3] = tmp[4] * src[0] + tmp[9] * src[1] + tmp[10] * src[2];
pa_out.arr[1][3] -= tmp[5] * src[0] + tmp[8] * src[1] + tmp[11] * src[2];
/* calculate pairs for second 8 elements (cofactors) */
tmp[0] = src[2] * src[7];
tmp[1] = src[3] * src[6];
tmp[2] = src[1] * src[7];
tmp[3] = src[3] * src[5];
tmp[4] = src[1] * src[6];
tmp[5] = src[2] * src[5];
tmp[6] = src[0] * src[7];
tmp[7] = src[3] * src[4];
tmp[8] = src[0] * src[6];
tmp[9] = src[2] * src[4];
tmp[10] = src[0] * src[5];
tmp[11] = src[1] * src[4];
/* calculate second 8 elements (cofactors) */
pa_out.arr[2][0] = tmp[0] * src[13] + tmp[3] * src[14] + tmp[4] * src[15];
pa_out.arr[2][0] -= tmp[1] * src[13] + tmp[2] * src[14] + tmp[5] * src[15];
pa_out.arr[2][1] = tmp[1] * src[12] + tmp[6] * src[14] + tmp[9] * src[15];
pa_out.arr[2][1] -= tmp[0] * src[12] + tmp[7] * src[14] + tmp[8] * src[15];
pa_out.arr[2][2] = tmp[2] * src[12] + tmp[7] * src[13] + tmp[10] * src[15];
pa_out.arr[2][2] -= tmp[3] * src[12] + tmp[6] * src[13] + tmp[11] * src[15];
pa_out.arr[2][3] = tmp[5] * src[12] + tmp[8] * src[13] + tmp[11] * src[14];
pa_out.arr[2][3] -= tmp[4] * src[12] + tmp[9] * src[13] + tmp[10] * src[14];
pa_out.arr[3][0] = tmp[2] * src[10] + tmp[5] * src[11] + tmp[1] * src[9];
pa_out.arr[3][0] -= tmp[4] * src[11] + tmp[0] * src[9] + tmp[3] * src[10];
pa_out.arr[3][1] = tmp[8] * src[11] + tmp[0] * src[8] + tmp[7] * src[10];
pa_out.arr[3][1] -= tmp[6] * src[10] + tmp[9] * src[11] + tmp[1] * src[8];
pa_out.arr[3][2] = tmp[6] * src[9] + tmp[11] * src[11] + tmp[3] * src[8];
pa_out.arr[3][2] -= tmp[10] * src[11] + tmp[2] * src[8] + tmp[7] * src[9];
pa_out.arr[3][3] = tmp[10] * src[10] + tmp[4] * src[8] + tmp[9] * src[9];
pa_out.arr[3][3] -= tmp[8] * src[9] + tmp[11] * src[10] + tmp[5] * src[8];
/* calculate determinant */
det = src[0] * pa_out.arr[0][0] + src[1] * pa_out.arr[0][1] + src[2] * pa_out.arr[0][2] + src[3] * pa_out.arr[0][3];
/* calculate matrix inverse */
det = 1 / det;
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < 4; i++)
{
pa_out.arr[j][i] *= det;
}
}
return pa_out;
}
static public CMat MatTranslation(CVec3 pa_vec)
{
CMat pa_out=new CMat();
pa_out.arr[0][0] = 1; pa_out.arr[0][1] = 0; pa_out.arr[0][2] = 0; pa_out.arr[0][3] = 0;
pa_out.arr[1][0] = 0; pa_out.arr[1][1] = 1; pa_out.arr[1][2] = 0; pa_out.arr[1][3] = 0;
pa_out.arr[2][0] = 0; pa_out.arr[2][1] = 0; pa_out.arr[2][2] = 1; pa_out.arr[2][3] = 0;
pa_out.arr[3][0] = pa_vec.x; pa_out.arr[3][1] = pa_vec.y; pa_out.arr[3][2] = pa_vec.z; pa_out.arr[3][3] = 1;
return pa_out;
}
static public CMat MatRotation(CVec3 pa_rot)
{
CMat pa_out=new CMat();
CVec4 L_qut = EulerToQut(pa_rot);
pa_out = QutToMatrix(L_qut);
return pa_out;
}
//Camera=====================================================================
static public CMat CameraPerspectiveLH(float width, float height, float zn, float zf)
{
CMat projMat=new CMat();
projMat.arr[0][0] = (2 * zn) / width; projMat.arr[0][1] = 0; projMat.arr[0][2] = 0; projMat.arr[0][3] = 0;
projMat.arr[1][0] = 0; projMat.arr[1][1] = (2 * zn) / height; projMat.arr[1][2] = 0; projMat.arr[1][3] = 0;
projMat.arr[2][0] = 0; projMat.arr[2][1] = 0; projMat.arr[2][2] = zf / (zf - zn); projMat.arr[2][3] = 1;
projMat.arr[3][0] = 0; projMat.arr[3][1] = 0; projMat.arr[3][2] = (zn*zf) / (zn - zf); projMat.arr[3][3] = 0;
return projMat;
}
//
static public CMat CameraOrthoLH(float width, float height, float zn, float zf)
{
CMat projMat=new CMat();
projMat.arr[0][0] = 2 / width; projMat.arr[0][1] = 0; projMat.arr[0][2] = 0; projMat.arr[0][3] = 0;
projMat.arr[1][0] = 0; projMat.arr[1][1] = 2 / height; projMat.arr[1][2] = 0; projMat.arr[1][3] = 0;
projMat.arr[2][0] = 0; projMat.arr[2][1] = 0; projMat.arr[2][2] = 1 / (zf - zn); projMat.arr[2][3] = 0;
projMat.arr[3][0] = 0; projMat.arr[3][1] = 0; projMat.arr[3][2] = -zn / (zf - zn); projMat.arr[3][3] = 1;
return projMat;
}
//Ļ
static public CMat CameraLookAtLH(CVec3 eyeVec, CVec3 lookVec, CVec3 upVec)
{
CMat viewMat=new CMat();
CVec3 Zaxis = Vec3MinusVec3(lookVec, eyeVec);
Zaxis = Vec3Normalize(Zaxis);
CVec3 Xaxis=new CVec3();
Xaxis = Vec3Cross(upVec, Zaxis);
if (Xaxis.IsZero())
CMsg.E("CameraLookAtLH error");//ī ġ ٲ!
Xaxis = Vec3Normalize(Xaxis);
CVec3 Yaxis=new CVec3();
Yaxis = Vec3Cross(Zaxis, Xaxis);
viewMat.arr[0][0] = Xaxis.x; viewMat.arr[0][1] = Yaxis.x; viewMat.arr[0][2] = Zaxis.x; viewMat.arr[0][3] = 0;
viewMat.arr[1][0] = Xaxis.y; viewMat.arr[1][1] = Yaxis.y; viewMat.arr[1][2] = Zaxis.y; viewMat.arr[1][3] = 0;
viewMat.arr[2][0] = Xaxis.z; viewMat.arr[2][1] = Yaxis.z; viewMat.arr[2][2] = Zaxis.z; viewMat.arr[2][3] = 0;
viewMat.arr[3][0] = -Vec3Dot(Xaxis, eyeVec);
viewMat.arr[3][1] = -Vec3Dot(Yaxis, eyeVec);
viewMat.arr[3][2] = -Vec3Dot(Zaxis, eyeVec);
viewMat.arr[3][3] = 1;
return viewMat;
}
//PI================================================================
static public float DegreeToRadian(int pa_val)
{
return pa_val / 180.0f*d_PI;
}
static public int RadianToDegree(float pa_val)
{
return (int)((180 * pa_val) / d_PI);
}
//Qut============================================================
static public CVec4 EulerToQut(CVec3 pa_radian)
{
CVec4 pa_qut=new CVec4();
CVec4 qpitch=new CVec4();
CVec4 qyaw=new CVec4();
CVec4 qroll=new CVec4();
qroll = QutAxisToRotation(new CVec3(1, 0, 0), pa_radian.x);
qpitch = QutAxisToRotation(new CVec3(0, 1, 0), pa_radian.y);
qyaw = QutAxisToRotation(new CVec3(0, 0, 1), pa_radian.z);
qroll = QutMul(qroll, qyaw);
pa_qut = QutMul(qroll, qpitch);
return pa_qut;
}
static public CVec4 QutMul(CVec4 pa_val1, CVec4 pa_val2)
{
CVec3 L_vec=new CVec3();
CVec3 L_qut=new CVec3();
CVec4 L_Oqut=new CVec4();
L_vec = Vec3Cross(new CVec3(pa_val2.x, pa_val2.y, pa_val2.z),new CVec3(pa_val1.x, pa_val1.y, pa_val1.z));
L_qut.x = L_vec.x + pa_val1.w*pa_val2.x + pa_val2.w*pa_val1.x;
L_qut.y = L_vec.y + pa_val1.w *pa_val2.y + pa_val2.w*pa_val1.y;
L_qut.z = L_vec.z + pa_val1.w * pa_val2.z + pa_val2.w*pa_val1.z;
L_Oqut.x = L_qut.x; L_Oqut.y = L_qut.y; L_Oqut.z = L_qut.z;
float L_val = 0;
L_val = Vec3Dot(new CVec3(pa_val1.x, pa_val1.y, pa_val1.z),new CVec3(pa_val2.x, pa_val2.y, pa_val2.z));
L_Oqut.w = pa_val2.w*pa_val1.w - L_val;
return L_Oqut;
}
static public CVec4 QutInverse(CVec4 pa_val1)
{
CVec4 L_con=new CVec4();
float L_len = 0;
L_con = QutConjugate(pa_val1);
L_len = QutLenght(pa_val1);
L_con.x = L_con.x / L_len;
L_con.y = L_con.y / L_len;
L_con.z = L_con.z / L_len;
L_con.w = L_con.w / L_len;
return L_con;
}
static public CVec4 QutNomalize(CVec4 pa_val1)
{
CVec4 L_con=new CVec4();
float L_len = 0;
L_len = QutLenght(pa_val1);
L_con.x = pa_val1.x / L_len;
L_con.y = pa_val1.y / L_len;
L_con.z = pa_val1.z / L_len;
L_con.w = pa_val1.w / L_len;
return L_con;
}
static public CVec4 QutConjugate(CVec4 pa_val1)
{
CVec4 pa_out=new CVec4();
pa_out.x = -pa_val1.x;
pa_out.y = -pa_val1.y;
pa_out.z = -pa_val1.z;
pa_out.w = pa_val1.w;
return pa_out;
}
static public float QutLenght(CVec4 pa_val1)
{
return pa_val1.x*pa_val1.x + pa_val1.y*pa_val1.y + pa_val1.z*pa_val1.z + pa_val1.w*pa_val1.w;
}
static public CVec4 QutAxisToRotation(CVec3 axis,float radianAngle)
{
CVec4 pa_out=new CVec4();
pa_out.x = (float) (axis.x*Math.sin(radianAngle / 2));
pa_out.y = (float) (axis.y*Math.sin(radianAngle / 2));
pa_out.z = (float) (axis.z*Math.sin(radianAngle / 2));
pa_out.w = (float) Math.cos(radianAngle / 2);
return pa_out;
}
static public CMat QutToMat(CVec4 pa_val1)
{
CMat pa_out=new CMat();
pa_out.arr[0][0] = 1 - (2 * pa_val1.y*pa_val1.y) - (2 * pa_val1.z*pa_val1.z);
pa_out.arr[0][1] = (2 * pa_val1.x*pa_val1.y) + (2 * pa_val1.z*pa_val1.w);
pa_out.arr[0][2] = (2 * pa_val1.x*pa_val1.z) - (2 * pa_val1.y*pa_val1.w);
pa_out.arr[0][3] = 0;
pa_out.arr[1][0] = (2 * pa_val1.x*pa_val1.y) - (2 * pa_val1.z*pa_val1.w);
pa_out.arr[1][1] = 1 - (2 * pa_val1.x*pa_val1.x) - (2 * pa_val1.z*pa_val1.z);
pa_out.arr[1][2] = (2 * pa_val1.y*pa_val1.z) + (2 * pa_val1.x*pa_val1.w);
pa_out.arr[1][3] = 0;
pa_out.arr[2][0] = (2 * pa_val1.x*pa_val1.z) + (2 * pa_val1.y*pa_val1.w);
pa_out.arr[2][1] = (2 * pa_val1.y*pa_val1.z) - (2 * pa_val1.x*pa_val1.w);
pa_out.arr[2][2] = 1 - (2 * pa_val1.x*pa_val1.x) - (2 * pa_val1.y*pa_val1.y);
pa_out.arr[2][3] = 0;
pa_out.arr[3][0] = 0;
pa_out.arr[3][1] = 0;
pa_out.arr[3][2] = 0;
pa_out.arr[3][3] = 1;
return pa_out;
}
static public CVec3 QutToEuler(CVec4 pa_qut)
{
CVec3 pa_radian=new CVec3();
float x, y, z, w;
x = pa_qut.x;
y = pa_qut.y;
z = pa_qut.z;
w = pa_qut.w;
float sqx = x * x;
float sqy = y * y;
float sqz = z * z;
float sqw = w * w;
pa_radian.x = (float) Math.asin(2.0f * (pa_qut.w*pa_qut.x - pa_qut.y*pa_qut.z)); // rotation about x-axis
pa_radian.y = (float) Math.atan2(2.0f * (pa_qut.x*pa_qut.z + pa_qut.w*pa_qut.y), (-sqx - sqy + sqz + sqw)); // rotation about y-axis
pa_radian.z = (float) Math.atan2(2.0f * (pa_qut.x*pa_qut.y + pa_qut.w*pa_qut.z), (-sqx + sqy - sqz + sqw)); // rotation about z-axis
return pa_radian;
}
static public CMat QutToMatrix(CVec4 pa_val1)
{
CMat pa_out=new CMat();
pa_out.arr[0][0] = 1 - (2 * pa_val1.y*pa_val1.y) - (2 * pa_val1.z*pa_val1.z);
pa_out.arr[0][1] = (2 * pa_val1.x*pa_val1.y) + (2 * pa_val1.z*pa_val1.w);
pa_out.arr[0][2] = (2 * pa_val1.x*pa_val1.z) - (2 * pa_val1.y*pa_val1.w);
pa_out.arr[0][3] = 0;
pa_out.arr[1][0] = (2 * pa_val1.x*pa_val1.y) - (2 * pa_val1.z*pa_val1.w);
pa_out.arr[1][1] = 1 - (2 * pa_val1.x*pa_val1.x) - (2 * pa_val1.z*pa_val1.z);
pa_out.arr[1][2] = (2 * pa_val1.y*pa_val1.z) + (2 * pa_val1.x*pa_val1.w);
pa_out.arr[1][3] = 0;
pa_out.arr[2][0] = (2 * pa_val1.x*pa_val1.z) + (2 * pa_val1.y*pa_val1.w);
pa_out.arr[2][1] = (2 * pa_val1.y*pa_val1.z) - (2 * pa_val1.x*pa_val1.w);
pa_out.arr[2][2] = 1 - (2 * pa_val1.x*pa_val1.x) - (2 * pa_val1.y*pa_val1.y);
pa_out.arr[2][3] = 0;
pa_out.arr[3][0] = 0;
pa_out.arr[3][1] = 0;
pa_out.arr[3][2] = 0;
pa_out.arr[3][3] = 1;
return pa_out;
}
//Ray and Collision================================================================
static public boolean RayTriangleIS(CVec3 pa_one,CVec3 pa_two,
CVec3 pa_three, CThreeVec3 pa_ray, float pa_dist, boolean pa_ccw)//IS -> Intersection
{
CMsg.E("java Ͱ ");
float det, u, v, dist;
CVec3 pvec=new CVec3();
CVec3 tvec=new CVec3();
CVec3 qvec=new CVec3();
CVec3 edge1 = Vec3MinusVec3(pa_two, pa_one);
CVec3 edge2 = Vec3MinusVec3(pa_three, pa_one);
CVec3 L_dir = Vec3MinusVec3(pa_ray.GetOriginal(), pa_one);
if (L_dir.x == 0 && L_dir.y == 0 && L_dir.z == 0)
{
pa_dist = 0.00001f;
return true;
}
else
{
L_dir = Vec3Normalize(L_dir);
det = Vec3Dot(L_dir, Vec3MulFloat(pa_ray.GetDirect(), -1));
if (det < 0)// pa_ccw)
{
return false;
}
}
pvec = Vec3Cross(pa_ray.GetDirect(), edge2);
det = Vec3Dot(edge1, pvec);
if (det > 0)
{
tvec = Vec3MinusVec3(pa_ray.GetOriginal(), pa_one);
}
else//̺κ ø Ҽ ִ!
{
tvec = Vec3MinusVec3(pa_one, pa_ray.GetOriginal());
det = -det;
//L_back=true;
if (pa_ccw)
{
return false;
}
}
if (det < 0.000001f)
{
return false;
}
u = Vec3Dot(tvec, pvec);
if (u < 0.0f || u > det)
{
return false;
}
qvec = Vec3Cross(tvec, edge1);
v = Vec3Dot(pa_ray.GetDirect(), qvec);
if (v < 0.0f || u + v > det)
{
return false;
}
dist = Vec3Dot(edge2, qvec);
dist *= (1.0f / det);
pa_dist = dist;
return true;
}
static public boolean RayBoxIS(CVec3 _min, CVec3 _max, CThreeVec3 pa_ray)
{
boolean inside = true;
int quadrant[] = {0,0,0};
int i;
int whichPlane;
float maxT[] = {0,0,0};
float candidatePlane[] = {0,0,0};
var vecList=pa_ray.GetVecList();
float pOrigin[] = { vecList[2].x ,vecList[2].y ,vecList[2].z };
float pBoxMin[] = { _min.x,_min.y,_min.z };
float pBoxMax[] = { _max.x,_max.y,_max.z };
float pDir[] = { vecList[0].x ,vecList[0].y ,vecList[0].z };
float pIntersect[] = { 0 ,0,0 };
//ڽ 1 ྿ Ѵ üũѴ
//˵Ÿ ּ,ִ Ÿ ִ´
for (i = 0; i < 3; ++i)
{
if (pOrigin[i] < pBoxMin[i])
{
quadrant[i] = RayBoxLEFT;
candidatePlane[i] = pBoxMin[i];
inside = false;
}
else if (pOrigin[i] > pBoxMax[i])
{
quadrant[i] = RayBoxRIGHT;
candidatePlane[i] = pBoxMax[i];
inside = false;
}
else
{
quadrant[i] = RayBoxMIDDLE;
}
}
//´ ̸ ̴
if (inside)
{
//浹 ڽ ǥ
pa_ray.SetPosition(new CVec3(pOrigin[0], pOrigin[1], pOrigin[2]));
return true;
}
// Calculate T distances to candidate planes
for (i = 0; i < 3; i++)
{
//߽̾ƴϿ ʹ н
if (quadrant[i] != RayBoxMIDDLE &&
(pDir[i] > d_EPSILON || pDir[i] < -d_EPSILON))
{
//(ƽø-ġ)/
maxT[i] = (candidatePlane[i] - pOrigin[i]) / pDir[i];
}
//ƴϸ ̱ -1
else
{
maxT[i] = -1.0f;
}
}
// ū ã
whichPlane = 0;
for (i = 1; i < 3; i++)
{
if (maxT[whichPlane] < maxT[i])
whichPlane = i;
}
// 0 浹 ƴѻȲ
if (maxT[whichPlane] < 0.0f)
{
return false;
}
for (i = 0; i < 3; i++)
{
// ū ƴѰ
if (whichPlane != i)
{
//浹 ϰ
pIntersect[i] = pOrigin[i] + maxT[whichPlane] * pDir[i];
//,ƽ Ѿ 쵵 н
if (pIntersect[i] < pBoxMin[i] || pIntersect[i] > pBoxMax[i])
{
return false;
}
}
else
{
//
pIntersect[i] = candidatePlane[i];
}
}
pa_ray.SetPosition(new CVec3(pIntersect[0], pIntersect[1], pIntersect[2]));
return true;
}
// ŷ ִ°
static public boolean RaySphereIS(CVec3 pa_center, float pa_radian, CThreeVec3 pa_ray)
{
CVec3 l = Vec3MinusVec3(pa_center, pa_ray.GetOriginal());
float s = Vec3Dot(l, Vec3Normalize(pa_ray.GetDirect()));
float l2 = Vec3Dot(l, l);
float r2 = (float) Math.pow(pa_radian, 2);
if (s < 0 && l2 > r2) // ƿ ٸ ̰ ũٴ° ο ٴ ǹ
{
return false; // ݴ ϰų ģ
}
float s2 = (float) Math.pow(s, 2);
float m2 = l2 - s2;
if (m2 > r2)
{
return false; //
}
float q = (float) Math.sqrt(r2 - m2);
float distance;
//// ϴ°?
if (l2 > r2)
{
distance = s - q;
}
else
{
distance = s + q;
}
pa_ray.SetPosition(Vec3PlusVec3(pa_ray.GetOriginal(), Vec3MulFloat(pa_ray.GetDirect(), distance)));
return true;
}
static public float ColSphereSphere(CVec3 _posA, float _radiusA,CVec3 _posB, float _radiusB)
{
float vlen = Vec3Lenght(Vec3MinusVec3(_posA, _posB));
if (vlen <= _radiusA + _radiusB)
return (_radiusA + _radiusB)-vlen;
return -1;
}
static public CVec4 Vec3toPlane(CVec3 pa_vec1,CVec3 pa_vec2,CVec3 pa_vec3)
{
CVec4 pa_out=new CVec4();
CVec3 L_temp=new CVec3();
L_temp = Vec3Cross(Vec3MinusVec3(pa_vec2, pa_vec1), Vec3MinusVec3(pa_vec3, pa_vec1));
L_temp = Vec3Normalize(L_temp);
pa_out = NormalAndVertexFromPlane(L_temp, pa_vec1);
return pa_out;
}
static public CVec4 NormalAndVertexFromPlane(CVec3 pa_normal,CVec3 pa_vertex)
{
CVec4 pa_out=new CVec4();
pa_out.x = pa_normal.x;
pa_out.y = pa_normal.y;
pa_out.z = pa_normal.z;
pa_out.w = -Vec3Dot(pa_normal, pa_vertex);
return pa_out;
}
static public float PlaneVec3DotCoordinate( CVec4 pa_plane, CVec3 pa_vec)
{
return Vec3Dot(new CVec3(pa_plane.x, pa_plane.y, pa_plane.z), pa_vec) + pa_plane.w;
}
static public float PlaneVec3DotNormal( CVec4 pa_plane, CVec3 pa_vec)
{
return Vec3Dot(new CVec3(pa_plane.x, pa_plane.y, pa_plane.z), pa_vec);
}
static public void PlaneSphereInside(CSixVec4 pa_plane, CVec3 pa_posion, float pa_radius, CPlaneOutJoin _poj)
{
float outSize=0;
float inSize=0;
if (_poj.tOutfJoin)
{
outSize = pa_radius;
inSize = 0;
}
else
{
outSize = 0;
inSize = pa_radius;
}
float L_dist = 0;
L_dist = PlaneVec3DotCoordinate(pa_plane.GetBottom(), pa_posion);
if (L_dist + inSize > outSize && (_poj.plane == DfPlane.Bottom || _poj.plane == DfPlane.Null))
{
_poj.plane = DfPlane.Bottom;
_poj.len = L_dist + inSize;
return;
}
L_dist = PlaneVec3DotCoordinate(pa_plane.GetFar(), pa_posion);
if (L_dist + inSize > outSize && (_poj.plane == DfPlane.Far || _poj.plane == DfPlane.Null))
{
_poj.plane = DfPlane.Far;
_poj.len = L_dist + inSize;
return;
}
L_dist = PlaneVec3DotCoordinate(pa_plane.GetLeft(), pa_posion);
if (L_dist + inSize > outSize && (_poj.plane == DfPlane.Left || _poj.plane == DfPlane.Null))
{
_poj.plane = DfPlane.Left;
_poj.len = L_dist + inSize;
return;
}
L_dist = PlaneVec3DotCoordinate(pa_plane.GetNear(), pa_posion);
if (L_dist + inSize > outSize && (_poj.plane == DfPlane.Near || _poj.plane == DfPlane.Null))
{
_poj.plane = DfPlane.Near;
_poj.len = L_dist + inSize;
return;
}
L_dist = PlaneVec3DotCoordinate(pa_plane.GetRight(), pa_posion);
if (L_dist + inSize > outSize && (_poj.plane == DfPlane.Right || _poj.plane == DfPlane.Null))
{
_poj.plane = DfPlane.Right;
_poj.len = L_dist + inSize;
return;
}
L_dist = PlaneVec3DotCoordinate(pa_plane.GetTop(), pa_posion);
if (L_dist + inSize > outSize && (_poj.plane == DfPlane.Top || _poj.plane == DfPlane.Null))
{
_poj.plane = DfPlane.Top;
_poj.len = L_dist + inSize;
return;
}
_poj.plane = DfPlane.Null;
_poj.len = 0;
}
static public float QutDot( CVec4 pa_val1, CVec4 pa_val2)
{
return pa_val1.x*pa_val2.x + pa_val1.y*pa_val2.y + pa_val1.z*pa_val2.z + pa_val1.w*pa_val2.w;
}
static public float FloatInterpolate(float _first, float _second, float pa_time)
{
return _first * (1 - pa_time) + _second * _second*pa_time;
}
static public CVec4 QutInterpolate(CVec4 pa_first, CVec4 pa_second, float pa_time)
{
CVec4 pa_out=new CVec4();
float omega, cosom, sinom, scale0, scale1;
cosom = QutDot(pa_first, pa_second); // = cos()
//float fAngle = acos(fcos);
if (cosom < 0.0f)//ؼ 0 ۴ٴ°
{
cosom *= -1;
pa_first.x *= -1;
pa_first.y *= -1;
pa_first.z *= -1;
pa_first.w *= -1;
}
if ((1.0 - cosom) > 0.0f)
{
// standard case (slerp)
omega = (float) Math.acos(cosom);
sinom = (float) Math.sin(omega);
scale0 = (float) (Math.sin((1.0f - pa_time) * omega) / sinom);
scale1 = (float) (Math.sin(pa_time * omega) / sinom);
}
else {
// "from" and "to" quaternions are very close
// ... so we can do a linear interpolation
scale0 = 1.0f - pa_time;
scale1 = pa_time;
}
// calculate final values
pa_out.x = scale1 * pa_second.x + scale0 * pa_first.x;
pa_out.y = scale1 * pa_second.y + scale0 * pa_first.y;
pa_out.z = scale1 * pa_second.z + scale0 * pa_first.z;
pa_out.w = scale1 * pa_second.w + scale0 * pa_first.w;
return pa_out;
}
static public int CloseToExp(float fInput, float fExponent)
{
if (fInput > 0.0f && fInput <= 1.0f)
return 0;
float fResult = (float) (Math.log(Abs(fInput)) / Math.log(fExponent));
int nResult = (int)fResult;
float fEpsilon = Abs(fResult - (float)((int)fResult));
if (Abs(fEpsilon - 0.0f) <= g_fEpsilon)
return (int)Math.pow(fExponent, nResult);
nResult = (int)Math.pow(fExponent, nResult + 1);
if (fInput < 0.0f)
return -nResult;
return nResult;
}
static public CMat MatRotExport( CMat pa_viewMat, boolean pa_x, boolean pa_y, boolean pa_z)
{
CMat pa_outMat=new CMat();
if (pa_x)
{
pa_outMat.arr[1][1] = pa_viewMat.arr[1][1]; pa_outMat.arr[1][2] = pa_viewMat.arr[1][2];
pa_outMat.arr[2][1] = pa_viewMat.arr[2][1]; pa_outMat.arr[2][2] = pa_viewMat.arr[2][2];
}
if (pa_y)
{
pa_outMat.arr[0][0] = pa_viewMat.arr[0][0]; pa_outMat.arr[0][2] = pa_viewMat.arr[0][2];
pa_outMat.arr[2][0] = pa_viewMat.arr[2][0]; pa_outMat.arr[2][2] = pa_viewMat.arr[2][2];
}
if (pa_z)
{
pa_outMat.arr[0][0] = pa_viewMat.arr[0][0]; pa_outMat.arr[0][1] = pa_viewMat.arr[0][1];
pa_outMat.arr[1][0] = pa_viewMat.arr[1][0]; pa_outMat.arr[1][1] = pa_viewMat.arr[1][1];
}
return pa_outMat;
}
// static public void UvIndexToVertexIndex(Vector<CVec3> pa_po_vertex, Vector<CVec2> pa_po_uv,
// Vector<CVec3> pa_po_normal, Vector<CVec4> pa_po_weight, Vector<CVec4> pa_po_weightIndex,
// Vector<Integer> RF_index, Vector<Integer> RF_Tface)
// {
// d_INT32 L_vertexNum = pa_po_vertex.size();
// d_INT32 L_indexNum = RF_index.size() / 3;
//
// //1. ؽ ε صд
// //d_VEC_VEC3 L_aVer;
// vector<CVec2> L_aUv;
//
// // ε 뿵 д
//
// vector<d_UINT32> L_aIn;
// L_aIn.resize(L_indexNum * 3);
// for (int i = 0; i < L_indexNum * 3; ++i)
// {
// L_aIn[i] = RF_index[i];
// }
//
// vector<s_FACE> L_list;
// L_list.resize(L_vertexNum);
//
// for (d_INT32 i = 0; i < L_indexNum; ++i)
// {
// for (d_INT32 j = 0; j < (d_INT32)L_list[RF_index[i * 3 + 0]].Tface.size(); ++j)
// {
// if (L_list[RF_index[i * 3] + 0].Tface[j] == RF_Tface[i * 3 + 0])
// {
// RF_index[i * 3 + 0] = L_list[L_aIn[i * 3] + 0].Cindex[j];
// L_list[L_aIn[i * 3 + 0]].Cindex.push_back(RF_index[i * 3 + 0]);
// break;
// }
// if ((d_INT32)L_list[RF_index[i * 3 + 0]].Tface.size() == j + 1)
// {
// pa_po_vertex.push_back(pa_po_vertex[RF_index[i * 3 + 0]]);
// RF_index[i * 3 + 0] = (d_INT32)pa_po_vertex.size() - 1;
// L_list[L_aIn[i * 3 + 0]].Cindex.push_back(RF_index[i * 3 + 0]);
// break;
// }
//
// }
//
// L_list[L_aIn[i * 3 + 0]].Tface.push_back(RF_Tface[i * 3 + 0]);
// if (L_list[L_aIn[i * 3 + 0]].Cindex.empty())
// L_list[L_aIn[i * 3 + 0]].Cindex.push_back(L_aIn[i * 3 + 0]);
// //======================================================
// for (d_INT32 j = 0; j < (d_INT32)L_list[RF_index[i * 3 + 1]].Tface.size(); ++j)
// {
// if (L_list[RF_index[i * 3 + 1]].Tface[j] == RF_Tface[i * 3 + 1])
// {
// RF_index[i * 3 + 1] = L_list[L_aIn[i * 3 + 1]].Cindex[j];
// L_list[L_aIn[i * 3 + 1]].Cindex.push_back(RF_index[i * 3 + 1]);
// break;
// }
// if ((d_INT32)L_list[RF_index[i * 3 + 1]].Tface.size() == j + 1)
// {
// pa_po_vertex.push_back(pa_po_vertex[RF_index[i * 3 + 1]]);
// RF_index[i * 3 + 1] = (d_INT32)pa_po_vertex.size() - 1;
// L_list[L_aIn[i * 3 + 1]].Cindex.push_back(RF_index[i * 3 + 1]);
// break;
// }
//
// }
//
// L_list[L_aIn[i * 3 + 1]].Tface.push_back(RF_Tface[i * 3 + 1]);
// if (L_list[L_aIn[i * 3 + 1]].Cindex.empty())
// L_list[L_aIn[i * 3 + 1]].Cindex.push_back(L_aIn[i * 3 + 1]);
// //======================================================
// for (d_INT32 j = 0; j < (d_INT32)L_list[RF_index[i * 3 + 2]].Tface.size(); ++j)
// {
// if (L_list[RF_index[i * 3 + 2]].Tface[j] == RF_Tface[i * 3 + 2])
// {
// RF_index[i * 3 + 2] = L_list[L_aIn[i * 3 + 2]].Cindex[j];
// L_list[L_aIn[i * 3 + 2]].Cindex.push_back(RF_index[i * 3 + 2]);
// break;
// }
// if ((d_INT32)L_list[RF_index[i * 3 + 2]].Tface.size() == j + 1)
// {
// pa_po_vertex.push_back(pa_po_vertex[RF_index[i * 3 + 2]]);
// RF_index[i * 3 + 2] = (d_INT32)pa_po_vertex.size() - 1;
// L_list[L_aIn[i * 3 + 2]].Cindex.push_back(RF_index[i * 3 + 2]);
// break;
// }
//
// }
//
// L_list[L_aIn[i * 3 + 2]].Tface.push_back(RF_Tface[i * 3 + 2]);
// if (L_list[L_aIn[i * 3 + 2]].Cindex.empty())
// L_list[L_aIn[i * 3 + 2]].Cindex.push_back(L_aIn[i * 3 + 2]);
//
//
// }
// //delete [] mpar_uv;
//
// L_vertexNum = (d_INT32)pa_po_vertex.size();
// vector<CVec2> L_uv;
// L_uv.resize(L_vertexNum);
//
//
//
//
//
// if (pa_po_vertex.empty())
// CMsg.E("üũڵ");
// vector<CVec3> L_nor;
// vector<CVec4> L_we;
// vector<CVec4> L_weI;
//
// bool L_copy[3] = { 0, };//0븻
// if (!pa_po_normal.empty())
// {
// L_copy[0] = true;
// L_nor.resize(L_vertexNum);
// }
// if (!pa_po_weight.empty())
// {
// L_copy[1] = true;
// L_we.resize(L_vertexNum);
// }
// if (!pa_po_weightIndex.empty())
// {
// L_copy[2] = true;
// L_weI.resize(L_vertexNum);
// }
//
//
//
// for (d_INT32 i = 0; i < L_indexNum; ++i)
// {
// L_uv[RF_index[i * 3] + 0] = pa_po_uv[RF_Tface[i * 3] + 0];
// L_uv[RF_index[i * 3 + 1]] = pa_po_uv[RF_Tface[i * 3 + 1]];
// L_uv[RF_index[i * 3 + 2]] = pa_po_uv[RF_Tface[i * 3 + 2]];
// if (L_copy[0])
// {
//
// L_nor[RF_index[i * 3] + 0] = pa_po_normal[L_aIn[i * 3] + 0];
// L_nor[RF_index[i * 3 + 1]] = pa_po_normal[L_aIn[i * 3 + 1]];
// L_nor[RF_index[i * 3 + 2]] = pa_po_normal[L_aIn[i * 3 + 2]];
// }
// if (L_copy[1])
// {
// CMsg.E("ġ Ʈ ߽");
// L_we[RF_index[i * 3] + 0] = pa_po_weight[L_aIn[i * 3] + 0];
// L_we[RF_index[i * 3 + 1]] = pa_po_weight[L_aIn[i * 3 + 1]];
// L_we[RF_index[i * 3 + 2]] = pa_po_weight[L_aIn[i * 3 + 2]];
// }
// if (L_copy[2])
// {
// L_weI[RF_index[i * 3] + 0] = pa_po_weightIndex[L_aIn[i * 3] + 0];
// L_weI[RF_index[i * 3 + 1]] = pa_po_weightIndex[L_aIn[i * 3 + 1]];
// L_weI[RF_index[i * 3 + 2]] = pa_po_weightIndex[L_aIn[i * 3 + 2]];
// }
// }
//
// pa_po_uv.swap(L_uv);
// if (L_copy[0])
// pa_po_normal.swap(L_nor);
// if (L_copy[1])
// pa_po_weight.swap(L_we);
// if (L_copy[2])
// pa_po_weightIndex.swap(L_weI);
//
// }
static public CMat MatTranspose(CMat _mat)
{
CMat L_out=new CMat();
for (int y = 0; y < 4; ++y)
{
for (int x = 0; x < 4; ++x)
{
if (x == y)
continue;
L_out.arr[x][y] = _mat.arr[y][x];
}
}
return L_out;
}
static public CBound BoundMulMat( CBound _bound, CMat _mat)
{
CBound rBound=new CBound();
rBound.min = MatToVec3Normal(_bound.min, _mat);
rBound.max = MatToVec3Normal(_bound.max, _mat);
return rBound;
}
static public boolean ColBoxBoxOBB(CBound _boundA, CMat _matA, CBound _boundB, CMat _matB)
{
CVec3 L_center[]=new CVec3[2];
CVec3 L_dir[][]=new CVec3[2][3];
CVec3 L_len[]=new CVec3[2];
CVec3 L_rLen[]=new CVec3[2];
L_rLen[0]=new CVec3();
L_rLen[1]=new CVec3();
L_dir[0][0] = new CVec3(_matA.arr[0][0], _matA.arr[0][1], _matA.arr[0][2]);
L_dir[0][1] = new CVec3(_matA.arr[1][0], _matA.arr[1][1], _matA.arr[1][2]);
L_dir[0][2] = new CVec3(_matA.arr[2][0], _matA.arr[2][1], _matA.arr[2][2]);
L_dir[1][0] = new CVec3(_matB.arr[0][0], _matB.arr[0][1], _matB.arr[0][2]);
L_dir[1][1] = new CVec3(_matB.arr[1][0], _matB.arr[1][1], _matB.arr[1][2]);
L_dir[1][2] = new CVec3(_matB.arr[2][0], _matB.arr[2][1], _matB.arr[2][2]);
L_center[0] = _matA.GetPos();
L_center[1] = _matB.GetPos();
L_dir[0][0] = Vec3Normalize(L_dir[0][0]);
L_dir[0][1] = Vec3Normalize(L_dir[0][1]);
L_dir[0][2] = Vec3Normalize(L_dir[0][2]);
L_dir[1][0] = Vec3Normalize(L_dir[1][0]);
L_dir[1][1] = Vec3Normalize(L_dir[1][1]);
L_dir[1][2] = Vec3Normalize(L_dir[1][2]);
L_len[0] = _boundA.GetRadiusLen();
L_len[1] = _boundB.GetRadiusLen();
L_rLen[0].x = Vec3Lenght(new CVec3(_matA.arr[0][0], _matA.arr[0][1], _matA.arr[0][2]));
L_rLen[0].y = Vec3Lenght(new CVec3(_matA.arr[1][0], _matA.arr[1][1], _matA.arr[1][2]));
L_rLen[0].z = Vec3Lenght(new CVec3(_matA.arr[2][0], _matA.arr[2][1], _matA.arr[2][2]));
L_rLen[1].x = Vec3Lenght(new CVec3(_matB.arr[0][0], _matB.arr[0][1], _matB.arr[0][2]));
L_rLen[1].y = Vec3Lenght(new CVec3(_matB.arr[1][0], _matB.arr[1][1], _matB.arr[1][2]));
L_rLen[1].z = Vec3Lenght(new CVec3(_matB.arr[2][0], _matB.arr[2][1], _matB.arr[2][2]));
L_len[0].x *= L_rLen[0].x;
L_len[0].y *= L_rLen[0].y;
L_len[0].z *= L_rLen[0].z;
L_len[1].x *= L_rLen[1].x;
L_len[1].y *= L_rLen[1].y;
L_len[1].z *= L_rLen[1].z;
//XZ -1~1 Y 0~2 ϸ ݸŭ
//κ
//L_center[0].y+=(pa_A.max.y*L_rLen[0].y)-L_len[0].y;
//L_center[1].y+=(pa_B.max.y*L_rLen[1].y)-L_len[1].y;
CVec3 L_diff[]=new CVec3[2];
L_diff[0] = Vec3MulFloat(Vec3PlusVec3(_boundA.max, _boundA.min), 0.5f);
L_diff[1] = Vec3MulFloat(Vec3PlusVec3(_boundB.max, _boundB.min), 0.5f);
L_diff[0] = MatToVec3Normal(L_diff[0], _matA);
L_diff[1] = MatToVec3Normal(L_diff[1], _matB);
L_center[0] = Vec3PlusVec3(L_center[0], L_diff[0]);
L_center[1] = Vec3PlusVec3(L_center[1], L_diff[1]);
// ⼭ R0 OBB A interval radius, R1 OBB B interval radius, R 2 OBB ߽ Ÿ Ÿ.
// D ʹ 2 OBB ߽ մ Ÿ.
// Cij rotation matrix R (i,j) Ÿ.
float c[][]=new float[3][3];
float absC[][]=new float[3][3];
float d[]=new float[3];
float r0, r1, r;
int i;
float cutoff = 0.999999f;
boolean existsParallelPair = false;
CVec3 diff = Vec3MinusVec3(L_center[0], L_center[1]);
//3 ϰ A0,A1,A2 Ѵ
for (i = 0; i < 3; ++i)
{
//Aڽ B r1 Ѵ
c[0][i] = Vec3Dot(L_dir[0][0], L_dir[1][i]);
// Ļ 90 -ε
//A Ѵٴ ǹ̷ ߴ
absC[0][i] = Abs(c[0][i]);
if (absC[0][i] > cutoff)
existsParallelPair = true;
}
//Aڽ D ϰ
d[0] = Vec3Dot(diff, L_dir[0][0]);
r = Abs(d[0]);
r0 = L_len[0].x;
r1 = L_len[1].x * absC[0][0] + L_len[1].y * absC[0][1] + L_len[1].z * absC[0][2];
if (r > r0 + r1)// ؼ R ũ и ̴
return false;
for (i = 0; i < 3; ++i)
{
c[1][i] = Vec3Dot(L_dir[0][1], L_dir[1][i]);
absC[1][i] = Abs(c[1][i]);
if (absC[1][i] > cutoff)
existsParallelPair = true;
}
d[1] = Vec3Dot(diff, L_dir[0][1]);
r = Abs(d[1]);
r0 = L_len[0].y;
r1 = L_len[1].x * absC[1][0] + L_len[1].y * absC[1][1] + L_len[1].z * absC[1][2];
if (r > r0 + r1)
return false;
for (i = 0; i < 3; ++i)
{
c[2][i] = Vec3Dot(L_dir[0][2], L_dir[1][i]);
absC[2][i] = Abs(c[2][i]);
if (absC[2][i] > cutoff)
existsParallelPair = true;
}
d[2] = Vec3Dot(diff, L_dir[0][2]);
r = Abs(d[2]);
r0 = L_len[0].z;
r1 = L_len[1].x * absC[2][0] + L_len[1].y * absC[2][1] + L_len[1].z * absC[2][2];
if (r > r0 + r1)
return false;
//A ɰ B0,..Ѵ
r = Abs(Vec3Dot(diff, L_dir[1][0]));
r0 = L_len[0].x * absC[0][0] + L_len[0].y * absC[1][0] + L_len[0].z * absC[2][0];
r1 = L_len[1].x;
if (r > r0 + r1)
return false;
r = Abs(Vec3Dot(diff, L_dir[1][1]));
r0 = L_len[0].x * absC[0][1] + L_len[0].y * absC[1][1] + L_len[0].z * absC[2][1];
r1 = L_len[1].y;
if (r > r0 + r1)
return false;
r = Abs(Vec3Dot(diff, L_dir[1][2]));
r0 = L_len[0].x * absC[0][2] + L_len[0].y * absC[1][2] + L_len[0].z * absC[2][2];
r1 = L_len[1].z;
if (r > r0 + r1)
return false;
//浹 ̴
if (existsParallelPair == true)
return true;
r = Abs(d[2] * c[1][0] - d[1] * c[2][0]);
r0 = L_len[0].y * absC[2][0] + L_len[0].z * absC[1][0];
r1 = L_len[1].y * absC[0][2] + L_len[1].z * absC[0][1];
if (r > r0 + r1)
return false;
r = Abs(d[2] * c[1][1] - d[1] * c[2][1]);
r0 = L_len[0].y * absC[2][1] + L_len[0].z * absC[1][1];
r1 = L_len[1].x * absC[0][2] + L_len[1].z * absC[0][0];
if (r > r0 + r1)
return false;
r = Abs(d[2] * c[1][2] - d[1] * c[2][2]);
r0 = L_len[0].y * absC[2][2] + L_len[0].z * absC[1][2];
r1 = L_len[1].x * absC[0][1] + L_len[1].y * absC[0][0];
if (r > r0 + r1)
return false;
r = Abs(d[0] * c[2][0] - d[2] * c[0][0]);
r0 = L_len[0].x * absC[2][0] + L_len[0].z * absC[0][0];
r1 = L_len[1].y * absC[1][2] + L_len[1].z * absC[1][1];
if (r > r0 + r1)
return false;
r = Abs(d[0] * c[2][1] - d[2] * c[0][1]);
r0 = L_len[0].x * absC[2][1] + L_len[0].z * absC[0][1];
r1 = L_len[1].x * absC[1][2] + L_len[1].z * absC[1][0];
if (r > r0 + r1)
return false;
r = Abs(d[0] * c[2][2] - d[2] * c[0][2]);
r0 = L_len[0].x * absC[2][2] + L_len[0].z * absC[0][2];
r1 = L_len[1].x * absC[1][1] + L_len[1].y * absC[1][0];
if (r > r0 + r1)
return false;
r = Abs(d[1] * c[0][0] - d[0] * c[1][0]);
r0 = L_len[0].x * absC[1][0] + L_len[0].y * absC[0][0];
r1 = L_len[1].y * absC[2][2] + L_len[1].z * absC[2][1];
if (r > r0 + r1)
return false;
r = Abs(d[1] * c[0][1] - d[0] * c[1][1]);
r0 = L_len[0].x * absC[1][1] + L_len[0].y * absC[0][1];
r1 = L_len[1].x * absC[2][2] + L_len[1].z * absC[2][0];
if (r > r0 + r1)
return false;
r = Abs(d[1] * c[0][2] - d[0] * c[1][2]);
r0 = L_len[0].x * absC[1][2] + L_len[0].y * absC[0][2];
r1 = L_len[1].x * absC[2][1] + L_len[1].y * absC[2][0];
if (r > r0 + r1)
return false;
return true;
}
public static int d_COSTMUL = 100;
public static int Manhattan(CVec3 pa_distination, CVec3 pa_point)
{
return (int)((Abs(pa_distination.x - pa_point.x) +
Abs(pa_distination.y - pa_point.y) +
Abs(pa_distination.z - pa_point.z))*d_COSTMUL);
}
public static float TwoVec3DirAngle(CVec3 pa_vec1, CVec3 pa_vec2)
{
float radian;
pa_vec1 = Vec3Normalize(pa_vec1);
pa_vec2 = Vec3Normalize(pa_vec2);
CVec3 L_cro = Vec3Cross(pa_vec1, pa_vec2);
radian = (float) Math.acos(Vec3Dot(pa_vec2, pa_vec1));
float dir = L_cro.x + L_cro.y + L_cro.z;
if (dir < 0)
radian = -radian;
return radian;
}
};
| true |
002a39847d6f1e4b49034762a56645f19633bcf9
|
Java
|
naaoo/PracticeNew
|
/CountLetters/src/com/company/Main.java
|
UTF-8
| 1,785 | 3.1875 | 3 |
[] |
no_license
|
package com.company;
public class Main {
public static void main(String[] args) {
String[] alphabet = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "X", "Y", "Z"};
int[] counts = new int[26];
String inputString = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.".toUpperCase();
for (int i = 0; i < inputString.length(); i++) { //Schleife inputString iterieren
String inputLetter = inputString.substring(i, i + 1);
getIndexOfLetter(alphabet, counts, inputLetter);
}
for (int i = 0; i < alphabet.length; i++) { //Output
System.out.println("Der Buchstabe " + alphabet[i] + " kommt " + counts[i] + " mal vor");
}
}
public static void getIndexOfLetter(String[] alphabet, int[] counts, String inputLetter) {
for (int j = 0; j < alphabet.length; j++) { //Schleife alphabet iterieren
String alphabetletter = alphabet[j];
if (inputLetter.equals(alphabetletter)) {
counts[j] = counts[j] + 1;
}
}
}
}
| true |
f0df3e2f94d513935feb53a523376bd70e1ec72e
|
Java
|
devproandroid2017/Duonglkh
|
/app/src/main/java/com/example/windows7/demoandroidapp/Main2Activity.java
|
UTF-8
| 1,292 | 2.296875 | 2 |
[] |
no_license
|
package com.example.windows7.demoandroidapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class Main2Activity extends AppCompatActivity {
ArrayList<List>contacts = new ArrayList<>();
android.widget.ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
listView = (android.widget.ListView) findViewById(R.id.listView);
contacts.add(new ListView("Calendar","System", "CPU : 0%", "1"));
contacts.add(new ListView("Contacts","System", "CPU : 0%", "2"));
contacts.add(new ListView("Facebook","Background", "CPU : 28%", "3"));
contacts.add(new ListView("Twitter","Background", "CPU : 0%", "4"));
contacts.add(new ListView("Messaging","System", "CPU : 0%", "5"));
contacts.add(new ListView("Dictionary Provider","System", "CPU : 0%", "6"));
contacts.add(new ListView("Music FX","System", "CPU : 0%", "7"));
contacts.add(new ListView("Nfc Service","System", "CPU : 0%", "8"));
ListAdapter contactAdapter = new ListAdapter(contacts);
listView.setAdapter(contactAdapter);
}
}
| true |
728ba403aa97ccce50b575ad8c785a201992dab1
|
Java
|
wisdomledger/wwallet
|
/src/main/java/wisdomledger/wwallet/Key.java
|
UTF-8
| 1,856 | 2.34375 | 2 |
[] |
no_license
|
package wisdomledger.wwallet;
import java.math.BigInteger;
import java.util.Arrays;
import org.spongycastle.asn1.x9.X9ECParameters;
import org.spongycastle.crypto.digests.SHA512Digest;
import org.spongycastle.crypto.ec.CustomNamedCurves;
import org.spongycastle.crypto.macs.HMac;
import org.spongycastle.crypto.params.ECDomainParameters;
import org.spongycastle.crypto.params.KeyParameter;
import org.spongycastle.math.ec.ECPoint;
import org.spongycastle.math.ec.FixedPointCombMultiplier;
public class Key {
X9ECParameters CURVE_PARAMS = CustomNamedCurves.getByName("secp256k1");
ECDomainParameters CURVE = new ECDomainParameters(CURVE_PARAMS.getCurve(),
CURVE_PARAMS.getG(), CURVE_PARAMS.getN(), CURVE_PARAMS.getH());
// byte[] k;
BigInteger k;
ECPoint K;
byte[] chainCode;
public Key(byte[] seed) {
super();
byte[] i = hmac_sha512(seed);
k = new BigInteger(1, Arrays.copyOfRange(i, 0, 32));
K = kToK(k);
chainCode = Arrays.copyOfRange(i, 32, 64);
}
static HMac createHmacSha512Digest(byte[] key) {
SHA512Digest digest = new SHA512Digest();
HMac hMac = new HMac(digest);
hMac.init(new KeyParameter(key));
return hMac;
}
static byte[] hmacSha512(HMac hmacSha512, byte[] input) {
hmacSha512.reset();
hmacSha512.update(input, 0, input.length);
byte[] out = new byte[64];
hmacSha512.doFinal(out, 0);
return out;
}
// k to K
ECPoint kToK(BigInteger k) {
ECPoint K = new FixedPointCombMultiplier().multiply(CURVE.getG(), k);
return K;
}
byte[] hmac_sha512(byte[] seed) {
return hmacSha512(createHmacSha512Digest("Bitcoin seed".getBytes()),
seed);
}
public BigInteger getk() {
return k;
}
public ECPoint getK() {
return K;
}
public byte[] getChainCode() {
return chainCode;
}
}
| true |
5c7572889b16cbec7a61c40364aea7763d77c1cf
|
Java
|
JiangtoYan/GitDemo
|
/sccp_library/src/com/sccp/library/widget/TabButton.java
|
UTF-8
| 10,179 | 2.0625 | 2 |
[] |
no_license
|
package com.sccp.library.widget;
import com.sccp.frame.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class TabButton extends HorizontalScrollView {
private static final int DEF_LINE_COLOR = 0x66000000;
private static final int DEF_SLIDER_COLOR = 0xFF6595F9;
private static final int DEF_TEXT_COLOR = 0xFF000000;
private static final int DEF_TAB_PADDING = 20;
private static final float DEF_BOTTON_LINE_SIZE = 0.5f;
private static final float DEF_DIVIDER_SIZE = 20f;
private static final float DEF_SLIDER_SIZE = 4f;
private static final float DEF_TEXT_SIZE = 14f;
private int screenWidth;
private LinearLayout mLinearLayout;
private ViewPager mViewPager;
private int mButtonBackground; // 按钮背景
private float mTextSize; // 字体大小
private int mTextColor; // 字体颜色
private Paint sliderPaint; // 滑块的画笔
private Paint bottomPaint; // 底部线条的画笔
private Paint dividerPaint; // 分割线的画笔
private float dividerSize; // 分割线高度
private float bottomLineSize; // 底部线高度
private float sliderSize; // 滑块高度
private int sliderWidth; // 滑块宽度
private int tabSize; // 选项卡的个数
private int tabPadding; // 选项卡的边距
private int pageSelect; // 当前选中的页面
private float scrollOffset; // 滑块已经滑动过的宽度
private TabsButtonOnClickListener onClickListener;
public TabButton(Context context) {
super(context);
init(context, null);
}
public TabButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public TabButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final int layoutHeight = getHeight();
final int layoutWidth = getWidth();
// 绘制分割线
for (int i = 0; i < mLinearLayout.getChildCount(); i++) {
View view = mLinearLayout.getChildAt(i);
float pianyi = (layoutHeight - dividerSize) / 2;
canvas.drawRect(view.getLeft()-1f, pianyi, view.getLeft(), layoutHeight - pianyi, dividerPaint);
//width = view.getWidth();
}
// 绘制滑块
canvas.drawRect(scrollOffset, layoutHeight - sliderSize, scrollOffset + sliderWidth, layoutHeight, sliderPaint);
// 绘制底线
canvas.drawRect(0, layoutHeight - bottomLineSize, layoutWidth, layoutHeight, bottomPaint);
}
private void init(Context context, AttributeSet attrs) {
TypedArray tArray = context.obtainStyledAttributes(attrs, R.styleable.TabButton);
mButtonBackground = tArray.getResourceId(R.styleable.TabButton_buttonBackground, R.drawable.background_tabs);
int bottomLineColor = tArray.getColor(R.styleable.TabButton_bottomLineColor, DEF_LINE_COLOR);
int dividerColor = tArray.getColor(R.styleable.TabButton_dividerColor, DEF_LINE_COLOR);
int sliderColor = tArray.getColor(R.styleable.TabButton_sliderColor, DEF_SLIDER_COLOR);
float defBottonLineSize = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEF_BOTTON_LINE_SIZE,
getResources().getDisplayMetrics());
float defDividerSize = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEF_DIVIDER_SIZE,
getResources().getDisplayMetrics());
float defSliderSize = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEF_SLIDER_SIZE,
getResources().getDisplayMetrics());
float defTextSize = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP,
DEF_TEXT_SIZE,
getResources().getDisplayMetrics());
tabPadding = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEF_TAB_PADDING,
getResources().getDisplayMetrics());
bottomLineSize = tArray.getDimension(R.styleable.TabButton_bottomLineSize, defBottonLineSize);
dividerSize = tArray.getDimension(R.styleable.TabButton_dividerSize, defDividerSize);
sliderSize = tArray.getDimension(R.styleable.TabButton_sliderSize, defSliderSize);
mTextSize = tArray.getDimension(R.styleable.TabButton_textSize, defTextSize);
mTextColor = tArray.getColor(R.styleable.TabButton_textColor, DEF_TEXT_COLOR);
tArray.recycle();
if (isInEditMode()) {
return;
}
mLinearLayout = new LinearLayout(getContext());
//mLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
mLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
mLinearLayout.setGravity(Gravity.CENTER);
addView(mLinearLayout);
setWillNotDraw(false);
setHorizontalScrollBarEnabled(false);
sliderPaint = new Paint();
sliderPaint.setAntiAlias(true);
sliderPaint.setStyle(Style.FILL);
sliderPaint.setColor(sliderColor);
dividerPaint = new Paint();
dividerPaint.setAntiAlias(true);
dividerPaint.setStyle(Style.FILL);
dividerPaint.setColor(dividerColor);
bottomPaint = new Paint();
bottomPaint.setAntiAlias(true);
bottomPaint.setStyle(Style.FILL);
bottomPaint.setColor(bottomLineColor);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
// 当布局确定大小的时候,初始化滑块的位置。
drawUnderLine(pageSelect, 0);
}
public void setViewPager(ViewPager vp) {
this.mViewPager = vp;
vp.setOnPageChangeListener(getOnPageChangeListener());
PagerAdapter pagerAdapter = vp.getAdapter();
int count = pagerAdapter.getCount();
for (int i = 0; i < count; i++) {
addTab(newTextTab(pagerAdapter.getPageTitle(i)));
}
}
@SuppressWarnings("deprecation")
public View newTextTab(CharSequence text) {
TextView tv = new TextView(getContext());
LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT,
1f);
tv.setLayoutParams(lParams);
tv.setGravity(Gravity.CENTER);
tv.setPadding(tabPadding, 0, tabPadding, 0);
tv.setBackgroundResource(mButtonBackground);
tv.setOnClickListener(buttonOnClick);
tv.setTextColor(mTextColor);
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX,mTextSize);
tv.setText(text);
return tv;
}
public void addTab(View view) {
view.setId(tabSize++);
mLinearLayout.addView(view);
}
public void setTab(String... strings) {
for (String text : strings) {
addTab(newTextTab(text));
}
}
public OnPageChangeListener getOnPageChangeListener() {
return new OnPageChangeListener() {
public void onPageSelected(int arg0) {
pageSelect = arg0;
}
public void onPageScrolled(int index, float arg1, int scroll) {
if (scroll != 0)
drawUnderLine(index, arg1);
}
public void onPageScrollStateChanged(int state) {
if(state == ViewPager.SCROLL_STATE_IDLE)
drawUnderLine(pageSelect, 0);
}
};
}
private void drawUnderLine(int index, float scroll){
int itemWidth = mLinearLayout.getChildAt(index).getWidth();
// 滑块的长度。ratio
if (index < tabSize-1) {
int add = mLinearLayout.getChildAt(index+1).getWidth()-itemWidth;
sliderWidth = (int) (scroll * add + itemWidth + 0.5f);
}
// 滑块已经滑动的距离。
scrollOffset = mLinearLayout.getChildAt(index).getLeft() + scroll * itemWidth;
// 控件宽度。
screenWidth = getWidth();
// 滑块中间点距离控件左边的距离。
int half = (int) (scrollOffset+sliderWidth/2);
// 当滑块中间点大于控件宽度一半或水平滚动量大于零时,让滑块保持在控件中间。
if( half > (screenWidth/2)||computeHorizontalScrollOffset()!=0)
scrollTo(half - screenWidth/2, 0);
invalidate();
}
private OnClickListener buttonOnClick = new OnClickListener() {
public void onClick(View v) {
if (onClickListener != null) {
onClickListener.tabsButtonOnClick(v.getId(), v);
}else if (mViewPager!= null){
mViewPager.setCurrentItem(v.getId());
}
}
};
/**
* 监听按钮条被点击的接口。
*
*/
public interface TabsButtonOnClickListener {
void tabsButtonOnClick(int id, View v);
}
public void setTabsButtonOnClickListener(TabsButtonOnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
/**
* 保存滑块的当前位置。当横竖屏切换或Activity被系统杀死时调用。
*/
protected Parcelable onSaveInstanceState() {
Parcelable parcelable = super.onSaveInstanceState();
TabsSaveState tabsSaveState = new TabsSaveState(parcelable);
tabsSaveState.select = pageSelect;
return tabsSaveState;
}
/**
* 还原滑块的位置。
*/
protected void onRestoreInstanceState(Parcelable state) {
TabsSaveState tabsSaveState = (TabsSaveState) state;
super.onRestoreInstanceState(tabsSaveState.getSuperState());
pageSelect = tabsSaveState.select;
drawUnderLine(pageSelect, 0);
}
static class TabsSaveState extends BaseSavedState {
private int select;
public TabsSaveState(Parcelable arg0) {
super(arg0);
}
public TabsSaveState(Parcel arg0) {
super(arg0);
select = arg0.readInt();
}
public int describeContents() {
return super.describeContents();
}
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(select);
}
public static final Parcelable.Creator<TabButton.TabsSaveState> CREATOR = new Parcelable.Creator<TabButton.TabsSaveState>() {
public TabsSaveState createFromParcel(Parcel source) {
return new TabsSaveState(source);
}
public TabsSaveState[] newArray(int size) {
return new TabsSaveState[size];
}
};
}
}
| true |
135ad65eaff1aeec6a51cbaed47029fd2c04801a
|
Java
|
harvminhas/myclerkapp
|
/src/com/harvraja/myclerk/client/event/HomeEventHandler.java
|
UTF-8
| 186 | 1.578125 | 2 |
[] |
no_license
|
package com.harvraja.myclerk.client.event;
import com.google.gwt.event.shared.EventHandler;
public interface HomeEventHandler extends EventHandler{
void onHome(HomeEvent event);
}
| true |
36bf9bc7e6871ac3bc2d0c8622f91d6ae3cfc26f
|
Java
|
viveklimaye/kafka-stream-xml-parsing
|
/src/main/java/com/example/parsing/ModelParser.java
|
UTF-8
| 2,034 | 2.625 | 3 |
[] |
no_license
|
package com.example.parsing;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import com.example.models.BaseModel;
import com.example.models.ResultInfoModel;
import com.example.models.StudentInfoModel;
import com.example.myschema.ExamResult;
import com.example.myschema.ExamResult.Subjects.Subject;
public class ModelParser {
public ExamResult parseData(String xmlDataString) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(ExamResult.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
return (ExamResult) unmarshaller.unmarshal(new StringReader(xmlDataString));
}
public List<BaseModel> getStudentInfoData(ExamResult examResults) {
List<BaseModel> studentInfoModelList = new ArrayList<>();
StudentInfoModel currentModel = new StudentInfoModel();
currentModel.setCurrentClassName(StudentInfoModel.class.getName());
currentModel.setId(examResults.getStudentInfo().getId());
currentModel.setGivenName(examResults.getStudentInfo().getGivenName());
currentModel.setMiddleName(examResults.getStudentInfo().getMiddleName());
currentModel.setLastName(examResults.getStudentInfo().getLastName());
studentInfoModelList.add(currentModel);
return studentInfoModelList;
}
public List<BaseModel> getResultInfoData(ExamResult examResults) {
List<BaseModel> resultInfoModelList = new ArrayList<>();
for (Subject subjectData : examResults.getSubjects().getSubject()) {
ResultInfoModel currentModel = new ResultInfoModel();
currentModel.setCurrentClassName(ResultInfoModel.class.getName());
currentModel.setStudentId(examResults.getStudentInfo().getId());
currentModel.setSubjectCode(subjectData.getCode());
currentModel.setSubject(subjectData.getName());
currentModel.setMarksObtained(subjectData.getMarksObtained());
resultInfoModelList.add(currentModel);
}
return resultInfoModelList;
}
}
| true |
02d64b986b4565d20028f97160e8c5a2f3c73685
|
Java
|
rahulshelke3099/StudyRepo
|
/Java/New folder/Interfacedemo/src/DemoImpl.java
|
UTF-8
| 440 | 2.953125 | 3 |
[] |
no_license
|
public class DemoImpl implements Printable,Scrollable{
@Override
public void print(String msg) {
System.out.println("from print");
}
public static void main(String[] args)
{
System.out.println("var = "+Printable.var);
System.out.println("var = "+Scrollable.var);
Demo obj = new Demo();
obj.method1();
obj.method2();
DemoI ref = new Demo();
ref.method1();
ref.method2();
obj.fromInterface();
}
}
| true |
24a919d917cb4e1975c5a7df957dcd5d038b0bae
|
Java
|
dstockton/java
|
/com/demo/StackTest.java
|
UTF-8
| 343 | 3 | 3 |
[] |
no_license
|
package com.demo;
public class StackTest {
public static void main(String[] args) throws Exception {
Stack<Integer> s = new Stack<>(10000);
for (int i = 0; i < 10000; i++) {
s.push(i);
}
while (!s.isEmpty()) {
s.pop();
}
System.out.println("OK - grab a heap dump now");
while(true){
Thread.sleep(1000);
}
}
}
| true |
cb6082dc7dfddb3b750972b7dc266664280a3eaf
|
Java
|
3dcitydb/web-feature-service
|
/src/main/java/vcs/citydb/wfs/kvp/DescribeFeatureTypeReader.java
|
UTF-8
| 1,855 | 1.984375 | 2 |
[
"Apache-2.0",
"LGPL-3.0-only"
] |
permissive
|
package vcs.citydb.wfs.kvp;
import net.opengis.wfs._2.DescribeFeatureTypeType;
import vcs.citydb.wfs.config.WFSConfig;
import vcs.citydb.wfs.exception.KVPParseException;
import vcs.citydb.wfs.exception.WFSException;
import vcs.citydb.wfs.exception.WFSExceptionCode;
import vcs.citydb.wfs.kvp.parser.FlatValueListParser;
import vcs.citydb.wfs.kvp.parser.QNameParser;
import vcs.citydb.wfs.kvp.parser.StringParser;
import java.util.Map;
public class DescribeFeatureTypeReader extends KVPRequestReader {
private final BaseRequestReader baseRequestReader;
public DescribeFeatureTypeReader(Map<String, String> parameters, WFSConfig wfsConfig) {
super(parameters, wfsConfig);
baseRequestReader = new BaseRequestReader();
}
@Override
public DescribeFeatureTypeType readRequest() throws WFSException {
DescribeFeatureTypeType wfsRequest = new DescribeFeatureTypeType();
baseRequestReader.read(wfsRequest, parameters);
try {
if (parameters.containsKey(KVPConstants.TYPE_NAME))
wfsRequest.getTypeName().addAll(new FlatValueListParser<>(new QNameParser(getNamespaces())).parse(KVPConstants.TYPE_NAME, parameters.get(KVPConstants.TYPE_NAME)));
if (parameters.containsKey(KVPConstants.TYPE_NAMES))
wfsRequest.getTypeName().addAll(new FlatValueListParser<>(new QNameParser(getNamespaces())).parse(KVPConstants.TYPE_NAMES, parameters.get(KVPConstants.TYPE_NAMES)));
if (parameters.containsKey(KVPConstants.OUTPUT_FORMAT))
wfsRequest.setOutputFormat(new StringParser().parse(KVPConstants.OUTPUT_FORMAT, parameters.get(KVPConstants.OUTPUT_FORMAT)));
} catch (KVPParseException e) {
throw new WFSException(WFSExceptionCode.INVALID_PARAMETER_VALUE, e.getMessage(), e.getParameter(), e.getCause());
}
return wfsRequest;
}
@Override
public String getOperationName() {
return KVPConstants.DESCRIBE_FEATURE_TYPE;
}
}
| true |
4aa32c5ed01e45a04e96097b300767e0de0ed81a
|
Java
|
huyleonis/Capstone
|
/KTK/KTK_Server/src/main/java/hackathon/fpt/ktk/dto/AccountDTO.java
|
UTF-8
| 5,197 | 2.265625 | 2 |
[] |
no_license
|
package hackathon.fpt.ktk.dto;
import hackathon.fpt.ktk.entity.Account;
public class AccountDTO {
private int id;
private String username;
private int role;
private String fullname;
private String email;
private String phone;
private String numberId;
private String eWallet;
private int vehicleId;
private String licensePlate;
private String vehicleType;
private String licenseId;
private double balance;
private boolean isActive;
private boolean isEnable;
private boolean loginStatus;
private String token;
public AccountDTO() {
}
public AccountDTO(int id, String username, int role, String fullname, String email, String phone, String numberId,
String eWallet, int vehicleId, String licensePlate, String vehicleType, String licenseId,
double balance, boolean isActive, boolean isEnable, boolean loginStatus, String token) {
this.id = id;
this.username = username;
this.role = role;
this.fullname = fullname;
this.email = email;
this.phone = phone;
this.numberId = numberId;
this.eWallet = eWallet;
this.vehicleId = vehicleId;
this.licensePlate = licensePlate;
this.vehicleType = vehicleType;
this.licenseId = licenseId;
this.balance = balance;
this.isActive = isActive;
this.isEnable = isEnable;
this.loginStatus = loginStatus;
this.token = token;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getRole() {
return role;
}
public void setRole(int role) {
this.role = role;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getNumberId() {
return numberId;
}
public void setNumberId(String numberId) {
this.numberId = numberId;
}
public String geteWallet() {
return eWallet;
}
public void seteWallet(String eWallet) {
this.eWallet = eWallet;
}
public int getVehicleId() {
return vehicleId;
}
public void setVehicleId(int vehicleId) {
this.vehicleId = vehicleId;
}
public String getLicensePlate() {
return licensePlate;
}
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
public String getVehicleType() {
return vehicleType;
}
public void setVehicleType(String vehicleType) {
this.vehicleType = vehicleType;
}
public String getLicenseId() {
return licenseId;
}
public void setLicenseId(String licenseId) {
this.licenseId = licenseId;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
public boolean isEnable() {
return isEnable;
}
public void setEnable(boolean enable) {
isEnable = enable;
}
public boolean isLoginStatus() {
return loginStatus;
}
public void setLoginStatus(boolean loginStatus) {
this.loginStatus = loginStatus;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public static AccountDTO convertFromEntity(Account account) {
if (account == null) {
return null;
}
AccountDTO dto = new AccountDTO();
dto.setId(account.getId());
dto.setUsername(account.getUsername());
dto.setRole(account.getRole());
dto.setFullname(account.getFullname());
dto.setEmail(account.getEmail());
dto.setPhone(account.getPhone());
dto.setNumberId(account.getNumberId());
dto.seteWallet(account.geteWallet());
dto.setLicenseId("ABC-XYZ-11");
if (account.getVehicle() != null) {
dto.setVehicleId(account.getVehicle().getId());
dto.setLicensePlate(account.getVehicle().getLicensePlate());
dto.setVehicleType(account.getVehicle().getVehicleType().getName());
}
if (account.getBalance() != null) {
dto.setBalance(account.getBalance());
}
dto.setActive(account.getActive());
dto.setEnable(account.getEnabled());
dto.setLoginStatus(account.getLoginStatus());
dto.setToken(account.getToken());
return dto;
}
}
| true |
09a3574b36a1e2a28ebdf427f06c5be8b7539c0c
|
Java
|
Joh4nAndersson/saleProcessWithExAndDesPat
|
/src/se/kth/iv1350/saleProcessWithExAndDesPat/model/SaleTest.java
|
UTF-8
| 883 | 2.5 | 2 |
[] |
no_license
|
package se.kth.iv1350.saleProcessWithExAndDesPat.model;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import se.kth.iv1350.saleProcessWithExAndDesPat.integration.ItemNotFoundException;
import se.kth.iv1350.saleProcessWithExAndDesPat.integration.ItemRegistry;
import static org.junit.Assert.*;
public class SaleTest {
ItemRegistry itemRegistry;
Sale sale;
@Before
public void setUp() throws Exception {
itemRegistry = new ItemRegistry();
sale = new Sale(itemRegistry);
}
@After
public void tearDown() throws Exception {
itemRegistry = null;
sale = null;
}
@Test
public void addItem() throws ItemNotFoundException {
sale.addItem(1, 1);
double expectedTotal = 1.0;
double total = sale.getRunningTotal();
assertEquals(expectedTotal, total, 0);
}
}
| true |
6a47c7a9adf85229246e76d02d5277abf3c7b07a
|
Java
|
ylliu/TodoList-java
|
/src/test/java/ItemTest.java
|
UTF-8
| 390 | 2.390625 | 2 |
[] |
no_license
|
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class ItemTest {
@Test
public void should_create_an_item() {
assertThat(new Item("taskName").getName(),is("taskName"));
}
@Test
public void should_return_item_index() {
assertThat(new Item("taskName",1).getIndex(),is(1));
}
}
| true |
0aa8b8e8765dc3e0a7c36985545ef1c51dddc7f7
|
Java
|
LoRod03/MercuryToursScreenPlay
|
/src/main/java/com/mercurytours/automations/userinterfaces/RegistrationPage.java
|
UTF-8
| 275 | 1.632813 | 2 |
[] |
no_license
|
package com.mercurytours.automations.userinterfaces;
import net.serenitybdd.screenplay.targets.Target;
public class RegistrationPage {
public static final Target REGISTRATION_LINK = Target.the("Registration link locator").locatedBy("(//a[@href='register.php'])[1]");
}
| true |
d93cb1defc775e57090af5145623ecc66615f367
|
Java
|
abhijeets1/JAVA
|
/Java Programs/fun().fun().fun()/main_class.java
|
UTF-8
| 404 | 3.171875 | 3 |
[] |
no_license
|
class main_class {
main_class fun_1() {
System.out.println("C");
return this;
}
main_class fun_2() {
System.out.println("C++");
return this;
}
main_class fun_3() {
System.out.println("Java");
return this;
}
public static void main(String[] args) {
main_class obj = new main_class().fun_1().fun_2().fun_3();
System.out.println();
new main_class().fun_1().fun_2().fun_3();
}
}
| true |
9b5bc6a4813671d3c9b40213ce2a63b07e2b9efc
|
Java
|
williambernardet/japi-checker-online
|
/src/main/java/com/googlecode/japi/checker/online/model/WebReport.java
|
UTF-8
| 553 | 2.296875 | 2 |
[
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
package com.googlecode.japi.checker.online.model;
import com.googlecode.japi.checker.Reporter.Report;
import com.googlecode.japi.checker.Severity;
public class WebReport {
private Severity severity;
private String message;
private String source;
public WebReport(Report report) {
severity = report.getSeverity();
message = report.getMessage();
source = report.getSource();
}
public Severity getSeverity() {
return severity;
}
public String getMessage() {
return message;
}
public String getSource() {
return source;
}
}
| true |
9c604adf7b55f4cd8daed0a41f9588f728deaa32
|
Java
|
zhzava/socketio
|
/server/src/com/odin/itms/util/AppConfig.java
|
UTF-8
| 4,207 | 2.265625 | 2 |
[] |
no_license
|
package com.odin.itms.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.odin.itms.constant.Constants;
public class AppConfig {
/**
*
*/
private static final long serialVersionUID = 893965175316829440L;
private static final Logger log = Logger.getLogger(AppConfig.class);
//配置参数
public static final String DATA_PATH_DATA_HOME ="data_path.data_home";
public static final String DATA_HOME ="user_data";
private static Properties environments = null;
private static String localCtxPath = null;
private static String data_home = null;
static Properties properties = new Properties();
static{
init();
}
public static void addProperties(Properties properties){
AppConfig.properties.putAll(properties);
}
public static void addProperty(String key,String value){
properties.put(key, value);
}
public static void removeProperty(String key){
properties.remove(key);
}
public static void init() {
try {
InputStream is = new FileInputStream(new File(System.getProperty("user.dir") + "/conf/Netty-Socket.properties"));
Properties dbProps = new Properties();
dbProps.load(is);
AppConfig.properties.putAll(dbProps);
log.info("读取配置"+System.getProperty("user.dir") + "/conf/Netty-Socket.properties"+"成功!");
} catch (Exception e) {
log.error("不能读取"+System.getProperty("user.dir") + "/conf/Netty-Socket.properties"+"配置文件");
}
}
public static String getProperty(String key){
return properties.getProperty(key);
}
public static String getPropertyEncoding(String key,String encoding){
String str = null;
try {
//进行编码转换,解决问题
str = new String(properties.getProperty(key).getBytes("ISO8859-1"), encoding);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public static String getPropertyEncoding(String key,String defaultValue,String encoding){
String str = null;
try {
//进行编码转换,解决问题
String value=properties.getProperty(key);
if(null == value){
str=defaultValue;
}else{
str = new String(value.getBytes("ISO8859-1"), encoding);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public static String getProperty(String key,String defaultValue){
return properties.getProperty(key,defaultValue);
}
public static String getLocalCtxPath() {
return localCtxPath;
}
public static void setLocalCtxPath(String _localCtxPath) {
localCtxPath = _localCtxPath;
}
public static String getDataHome() {
if(null==data_home){
String _data_home = properties.getProperty(DATA_PATH_DATA_HOME);
if(null!=_data_home && !"".equals(_data_home))
data_home = _data_home;
else
data_home = localCtxPath + "/" + DATA_HOME;
}
return data_home;
}
/**
* mht文件目录
*/
public static String getMhtDataHome(String entryId) {
return getDataHome() + "/" + Constants.FOLDER_NAME_MHT + "/" + entryId;
}
/**
* 临时mht文件目录
* @param user
* @return
*/
public static String getTempMhtDataHome() {
return getDataHome()+"/"+Constants.FOLDER_NAME_TEMPMHT;
}
/**
* ueditor 存放内容的内容目录
*/
public static String getUeditorDataHome(String entryId) {
return getDataHome() + "/" + Constants.FOLDER_NAME_UEDITOR + "/entry/" + entryId;
}
/**
* 存放内容的附件目录
*/
public static String getAttachmentDataHome(String entryId) {
return getDataHome() + "/" + Constants.FOLDER_NAME_ATTACHMENT + "/" + entryId;
}
/**
* zip文件目录
*/
public static String getZipDataHome(String entryId) {
return getDataHome() + "/" + Constants.FOLDER_NAME_ZIP + "/" + entryId;
}
}
| true |
f7210cbd71c68120596f4a3cdf3ad6ce7f7573a4
|
Java
|
quchuangh/anarres
|
/anr-base/anr-rbac-starter/src/main/java/com/chuang/anarres/rbac/model/uo/AbilityUO.java
|
UTF-8
| 1,318 | 2.078125 | 2 |
[] |
no_license
|
package com.chuang.anarres.rbac.model.uo;
import com.chuang.anarres.crud.enums.AbilityType;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
@Data
public class AbilityUO {
@ApiModelProperty(value = "ID")
@NotNull(message = "ID不能为空")
private Integer id;
@ApiModelProperty("父节点ID")
@NotNull(message = "父节点ID不能为空")
private Integer parentId;
@ApiModelProperty("名称")
private String name;
@ApiModelProperty("权限字符")
private String ability;
@ApiModelProperty("权限路径(系统的权限设计没有父子关系,这样做只是为了方便查看)")
private String parents;
@ApiModelProperty("权限类型")
private AbilityType abilityType;
@ApiModelProperty("排序")
private Integer sortRank;
@ApiModelProperty("描述")
private String description;
@ApiModelProperty("是否启用")
private Boolean enabled;
@ApiModelProperty("创建人")
private String creator;
@ApiModelProperty("创建时间")
private LocalDateTime createdTime;
@ApiModelProperty("更新人")
private String updater;
@ApiModelProperty("更新时间")
private LocalDateTime updatedTime;
}
| true |
9dcb36cb7b04c6d246c0f1e7bf8b69c92d438a57
|
Java
|
adrcesar/coursera-ita-java-avancado-forum-mvc
|
/test/TesteTopicoDAO.java
|
UTF-8
| 5,377 | 2.171875 | 2 |
[] |
no_license
|
import Model.Topico;
import Model.Usuario;
import Session.ForumDAO;
import Session.TopicoDAO;
import Session.UsuarioDAO;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.List;
import static org.junit.Assert.assertEquals;
//import java.util.List;
import org.dbunit.Assertion;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.operation.DatabaseOperation;
import org.dbunit.util.fileloader.FlatXmlDataFileLoader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TesteTopicoDAO {
JdbcDatabaseTester jdt;
@Before
public void setUp() throws Exception {
jdt = new JdbcDatabaseTester("org.postgresql.Driver", "jdbc:postgresql://localhost/coursera", "postgres",
"PTacf4994");
FlatXmlDataFileLoader loader = new FlatXmlDataFileLoader();
IDataSet dataSetDeleteComentario = loader.load("/comentario.xml");
jdt.setDataSet(dataSetDeleteComentario);
jdt.setSetUpOperation(DatabaseOperation.DELETE_ALL);
jdt.onSetup();
IDataSet dataSetDeleteTopico = loader.load("/topico.xml");
jdt.setDataSet(dataSetDeleteTopico);
jdt.setSetUpOperation(DatabaseOperation.DELETE_ALL);
jdt.onSetup();
IDataSet dataSetDeleteUsuario = loader.load("/usuario.xml");
jdt.setDataSet(dataSetDeleteUsuario);
jdt.setSetUpOperation(DatabaseOperation.DELETE_ALL);
jdt.onSetup();
IDatabaseConnection connection = jdt.getConnection();
Statement statement = connection.getConnection().createStatement();
statement.execute("alter sequence topico_id_topico_seq RESTART WITH 5");
IDataSet dataSetInsereUsuario = loader.load("/usuario.xml");
jdt.setDataSet(dataSetInsereUsuario);
jdt.setSetUpOperation(DatabaseOperation.INSERT);
jdt.onSetup();
IDataSet dataSetInsereTopico = loader.load("/topico.xml");
jdt.setDataSet(dataSetInsereTopico);
jdt.setSetUpOperation(DatabaseOperation.INSERT);
jdt.onSetup();
}
@Test
public void inserirTopicoESelecionarTodos() throws Exception {
TopicoDAO tDAO = new TopicoDAO();
List<Topico> topicos = tDAO.selectAll();
int qtdTopicosAnterior = topicos.size();
UsuarioDAO login = new UsuarioDAO();
Usuario u = login.selectID("pedro");
Topico t = new Topico();
t.setId(3);
t.setTitulo("outro topico do pedro");
t.setConteudo("topico do pedro");
t.setUsuario(u);
tDAO.insert(t);
topicos = tDAO.selectAll();
assertEquals(qtdTopicosAnterior + 1, topicos.size());
}
@Test
public void inserirTopicoXML() throws Exception {
UsuarioDAO login = new UsuarioDAO();
Usuario u = login.selectID("pedro");
Topico t = new Topico();
t.setTitulo("outro topico do pedro");
t.setConteudo("topico do pedro");
t.setUsuario(u);
TopicoDAO tDAO = new TopicoDAO();
tDAO.insert(t);
IDataSet currentDataset = jdt.getConnection().createDataSet();
ITable currentTable = currentDataset.getTable("topico");
FlatXmlDataFileLoader loader = new FlatXmlDataFileLoader();
IDataSet expectedDataset = loader.load("/topicoVerifica.xml");
ITable expectedTable = expectedDataset.getTable("topico");
Assertion.assertEquals(expectedTable, currentTable);
}
@Test
public void alterarTopicoESelectId() throws Exception {
TopicoDAO tDAO = new TopicoDAO();
Topico topico = tDAO.selectID(1);
topico.setConteudo(topico.getConteudo() + " alteracao");
tDAO.update(topico);
Topico topicoAlterado = tDAO.selectID(1);
assertEquals(topico.getConteudo(), topicoAlterado.getConteudo());
}
@Test
public void selecionarTopicosDoUsuario() throws Exception {
TopicoDAO tDAO = new TopicoDAO();
List<Topico> topicosUsuario = tDAO.selectTopicosUsuario("pedro");
topicosUsuario.forEach((t) -> {
assertEquals("pedro", t.getUsuario().getLogin());
});
assertEquals(3, topicosUsuario.size());
}
@After
public void destroy() throws Exception {
// jdt = new JdbcDatabaseTester("org.postgresql.Driver", "jdbc:postgresql://localhost/coursera", "postgres",
// "PTacf4994");
FlatXmlDataFileLoader loaderDelete = new FlatXmlDataFileLoader();
IDataSet dataSetDeleteComentario = loaderDelete.load("/comentario.xml");
jdt.setDataSet(dataSetDeleteComentario);
jdt.setSetUpOperation(DatabaseOperation.DELETE_ALL);
jdt.onSetup();
IDataSet dataSetDeleteTopico = loaderDelete.load("/topico.xml");
jdt.setDataSet(dataSetDeleteTopico);
jdt.setSetUpOperation(DatabaseOperation.DELETE_ALL);
jdt.onSetup();
IDataSet dataSetDeleteUsuario = loaderDelete.load("/usuario.xml");
jdt.setDataSet(dataSetDeleteUsuario);
jdt.setSetUpOperation(DatabaseOperation.DELETE_ALL);
jdt.onSetup();
}
}
| true |
a9f79281f0b1fc37c085bd14aca904539fb5be22
|
Java
|
Raul-A/LearningJava
|
/src/Main.java
|
UTF-8
| 1,548 | 3.6875 | 4 |
[] |
no_license
|
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Person person1 = new Person ("Raul","Aldrete");
System.out.println(person1.getFirstName()+" "+person1.getMiddleName()+" "+person1.getLastName());
System.out.println("Age: "+person1.getAge());
System.out.println("DOB: "+person1.getDateOfBirth());
Person person2 = new Person ("Dude","James","Wilson");
System.out.println(person2.getFirstName()+" "+person2.getMiddleName()+" "+person2.getLastName());
System.out.println("Age: "+person2.getAge());
System.out.println("DOB: "+person2.getDateOfBirth());
Animal animal1 = new Animal("dog", "Chino", 12, true);
Animal animal2 = new Animal("cat", "Garfield", 4, false);
List<Animal> animals = new ArrayList<>();
animals.add(animal1);
animals.add(animal2);
Person person3 = new Person ("Anekin","Luke","Skywalker",46,"09/12/1974",animals);
System.out.println(person3.getFirstName()+" "+person3.getMiddleName()+" "+person3.getLastName());
System.out.println("Age: "+person3.getAge());
System.out.println("DOB: "+person3.getDateOfBirth());
for(Animal animal: person3.getAnimals()){
System.out.println(animal.getType());
System.out.println(animal.getName());
System.out.println(animal.getAge());
System.out.println(animal.hasFourLegs());
System.out.println("\n\n");
}
}
}
| true |
b1cfbfc45183d1c08a6628ed7a9089c21ab2782b
|
Java
|
upupming/algorithm
|
/BasicLevel_Java/1011. A+B和C (15).java
|
UTF-8
| 490 | 3.375 | 3 |
[
"MIT"
] |
permissive
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
int i = 1;
while (i <= T) {
double a = in.nextDouble();
double b = in.nextDouble();
double c = in.nextDouble();
System.out.println("Case #" + i + ": " + ((a + b) - c < 0.000000000000001 ? "false" : "true"));
i++;
}
}
}
| true |
ffc6583ea74ef8ff334bf89e3c78c8c9bb3f3939
|
Java
|
ITYim/BeikoHealthAndroid
|
/app/src/main/java/com/alensic/beikohealth/mvppresenter/LoginPresenter.java
|
UTF-8
| 444 | 1.9375 | 2 |
[] |
no_license
|
package com.alensic.beikohealth.mvppresenter;
import android.content.Context;
import com.alensic.beikohealth.mvp.BasePresenter;
import com.alensic.beikohealth.mvp.BaseView;
import com.alensic.beikohealth.mvpview.LoginView;
/**
* @author zym
* @since 2017-08-08 14:13
*/
public class LoginPresenter extends BasePresenter<LoginView> {
public LoginPresenter(Context context, BaseView mvpView) {
super(context, mvpView);
}
}
| true |
4f788b293aeb6bba0dc54df558f3faeecf42a4e9
|
Java
|
kihwankim/web_term_project
|
/newCreativeProjectWithMVC/src/web/com/javalec/Ok/Fourth_FIfth_PageOk.java
|
UTF-8
| 3,586 | 2.703125 | 3 |
[] |
no_license
|
package web.com.javalec.Ok;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import app.AppControllerForWeb;
import list.LinkedList;
/**
* Servlet implementation class Fourth_FIfth_Page
*/
@WebServlet("/FFOk")
public class Fourth_FIfth_PageOk extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Fourth_FIfth_PageOk() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("doPost");
this.actionDo(request, response);
}
@SuppressWarnings("unchecked")
private void actionDo(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("EUC-KR");
HttpSession session = request.getSession();// 섹션 객체 생성
int numberOfSubjects = Integer.parseInt((String) session.getAttribute("numberOfSubs"));
LinkedList<String>[] listOfProfess = new LinkedList[numberOfSubjects];// 배열 생성
for (int frontIndex = 0; frontIndex < numberOfSubjects; frontIndex++) {// 교수님 명 저장하는 코드
listOfProfess[frontIndex] = new LinkedList<String>();// 객체 생성
for (int lastIndex = 0; lastIndex < 4; lastIndex++) {
String professName = request
.getParameter("profess" + Integer.toString(frontIndex) + Integer.toString(lastIndex));
if (professName.length() != 0) {
listOfProfess[frontIndex].add(professName);// 데이터 추가
}
}
}
String[] subjectsName = this.subjectsName((ArrayList<String>) session.getAttribute("List"), numberOfSubjects);
String emptyDay = request.getParameter("emptyDay");
AppControllerForWeb controller = new AppControllerForWeb(numberOfSubjects, subjectsName, listOfProfess,
emptyDay);// 객체 생성
if (emptyDay != null && controller.isThereNoProfessOrNot()) {// 예외 처리하고 이동한느 부분
System.out.println("success");
session.setAttribute("outputOfTheTimeTable", controller.scheduleList());
session.setAttribute("professNames", listOfProfess);// db에 저장 용로 일단 session에 저장
session.setAttribute("emptyDay", emptyDay);// 공강인 요일을 String 으로 저장해서 넘김 db저장 때문에 넘김
response.sendRedirect("fifthPage.jsp");
} else {
System.out.println("fail");
response.sendRedirect("fourthPage.jsp");
}
}
private String[] subjectsName(ArrayList<String> subjectsName, int numberOfSubjects) {
String[] subjectsNameInStr = new String[numberOfSubjects];
Iterator<String> iterator = subjectsName.iterator();
int index = 0;
while (iterator.hasNext()) {
subjectsNameInStr[index++] = iterator.next();
}
return subjectsNameInStr;
}
}
| true |
f3ca4461d9576742c6457c15e4372bd736407879
|
Java
|
whatisname/OrderAppService
|
/src/main/java/com/xxy/ordersystem/form/DelivererForm.java
|
UTF-8
| 908 | 1.726563 | 2 |
[] |
no_license
|
package com.xxy.ordersystem.form;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import java.sql.Timestamp;
/**
* @author X
* @package com.xxy.ordersystem.form
* @date 8/14/2018 6:58 PM
*/
@Data
public class DelivererForm {
private String dId;
@NotEmpty(message = "必须填写名字")
private String dName;
@NotEmpty(message = "必须填写手机号")
private String dPhone;
@NotEmpty(message = "必须填写系别班级")
private String dXibieBanji;
@NotEmpty(message = "必须填写身份证")
private String dIdcard;
@NotEmpty(message = "必须填写邮箱")
private String dEmail;
private Integer dQuyu;
// @NotEmpty(message = "必须填写名字")
// private String dPassword;
private String dComment;
// private Timestamp dCreateTime;
// private Timestamp dUpdateTime;
// private Integer dAccountState;
}
| true |
ed4f0bc03ae0c4c30d97f01fb760db00ff0947a9
|
Java
|
chopmann/ftswt
|
/hexagonfield/src/main/java/de/ostfalia/hexagonfield/HexagonFieldJsonKey.java
|
UTF-8
| 787 | 2.46875 | 2 |
[] |
no_license
|
package de.ostfalia.hexagonfield;
public enum HexagonFieldJsonKey {
VALUE("value"),
SESSION_ID("sessionId"),
INIT("init"),
EVENT("event"),
WIDTH("width"),
HEIGHT("height"),
SIZE("size"),
FIELDS("fields"),
FIELD_X("fieldX"),
FIELD_Y("fieldY"),
BACKGROUND_IMG("bgImg"),
CONTEXT_MENU("contextMenu");
private String key;
private HexagonFieldJsonKey(String key) {
this.key = key;
}
public String getKey() {
return key;
}
@Override
public String toString() {
return key;
}
public static HexagonFieldJsonKey fromString(String key) {
if (key != null) {
for (HexagonFieldJsonKey jsonKey : HexagonFieldJsonKey.values()) {
if (key.equals(jsonKey.getKey())) {
return jsonKey;
}
}
}
return null;
}
}
| true |
1ee2993bc5d894b87ae0ec6d9f3728f4feb999cf
|
Java
|
Ni2014/coding2017
|
/group05/183127807/HomeWork0226/src/com/coding/basic/LinkedList.java
|
UTF-8
| 2,399 | 3.5 | 4 |
[] |
no_license
|
package com.coding.basic;
public class LinkedList implements List {
private Node head;
private int size ;
private Node current = head;
public LinkedList() {
head = null;
size = 0;
}
public void add(Object o){
Node newNode = new Node();
newNode.data = o;
if (current.next == null)
{
current.next = newNode;
}
while (current.next != null){
current = current.next;
}
current.next = newNode;
size++;
}
public void add(int index , Object o){
Node newNode = new Node();
newNode.data = o;
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException();
}
for (int i = 0; i < index - 2; i++) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
size++;
}
public Object get(int index){
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException();
} else if (index == 0) {
return head;
}
for (int i = 0;i<index - 1; i++) {
current = current.next;
}
return current;
}
public Object remove(int index){
for (int i = 1; i <= index; i++) {
if (i == index - 1) {
current.next = current.next.next;
size--;
} else {
current = current.next;
}
}
return null;
}
public int size(){
return size;
}
public void addFirst(Object o){
Node newHead = new Node();
newHead.data = o;
newHead.next = head;
head = newHead;
size++;
}
public void addLast(Object o){
Node newNode = new Node();
newNode.data = o;
while (current.next != null){
current = current.next;
}
current.next = newNode;
size++;
}
public Object removeFirst(){
Node removeHead = head;
head.next = head.next.next;
size--;
return removeHead;
}
public Object removeLast(){
Node theNext = current.next;
Node oldLast;
while(theNext.next != null) {
current = theNext;
theNext = theNext.next;
}
oldLast=current.next;
current.next = theNext.next;
size--;
return oldLast;
}
public Iterator iterator(){
return new LinkedListIterator();
}
public Object head() {
return head;
}
private class LinkedListIterator implements Iterator {
@Override
public boolean hasNext() {
return current.next!=null;
}
@Override
public Object next() {
Node data = (Node) current.data;
current.next = current.next.next;
return data;
}
}
private static class Node{
Object data;
Node next;
}
}
| true |
6d937dfeac07c2aca0cf683665885957f024cf48
|
Java
|
sthendev/DungeonGame
|
/src/unsw/dungeon/CompositeGoal.java
|
UTF-8
| 641 | 2.875 | 3 |
[] |
no_license
|
package unsw.dungeon;
import java.util.List;
import java.util.ArrayList;
public abstract class CompositeGoal implements Goal {
private List<Goal> goals;
public CompositeGoal() {
goals = new ArrayList<>();
}
/**
*
* @return subgoals
*/
public List<Goal> getGoals() {
return goals;
}
/**
* remove specified goal
* @param g
*/
public void remove(Goal g) {
goals.remove(g);
}
/**
* add specified goal
* @param goal
*/
public void addGoal(Goal goal) {
goals.add(goal);
}
@Override
public void linkEntity(Entity entity) {
for (Goal goal : getGoals()) {
goal.linkEntity(entity);
}
}
}
| true |
c2ac3e001e3959efc52f7375368ee32676f76ea7
|
Java
|
jiandanguang1314/generator
|
/core/src/main/java/cc/yao01/rabbit/generator/config/dbloader/IntrospectedTable.java
|
UTF-8
| 2,214 | 2.09375 | 2 |
[] |
no_license
|
package cc.yao01.rabbit.generator.config.dbloader;
import cc.yao01.rabbit.generator.config.TableConfig;
import cc.yao01.rabbit.generator.datamodel.ProjectModel;
import cc.yao01.rabbit.generator.datamodel.TableModel;
import cc.yao01.rabbit.generator.utils.StringUtil;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* @author 姚华成
* @date 2017-10-19
*/
@Data
public class IntrospectedTable {
private String tableName;
private String remarks;
private String tableType;
private List<IntrospectedColumn> primaryKeyColumns = new ArrayList<>();
private List<IntrospectedColumn> baseColumns = new ArrayList<>();
private List<IntrospectedColumn> blobColumns = new ArrayList<>();
public TableModel genTableModel(TableConfig tableConfig, ProjectModel projectModel) {
TableModel tableModel = new TableModel(projectModel);
tableModel.setTableName(tableConfig.getTableName());
tableModel.setRemarks(this.getRemarks());
tableModel.setClassName(tableConfig.getDomainClassName());
tableModel.setVariableName(StringUtil.getVariableName(tableConfig.getDomainClassName()));
tableModel.setProjectRootPath(projectModel.getProjectRootPath());
tableModel.setPackagePath(tableConfig.getPackageName().replaceAll("\\.", "/"));
tableModel.setPackageName(tableConfig.getPackageName());
tableModel.setAuthor(projectModel.getAuthor());
tableModel.getGenerateFlags().putAll(tableConfig.getGenerateFlags());
for (IntrospectedColumn column : baseColumns) {
tableModel.addBaseColumn(column.genColumnModel(tableModel));
}
for (IntrospectedColumn column : primaryKeyColumns) {
tableModel.addPrimaryKeyColumn(column.genColumnModel(tableModel));
}
return tableModel;
}
public void addPrimaryKeyColumn(IntrospectedColumn primaryKeyColumn) {
this.primaryKeyColumns.add(primaryKeyColumn);
}
public void addBaseColumns(IntrospectedColumn baseColumn) {
this.baseColumns.add(baseColumn);
}
public void addBlobColumns(IntrospectedColumn blobColumn) {
this.blobColumns.add(blobColumn);
}
}
| true |
5cba61e1986b7c375135ee93ee77aed74c1e741f
|
Java
|
an-rninn7/bookmall
|
/bookmall/src/com/demo/common/model/Comments.java
|
UTF-8
| 398 | 1.867188 | 2 |
[] |
no_license
|
package com.demo.common.model;
import com.demo.common.model.base.BaseComments;
/**
* Generated by JFinal.
*/
@SuppressWarnings("serial")
public class Comments extends BaseComments<Comments> {
public static final Comments dao = new Comments().dao();
private Book book;
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
}
| true |
5074647121b3b1645b3a8f799cfad6e8f1a48fe6
|
Java
|
sion-naux/ContractManagementSystem
|
/src/Utils/Get_Para_Data.java
|
UTF-8
| 466 | 2.578125 | 3 |
[] |
no_license
|
package Utils;
import java.io.BufferedReader;
public class Get_Para_Data {
public StringBuffer getParaData(BufferedReader bufferedReader){
StringBuffer sb = new StringBuffer();
String line = null;
try{
BufferedReader br = bufferedReader;
while((line = br.readLine()) != null)
sb.append(line);
} catch (Exception e){
e.printStackTrace();
}
return sb;
}
}
| true |
4a0a9de267080d04477e3e174af1950cbc5bc798
|
Java
|
Superklaas/ParkShark-1
|
/domain/src/main/java/be/willekens/multi/module/template/domain/models/price/Currency.java
|
UTF-8
| 144 | 1.835938 | 2 |
[] |
no_license
|
package be.willekens.multi.module.template.domain.models.price;
public enum Currency {
EURO(),
DOLLAR(),
YEN,
STERLING_POUND
}
| true |
3bc3dd86a71aa57223e13362131bb36e976932c4
|
Java
|
Mysunshineps/designMode
|
/behaviorTypeMode/src/main/java/com/psq/design/model/Memo.java
|
UTF-8
| 285 | 2.484375 | 2 |
[] |
no_license
|
package com.psq.design.model;
/**
* @Description 备忘录模式
* @Author psq
* @Date 2021/2/4/15:55
*/
public class Memo {
private String state;
public Memo(String state) {
this.state = state;
}
public String getState() {
return state;
}
}
| true |
d62ab6cee0f249d37f67399fcef190c87e185fd3
|
Java
|
stasadd/Coursework
|
/src/main/java/models/YoutubeChannelInfoAnswer/Item.java
|
UTF-8
| 196 | 1.625 | 2 |
[] |
no_license
|
package models.YoutubeChannelInfoAnswer;
public class Item {
public String kind;
public String etag;
public String id;
public Statistics statistics;
public Snippet snippet;
}
| true |
477d876b9ead50f172f7175f678a3a26ecac135e
|
Java
|
iterge/springbootDemo
|
/src/test/java/com/example/demo/LambdaTest.java
|
UTF-8
| 4,723 | 2.84375 | 3 |
[] |
no_license
|
package com.example.demo;
import com.example.demo.controller.SocketServerTest;
import com.example.demo.controller.SocketTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @Description lambda表达式测试
* @Author lph
* @Date 2019/5/24 14:38
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class LambdaTest {
@Test
public void lambda1(){
String str = " dfasdf ";
System.out.println(str);
System.out.println(str.trim());
new Thread(() -> System.out.println(2)).start();
}
@Test
public void lambda2(){
Arrays.asList("d","g","r","b","j","a","z").forEach(e -> System.out.println(e));
}
/**
* java8 新特性 流库
*/
@Test
public void streamLib(){
try {
String con = new String(Files.readAllBytes(Paths.get("F:\\aa.txt")), StandardCharsets.UTF_8);
//\PL+ 正则表达式 以非字母分隔符;
List<String> words = Arrays.asList(con.split("\\PL+"));
//使用一般方法
/*long count = 0;
for (String word:words) {
if(word.length() > 10){
count++;
}
}*/
//使用流时
long count = words.stream().filter(w -> w.length() > 10).count();
Stream stream = words.stream().filter(w -> w.length() > 10);
Object[] arr = stream.toArray();
for (Object obj:arr) {
System.out.println(obj.toString());
}
System.out.println("长度大于10的单词的个数:"+count);
int[] array = {1,5,4,8,6,9};
List l = Arrays.asList(array);
l.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
//io流操作
@Test
public void inputstream(){
File file = new File("F:\\aa.txt");
byte[] bytes = new byte[10];
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(file);
os = new FileOutputStream("F:\\a.txt");
int len = 0;
while ((len = is.read(bytes)) != -1){
System.out.println(new String(bytes,0,len));
}
os.write("000000".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//使用ZipOutputStream时要记得关闭流,不然会导致文件丢失错误
@Test
public void zipIO(){
File file = new File("C:\\Users\\mayura\\Desktop\\a.zip");
File f = new File("F:\\aa.txt");
OutputStream os = null;
byte[] bytes = new byte[1024];
InputStream is = null;
ZipOutputStream zipOutputStream = null;
try {
is = new FileInputStream(f);
os = new FileOutputStream("C:\\Users\\mayura\\Desktop\\a.txt");
zipOutputStream = new ZipOutputStream(new FileOutputStream(file));
zipOutputStream.putNextEntry(new ZipEntry(f.getName()));
int len;
while ((len = is.read(bytes)) != -1) {
zipOutputStream.write(bytes,0,len);
os.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
is.close();
os.close();
zipOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void myThread(){
String con = "my thread";
boolean f = false;
}
@Test
public void socket() throws IOException {
String str = SocketTest.getStr();
System.out.println(str);
}
@Test
public void server() throws IOException {
String s = SocketServerTest.socketServer();
System.out.println();
}
}
| true |
a22910555e5ec3483321de7254b0b3048ee9ec99
|
Java
|
steve11235/ng-springboot-template
|
/java/springboot-template/springboot-template-api/src/main/java/com/fusionalliance/internal/springboottemplate/api/user/UserOutboundDto.java
|
UTF-8
| 2,410 | 2.25 | 2 |
[] |
no_license
|
/**
* Copyright 2018 by Steve Page of Fusion Alliance
*
* Created Apr 6, 2018
*/
package com.fusionalliance.internal.springboottemplate.api.user;
import org.apache.commons.lang3.StringUtils;
import com.fusionalliance.internal.sharedspringboot.api.BaseOutboundDto;
/**
* This class implements an outbound DTO for user.
*/
public class UserOutboundDto extends BaseOutboundDto<UserOutboundDto> {
private long userKey;
/** Has this user been deactivated? */
private boolean deactivated;
/** The unique value supplied on the login screen */
private String login;
// private String creds; intentionally omitted
/** Full fullName */
private String fullName;
private String description;
private boolean admin;
@Override
public void validate() {
super.validate();
validateUserKey();
validateLogin();
validateFullfullName();
validateDescription();
}
void validateUserKey() {
if (userKey <= 0) {
addValidationError("User ID is less than or equal to 0");
}
}
void validateLogin() {
if (StringUtils.isBlank(login)) {
addValidationError("Login is blank");
}
}
void validateFullfullName() {
if (StringUtils.isBlank(fullName)) {
addValidationError("FullfullName is blank");
}
}
void validateDescription() {
if (StringUtils.isBlank(description)) {
addValidationError("Description is blank");
}
}
public long getUserKey() {
return userKey;
}
public boolean isDeactivated() {
return deactivated;
}
public String getLogin() {
return login;
}
public String getFullfullName() {
return fullName;
}
public String getDescription() {
return description;
}
public boolean isAdmin() {
return admin;
}
public UserOutboundDto userKey(long userKeyParm) {
checkNotBuilt();
userKey = userKeyParm;
return this;
}
public UserOutboundDto deactivated(boolean deactivatedParm) {
checkNotBuilt();
deactivated = deactivatedParm;
return this;
}
public UserOutboundDto login(String loginParm) {
checkNotBuilt();
login = loginParm;
return this;
}
public UserOutboundDto fullName(String fullNameParm) {
checkNotBuilt();
fullName = fullNameParm;
return this;
}
public UserOutboundDto description(String descriptionParm) {
checkNotBuilt();
description = descriptionParm;
return this;
}
public UserOutboundDto admin(boolean adminParm) {
checkNotBuilt();
admin = adminParm;
return this;
}
}
| true |
6cde9590960422120d133bfdd97b6cd55753e1b9
|
Java
|
Link1996miky/demoN
|
/src/main/java/com/example/demon/timetask/ScheduledJobs.java
|
UTF-8
| 916 | 2.421875 | 2 |
[] |
no_license
|
package com.example.demon.timetask;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class ScheduledJobs {
//
// @Scheduled(fixedDelay = 5000)
// public void fixedDelayJob() throws InterruptedException{
// System.out.println("fixedDelay start:"+new Date());
// Thread.sleep(10*1000);
// System.out.println("fixedDelay end:"+new Date());
// }
//
//
// @Scheduled(fixedRate = 5000)
// public void fixedRateJob() throws InterruptedException{
// System.out.println("fixedRate start:"+new Date());
// Thread.sleep(5*1000);
// System.out.println("fixedRate end:"+new Date());
// }
//
// @Scheduled(cron = "0/10 * * * * ?")
// public void cronJob() {
// System.out.println("=========================== -> cron"+new Date());
// }
}
| true |
425e9483b21542c64ab1c024efa45f232c1798e5
|
Java
|
UbuntuEvangelist/sms-pull
|
/sms1103/sms/src/main/java/cn/tangjiabin/sms/service/UserService.java
|
UTF-8
| 596 | 1.875 | 2 |
[] |
no_license
|
package cn.tangjiabin.sms.service;
import cn.tangjiabin.sms.common.ServerResponse;
import cn.tangjiabin.sms.dto.UserDTO;
import cn.tangjiabin.sms.pojo.User;
import javax.servlet.http.HttpServletRequest;
public interface UserService {
ServerResponse addUser(User user, HttpServletRequest request);
ServerResponse findUserPage(UserDTO userDTO);
ServerResponse getUserById(Integer userId);
ServerResponse findUserNumber();
ServerResponse login(UserDTO userDTO, HttpServletRequest request);
ServerResponse registerUser(UserDTO userDTO, HttpServletRequest request);
}
| true |
4f8486a5fe403833306d2cb76f5da6d3332af501
|
Java
|
babamyrat/JSON_APP
|
/app/src/main/java/com/example/json_app/ExampleAdapter.java
|
UTF-8
| 2,866 | 2.234375 | 2 |
[] |
no_license
|
package com.example.json_app;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.json_app.ExampleItem;
import java.util.List;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.MyViewHolder> {
private Context mContext;
private List<ExampleItem> mExampleItem;
private RecyclerViewClickListener listener;
public ExampleAdapter(Context mContext, List<ExampleItem> mExampleItem, RecyclerViewClickListener listener) {
this.mContext = mContext;
this.mExampleItem = mExampleItem;
this.listener = listener;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v;
LayoutInflater inflater = LayoutInflater.from(mContext);
v = inflater.inflate(R.layout.movie_item, parent, false);
return new MyViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull ExampleAdapter.MyViewHolder holder, int position) {
holder.name.setText(mExampleItem.get(position).getName());
holder.species.setText(mExampleItem.get(position).getSpecies());
// holder.gender.setText(mExampleItem.get(position).getHogwartsStudent());
// using Glide
Glide.with(mContext)
.load(mExampleItem.get(position).getImg())
.into(holder.img);
// holder.wood.setText(mExampleItem.get(position).getWood());
// holder.length.setText(mExampleItem.get(position).getLength());
}
@Override
public int getItemCount() {
return mExampleItem.size();
}
public interface RecyclerViewClickListener{
void onClick(View v, int position);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView name;
TextView species;
// TextView gender;
ImageView img;
// TextView wood;
// TextView length;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name_txt);
species = itemView.findViewById(R.id.id_txt);
// gender = itemView.findViewById(R.id10.test_txt);
img = itemView.findViewById(R.id.imageView);
// wood = itemView.findViewById(R.id.wood_txt);
// length = itemView.findViewById(R.id.length_txt);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
listener.onClick(itemView, getAdapterPosition());
}
}
}
| true |
35e446f7f95b85840b5cf0dab3e0d04f354c4a09
|
Java
|
Mathilda11/Algorithms
|
/test09/Solution.java
|
UTF-8
| 1,493 | 4.0625 | 4 |
[] |
no_license
|
package test09;
/**
*
* 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
* 例如数组 {3, 4, 5, 1, 2} 为 {1, 2, 3, 4, 5} 的一个旋转,该数组的最小值为 1。
*
* 本题可以修改二分查找算法进行求解:
* 当 nums[m] <= nums[h] 的情况下,说明解在 [l, m] 之间,此时令 h = m;
* 否则解在 [m + 1, h] 之间,令 l = m + 1。
* @author 54060
*
*/
public class Solution {
public int minNumberInRotateArray(int[] nums) {
if (nums.length == 0)
return 0;
int l = 0, h = nums.length - 1;
while (l < h) {//当不满足该条件时,l指针已经指向第二个数组的开头
int m = l + (h - l) / 2;
//如果数组元素允许重复的话,那么就会出现一个特殊的情况:nums[l] == nums[m] == nums[h],那么此时无法确定解在哪个区间,需要切换到顺序查找。
if (nums[l] == nums[m] && nums[m] == nums[h])
return minNumber(nums, l, h);
else if (nums[m] <= nums[h])
h = m;
else
l = m + 1;
}
return nums[l];
}
//返回最小的元素
private int minNumber(int[] nums, int l, int h) {
for (int i = l; i < h; i++)
if (nums[i] > nums[i + 1])
return nums[i + 1];
return nums[l];
}
}
| true |
c77cbc248fd5b4d70b2c18639cc353ffd90af8ff
|
Java
|
CienProject2014/TreasureHunter
|
/src/view/StatusPanel.java
|
UHC
| 455 | 2.453125 | 2 |
[] |
no_license
|
package view;
import javax.swing.JButton;
import javax.swing.JPanel;
import model.dao.listener.StatusListener;
@SuppressWarnings("serial")
public class StatusPanel extends JPanel {
JButton Return;
public StatusPanel() {
Return = new JButton("ó ư");
add(Return);
setVisible(true);
StatusListener EL = new StatusListener();
Return.setActionCommand("return");
Return.addActionListener(EL);
}
}
| true |
998ba983468b6afd8a396901ed321c804eb7d344
|
Java
|
fabiozambelli/ExpenseManagement
|
/expensemanagement-model-jar/src/main/java/biz/fz5/expensemanagement/model/hibernate/dao/UserDeviceDAO.java
|
UTF-8
| 2,950 | 2.390625 | 2 |
[
"CC-BY-4.0"
] |
permissive
|
/**
* License CC BY | 2013 fabiozambelli.eu | Some Rights Reserved
*/
package biz.fz5.expensemanagement.model.hibernate.dao;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import biz.fz5.expensemanagement.model.hibernate.BaseHibernateDAO;
import biz.fz5.expensemanagement.model.hibernate.pojo.UserDevice;
/**
* @author fabiozambelli
*
*/
public class UserDeviceDAO extends BaseHibernateDAO {
private static final Log log = LogFactory.getLog(UserDeviceDAO.class);
public void save(UserDevice transientInstance) {
log.debug("saving UserDevice instance");
try {
getSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void attachDirty(UserDevice instance) {
log.debug("attaching dirty UserDevice instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void delete(UserDevice persistentInstance) {
log.debug("deleting UserDevice instance");
try {
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public UserDevice findItem(Long id) throws Exception {
UserDevice userDevice = null;
try {
Criteria crit = null;
crit = getSession().createCriteria(UserDevice.class);
crit.add(Restrictions.eq("id", id));
userDevice = (UserDevice) crit.uniqueResult();
} catch (Exception e) {
log.error("findItem failed", e);
throw new Exception(e);
}
return userDevice;
}
public List<UserDevice> findItems(Map parameters, String orderBy, boolean orderAsc)
throws Exception {
List<UserDevice> userDevices = null;
try {
Criteria crit = null;
crit = getSession().createCriteria(UserDevice.class);
if (!parameters.isEmpty()) {
if (parameters.containsKey("status")) {
crit.add(Restrictions.eq("status.id",
(Integer) parameters.get("status")));
}
if (parameters.containsKey("idUser")) {
crit.add(Restrictions.eq("idUser",
(String) parameters.get("idUser")));
}
if (parameters.containsKey("idRegistration")) {
crit.add(Restrictions.eq("idRegistration",
(String) parameters.get("idRegistration")));
}
}
// ordinamento
if ((orderBy != null) && (orderAsc))
crit.addOrder(Order.asc(orderBy));
if ((orderBy != null) && (!orderAsc))
crit.addOrder(Order.desc(orderBy));
userDevices = crit.list();
log.debug("userDevices:" + userDevices);
} catch (Exception e) {
log.error("findItems failed", e);
throw new Exception(e);
}
return userDevices;
}
}
| true |
f97fe5fb23ebd7ecbc59e8e01d7b54314b273de4
|
Java
|
tianxiawudidong/spark
|
/bi/src/main/java/com/ifchange/spark/bi/bean/cv/BaseCertificate.java
|
UTF-8
| 1,775 | 2 | 2 |
[] |
no_license
|
package com.ifchange.spark.bi.bean.cv;
import java.io.Serializable;
public class BaseCertificate implements Serializable {
private long resume_id;
private String name;
private String start_time;
private String description;
private String id;
private String is_deleted;
private int sort_id;
private String created_at;
private String updated_at;
public long getResume_id() {
return resume_id;
}
public void setResume_id(long resume_id) {
this.resume_id = resume_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStart_time() {
return start_time;
}
public void setStart_time(String start_time) {
this.start_time = start_time;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIs_deleted() {
return is_deleted;
}
public void setIs_deleted(String is_deleted) {
this.is_deleted = is_deleted;
}
public int getSort_id() {
return sort_id;
}
public void setSort_id(int sort_id) {
this.sort_id = sort_id;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
| true |
ef07e5a8e4030121b06baa2d12f3ee418604f517
|
Java
|
jinmu1/mynetwork
|
/ruoyi-system/src/main/java/com/ruoyi/system/mapper/EduFacilityMapper.java
|
UTF-8
| 1,367 | 1.921875 | 2 |
[
"MIT"
] |
permissive
|
package com.ruoyi.system.mapper;
import java.util.List;
import com.ruoyi.system.domain.EduFacility;
/**
* 设施数据Mapper接口
*
* @author ruoyi
* @date 2021-01-10
*/
public interface EduFacilityMapper
{
/**
* 查询设施数据
*
* @param id 设施数据ID
* @return 设施数据
*/
public EduFacility selectEduFacilityById(Long id);
/**
* 查询设施数据列表
*
* @param eduFacility 设施数据
* @return 设施数据集合
*/
public List<EduFacility> selectEduFacilityList(EduFacility eduFacility);
/**
* 新增设施数据
*
* @param eduFacility 设施数据
* @return 结果
*/
public int insertEduFacility(EduFacility eduFacility);
/**
* 修改设施数据
*
* @param eduFacility 设施数据
* @return 结果
*/
public int updateEduFacility(EduFacility eduFacility);
/**
* 删除设施数据
*
* @param id 设施数据ID
* @return 结果
*/
public int deleteEduFacilityById(Long id);
/**
* 批量删除设施数据
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteEduFacilityByIds(String[] ids);
int deleteEduFacilitiesByUserId(Long userId);
void insertEduFacilityList(List<EduFacility> list);
}
| true |
cd29fd5407c403605f590b8a30f4712270d1395d
|
Java
|
YujunWu-King/university
|
/src/main/java/com/tranzvision/gd/TZRecommendationBundle/service/impl/TzToTjxClsServiceImpl.java
|
UTF-8
| 6,893 | 1.75 | 2 |
[] |
no_license
|
package com.tranzvision.gd.TZRecommendationBundle.service.impl;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tranzvision.gd.TZAuthBundle.service.impl.TzLoginServiceImpl;
import com.tranzvision.gd.TZBaseBundle.service.impl.FrameworkImpl;
import com.tranzvision.gd.TZWebsiteApplicationBundle.dao.PsTzAppInsTMapper;
import com.tranzvision.gd.TZWebsiteApplicationBundle.model.PsTzAppInsT;
import com.tranzvision.gd.util.base.JacksonUtil;
import com.tranzvision.gd.util.base.MessageTextServiceImpl;
import com.tranzvision.gd.util.sql.GetSeqNum;
import com.tranzvision.gd.util.sql.SqlQuery;
import com.tranzvision.gd.util.sql.TZGDObject;
/**
* PS:TZ_GD_TJX_PKG:TZ_TO_TJX_CLS
*
* @author tang
*
*/
@Service("com.tranzvision.gd.TZRecommendationBundle.service.impl.TzToTjxClsServiceImpl")
public class TzToTjxClsServiceImpl extends FrameworkImpl {
@Autowired
private SqlQuery jdbcTemplate;
@Autowired
private TzLoginServiceImpl tzLoginServiceImpl;
@Autowired
private HttpServletRequest request;
@Autowired
private MessageTextServiceImpl messageTextServiceImpl;
@Autowired
private TZGDObject tzGdObject;
@Autowired
private GetSeqNum getSeqNum;
@Autowired
private PsTzAppInsTMapper psTzAppInsTMapper;
/*
* 功能描述: 点击邮件链接 跳转到推荐信报名表 参数说明: + &strTjxId 推荐信报名表ID + &strOprid 发送人ID +
* &strModal 推荐信报名表模板编号
*/
public String toReference(String strTjxId, String strOprid) {
String strRtn = "";
long numAppinsId = 0;
String strTjxYx = "";
String strTjxType = "";
long numTjxAppinsId = 0;
String contextPath = request.getContextPath();
try {
if (strTjxId != null && !"".equals(strTjxId) && strOprid != null && !"".equals(strOprid)) {
Map<String, Object> map = jdbcTemplate.queryForMap(
"select TZ_APP_INS_ID,TZ_MBA_TJX_YX,TZ_TJX_TYPE,TZ_TJX_APP_INS_ID from PS_TZ_KS_TJX_TBL where TZ_REF_LETTER_ID=? and OPRID=? limit 0,1",
new Object[] { strTjxId, strOprid });
if (map != null) {
try{
numAppinsId = Long.parseLong( map.get("TZ_APP_INS_ID").toString());
}catch(Exception e){
numAppinsId = 0L;
}
strTjxYx = (String) map.get("TZ_MBA_TJX_YX");
strTjxType = (String) map.get("TZ_TJX_TYPE");
try{
numTjxAppinsId = Long.parseLong(map.get("TZ_TJX_APP_INS_ID").toString());
}catch(Exception e){
numTjxAppinsId = 0L;
}
}
String str_tjx_mb_id = "", str_bmb_mb_id = "";
str_bmb_mb_id = jdbcTemplate.queryForObject(
"SELECT TZ_APP_TPL_ID FROM PS_TZ_APP_INS_T WHERE TZ_APP_INS_ID=? limit 0,1",
new Object[] { numAppinsId }, "String");
String str_tjx_sx = "";
// 推荐信有效-------------------------------;
if (!"Y".equals(strTjxYx)) {
// 推荐信无效;
if ("E".equals(strTjxType)) {
// 英文;
str_tjx_mb_id = jdbcTemplate.queryForObject(
"SELECT TZ_ENG_MODAL_ID FROM PS_TZ_APPTPL_DY_T WHERE TZ_APP_TPL_ID=? limit 0,1",
new Object[] { str_bmb_mb_id }, "String");
str_tjx_sx = messageTextServiceImpl.getMessageTextWithLanguageCd("TZGD_APPONLINE_MSGSET",
"REF_FAIL", "ENG", "", "");
strRtn = tzGdObject.getHTMLText("HTML.TZRecommendationBundle.TZ_GD_TJX_ERROR_HTML", str_tjx_sx,contextPath);
return strRtn;
} else {
// 中文;
str_tjx_mb_id = jdbcTemplate.queryForObject(
"SELECT TZ_CHN_MODAL_ID FROM PS_TZ_APPTPL_DY_T WHERE TZ_APP_TPL_ID=? limit 0,1",
new Object[] { str_bmb_mb_id }, "String");
str_tjx_sx = messageTextServiceImpl.getMessageTextWithLanguageCd("TZGD_APPONLINE_MSGSET",
"REF_FAIL", "ZHS", "", "");
strRtn = tzGdObject.getHTMLText("HTML.TZRecommendationBundle.TZ_GD_TJX_ERROR_HTML", str_tjx_sx,contextPath);
return strRtn;
}
} else {
if ("E".equals(strTjxType)) {
// 英文;
str_tjx_mb_id = jdbcTemplate.queryForObject(
"SELECT TZ_ENG_MODAL_ID FROM PS_TZ_APPTPL_DY_T WHERE TZ_APP_TPL_ID=? limit 0,1",
new Object[] { str_bmb_mb_id }, "String");
} else {
// 中文;
str_tjx_mb_id = jdbcTemplate.queryForObject(
"SELECT TZ_CHN_MODAL_ID FROM PS_TZ_APPTPL_DY_T WHERE TZ_APP_TPL_ID=? limit 0,1",
new Object[] { str_bmb_mb_id }, "String");
}
}
// 报名表ID不存在,错误---------------------;
if (numAppinsId < 0) {
strRtn = tzGdObject.getHTMLText("HTML.TZRecommendationBundle.TZ_GD_TJX_ERROR_HTML","非法操作",contextPath);
return strRtn;
}
String oprid = tzLoginServiceImpl.getLoginedManagerOprid(request);
// 如果推荐信报名表ID不存在,生成-----------;
if (numTjxAppinsId <= 0) {
numTjxAppinsId = getSeqNum.getSeqNum("TZ_APP_INS_T", "TZ_APP_INS_ID");
PsTzAppInsT psTzAppInsT = new PsTzAppInsT();
psTzAppInsT.setTzAppInsId(numTjxAppinsId);
psTzAppInsT.setTzAppTplId(str_tjx_mb_id);
psTzAppInsT.setRowAddedDttm(new Date());
psTzAppInsT.setRowAddedOprid(oprid);
psTzAppInsT.setRowLastmantDttm(new Date());
psTzAppInsT.setRowLastmantOprid(oprid);
psTzAppInsTMapper.insert(psTzAppInsT);
jdbcTemplate.update("update PS_TZ_KS_TJX_TBL set TZ_TJX_APP_INS_ID=? where TZ_REF_LETTER_ID=?",
new Object[] { numTjxAppinsId, strTjxId });
}
//跳转到推荐信报名表的链接;
//String strTzUrl = jdbcTemplate.queryForObject("SELECT TZ_HARDCODE_VAL FROM PS_TZ_HARDCD_PNT WHERE TZ_HARDCODE_PNT = ?", new Object[]{"TZ_TJX_URL"},"String");
String strTzUrl = request.getContextPath() + "/dispatcher?classid=appId&TZ_APP_INS_ID=" + numTjxAppinsId + "&TZ_REF_LETTER_ID=" + strTjxId;
strRtn = tzGdObject.getHTMLText("HTML.TZRecommendationBundle.TZ_GD_TJX_TRANS_HTML",strTzUrl);
}else{
strRtn = tzGdObject.getHTMLText("HTML.TZRecommendationBundle.TZ_GD_TJX_ERROR_HTML","参数不完整",contextPath);
}
} catch (Exception e) {
e.printStackTrace();
strRtn = "参数错误";
}
return strRtn;
}
@Override
public String tzGetHtmlContent(String strParams) {
String strRtn = "";
JacksonUtil jacksonUtil = new JacksonUtil();
try {
jacksonUtil.parseJson2Map(strParams);
String strTjxId = "";
String strOprid = "";
/* 报名表应用编号 */
String str_appId = request.getParameter("classid");
if (str_appId != null && !"".equals(str_appId)) {
strTjxId = request.getParameter("TZ_REF_LETTER_ID");
strOprid = request.getParameter("OPRID");
} else {
strTjxId = jacksonUtil.getString("TZ_REF_LETTER_ID");
strOprid = jacksonUtil.getString("OPRID");
}
strRtn = this.toReference(strTjxId, strOprid);
} catch (Exception e) {
e.printStackTrace();
}
return strRtn;
}
}
| true |
1323d2c2a35ea36110c1146d39142cccba1d9e4e
|
Java
|
matan3/OOP_PROJECT
|
/src/main/java/Filter/FilterInterFace.java
|
UTF-8
| 457 | 2.28125 | 2 |
[] |
no_license
|
package main.java.Filter;
import java.util.List;
import main.java.Objects.Row;
public interface FilterInterFace {
public List<Row> CalculateByLocation1(List<Row> listInput, List<Row> listOutput, double Lon ,double Lat,double Radius) ;
public List<Row> CalculateByID1(List<Row> listInput,List<Row> listOutput,String id);
public List<Row> CalculateByTime1(List<Row> listInput, List<Row> listOutput,String startDate,String endDate);
}
| true |
8830601c8d05b5c3fb969652e4181f6ac07d65d1
|
Java
|
ScarSmith/Beep-boop
|
/GameT/src/gamet/Start.java
|
UTF-8
| 1,625 | 2.796875 | 3 |
[] |
no_license
|
package gamet;
import java.applet.AudioClip;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class Start implements ActionListener
{
private JFrame frame = new JFrame("Survival");
private Timer paintTimer = new Timer(33, this);
private Timer pimplandTimer = new Timer(30, this);
private World world = new World();
private Draw paint = new Draw(world);
public Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
Random random = new Random();
public static void main(String[] args)
{
Start start = new Start();
}
public Start()
{
frame.setBounds(0, 0, dim.width, dim.height);
frame.addKeyListener(paint);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.add(paint);
frame.setResizable(false);
paintTimer.start();
playSound();
pimplandTimer.start();
frame.setVisible(true);
}
public void playSound() {
int songSelection = random.nextInt(3);
AudioClip W2 = JApplet
.newAudioClip(getClass().getResource("Wandering2.wav"));
AudioClip W = JApplet
.newAudioClip(getClass().getResource("Wandering.wav"));
AudioClip Op = JApplet
.newAudioClip(getClass().getResource("Opening.wav"));
if (songSelection == 1) {
W2.loop();
}else if (songSelection == 2) {
W.loop();
}else {
Op.loop();
}
}
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource().equals(paintTimer))
{
paint.repaint();
}
if (e.getSource().equals(pimplandTimer))
{
world.move();
}
}
}
//}
| true |
17c5278e8bd4d47d1a33728789f48d42cba7c8bc
|
Java
|
AshkanM96/EECS-3481-Applied-Cryptography
|
/src/symmetric/B1Q4.java
|
UTF-8
| 2,076 | 3.421875 | 3 |
[
"MIT"
] |
permissive
|
package symmetric;
import util.Binary;
import util.CryptoTools;
import util.Hex;
/**
* OTP 3-pass decryption use case.
*
* @author Ashkan Moatamed
*/
public class B1Q4 {
/**
* Dependencies: <code>
* 1. util.Binary
* 2. util.Hex
* 3. util.CryptoTools
* </code>
*/
/**
* The first transmission.
*/
private static final byte[] TRANSMISSION_1 = Hex.toBytes("0A4F0C08003503492F247442105B5757");
/**
* The second transmission.
*/
private static final byte[] TRANSMISSION_2 = Hex.toBytes("5E2769286B507A69494B066252343579");
/**
* The third transmission.
*/
private static final byte[] TRANSMISSION_3 = Hex.toBytes("170708454B1116002A2E2111725F5000");
/**
* Prevent instantiation.
*/
private B1Q4() {
// Empty by design.
}
@Override
protected Object clone() throws CloneNotSupportedException { // semi-copy
throw new CloneNotSupportedException();
}
public static void main(String[] args) {
/**
* We know the following: <br>
* 1. <code>B1Q4.TRANSMISSION_1</code> is <code>plaintext xor key_alice</code> <br>
* 2. <code>B1Q4.TRANSMISSION_2</code> is <code>B1Q4.TRANSMISSION_1 xor key_bob</code> <br>
* 3. <code>B1Q4.TRANSMISSION_3</code> is <code>B1Q4.TRANSMISSION_2 xor key_alice</code> <br>
*
* Therefore, we can conclude the following: <br>
* 1. <code>B1Q4.TRANSMISSION_1</code> is <code>plaintext xor key_alice</code> <br>
* 2. <code>B1Q4.TRANSMISSION_2</code> is <code>plaintext xor key_alice xor key_bob</code> <br>
* 3. <code>B1Q4.TRANSMISSION_3</code> is <code>plaintext xor key_bob</code> <br>
*
* Thus, Eve can just xor the first and second transmission to find <code>key_bob</code> and then
* xor that with the third transmission to find the <code>plaintext</code>.
*/
final byte[] key_bob = Binary.xor(B1Q4.TRANSMISSION_1, B1Q4.TRANSMISSION_2);
final byte[] plaintext = Binary.xor(B1Q4.TRANSMISSION_3, key_bob);
System.out.println("The plaintext is:\n" + CryptoTools.toString(plaintext) + "\n");
}
}
| true |
37e73cff0d56c8c8c9966354276d007e3f4ba895
|
Java
|
piropiro/dragon
|
/dragon2/src/main/java/EndPaint.java
|
UTF-8
| 1,388 | 2.015625 | 2 |
[] |
no_license
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: EndPaint.java
import java.awt.Point;
import mine.UnitMap;
class EndPaint extends ActionBase {
EndPaint(Body body) {
ba = body;
PaintBase.V.clear(1, 0, 0);
PaintBase.V.S(1, 0, body.x, body.y, 3);
PaintBase.V.S(3, 0, body.x, body.y, 1);
setHelp();
}
private void setHelp() {
if (!Colors.isPlayer(ba)) {
return;
} else {
PaintBase.uw.setHelp(Texts.help[11], 1);
return;
}
}
public void actionMain() {
Point point = PaintBase.map.getWaku();
if (point.x == ba.x && point.y == ba.y)
PaintBase.uw.setEnd(ba, false);
else
PaintBase.uw.setEnd(ba, true);
}
public void leftPressed() {
SlgClient.setActionEnd();
PaintBase.V.S(1, 0, ba.x, ba.y, 0);
action();
}
public void rightPressed() {
Rewalk.rewalk(ba);
}
public boolean isNextPoint(Point point) {
Body body = PaintBase.uw.search(point.x, point.y);
if (body == null)
return false;
if (body.isType(21))
return false;
if (PaintBase.V.G(3, 0, point.x, point.y) != 0)
return false;
if (Colors.isPlayer(body)) {
if (body.isType(27))
return false;
} else if (!body.isType(27))
return false;
return true;
}
private Body ba;
}
| true |
22108e5a4d7439144315220b3ffc472ba586c586
|
Java
|
aliyun/aliyun-openapi-java-sdk
|
/aliyun-java-sdk-actiontrail/src/main/java/com/aliyuncs/actiontrail/transform/v20200706/GetAccessKeyLastUsedIpsResponseUnmarshaller.java
|
UTF-8
| 2,029 | 1.796875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* 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.aliyuncs.actiontrail.transform.v20200706;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.actiontrail.model.v20200706.GetAccessKeyLastUsedIpsResponse;
import com.aliyuncs.actiontrail.model.v20200706.GetAccessKeyLastUsedIpsResponse.IpsItem;
import com.aliyuncs.transform.UnmarshallerContext;
public class GetAccessKeyLastUsedIpsResponseUnmarshaller {
public static GetAccessKeyLastUsedIpsResponse unmarshall(GetAccessKeyLastUsedIpsResponse getAccessKeyLastUsedIpsResponse, UnmarshallerContext _ctx) {
getAccessKeyLastUsedIpsResponse.setRequestId(_ctx.stringValue("GetAccessKeyLastUsedIpsResponse.RequestId"));
getAccessKeyLastUsedIpsResponse.setNextToken(_ctx.stringValue("GetAccessKeyLastUsedIpsResponse.NextToken"));
List<IpsItem> ips = new ArrayList<IpsItem>();
for (int i = 0; i < _ctx.lengthValue("GetAccessKeyLastUsedIpsResponse.Ips.Length"); i++) {
IpsItem ipsItem = new IpsItem();
ipsItem.setUsedTimestamp(_ctx.longValue("GetAccessKeyLastUsedIpsResponse.Ips["+ i +"].UsedTimestamp"));
ipsItem.setDetail(_ctx.stringValue("GetAccessKeyLastUsedIpsResponse.Ips["+ i +"].Detail"));
ipsItem.setSource(_ctx.stringValue("GetAccessKeyLastUsedIpsResponse.Ips["+ i +"].Source"));
ipsItem.setIp(_ctx.stringValue("GetAccessKeyLastUsedIpsResponse.Ips["+ i +"].Ip"));
ips.add(ipsItem);
}
getAccessKeyLastUsedIpsResponse.setIps(ips);
return getAccessKeyLastUsedIpsResponse;
}
}
| true |
d97ce6390267d35180bdf31452d7cbb3a62c2451
|
Java
|
rolandotr/db_comparison
|
/src/utils/EntropyCalculator.java
|
UTF-8
| 4,887 | 2.96875 | 3 |
[] |
no_license
|
package utils;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.linear.OpenMapRealMatrix;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
public class EntropyCalculator {
public static double entropy(DefaultDirectedGraph<String, DefaultEdge> graph, int walkLength, String initialVertex, boolean allLengths, boolean squareProbabilities) {
ArrayList<String> vertList = new ArrayList<String>(graph.vertexSet());
// Create initial probability vector
OpenMapRealMatrix initProb = new OpenMapRealMatrix(1, graph.vertexSet().size());
// Initialize initial probability vector
for (int i = 0; i < vertList.size(); i++)
if (vertList.get(i).equals(initialVertex))
initProb.setEntry(0, i, 1d);
else
initProb.setEntry(0, i, 0d);
// Create transition probability matrix
OpenMapRealMatrix transProbMatrix = new OpenMapRealMatrix(graph.vertexSet().size(), graph.vertexSet().size());
// Initialize transition probability matrix
for (int i = 0; i < vertList.size(); i++)
for (int j = 0; j < vertList.size(); j++)
if (graph.containsEdge(vertList.get(i), vertList.get(j)))
transProbMatrix.setEntry(i, j, 1d / (double)graph.outDegreeOf(vertList.get(i)));
else
transProbMatrix.setEntry(i, j, 0d);
// Iterate updating powers of transition probability matrix
ArrayList<OpenMapRealMatrix> allLengthProbMatrices = new ArrayList<>();
OpenMapRealMatrix matrixMultiplier = transProbMatrix;
if (allLengths)
allLengthProbMatrices.add(new OpenMapRealMatrix(initProb.multiply(transProbMatrix)));
for (int len = 2; len <= walkLength; len++) {
matrixMultiplier = (OpenMapRealMatrix)matrixMultiplier.multiply(transProbMatrix);
if (allLengths)
allLengthProbMatrices.add(initProb.multiply(matrixMultiplier));
}
/* Compute entropy of the distribution (\pi(v_0),\pi(v_1),...,\pi(v_{2n-1})),
* where \pi(v_i) is the probability that a walkLength-length walk starting at vertex v_0
* ends at vertex v_i
*/
double entropySum = 0d;
OpenMapRealMatrix finalProb = initProb.multiply(matrixMultiplier);
for (int i = 0; i < vertList.size(); i++) {
double prob = 0d;
if (allLengths) {
for (int l = 0; l < walkLength; l++)
prob += allLengthProbMatrices.get(l).getEntry(0, i) * (Math.pow(2d, (double)(l + 1)) / (Math.pow(2d, walkLength) - 1d));
}
else
prob = finalProb.getEntry(0, i);
if (squareProbabilities)
prob *= prob;
if (prob > 0d)
entropySum += -(prob * Math.log(prob));
}
return entropySum;
}
public static List<Double> entropyVector(DefaultDirectedGraph<String, DefaultEdge> graph, int walkLength, String initialVertex) {
ArrayList<String> vertList = new ArrayList<String>(graph.vertexSet());
// Create initial probability vector
OpenMapRealMatrix initProb = new OpenMapRealMatrix(1, graph.vertexSet().size());
// Initialize initial probability vector
for (int i = 0; i < vertList.size(); i++)
if (vertList.get(i).equals(initialVertex))
initProb.setEntry(0, i, 1d);
else
initProb.setEntry(0, i, 0d);
// Create transition probability matrix
OpenMapRealMatrix transProbMatrix = new OpenMapRealMatrix(graph.vertexSet().size(), graph.vertexSet().size());
// Initialize transition probability matrix
for (int i = 0; i < vertList.size(); i++)
for (int j = 0; j < vertList.size(); j++)
if (graph.containsEdge(vertList.get(i), vertList.get(j)))
transProbMatrix.setEntry(i, j, 1d / (double)graph.outDegreeOf(vertList.get(i)));
else
transProbMatrix.setEntry(i, j, 0d);
// Iterate updating powers of transition probability matrix
ArrayList<OpenMapRealMatrix> allLengthProbMatrices = new ArrayList<>();
OpenMapRealMatrix matrixMultiplier = transProbMatrix;
allLengthProbMatrices.add(new OpenMapRealMatrix(initProb.multiply(transProbMatrix)));
for (int len = 2; len <= walkLength; len++) {
matrixMultiplier = (OpenMapRealMatrix)matrixMultiplier.multiply(transProbMatrix);
allLengthProbMatrices.add(initProb.multiply(matrixMultiplier));
}
/* Compute entropy of the distribution (\pi(v_0),\pi(v_1),...,\pi(v_{2n-1})),
* where \pi(v_i) is the probability that a walkLength-length walk starting at vertex v_0
* ends at vertex v_i
*/
List<Double> vector = new ArrayList<>();
for (int l = 0; l < walkLength; l++) {
double entropySum = 0d;
for (int i = 0; i < vertList.size(); i++) {
double prob = allLengthProbMatrices.get(l).getEntry(0, i) * (Math.pow(2d, (double)(l + 1)) / (Math.pow(2d, walkLength) - 1d));
if (prob > 0d)
entropySum += -(prob * Math.log(prob));
}
vector.add(entropySum);
}
return vector;
}
}
| true |
6b4ccd25381c0ea7bdbc835bc29c9a843e3ed04e
|
Java
|
mc-cat-tty/PersonalFinance
|
/ui/components/containers/UpperPanel.java
|
UTF-8
| 4,237 | 2.6875 | 3 |
[] |
no_license
|
package ui.components.containers;
import ui.components.text.TunableText;
import tunable.*;
import ui.core.*;
import java.util.Date;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import model.core.Transaction;
import model.events.EventsBroker;
/**
* Upper panel showing balance and current filter.
*/
public class UpperPanel extends RoundedPanel implements IComponent {
private final static int RADIUS = 80;
private final TunableText plusMinus;
private final TunableText amount;
private final TunableText startDate;
private final TunableText endDate;
private float balance;
public UpperPanel() {
super(
new Point(
0,
-RADIUS
),
new Dimension(
CommonDimensions.UPPER_PANEL.getWidth(),
CommonDimensions.UPPER_PANEL.getHeight() + RADIUS
),
new Point(
0,
-RADIUS
),
RADIUS,
CommonColors.CARD.getColor()
);
plusMinus = new TunableText("+")
.withColor(CommonColors.PLUS.getColor())
.withOpacity(1f)
.withFont(CommonFonts.TEXT_MEDIUM_WEIGHT.getFont().deriveFont(96f));
amount = new TunableText("000.00 ")
.withColor(CommonColors.TEXT.getColor())
.withOpacity(1f)
.withFont(CommonFonts.TEXT_NORMAL.getFont().deriveFont(96f));
startDate = new TunableText("01/01/'22")
.withColor(CommonColors.TEXT.getColor())
.withOpacity(1f)
.withFont(CommonFonts.TEXT_MEDIUM_WEIGHT.getFont().deriveFont(36f));
endDate = new TunableText("02/02/'23")
.withColor(CommonColors.TEXT.getColor())
.withOpacity(1f)
.withFont(CommonFonts.TEXT_MEDIUM_WEIGHT.getFont().deriveFont(36f));
composeView();
registerCallbacks();
}
public void setAmount(float amount) {
if (amount < 0f) {
plusMinus
.withColor(CommonColors.MINUS.getColor())
.setText("-");
amount *= -1; // remove sign
}
else {
plusMinus
.withColor(CommonColors.PLUS.getColor())
.setText("+");
}
this.amount.setText(
String.format("%06.02f ", amount)
);
}
public void setStartDate(Date startDate) {
this.startDate.setText(
CommonDateFormats.EU_DATE_FORMAT_SHORT.getFormatter().format(startDate)
);
}
public void setEndDate(Date endDate) {
this.endDate.setText(
CommonDateFormats.EU_DATE_FORMAT_SHORT.getFormatter().format(endDate)
);
}
@Override public void composeView() {
setBorder(
new EmptyBorder(
0,
0,
CommonPaddings.UPPER_PANEL_BOTTOM_PADDING.getPadding(),
0
)
);
final var internalPanel = new JPanel();
internalPanel.setBackground(CommonColors.CARD.getColor());
internalPanel.setBorder(
new EmptyBorder(
30,
5,
5,
5
)
);
add(internalPanel);
internalPanel.add(plusMinus);
internalPanel.add(amount);
internalPanel.add(
new TunableText("Your balance from ")
.withColor(CommonColors.TEXT.getColor())
.withOpacity(1f)
.withFont(CommonFonts.TEXT_NORMAL.getFont().deriveFont(36f))
);
internalPanel.add(startDate);
internalPanel.add(
new TunableText(" to ")
.withColor(CommonColors.TEXT.getColor())
.withOpacity(1f)
.withFont(CommonFonts.TEXT_NORMAL.getFont().deriveFont(36f))
);
internalPanel.add(endDate);
}
@Override public void registerCallbacks() {
EventsBroker
.getInstance()
.getFilterEvent()
.attachObserver(
transactions -> {
balance = 0;
for (final Transaction t : transactions) {
balance += t.getAmount();
}
setAmount(balance);
}
);
EventsBroker
.getInstance()
.getFilterDateEvent()
.attachObserver(
(startDate, endDate) -> {setStartDate(startDate); setEndDate(endDate);}
);
EventsBroker
.getInstance()
.getDeleteEvent()
.attachObserver(
transactions -> {
for (final var t : transactions) {
balance -= t.getAmount();
}
setAmount(balance);
}
);
}
}
| true |
7254de506c9cca7746ab5558a48e27299f32085a
|
Java
|
fjh658/bindiff
|
/src_procyon/y/g/S_1.java
|
UTF-8
| 5,613 | 2.75 | 3 |
[] |
no_license
|
package y.g;
import y.c.*;
final class S implements A
{
double[] a;
int[] b;
boolean[] c;
Object[] d;
S(final double[] a, final int[] b, final boolean[] c, final Object[] d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public Object b(final Object o) {
try {
return this.d[((q)o).d()];
}
catch (ClassCastException ex) {
throw new IllegalArgumentException("Argument must be of type Node.");
}
catch (NullPointerException ex2) {
if (o == null) {
throw new IllegalArgumentException("Argument must be non-null.");
}
if (o instanceof q && ((q)o).e() == null) {
throw new IllegalArgumentException("Argument is not in graph");
}
throw new UnsupportedOperationException("Cannot get Object from this type of Map!");
}
}
public double c(final Object o) {
try {
return this.a[((q)o).d()];
}
catch (ClassCastException ex) {
throw new IllegalArgumentException("Argument must be of type Node.");
}
catch (NullPointerException ex2) {
if (o == null) {
throw new IllegalArgumentException("Argument must be non-null.");
}
if (o instanceof q && ((q)o).e() == null) {
throw new IllegalArgumentException("Argument is not in graph");
}
throw new UnsupportedOperationException("Cannot get double from this type of Map!");
}
}
public int a(final Object o) {
try {
return this.b[((q)o).d()];
}
catch (ClassCastException ex) {
throw new IllegalArgumentException("Argument must be of type Node.");
}
catch (NullPointerException ex2) {
if (o == null) {
throw new IllegalArgumentException("Argument must be non-null.");
}
if (o instanceof q && ((q)o).e() == null) {
throw new IllegalArgumentException("Argument is not in graph");
}
throw new UnsupportedOperationException("Cannot get int from this type of Map!");
}
}
public boolean d(final Object o) {
try {
return this.c[((q)o).d()];
}
catch (ClassCastException ex) {
throw new IllegalArgumentException("Argument must be of type Node.");
}
catch (NullPointerException ex2) {
if (o == null) {
throw new IllegalArgumentException("Argument must be non-null.");
}
if (o instanceof q && ((q)o).e() == null) {
throw new IllegalArgumentException("Argument is not in graph");
}
throw new UnsupportedOperationException("Cannot get boolean from this type of Map!");
}
}
public void a(final Object o, final Object o2) {
try {
this.d[((q)o).d()] = o2;
}
catch (ClassCastException ex) {
throw new IllegalArgumentException("Key must be of type Node.");
}
catch (NullPointerException ex2) {
if (o == null) {
throw new IllegalArgumentException("Key must be non-null.");
}
if (o instanceof q && ((q)o).e() == null) {
throw new IllegalArgumentException("Key is not in graph");
}
throw new UnsupportedOperationException("Cannot set Object in this type of Map!");
}
}
public void a(final Object o, final double n) {
try {
this.a[((q)o).d()] = n;
}
catch (ClassCastException ex) {
throw new IllegalArgumentException("Key must be of type Node.");
}
catch (NullPointerException ex2) {
if (o == null) {
throw new IllegalArgumentException("Key must be non-null.");
}
if (o instanceof q && ((q)o).e() == null) {
throw new IllegalArgumentException("Key is not in graph");
}
throw new UnsupportedOperationException("Cannot set double in this type of Map!");
}
}
public void a(final Object o, final int n) {
try {
this.b[((q)o).d()] = n;
}
catch (ClassCastException ex) {
throw new IllegalArgumentException("Key must be of type Node.");
}
catch (NullPointerException ex2) {
if (o == null) {
throw new IllegalArgumentException("Key must be non-null.");
}
if (o instanceof q && ((q)o).e() == null) {
throw new IllegalArgumentException("Key is not in graph");
}
throw new UnsupportedOperationException("Cannot set int in this type of Map!");
}
}
public void a(final Object o, final boolean b) {
try {
this.c[((q)o).d()] = b;
}
catch (ClassCastException ex) {
throw new IllegalArgumentException("Key must be of type Node.");
}
catch (NullPointerException ex2) {
if (o == null) {
throw new IllegalArgumentException("Key must be non-null.");
}
if (o instanceof q && ((q)o).e() == null) {
throw new IllegalArgumentException("Key is not in graph");
}
throw new UnsupportedOperationException("Cannot set boolean in this type of Map!");
}
}
}
| true |
4292981be243674e81444f501a2da254887c358d
|
Java
|
xiaobei1009/bumble
|
/bumble/bumble-client/src/main/java/org/bumble/client/conn/BumbleConnectionCloseProcessor.java
|
UTF-8
| 3,826 | 2.484375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.bumble.client.conn;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import org.bumble.client.action.ClientActionBuilder;
import org.bumble.client.condition.BumbleCondition;
import org.bumble.client.condition.BumbleConditionFactory;
import org.bumble.client.remoting.RemotingTransporterFactory4BClient;
import org.bumble.client.threadlocal.TxnThreadLocal;
import org.bumble.core.action.ActionConst;
import org.bumble.core.thread.ThreadExecutorGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <pre>
* The {@link java.sql.Connection} is proxied
* by {@link org.bumble.client.conn.BumbleConnection}
* And the close connection will be processed by this class.
*
* And {@link org.bumble.client.conn.BumbleConnectionCloseProcessor#process(Connection)}
* will be called
* by {@link org.bumble.client.conn.BumbleConnection#close()}
*
* </pre>
* @author shenxiangyu
*
*/
public class BumbleConnectionCloseProcessor {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private volatile static BumbleConnectionCloseProcessor instance = null;
public static BumbleConnectionCloseProcessor getInstance() {
if (instance == null) {
instance = new BumbleConnectionCloseProcessor();
}
return instance;
}
private ExecutorService threadPool = ThreadExecutorGenerator.getInstance().getExecutor();
private String prepareActionString(String actionType) {
String ret = ClientActionBuilder.getInstance().buildActionMsg(actionType);
return ret;
}
/**
* Process the close connection
* @param conn
*/
public void process(final Connection conn) {
TxnThreadLocal current = TxnThreadLocal.getCurrent();
final String txnId = current.getTxnId();
final BumbleCondition condition = BumbleConditionFactory.getInstance().getCondition(txnId);
final RemotingTransporterFactory4BClient client = RemotingTransporterFactory4BClient.getInstance();
final String successMsg2ndPhase = prepareActionString(ActionConst.Type.TXN_SUCCESS_2PHASE);
final String faileMsg2ndPhase = prepareActionString(ActionConst.Type.TXN_FAIL_2PHASE);
threadPool.execute(new Runnable() {
public void run() {
logger.debug("Awaiting on condition [" + txnId + "], waiting for signal to commit/rollback...");
try {
if (condition == null) {
throw new Exception("Condition [" + txnId + "] does not exist.");
}
condition.await();
} catch (Exception e) {
logger.error(e.getMessage());
logger.trace(e.getMessage(), e);
condition.setState(BumbleCondition.State.FAIL);
} finally {
BumbleConditionFactory.getInstance().remove(txnId);
}
String state = condition.getState();
if (state.equals(BumbleCondition.State.SUCCESS)) {
try {
logger.debug("Commit the transaction");
conn.commit();
// Send 2nd phase commit succeeded message to manager
client.sendMsg(successMsg2ndPhase);
} catch (SQLException e) {
logger.error(e.getMessage());
logger.trace(e.getMessage(), e);
// Send 2nd phase commit failed message to manager
client.sendMsg(faileMsg2ndPhase);
}
} else if (state.equals(BumbleCondition.State.FAIL)) {
try {
logger.debug("Rollback the transaction");
conn.rollback();
} catch (SQLException e) {
logger.error(e.getMessage());
logger.trace(e.getMessage(), e);
}
}
try {
conn.close();
} catch (SQLException e) {
logger.error(e.getMessage());
logger.trace(e.getMessage(), e);
}
logger.debug("Transaction txnId[" + txnId + "] complete");
}
});
}
}
| true |
8da6d14e9fbce02d724df89bf9ee4c660d582238
|
Java
|
SpudGambler/IngSoftwareI
|
/EjemploPatronPrototipo/src/ejemplopatronprototipo/Maquina.java
|
UTF-8
| 1,302 | 2.671875 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ejemplopatronprototipo;
/**
*
* @author jaime
*/
public class Maquina extends PrototipoMaquina{
private int tiempoUso;
public Maquina() {
}
public Maquina(int datos, String nombre, String conector, int tiempoUso) {
super(datos, nombre, conector);
this.tiempoUso = tiempoUso;
}
/**
* @return the datos
*/
public int getDatos() {
return datos;
}
/**
* @param datos the datos to set
*/
public void setDatos(int datos) {
this.datos = datos;
}
/**
* @return the nombre
*/
public String getNombre() {
return nombre;
}
/**
* @param nombre the nombre to set
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* @return the conector
*/
public String getConector() {
return conector;
}
/**
* @param conector the conector to set
*/
public void setConector(String conector) {
this.conector = conector;
}
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.