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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
912efd459f0d90331d5a8d0edede8100b1957d87 | Java | HanGiHong/Biz_2021_01_java | /Java_015/src/com/callor/applications/service/PrimeServiceV2.java | UTF-8 | 1,033 | 3.515625 | 4 | [] | no_license | /*
* 1) c.c.a.servicePrimeServiceV2 클래스 생성
*
* 2) 정수형 매개변수 1개를 갖는 prime()method 생성
*
* 3) 매개변수값이 소수이면 매개변수 값, 아니면 -1을 return
*
* 4) prime_03 클래스의 main()method 에서 키보드로부터 숫자를 입력받고
*
* 5) prime()method에 값을 전달하며 호출하고
* return 값에 따라 소수인지 아닌지를 판별하여 출력
*/
package com.callor.applications.service;
public class PrimeServiceV2 {
public int prime(int Num) {
// num 값이 소수이면 return num
// 아니면 return -1
// if(소수이면) return num;
// else return -1;
for (int i = 1; i < Num; i++) {
// true 이면 소수가 아니다
if (Num % (i + 1) == 0) {
// prime() method 실행을 중단하고
// main() method에게 -1을 되돌려줘라
return -1;
}
}
// num값이 소수이어서 for() 반복문을 모두 수행하고
// 여기에 다다르면 num값을 그대로 return 하라
return Num;
}
} | true |
637bb082a9e8b7cd70b4b43f8defc6f0f657809e | Java | hanlinc27/ecolens | /app/src/main/java/com/google/firebase/ml/md/java/productsearch/SearchEngine.java | UTF-8 | 6,153 | 2.046875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.ml.md.java.productsearch;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import androidx.annotation.NonNull;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.ml.common.FirebaseMLException;
import com.google.firebase.ml.md.java.LiveObjectDetectionActivity;
import com.google.firebase.ml.md.java.objectdetection.DetectedObject;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.automl.FirebaseAutoMLLocalModel;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.label.FirebaseVisionImageLabel;
import com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler;
import com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceAutoMLImageLabelerOptions;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/** A fake search engine to help simulate the complete work flow. */
public class SearchEngine {
private static final String TAG = "SearchEngine";
private static String successful_label = "";
public static String formatted_label = "";
public interface SearchResultListener {
void onSearchCompleted(DetectedObject object, List<Product> productList);
}
private final RequestQueue searchRequestQueue;
private final ExecutorService requestCreationExecutor;
public SearchEngine(Context context) {
searchRequestQueue = Volley.newRequestQueue(context);
requestCreationExecutor = Executors.newSingleThreadExecutor();
}
public void search(DetectedObject object, SearchResultListener listener) {
// Crops the object image out of the full image is expensive, so do it off the UI thread.
Tasks.call(requestCreationExecutor, () -> createRequest(object))
.addOnSuccessListener(productRequest -> {
List<Product> list = new ArrayList<>();
listener.onSearchCompleted(object, list);
})
.addOnFailureListener(
e -> {
Log.e(TAG, "Failed to create product search request!", e);
// Remove the below dummy code after your own product search backed hooked up.
List<Product> productList = new ArrayList<>();
for (int i = 0; i < 8; i++) {
productList.add(
new Product(/* imageUrl= */ "", "Product title " + i, "Product subtitle " + i));
}
listener.onSearchCompleted(object, productList);
});
}
private static String createRequest(DetectedObject searchingObject) throws Exception {
Bitmap objectImageData = searchingObject.getBitmap();
if (objectImageData == null) {
throw new Exception("Failed to get object image data!");
}
FirebaseAutoMLLocalModel localModel = new FirebaseAutoMLLocalModel.Builder()
.setAssetFilePath("model/manifest.json").build();
FirebaseVisionImageLabeler labeler;
try {
FirebaseVisionOnDeviceAutoMLImageLabelerOptions options =
new FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder(localModel)
.setConfidenceThreshold(0.3f) // Evaluate your model in the Firebase console
// to determine an appropriate value.
.build();
labeler = FirebaseVision.getInstance().getOnDeviceAutoMLImageLabeler(options);
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(objectImageData);
labeler.processImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionImageLabel>>() {
@Override
public void onSuccess(List<FirebaseVisionImageLabel> labels) {
// Task completed successfully
System.out.println("nice");
for (FirebaseVisionImageLabel label: labels){
String text = label.getText();
successful_label = labels.get(0).getText();
}
formatted_label = display_name(successful_label);
LiveObjectDetectionActivity.bottomSheetButton.setText(formatted_label);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Task failed with an exception
// ...
}
});
} catch (FirebaseMLException e) {
// ...
}
return successful_label;
}
public void shutdown() {
searchRequestQueue.cancelAll(TAG);
requestCreationExecutor.shutdown();
}
public static String display_name(String label) {
if (label.equals("plastic_cups"))
return "Plastic Cups";
else if (label.equals("water_bottle_caps"))
return "Bottle Caps";
else if (label.equals("milk_cartons"))
return "Milk Cartons";
else if (label.equals("paper_coffee_cups"))
return "Coffee Cups";
else if (label.equals("soda_cans"))
return "Soda Cans";
else if (label.equals("plastic_bags"))
return "Plastic Bags";
else if (label.equals("plastic_bottles"))
return "Plastic Bottles";
else return "";
}
}
| true |
8128fc52b77e65b2fe04ec32ba6c427d7bdc26de | Java | DiegoSMelo/redAmber-WebApp | /src/main/java/br/com/sistema/redAmber/basicas/integracao/MatriculaIntegracao.java | UTF-8 | 2,106 | 2.28125 | 2 | [] | no_license | package br.com.sistema.redAmber.basicas.integracao;
import java.io.Serializable;
import java.util.Calendar;
import br.com.sistema.redAmber.basicas.Grade;
import br.com.sistema.redAmber.basicas.Turma;
import br.com.sistema.redAmber.basicas.enums.StatusMatricula;
public class MatriculaIntegracao implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private String codigoMatricula;
private Long idAluno;
private Calendar dataMatricula;
private Grade grade;
private Integer entrada;
private Turma turma;
private StatusMatricula status;
/*
* Getters and setters
*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCodigoMatricula() {
return codigoMatricula;
}
public void setCodigoMatricula(String codigoMatricula) {
this.codigoMatricula = codigoMatricula;
}
public Long getIdAluno() {
return idAluno;
}
public void setIdAluno(Long idAluno) {
this.idAluno = idAluno;
}
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
public Calendar getDataMatricula() {
return dataMatricula;
}
public void setDataMatricula(Calendar dataMatricula) {
this.dataMatricula = dataMatricula;
}
public Integer getEntrada() {
return entrada;
}
public void setEntrada(Integer entrada) {
this.entrada = entrada;
}
public Turma getTurma() {
return turma;
}
public void setTurma(Turma turma) {
this.turma = turma;
}
public StatusMatricula getStatus() {
return status;
}
public void setStatus(StatusMatricula status) {
this.status = status;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MatriculaIntegracao other = (MatriculaIntegracao) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
} | true |
4f0c61c1eb90b994ef63aa1cb6965a862667e537 | Java | abhishekpalavancha/Department-site | /src/controller/deletedisservlet.java | UTF-8 | 1,296 | 2.4375 | 2 | [] | no_license | package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.deletedis;
/**
* Servlet implementation class deletedisservlet
*/
@WebServlet("/deletedisservlet")
public class deletedisservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public deletedisservlet() {
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
String identity = request.getParameter("identity");
deletedis ds = new deletedis();
ds.delete();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| true |
7e64b5f02ab38c6980d4a3745331d14196d786c1 | Java | 7410abhi/Playground | /Handshakes/Main.java | UTF-8 | 142 | 1.859375 | 2 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int sum = 0;
for (int i=1; i<n; i++)
sum=sum+i;
cout<<sum;
} | true |
6eaf96a8f424d6a9e19c69dfb6c035821c304e14 | Java | rcrespillio/PROYECTO_AD | /CLIENTE_RMI/src/utils/Json.java | UTF-8 | 1,723 | 2.671875 | 3 | [] | no_license | package utils;
import org.json.simple.JSONObject;
import repo.LogeadoDTO;
public class Json {
public static JSONObject crearJSON(Object object){
System.out.println("ENTRE EN EL METODO JSON");
try{
//cosa rara,,, el instanceof no funciona....
System.out.println(object.getClass().toString());
System.out.println(LogeadoDTO.class.toString());
System.out.println(LogeadoDTO.class.toString());
//cosa rara QUE FUNCIONA,,, el instanceof no funciona....
if(object.getClass()==LogeadoDTO.class){
LogeadoDTO logeado = (LogeadoDTO) object;
System.out.println("pase el equals");
JSONObject obj = (JSONObject) new JSONObject();
obj.put("action", "usuariosConectados");
obj.put("apodo", logeado.getApodo());
obj.put("estado", logeado.getEstado());
System.out.println("obj json pendiente retorno: "+obj.toJSONString());
return obj;
}
System.out.println("class json: return null");
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public static JSONObject crearJSONError(String error) {
JSONObject obj = (JSONObject) new JSONObject();
obj.put("action", error);
return obj;
}
public static JSONObject crearJSONListaEspera() {
JSONObject obj = (JSONObject) new JSONObject();
obj.put("action", "enlista");
return obj;
}
public static JSONObject crearJSONJugarIndividual() {
JSONObject obj = (JSONObject) new JSONObject();
obj.put("action", "individualcreada");
return obj;
}
public static JSONObject crearJSONRedireccionIndividual() {
JSONObject obj = (JSONObject) new JSONObject();
obj.put("action", "redireccionindividual");
return obj;
}
} | true |
dd2197526e15c87c7ba25d0c62d85ea5631bd7cf | Java | benkaddour/E-drive | /src/java/serveur/Moniteur.java | UTF-8 | 810 | 2.421875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package serveur;
import java.util.ArrayList;
/**
*
* @author Sénthène
*/
public class Moniteur extends Utilisateur {
private int experience;
private Voiture voiture;
private ArrayList <Offre> offres;
public Moniteur(String n, String p, int tel, String m, String a, String d, int c, String u, String mdp, int age, int e, Voiture v, ArrayList <Offre> o) {
super(n, p, tel, m, a, d, c, u, mdp, age);
experience = e;
voiture = v;
offres = o;
}
public void ajoutOffre(Offre o){
offres.add(o);
}
}
| true |
a0f98e7d17d7ada9ff2da850ffc6794daac8cbf0 | Java | ztoroschin/flashcards | /src/flashcards/commands/ExportCommand.java | UTF-8 | 1,337 | 3.078125 | 3 | [] | no_license | package flashcards.commands;
import flashcards.Card;
import flashcards.Database;
import flashcards.console.ApplicationCommand;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Scanner;
public class ExportCommand implements ApplicationCommand {
private final Database database;
public ExportCommand(Database database) {
this.database = database;
}
@Override
public void execute() {
Scanner scanner = new Scanner(System.in);
database.print("File name:");
String filename = scanner.nextLine().trim();
database.appendLog(filename);
exportCards(filename);
}
public void exportCards(String filename) {
Map<String, Card> cards = database.getCards();
File file = new File(filename);
try (PrintWriter printWriter = new PrintWriter(file)) {
for (var card : cards.entrySet()) {
printWriter.printf("%s\t%s\t%s\n", card.getKey(), card.getValue().getDefinition(), card.getValue().getMistakes());
}
} catch (FileNotFoundException e) {
database.print(String.format("File not found: %s", e.getMessage()));
}
database.print(String.format("%d cards have been saved.", cards.size()));
}
} | true |
5c8e7e676999487cff16f670df8ec33ec1836a7a | Java | zhyusgethup/learnAndDo | /gitwaySir/src/test/java/com/cellsgame/command/paramHandler/ParamParseHandler.java | UTF-8 | 187 | 2.015625 | 2 | [] | no_license | package com.cellsgame.command.paramHandler;
public interface ParamParseHandler {
public boolean match(Class cl);
public Object parse(String word);
public String getName();
}
| true |
76ead42ea2d7d79aa783e807aaf71c79713994f8 | Java | corneil/spring-data-rdf | /spring-data-rdf2go/src/main/java/org/springframework/data/rdf/repository/RdfRepository.java | UTF-8 | 234 | 1.515625 | 2 | [] | no_license | package org.springframework.data.rdf.repository;
import java.io.Serializable;
import org.springframework.data.repository.CrudRepository;
public interface RdfRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {
}
| true |
da2d145a74d326fffdc5143f80eccbe8ea121f0b | Java | YuiGin/SSMShoppingWeb | /src/main/java/packageModel/ItemCategory.java | UTF-8 | 14,978 | 2.4375 | 2 | [] | no_license | package packageModel;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
/**
*
* @author DAO
*/
public class ItemCategory implements Serializable {
private static final long serialVersionUID = 1632808912194L;
/**
* 主键
*
* isNullAble:0
*/
private Integer id;
/**
*
* isNullAble:1
*/
private String name;
/**
*
* isNullAble:1
*/
private Integer pid;
/**
*
* isNullAble:1
*/
private Integer isDelete;
public void setId(Integer id){this.id = id;}
public Integer getId(){return this.id;}
public void setName(String name){this.name = name;}
public String getName(){return this.name;}
public void setPid(Integer pid){this.pid = pid;}
public Integer getPid(){return this.pid;}
public void setIsDelete(Integer isDelete){this.isDelete = isDelete;}
public Integer getIsDelete(){return this.isDelete;}
@Override
public String toString() {
return "ItemCategory{" +
"id='" + id + '\'' +
"name='" + name + '\'' +
"pid='" + pid + '\'' +
"isDelete='" + isDelete + '\'' +
'}';
}
public static Builder Build(){return new Builder();}
public static ConditionBuilder ConditionBuild(){return new ConditionBuilder();}
public static UpdateBuilder UpdateBuild(){return new UpdateBuilder();}
public static QueryBuilder QueryBuild(){return new QueryBuilder();}
public static class UpdateBuilder {
private ItemCategory set;
private ConditionBuilder where;
public UpdateBuilder set(ItemCategory set){
this.set = set;
return this;
}
public ItemCategory getSet(){
return this.set;
}
public UpdateBuilder where(ConditionBuilder where){
this.where = where;
return this;
}
public ConditionBuilder getWhere(){
return this.where;
}
public UpdateBuilder build(){
return this;
}
}
public static class QueryBuilder extends ItemCategory{
/**
* 需要返回的列
*/
private Map<String,Object> fetchFields;
public Map<String,Object> getFetchFields(){return this.fetchFields;}
private List<Integer> idList;
public List<Integer> getIdList(){return this.idList;}
private Integer idSt;
private Integer idEd;
public Integer getIdSt(){return this.idSt;}
public Integer getIdEd(){return this.idEd;}
private List<String> nameList;
public List<String> getNameList(){return this.nameList;}
private List<String> fuzzyName;
public List<String> getFuzzyName(){return this.fuzzyName;}
private List<String> rightFuzzyName;
public List<String> getRightFuzzyName(){return this.rightFuzzyName;}
private List<Integer> pidList;
public List<Integer> getPidList(){return this.pidList;}
private Integer pidSt;
private Integer pidEd;
public Integer getPidSt(){return this.pidSt;}
public Integer getPidEd(){return this.pidEd;}
private List<Integer> isDeleteList;
public List<Integer> getIsDeleteList(){return this.isDeleteList;}
private Integer isDeleteSt;
private Integer isDeleteEd;
public Integer getIsDeleteSt(){return this.isDeleteSt;}
public Integer getIsDeleteEd(){return this.isDeleteEd;}
private QueryBuilder (){
this.fetchFields = new HashMap<>();
}
public QueryBuilder idBetWeen(Integer idSt,Integer idEd){
this.idSt = idSt;
this.idEd = idEd;
return this;
}
public QueryBuilder idGreaterEqThan(Integer idSt){
this.idSt = idSt;
return this;
}
public QueryBuilder idLessEqThan(Integer idEd){
this.idEd = idEd;
return this;
}
public QueryBuilder id(Integer id){
setId(id);
return this;
}
public QueryBuilder idList(Integer ... id){
this.idList = solveNullList(id);
return this;
}
public QueryBuilder idList(List<Integer> id){
this.idList = id;
return this;
}
public QueryBuilder fetchId(){
setFetchFields("fetchFields","id");
return this;
}
public QueryBuilder excludeId(){
setFetchFields("excludeFields","id");
return this;
}
public QueryBuilder fuzzyName (List<String> fuzzyName){
this.fuzzyName = fuzzyName;
return this;
}
public QueryBuilder fuzzyName (String ... fuzzyName){
this.fuzzyName = solveNullList(fuzzyName);
return this;
}
public QueryBuilder rightFuzzyName (List<String> rightFuzzyName){
this.rightFuzzyName = rightFuzzyName;
return this;
}
public QueryBuilder rightFuzzyName (String ... rightFuzzyName){
this.rightFuzzyName = solveNullList(rightFuzzyName);
return this;
}
public QueryBuilder name(String name){
setName(name);
return this;
}
public QueryBuilder nameList(String ... name){
this.nameList = solveNullList(name);
return this;
}
public QueryBuilder nameList(List<String> name){
this.nameList = name;
return this;
}
public QueryBuilder fetchName(){
setFetchFields("fetchFields","name");
return this;
}
public QueryBuilder excludeName(){
setFetchFields("excludeFields","name");
return this;
}
public QueryBuilder pidBetWeen(Integer pidSt,Integer pidEd){
this.pidSt = pidSt;
this.pidEd = pidEd;
return this;
}
public QueryBuilder pidGreaterEqThan(Integer pidSt){
this.pidSt = pidSt;
return this;
}
public QueryBuilder pidLessEqThan(Integer pidEd){
this.pidEd = pidEd;
return this;
}
public QueryBuilder pid(Integer pid){
setPid(pid);
return this;
}
public QueryBuilder pidList(Integer ... pid){
this.pidList = solveNullList(pid);
return this;
}
public QueryBuilder pidList(List<Integer> pid){
this.pidList = pid;
return this;
}
public QueryBuilder fetchPid(){
setFetchFields("fetchFields","pid");
return this;
}
public QueryBuilder excludePid(){
setFetchFields("excludeFields","pid");
return this;
}
public QueryBuilder isDeleteBetWeen(Integer isDeleteSt,Integer isDeleteEd){
this.isDeleteSt = isDeleteSt;
this.isDeleteEd = isDeleteEd;
return this;
}
public QueryBuilder isDeleteGreaterEqThan(Integer isDeleteSt){
this.isDeleteSt = isDeleteSt;
return this;
}
public QueryBuilder isDeleteLessEqThan(Integer isDeleteEd){
this.isDeleteEd = isDeleteEd;
return this;
}
public QueryBuilder isDelete(Integer isDelete){
setIsDelete(isDelete);
return this;
}
public QueryBuilder isDeleteList(Integer ... isDelete){
this.isDeleteList = solveNullList(isDelete);
return this;
}
public QueryBuilder isDeleteList(List<Integer> isDelete){
this.isDeleteList = isDelete;
return this;
}
public QueryBuilder fetchIsDelete(){
setFetchFields("fetchFields","isDelete");
return this;
}
public QueryBuilder excludeIsDelete(){
setFetchFields("excludeFields","isDelete");
return this;
}
private <T>List<T> solveNullList(T ... objs){
if (objs != null){
List<T> list = new ArrayList<>();
for (T item : objs){
if (item != null){
list.add(item);
}
}
return list;
}
return null;
}
public QueryBuilder fetchAll(){
this.fetchFields.put("AllFields",true);
return this;
}
public QueryBuilder addField(String ... fields){
List<String> list = new ArrayList<>();
if (fields != null){
for (String field : fields){
list.add(field);
}
}
this.fetchFields.put("otherFields",list);
return this;
}
@SuppressWarnings("unchecked")
private void setFetchFields(String key,String val){
Map<String,Boolean> fields= (Map<String, Boolean>) this.fetchFields.get(key);
if (fields == null){
fields = new HashMap<>();
}
fields.put(val,true);
this.fetchFields.put(key,fields);
}
public ItemCategory build(){return this;}
}
public static class ConditionBuilder{
private List<Integer> idList;
public List<Integer> getIdList(){return this.idList;}
private Integer idSt;
private Integer idEd;
public Integer getIdSt(){return this.idSt;}
public Integer getIdEd(){return this.idEd;}
private List<String> nameList;
public List<String> getNameList(){return this.nameList;}
private List<String> fuzzyName;
public List<String> getFuzzyName(){return this.fuzzyName;}
private List<String> rightFuzzyName;
public List<String> getRightFuzzyName(){return this.rightFuzzyName;}
private List<Integer> pidList;
public List<Integer> getPidList(){return this.pidList;}
private Integer pidSt;
private Integer pidEd;
public Integer getPidSt(){return this.pidSt;}
public Integer getPidEd(){return this.pidEd;}
private List<Integer> isDeleteList;
public List<Integer> getIsDeleteList(){return this.isDeleteList;}
private Integer isDeleteSt;
private Integer isDeleteEd;
public Integer getIsDeleteSt(){return this.isDeleteSt;}
public Integer getIsDeleteEd(){return this.isDeleteEd;}
public ConditionBuilder idBetWeen(Integer idSt,Integer idEd){
this.idSt = idSt;
this.idEd = idEd;
return this;
}
public ConditionBuilder idGreaterEqThan(Integer idSt){
this.idSt = idSt;
return this;
}
public ConditionBuilder idLessEqThan(Integer idEd){
this.idEd = idEd;
return this;
}
public ConditionBuilder idList(Integer ... id){
this.idList = solveNullList(id);
return this;
}
public ConditionBuilder idList(List<Integer> id){
this.idList = id;
return this;
}
public ConditionBuilder fuzzyName (List<String> fuzzyName){
this.fuzzyName = fuzzyName;
return this;
}
public ConditionBuilder fuzzyName (String ... fuzzyName){
this.fuzzyName = solveNullList(fuzzyName);
return this;
}
public ConditionBuilder rightFuzzyName (List<String> rightFuzzyName){
this.rightFuzzyName = rightFuzzyName;
return this;
}
public ConditionBuilder rightFuzzyName (String ... rightFuzzyName){
this.rightFuzzyName = solveNullList(rightFuzzyName);
return this;
}
public ConditionBuilder nameList(String ... name){
this.nameList = solveNullList(name);
return this;
}
public ConditionBuilder nameList(List<String> name){
this.nameList = name;
return this;
}
public ConditionBuilder pidBetWeen(Integer pidSt,Integer pidEd){
this.pidSt = pidSt;
this.pidEd = pidEd;
return this;
}
public ConditionBuilder pidGreaterEqThan(Integer pidSt){
this.pidSt = pidSt;
return this;
}
public ConditionBuilder pidLessEqThan(Integer pidEd){
this.pidEd = pidEd;
return this;
}
public ConditionBuilder pidList(Integer ... pid){
this.pidList = solveNullList(pid);
return this;
}
public ConditionBuilder pidList(List<Integer> pid){
this.pidList = pid;
return this;
}
public ConditionBuilder isDeleteBetWeen(Integer isDeleteSt,Integer isDeleteEd){
this.isDeleteSt = isDeleteSt;
this.isDeleteEd = isDeleteEd;
return this;
}
public ConditionBuilder isDeleteGreaterEqThan(Integer isDeleteSt){
this.isDeleteSt = isDeleteSt;
return this;
}
public ConditionBuilder isDeleteLessEqThan(Integer isDeleteEd){
this.isDeleteEd = isDeleteEd;
return this;
}
public ConditionBuilder isDeleteList(Integer ... isDelete){
this.isDeleteList = solveNullList(isDelete);
return this;
}
public ConditionBuilder isDeleteList(List<Integer> isDelete){
this.isDeleteList = isDelete;
return this;
}
private <T>List<T> solveNullList(T ... objs){
if (objs != null){
List<T> list = new ArrayList<>();
for (T item : objs){
if (item != null){
list.add(item);
}
}
return list;
}
return null;
}
public ConditionBuilder build(){return this;}
}
public static class Builder {
private ItemCategory obj;
public Builder(){
this.obj = new ItemCategory();
}
public Builder id(Integer id){
this.obj.setId(id);
return this;
}
public Builder name(String name){
this.obj.setName(name);
return this;
}
public Builder pid(Integer pid){
this.obj.setPid(pid);
return this;
}
public Builder isDelete(Integer isDelete){
this.obj.setIsDelete(isDelete);
return this;
}
public ItemCategory build(){return obj;}
}
}
| true |
c083025d3ec02a67284a203f963f273fab1822ec | Java | gongwy/cheche365 | /wechat/src/main/groovy/com/cheche365/cheche/wechat/PaymentManager.java | UTF-8 | 2,254 | 2.3125 | 2 | [] | no_license | package com.cheche365.cheche.wechat;
import com.cheche365.cheche.core.constants.WebConstants;
import com.cheche365.cheche.core.repository.WechatUserInfoRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
/**
* Created by liqiang on 4/4/15.
*/
@Component
public class PaymentManager {
protected final static int RETRY_TIMES = 5;
private Logger logger = LoggerFactory.getLogger(PaymentManager.class);
protected static final String PROCESSED_ORDER_KEY = "wechat:processed_order";
protected String ip;
@Autowired
protected RedisTemplate redisTemplate;
@Autowired
protected WechatUserInfoRepository wechatUserInfoRepository;
@Autowired
protected MessageSender messageSender;
public PaymentManager(){
ip = getPublicIP();
}
private String getPublicIP() {
try {
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
return in.readLine();
} catch (MalformedURLException e) {
logger.warn("can't find public ip by access amazon service",e);
} catch (IOException e) {
logger.warn("can't find public ip by access amazon service", e);
}
try {
return InetAddress.getByName(WebConstants.getDomain()).getHostAddress();
} catch (UnknownHostException e) {
try {
logger.warn("can't get ip address for " + WebConstants.getDomain() + "will try to get local ip address.");
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e1) {
logger.warn("can't get ip address of current server, will return empty String");
}
}
return "";
}
}
| true |
965588886047420c710e8ba3d874a9618009fff0 | Java | RafaelAbreu05/Dissertacao | /ClienteAndroid/src/clienteTCP/EnviarSinais.java | UTF-8 | 774 | 2.734375 | 3 | [] | no_license | package clienteTCP;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import classes.Sinal;
public class EnviarSinais {
private Socket socket;
public void enviarSinais(ArrayList<Sinal> sinais) {
try {
System.out.println(sinais.toString());
socket = new Socket(Constantes.SERVIDOR_IP,
Constantes.SERVIDOR_PORTA_SINAIS);
OutputStream os = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(sinais);
oos.close();
os.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
1847b25041c33aaae15055d4e5e8be6dd3895aa1 | Java | aekuzmin96/GameOfLife3D | /src/Presets.java | UTF-8 | 3,742 | 3.265625 | 3 | [] | no_license | import javafx.scene.paint.PhongMaterial;
import java.util.Random;
/**
* Anton Kuzmin
*
* This class holds all of the preset configuration for the cube.
*/
public class Presets
{
/**
* Resets the cube (current generation and next generation)
* to the state in which all of the cells are dead.
*
* @param board current generation board
* @param boardTwo next generation board
* @param blueMaterial color to set the cells to
*/
public void reset(Cell[][][] board, boolean[][][] boardTwo, PhongMaterial blueMaterial)
{
for (int x = 1; x < 32; x++)
{
for (int y = 1; y < 32; y++)
{
for (int z = 1; z < 32; z++)
{
board[x][y][z].setDead();
board[x][y][z].cellBox.setMaterial(blueMaterial);
board[x][y][z].cellBox.setVisible(false);
boardTwo[x][y][z] = false;
}
}
}
}
/**
* Randomly place cells in the cube
*
* @param board current generation board
*/
public void randomPreset(Cell[][][] board)
{
Random rand = new Random();
for (int x = 1; x < 31; x++)
{
for (int y = 1; y < 31; y++)
{
for (int z = 1; z < 31; z++)
{
int n = rand.nextInt(100);
if (n > 85)
{
board[x][y][z].setAlive();
}
}
}
}
}
/**
* First preset for the cube. It is a cube that
* has cells in every other index.
*
* @param board current generation board
*/
public void preset1(Cell[][][] board)
{
for (int x = 1; x < 31; x++)
{
for (int y = 1; y < 31; y++)
{
for (int z = 1; z < 31; z++)
{
if ((x % 2 == 0) && (y % 2 == 0) && (z % 2 == 0))
{
board[x][y][z].setAlive();
}
}
}
}
}
/**
* Second preset for the cube.
*
* @param board current generation board
*/
public void preset2(Cell[][][] board)
{
for (int i = 1; i < 31; i++)
{
for (int j = 1; j < 31; j++)
{
board[i][j][j].setAlive();
board[j][j][i].setAlive();
board[j][i][j].setAlive();
}
}
}
/**
* Third preset for the cube.
*
* @param board current generation board
*/
public void preset3(Cell[][][] board)
{
for (int i = 3; i < 28; i += 5)
{
for (int j = 3; j < 28; j += 5)
{
for (int k = 3; k < 28; k += 5)
{
for (int l = 0; l < 4; l++)
{
board[j][i + l][k].setAlive();
board[j + 1][i + l][k].setAlive();
board[j + 2][i + l][k].setAlive();
board[j + 3][i + l][k].setAlive();
}
}
}
}
}
/**
* Fourth preset for the cube. After several generations
* have passed, the remaining cells become oscillators.
*
* @param board current generation board
*/
public void preset4(Cell[][][] board)
{
for (int i = 1; i < 31; i++)
{
for (int j = 1; j < 31; j++)
{
board[15][i][j].setAlive();
board[i][15][j].setAlive();
board[i][j][15].setAlive();
}
}
}
/**
* Fifth preset for the cube.
*
* @param board current generation board
*/
public void preset5(Cell[][][] board)
{
for (int i = 1; i < 31; i++)
{
board[i][1][1].setAlive();
board[1][i][1].setAlive();
board[1][1][i].setAlive();
board[i][30][30].setAlive();
board[30][i][30].setAlive();
board[30][30][i].setAlive();
board[1][i][i].setAlive();
board[i][1][i].setAlive();
board[i][i][1].setAlive();
board[30][i][i].setAlive();
board[i][30][i].setAlive();
board[i][i][30].setAlive();
}
}
}
| true |
fde5f3903bc37287e534753d2fd6a515654ed1ee | Java | rockduan/androidN-android-7.1.1_r28 | /WORKING_DIRECTORY/packages/services/Car/car-cluster-demo-renderer/src/android/car/cluster/demorenderer/CallStateMonitor.java | UTF-8 | 4,293 | 1.9375 | 2 | [] | no_license | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.car.cluster.demorenderer;
import android.annotation.Nullable;
import android.car.cluster.demorenderer.PhoneBook.Contact;
import android.car.cluster.demorenderer.PhoneBook.ContactLoadedListener;
import android.car.cluster.demorenderer.PhoneBook.ContactPhotoLoadedListener;
import android.content.Context;
import android.graphics.Bitmap;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.lang.ref.WeakReference;
/**
* Monitors call state.
*/
public class CallStateMonitor implements ContactLoadedListener, ContactPhotoLoadedListener {
private final static String TAG = CallStateMonitor.class.getSimpleName();
private final PhoneBook mPhoneBook;
private final TelephonyManager mTelephonyManager;
private final PhoneStateListener mListener;
private final CallStateListener mCallStateListener;
CallStateMonitor(Context context, PhoneStateListener listener) {
Log.d(TAG, "ctor, context: " + context + ", phoneRenderer: " + listener +
", contentResolver: " + context.getContentResolver() +
", applicationContext: " + context.getApplicationContext());
mListener = listener;
mTelephonyManager = context.getSystemService(TelephonyManager.class);
mPhoneBook = new PhoneBook(context, mTelephonyManager);
mCallStateListener = new CallStateListener(this);
mTelephonyManager.listen(mCallStateListener,
android.telephony.PhoneStateListener.LISTEN_CALL_STATE);
updateRendererPhoneStatusIfAvailable();
}
public void release() {
mTelephonyManager.listen(mCallStateListener,
android.telephony.PhoneStateListener.LISTEN_NONE);
}
private void updateRendererPhoneStatusIfAvailable() {
onCallStateChanged(mTelephonyManager.getCallState(), null);
}
private void onCallStateChanged(int state, final String number) {
Log.d(TAG, "onCallStateChanged, state:" + state + ", phoneNumber: " + number);
// Update call state immediately on instrument cluster.
mListener.onCallStateChanged(state, PhoneBook.getFormattedNumber(number));
// Now fetching details asynchronously.
mPhoneBook.getContactDetailsAsync(number, this);
}
@Override
public void onContactLoaded(String number, @Nullable Contact contact) {
if (contact != null) {
mListener.onContactDetailsUpdated(contact.getName(), contact.getType(),
mPhoneBook.isVoicemail(number));
mPhoneBook.getContactPictureAsync(contact.getId(), this);
}
}
@Override
public void onPhotoLoaded(int contactId, @Nullable Bitmap photo) {
mListener.onContactPhotoUpdated(photo);
}
public interface PhoneStateListener {
void onCallStateChanged(int state, @Nullable String number);
void onContactDetailsUpdated(
@Nullable CharSequence name,
@Nullable CharSequence typeLabel,
boolean isVoiceMail);
void onContactPhotoUpdated(Bitmap picture);
}
private static class CallStateListener extends android.telephony.PhoneStateListener {
private final WeakReference<CallStateMonitor> mServiceRef;
CallStateListener(CallStateMonitor service) {
mServiceRef = new WeakReference<>(service);
}
@Override
public void onCallStateChanged(int state, String incomingNumber) {
CallStateMonitor service = mServiceRef.get();
if (service != null) {
service.onCallStateChanged(state, incomingNumber);
}
}
}
}
| true |
4defdd0c2e99cfb61d94dda78d92c03bd1af97c7 | Java | hoolatech/datarouter | /datarouter-web/src/main/java/io/datarouter/web/port/TomcatPortIdentifier.java | UTF-8 | 2,262 | 2.28125 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**
* Copyright © 2009 HotPads (admin@hotpads.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.datarouter.web.port;
import java.lang.management.ManagementFactory;
import javax.inject.Singleton;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import io.datarouter.httpclient.security.UrlScheme;
@Singleton
public class TomcatPortIdentifier implements PortIdentifier{
private Integer httpPort;
private Integer httpsPort;
public TomcatPortIdentifier() throws MalformedObjectNameException{
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName query = new ObjectName(CompoundPortIdentifier.CATALINA_JMX_DOMAIN + ":type=ProtocolHandler,*");
server.queryNames(query, null).stream().forEach(objectName -> {
int port;
boolean sslEnabled;
String scheme;
try{
port = (int)server.getAttribute(objectName, "port");
sslEnabled = (boolean)server.getAttribute(objectName, "sSLEnabled");
objectName = new ObjectName(CompoundPortIdentifier.CATALINA_JMX_DOMAIN + ":type=Connector,port="
+ port);
scheme = (String)server.getAttribute(objectName, "scheme");
}catch(JMException e){
throw new RuntimeException(e);
}
if(sslEnabled){
this.httpsPort = port;
}else{
if(scheme.equals(UrlScheme.HTTP.getStringRepresentation())){
this.httpPort = port;
}
}
});
if(this.httpPort == null || this.httpsPort == null){
throw new RuntimeException("TomcatPortIdentifier didn't found port numbers in jmx");
}
}
@Override
public Integer getHttpPort(){
return httpPort;
}
@Override
public Integer getHttpsPort(){
return httpsPort;
}
}
| true |
6745e554a75a7a0da1d4dde4599dfbbd73f0faf4 | Java | TomD011099/trm4j | /src/test/java/world/inetum/realdolmen/validation/ProjectTests.java | UTF-8 | 7,548 | 2.484375 | 2 | [] | no_license | package world.inetum.realdolmen.validation;
import org.hibernate.validator.internal.engine.ConstraintViolationImpl;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import world.inetum.realdolmen.project.Project;
import world.inetum.realdolmen.project.models.NewProjectModel;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.time.Duration;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
public class ProjectTests {
private ValidatorFactory validatorFactory;
private Validator validator;
@BeforeEach
void setUp() {
validatorFactory = Validation.buildDefaultValidatorFactory();
validator = validatorFactory.getValidator();
}
@AfterEach
void tearDown() {
validatorFactory.close();
}
@Test
void project_nullName_invalid() {
Project p = new Project();
p.setName(null);
p.setPurchasedHours(Duration.ofHours(5));
Set<ConstraintViolation<Project>> violations = validator.validate(p);
assertFalse(violations.isEmpty());
boolean isFound = false;
for (Object o : violations.toArray()) {
ConstraintViolationImpl c = (ConstraintViolationImpl) o;
if (c.getMessage().equals("must not be null")) {
isFound = true;
break;
}
}
assertTrue(isFound);
}
@Test
void project_emptyName_invalid() {
Project p = new Project();
p.setName(" ");
p.setPurchasedHours(Duration.ofHours(5));
Set<ConstraintViolation<Project>> violations = validator.validate(p);
assertEquals(1, violations.size());
ConstraintViolationImpl constraintViolation = (ConstraintViolationImpl) violations.toArray()[0];
assertEquals("must not be blank", constraintViolation.getMessage());
}
@Test
void project_nullHours_invalid() {
Project p = new Project();
p.setName("Test");
p.setPurchasedHours(null);
Set<ConstraintViolation<Project>> violations = validator.validate(p);
assertFalse(violations.isEmpty());
boolean isFound = false;
for (Object o : violations.toArray()) {
ConstraintViolationImpl c = (ConstraintViolationImpl) o;
if (c.getMessage().equals("must not be null")) {
isFound = true;
break;
}
}
assertTrue(isFound);
}
@Test
void project_negativeHours_invalid() {
Project p = new Project();
p.setName("Test");
p.setPurchasedHours(Duration.ofHours(-5));
Set<ConstraintViolation<Project>> violations = validator.validate(p);
assertFalse(violations.isEmpty());
boolean isFound = false;
for (Object o : violations.toArray()) {
ConstraintViolationImpl c = (ConstraintViolationImpl) o;
if (c.getMessage().equals("Registered hours cannot be negative")) {
isFound = true;
break;
}
}
assertTrue(isFound);
}
@Test
void project_zeroHours_invalid() {
Project p = new Project();
p.setName("Test");
p.setPurchasedHours(Duration.ZERO);
Set<ConstraintViolation<Project>> violations = validator.validate(p);
assertFalse(violations.isEmpty());
boolean isFound = false;
for (Object o : violations.toArray()) {
ConstraintViolationImpl c = (ConstraintViolationImpl) o;
if (c.getMessage().equals("Registered hours cannot be negative")) {
isFound = true;
break;
}
}
assertTrue(isFound);
}
@Test
void project_goodProject_valid() {
Project p = new Project();
p.setName("Test");
p.setPurchasedHours(Duration.ofHours(5));
Set<ConstraintViolation<Project>> violations = validator.validate(p);
assertTrue(violations.isEmpty());
}
@Test
void newProjectModel_nullName_invalid() {
NewProjectModel p = new NewProjectModel();
p.setName(null);
p.setPurchasedHours(5);
Set<ConstraintViolation<NewProjectModel>> violations = validator.validate(p);
assertFalse(violations.isEmpty());
boolean isFound = false;
for (Object o : violations.toArray()) {
ConstraintViolationImpl c = (ConstraintViolationImpl) o;
if (c.getMessage().equals("must not be null")) {
isFound = true;
break;
}
}
assertTrue(isFound);
}
@Test
void newProjectModel_emptyName_invalid() {
NewProjectModel p = new NewProjectModel();
p.setName(" ");
p.setPurchasedHours(5);
Set<ConstraintViolation<NewProjectModel>> violations = validator.validate(p);
assertEquals(1, violations.size());
ConstraintViolationImpl constraintViolation = (ConstraintViolationImpl) violations.toArray()[0];
assertEquals("must not be blank", constraintViolation.getMessage());
}
@Test
void newProjectModel_nullHours_invalid() {
NewProjectModel p = new NewProjectModel();
p.setName("Test");
p.setPurchasedHours(null);
Set<ConstraintViolation<NewProjectModel>> violations = validator.validate(p);
assertFalse(violations.isEmpty());
boolean isFound = false;
for (Object o : violations.toArray()) {
ConstraintViolationImpl c = (ConstraintViolationImpl) o;
if (c.getMessage().equals("must not be null")) {
isFound = true;
break;
}
}
assertTrue(isFound);
}
@Test
void newProjectModel_negativeHours_invalid() {
NewProjectModel p = new NewProjectModel();
p.setName("Test");
p.setPurchasedHours(-5);
Set<ConstraintViolation<NewProjectModel>> violations = validator.validate(p);
assertFalse(violations.isEmpty());
boolean isFound = false;
for (Object o : violations.toArray()) {
ConstraintViolationImpl c = (ConstraintViolationImpl) o;
System.out.println(c.getMessage());
if (c.getMessage().equals("must be greater than 0")) {
isFound = true;
break;
}
}
assertTrue(isFound);
}
@Test
void newProjectModel_zeroHours_invalid() {
NewProjectModel p = new NewProjectModel();
p.setName("Test");
p.setPurchasedHours(0);
Set<ConstraintViolation<NewProjectModel>> violations = validator.validate(p);
assertFalse(violations.isEmpty());
boolean isFound = false;
for (Object o : violations.toArray()) {
ConstraintViolationImpl c = (ConstraintViolationImpl) o;
if (c.getMessage().equals("must be greater than 0")) {
isFound = true;
break;
}
}
assertTrue(isFound);
}
@Test
void newProjectModel_goodNewProjectModel_valid() {
NewProjectModel p = new NewProjectModel();
p.setName("Test");
p.setPurchasedHours(5);
Set<ConstraintViolation<NewProjectModel>> violations = validator.validate(p);
assertTrue(violations.isEmpty());
}
}
| true |
0c26561f71a4ddb63cfd4eeff4cece81f285b724 | Java | Abish-R/Ridio-1.1 | /app/src/main/java/helix/ridioandroidstudio/SplashScreen.java | UTF-8 | 3,109 | 2.359375 | 2 | [] | no_license | /** Ridio v1.0.1
* Purpose : SplashScreen
* Created by : Abish
* Created Dt : old file
* Modified on:
* Verified by: Srinivas
* Verified Dt:
* **/
package helix.ridioandroidstudio;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.WindowManager;
import android.widget.TextView;
public class SplashScreen extends Activity {
Ridiologin rid_login=new Ridiologin();
/**Class Variables*/
String status_user,status_login;
String fontPath = "fonts/Lato-Bold.ttf";
TextView helix_textf,helix_textanager,helix_made_with,helix_at;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splashscreen);
initializeViews();
/**Getting Vendor ID*/
SharedPreferences sp=getSharedPreferences("key", Context.MODE_PRIVATE);
final String value = sp.getString("value", "");
Log.e("Username", value);
// Log.d(status_login, status_user);
Thread background = new Thread() {
public void run() {
try {
/** Thread will sleep for 3 seconds*/
sleep(3000);
/**Validation and Conditions for login*/
if(value!=""){
/**Starts Main Screen*/
Intent i=new Intent(getBaseContext(),MainScreen.class);
startActivity(i);
finish();
}
else{
/**Starts SignIn&UP Controller Screen*/
Intent i=new Intent(getBaseContext(),SignInSignUpController.class);
startActivity(i);
finish();
}
} catch (Exception e) {
}
}
};
/** start thread*/
background.start();
}
/**initialize and set views as per the requirement alignment*/
private void initializeViews() {
helix_textf= (TextView)findViewById(R.id.helix_textf);
helix_made_with= (TextView)findViewById(R.id.helix_made_with);
helix_at= (TextView)findViewById(R.id.helix_at);
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
helix_made_with.setTypeface(tf);
helix_at.setTypeface(tf);
helix_textf.setTypeface(tf);
String s= helix_textf.getText().toString();
SpannableString ss1= new SpannableString(s);
ss1.setSpan(new RelativeSizeSpan(1.3f), 0,1, 0); // set size
ss1.setSpan(new RelativeSizeSpan(1.3f), 6,7, 0); // set size
helix_textf.setText(ss1);
}
}
| true |
cc0a38fbd83175726b524a2c8ad136009023e563 | Java | smartrecruiters/jenkins-build-monitor-plugin | /build-monitor-plugin/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/features/headline/HeadlineOfFixed.java | UTF-8 | 1,841 | 2.21875 | 2 | [
"MIT"
] | permissive | package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.features.headline;
import com.smartcodeltd.jenkinsci.plugins.buildmonitor.readability.Lister;
import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.BuildViewModel;
import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.JobView;
import hudson.model.Result;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
public class HeadlineOfFixed implements CandidateHeadline {
private final JobView job;
private final HeadlineConfig config;
public HeadlineOfFixed(JobView job, HeadlineConfig config) {
this.job = job;
this.config = config;
}
@Override
public boolean isApplicableTo(JobView job) {
return didTheJobJustGetFixedWith(job.lastCompletedBuild());
}
@Override
public Headline asJson() {
return new Headline(textFor(job.lastCompletedBuild()));
}
private String textFor(BuildViewModel lastBuild) {
return Lister.describe(
"Back in the green!",
"Fixed after %s committed their changes :-)",
new LinkedList<>(committersOf(lastBuild)));
}
private boolean didTheJobJustGetFixedWith(BuildViewModel build) {
return Result.SUCCESS.equals(build.result()) && previousFailed(build);
}
private boolean previousFailed(BuildViewModel build) {
return build.hasPreviousBuild()
&& (Result.FAILURE.equals(build.previousBuild().result())
|| Result.UNSTABLE.equals(build.previousBuild().result())
|| Result.ABORTED.equals(build.previousBuild().result()));
}
private Set<String> committersOf(BuildViewModel build) {
return config.displayCommitters ? build.committers() : new HashSet<>();
}
}
| true |
9664215729cabc0438c233146e0a2ce6cbdd919d | Java | terry-flander/ShutterBug | /ShutterBug/src/au/com/fundfoto/shutterbug/entities/OrderPaymentService.java | UTF-8 | 4,566 | 2.421875 | 2 | [] | no_license | package au.com.fundfoto.shutterbug.entities;
import java.sql.*;
import java.util.Vector;
import au.com.fundfoto.shutterbug.util.DbUtil;
import org.apache.log4j.*;
public class OrderPaymentService {
static Logger logger = Logger.getLogger("OrderPaymentService");
public OrderPaymentService() {
}
public OrderPayment getOrderPayment (long PaymentID) {
OrderPayment result = null;
Connection con = null;
if (PaymentID!=0) {
try {
con = DbUtil.getConnection();
String sql =
"SELECT OrderID, PaymentID, PaymentDate, Type, Amount, Note " +
" FROM OrderPayment " +
" WHERE PaymentID=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setLong(1,PaymentID);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
if (result==null) {
result = createOrderPayment(rs);
}
}
rs.close();
ps.close();
} catch (Exception e) {
logger.error("getOrderPayment() Error: " + e.getMessage());
} finally {
DbUtil.freeConnection(con);
}
}
return (result==null?new OrderPayment():result);
}
public boolean saveOrderPayment(OrderPayment op) {
boolean result = false;
Connection con = null;
try {
boolean insertLine = op.getPaymentID()==0;
String sql = null;
if (insertLine) {
sql = "INSERT INTO OrderPayment (PaymentDate, Type, Amount, Note, OrderID) VALUES (?,?,?,?,?)";
} else {
sql = "UPDATE OrderPayment SET PaymentDate=?,Type=?,Amount=?,Note=? WHERE PaymentID=?";
}
con = DbUtil.getConnection();
PreparedStatement ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
ps.setDate(1,op.getdPaymentDate());
ps.setString(2,op.getType());
ps.setDouble(3,op.getdAmount());
ps.setString(4,op.getNote());
if (!insertLine) {
ps.setLong(5,op.getPaymentID());
} else {
ps.setLong(5,op.getOrderID());
}
ps.executeUpdate();
if (op.getPaymentID()==0) {
long PaymentID = DbUtil.getGeneratedKey(ps);
op.setPaymentID(PaymentID);
}
ps.close();
result = true;
} catch (Exception e) {
logger.warn("saveOrderPayment() Could not update: "+e.getMessage());
result = false;
} finally {
DbUtil.freeConnection(con);
}
if (result) {
new OrderService().retotalOrder(op.getOrderID());
}
return result;
}
public boolean deleteOrderPayment(OrderPayment ol) {
boolean result = false;
Connection con = null;
try {
con = DbUtil.getConnection();
String sql = "DELETE FROM OrderPayment WHERE PaymentID=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setLong(1,ol.getPaymentID());
ps.executeUpdate();
ps.close();
result = true;
} catch (Exception e) {
logger.warn("deleteOrderPayment() Could not delete: "+e.getMessage());
result = false;
} finally {
DbUtil.freeConnection(con);
}
if (result) {
new OrderService().retotalOrder(ol.getOrderID());
}
return result;
}
public OrderPayment[] getOrderPaymentList(long OrderID) {
Vector<OrderPayment> result = new Vector<OrderPayment>();
Connection con = null;
try {
String sql = "SELECT OrderID, PaymentID, PaymentDate, Type, Amount, Note FROM OrderPayment WHERE OrderID=? ORDER BY PaymentID";
con = DbUtil.getConnection();
PreparedStatement ps = con.prepareStatement(sql);
ps.setLong(1,OrderID);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
result.add(createOrderPayment(rs));
}
ps.close();
} catch (Exception e) {
logger.warn("getOrderPaymentList() Could not update: "+e.getMessage());
logger.error("getOrderPaymentList() Could not update",e);
} finally {
DbUtil.freeConnection(con);
}
return (OrderPayment[])result.toArray(new OrderPayment[result.size()]);
}
private OrderPayment createOrderPayment(ResultSet rs) {
OrderPayment result = new OrderPayment();
try {
result.setPaymentID(rs.getLong("PaymentID"));
result.setOrderID(rs.getLong("OrderID"));
result.setdPaymentDate(rs.getDate("PaymentDate"));
result.setType(rs.getString("Type"));
result.setNote(rs.getString("Note"));
result.setdAmount(rs.getDouble("Amount"));
} catch (Exception e) {
logger.warn("createOrderPayment() Could not create: "+e.getMessage());
}
return result;
}
}
| true |
7dcf5b017b977462d621062954a1f91bca59eda8 | Java | Suprajass/29-9-16 | /Anoth.java | UTF-8 | 200 | 2.71875 | 3 | [] | no_license | public class Anoth{
String s1,s2;
public String embedWord(String s1,String s2)
{
int n=s1.length();
String s3=s1.substring(0,(n/2))+s2+s1.substring((n/2));
return s3;
}
}
| true |
22f81acac41cd51ba484e62b0da58ebdf44a1fce | Java | ITSE-HNU/MPG-Back | /src/main/java/com/ghstudio/pairprogram/service/entity/LoginResponseBody.java | UTF-8 | 322 | 1.882813 | 2 | [] | no_license | package com.ghstudio.pairprogram.service.entity;
import lombok.Builder;
import lombok.Data;
/**
* LoginResponseBody 登陆请求返回体定义: token id username role
*/
@Data
@Builder
public class LoginResponseBody {
private String token;
private int id;
private String username;
private int role;
}
| true |
569facb0d0172304753cb53227c53f8dc7708c1f | Java | parikshitks/MyRepository | /src/test/java/testing/MinCostClimbingStair.java | UTF-8 | 658 | 3.5625 | 4 | [] | no_license | package testing;
public class MinCostClimbingStair {
//Doesn't work for all scenarios currently, the logic is not correct
public static void main(String[] args) {
int a[] = { 1,100,1,1,1,100,1,1,100,1 };
int n = a.length;
System.out.println(minimumCost(n-2,a));
}
// function to find minimum cost
public static int minimumCost(int n, int cost[]){
if(n == 0) return cost[0] ;
if(n == 1) return cost[1] ;
//System.out.println(minimumCost(n-1,cost) + cost[n]);
//System.out.println(minimumCost(n-2, cost)+ cost[n]);
int top = Math.min( minimumCost(n-1,cost) + cost[n] ,
minimumCost(n-2, cost)+ cost[n] );
return top;
}
}
| true |
52c30af3adbd10f29da225021184f8c013765c6a | Java | skuldchen/Komica | /app/src/main/java/idv/kuma/komica/manager/MLocationManager.java | UTF-8 | 2,707 | 2.25 | 2 | [] | no_license | package idv.kuma.komica.manager;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.content.ContextCompat;
import com.google.android.gms.location.LocationListener;
/**
* Created by TakumaLee on 15/2/24.
*/
public class MLocationManager implements LocationListener {
private static final String TAG = MLocationManager.class.getSimpleName();
// private LocationManager locationManager;
private Location location;
private static MLocationManager instance = null;
public static void initSingleton(Context context) {
if (null == instance)
instance = new MLocationManager(context.getApplicationContext());
}
public MLocationManager(Context context) {
// if ( ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
//
// ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
// LocationService.MY_PERMISSION_ACCESS_COURSE_LOCATION);
// }
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(@NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
public static MLocationManager getInstance() {
return instance;
}
public double getLatitude() {
if (location == null)
return 0;
return location.getLatitude();
}
public double getLongititude() {
if (location == null)
return 0;
return location.getLongitude();
}
@Override
public void onLocationChanged(Location location) {
}
}
| true |
817a8809caf5af504ed8b43f83287543367b2776 | Java | chubock/test-center-backend | /src/main/java/com/ztc/testcenter/gre/domain/question/InnerQuestion.java | UTF-8 | 194 | 1.84375 | 2 | [] | no_license | package com.ztc.testcenter.gre.domain.question;
/**
* Created by Yubar on 3/16/2017.
*/
public interface InnerQuestion<T extends Question> {
Integer getNumber();
T getParent();
}
| true |
d7cd7ffd73e3c2c27930214f9229b1cef67c94f5 | Java | javadev/LeetCode-in-Java | /src/main/java/g2201_2300/s2296_design_a_text_editor/TextEditor.java | UTF-8 | 1,322 | 3.46875 | 3 | [
"MIT"
] | permissive | package g2201_2300.s2296_design_a_text_editor;
// #Hard #String #Stack #Design #Simulation #Linked_List #Doubly_Linked_List
// #2022_06_17_Time_238_ms_(87.02%)_Space_57.6_MB_(93.83%)
public class TextEditor {
private final StringBuilder sb;
private int cursor;
public TextEditor() {
sb = new StringBuilder();
cursor = 0;
}
public void addText(String text) {
sb.insert(cursor, text);
cursor += text.length();
}
public int deleteText(int k) {
int prevPos = cursor;
if (cursor - k >= 0) {
cursor -= k;
sb.delete(cursor, cursor + k);
} else {
sb.delete(0, cursor);
cursor = 0;
}
return prevPos - cursor;
}
public String cursorLeft(int k) {
cursor = Math.max(cursor - k, 0);
return sb.substring(Math.max(cursor - 10, 0), cursor);
}
public String cursorRight(int k) {
cursor = Math.min(cursor + k, sb.length());
return sb.substring(Math.max(cursor - 10, 0), cursor);
}
}
/*
* Your TextEditor object will be instantiated and called as such:
* TextEditor obj = new TextEditor();
* obj.addText(text);
* int param_2 = obj.deleteText(k);
* String param_3 = obj.cursorLeft(k);
* String param_4 = obj.cursorRight(k);
*/
| true |
16ea7fead05c993c246257bb8a86d0ef284b4b93 | Java | denysos/java-poo-j9-j10 | /src/main/java/fr/diginamic/annotations/Rule.java | UTF-8 | 944 | 2.984375 | 3 | [] | no_license | package fr.diginamic.annotations;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Annotation à poser sur un attribut d'instance de classe et qui permet
* d'indiquer des contraintes sur la valeur de cet attribut.<br>
* <br>
* Cette annotation est prise en compte par la classe Validator. <br>
* <br>
* Exemples de contraintes sur un attribut de type nombre:<br>
* min=0,<br>
* max=10000,<br>
*
* @author RichardBONNAMY
*
*/
@Retention(RUNTIME)
@Target(ElementType.FIELD)
public @interface Rule {
/**
* Permet d'indiquer une valeur minimum pour un attribut de type nombre
*
* @return double
*/
double min() default Double.MIN_VALUE;
/**
* Permet d'indiquer une valeur maximum pour un attribut de type nombre
*
* @return double
*/
double max() default Double.MAX_VALUE;
}
| true |
82f5ff2d5505ad4b4b1d9b7cf5e8f1c2687a8fbb | Java | GlowKitty/meow-bot | /src/meow-bot/Factoids.java | UTF-8 | 988 | 2.96875 | 3 | [] | no_license | package org.meowbot;
import java.util.*;
import java.io.*;
public class Factoids implements Serializable{
String topic;
ArrayList facts = new ArrayList();
public Factoids(){}
public Factoids(String topic, String newFact){
this.topic = topic;
//this.facts = new ArrayList();
this.facts.add((String) newFact);
}
public void setTopic(String topic){
this.topic = topic;
}
public void newFactoid(String newFact){
this.facts.add(newFact);
}
public void rmFactoid(int factNum){
this.facts.remove(factNum);
}
public String viewFactoids(){
String toReturn = this.topic + " is ";
if (this.facts.size() == 1){
toReturn = toReturn + this.facts.get(0);
}
else if (this.facts.size() == 0){
return "No factoids for " + topic;
}
else{
for (int i = 0; i < this.facts.size(); i++){
int iTemp = i + 1;
toReturn = toReturn + "(#" + iTemp + ") " + this.facts.get(i) + " ";
}
}
return toReturn;
}
public String getTopic(){
return this.topic;
}
} | true |
23500a3925394c3202b08954f342ef8ce34e3483 | Java | t0HiiBwn/CoolapkRelease | /sources/com/xiaomi/push/je.java | UTF-8 | 553 | 2.140625 | 2 | [] | no_license | package com.xiaomi.push;
import android.content.Context;
import java.io.File;
final class je extends jd {
final /* synthetic */ Runnable a;
/* JADX INFO: super call moved to the top of the method (can break code semantics) */
je(Context context, File file, Runnable runnable) {
super(context, file, null);
this.a = runnable;
}
@Override // com.xiaomi.push.jd
protected void a(Context context) {
Runnable runnable = this.a;
if (runnable != null) {
runnable.run();
}
}
}
| true |
2e03657bd4b727ea236d4e5618c1813dcba110ac | Java | mashkarharis/Management-System-For-Supermarket | /src/abc/sup/wfx/controller/CUSTOMERPRINTController.java | UTF-8 | 3,493 | 2.0625 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package abc.sup.wfx.controller;
import abc.sup.bo.BOFactory;
import abc.sup.bo.SuperBO;
import abc.sup.dto.customerDTO;
import com.jfoenix.controls.JFXButton;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
/**
* FXML Controller class
*
* @author U s E r ™
*/
public class CUSTOMERPRINTController implements Initializable {
@FXML
private TextField cregno;
@FXML
private TextField cname;
@FXML
private TextField caddress;
@FXML
private TextField ctel;
@FXML
private TextField cemail;
@FXML
private TextField cpoints;
@FXML
private TextField cdate;
@FXML
private JFXButton S5PRINT;
@FXML
private ComboBox<String> ccid;
SuperBO supbo;
@FXML
void SPRINT(ActionEvent event) {
customerDTO customer=new customerDTO(ccid.getValue(),cdate.getText().toString(),cregno.getText().toString(),cname.getText().toString(),caddress.getText().toString(),cemail.getText().toString(),Integer.parseInt(ctel.getText().toString()),Double.parseDouble(cpoints.getText().toString()));
supbo.print(customer);
}
@FXML
void SELECT(ActionEvent event) throws Exception {
ArrayList<customerDTO> getdto=supbo.getAll();
for (customerDTO c:getdto) {
if (c.getCid().endsWith(ccid.getValue())){
caddress.setText(c.getAddress());
cdate.setText(c.getMembershipdate());
cemail.setText(c.getEmail());
cname.setText(c.getName());
cpoints.setText(c.getPoints()+"");
cregno.setText(c.getRegno());
ctel.setText(c.getTele()+"");
}
}
}
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
try {
supbo=BOFactory.getInstance().getBO(BOFactory.BOTypes.CUSTOMERS);
// Weekdays
ArrayList<String> getcid=supbo.getAllCID();
ArrayList<customerDTO> getdto=supbo.getAll();
ccid.setItems(FXCollections.observableArrayList(getcid));
ccid.getSelectionModel().selectFirst();
for (customerDTO c:getdto) {
if (c.getCid().endsWith(ccid.getValue())){
caddress.setText(c.getAddress());
cdate.setText(c.getMembershipdate());
cemail.setText(c.getEmail());
cname.setText(c.getName());
cpoints.setText(c.getPoints()+"");
cregno.setText(c.getRegno());
ctel.setText(c.getTele()+"");
}
}
} catch (Exception ex) {
Logger.getLogger(CUSTOMEREDITController.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO
}
}
| true |
ec0fc8604047f48508a51130cf56f805b542813b | Java | annaoomph/TasksTestApplication | /app/src/main/java/com/example/annakocheshkova/testapplication/client/BaseHttpClient.java | UTF-8 | 847 | 2.625 | 3 | [] | no_license | package com.example.annakocheshkova.testapplication.client;
import okhttp3.Callback;
import okhttp3.MediaType;
/**
* A basic interface for http clients
*/
public interface BaseHttpClient {
/**
* Content media type
*/
MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
/**
* Makes a get-request
* @param url url to make request to
* @param callback a callback for responding to client events
*/
void doGetRequest(String url, Callback callback);
/**
* Makes a post-request
* @param url url to make request to
* @param data data to be sent
* @param mediaType type of the content
* @param callback a callback for responding to client events
*/
void doPostRequest(String url, String data, MediaType mediaType, Callback callback);
}
| true |
afb2fa2c103b24b72f209da8f0a02221ef289feb | Java | bigwater/ip7502 | /IPWorkshopUpg/src/hk/hku/cs/comp7502/config/Configuration.java | UTF-8 | 470 | 2.796875 | 3 | [] | no_license | package hk.hku.cs.comp7502.config;
import java.util.HashMap;
import java.util.Map;
public class Configuration {
private Map<String, Object> configMap = new HashMap<String, Object> ();
public Object getConfig(String name) {
if (name == null || !configMap.containsKey(name)) {
throw new RuntimeException("config not exist");
}
return configMap.get(name);
}
public void setConfig(String name, Object config) {
configMap.put(name, config);
}
}
| true |
48c0a61b1b1fbc364fb7d4260f3d44953b5987a2 | Java | tjdwns3710/BigData_JobLink | /java/workspace/Day0628/src/kdata/anonymous/Movable.java | UHC | 275 | 2.4375 | 2 | [] | no_license | package kdata.anonymous;
public interface Movable {
void move();
}
//movable move Ҷ
//1.unitŬ typecasttestó ȯ ؾϴ
//2.anonymoustestó ؼ move Ҽ ִ | true |
3622bdc425e521a24a07aac40a1af6994f693c25 | Java | mquasten/iot | /iot.batch/src/test/java/de/mq/iot/resource/support/TestResourceIdentifier.java | UTF-8 | 857 | 2.25 | 2 | [] | no_license | package de.mq.iot.resource.support;
import java.util.HashMap;
import java.util.Map;
import de.mq.iot.resource.ResourceIdentifier;
import de.mq.iot.resource.ResourceIdentifier.ResourceType;
public interface TestResourceIdentifier {
static final String HOST_KEY = "host";
static final String HOST_VALUE = "192.168.2.102";
static final String PORT_KEY = "port";
static final String PORT_VALUE = "80";
static final String URI = "http://{host}:{port}/addons/xmlapi/{resource}";
public static ResourceIdentifier resourceIdentifier() {
final ResourceIdentifier result = new ResourceIdentifierImpl(ResourceType.XmlApi,URI);
final Map<String,String> parameters = new HashMap<>();
parameters.put(HOST_KEY, HOST_VALUE);
parameters.put(PORT_KEY, PORT_VALUE);
result.assign(parameters);
return result;
}
}
| true |
2b82a3b543c7527f5e53ee9ba674906db55602a6 | Java | misalen/MisalenSpring | /misalen-spring-parent/misalen-spring-web/src/main/java/org/misalen/common/thymeleaf/dt/DtDialect.java | UTF-8 | 1,140 | 2.1875 | 2 | [] | no_license | package org.misalen.common.thymeleaf.dt;
import java.util.LinkedHashSet;
import java.util.Set;
import org.springframework.stereotype.Component;
import org.thymeleaf.dialect.AbstractProcessorDialect;
import org.thymeleaf.processor.IProcessor;
import org.thymeleaf.standard.StandardDialect;
import org.thymeleaf.standard.processor.StandardXmlNsTagProcessor;
import org.thymeleaf.templatemode.TemplateMode;
@Component
public class DtDialect extends AbstractProcessorDialect {
private static final String NAME = "dictionary-table";
private static final String PREFIX = "dt";
public DtDialect() {
super(NAME, PREFIX, StandardDialect.PROCESSOR_PRECEDENCE);
}
@Override
public Set<IProcessor> getProcessors(String dialectPrefix) {
return createStandardProcessorsSet(dialectPrefix);
}
private Set<IProcessor> createStandardProcessorsSet(String dialectPrefix) {
LinkedHashSet<IProcessor> processors = new LinkedHashSet<IProcessor>();
processors.add(new DtProcessor(dialectPrefix));
processors.add(new StandardXmlNsTagProcessor(TemplateMode.HTML, dialectPrefix));
return processors;
}
}
| true |
98b4ca0e7f11b02fd57dbb7795525379e2496fe3 | Java | emothion/VoteSysWeb | /src/com/votesys/tools/ExportInExcelUtil.java | UTF-8 | 2,875 | 2.796875 | 3 | [] | no_license | package com.votesys.tools;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class ExportInExcelUtil {
/**
* @Function com.votesys.tools.ExportInExcelUtil::readWriter
* @Description 读入Excel模板并写入数据
* @param templatePath
* @param topicID
* @param params
* 数据库获取的数据
* @return
* @throws WriteException
*/
public static boolean readWriter(String templatePath, String topicID, List<String[]> params) throws WriteException {
WritableWorkbook wwb = null;
WritableSheet wws = null;
FileOutputStream out = null;
jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#0");// 设置数字类型的格式
jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf);// 设置表单格式
wcfN.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN, jxl.format.Colour.BLACK);// 设置单元格全边框,实线,黑色
// 获取要读取的EXCEL表格模板
File is = new File(templatePath + File.separator + "ExcelTemplate.xls");
String filename = templatePath + "\\export-excel\\";
// 写入到新的表格里
File f = new File(filename, topicID + ".xls");
try {
// 创建新文件
f.createNewFile();
out = new FileOutputStream(f);
// 获取工作簿对象
Workbook wb = Workbook.getWorkbook(is);
// 创建可写入的工作簿对象
wwb = Workbook.createWorkbook(out, wb);
// 根据工作表名获取WritableSheet对象
wws = wwb.getSheet("Vote");
Label label = null;
int num = 0;
for (int i = 0; i < params.size(); i++) {
num = num + Integer.parseInt(params.get(i)[2]);
}
for (int i = 1; i <= params.size(); i++) {
for (int j = 0; j < 4; j++) {
// 创建label对象设置value值j相当于是X轴I是Y轴位置
if (j == 1) {
label = new Label(j, i, params.get(i - 1)[j], wcfN);// 插入文本类型
wws.addCell(label);// 添加到工作薄中
} else if(j == 2) {
jxl.write.Number labelNF = new Number(j, i, Double.valueOf(params.get(i - 1)[j]), wcfN);// 插入数字类型
wws.addCell(labelNF);
}
if (j==3) {
double part = (Double.parseDouble(params.get(i - 1)[j-1])/num)*100;
label = new Label(j, i, part+"%", wcfN);// 插入文本类型
wws.addCell(label);
}
}
}
// 将新建立的工作薄写入到磁盘
wwb.write();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
// 关闭流
try {
wwb.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} | true |
ec68ac04b5a133660d24a51ad927d59cee55e561 | Java | wausrotas/ITI1121-Assignments | /Jeopardy Game/src/Question.java | UTF-8 | 524 | 2.828125 | 3 | [] | no_license | /**
* @author Willie Ausrotas, Brian Lee
* Student Numbers: 7804922, 7938501
* Assignment Number: 2
* Section: ITI1121 - A
*/
public class Question {
private String question;
private String response;
/**
*
* @param question
* @param response
*/
public Question(String question, String response)
{
this.question = question;
this.response = response;
}
/**
*
* @return
*/
String getQuestion()
{
return this.question;
}
/**
*
* @return
*/
String getResponse()
{
return this.response;
}
}
| true |
736ec1349229c79a065898edc326e74b53d627cb | Java | aggressivepixels/ApkExtractor | /app/src/main/java/com/apkextractor/android/about/adapters/ContributionsAdapter.java | UTF-8 | 3,058 | 2.734375 | 3 | [
"MIT"
] | permissive | package com.apkextractor.android.about.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.apkextractor.android.R;
import com.apkextractor.android.about.models.Contribution;
import com.apkextractor.android.about.viewholders.ContributionViewHolder;
import com.apkextractor.android.about.viewholders.HeaderViewHolder;
import com.apkextractor.android.common.itemdecorations.SimpleDividerItemDecoration;
import java.util.List;
/**
* {@link android.support.v7.widget.RecyclerView.Adapter RecyclerView.Adapter} that shows a list of {@link Contribution Contributions}.
* It also shows some information about the app as a header.
*
* @author Jonathan Hernández
*/
public class ContributionsAdapter extends RecyclerView.Adapter implements SimpleDividerItemDecoration.DividerAdapter {
//View types of this Adapter.
private static final int VIEW_TYPE_HEADER = 0;
private static final int VIEW_TYPE_CONTRIBUTION = 1;
private List<Contribution> contributions;
private LayoutInflater inflater;
public ContributionsAdapter(Context context, List<Contribution> contributions) {
this.contributions = contributions;
inflater = LayoutInflater.from(context);
}
/**
* {@inheritDoc}
*/
@Override
public int getItemViewType(int position) {
if (position == 0) {
return VIEW_TYPE_HEADER;
}
return VIEW_TYPE_CONTRIBUTION;
}
/**
* {@inheritDoc}
*/
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case VIEW_TYPE_HEADER:
return new HeaderViewHolder(
inflater.inflate(
R.layout.about_header,
parent,
false));
case VIEW_TYPE_CONTRIBUTION:
return new ContributionViewHolder(
inflater.inflate(
R.layout.item_contribution,
parent,
false));
default:
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (getItemViewType(position) == VIEW_TYPE_CONTRIBUTION) {
((ContributionViewHolder) holder).setContribution(contributions.get(position - 1));
}
}
/**
* {@inheritDoc}
*/
@Override
public int getItemCount() {
//We add one to make space for the header.
return contributions.size() + 1;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDividerEnabledForItem(int position) {
//This way the divider doesn't shows up for the first (header)
//and last items.
return position > 0 && position < getItemCount() - 1;
}
}
| true |
daf64cf016e6e657ff079f65803e77753201833b | Java | suchaoxiao/ttc2017smartGrids | /solutions/ModelJoin/src/main/java/COSEM/COSEMObjects/impl/ScheduleObjectImpl.java | UTF-8 | 794 | 1.8125 | 2 | [
"MIT"
] | permissive | /**
*/
package COSEM.COSEMObjects.impl;
import COSEM.COSEMObjects.COSEMObjectsPackage;
import COSEM.COSEMObjects.ScheduleObject;
import COSEM.InterfaceClasses.impl.ScheduleImpl;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Schedule Object</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class ScheduleObjectImpl extends ScheduleImpl implements ScheduleObject {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ScheduleObjectImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return COSEMObjectsPackage.eINSTANCE.getScheduleObject();
}
} //ScheduleObjectImpl
| true |
7f13d122d3e56db64460f0a75ded39db81afbb12 | Java | cowbi/sparrow | /design-pattern/src/main/java/decorator/AbstractDecorator.java | UTF-8 | 412 | 2.734375 | 3 | [] | no_license | package decorator;
/**
* 装饰者 装饰core
*
* @author zhaoyancheng
* @date 2021-05-23 15:16
**/
public class AbstractDecorator extends AbstractCore {
private AbstractCore core;
public AbstractDecorator(AbstractCore core) {
this.core = core;
}
@Override
void report() {
this.core.report();
}
@Override
void sign() {
this.core.sign();
}
}
| true |
aa2287f6b46d3d58875ef8a61f036d254ec777d3 | Java | erykskn/design-pattern | /src/com/ery/behavioral/observer/SubscriberTwo.java | UTF-8 | 225 | 2.75 | 3 | [] | no_license | package com.ery.behavioral.observer;
public class SubscriberTwo implements Observer{
@Override
public void update(Message m) {
System.out.println("Subscriber Two, message: " + m.getMessageContent());
}
}
| true |
2f7d14c032e6f843deece8fff71833d9c5e57fdb | Java | fredoxia/qx-barcodes | /QXBaby-MIS/src/com/onlineMIS/ORM/entity/chainS/sales/ChainStoreSalesOrderProduct.java | UTF-8 | 2,742 | 2.09375 | 2 | [] | no_license | package com.onlineMIS.ORM.entity.chainS.sales;
import java.io.Serializable;
import com.onlineMIS.ORM.entity.base.BaseProduct;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Product;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.ProductBarcode;
public class ChainStoreSalesOrderProduct extends BaseProduct implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2014155412210076945L;
/**
* for both sale-out product the type is 0
*/
public static final int SALES_OUT = 1;
/**
* for the return-back product is 2
*/
public static final int RETURN_BACK = 2;
/**
* for the 赠品
*/
public static final int FREE = 3;
private int id;
private int type;
private ChainStoreSalesOrder chainSalesOrder;
private ProductBarcode productBarcode = new ProductBarcode();
private String memo;
private double costPrice;
private double retailPrice;
private double discountRate = 1;
private int quantity;
/**
* the product inventory level by calculation
*/
private int inventoryLevel;
private int normalSale;
public int getNormalSale() {
return normalSale;
}
public void setNormalSale(int normalSale) {
this.normalSale = normalSale;
}
public int getInventoryLevel() {
return inventoryLevel;
}
public void setInventoryLevel(int inventoryLevel) {
this.inventoryLevel = inventoryLevel;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ChainStoreSalesOrder getChainSalesOrder() {
return chainSalesOrder;
}
public void setChainSalesOrder(ChainStoreSalesOrder chainSalesOrder) {
this.chainSalesOrder = chainSalesOrder;
}
public ProductBarcode getProductBarcode() {
return productBarcode;
}
public void setProductBarcode(ProductBarcode productBarcode) {
this.productBarcode = productBarcode;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public double getRetailPrice() {
return retailPrice;
}
public void setRetailPrice(double retailPrice) {
this.retailPrice = retailPrice;
}
public double getDiscountRate() {
return discountRate;
}
public void setDiscountRate(double discountRate) {
this.discountRate = discountRate;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getCostPrice() {
return costPrice;
}
public void setCostPrice(double costPrice) {
this.costPrice = costPrice;
}
}
| true |
a2c71f1fe6670c14f830bb2e10b7103366b528b5 | Java | dportnov75/example | /example/src/main/java/ru/abcd/example/interactor/departmentdirector/controller/DirectorOfDepartmentGraphQlQueryHandler.java | UTF-8 | 1,206 | 2.5 | 2 | [] | no_license | package ru.abcd.example.interactor.departmentdirector.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.coxautodev.graphql.tools.GraphQLQueryResolver;
import ru.abcd.example.interactor.School;
import ru.abcd.example.interactor.departmentdirector.DirectorOfDepartment;
/**
* Пример сервиса обрабатывающего запросы GraphQL<br>
* Вызвать <a href="http://localhost:9999/example/graphiql"> GraphiQl</a>
* <p>
* Выполнить - {@code {
findByNumber(number: 2) {
number
phones }
}
}
* </p>
* <p>
* Файл с описанием и привязкой находится в {@code /resources/school.graphsqls}
*
* @author dmitry
*
*/
@Service
public class DirectorOfDepartmentGraphQlQueryHandler implements GraphQLQueryResolver {
@Autowired
private DirectorOfDepartment service;
/**
* Пример обработчика запроса для GraphQL
*
* @param number Номер
* @param name Имя
* @return Школа
*/
public School findByNumber(int number) {
return service.findByNumber(number).orElse(null);
}
}
| true |
a8c0b614651b88772cac8b6d96665dc71a91a6c9 | Java | bellmit/sjzerp | /sjzerp/src/com/qxh/service/DemandSummService.java | UTF-8 | 769 | 1.789063 | 2 | [] | no_license | package com.qxh.service;
import com.qxh.utils.Result;
public interface DemandSummService {
/**
* 查询销售汇总
* @param stime
* @param etime
* @param customerId
* @param goodsNm
* @param kindCode
* @return
*/
Result getDemandSummary(String stime, String etime,int structId, String customerId,String goodsNm
,String kindCode);
/**
* @description : [根据物料查询销售汇总]
* @param goodsId
* @param goodsType
* @param stime
* @param etime
* @param structId
* @param demandListDId
* @param customerId
* @return
* @时间:2016年12月8日下午7:33:26
*/
Result getDemandSummByGoods(String goodsId, String goodsType, String stime, String etime, int structId,
String demandListDId, String customerId);
}
| true |
17793b170b1d934844ab5e3fe58fbce45d8160f0 | Java | searchisko/searchisko | /api/src/test/java/org/searchisko/persistence/service/JpaTestBase.java | UTF-8 | 1,869 | 1.898438 | 2 | [
"Apache-2.0"
] | permissive | /*
* JBoss, Home of Professional Open Source
* Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
*/
package org.searchisko.persistence.service;
import java.sql.Connection;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.hibernate.Session;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.searchisko.api.testtools.ESRealClientTestBase;
/**
* Unit test for {@link JpaEntityService}
*
* @author Vlastimil Elias (velias at redhat dot com)
*/
public class JpaTestBase extends ESRealClientTestBase {
protected Logger logger = Logger.getLogger(JpaTestBase.class.getName());
protected EntityManagerFactory emFactory;
protected EntityManager em;
protected Connection connection;
public DriverManagerConnectionProviderImpl getConnectionProvider() {
SessionFactoryImpl factory = (SessionFactoryImpl) em.unwrap(Session.class).getSessionFactory();
return (DriverManagerConnectionProviderImpl) factory.getConnectionProvider();
}
@Before
public void setUp() throws Exception {
try {
logger.info("Building JPA EntityManager for unit tests");
emFactory = Persistence.createEntityManagerFactory("testPU");
em = emFactory.createEntityManager();
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail("Exception during JPA EntityManager initialization.");
}
}
@After
public void tearDown() throws Exception {
logger.info("Shutting down Hibernate JPA layer.");
if (em != null) {
em.close();
}
if (emFactory != null) {
emFactory.close();
}
}
}
| true |
4ca2ddf6951041776a8b4b981fb4999173d31488 | Java | serivesmejia/EOCV-Sim | /EOCV-Sim/src/main/java/com/github/serivesmejia/eocvsim/input/source/VideoSource.java | UTF-8 | 6,093 | 2.0625 | 2 | [
"MIT"
] | permissive | /*
* Copyright (c) 2021 Sebastian Erives
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.github.serivesmejia.eocvsim.input.source;
import com.github.serivesmejia.eocvsim.gui.Visualizer;
import com.github.serivesmejia.eocvsim.input.InputSource;
import com.github.serivesmejia.eocvsim.util.FileFilters;
import com.github.serivesmejia.eocvsim.util.Log;
import com.google.gson.annotations.Expose;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.Videoio;
import org.openftc.easyopencv.MatRecycler;
import javax.swing.filechooser.FileFilter;
import java.util.Objects;
public class VideoSource extends InputSource {
@Expose
private final String videoPath;
private transient VideoCapture video = null;
private transient MatRecycler.RecyclableMat lastFramePaused = null;
private transient MatRecycler.RecyclableMat lastFrame = null;
private transient boolean initialized = false;
@Expose
private volatile Size size;
private volatile transient MatRecycler matRecycler = null;
private transient double lastFramePosition = 0;
public VideoSource(String videoPath, Size size) {
this.videoPath = videoPath;
this.size = size;
}
@Override
public boolean init() {
if (initialized) return false;
initialized = true;
video = new VideoCapture();
video.open(videoPath);
if (!video.isOpened()) {
Log.error("VideoSource", "Unable to open video " + videoPath);
return false;
}
if (matRecycler == null) matRecycler = new MatRecycler(4);
MatRecycler.RecyclableMat newFrame = matRecycler.takeMat();
newFrame.release();
video.read(newFrame);
if (newFrame.empty()) {
Log.error("VideoSource", "Unable to open video " + videoPath + ", returned Mat was empty.");
return false;
}
newFrame.release();
matRecycler.returnMat(newFrame);
return true;
}
@Override
public void reset() {
if (!initialized) return;
if (video != null && video.isOpened()) video.release();
if(lastFrame != null && lastFrame.isCheckedOut())
lastFrame.returnMat();
if(lastFramePaused != null && lastFramePaused.isCheckedOut())
lastFramePaused.returnMat();
matRecycler.releaseAll();
video = null;
initialized = false;
}
@Override
public void close() {
if(video != null && video.isOpened()) video.release();
if(lastFrame != null) lastFrame.returnMat();
if (lastFramePaused != null) {
lastFramePaused.returnMat();
lastFramePaused = null;
}
}
@Override
public Mat update() {
if (isPaused) {
return lastFramePaused;
} else if (lastFramePaused != null) {
lastFramePaused.returnMat();
lastFramePaused = null;
}
if (lastFrame == null) lastFrame = matRecycler.takeMat();
if (video == null) return lastFrame;
MatRecycler.RecyclableMat newFrame = matRecycler.takeMat();
video.read(newFrame);
//with videocapture for video files, when an empty mat is returned
//the most likely reason is that the video ended, so we set the
//playback position back to 0 for looping in here and start over
//in next update
if (newFrame.empty()) {
newFrame.returnMat();
video.set(Videoio.CAP_PROP_POS_FRAMES, 0);
return lastFrame;
}
if (size == null) size = lastFrame.size();
Imgproc.cvtColor(newFrame, lastFrame, Imgproc.COLOR_BGR2RGB);
Imgproc.resize(lastFrame, lastFrame, size, 0.0, 0.0, Imgproc.INTER_AREA);
matRecycler.returnMat(newFrame);
return lastFrame;
}
@Override
public void onPause() {
if (lastFrame != null) lastFrame.release();
if (lastFramePaused == null) lastFramePaused = matRecycler.takeMat();
video.read(lastFramePaused);
Imgproc.cvtColor(lastFramePaused, lastFramePaused, Imgproc.COLOR_BGR2RGB);
Imgproc.resize(lastFramePaused, lastFramePaused, size, 0.0, 0.0, Imgproc.INTER_AREA);
update();
lastFramePosition = video.get(Videoio.CAP_PROP_POS_FRAMES);
video.release();
video = null;
}
@Override
public void onResume() {
video = new VideoCapture();
video.open(videoPath);
video.set(Videoio.CAP_PROP_POS_FRAMES, lastFramePosition);
}
@Override
protected InputSource internalCloneSource() {
return new VideoSource(videoPath, size);
}
@Override
public FileFilter getFileFilters() {
return FileFilters.videoMediaFilter;
}
@Override
public String toString() {
return "VideoSource(" + videoPath + ", " + (size != null ? size.toString() : "null") + ")";
}
} | true |
f70f64b893f44b29c3bbb85858b9082539831a3e | Java | a120476536/OtherToLogin | /src/com/qiao/bean/UserInfo.java | UTF-8 | 1,151 | 1.765625 | 2 | [] | no_license | package com.qiao.bean;
import cn.bmob.v3.BmobObject;
public class UserInfo extends BmobObject {
private String PlatformName;//平台名称
private String UserName;//用户名称
private String UserId;//用户id
private String UserIcon;//用户icon
private String UserPoints;//用户点数
private String Gender;//用户性别
public String getPlatformName() {
return PlatformName;
}
public void setPlatformName(String platformName) {
PlatformName = platformName;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getUserId() {
return UserId;
}
public void setUserId(String userId) {
UserId = userId;
}
public String getUserIcon() {
return UserIcon;
}
public void setUserIcon(String userIcon) {
UserIcon = userIcon;
}
public String getUserPoints() {
return UserPoints;
}
public void setUserPoints(String userPoints) {
UserPoints = userPoints;
}
public String getGender() {
return Gender;
}
public void setGender(String gender) {
Gender = gender;
}
}
| true |
a6737782d05dcc90d59e6a2444886b927179dc0b | Java | schandan696/Playing-With-Java-Ds-Algo | /1_Array/5_Search_in_SortedArray.java | UTF-8 | 695 | 3.5 | 4 | [] | no_license | class Search_in_SortedArray{
static int search(int arr[],int low,int high, int key)
{
if (high < low)
return -1;
int mid = (low + high)/2; /*low + (high - low)/2;*/
if (key == arr[mid])
return mid;
if (key > arr[mid])
return search(arr, (mid + 1), high, key);
return search(arr, low, (mid -1), key);
}
public static void main(String args[]){
int arr[] = {5,25,65,75,85,91,111,522};
int key =65;
System.out.println("Indes of "+key+" is : "+ search(arr,0,arr.length,key));
}
}; | true |
f90a2fba3ff2354bee9af2b48c0bf773aa805c72 | Java | pawelczak/solaris | /src/main/java/pl/pawelczak/solaris/webapp/admin/gallery/form/GalleryFormConverter.java | UTF-8 | 608 | 2.09375 | 2 | [] | no_license | package pl.pawelczak.solaris.webapp.admin.gallery.form;
import org.springframework.stereotype.Service;
import pl.pawelczak.solaris.persistence.model.Gallery;
@Service
public class GalleryFormConverter {
//------------------------ LOGIC --------------------------
public Gallery convert(GalleryForm galleryForm) {
//TODO galleryForm.getName not null
//introduce google predicate check
Gallery gallery = Gallery.getBuilder(galleryForm.getName())
.description(galleryForm.getDescription())
.visible(galleryForm.getVisible())
.build();
return gallery;
}
}
| true |
bb56d934a7f9a6219d1a9e302a348c0bb4fcf880 | Java | AlexandrKiss/klingar | /app/src/test/java/net/simno/klingar/playback/QueueManagerTest.java | UTF-8 | 7,596 | 2.171875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2017 Simon Norberg
*
* 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 net.simno.klingar.playback;
import net.simno.klingar.data.model.Track;
import net.simno.klingar.util.Pair;
import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import io.reactivex.subscribers.TestSubscriber;
import okhttp3.HttpUrl;
import static net.simno.klingar.playback.QueueManager.REPEAT_ALL;
import static net.simno.klingar.playback.QueueManager.REPEAT_OFF;
import static net.simno.klingar.playback.QueueManager.REPEAT_ONE;
import static net.simno.klingar.playback.QueueManager.SHUFFLE_ALL;
import static net.simno.klingar.playback.QueueManager.SHUFFLE_OFF;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class QueueManagerTest {
private QueueManager queueManager;
private List<Track> queue;
@Before public void setup() {
queueManager = new QueueManager(new Random(1337));
queue = Arrays.asList(
createTrack(100),
createTrack(200),
createTrack(300),
createTrack(400),
createTrack(500));
queueManager.setQueue(new ArrayList<>(queue), 1000);
}
@Test public void currentQueue() {
TestSubscriber<Pair<List<Track>, Integer>> test = queueManager.queue().take(1).test();
test.awaitTerminalEvent();
List<Track> actualQueue = test.values().get(0).first;
int actualPosition = test.values().get(0).second;
assertThat(actualQueue, IsIterableContainingInOrder.contains(
queue.get(0), queue.get(1), queue.get(2), queue.get(3), queue.get(4)));
assertThat(actualPosition, is(0));
}
@Test public void currentTrack() {
Track actualTrack = queueManager.currentTrack();
assertThat(actualTrack, is(queue.get(0)));
}
@Test public void setQueuePosition() {
queueManager.setQueuePosition(queue.get(3).queueItemId());
assertThat(queueManager.currentTrack(), is(queue.get(3)));
TestSubscriber<Pair<List<Track>, Integer>> test = queueManager.queue().take(1).test();
test.awaitTerminalEvent();
int actualPosition = test.values().get(0).second;
assertThat(actualPosition, is(3));
}
@Test public void setExistingTrack() {
queueManager.setCurrentTrack(queue.get(3));
assertThat(queueManager.currentTrack(), is(queue.get(3)));
}
@Test public void setNewTrack() {
Track expectedTrack = createTrack(20);
queueManager.setCurrentTrack(expectedTrack);
assertThat(queueManager.currentTrack(), is(expectedTrack));
}
@Test public void setNewQueueShouldSetShuffleOff() {
TestSubscriber<Pair<Integer, Integer>> test = queueManager.mode().take(3).test();
queueManager.shuffle();
queueManager.setQueue(new ArrayList<>(queue), 2000);
test.awaitTerminalEvent();
List<Pair<Integer, Integer>> modes = test.values();
assertThat(modes.get(0).first, is(SHUFFLE_OFF));
assertThat(modes.get(1).first, is(SHUFFLE_ALL));
assertThat(modes.get(2).first, is(SHUFFLE_OFF));
}
@Test public void shuffleModes() {
TestSubscriber<Pair<Integer, Integer>> test = queueManager.mode().take(3).test();
queueManager.shuffle();
queueManager.shuffle();
test.awaitTerminalEvent();
List<Pair<Integer, Integer>> modes = test.values();
assertThat(modes.get(0).first, is(SHUFFLE_OFF));
assertThat(modes.get(1).first, is(SHUFFLE_ALL));
assertThat(modes.get(2).first, is(SHUFFLE_OFF));
}
@Test public void repeatModes() {
TestSubscriber<Pair<Integer, Integer>> test = queueManager.mode().take(4).test();
queueManager.repeat();
queueManager.repeat();
queueManager.repeat();
test.awaitTerminalEvent();
List<Pair<Integer, Integer>> modes = test.values();
assertThat(modes.get(0).second, is(REPEAT_OFF));
assertThat(modes.get(1).second, is(REPEAT_ALL));
assertThat(modes.get(2).second, is(REPEAT_ONE));
assertThat(modes.get(3).second, is(REPEAT_OFF));
}
@Test public void shouldChangeQueueOrderOnShuffle() {
queueManager.shuffle();
TestSubscriber<Pair<List<Track>, Integer>> test = queueManager.queue().take(1).test();
test.awaitTerminalEvent();
List<Track> shuffledQueue = test.values().get(0).first;
assertThat(shuffledQueue, IsIterableContainingInOrder.contains(
queue.get(3), queue.get(4), queue.get(2), queue.get(0), queue.get(1)));
}
@Test public void shouldNotChangeCurrentTrackOnShuffle() {
Track exptectedTrack = queueManager.currentTrack();
queueManager.shuffle();
assertThat(queueManager.currentTrack(), is(exptectedTrack));
}
@Test public void skipToNextTrackNoRepeat() {
queueManager.next();
queueManager.next();
queueManager.next();
queueManager.next();
queueManager.next();
assertThat(queueManager.getRepeatMode(), is(REPEAT_OFF));
assertThat(queueManager.currentTrack(), is(queue.get(4)));
assertThat(queueManager.hasNext(), is(false));
}
@Test public void skipToNextTrackRepeatAll() {
queueManager.repeat();
queueManager.next();
queueManager.next();
queueManager.next();
queueManager.next();
queueManager.next();
assertThat(queueManager.getRepeatMode(), is(REPEAT_ALL));
assertThat(queueManager.currentTrack(), is(queue.get(0)));
assertThat(queueManager.hasNext(), is(true));
}
@Test public void skipToNextTrackRepeatOne() {
queueManager.repeat();
queueManager.repeat();
queueManager.next();
queueManager.next();
assertThat(queueManager.getRepeatMode(), is(REPEAT_ONE));
assertThat(queueManager.currentTrack(), is(queue.get(0)));
assertThat(queueManager.hasNext(), is(true));
}
@Test public void skipToPreviousTrackNoRepeat() {
queueManager.previous();
queueManager.previous();
assertThat(queueManager.getRepeatMode(), is(REPEAT_OFF));
assertThat(queueManager.currentTrack(), is(queue.get(0)));
}
@Test public void skipToPreviousTrackRepeatAll() {
queueManager.repeat();
queueManager.previous();
queueManager.previous();
assertThat(queueManager.getRepeatMode(), is(REPEAT_ALL));
assertThat(queueManager.currentTrack(), is(queue.get(3)));
}
@Test public void skipToPreviousTrackRepeatOne() {
queueManager.repeat();
queueManager.repeat();
queueManager.previous();
queueManager.previous();
assertThat(queueManager.getRepeatMode(), is(REPEAT_ONE));
assertThat(queueManager.currentTrack(), is(queue.get(0)));
}
private Track createTrack(int index) {
return Track.builder()
.queueItemId(index * 10)
.libraryId("libraryId")
.key("key")
.ratingKey("ratingKey")
.parentKey("parentKey")
.title("title")
.albumTitle("albumTitle")
.artistTitle("artistTitle")
.index(index)
.duration(30000)
.thumb("thumb")
.source("source")
.uri(HttpUrl.parse("https://plex.tv"))
.build();
}
}
| true |
1bca996c042f9fda72add2350f72e7bed7c96420 | Java | aceleradora-TW/biblioteca-rosa-aline | /src/main/java/com/aceleradora/biblioteca/Main.java | UTF-8 | 2,190 | 3.640625 | 4 | [] | no_license | package com.aceleradora.biblioteca;
import java.util.ArrayList;
public class Main {
public static ArrayList<Livros>ListaDeLivros = new ArrayList<>();
public static void main(String[] args) {
System.out.println("Bem vinda(o) à biblioteca, onde você encontra os melhores livros de Porto Alegre");
criarLivros();
imprimirListaDeLivros();
}
public static void criarLivros(){
Livros livros1 = new Livros("Barbara Liskov", "Program development in Java");
ListaDeLivros.add(livros1);
Livros livros2 = new Livros("Elisabeth Freeman, Kathy Sierra", "Use a Cabeça: Padrões de projet");
ListaDeLivros.add(livros2);
}
private static void imprimirListaDeLivros() {
System.out.println("Lista de Livros:");
for (Livros livro : ListaDeLivros) {
livro.obterInformacoes();
}
}
/*package com.biblioteca;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static ArrayList<Livro> listaDeLivros = new ArrayList<>();
public static void main(String[] args) {
// write your code here
criarLivros();
String opcao;
do {
System.out.println("Bem vinda à Biblioteca. \n Escolha uma opcao: \n [0]- Sair \n [1]-Imprimir lista de livros ");
Scanner entradaDoUsuario = new Scanner(System.in);
opcao = entradaDoUsuario.next();
if (opcao.equals("1")){
imprimirListaDeLivros();
}
} while(!opcao.equals("0"));
}
private static void imprimirListaDeLivros() {
for (Livro livro :listaDeLivros) {
livro.obterInformacoes();
}
}
/*private static void imprimirListaDeLivros() {
for (int indice = 0; indice < listaDeLivros.size() ; indice ++) {
listaDeLivros.get(indice).obterInformacoes();
}
}*/
/*
public static void criarLivros(){
Livro prideAndPrejudice = new Livro("Jane Austen", "pride and prejudice", 1865);
listaDeLivros.add(prideAndPrejudice);
Livro Sapiens = new Livro("Yuval Noah Harari", "Sapiens", 2009);
listaDeLivros.add(Sapiens);
}*/
}
| true |
3d74f16e96d69984b2dc4570f77cf491dce0c882 | Java | KlymyshynAndrii/headtail | /src/HomeWork/Task4.java | UTF-8 | 280 | 3.078125 | 3 | [] | no_license | package HomeWork;
public class Task4 {
public static void main(String[] args) {
int meter;
meter= 8;
int cm=meter*100;
double ft= meter*3.281;
System.out.println("The is "+cm+" centimeters or foot "+ft+" in "+meter+" meter");
}
}
| true |
99cb36ee63a2bfee143d9a92362e693f1aa88fde | Java | walter-woodall/banana_now | /app/models/Category.java | UTF-8 | 1,253 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | package models;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.SqlQuery;
import com.avaje.ebean.SqlRow;
import play.db.ebean.Model;
import java.util.LinkedList;
import java.util.List;
/**
* Created by walterwoodall on 12/6/14.
*/
public class Category extends Model {
public String mainCategory;
public String subcategory;
public Category(String category, String subcategory){
this.mainCategory = category;
this.subcategory = subcategory;
}
public static List<Category> getAllCategories(Store store){
int id = store.id;
String sql = "select category, subcategory from product where store_id = " + id + " group by subcategory order by category asc;";
LinkedList<Category> categories = null;
SqlQuery sqlQuery = Ebean.createSqlQuery(sql);
List<SqlRow> list = sqlQuery.findList();
if(list != null) {
categories = new LinkedList<Category>();
for (SqlRow row : list) {
String category = row.getString("category");
String subcategory = row.getString("subcategory");
Category c = new Category(category, subcategory);
categories.add(c);
}
}
return categories;
}
}
| true |
cef1405eab62ca3a33d41ae0d3b4606d14e63518 | Java | MWrobel92/Karty-oczko | /src/algorytm/wyjatki/ZasadyGryException.java | UTF-8 | 216 | 1.648438 | 2 | [] | no_license | package algorytm.wyjatki;
/**
* Klasa wyjątku, po której dziedziczą wszystkie wyjątki stanowiące naruszenie zasad gry.
* @author Michał Wróbel
*/
public class ZasadyGryException extends Exception {
}
| true |
383ceef0689daac054c9a527d437b9a994b99340 | Java | klose911/klose911.github.io | /src/jcip/src/main/java/org/klose/concurrency/shutdown/BrokenLogWriter.java | UTF-8 | 1,708 | 3.296875 | 3 | [
"BSD-2-Clause"
] | permissive | /*
* 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 org.klose.concurrency.shutdown;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class BrokenLogWriter {
private final BlockingQueue<String> queue;
private final LoggerThread logger;
private final int CAPACITY = 100;
public BrokenLogWriter(PrintWriter writer) {
this.queue = new LinkedBlockingQueue<>(CAPACITY);
this.logger = new LoggerThread(writer);
}
public void start() {
logger.start();
}
/**
* 需要打印数据的线程调用该方法, 将待打印数据加入阻塞队列
*
* @param msg
* @throws java.lang.InterruptedException
*/
public void log(String msg) throws InterruptedException {
queue.put(msg);
}
/**
* 负责从阻塞队列中取出数据输出的线程
*/
private class LoggerThread extends Thread {
private final PrintWriter writer;
private LoggerThread(PrintWriter writer) {
this.writer = writer;
}
@Override
public void run() {
try {
while (true) {
writer.println(queue.take());
}
} catch (InterruptedException ignored) {
} finally {
writer.close();
}
}
}
/**
* 该方法用于停止LoggerThread线程
*/
public void shutDown() {
logger.interrupt();
}
}
| true |
03910bac0667846c530fd9abff4b30235aa10f75 | Java | kfcoding/kfcoding-cloud | /kfcoding-modules/kfcoding-basic/src/main/java/com/cuiyun/kfcoding/basic/model/Thirdpart.java | UTF-8 | 2,639 | 1.65625 | 2 | [] | no_license | package com.cuiyun.kfcoding.basic.model;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import com.cuiyun.kfcoding.api.vo.authority.enums.AuthTypeEnum;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
*
* </p>
*
* @author maple123
* @since 2018-05-19
*/
@Data
@TableName("basic_thirdpart")
public class Thirdpart extends Model<Thirdpart> {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.UUID)
private String id;
@TableField("user_id")
private String userId;
@JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
@TableField("auth_type")
private AuthTypeEnum authType;
@TableField("thirdpart_id")
private String thirdpartId;
@TableField("gists_url")
private String gistsUrl;
@TableField("repos_url")
private String reposUrl;
@TableField("following_url")
private String followingUrl;
private String bio;
@TableField("created_at")
private Date createdAt;
private String login;
private String type;
private String blog;
@TableField("subscriptions_url")
private String subscriptionsUrl;
@TableField("updated_at")
private Date updatedAt;
@TableField("site_admin")
private String siteAdmin;
private String company;
@TableField("public_repos")
private String publicRepos;
@TableField("gravatar_id")
private String gravatarId;
private String email;
@TableField("organizations_url")
private String organizationsUrl;
private String hireable;
@TableField("starred_url")
private String starredUrl;
@TableField("followers_url")
private String followersUrl;
@TableField("public_gists")
private Integer publicGists;
private String url;
@TableField("access_token")
private String accessToken;
@TableField("received_events_url")
private String receivedEventsUrl;
private Integer followers;
@TableField("avatar_url")
private String avatarUrl;
@TableField("events_url")
private String eventsUrl;
@TableField("html_url")
private String htmlUrl;
private Integer following;
private String name;
private String location;
@Override
protected Serializable pkVal() {
return this.id;
}
}
| true |
8adbbf1022505e6c53b8e6b41e6fc8dbcb63368f | Java | kziomek/kata01-supermarket-pricing | /src/main/java/discount/rule/DiscountRule.java | UTF-8 | 236 | 2.03125 | 2 | [] | no_license | package discount.rule;
import basket.Item;
import discount.Discount;
import java.util.Optional;
/**
* @author Krzysztof Ziomek
* @since 04/04/2017.
*/
public interface DiscountRule {
Optional<Discount> calculateDiscount(Item item);
}
| true |
fcefe5b28d6efd7cfc596030c5279a5004a4495c | Java | dmanjuyanig/FlipKartApplication | /src/main/java/page/MyEmployeePage.java | UTF-8 | 2,295 | 2.21875 | 2 | [] | no_license | package page;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import generic.WebGeneric;
public class MyEmployeePage
{
private WebDriver driver;
//***************************************************************************************
@FindBy(xpath="//div[@id = \"menuheading\"]")
private WebElement ManuHeading;
@FindBy(xpath="//span[contains(text(),'Official')]")
private WebElement OfficialTab;
@FindBy(xpath="//span[contains(text(),'Personal')]")
private WebElement PersonalTab;
@FindBy(xpath="//span[contains(text(),'Banking')]")
private WebElement BankingTab;
@FindBy(xpath="//span[contains(text(),'Academic-Passport')]")
private WebElement AcademicPassportTab;
@FindBy(xpath="//span[contains(text(),'Skills-Certification')]")
private WebElement SkillsCertificationTab;
@FindBy(xpath="//span[contains(text(),'Leave History')]")
private WebElement LeaveHistoryTab;
@FindBy(xpath="//span[contains(text(),'Status History')]")
private WebElement StatusHistoryTab;
//***************************************************************************************
public MyEmployeePage(WebDriver driver)
{
this.driver = driver;
PageFactory.initElements(driver,this);
}
//***************************************************************************************
/*public String menuHeader()
{
return ManuHeading.getText();
}*/
public void VerifyOfficialTab()
{
WebGeneric.WebelementPresent(OfficialTab);
}
public void VerifyPersonalTab()
{
WebGeneric.WebelementPresent(PersonalTab);
}
public void ClickPersonalTab() throws InterruptedException
{
Thread.sleep(3000);
PersonalTab.click();
WebGeneric.WebelementPresent(PersonalTab);
}
public void VerifyBankingTab()
{
WebGeneric.WebelementPresent(BankingTab);
}
public void VerifyAcademicPassportTab()
{
WebGeneric.WebelementPresent(AcademicPassportTab);
}
public void VerifySkillsCertificationTab()
{
WebGeneric.WebelementPresent(SkillsCertificationTab);
}
public void VerifyLeaveHistoryTab()
{
WebGeneric.WebelementPresent(LeaveHistoryTab);
}
public void VerifyStatusHistoryTab()
{
WebGeneric.WebelementPresent(StatusHistoryTab);
}
}
| true |
5ab8015efd44f99d5a45a4cf0a8d4d7aec6b4b8a | Java | Jally-S/gitLearning | /4.CRM/src/org/jvsun/servlet/AddContract.java | UTF-8 | 1,459 | 2.421875 | 2 | [] | no_license | package org.jvsun.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jvsun.dao.factory.ContractDAOFactory;
import org.jvsun.pojo.ContractPOJO;
public class AddContract extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
BigDecimal customerName=new BigDecimal(request.getParameter("customerName"));
BigDecimal workerName=new BigDecimal(request.getParameter("workerName"));
String contractName=request.getParameter("contractName");
String contractContent=request.getParameter("contractContent");
int isPhoto=Integer.parseInt(request.getParameter("isPhoto"));
ContractPOJO pojo = new ContractPOJO(customerName,workerName,contractName,contractContent,isPhoto);
System.out.println("输出数据:"+pojo.toString());
boolean flag=ContractDAOFactory.getDAOInstance().doIns(pojo);
PrintWriter out = response.getWriter();
StringBuffer sb = new StringBuffer();
sb.append(flag);
out.print(sb.toString());
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
| true |
fa3c536acd7b9025ca536424eca476698acc8712 | Java | google-code/auto-parts | /myweb/src/main/java/com/huarui/desktop/service/TableMetaDataService.java | UTF-8 | 204 | 1.75 | 2 | [] | no_license | package com.huarui.desktop.service;
import com.huarui.desktop.model.TableMetaData;
public interface TableMetaDataService {
public abstract TableMetaData viewTableMetaData(String tableName);
} | true |
05e4f63f85690ec6e4e3bbe78eacf4dd173105a3 | Java | Sobunge/Procurement | /src/java/Control/tendersRejected.java | UTF-8 | 3,370 | 2.421875 | 2 | [] | no_license | package Control;
import Business.User;
import Business.tenderApplied;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.logging.*;
import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;
public class tendersRejected extends HttpServlet {
@Resource(name = "jdbc/Procurement")
private DataSource datasource;
String url = "";
String message = "";
User user = new User();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
//set content type
response.setContentType("text/html");
//get printwriter
PrintWriter out = response.getWriter();
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<tenderApplied> tenderR = new ArrayList<>();
tenderApplied tenderApp = new tenderApplied();
try {
connection = datasource.getConnection();
//Step 2: create a sql statement string
String query = "select bid.tenderNumber,tenders.description,"
+ "tenders.closingdate,tenders.closingtime,bid.amount,"
+ "bid.status,bid.username from tenders INNER JOIN bid "
+ "on tenders.number=bid.tenderNumber";
ps = connection.prepareStatement(query);
//Step 3: Execute sql query
rs = ps.executeQuery(query);
while (rs.next()) {
if ((("rejected").equals(rs.getString("status"))) &&
(user.getUsername().equals(rs.getString("username")))) {
tenderApp.setTenderNumber(rs.getString("tenderNumber"));
tenderApp.setDescription(rs.getString("description"));
tenderApp.setClosingDate(rs.getString("closingdate"));
tenderApp.setClosingTime(rs.getString("closingtime"));
tenderApp.setAmount(rs.getString("amount"));
tenderApp.setStatus(rs.getString("status"));
tenderR.add(tenderApp);
}
}
//Step 4: Process the result set
} catch (SQLException ex) {
Logger.getLogger(tendersRejected.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
connection.close();
ps.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(tendersRejected.class.getName()).log(Level.SEVERE, null, ex);
}
}
url = "/tendersRejected.jsp";
session.setAttribute("tenderR", tenderR);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
| true |
cb4517cb2e71b8ddfe0e0db47cf0aed24e5e6b33 | Java | jaeho214/Algorithm_study | /src/programmers/sort/PGMS_가장큰수_second.java | UTF-8 | 1,006 | 3.703125 | 4 | [] | no_license | package programmers.sort;
import java.util.Arrays;
public class PGMS_가장큰수_second {
public static void main(String[] args) {
PGMS_가장큰수_second pgms_가장큰수_second = new PGMS_가장큰수_second();
int[] numbers = {0,0,0,0};
System.out.println(pgms_가장큰수_second.solution(numbers));
}
public String solution(int[] numbers) {
StringBuilder answer = new StringBuilder();
String[] numStr = new String[numbers.length];
for(int i=0;i<numbers.length;i++){
numStr[i] = String.valueOf(numbers[i]);
}
Arrays.sort(numStr, (o1, o2) -> String.valueOf(Long.parseLong(o1+o2)).compareTo(String.valueOf(Long.parseLong(o2+o1))));
int cnt =0;
for(int i=numStr.length-1;i>=0;i--) {
answer.append(numStr[i]);
if(numStr[i].equals("0"))
cnt++;
}
if(cnt == numStr.length)
return "0";
return answer.toString();
}
}
| true |
55552239cfe69f6abcd7d299916d481ce903c441 | Java | aswini50/MyFramework | /src/test/java/com/learnautomation/framework/pages/LeavePage.java | UTF-8 | 1,893 | 2.265625 | 2 | [] | no_license | package com.learnautomation.framework.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
public class LeavePage {
WebDriver driver ;
public LeavePage(WebDriver driver)
{
this.driver=driver;
PageFactory.initElements(driver,this);
}
// Navigate to LeavePage from Admin Page
// Locators on LeavePage
//By applyTab = By.id("menu_leave_applyLeave");
//By personalLeaveType = By.xpath("//*[text()='Leave Type ']//following::select[1]");
By fromDate =By.xpath("//*[text()='From Date ']//following::input[1]");
By toDate = By.xpath("//*[text()='To Date ']//following::input[1]");
By comment=By.xpath("//*[text()='Comment']//following::textarea");
By submitBtn =By.xpath("//input[@value='Apply']");
By dateSelection=By.xpath("//table[contains(@class,'calendar')]//a[text()=25]");
By leaveType = By.xpath("//*[text()='Leave Type ']//following::select[1]");
//By dateSelection = By.xpath("//table[contains(@class,'calendar')]//a[text()=25]");
// Methods for actions
public void applyLeave(String leaveCategory, String commentEntry ){
Select leave =new Select(driver.findElement(leaveType));
leave.selectByVisibleText(leaveCategory);
driver.findElement(fromDate).click();//sendkeys will take String
driver.findElement(dateSelection).click();
driver.findElement(toDate).click();
driver.findElement(dateSelection).click();
driver.findElement(comment).sendKeys(commentEntry);
driver.findElement(submitBtn).click();
//*[text()='Leave Type ']//following::select[1]
//*[text()='From Date ']//following::input[1]
//*[text()='To Date ']//following::input[1]
//*[text()='Comment']//following::textarea
//*[text()='Apply ']//following::input[@value='Apply']
}
}
| true |
0ed35189d1d8b2ad0448b24d1eaa2815809be4f2 | Java | wsyx04/JavaSE_20171.1 | /src/main/java/reflect/demo/b/Service.java | UTF-8 | 342 | 2.25 | 2 | [] | no_license | package reflect.demo.b;
/**
* Created by whb on
* 2017/5/5 9:43
*/
//强耦合---松散耦合---》解耦
public class Service {
private DeviceWriter deviceWriter;
public Service(DeviceWriter deviceWriter) {
this.deviceWriter = deviceWriter;
}
public void write() {
deviceWriter.writeToDevice();
}
}
| true |
998a86ec4fabd24122c0946429135b6dacbf0df6 | Java | rrohitmaheshwari/JavaPractice | /src/leetcodeProblems/bstIterator.java | UTF-8 | 1,228 | 3.734375 | 4 | [] | no_license | /*
173. Binary Search Tree Iterator
https://leetcode.com/problems/binary-search-tree-iterator/
O(N)
O(N)
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class BSTIterator {
Queue<TreeNode> queue;
public BSTIterator(TreeNode root) {
this.queue = new LinkedList<TreeNode>();
this._inorder(root);
}
private void _inorder(TreeNode root) {
if (root == null) {
return;
}
this._inorder(root.left);
this.queue.add(root);
this._inorder(root.right);
}
public int next() {
return queue.poll().val;
}
public boolean hasNext() {
return !queue.isEmpty();
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/ | true |
25d449269ce803a11c3bb510a236cda2d547dec8 | Java | gunjankhandelwalsjsu/RESTfulExample | /src/main/java/com/mkyong/database/ClentData.java | UTF-8 | 1,017 | 1.976563 | 2 | [] | no_license | package com.mkyong.database;
import java.util.ArrayList;
import java.util.List;
import javax.xml.datatype.Duration;
import com.mykong.pojo.Product;
public class ClentData {
String object_id;
public String getInstance_id() {
return instance_id;
}
public void setInstance_id(String instance_id) {
this.instance_id = instance_id;
}
String instance_id;
String lifetime;
String resource_id1;
String resource_id2;
public String getResource_id1() {
return resource_id1;
}
public void setResource_id1(String resource_id1) {
this.resource_id1 = resource_id1;
}
public String getResource_id2() {
return resource_id2;
}
public void setResource_id2(String resource_id2) {
this.resource_id2 = resource_id2;
}
public String getObject_id() {
return object_id;
}
public void setObject_id(String object_id) {
this.object_id = object_id;
}
public String getLifetime() {
return lifetime;
}
public void setLifetime(String lifetime) {
this.lifetime = lifetime;
}
}
| true |
0617011a2f0e06d23d6c54c39860748387859ef5 | Java | jrross/csc468-gui | /JavaFX/src/ross_jeffrey/Shrubbery.java | UTF-8 | 3,449 | 3.734375 | 4 | [] | no_license | package ross_jeffrey;
/*************************************************************************//**
* @file Shrubbery.java
*
* @author Jeff Ross
*
* @details
* Handles the Shrubbery class, inherited from Plant.
*
*****************************************************************************/
public class Shrubbery extends Plant {
private double health;
private double waterNeeds;
private double moisture;
private String name;
/*********************************************************************//**
* @name fertillize
* @par Description:
* Increases the health by 10, and returns true to indicate success.
*
* @returns true
* *************************************************************************/
public Boolean fertilize(){
health += 10;
return true;
}
/*********************************************************************//**
* @name getHealth
* @par Description:
* gets the health of the plant.
*
* @returns the health value
* *************************************************************************/
public double getHealth(){
return health;
}
/*********************************************************************//**
* @name getText
* @par Description:
* Gets the text to be displayed on the button. Puts name, health, and soil
* moisture into a string and returns it.
*
* @returns the text to display on the button
* *************************************************************************/
public String getText(){
String string = name + "\nHealth: " + String.valueOf(health);
string = string + "\nSoil Moisture: " + String.valueOf(moisture);
return string;
}
/*********************************************************************//**
* @name newDay
* @par Description:
* Decreases health by 5, and decreases moisture by 10. If moisture falls
* below 0, it is set to 0. If, following this, the water moisture is below
* the water requirement, health is further decremented by 10.
*
* @returns nothing
* *************************************************************************/
public void newDay(){
health -= 5;
if(moisture <= 10){
moisture = 0;
}
else {
moisture -= 10;
}
if(moisture < waterNeeds){
health -= 10;
}
}
/*********************************************************************//**
* @name Shrubbery
* @par Description:
* Constructor for Shrubbery. Sets health to 40, amount of water needed to 15,
* current moisture to 0, and the name of the plant to "Shrubbery"
*
* @returns nothing
* *************************************************************************/
public Shrubbery(){
health = 40.0;
waterNeeds = 15.0;
moisture = 0.0;
name = "Shrubbery";
}
/*********************************************************************//**
* @name water
* @par Description:
* Increases the moisture by the specified amount
*
* param[in] amount - the amount to increase moisture by
*
* @returns nothing
* *************************************************************************/
public void water(double amount){
moisture += amount;
}
}
| true |
80d15779374baef8b87dda46d07321c9b9959a11 | Java | crazyman106/xiangxue | /serializable/src/main/java/com/example/serializable/test/User6.java | UTF-8 | 599 | 2.6875 | 3 | [] | no_license | package com.example.serializable.test;
/**
* author : fenzili
* e-mail : 291924028@qq.com
* date : 2020/5/25 23:23
* pkn : com.example.serializable.test
* desc :
*/
public class User6 {
private String name;
private String sax;
public String getName() {
return name;
}
public String getSax() {
return sax;
}
public User6() {
this.name ="test1--name";
this.sax ="test1--sax";
System.out.println("empty constructor");
}
public User6(String name, String sax) {
this.name = name;
this.sax = sax;
}
}
| true |
b8a5ce911b975f6df5c5e45417aedf50c2facb58 | Java | tinxwong/my-pro | /chipin/src/main/java/com/tinx/java/chipin/controller/LotteryController.java | UTF-8 | 2,014 | 1.914063 | 2 | [] | no_license | package com.tinx.java.chipin.controller;
import com.baomidou.mybatisplus.mapper.Condition;
import com.tinx.java.chipin.entity.Lottery;
import com.tinx.java.chipin.entity.User;
import com.tinx.java.chipin.entity.query.LotteryQuery;
import com.tinx.java.chipin.entity.vo.LotteryVo;
import com.tinx.java.chipin.entity.vo.UserVo;
import com.tinx.java.chipin.enums.RoleEnum;
import com.tinx.java.chipin.service.ChipinService;
import com.tinx.java.chipin.service.LotteryService;
import com.tinx.java.chipin.service.impl.LotteryServiceImpl;
import com.tinx.java.chipin.utils.MyBeanUtils;
import com.tinx.java.common.response.BaseResponse;
import com.tinx.java.common.response.enums.VisibilityEnum;
import com.tinx.java.common.response.status.ResponseCode;
import com.tinx.java.common.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author tinx123
* @since 2018-08-11
*/
@Controller
@RequestMapping("/chipin/lottery")
public class LotteryController extends ChipInController<LotteryQuery,LotteryVo>{
@Autowired
private LotteryService lotteryService;
@Override
public String getModuleName() {
return "lottery";
}
@Override
public ChipinService getServiceName() {
return lotteryService;
}
@RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public BaseResponse list(){
List<Lottery> list = lotteryService.selectList(Condition.create().eq("visibility", VisibilityEnum.CAN_USE.getCode()));
List<LotteryVo> lotteryVos = MyBeanUtils.convertBeanList(list,LotteryVo.class);
return ResultUtil.makeBaseResponse(lotteryVos, ResponseCode.SUCCESS);
}
}
| true |
0d86da28266737cec31be2dc51daac30d2c3c463 | Java | JiefengHou/HKUST-MSc | /CSIT5510-Mobile Application Development/S-Trade/app/src/main/java/com/s_trade/s_trade/SignUpActivity.java | UTF-8 | 4,772 | 2.4375 | 2 | [] | no_license | /**
#Course Code #Name Student ID Email address
CSIT 5510 KWAN Chak Lam 20095398 clkwanaa@connect.ust.hk
CSIT 5510 Deng Ken 20400660 kdengab@connect.ust.hk
CSIT 5510 Hou Jiefeng 20361723 jhouad@connect.ust.hk
*/
package com.s_trade.s_trade;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.s_trade.s_trade.presenter.getinfo;
public class SignUpActivity extends AppCompatActivity {
Toast toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
ImageView imageView = (ImageView) findViewById(R.id.imageView_back);
imageView.setOnClickListener(new TextView.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
Button button_signUp = (Button) findViewById(R.id.button_signUp);
button_signUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// check the username, password, email and phone number is empty or not
EditText userName = (EditText) findViewById(R.id.signUp_userName);
EditText password = (EditText) findViewById(R.id.signUp_password);
EditText email = (EditText) findViewById(R.id.signUp_email);
EditText phoneNum = (EditText) findViewById(R.id.signUp_phoneNum);
EditText uname = (EditText) findViewById(R.id.signUp_uname);
if(TextUtils.isEmpty(userName.getText())) {
toast = Toast.makeText(getApplicationContext(), "Account cannot be empty",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else if(TextUtils.isEmpty(password.getText())) {
toast = Toast.makeText(getApplicationContext(), "Password cannot be empty",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else if(TextUtils.isEmpty(email.getText())){
toast = Toast.makeText(getApplicationContext(), "Email cannot be empty",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else if(TextUtils.isEmpty(phoneNum.getText())) {
toast = Toast.makeText(getApplicationContext(), "Phone Number cannot be empty",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else {
MyTask my=new MyTask();
my.execute(userName.getText().toString(),password.getText().toString(),
email.getText().toString()+"@connect.ust.hk",phoneNum.getText().toString(),
uname.getText().toString());
}
}
});
}
private class MyTask extends AsyncTask<String, Integer, Integer> {
@Override
protected Integer doInBackground(String... params) {
try {
int temp= getinfo.newuser(params[0],params[1],params[2],params[3],params[4]);
return temp;
} catch (Exception e) {
return 0;
}
}
@Override
protected void onPostExecute(final Integer result) {
if (result.equals(0)||result.equals(3))
{
toast = Toast.makeText(getApplicationContext(), "database error",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else if (result.equals(2))
{
toast = Toast.makeText(getApplicationContext(), "the account has been exist",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else {
toast = Toast.makeText(getApplicationContext(), "Sign Up Successfully, Please Sign In",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
onBackPressed();
}
}
}
}
| true |
9571f0f18992ec603576787d8187441667864cd4 | Java | charafmrah/Data-Structures | /Data_Structures/src/AVLTree/Test.java | UTF-8 | 182 | 2.140625 | 2 | [] | no_license | package AVLTree;
public class Test {
public static void main(String[] args) {
AVLTree avl = new AVLTree();
Node newNode = new Node(3);
avl.insert(new Node(3), 3);
}
}
| true |
b313007bd28dc4b795755546b6f1d4a66d464109 | Java | KingLemming/1.13-pre | /ThermalSeries/src/main/java/cofh/thermal/core/fluid/BlockFluidCrudeOil.java | UTF-8 | 1,515 | 2.40625 | 2 | [] | no_license | package cofh.thermal.core.fluid;
import cofh.core.fluid.BlockFluidCoFH;
import cofh.thermal.core.ThermalSeries;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.MaterialLiquid;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.Fluid;
import static cofh.lib.util.Constants.ID_THERMAL_SERIES;
public class BlockFluidCrudeOil extends BlockFluidCoFH {
private static boolean effect = true;
public static void config() {
String category = "Fluid.CrudeOil";
String comment = "If TRUE, Crude Oil will be flammable.";
effect = ThermalSeries.config.getBoolean("Flammable", category, effect, comment);
}
public BlockFluidCrudeOil(Fluid fluid) {
super(fluid, new MaterialLiquid(MapColor.BLACK), fluid.getName(), ID_THERMAL_SERIES);
setQuantaPerBlock(6);
setTickRate(10);
setHardness(100F);
setLightOpacity(7);
setParticleColor(0.2F, 0.2F, 0.2F);
config();
}
@Override
public int getFireSpreadSpeed(IBlockAccess world, BlockPos pos, EnumFacing face) {
return effect ? 300 : 0;
}
@Override
public int getFlammability(IBlockAccess world, BlockPos pos, EnumFacing face) {
return 25;
}
@Override
public boolean isFlammable(IBlockAccess world, BlockPos pos, EnumFacing face) {
return effect;
}
@Override
public boolean isFireSource(World world, BlockPos pos, EnumFacing face) {
return effect;
}
}
| true |
3f9bd0eaa25cc0a18121983e10f319c5b2b30122 | Java | t4upl/Loan-Rest-API | /src/main/java/com/example/loanrestapi/decisionsystem/DecisionRuleFactoryImpl.java | UTF-8 | 2,281 | 2.15625 | 2 | [] | no_license | package com.example.loanrestapi.decisionsystem;
import com.example.loanrestapi.dto.ProductRequestDto;
import com.example.loanrestapi.enums.SettingName;
import com.example.loanrestapi.model.ProductTypeSetting;
import com.example.loanrestapi.service.ProductTypeSettingService;
import java.time.LocalTime;
import java.util.List;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@AllArgsConstructor
public class DecisionRuleFactoryImpl implements DecisionRuleFactory {
ProductTypeSettingService productTypeSettingService;
@Override
public DecisionRule rulesForTestProductType(ProductRequestDto productRequestDto) {
List<ProductTypeSetting> productTypeSettings = productTypeSettingService.findByProductType_Id(
productRequestDto.getProductTypeId());
Integer minAmount = productTypeSettingService.findAndGetAsInteger(
productTypeSettings, SettingName.MIN_AMOUNT);
Integer maxAmount = productTypeSettingService.findAndGetAsInteger(productTypeSettings,
SettingName.MAX_AMOUNT);
Integer loanAmount = productRequestDto.getAmount();
Integer minTerm = productTypeSettingService.findAndGetAsInteger(productTypeSettings,
SettingName.MIN_TERM);
Integer maxTerm = productTypeSettingService.findAndGetAsInteger(productTypeSettings,
SettingName.MAX_TERM);
Integer loanTerm = productRequestDto.getTerm();
LocalTime minRejectionTime = productTypeSettingService
.findAndGetAsLocalTime(productTypeSettings,
SettingName.MIN_REJECTION_TIME);
LocalTime maxRejectionTime = productTypeSettingService
.findAndGetAsLocalTime(productTypeSettings, SettingName.MAX_REJECTION_TIME);
LocalTime loanApplicationTime = productRequestDto.getApplicationDate().toLocalTime();
return DecisionRule.DecisionRuleBuilder
.builder()
.addFilter(DecisionFilterFactory.valueInRange(minAmount, maxAmount, loanAmount)) //amount
.addFilter(DecisionFilterFactory.valueInRange(minTerm, maxTerm, loanTerm)) //term
// don't accept if between hours and max amount is asked
.addFilter(DecisionFilterFactory.outsideOfRejectionHours(maxAmount, loanAmount,
minRejectionTime, maxRejectionTime, loanApplicationTime))
.build();
}
}
| true |
a855b29e61e74a56f9d72430f835a314c8e2f453 | Java | ReactiveSprint/RsAndroid | /rsjava/src/test/java/io/reactivesprint/rx/functions/FuncNCharSequenceNotNullAndLengthTest.java | UTF-8 | 1,150 | 2.375 | 2 | [] | no_license | package io.reactivesprint.rx.functions;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by Ahmad Baraka on 4/13/16.
*/
public class FuncNCharSequenceNotNullAndLengthTest extends TestCase {
FuncNCharSequenceNotNullAndLength func;
public void testCall() throws Exception {
func = new FuncNCharSequenceNotNullAndLength();
assertThat(func.call("Test", "Test")).isTrue();
assertThat(func.call("1", "1")).isTrue();
assertThat(func.call("Test", "")).isFalse();
assertThat(func.call(null, "Test")).isFalse();
assertThat(func.call(null, null)).isFalse();
assertThat(func.call("", "")).isFalse();
}
public void testCall10() throws Exception {
func = new FuncNCharSequenceNotNullAndLength(4);
assertThat(func.call("Test", "Test")).isTrue();
assertThat(func.call("123", "Test")).isFalse();
assertThat(func.call("Test", "")).isFalse();
assertThat(func.call(null, "Test")).isFalse();
assertThat(func.call(null, null)).isFalse();
assertThat(func.call("", "")).isFalse();
}
}
| true |
909e2cdbae190635c69784aa88da859b9f8e3fcb | Java | fjsimon/Algorithms | /src/main/java/HackerRank/StacksAndQueues/CastleOnTheGrid/CastleOnTheGrid.java | UTF-8 | 3,335 | 3.34375 | 3 | [] | no_license | package HackerRank.StacksAndQueues.CastleOnTheGrid;
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
/**
*
* https://www.hackerrank.com/challenges/castle-on-the-grid/problem?h_l=interview&isFullScreen=false&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=stacks-queues
*
*/
class Result {
static final int[] X_OFFSETS = { -1, 0, 1, 0 };
static final int[] Y_OFFSETS = { 0, 1, 0, -1 };
public static int minimumMoves(List<String> grid, int startX, int startY, int goalX, int goalY) {
if (startX == goalX && startY == goalY) {
return 0;
}
int size = grid.size();
int[][] moves = new int[size][size];
IntStream.range(0, size).forEach(x -> Arrays.fill(moves[x], -1));
moves[startX][startY] = 0;
Queue<Point> queue = new LinkedList<>();
queue.offer(new Point(startX, startY));
while (true) {
Point head = queue.poll();
for (int i = 0; i < X_OFFSETS.length; i++) {
int nextX = head.x;
int nextY = head.y;
while (isOpen(grid, nextX + X_OFFSETS[i], nextY + Y_OFFSETS[i])) {
nextX += X_OFFSETS[i];
nextY += Y_OFFSETS[i];
if (nextX == goalX && nextY == goalY) {
return moves[head.x][head.y] + 1;
}
if (moves[nextX][nextY] < 0) {
moves[nextX][nextY] = moves[head.x][head.y] + 1;
queue.offer(new Point(nextX, nextY));
}
}
}
}
}
static boolean isOpen(List<String> grid, int x, int y) {
return x >= 0 && x < grid.size() && y >= 0 && y < grid.size() && grid.get(x).charAt(y) == '.';
}
}
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public class CastleOnTheGrid {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<String> grid = IntStream.range(0, n).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}).collect(toList());
String[] firstMultipleInput = bufferedReader.readLine().
replaceAll("\\s+$", "").split(" ");
int startX = Integer.parseInt(firstMultipleInput[0]);
int startY = Integer.parseInt(firstMultipleInput[1]);
int goalX = Integer.parseInt(firstMultipleInput[2]);
int goalY = Integer.parseInt(firstMultipleInput[3]);
int result = Result.minimumMoves(grid, startX, startY, goalX, goalY);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
| true |
a1bd825729647115baf45f14af5786f092c3e954 | Java | pradeep-ks/sportsbazaar | /web-jsp/src/main/java/com/sportsbazaar/web/jsp/controller/AppController.java | UTF-8 | 565 | 2.015625 | 2 | [
"MIT"
] | permissive | package com.sportsbazaar.web.jsp.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class AppController {
private static final Logger log = LoggerFactory.getLogger(AppController.class);
@RequestMapping("/")
public String index(Model model) {
log.info("returing 'index'");
return "index";
}
@RequestMapping("/about")
public String about() {
return "about";
}
}
| true |
a457b882327a719288e0e7f65716dddf72fd4ae3 | Java | tanmaya-git/SNN-ecomm | /SNS/src/com/anand/util/CurrentDate.java | UTF-8 | 320 | 2.421875 | 2 | [] | no_license | package com.anand.util;
import java.text.SimpleDateFormat;
public class CurrentDate {
public static String getCurrentDate() {
java.util.Date date = new java.util.Date();
SimpleDateFormat dt1 = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(dt1.format(date));
return dt1.format(date);
}
}
| true |
9ba54837b785a6ac7f95c8ca525a3effce133fd2 | Java | praweenkumargit/sdet_Activities | /testNG/Activity3.java | UTF-8 | 1,055 | 2.015625 | 2 | [] | no_license | package com.ibm.TestNG_Projects.TestNG;
import org.testng.annotations.Test;
import junit.framework.Assert;
import org.testng.annotations.BeforeClass;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
public class Activity3 {
WebDriver driver;
@Test
public void f() {
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).clear();
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.xpath("//button[@type='submit']")).click();
String expected = "Welcome Back, admin";
String actual = driver.findElement(By.xpath("//div[@id='action-confirmation']")).getText();
Assert.assertEquals(expected, actual);
}
@BeforeClass
public void beforeClass() {
driver = new FirefoxDriver();
driver.get("https://www.training-support.net/selenium/login-form");
}
@AfterClass
public void afterClass() {
driver.close();
}
}
| true |
c02e55015fa45013599abfc74b52f36f04a76d54 | Java | gleamy/spring-cloud-examples | /003-config/config-test-registration-center/src/main/java/com/bens/spring/cloud/examples/config/test/registration/center/ConfigTestRegistrationCenterApplication.java | UTF-8 | 507 | 1.640625 | 2 | [] | no_license | package com.bens.spring.cloud.examples.config.test.registration.center;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class ConfigTestRegistrationCenterApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigTestRegistrationCenterApplication.class, args);
}
}
| true |
1bea47018e31905639a2f14e1cd8faede18c4f66 | Java | yym-git/demo-test-one | /src/main/java/com/person/cn/demotestone/designmodel/proxy/Searcher.java | UTF-8 | 313 | 1.820313 | 2 | [] | no_license | package com.person.cn.demotestone.designmodel.proxy;
/**
* @author ym.y
* @description 抽象查询类:抽象主题类
* @package com.person.cn.demotestone.designmodel.proxy
* @updateUser
* @date 12:36 2020/12/15
*/
public interface Searcher {
public String doSearch(String userId,String keyword);
}
| true |
bbe3dcd41e05638d0debe175719bd34380023d2c | Java | sdgdsffdsfff/offline | /src/main/java/com/threathunter/bordercollie/slot/compute/graph/query/TopQuery.java | UTF-8 | 130 | 1.585938 | 2 | [
"Apache-2.0"
] | permissive | package com.threathunter.bordercollie.slot.compute.graph.query;
/**
*
*/
public interface TopQuery {
int getTopCount();
}
| true |
a4d29f961f39114ac4aae46fc5ed7b9ef8113407 | Java | ptngmbjr/SchoolApp | /app/src/main/java/com/baseschoolapp/schoolapp/fragments/Student/FeeFragment.java | UTF-8 | 9,506 | 1.773438 | 2 | [] | no_license | package com.baseschoolapp.schoolapp.fragments.Student;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.baseschoolapp.schoolapp.Adapters.Student.FeeAdapter;
import com.baseschoolapp.schoolapp.Adapters.Student.FeeHistoryAdapter;
import com.baseschoolapp.schoolapp.R;
import com.baseschoolapp.schoolapp.StudentDashBoard;
import com.baseschoolapp.schoolapp.models.Student.FeeDataModel;
import com.baseschoolapp.schoolapp.models.Student.FeeHistoryDataModel;
import java.util.ArrayList;
public class FeeFragment extends BaseFragment {
ArrayList<FeeDataModel> dataModels;
ArrayList<FeeHistoryDataModel> dataModels_fee_history_;
private static FeeAdapter adapter;
private static FeeHistoryAdapter adapter_fee_history;
public FeeFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fee, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// initHeaderName();
initialiseInstallment(view);
initialiseFeeHistory(view);
}
private void initHeaderName() {
((StudentDashBoard) getActivity()).updateToolbarTitle(getResources().getString(R.string.fee_details));
}
public void onHiddenChanged(boolean hidden) {
initHeaderName();
}
public void initialiseInstallment(View view) {
View next_installment_layout = view.findViewById(R.id.next_installment_layout);
final View fee_layout = view.findViewById(R.id.fee_layout);
TextView next_installment_text = (TextView) next_installment_layout.findViewById(R.id.intallment_text);
TextView currency_symbol = (TextView) next_installment_layout.findViewById(R.id.currency_symbol);
TextView installment_amount = (TextView) next_installment_layout.findViewById(R.id.installment_amount);
TextView due_date_text = (TextView) next_installment_layout.findViewById(R.id.due_date_text);
TextView due_date = (TextView) next_installment_layout.findViewById(R.id.due_date);
Button btn_pay_now = (Button) next_installment_layout.findViewById(R.id.btn_pay_now);
LinearLayout fee_break_down = (LinearLayout) next_installment_layout.findViewById(R.id.fee_break_down);
TextView fee_break_down_title = (TextView) next_installment_layout.findViewById(R.id.left_title);
final ImageView fee_break_down_image = (ImageView) next_installment_layout.findViewById(R.id.right_image);
GradientDrawable installment_background = (GradientDrawable) next_installment_layout.getBackground();
installment_background.setColor(getResources().getColor(R.color.loginblue));
GradientDrawable btn_pay_background = (GradientDrawable) btn_pay_now.getBackground();
btn_pay_background.setColor(getResources().getColor(R.color.green));
next_installment_text.setText(R.string.installment_text);
currency_symbol.setText(R.string.currency);
installment_amount.setText("55,000.00");
due_date_text.setText(R.string.due_text);
due_date.setText("08/10/2018");
btn_pay_now.setText(R.string.pay_now);
fee_break_down_title.setText(R.string.fee_break_down);
fee_break_down_image.setImageResource(R.drawable.img_arrow_expand);
fee_break_down.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (fee_layout.getVisibility() == View.VISIBLE) {
fee_layout.setVisibility(View.GONE);
fee_break_down_image.setImageResource(R.drawable.img_arrow_expand);
} else {
fee_break_down_image.setImageResource(R.drawable.img_arrow_collapse);
fee_layout.setVisibility(View.VISIBLE);
}
}
});
initialiseFeeBreakDownList(view);
initialisePaymentHistoryList(view);
}
public void initialiseFeeBreakDownList(View view) {
ListView listView = (ListView) view.findViewById(R.id.fee_listview);
ViewCompat.setNestedScrollingEnabled(listView, true);
dataModels = new ArrayList<>();
dataModels.add(new FeeDataModel(true, "Admission Fee", "15000.00"));
dataModels.add(new FeeDataModel(true, "Registration Fee", "15000.00"));
dataModels.add(new FeeDataModel(true, "Tution Fee", "15000.00"));
dataModels.add(new FeeDataModel(false, "Transportation Fee", "15000.00"));
dataModels.add(new FeeDataModel(true, "Caution Fee", "15000.00"));
dataModels.add(new FeeDataModel(true, "Special Fee", "15000.00"));
adapter = new FeeAdapter(dataModels, this.getContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FeeDataModel dataModel = dataModels.get(position);
// Snackbar.make(view, dataModel.getFee_name() + "\n" + dataModel.getFee_amout(), Snackbar.LENGTH_LONG)
// .setAction("No action", null).show();
}
});
}
public void initialisePaymentHistoryList(View view) {
ListView listView = (ListView) view.findViewById(R.id.listview_fee_history);
ViewCompat.setNestedScrollingEnabled(listView, true);
dataModels_fee_history_ = new ArrayList<>();
dataModels_fee_history_.add(new FeeHistoryDataModel("1", "153236", "15 Aug 2018", "15000.00",R.color.white));
dataModels_fee_history_.add(new FeeHistoryDataModel("1", "153236", "15 Aug 2018", "15000.00",R.color.pale_grey));
dataModels_fee_history_.add(new FeeHistoryDataModel("1", "153236", "15 Aug 2018", "15000.00",R.color.white));
dataModels_fee_history_.add(new FeeHistoryDataModel("1", "153236", "15 Aug 2018", "15000.00",R.color.pale_grey));
dataModels_fee_history_.add(new FeeHistoryDataModel("1", "153236", "15 Aug 2018", "15000.00",R.color.white));
dataModels_fee_history_.add(new FeeHistoryDataModel("1", "153236", "15 Aug 2018", "15000.00",R.color.pale_grey));
adapter_fee_history = new FeeHistoryAdapter(dataModels_fee_history_, this.getContext());
listView.setAdapter(adapter_fee_history);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FeeHistoryDataModel dataModel = dataModels_fee_history_.get(position);
// Snackbar.make(view, dataModel.getReceipt_no() + "\n" + dataModel.getAmout(), Snackbar.LENGTH_LONG)
// .setAction("No action", null).show();
}
});
}
public void initialiseFeeHistory(View view) {
View fee_history_header = view.findViewById(R.id.fee_history_header);
View fee_history_footer = view.findViewById(R.id.fee_history_footer);
TextView s_no = (TextView) fee_history_header.findViewById(R.id.s_no);
TextView receipt_no = (TextView) fee_history_header.findViewById(R.id.receipt_no);
TextView date = (TextView) fee_history_header.findViewById(R.id.date);
TextView amount = (TextView) fee_history_header.findViewById(R.id.fee_history_amount);
s_no.setText("#");
receipt_no.setText(R.string.receipt_no);
date.setText(R.string.date);
amount.setText(R.string.amount);
// TextView s_no_footer = (TextView) fee_history_footer.findViewById(R.id.s_no_foot);
// TextView receipt_no_footer = (TextView) fee_history_footer.findViewById(R.id.receipt_no);
TextView date_footer = (TextView) fee_history_footer.findViewById(R.id.date_foot);
TextView amount_footer = (TextView) fee_history_footer.findViewById(R.id.fee_history_amount_foot);
// s_no_footer.setVisibility(View.GONE);
// receipt_no_footer.setVisibility(View.GONE);
date_footer.setText(R.string.grand_total);
amount_footer.setText("$60,000.00");
GradientDrawable installment_background = (GradientDrawable) fee_history_header.getBackground();
installment_background.setColor(getResources().getColor(R.color.light_sky_blue));
GradientDrawable btn_pay_background = (GradientDrawable) fee_history_footer.getBackground();
btn_pay_background.setColor(getResources().getColor(R.color.light_grey));
}
public void payNowInstallment(View view) {
}
}
| true |
fd59ded1117c791ae44a4cf85959f15a34f20874 | Java | rbreuvart/2Dstruggle | /2Dstruggle-core/src/com/rbr/game/net/kryo/packet/lobby/PacketUpdateLobby.java | UTF-8 | 464 | 1.976563 | 2 | [] | no_license | package com.rbr.game.net.kryo.packet.lobby;
public class PacketUpdateLobby {
public int id;
public boolean roundStart;
public boolean localPlayerReady;
public boolean gameStart;
public String team;
public PacketUpdateLobby() {
}
@Override
public String toString() {
return "PacketUpdateLobby [id=" + id + ", roundStart=" + roundStart
+ ", localPlayerReady=" + localPlayerReady + ", gameStart="
+ gameStart + ", team=" + team + "]";
}
}
| true |
d193bd090046cff376836e8fd01fe757a54958c5 | Java | Epeltier/MarketSimulator | /src/main/java/marketsimulator/entities/Order.java | UTF-8 | 1,127 | 2.71875 | 3 | [] | no_license | package marketsimulator.entities;
import java.util.UUID;
import marketsimulator.entities.OrderType.OrderTypeEnum;
public class Order {
private Float price;
private String ticker;
private Integer quantity;
private OrderTypeEnum orderType;
private String id;
public Order(String ticker, Float price, OrderTypeEnum orderType, Integer quantity){
this.setPrice(price);
this.setTicker(ticker);
this.setOrderType(orderType);
this.setQuantity(quantity);
this.setId(UUID.randomUUID().toString());
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public OrderTypeEnum getOrderType() {
return orderType;
}
public void setOrderType(OrderTypeEnum orderType) {
this.orderType = orderType;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| true |
4897bc0adbf0a6e2903a84cafbe379729c2dac45 | Java | AdamczykMaciej/BYT | /Lab9/src/main/java/com/vogella/maven/Lab9/App.java | UTF-8 | 1,482 | 2.625 | 3 | [] | no_license | package com.vogella.maven.Lab9;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.util.Date;
import com.vogella.maven.Lab9.memento.Caretaker;
import com.vogella.maven.Lab9.memento.Memento;
import com.vogella.maven.Lab9.observer.Observer;
import com.vogella.maven.Lab9.observer.UrlObserver;
import com.vogella.maven.Lab9.observer.UrlSubject;
public class App {
public static void monitorWebPage(UrlSubject subject) throws IOException, ParseException {
long longtime;
URLConnection connect;
long prevLongTime = 0;
Caretaker c = new Caretaker("D:\\PJATK_Informatyka\\3_rok\\BYT\\LAB9\\states.txt");
while(true) {
connect = subject.getUrl().openConnection();
longtime = connect.getLastModified();
if(longtime>prevLongTime) {
subject.setState(new Date(longtime));;
Memento mem = subject.createMemento();
c.addMemento(mem);
subject.notifyObservers();
}
prevLongTime = longtime;
}
}
public static void main(String[] args) throws IOException, ParseException {
UrlSubject subject1 = new UrlSubject( new URL("http://www.pja.edu.pl/"));
UrlSubject subject2 = new UrlSubject( new URL("https://www.wp.pl/"));
Observer o1 = new UrlObserver(subject1);
Observer o2 = new UrlObserver(subject1);
Observer o3 = new UrlObserver(subject1);
Observer o4 = new UrlObserver(subject2);
monitorWebPage(subject1);
}
}
| true |
5c197bc943748e5c305f063dea831968b95f2c26 | Java | SparseDataTree/in-the-wind | /src/test/java/caccia/david/inthewind/impl/StringWinderTest.java | UTF-8 | 4,952 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | package caccia.david.inthewind.impl;
import org.testng.annotations.Test;
import java.util.LinkedList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class StringWinderTest
{
StringWinder sw = new StringWinder();
@Test
public void TwoFactorRoundTripTest()
{
int factorCount = 2;
String message = "hello world.";
List<String> factors = sw.unwind(message, factorCount);
String messageOut = sw.wind(factors); // factors in original order
assertThat(factors).hasSize(factorCount);
assertThat(message).isEqualTo(messageOut);
}
@Test
public void TwoFactorCommunteRoundTripTest()
{
int factorCount = 2;
String message = "hello world.";
List<String> factors = sw.unwind(message, factorCount);
// Let's change the order of the factors
String factor = factors.remove(0);
factors.add(factor);
String messageWithCommutedFactors = sw.wind(factors);
assertThat(factors).hasSize(factorCount);
assertThat(message).isEqualTo(messageWithCommutedFactors);
}
@Test
public void ThreeFactorRoundTripTest()
{
int factorCount = 3;
String message = "hello world.";
List<String> factors = sw.unwind(message, factorCount);
String messageOut = sw.wind(factors); // factors in original order
assertThat(factors).hasSize(factorCount);
assertThat(message).isEqualTo(messageOut);
}
@Test
public void ThreeFactorCommunteRoundTripTest()
{
int factorCount = 3;
String message = "hello world.";
List<String> factors = sw.unwind(message, factorCount);
// Let's change the order of the factors
String factor = factors.remove(0);
factors.add(factor);
String messageWithCommutedFactors = sw.wind(factors);
assertThat(factors).hasSize(factorCount);
assertThat(message).isEqualTo(messageWithCommutedFactors);
}
@Test
public void factorExpansionTest()
{
int factorCount = 2;
String message = "hello world.";
// encode two factors
List<String> factors = sw.unwind(message, factorCount);
// expand to three factors
String factor = factors.remove(0);
factors.addAll(sw.unwind(factor,factorCount));
String messageOut = sw.wind(factors); // expanded factors
assertThat(factors).hasSize(factorCount + 1);
assertThat(message).isEqualTo(messageOut);
}
@Test
public void factorConsolidationTest()
{
int factorCount = 3;
String message = "hello world.";
// encode two factors
List<String> factors = sw.unwind(message, factorCount);
// consolidate to two factors
List<String> factorsToConsolidate = new LinkedList<>();
factorsToConsolidate.add(factors.remove(0));
factorsToConsolidate.add(factors.remove(0));
factors.add(sw.wind(factorsToConsolidate));
String messageOut = sw.wind(factors); // expanded factors
assertThat(factors).hasSize(factorCount - 1);
assertThat(message).isEqualTo(messageOut);
}
// Note that factor replacement requires at least two factors be replaced
@Test
public void factorReplacementTest()
{
int factorCount = 3;
String message = "hello world.";
// encode two factors
List<String> factors = sw.unwind(message, factorCount);
// consolidate to two factors
List<String> factorsToConsolidate = new LinkedList<>();
factorsToConsolidate.add(factors.remove(0));
factorsToConsolidate.add(factors.remove(0));
String intermediateMessage = sw.wind(factorsToConsolidate);
List<String> replacementFactors = sw.unwind(intermediateMessage, 2);
factors.addAll(replacementFactors);
String messageOut = sw.wind(factors); // expanded factors
assertThat(factors).hasSize(factorCount);
assertThat(message).isEqualTo(messageOut);
for(String factor: factors)
{
assertThat(factor).isNotEqualTo(factorsToConsolidate.get(0));
assertThat(factor).isNotEqualTo(factorsToConsolidate.get(1));
}
}
@Test
public void parallelFactorsTest()
{
int factorCount = 3;
int factorCountTwo = 2;
String message = "hello world.";
// encode factors
List<String> factors = sw.unwind(message, factorCount);
List<String> factorsTwo = sw.unwind(message, factorCountTwo);
String messageOutThree = sw.wind(factors);
String messageOutTwo = sw.wind(factorsTwo);
assertThat(factors).hasSize(factorCount);
assertThat(factorsTwo).hasSize(factorCountTwo);
assertThat(message).isEqualTo(messageOutThree);
assertThat(message).isEqualTo(messageOutTwo);
}
} | true |
979244581b57c9e38d3a8c571e55cac400c94893 | Java | markymarkmk2/VSMGui | /src/de/dimm/vsm/vaadin/GuiElems/TablePanels/RoleTable.java | UTF-8 | 6,770 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.dimm.vsm.vaadin.GuiElems.TablePanels;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import de.dimm.vsm.fsengine.GenericEntityManager;
import de.dimm.vsm.records.AccountConnector;
import de.dimm.vsm.records.Role;
import de.dimm.vsm.records.RoleOption;
import de.dimm.vsm.vaadin.GuiElems.ComboEntry;
import de.dimm.vsm.vaadin.GuiElems.Fields.JPADBComboField;
import de.dimm.vsm.vaadin.GuiElems.Fields.JPADBLinkField;
import de.dimm.vsm.vaadin.GuiElems.Fields.JPAField;
import de.dimm.vsm.vaadin.GuiElems.Fields.JPATextField;
import de.dimm.vsm.vaadin.GuiElems.Table.BaseDataEditTable;
import de.dimm.vsm.vaadin.VSMCMain;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
class AccountConnectorJPADBComboField extends JPADBComboField
{
public AccountConnectorJPADBComboField(GenericEntityManager em)
{
super( VSMCMain.Txt("Authentifizierer"), "accountConnector", em, AccountConnector.class, "select T1 from AccountConnector T1", "");
}
@Override
public List<ComboEntry> getEntries() throws SQLException
{
List<ComboEntry> entries = new ArrayList<>();
List<AccountConnector> list = em.createQuery(qry, clazz);
for (int i = 0; i < list.size(); i++)
{
AccountConnector acct = list.get(i);
String s = acct.getType() + ":" + acct.getIp();
ComboEntry ce = new ComboEntry(acct, s);
entries.add(ce);
}
return entries;
}
}
class RoleOptionDBLinkField extends JPADBLinkField<RoleOption>
{
ArrayList<ComboEntry> roleOptionEntries;
public RoleOptionDBLinkField(GenericEntityManager em, ArrayList<ComboEntry> roleOptionEntries)
{
super( em, VSMCMain.Txt("Rollenoptionen"), "roleOptions", RoleOption.class);
this.roleOptionEntries = roleOptionEntries;
}
@Override
public String toString( Object _list )
{
StringBuilder sb = new StringBuilder();
try
{
if (_list instanceof List)
{
List list = (List) _list;
for (int i = 0; i < list.size(); i++)
{
Object object = list.get(i);
if (sb.length() > 0)
sb.append(", ");
String txt = object.toString();
for (int j = 0; j < roleOptionEntries.size(); j++)
{
ComboEntry c = roleOptionEntries.get(j);
if (c.isDbEntry(object.toString()))
txt = c.getGuiEntryKey();
}
sb.append(txt);
}
}
else
{
sb.append(_list.toString());
}
}
catch (Exception noSuchFieldException)
{
}
return sb.toString();
}
}
/**
*
* @author Administrator
*/
public class RoleTable extends BaseDataEditTable<Role>
{
public static final String ROLE_QRY = "select * from Role T1 order by name asc";
ArrayList<ComboEntry> roleOptionEntries;
private RoleTable( VSMCMain main, List<Role> list, ArrayList<JPAField> _fieldList, ItemClickListener listener, ArrayList<ComboEntry> roleOptionEntries)
{
super(main, list, Role.class, _fieldList, listener);
this.roleOptionEntries = roleOptionEntries;
}
public static RoleTable createTable( VSMCMain main, List<Role> list, ItemClickListener listener)
{
ArrayList<JPAField> fieldList = new ArrayList<>();
fieldList.add(new JPATextField(VSMCMain.Txt("Name"), "name"));
fieldList.add(new JPATextField(VSMCMain.Txt("Benutzerfilter (Regexp)"), "accountmatch"));
fieldList.add(new AccountConnectorJPADBComboField( VSMCMain.get_base_util_em() ));
ArrayList<ComboEntry> roe = new ArrayList<>();
roe.add( new ComboEntry(RoleOption.RL_ALLOW_VIEW_PARAM, VSMCMain.Txt("Parameter Client öffnen")));
roe.add( new ComboEntry(RoleOption.RL_ALLOW_EDIT_PARAM, VSMCMain.Txt("Parameter bearbeiten")));
roe.add( new ComboEntry(RoleOption.RL_ADMIN, VSMCMain.Txt("Administrator")));
roe.add( new ComboEntry(RoleOption.RL_READ_WRITE, VSMCMain.Txt("Schreibrechte")));
roe.add( new ComboEntry(RoleOption.RL_USERPATH, VSMCMain.Txt("Restorepfad")));
roe.add( new ComboEntry(RoleOption.RL_FSMAPPINGFILE, VSMCMain.Txt("VSM-Filesystem Mapping")));
roe.add( new ComboEntry(RoleOption.RL_GROUPMAPPINGFILE, VSMCMain.Txt("ACL-Gruppen Mapping")));
roe.add( new ComboEntry(RoleOption.RL_GROUP, VSMCMain.Txt("Gruppenzugehörigkeit")));
roe.add( new ComboEntry(RoleOption.RL_VALID_POOLS, VSMCMain.Txt("Sichtbare Pools")));
setTooltipText( fieldList, "accountmatch", VSMCMain.Txt("Wildcards mit .* (z.B.) user123.*" ) );
fieldList.add(new RoleOptionDBLinkField(VSMCMain.get_base_util_em(), roe));
return new RoleTable( main, list, fieldList, listener, roe);
}
@Override
protected GenericEntityManager get_em()
{
return VSMCMain.get_base_util_em();
}
@Override
public void setValueChanged()
{
super.setValueChanged(); //To change body of generated methods, choose Tools | Templates.
setNewList();
}
public void setNewList()
{
List<Role> list = null;
try
{
list = VSMCMain.get_base_util_em().createQuery(ROLE_QRY, Role.class);
setNewList(list);
}
catch (SQLException sQLException)
{
VSMCMain.notify(this, "Fehler beim Erzeugen der Role-Tabelle", sQLException.getMessage());
}
}
@Override
protected Role createNewObject()
{
Role p = new Role();
GenericEntityManager gem = get_em();
try
{
gem.check_open_transaction();
gem.em_persist(p);
gem.commit_transaction();
this.requestRepaint();
return p;
}
catch (Exception e)
{
gem.rollback_transaction();
VSMCMain.notify(this, "Abbruch in createNewObject", e.getMessage());
}
return null;
}
@Override
public <S> BaseDataEditTable createChildTable( VSMCMain main, Role role, List<S> list, Class child, ItemClickListener listener )
{
if ( child.isAssignableFrom(RoleOption.class))
return RoleOptionTable.createTable(main, role, (List) list, listener, roleOptionEntries);
return null;
}
}
| true |
a1f9570e8cee048c19f9f649a1773119144e933a | Java | cs-au-dk/streamliner | /src/main/java/dk/casa/streamliner/stream/Stream.java | UTF-8 | 894 | 2.765625 | 3 | [] | no_license | package dk.casa.streamliner.stream;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collector;
public interface Stream<V> {
/* Functions that return new streams */
<U> Stream<U> map(Function<? super V, ? extends U> f);
Stream<V> filter(Predicate<? super V> p);
<U> Stream<U> flatMap(Function<? super V, ? extends Stream<? extends U>> f);
Stream<V> peek(Consumer<? super V> f);
Stream<V> limit(long maxSize);
/* Terminal operations */
void forEach(Consumer<? super V> c);
<U> U reduce(U initial, BiFunction<U, ? super V, U> r);
<R, A> R collect(Collector<? super V, A, R> collector);
Optional<V> findFirst();
default Optional<V> findAny() { return findFirst(); }
default int count() {
return reduce(0, (x, y) -> x + 1);
}
} | true |
26e224287e9a3ece67d5b7c0fee3ebef8a9c7f96 | Java | 101companies/101repo | /contributions/javaTree/org/softlang/company/Employee.java | UTF-8 | 1,465 | 2.984375 | 3 | [
"MIT"
] | permissive | package org.softlang.company;
import java.io.Serializable;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* An employee has a salary and some person information
*
*/
public class Employee extends Basic implements Serializable {
private static final long serialVersionUID = -210889592677165250L;
private String name;
private String address;
private double salary;
private DefaultMutableTreeNode treeNode;
private boolean manager = false;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public void setManager(boolean m) {
this.manager = m;
}
/**
* This method returns the name for the tree-view.
*/
@Override
public String toString(){
String treeName = this.getName();
if (manager) {
return treeName + " (Manager)";
}
return treeName;
}
public void setTreeNode(DefaultMutableTreeNode treeNode) {
this.treeNode = treeNode;
}
public DefaultMutableTreeNode getTreeNode() {
return treeNode;
}
/*
* (non-Javadoc)
* @see org.softlang.company.Basic#isEmployee()
*/
@Override
public boolean isEmployee() {
return true;
}
}
| true |
5b7fe8a14c9cc4a901973051f4e3257789f98c49 | Java | ttt9912/prospring5 | /ch12-remoting/springboot-httpinvoker/server/src/main/java/ch12/httpinvoker/server/service/SingerServiceImpl.java | UTF-8 | 2,100 | 2.25 | 2 | [] | no_license | package ch12.httpinvoker.server.service;
import ch12.httpinvoker.api.element.SingerApiElement;
import ch12.httpinvoker.api.service.SingerService;
import ch12.httpinvoker.server.data.Singer;
import ch12.httpinvoker.server.data.SingerRepository;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.util.List;
import java.util.stream.Collectors;
@DependsOn("conversionService")
@Service("singerService")
@Transactional
public class SingerServiceImpl implements SingerService {
@Autowired
private SingerRepository singerRepository;
@Autowired
private ConversionService conversionService;
@Override
@Transactional(readOnly = true)
public List<SingerApiElement> findAll() {
return Lists.newArrayList(singerRepository.findAll()).stream()
.map(entity -> conversionService.convert(entity, SingerApiElement.class))
.collect(Collectors.toList());
}
@Override
@Transactional(readOnly = true)
public List<SingerApiElement> findByFirstName(String firstName) {
return singerRepository.findByFirstName(firstName).stream()
.map(entity -> conversionService.convert(entity, SingerApiElement.class))
.collect(Collectors.toList());
}
@Override
@Transactional(readOnly = true)
public SingerApiElement findById(Long id) {
final Singer entity = singerRepository.findById(id).get();
return conversionService.convert(entity, SingerApiElement.class);
}
@Override
public SingerApiElement save(SingerApiElement singer) {
throw new NotImplementedException();
}
@Override
public void delete(SingerApiElement singer) {
throw new NotImplementedException();
}
}
| true |
c8f63d5ba2213ef034809d797ea23892346ac7a9 | Java | santosh760/YashProjectDemo | /oneToManyDemo/src/main/java/com/yash/oneToManyDemo/daoimpl/EmployeeDaoImpl.java | UTF-8 | 1,787 | 2.28125 | 2 | [] | no_license | package com.yash.oneToManyDemo.daoimpl;
import java.util.List;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.yash.oneToManyDemo.dao.EmployeeDao;
import com.yash.oneToManyDemo.domain.Employee;
import com.yash.oneToManyDemo.domain.Project;
@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao {
@Autowired
HibernateTemplate hibernateTemplate;
public void addEmployee(Employee employee) {
Session session = hibernateTemplate.getSessionFactory().openSession();
try {
session.getTransaction().begin();
session.save(employee);
System.out.println("Project Saved "+employee.getEmpId()+"------------*****************");
System.out.println("saved...");
session.getTransaction().commit();
hibernateTemplate.flush();
} catch (Exception e) {
System.out.println("Exception Occured " + e);
}
}
public void deleteEmployee(int Id) {
Session session = hibernateTemplate.getSessionFactory().openSession();
try {
session.getTransaction().begin();
Employee employee = session.get(Employee.class, Id);
session.delete(employee);
System.out.println("deleted...");
session.getTransaction().commit();
hibernateTemplate.flush();
} catch (Exception e) {
System.out.println("Exception Occured " + e);
}
}
public List<Employee> showAllEmployee() {
return hibernateTemplate.loadAll(Employee.class);
}
public void searchById(int Id) {
// TODO Auto-generated method stub
}
public void updateProject(Employee employee) {
// TODO Auto-generated method stub
}
}
| true |
ff971d118c0a2a59d07aeace61100b91f8714703 | Java | pvelado/Java-Examples | /prereq_practice/src/practice/loops/ForLoopsPractice.java | UTF-8 | 713 | 4.03125 | 4 | [] | no_license | package practice.loops;
public class ForLoopsPractice {
public static void main(String[] args) {
String name = "Thisisateststring";
// prints i 10 times
for (int i = 0; i < 10; i++) {
System.out.println("i: " + i);
}
// prints all the characters of name string
for (int i = 0; i < name.length(); i++) {
System.out.println("char: " + name.charAt(i));
}
// prints all the characters of name string starting from the last character
for (int i = name.length() - 1; i >= 0; i--) {
System.out.println("char: " + name.charAt(i));
}
// Prints all the numbers that are even between 0 - 100
for(int i = 0; i <= 100; i += 2) {
System.out.println(i);
}
}
}
| true |
135cb671443c67cbf9741e3d649a63178647e874 | Java | paotaopeng/uexHtm | /taskwalker/src/main/java/com/wisemen/taskwalker/call/RealCall.java | UTF-8 | 5,292 | 2.5 | 2 | [] | no_license | package com.wisemen.taskwalker.call;
import com.wisemen.taskwalker.TaskWalker;
import com.wisemen.taskwalker.callback.AbsCallback;
import com.wisemen.taskwalker.callback.AbsCallbackWrapper;
import com.wisemen.taskwalker.model.Response;
import com.wisemen.taskwalker.request.BaseRequest;
import com.wisemen.taskwalker.utils.NetStatusTool;
import java.io.IOException;
import java.net.SocketTimeoutException;
import okhttp3.Request;
import okhttp3.RequestBody;
public class RealCall<T> implements Call<T> {
private volatile boolean canceled;
private boolean executed;
private BaseRequest baseRequest;
private okhttp3.Call rawCall;
private AbsCallback<T> mCallback;
private int currentRetryCount;
public RealCall(BaseRequest baseRequest) {
this.baseRequest = baseRequest;
}
@Override
public boolean execute(AbsCallback<T> callback) {
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
}
mCallback = callback;
if (mCallback == null) mCallback = new AbsCallbackWrapper<>();
if(!NetStatusTool.getInstance().isWifi() && !baseRequest.isIndependentOfNetStatus() &&
(null == mCallback || !mCallback.onBefore(baseRequest))) {
return false;
}
//构建请求
RequestBody requestBody = baseRequest.generateRequestBody();
final Request request = baseRequest.generateRequest(baseRequest.wrapRequestBody(requestBody));
rawCall = baseRequest.generateCall(request);
if (canceled) {
rawCall.cancel();
}
currentRetryCount = 0;
rawCall.enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
if (e instanceof SocketTimeoutException && currentRetryCount < baseRequest.getRetryCount()) {
//超时重试
currentRetryCount++;
okhttp3.Call newCall = baseRequest.generateCall(call.request());
newCall.enqueue(this);
} else {
mCallback.parseError(call, e);
if (!call.isCanceled()) {
sendFailResultCallback(call, null, e);
}
}
}
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
int responseCode = response.code();
if (responseCode == 404 || responseCode >= 500) {
sendFailResultCallback(call, response, new Exception("服务器数据异常!"));
return;
}
try {
Response<T> parseResponse = parseResponse(response);
T data = parseResponse.body();
//请求成功回调
sendSuccessResultCallback(data, call, response);
} catch (Exception e) {
sendFailResultCallback(call, response, e);
}
}
});
return true;
}
/** 失败回调,发送到主线程 */
@SuppressWarnings("unchecked")
private void sendFailResultCallback(final okhttp3.Call call, final okhttp3.Response response, final Exception e) {
TaskWalker.getInstance().getDelivery().post(new Runnable() {
@Override
public void run() {
mCallback.onError(call, response, e); //请求失败回调
mCallback.onAfter(null, e); //请求结束回调
}
});
}
/** 成功回调,发送到主线程 */
private void sendSuccessResultCallback(final T t, final okhttp3.Call call, final okhttp3.Response response) {
TaskWalker.getInstance().getDelivery().post(new Runnable() {
@Override
public void run() {
mCallback.onSuccess(t, call, response); //请求成功回调
mCallback.onAfter(t, null); //请求结束回调
}
});
}
@Override
public Response<T> execute() throws Exception {
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
}
okhttp3.Call call = baseRequest.getCall();
if (canceled) {
call.cancel();
}
return parseResponse(call.execute());
}
private Response<T> parseResponse(okhttp3.Response rawResponse) throws Exception {
T body = (T) baseRequest.getConverter().convertSuccess(rawResponse);
return Response.success(body, rawResponse);
}
@Override
public boolean isExecuted() {
return executed;
}
@Override
public void cancel() {
canceled = true;
if (rawCall != null) {
rawCall.cancel();
}
}
@Override
public boolean isCanceled() {
return canceled;
}
@Override
public Call<T> clone() {
return new RealCall<>(baseRequest);
}
@Override
public BaseRequest getBaseRequest() {
return baseRequest;
}
} | true |
5c03d38ac86933724c7dc501626bca0c93998e10 | Java | RemyBaroukh/BurgerQuiz | /BurgerQuiz/app/src/main/java/app/rems/burgerquiz/game/BurgerVariables.java | UTF-8 | 364 | 1.609375 | 2 | [] | no_license | package app.rems.burgerquiz.game;
/**
* Created by remsd_000 on 01/04/2015.
*/
public class BurgerVariables {
public enum Equipe {
MAYO,
KETCHUP
}
public enum Epreuve {
MAINMENU,
NUGGETS,
SELOUPOIVRE,
MENUS,
ADDITION,
BURGERDELAMORT
}
public static BurgerQuiz burgerQuiz;
}
| true |
973d0aed78f21611b76c03b2d696f34739159126 | Java | carloscgta/newVenturesPipeline | /src/main/java/agt/psrm/appModules/appModules_NIFSearch/pageObjects/test/utility/Utils.java | UTF-8 | 5,088 | 2.3125 | 2 | [] | no_license | package agt.psrm.appModules.appModules_NIFSearch.pageObjects.test.utility;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Utils {
public static WebDriver driver = null;
public static ChromeOptions chromeOptions;
public static WebDriver OpenBrowser(int iTestCaseRow) throws Exception{
String sBrowserName;
try{
sBrowserName = ExcelUtils.getCellData(iTestCaseRow, Constant.Col_Browser);
if(sBrowserName.equals("Chrome")){
/*/usr/bin/chromedriver
* usr/bin/chromedriver
* C:/projetos/Automation/Driver/chromedriver.exe
* */
System.setProperty("webdriver.chrome.driver","/usr/bin/chromedriver");
chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("window-size=1980,860");
driver = new ChromeDriver(chromeOptions);
Log.info("New driver instantiated");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Log.info("Implicit wait applied on the driver for 10 seconds");
driver.get(Constant.URL);
Log.info("Web application launched successfully");
driver.manage().window().maximize();
}
}catch (Exception e){
Log.error("Class Utils | Method OpenBrowser | Exception desc : "+e.getMessage());
}
return driver;
}
//By Carlos
public static WebDriver OpenBrowser02() throws Exception{
try{
// C:\projetos\Automation\Driver
System.setProperty("webdriver.chrome.driver","C:/projetos/Automation/Driver/chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
driver = new ChromeDriver(chromeOptions);
Log.info("New driver instantiated");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Log.info("Implicit wait applied on the driver for 10 seconds");
driver.get(Constant.URL);
Log.info("Web application launched successfully");
driver.manage().window().maximize();
}catch (Exception e){
Log.error("Class Utils | Method OpenBrowser | Exception desc : "+e.getMessage());
}
return driver;
}
public static String currentDate() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDateTime now = LocalDateTime.now();
String date = dtf.format(now);
return date;
}
public static String getTestCaseName(String sTestCase)throws Exception{
String value = sTestCase;
try{
int posi = value.indexOf("@");
value = value.substring(0, posi);
posi = value.lastIndexOf(".");
value = value.substring(posi + 1);
return value;
}catch (Exception e){
Log.error("Class Utils | Method getTestCaseName | Exception desc : "+e.getMessage());
throw (e);
}
}
public static void waitForElement(WebElement element)
{
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(element));
}
public static void waitForVisibleElement(WebElement element){
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOf(element));
}
public static void takeScreenshot(WebDriver driver, String sTestCaseName) throws Exception{
try{
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(Constant.Path_ScreenShot + sTestCaseName+System.currentTimeMillis() +"-Evidencia.jpg"));
} catch (Exception e){
Log.error("Class Utils | Method takeScreenshot | Exception occured while capturing ScreenShot : "+e.getMessage());
throw new Exception();
}
}
public static void takeScreenshot02(WebDriver driver) throws Exception{
try{
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(Constant.Path_ScreenShot+System.currentTimeMillis() +"Test-Evidencia.jpg"));
} catch (Exception e){
Log.error("Class Utils | Method takeScreenshot | Exception occured while capturing ScreenShot : "+e.getMessage());
throw new Exception();
}
}
public static void ScrollBar(int size) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,"+size+")");
}
public static void newWindowSwitch() {
String parantWindow = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
for(String currentWindow : allWindows) {
if (!currentWindow.equals(parantWindow)) {
driver.switchTo().window(currentWindow);
}
}
}
public static void ParantWindowSwitch(String parant) {
driver.switchTo().window(parant);
}
}
| true |
cedfd30e87fc19495aa78f5923f46681c98ea4fd | Java | jiangflong/common | /src/main/java/cn/feilong/common/utils/RedisUtils.java | UTF-8 | 11,306 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | package cn.feilong.common.utils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* redis的工具类
*
* @author chenjiabing
*/
public class RedisUtils{
private RedisTemplate<String, Object> template;
public final RedisTemplate<String, Object> getTemplate() {
return template;
}
public final void setTemplate(RedisTemplate<String, Object> template) {
this.template = template;
}
/**
* 使用redis事务
* @param exec 使用者需要实现Exec接口
* @return
* @throws Exception
*/
public Object execu(Exec exec) throws Exception {
this.template.setEnableTransactionSupport(true);
try {
this.template.multi();
Object result = exec.execu();
this.template.exec();
this.template.setEnableTransactionSupport(false);
return result;
}finally{
this.template.setEnableTransactionSupport(false);
}
}
protected interface Exec {
public Object execu() throws Exception;
}
public RedisUtils(RedisTemplate<String, Object> template) {
this.template = template;
}
/**
* 向redis中添加对象,string类型的对象
*
* @param object 需要存储的对象
* @param key 存储的键
* @throws Exception 出现异常信息
*/
public void addStringObject(String key, Object object) throws Exception {
this.addStringObject(key, object, null, null);
}
/**
* 添加指定的key到Redis中
*
* @param key 指定的Ke
* @param object 数据
* @param timeout 过期时间
* @param unit 时间单位
* @throws Exception
*/
public void addStringObject(String key, Object object, Long timeout, TimeUnit unit) throws Exception {
if (timeout == null) {
template.opsForValue().set(key, object);
} else {
template.opsForValue().set(key, object, timeout, unit);
}
}
/**
* 根据键值从redis中获取对象 string类型的对象
*
* @param key key
* @return 返回对象
* @throws Exception 抛出的异常
*/
public Object getStringObject(String key) throws Exception {
Object object = template.opsForValue().get(key);
return object;
}
/**
* 批量删除对象
*
* @param keys key的集合
*/
public void deleteObjectBatch(Collection<String> keys) throws Exception {
template.delete(keys);
}
/**
* 根据key更新值
*
* @param key key
* @param object value
* @throws Exception 异常信息
*/
public void modifyStringObject(String key, Object object) throws Exception {
this.addStringObject(key, object);
}
/**
* 添加数据在Hash中
*
* @param key key
* @param field 指定的域
* @param object 数据
*/
public void addHashObject(String key, String field, Object object) throws Exception {
template.opsForHash().put(key, field, object);
}
/**
* 向hash中添加数据,并且设置过期的时间
*
* @param key key
* @param field 域
* @param object 数据
* @param timeout 过期时间
* @param unit 单位
* @throws Exception
*/
public void addHashObject(String key, String field, Object object, Long timeout, TimeUnit unit) throws Exception {
this.addHashObject(key, field, object);
this.setExpireTimeForKey(key, timeout, unit);
}
/**
* 批量添加数据到指定的hash中
*
* @param key key
* @param map 需要添加的数据 Map<field,value>
* @param expireTime 过期时间,单位秒,如果为null,默认永远不过期
*/
public void addHashObjectBatch(String key, Map<Object, Object> map, Long expireTime, TimeUnit unit) throws Exception {
template.opsForHash().putAll(key, map);
this.setExpireTimeForKey(key, expireTime, unit);
}
/**
* 为指定的key设置过期时间
*
* @param key key
* @param timeout 过期时间
* @param unit 指定时间的单位
*/
public void setExpireTimeForKey(String key, Long timeout, TimeUnit unit) {
if (timeout != null) {
template.expire(key, timeout, unit); //设置过期时间
}
}
/**
* 删除指定的key
*
* @param key
*/
public void deleteKey(String key){
template.delete(key);
}
/**
* 根据key删除指定的值
*
* @param key key
* @throws Exception 异常信息
*/
public void deleteObject(String key) throws Exception {
template.delete(key);
}
/**
* 根据key,field从hash中获取数据
*
* @param key
* @param field
* @return Object对象
*/
public Object getHashObject(String key, String field) {
return template.opsForHash().get(key, field);
}
/**
* 根据key和fields批量获取其中的数据
*
* @param key key
* @param fields {@link Collection<Object> }
* @return
* @throws Exception
*/
public List<Object> getHashObjectBatch(String key, Collection<Object> fields) {
return template.opsForHash().multiGet(key, fields);
}
/**
* 根据key 获取全部数据
*
* @param key
* @return
*/
public Map<Object, Object> getHashObjectBatch(String key) {
return template.opsForHash().entries(key);
}
/**
* 修改指定key,field中的数据
*
* @param key
* @param field
* @param object
*/
public void modifyHashObject(String key, String field, Object object) throws Exception {
this.addHashObject(key, field, object);
}
/**
* 删除指定的key和field中的数据
*
* @param key
* @param field
*/
public void deleteHashObject(String key, String field) throws Exception {
this.deleteHashObjectBatch(key, new Object[]{field});
}
/**
* 批量删除指定key和fields的数据
*
* @param key key
* @param fields 需要删除的域
* @throws Exception
*/
public void deleteHashObjectBatch(String key, Object[] fields) throws Exception {
template.opsForHash().delete(key, fields);
}
/**
* 添加数据到ZSet中
*
* @param key 指定的key
* @param value 指定的value
* @param score 指定的score
*/
public void addZSetObject(String key, String value, double score) throws Exception {
template.opsForZSet().add(key, value, score);
}
/**
* 批量添加数据到Zset中
*
* @param key 指定的key
* @param typedTuple {@link TypedTuple}
*/
public void addZSetObjectBatch(String key, Set<TypedTuple<Object>> typedTuple) {
template.opsForZSet().add(key, typedTuple);
}
/**
* 根据key获取start--end之间的数据
*
* @param key 指定key
* @param start 开始索引,从0开始
* @param end 结束索引
* @return {@link Set<Object>}
*/
public Set<Object> getZSetObject(String key, Long start, Long end) {
return template.opsForZSet().range(key, start, end);
}
/**
* 根据Score的范围获取数据
*
* @param key 指定的key值
* @param min score的最小值
* @param max score的最大值
* @return {@link Set<Object>}
*/
public Set<Object> getZSetObjectRangeByScore(String key, Long min, Long max) {
return template.opsForZSet().rangeByScore(key, min, max);
}
/**
* 根据Score的范围获取数据,分页获取
*
* @param key 指定的key
* @param min 最小值
* @param max 最大值
* @param offset 偏移量
* @param count 数量
* @return
*/
public Set<Object> getZSetObjectRangeByScore(String key, Long min, Long max, Long offset, Long count) {
return template.opsForZSet().rangeByScore(key, min, max, offset, count);
}
/**
* 向List中添加元素,从表头添加
*
* @param key
* @param value
*/
public void addLeftListObject(String key, Object value) {
template.opsForList().leftPush(key, value);
}
/**
* 向List中添加元素,从表尾添加
*
* @param key
* @param value
*/
public void addRightListObject(String key, Object value) {
template.opsForList().rightPush(key, value);
}
/**
* 向List中添加元素,从表头添加
*
* @param key
* @param value
* @param timeOut 过期时间
* @param unit 单位
*/
public void addLeftListObject(String key, Object value, Long timeOut, TimeUnit unit) {
template.opsForList().leftPush(key, value);
this.setExpireTimeForKey(key, timeOut, unit); //设置过期时间
}
/**
* 批量从表头添加数据
*
* @param key
* @param timeout : 过期时间 如果为null表示永久不过期
* @param unit : 时间单位
* @param values {@link Collection<Object>}
*/
public void addLeftListObjectBatch(String key, Collection<Object> values, Long timeout, TimeUnit unit) {
template.opsForList().leftPushAll(key, values);
this.setExpireTimeForKey(key, timeout, unit);
}
/**
* 批量从表尾添加数据
*
* @param key
* @param values {@link Collection<Object>}
*/
public void addRigthListObjectBatch(String key, Collection<Object> values, Long timeout, TimeUnit unit) {
template.opsForList().rightPushAll(key, values);
this.setExpireTimeForKey(key, timeout, unit);
}
/**
* 获取指定范围内的数据
*
* @param key
* @param i 开始的索引 从0开始
* @param j 结束的索引,-1 表示结尾
* @return {@link List<Object>}
*/
public List<Object> getRangeListObject(String key, int i, int j) {
return template.opsForList().range(key, i, j);
}
/**
* 将Collection<?extend Object>的集合转换成Collection<Object>
*
* @param list 需要转换的集合
* @return Collection<Object>
* @throws Exception
*/
public static Collection<Object> convertToCollection(Collection<? extends Object> list) throws Exception {
List<Object> arrayList = new ArrayList<Object>(list.size());
for (Object object : list) {
arrayList.add(object);
}
return arrayList;
}
/**
* 将指定的List集合中的元素逆向
*
* @param objects List<? extends Object>
*/
public static void reverse(List<? extends Object> objects) {
Collections.reverse(objects);
}
/**
* 删除所有的键值
*/
public void delteAllKeys() {
Set<String> keys = template.keys("*"); //获取所有的key
template.delete(keys); //删除所有的键值
}
} | true |
24467a4eaf99b343ba7a2911e2fa77aea7ea18f8 | Java | abourn/lecture13-services | /app/src/main/java/edu/uw/servicedemo/CountingService.java | UTF-8 | 2,327 | 2.984375 | 3 | [] | no_license | package edu.uw.servicedemo;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
/*
There is a difference between started services and bound services.
This service here is a startService. What is important is the
onStartCommand() function. That takes in what intent we send to this
background thread. IntentService has already filled in a bunch of details
in the onStartCommand(). Basically works as a queueing service, which keeps
track of all of the intents that have been sent to it.
*/
public class CountingService extends IntentService {
public static final String TAG = "CountingService";
private int i;
private Handler mHandler;
public CountingService() {
super("CountingService");
}
@Override
public void onCreate() {
super.onCreate();
mHandler = new Handler();
}
// returns an int, which is a flag that says what service should do in the
// case that it is killed by system.
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
Log.v(TAG, "Received: " + intent.toString());
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
// run in the background
for (i = 0; i < 10; i++) {
Log.v(TAG, "count: " + i);
// You can't display UI elements from the background thread, but you can
// communicate from this background thread to the main UI thread. do this with handler
mHandler.post(new Runnable() {
@Override
public void run() {
// From the background thread, let's make a class that does a little UI work...
// Handler will send this to main thread
Toast.makeText(CountingService.this, "" + i, Toast.LENGTH_SHORT).show();
}
});
try {
Thread.sleep(5000); // hey thread, don't do anything for 5 seconds. Just wait.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} | true |
342d65f4cd712a450f4d2e70350ea0ea7a2f312e | Java | CosminRadu/AndroidBinding | /plugin/AndroidBinding.Plugin.ABS/src/gueei/binding/plugin/abs/menu/viewAttributes/DataSource.java | UTF-8 | 607 | 2.46875 | 2 | [
"MIT"
] | permissive | package gueei.binding.plugin.abs.menu.viewAttributes;
import gueei.binding.ViewAttribute;
import gueei.binding.plugin.abs.BindableOptionsMenu;
public class DataSource extends ViewAttribute<BindableOptionsMenu, Object> {
public DataSource(BindableOptionsMenu view) {
super(Object.class, view, "dataSource");
}
private Object mSource = null;
@Override
protected void doSetAttributeValue(Object newValue) {
if (mSource==null || !mSource.equals(newValue)){
mSource = newValue;
getHost().invalidate();
}
}
@Override
public Object get() {
return mSource;
}
}
| true |
07e7094ba485f52087a2fd66076a3eb4ac3b6eb3 | Java | Moonseonhyeon/jsp-shop | /src/com/shop/apparel/action/user/UserCartDeleteAction.java | UTF-8 | 651 | 2.265625 | 2 | [] | no_license | package com.shop.apparel.action.user;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.shop.apparel.action.Action;
import com.shop.apparel.repository.UserRepositroy;
public class UserCartDeleteAction implements Action{
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int cartId = Integer.parseInt(request.getParameter("cartId"));
UserRepositroy userRepositroy = UserRepositroy.getInstance();
userRepositroy.deleteCartId(cartId);
}
}
| true |
de15cec4a98372e119b4885afa9ef5d2a0bc9659 | Java | hvarolerdem/DSL_for_constraint_solver | /Parser.java | UTF-8 | 3,875 | 2.796875 | 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 apconstraintsolver;
/**
*
* @author HüseyinVarol
*/
import java.io.*;
import java.util.ArrayList;
import jdk.nashorn.internal.runtime.regexp.joni.exception.SyntaxException;
public class Parser {
private Scanner scanner;
private Type token;
private void match(Type t) throws SyntaxException{
if(token!=t) throw new SyntaxException("matching wrong because of "+token);
token=scanner.nextToken();
}
public Program parse(BufferedReader r) throws SyntaxException
{
scanner = new Scanner(r);
token = scanner.nextToken();
ArrayList<VariableValues> varList =parseVars(new ArrayList<>());
ArrayList<Tuple> posRels = parsePosRel();
ArrayList<Tuple> negRels = parseNegRel();
match(Type.EOF);
//return new Program(varList,posrel,negrel);
return new Program(varList, posRels, negRels);
}
private ArrayList<VariableValues> parseVars(ArrayList<VariableValues> varList) throws SyntaxException{
switch(token){
case OPEN_CURLY_BRACKET: //Parse until the positive relations start
return varList;
default:
varList.add(parseVar());
return parseVars(varList);
}
}
private VariableValues parseVar() throws SyntaxException{
VariableValues var = new VariableValues(scanner.getToken());
match(Type.VALUE); // it is actually a variable
match(Type.EQ);
match(Type.OPEN_CURLY_BRACKET);
var.setPossibleValues(parseValue(new ArrayList<>()));
match(Type.CLOSE_CURLY_BRACKET);
return var;
}
private ArrayList<Variable> parseValue(ArrayList<Variable> possibleValues) throws SyntaxException{
switch(token){
case CLOSE_CURLY_BRACKET:
return possibleValues;
default:
Variable val = new Variable(scanner.getToken());
match(Type.VALUE);
if(token == Type.COMMA) match(Type.COMMA);
possibleValues.add(val);
return parseValue(possibleValues); // it is recursive
}
}
private ArrayList<Tuple> parsePosRel() throws SyntaxException{
match(Type.OPEN_CURLY_BRACKET);
ArrayList<Tuple> posRels = parseTuples(new ArrayList<Tuple>());
match(Type.CLOSE_CURLY_BRACKET);
return posRels;
}
private ArrayList<Tuple> parseNegRel() throws SyntaxException{
match(Type.EXCLAMATION);
match(Type.OPEN_CURLY_BRACKET);
ArrayList<Tuple> negRels = parseTuples(new ArrayList<Tuple>());
match(Type.CLOSE_CURLY_BRACKET);
return negRels;
}
private ArrayList<Tuple> parseTuples(ArrayList<Tuple> tupleList) throws SyntaxException{
switch(token){
case CLOSE_CURLY_BRACKET: //Parse until the closing curly bracket
return tupleList;
default:
tupleList.add(parseTuple());
if(token == Type.COMMA)
match(Type.COMMA);
return parseTuples(tupleList);
}
}
private Tuple parseTuple() throws SyntaxException {
match(Type.OPEN_BRACKET);
String val1 = scanner.getToken();
match(Type.VALUE);
match(Type.COMMA);
String val2 = scanner.getToken();
match(Type.VALUE);
match(Type.CLOSE_BRACKET);
return new Tuple(val1,val2);
}
}
| true |