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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f28b415728243801d97dc07cd96b8c9cb88e6085 | Java | allazotova/Homework4OOP | /src/com/aqacourses/test/student/StudentPed.java | UTF-8 | 2,363 | 3.0625 | 3 | [] | no_license | package com.aqacourses.test.student;
import com.aqacourses.test.interfaces.ParseFileInterface;
import com.aqacourses.test.interfaces.WriteToDbInterface;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class StudentPed extends Student implements ParseFileInterface, WriteToDbInterface {
private FileWriter fileWriter;
private PrintWriter printWriter;
@Override
public List<String> parseFile(String pathToFile) {
List<String> data = new ArrayList<>();
try(Scanner scanner = new Scanner(new File(pathToFile));) {
String name = scanner.nextLine();
if (!name.isEmpty()) {
data.add(name);
}
String surname = scanner.nextLine();
if (!surname.isEmpty()) {
data.add(surname);
}
String age = scanner.nextLine();
if (!age.isEmpty()) {
data.add(age);
}
String sex = scanner.nextLine();
if (!sex.isEmpty()) {
data.add(sex);
}
} catch (Exception e){
e.printStackTrace();
}
return data;
}
@Override
public void writeToDb(List<String> data) {
try {
openConnectionToDb();
if (validateData(data)) {
for (String datum : data) {
printWriter.println(getDate() + " - " + datum);
}
printWriter.print("=====================\n");
System.out.println("All data is written to MS SQL DB");
closeConnectionToDb();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Open connection to MySQL DB
*/
private void openConnectionToDb() throws IOException {
String path = "/Users/alla/Documents/student.txt";
fileWriter = new FileWriter(path);
printWriter = new PrintWriter(fileWriter);
}
/**
* CLose connection to MySQL DB
*/
private void closeConnectionToDb() throws IOException {
printWriter.close();
fileWriter.close();
System.out.println("Close connection to MS SQL DB");
}
}
| true |
357c0e1f764d21fee64f5dc27a8cdc2ac3afecfc | Java | RRugnA/Gerenciamento-Ninja | /fatec.sgmn/dao/MissaoDAO.java | UTF-8 | 3,197 | 2.84375 | 3 | [] | no_license | package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.Missao;
public class MissaoDAO implements IDAO<Missao> {
Connection connection;
public MissaoDAO(Connection connection) {
this.connection = connection;
}
@Override
public void create(Missao missao) {
String sql = "insert into missions(mis_name, mis_rank, mis_pay, mis_desc, mis_team_id) values (?, ?, ?, ?, ?)";
try(PreparedStatement stm = connection.prepareStatement(sql)){
stm.setString(1, missao.getName());
stm.setString(2, missao.getRank());
stm.setDouble(3, missao.getPay());
stm.setString(4, missao.getDesc());
stm.setInt(5, missao.getTeamId());
System.out.println("Registrado no banco com sucesso!");
stm.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public List<Missao> read() {
List<Missao> missoes = new ArrayList<Missao>();
String sql2 = "select m.mis_id, m.mis_name, m.mis_rank, m.mis_pay, m.mis_desc, t.tea_lider from missions as m join teams as t on m.mis_team_id = t.tea_id order by m.mis_id";
try(PreparedStatement stm = connection.prepareStatement(sql2)){
stm.execute();
try(ResultSet rst = stm.getResultSet()){
while(rst.next()) {
Missao missao = new Missao(rst.getInt(1), rst.getString(2), rst.getString(3), rst.getDouble(4), rst.getString(5), rst.getString(6));
missoes.add(missao);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return missoes;
}
@Override
public void update(Missao missao) {
String sql = "Update missions set mis_name = ?, mis_rank = ?, mis_pay = ?, mis_desc = ?, mis_team_id = ? where mis_id = ?";
try(PreparedStatement stm = connection.prepareStatement(sql)){
stm.setString(1, missao.getName());
stm.setString(2, missao.getRank());
stm.setDouble(3, missao.getPay());
stm.setString(4, missao.getDesc());
stm.setInt(5, missao.getTeamId());
stm.setInt(6, missao.getId());
System.out.println("Alterado no banco com sucesso!");
stm.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void delete(Missao missao) {
String sql = "Delete from missions where mis_id = ?";
try(PreparedStatement stm = connection.prepareStatement(sql)){
stm.setInt(1, missao.getId());
stm.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public Missao getId(Missao missao) {
String sql = "Select mis_id, mis_name, mis_rank, mis_pay, mis_desc from missions where mis_id = ?";
try(PreparedStatement stm = connection.prepareStatement(sql)){
stm.setInt(1, missao.getId());
stm.execute();
try(ResultSet rst = stm.getResultSet()){
if( rst.next()) {
missao.setId(rst.getInt(1));
missao.setName(rst.getString(2));
missao.setRank(rst.getString(3));
missao.setPay(rst.getDouble(4));
missao.setDesc(rst.getString(5));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return missao;
}
}
| true |
e3a83319dad51e19c5e7af257b7979b97c4c5499 | Java | prachib28/SeleniumClass | /src/Screenshot/Ass1.java | UTF-8 | 1,003 | 2.203125 | 2 | [] | no_license | package Screenshot;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.server.handler.CaptureScreenshot;
public class Ass1 {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver","./software/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.myntra.com/");
TakesScreenshot t = (TakesScreenshot) driver;
File src= t.getScreenshotAs(OutputType.FILE);
File dest = new File("./photo/myntra.png");
FileUtils.copyFile(src,dest);
driver.close();
}
}
//For Screenshot need Fileutils class which can be ccessed after importig jar :commons_io
//download apache utils link:
//https://mvnrepository.com/artifact/commons-io/commons-io/2.6
| true |
ee4579a8b6c5e2b2ada9e1a3f49c1bd0d60f41dc | Java | bryan181/JuegoDamas | /src/tablero/Ficha.java | UTF-8 | 2,693 | 2.921875 | 3 | [] | no_license | package tablero;
public class Ficha {
private boolean esNegra;
private boolean debeAscender;
// private int x,y;
private Coordenada posicion;
private char celda = '░';
private Tablero tablero;
//private char celdaColor = '█';
// █▓
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_YELLOW = "\u001B[33m";
private String id;
public Coordenada getCoordenada(){
return this.posicion;
}
public boolean getEsNegra() {
return esNegra;
}
public String getCaracter() {
String res = (esNegra) ? "" + ANSI_RED + celda : "" + ANSI_YELLOW + celda;
return res;
}
public Ficha(boolean esNegra, String id, Coordenada posicion, boolean debeAscender, Tablero tablero) {
this.debeAscender = debeAscender;
this.tablero = tablero;
this.posicion = posicion;
this.esNegra = esNegra;
this.id = id;
}
public String getId() {
return id;
}
public Coordenada[] getMovimientosPosibles() {
Coordenada[] res = new Coordenada[4];
int movY = (debeAscender) ? 1 : -1;
int cont = this.evaluarMovimiento(-1, movY, this.posicion, res, 0);
cont = this.evaluarMovimiento(+1, movY, this.posicion, res, cont);
/*
System.out.println("Movimientos posibles - pos ini " + this.posicion.toString());
for (int i = 0; i < res.length; i++) {
if (res[i] != null) {
System.out.println(res[i].toString());
}
}
*/
if (cont == 0){
res = null;
}
return res;
}
public void setCoordenada(int x, int y){
this.posicion.setX(x);
this.posicion.setY(y);
}
private int evaluarMovimiento(int movX, int movY, Coordenada pos, Coordenada[] res, int indice){
Coordenada evaluando = new Coordenada(pos.getX() + movX, pos.getY() + movY);
Celda tmp = tablero.getCelda(evaluando);
if (tmp != null) {
if (!tmp.ocupadaPorFicha()) {
res[indice] = evaluando;
indice++;
} else {
if (tmp.getFicha().getEsNegra() != this.esNegra) {
Coordenada evaluando2 = new Coordenada(evaluando.getX() + movX, evaluando.getY() +movY);
tmp = tablero.getCelda(evaluando2);
if (!tmp.ocupadaPorFicha()) {
res[indice] = evaluando2;
indice++;
}
}
}
}
return indice;
}
}
| true |
3bf2f1e7e9c7b85e5c17c46ebc04cbc39b1e8f57 | Java | thithuynguyen/Practice-selenium | /src/test/java/testcases/locateElements/CheckboxesTest.java | UTF-8 | 421 | 1.96875 | 2 | [] | no_license | package testcases.locateElements;
import org.openqa.selenium.support.How;
import static supports.Browser.*;
public class CheckboxesTest {
public static void main(String[] args) {
openBrowser("Chrome");
visit("https://the-internet.herokuapp.com/checkboxes");
check(How.XPATH, "*//form[@id='checkboxes']/input[1]");
uncheck(How.XPATH, "*//form[@id='checkboxes']/input[2]");
}
}
| true |
ee6e901e907a87f0c60c8d415eb97b12a06b4162 | Java | AntoineTaithe/angularDemoGitHub | /src/main/java/com/adaming/service/UtilisateurService.java | UTF-8 | 905 | 2.21875 | 2 | [] | no_license | package com.adaming.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.adaming.entitties.Utilisateur;
import com.adaming.repositories.UtilisateurRepository;
@Service
public class UtilisateurService implements IUtilisateurService{
@Autowired
UtilisateurRepository utilisateurRepository;
@Override
public Utilisateur save(Utilisateur utilisateur) {
// TODO Auto-generated method stub
return utilisateurRepository.save(utilisateur);
}
@Override
public void delete(Long id) {
utilisateurRepository.delete(id);
}
@Override
public List<Utilisateur> findAll() {
// TODO Auto-generated method stub
return utilisateurRepository.findAll();
}
@Override
public Utilisateur findOne(Long id) {
// TODO Auto-generated method stub
return utilisateurRepository.findOne(id);
}
}
| true |
627b9cd8c94772fe7c606dbf595b2754191dc0f1 | Java | Hd465784272/ThinkinJava4thEdition | /src/code/container/Splitting.java | UTF-8 | 844 | 3.3125 | 3 | [] | no_license | package code.container;
import java.util.Arrays;
public class Splitting {
public static String dream = "Five score years ago, a great American, "
+ "in whose symbolic shadow we stand today, signed the "
+ "Emancipation Proclamation. This momentous decree came as"
+ " a great beacon light of hope to millions of Negro slaves"
+ " who had been seared in the flames of withering injustice."
+ " It came as a joyous daybreak to end the long night of bad "
+ "captivity.";
public static void split(String regex){
System.out.println(Arrays.toString(dream.split(regex)));
}
public static void main(String args[]) {
split(" ");
// \\ : 我要插入一个正则表达式的反斜线\
// \W : 非单词字符;注意一定是大写的W
split("\\W+");
split("e\\W+");
}
}
| true |
1a85993a11bb4646a3ac466e33927f6231ebc989 | Java | yinyuxuan2016/springmvc | /src/main/java/org/emall/cn/model/project/User.java | UTF-8 | 1,909 | 2.46875 | 2 | [] | no_license | package org.emall.cn.model.project;
/**
* @Description
* @Author <a href="mailto:dongbiaozheng@ebnew.com">zhengdb</a>
* @Date 2016/9/22
*/
public class User implements java.io.Serializable {
private Integer id;
private String username;
private String password;
private String age;
private String tel;
private String sessionid;
// Constructors
/** default constructor */
public User() {
}
/** minimal constructor */
public User(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
/** full constructor */
public User(Integer id, String username, String password, String age, String tel, String sessionid) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.tel = tel;
this.sessionid = sessionid;
}
@Override
public String toString(){
return this.username + this.password;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAge() {
return this.age;
}
public void setAge(String age) {
this.age = age;
}
public String getTel() {
return this.tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getSessionid() {
return sessionid;
}
public void setSessionid(String sessionid) {
this.sessionid = sessionid;
}
}
| true |
1e70a9264da884495f3b30e7ded5daa9437751c6 | Java | satishs1693/Java_8_Problems | /src/StringClass/Lab495.java | UTF-8 | 503 | 3.03125 | 3 | [] | no_license | package StringClass;
public class Lab495 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str ="JLC ,java Learning Center .No in Java Traing and JAVA is popular la";
String rest[] = str.split("Java");
System.out.println(rest.length);
for (int i = 0; i < rest.length; i++) {
String st = rest[i];
System.out.println(i +"\t "+st);
}
String exp ="[A-Za-z0-9]*";
System.out.println("Satish".matches(exp));
}
}
| true |
4da375446f15dc51c27a4216f0fe0b20991e6428 | Java | keke0123/acorn-project | /Acorn_Project/src/main/java/com/acorn/project/users/service/UsersService.java | UTF-8 | 875 | 1.960938 | 2 | [] | no_license | package com.acorn.project.users.service;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import com.acorn.project.users.dto.UsersDto;
public interface UsersService {
//회원 정보를 추가하는 비즈니스 로직을 수행하는 메소드의 형태 정의
public void addUser(ModelAndView mView, UsersDto dto);
//로그인 처리를 하는 메소드
public Map<String,Object> validUser(HttpSession session, ModelAndView mView, UsersDto dto);
//아이디 사용가능 여부를 Map에 담아서 리턴하는 로직
public Map<String, Object> canUseId(String inputId);
//닉네임 사용가능 여부를 Map에 담아서 리턴하는 로직
public Map<String, Object> canUseNick(String inputNick);
//구글 로그인 처리
public void validGoogle(HttpSession session,ModelAndView mView);
}
| true |
21ac794e3234ca5f47098e7af93e9c4e4074c101 | Java | andrey-qlogic/google-api-java-client-services | /clients/1.27.0/google-api-services-healthcare/v1alpha/com/google/api/services/healthcare/v1alpha/model/GcsDataLocation.java | UTF-8 | 3,268 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.healthcare.v1alpha.model;
/**
* Google Cloud Storage location.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Healthcare API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GcsDataLocation extends com.google.api.client.json.GenericJson {
/**
* The gcs_uri must be in the format "gs://bucket/path/to/object". The gcs_uri may include
* wildcards in the "path/to/object" part to to indicate potential matching of multiple objects.
* Supported wildcards: '*' to match 0 or more non-separator characters '**' to match 0 or
* more characters (including separators). Only supported at the end of a path and with no other
* wildcards. '?' to match 1 character.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String gcsUri;
/**
* The gcs_uri must be in the format "gs://bucket/path/to/object". The gcs_uri may include
* wildcards in the "path/to/object" part to to indicate potential matching of multiple objects.
* Supported wildcards: '*' to match 0 or more non-separator characters '**' to match 0 or
* more characters (including separators). Only supported at the end of a path and with no other
* wildcards. '?' to match 1 character.
* @return value or {@code null} for none
*/
public java.lang.String getGcsUri() {
return gcsUri;
}
/**
* The gcs_uri must be in the format "gs://bucket/path/to/object". The gcs_uri may include
* wildcards in the "path/to/object" part to to indicate potential matching of multiple objects.
* Supported wildcards: '*' to match 0 or more non-separator characters '**' to match 0 or
* more characters (including separators). Only supported at the end of a path and with no other
* wildcards. '?' to match 1 character.
* @param gcsUri gcsUri or {@code null} for none
*/
public GcsDataLocation setGcsUri(java.lang.String gcsUri) {
this.gcsUri = gcsUri;
return this;
}
@Override
public GcsDataLocation set(String fieldName, Object value) {
return (GcsDataLocation) super.set(fieldName, value);
}
@Override
public GcsDataLocation clone() {
return (GcsDataLocation) super.clone();
}
}
| true |
87bd996d93394a06bdfeb5fa42045981feb8d6a3 | Java | teramura/flex-sdk | /modules/thirdparty/velocity/src/java/org/apache/flex/forks/velocity/runtime/parser/node/PropertyExecutor.java | UTF-8 | 3,018 | 2.59375 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.1",
"MPL-1.0",
"BSD-3-Clause"
] | permissive | package org.apache.flex.forks.velocity.runtime.parser.node;
/*
* Copyright 2000-2002,2004 The Apache Software Foundation.
*
* 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.
*/
import java.lang.reflect.InvocationTargetException;
import org.apache.flex.forks.velocity.util.introspection.Introspector;
import org.apache.flex.forks.velocity.runtime.RuntimeLogger;
/**
* Returned the value of object property when executed.
*/
public class PropertyExecutor extends AbstractExecutor
{
protected Introspector introspector = null;
protected String methodUsed = null;
public PropertyExecutor(RuntimeLogger r, Introspector ispctr,
Class clazz, String property)
{
rlog = r;
introspector = ispctr;
discover(clazz, property);
}
protected void discover(Class clazz, String property)
{
/*
* this is gross and linear, but it keeps it straightforward.
*/
try
{
char c;
StringBuffer sb;
Object[] params = { };
/*
* start with get<property>
* this leaves the property name
* as is...
*/
sb = new StringBuffer("get");
sb.append(property);
methodUsed = sb.toString();
method = introspector.getMethod(clazz, methodUsed, params);
if (method != null)
return;
/*
* now the convenience, flip the 1st character
*/
sb = new StringBuffer("get");
sb.append(property);
c = sb.charAt(3);
if (Character.isLowerCase(c))
{
sb.setCharAt(3, Character.toUpperCase(c));
}
else
{
sb.setCharAt(3, Character.toLowerCase(c));
}
methodUsed = sb.toString();
method = introspector.getMethod(clazz, methodUsed, params);
if (method != null)
return;
}
catch(Exception e)
{
rlog.error("PROGRAMMER ERROR : PropertyExector() : " + e );
}
}
/**
* Execute method against context.
*/
public Object execute(Object o)
throws IllegalAccessException, InvocationTargetException
{
if (method == null)
return null;
return method.invoke(o, null);
}
}
| true |
50d5d4527491efd462b55cb2de334c11839224fd | Java | ImRetard/GuessNubemGame | /src/interface_lesson_22/ConsoleReader.java | UTF-8 | 305 | 2.734375 | 3 | [] | no_license | package interface_lesson_22;
import java.util.Scanner;
public class ConsoleReader implements Read {
@Override
public String getDate() {
Scanner ch = new Scanner(System.in);
System.out.print("Please enter text: ");
String line=ch.nextLine();
return line;
}
}
| true |
b2c0a86a1841f552332ae2bced5706a82a46da25 | Java | nooshhub/xa-sample | /collaboration-svc/src/main/java/cn/xa/CollaborationController.java | UTF-8 | 816 | 1.96875 | 2 | [] | no_license | package cn.xa;
import cn.xa.collaboration.CollaborationDto;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
/**
* @author Neal Shan
* @since 0.0.1
*/
@RestController
@RequestMapping("/v1/collaboration")
@RequiredArgsConstructor
public class CollaborationController {
private final CollaborationService collaborationService;
@PostMapping("/create")
public CollaborationDto createCollaboration(
@RequestBody @Valid CollaborationDto collaborationDto) {
return collaborationService.create(collaborationDto);
}
}
| true |
99499f271ab040e62d6e1a7114ec2e72d181b44a | Java | nikhilketkar/spark-transformers | /adapters/src/main/java/com/flipkart/fdp/ml/adapter/HashingTFModelInfoAdapter.java | UTF-8 | 1,212 | 2.359375 | 2 | [
"Apache-2.0"
] | permissive | package com.flipkart.fdp.ml.adapter;
import com.flipkart.fdp.ml.modelinfo.HashingTFModelInfo;
import org.apache.spark.ml.feature.HashingTF;
import org.apache.spark.sql.DataFrame;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Transforms Spark's {@link HashingTF} in MlLib to {@link com.flipkart.fdp.ml.modelinfo.HashingTFModelInfo} object
* that can be exported through {@link com.flipkart.fdp.ml.export.ModelExporter}
*/
public class HashingTFModelInfoAdapter extends AbstractModelInfoAdapter<HashingTF, HashingTFModelInfo> {
@Override
public HashingTFModelInfo getModelInfo(final HashingTF from, DataFrame df) {
final HashingTFModelInfo modelInfo = new HashingTFModelInfo();
modelInfo.setNumFeatures(from.getNumFeatures());
Set<String> inputKeys = new LinkedHashSet<String>();
inputKeys.add(from.getInputCol());
modelInfo.setInputKeys(inputKeys);
modelInfo.setOutputKey(from.getOutputCol());
return modelInfo;
}
@Override
public Class<HashingTF> getSource() {
return HashingTF.class;
}
@Override
public Class<HashingTFModelInfo> getTarget() {
return HashingTFModelInfo.class;
}
}
| true |
92baf1a16b7d5205b03af417952cf4f2ec1597fd | Java | niteesh777/wpsassignments | /Assignment2_Wps/2_ques/src/Home.java | UTF-8 | 3,766 | 2.5 | 2 | [] | no_license | import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Home extends HttpServlet {
private static final long serialVersionUID = 1L;
public Home() {
super();
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.print("<!DOCTYPE html>\r\n"
+ "<html lang=\"en\">\r\n"
+ "\r\n"
+ "<head>\r\n"
+ " <meta charset=\"UTF-8\">\r\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\r\n"
+ " <title>Document</title>\r\n"
+ " <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css\"\r\n"
+ " integrity=\"sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2\" crossorigin=\"anonymous\">\r\n"
+ "\r\n"
+ "</head>\r\n"
+ "\r\n"
+ "<body>\r\n"
+ " <br><br>\r\n"
+ "\r\n"
+ " <div class=\"container\" style=\"text-align: center;\">\r\n"
+ " <h5> Create a Blog</h5>\r\n"
+ " </div>\r\n"
+ " <div class=\"container\">\r\n"
+ " <form action=\"preview\" method=\"post\">\r\n"
+ " <div class=\"form-group\">\r\n"
+ " <label for=\"title\">Title</label>\r\n"
+ " <input type=\"text\" class=\"form-control\" id=\"title\" name=\"title\" required>\r\n"
+ " </div>\r\n"
+ " <div class=\"form-group\">\r\n"
+ " <label for=\"exampleFormControlTextarea1\">Body</label>\r\n"
+ " <textarea class=\"form-control\" id=\"exampleFormControlTextarea1\" required rows=\"10\" name=\"body\"></textarea>\r\n"
+ " </div>\r\n"
+ " <button type=\"submit\" class=\"btn btn-primary\">Preview</button>\r\n"
+ " </form>\r\n"
+ " </div>\r\n"
+ " <br>");
Connection con=Save.connect();
Statement smt = null;
ResultSet rs=null;
if(con==null)
out.print("Connection Error");
try {
smt=con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rs=smt.executeQuery("SELECT * FROM blogs");
out.print("<div class='container'>");
out.print("<h5>Blogs List</h5>");
out.print("<ul>");
while(rs.next())
{
out.print("<li><a href='view?id="+rs.getInt(1)+"'>"+rs.getString(2)+"</a></li>");
}
out.print("</ul>");
out.print("</div>");
} catch (SQLException e) {
out.print(" <div class='container'>\r\n"
+ " Could not fetch Blogs from DataBase\r\n"
+ " </div>");
// TODO Auto-generated catch block
// e.printStackTrace();
}
out.print("<script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\"\r\n"
+ " integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\"\r\n"
+ " crossorigin=\"anonymous\"></script>\r\n"
+ " <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js\"\r\n"
+ " integrity=\"sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx\"\r\n"
+ " crossorigin=\"anonymous\"></script>\r\n"
+ "\r\n"
+ "</body>\r\n"
+ "\r\n"
+ "</html>");
}
}
| true |
a47a4357b07e835c86e1ec309afa7f0c2337f75e | Java | wayshall/onetwo | /core/modules/common/src/main/java/org/onetwo/common/commandline/CmdRunner.java | UTF-8 | 2,546 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | package org.onetwo.common.commandline;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.onetwo.common.log.MyLoggerFactory;
import org.onetwo.common.utils.LangUtils;
import org.slf4j.Logger;
public class CmdRunner {
protected final Logger logger = MyLoggerFactory.getLogger(this.getClass());
protected CommandManager cmdManager;
public CmdRunner() {
}
/**
* main template
* @param args
* @throws IOException
*/
public void run(String[] args) {
try {
startAppContext(args);
} catch (Exception e) {
logger.error("startAppContext error : " + e.getMessage(), e);
}
loadCommand(args);
initAfterLoadCommand(args);
onRuning();
}
protected void startAppContext(String[] args) {
}
protected void initAfterLoadCommand(String[] args) {
}
protected void loadCommand(String[] args) {
cmdManager = new DefaultCommandManager();
cmdManager.addCommand(new ExitCommand());
cmdManager.addCommand(new HelpCommand());
}
protected CmdContext createCmdContext(BufferedReader br){
return new SimpleCmdContext(br);
}
protected void onRuning() {
this.waitForCommand();
}
protected void waitForCommand() {
InputStreamReader reader = null;
try {
System.out.print("please input > ");
reader = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(reader);
String str = null;
CmdContext cmdContext = createCmdContext(br);
while ((str = br.readLine()) != null) {
Command cmd = cmdManager.getCommand(str);
if(cmd!=null){
try {
cmd.execute(cmdContext);
} catch (CommandStopException e) {
// logger.error("command line error: " + e.getMessage());
System.out.println("command stop " + e.getMessage());
} catch (CommandLineException e) {
// logger.error("command line error: " + e.getMessage());
System.out.println("command line message " + e.getMessage());
} catch (Exception e) {
logger.error("execute command error: " + e.getMessage(), e);
System.out.println("execute command error : " + e.getMessage()+", see detail in log file!");
}
System.out.print("please input > ");
}
}
} catch (IOException e) {
logger.error("input error : " + e.getMessage(), e);
System.out.println("input error : " + e.getMessage()+", see detail in log file!");
} finally{
System.out.println("goodbye!");
LangUtils.closeIO(reader);
}
}
}
| true |
1acc8a00145d0bb1e36d965f9bb32f69f0589e44 | Java | igorcastro-dsn/escola-ddd | /src/main/java/br/com/alura/escola/academico/dominio/indicacao/Indicacao.java | UTF-8 | 570 | 2.53125 | 3 | [] | no_license | package br.com.alura.escola.academico.dominio.indicacao;
import java.time.LocalDateTime;
import br.com.alura.escola.academico.dominio.aluno.Aluno;
public class Indicacao {
private Aluno indicante;
private Aluno indicado;
private LocalDateTime data;
public Indicacao(Aluno indicante, Aluno indicado) {
this.data = LocalDateTime.now();
this.indicante = indicante;
this.indicado = indicado;
}
public Aluno getIndicante() {
return indicante;
}
public Aluno getIndicado() {
return indicado;
}
public LocalDateTime getData() {
return data;
}
}
| true |
e3692e9b9c83d11ff370f4f265d64faeb2214d62 | Java | Oxxrim/TestTask | /src/org/itstep/Reader.java | UTF-8 | 1,276 | 2.515625 | 3 | [] | no_license | package org.itstep;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Reader {
FileReader reader;
Scanner scanner;
List<String> listWithWaitingTime = new ArrayList<>();
Service service = new Service();
public void readFile() throws ParseException {
{
String line;
try {
reader = new FileReader("resources//test.txt");
scanner = new Scanner(reader);
while (scanner.hasNextLine()){
line = scanner.nextLine();
if (line.contains("C")){
listWithWaitingTime.add(line);
} else {
service.queryProcessing(listWithWaitingTime, line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| true |
c1266354eca9de45cd03547c1d1d774f71640615 | Java | moutainhigh/xcdv1 | /msk-dev/msk-batch/src/main/java/com/msk/batch/LockBatch.java | UTF-8 | 1,084 | 2.1875 | 2 | [] | no_license | package com.msk.batch;
import com.msk.batch.base.logic.BatchRecordLogic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.msk.common.consts.StatusConst.BatchStatusDef;
import com.msk.core.entity.BatchRecord;
import com.msk.core.utils.DateTimeUtil;
/**
* Batch锁,如果Batch已经执行,无法再次启动Batch
*
* @author jiang_nan
*/
@Component
public class LockBatch {
/** Batch Record Logic */
@Autowired
private BatchRecordLogic batchRecordLogic;
/**
* Lock Batch
* @param batchId Batch Id
*/
public void lockBatch(String batchId) {
batchRecordLogic.checkBatchRecord(batchId);
BatchRecord batchRecord = new BatchRecord();
batchRecord.setRunId(this.batchRecordLogic.maxBatchId());
batchRecord.setBatchCode(batchId);
batchRecord.setStatus(BatchStatusDef.NEW);
batchRecord.setCrtId("batch");
batchRecord.setCrtTime(DateTimeUtil.getCustomerDate());
this.batchRecordLogic.save(batchRecord);
}
}
| true |
c5f2af0a5683d1dcbeb8e68f03cdd8dbceb88c7e | Java | formernest/leetcode | /interview/prime.java | UTF-8 | 571 | 3.21875 | 3 | [] | no_license | package interview;
/**
* 求1到1000000的质数
* https://github.com/muhualing/coding-interview-chinese/tree/master/microsoft
*
*/
public class prime {
public static void main(String[] args) {
int NUM = 1000000;
System.out.println(2);
int j = 3;
for (int i = 3; i <= NUM; i += 2) {
for (j = 3; j < i; j += 2) {
if (i % j == 0 || j * j > i) {
break;
}
}
if (j * j > i) {
System.out.println(i);
}
}
}
} | true |
4a7a99a9b4d6853ab3bc50d4253992a4f6134a2d | Java | venkat-thota/java-simulations | /battery-resistor-circuit/src/main/java/com/aimxcel/abclearn/batteryresistorcircuit/common/wire1d/paint/WirePatchPainter.java | UTF-8 | 1,047 | 2.65625 | 3 | [] | no_license |
package com.aimxcel.abclearn.batteryresistorcircuit.common.wire1d.paint;
import java.awt.*;
import com.aimxcel.abclearn.batteryresistorcircuit.common.paint.Painter;
import com.aimxcel.abclearn.batteryresistorcircuit.common.phys2d.DoublePoint;
import com.aimxcel.abclearn.batteryresistorcircuit.common.wire1d.WirePatch;
import com.aimxcel.abclearn.batteryresistorcircuit.common.wire1d.WireSegment;
public class WirePatchPainter implements Painter {
Stroke s;
Color c;
WirePatch wp;
public WirePatchPainter( Stroke s, Color c, WirePatch wp ) {
this.s = s;
this.c = c;
this.wp = wp;
}
public void paint( Graphics2D g ) {
for ( int i = 0; i < wp.numSegments(); i++ ) {
WireSegment ws = wp.segmentAt( i );
g.setStroke( s );
g.setColor( c );
DoublePoint start = ws.getStart();
DoublePoint end = ws.getFinish();
g.drawLine( (int) start.getX(), (int) start.getY(), (int) end.getX(), (int) end.getY() );
}
}
}
| true |
05d0f18bca12ee215b43be79a3ff6e6ade4a1a59 | Java | LuckyBaquet/AccessLab04 | /src/main/java/magpiesfate/Suit.java | UTF-8 | 114 | 1.710938 | 2 | [] | no_license | package magpiesfate;
/**
* Created by lucky on 1/26/16.
*/
public enum Suit {
CLUBS,SPADES,HEARTS,DIAMONDS
}
| true |
e63128b4551c552762f09f1262179f57698aad58 | Java | shkumar007/java-first- | /Interface3/Word.java | UTF-8 | 329 | 2.546875 | 3 | [] | no_license | package Interface3;
public class Word extends Get implements Iprinter {
public void print() {
System.out.println(" hi am in word print method");
open();
close();
}
@Override
public void read() {
System.out.println(" hi am in word read method");
open();
close();
// TODO Auto-generated method stub
}
}
| true |
dc8afe769ba5f10690fc6149f88ba6c1532aa6f3 | Java | pasite/mall | /mall-coupon/src/main/java/com/cjy/mall/coupon/dao/CouponSpuRelationDao.java | UTF-8 | 398 | 1.5625 | 2 | [
"Apache-2.0"
] | permissive | package com.cjy.mall.coupon.dao;
import com.cjy.mall.coupon.entity.CouponSpuRelationEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 优惠券与产品关联
*
* @author chenjy01
* @email chenjunyu102@126.com
* @date 2020-08-20 15:17:51
*/
@Mapper
public interface CouponSpuRelationDao extends BaseMapper<CouponSpuRelationEntity> {
}
| true |
b3fc88edc00748e76ac3bbe4c2d3b5708f2f3507 | Java | DeveloperRachit/microserviceDemo | /teacher/src/main/java/com/hcl/teacher/TeacherApplication.java | UTF-8 | 924 | 2.0625 | 2 | [] | no_license | package com.hcl.teacher;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
@RestController
@RequestMapping("/teacher")
public class TeacherApplication {
private static final Logger LOG = Logger.getLogger(TeacherApplication.class.getName());
public static void main(String[] args) {
SpringApplication.run(TeacherApplication.class, args);
}
@RequestMapping("/newTeacherRegistration")
public String stuRegistration() {
LOG.log(Level.INFO, "This is Teacher Registration API.");
return "Teacher Registration has been succussfully.";
}
}
| true |
1a23a2f00d6432210b1782841f7fb4c6eaca4611 | Java | FraunhoferCESE/madcap | /sensorlisteners/src/main/java/edu/umd/fcmd/sensorlisteners/model/bluetooth/BluetoothStaticAttributesProbe.java | UTF-8 | 2,303 | 3.1875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package edu.umd.fcmd.sensorlisteners.model.bluetooth;
import edu.umd.fcmd.sensorlisteners.model.Probe;
/**
* Created by MMueller on 12/6/2016.
*
* Model Class for static attributes of a Bluetooth Adapter.
*/
public class BluetoothStaticAttributesProbe extends Probe {
private String name;
private String address;
/**
* Getter for the name the user can configure.
* Something like "Bob's phone"
* @return the bluetooth device name.
*/
public String getName() {
return name;
}
/**
* Setter for the name.
* @param name name to be set.
*/
public void setName(String name) {
this.name = name;
}
/**
* Getter for the bluetooth Adapter address.
* @return the address.
*/
public String getAddress() {
return address;
}
/**
* Setter for the Address.
* @param address to be set.
*/
public void setAddress(String address) {
this.address = address;
}
/**
* Gets the type of an state e.g. Accelerometer
*
* @return the type of state.
*/
@Override
public String getType() {
return "BluetoothStaticAttributes";
}
/**
* Returns a string representation of the object. In general, the
* {@code toString} method returns a string that
* "textually represents" this object. The result should
* be a concise but informative representation that is easy for a
* person to read.
* It is recommended that all subclasses override this method.
* <p>
* The {@code toString} method for class {@code Object}
* returns a string consisting of the name of the class of which the
* object is an instance, the at-sign character `{@code @}', and
* the unsigned hexadecimal representation of the hash code of the
* object. In other words, this method returns a string equal to the
* value of:
* <blockquote>
* <pre>
* getClass().getName() + '@' + Integer.toHexString(hashCode())
* </pre></blockquote>
*
* @return a string representation of the object.
*/
@Override
public String toString() {
return "{\"name\": " + name +
", \"address\": " + "\"" + address + "\"" +
'}';
}
}
| true |
2269f1b00afe6892c9902c1b8ceff7196765e5a5 | Java | Xilma/SweetCulinary | /app/src/main/java/rilma/example/com/sweetculinary/views/TutorialActivity.java | UTF-8 | 6,734 | 2.15625 | 2 | [] | no_license | package rilma.example.com.sweetculinary.views;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Objects;
import butterknife.BindView;
import butterknife.ButterKnife;
import rilma.example.com.sweetculinary.R;
import rilma.example.com.sweetculinary.adapters.StepAdapter;
import rilma.example.com.sweetculinary.models.Step;
import rilma.example.com.sweetculinary.utils.ConstantValues;
public class TutorialActivity extends AppCompatActivity implements View.OnClickListener, StepAdapter.OnStepClick {
public static final String STEP_LIST_STATE = "step_list_state";
public static final String STEP_NUMBER_STATE = "step_number_state";
public static final String STEP_LIST_JSON_STATE = "step_list_json_state";
private boolean isTablet;
private int videoNumber = 0;
@Nullable
@BindView(R.id.bv_next_step)
Button nextStep;
@Nullable
@BindView(R.id.bv_previous_step)
Button previousStep;
@Nullable
@BindView(R.id.rv_recipe_steps)
RecyclerView recyclerView;
ArrayList<Step> stepList = new ArrayList<>();
String jsonResult;
boolean isFromWidget;
LinearLayoutManager linearLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorial);
// Check if device is a tablet
if(findViewById(R.id.tutorial_tablet) != null){
isTablet = true;
}
else{
isTablet = false;
}
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra(ConstantValues.STEP_INTENT_EXTRA)) {
stepList = getIntent().getParcelableArrayListExtra(ConstantValues.STEP_INTENT_EXTRA);
}
if (intent.hasExtra(ConstantValues.JSON_RESULT_EXTRA)) {
jsonResult = getIntent().getStringExtra(ConstantValues.JSON_RESULT_EXTRA);
}
if (intent.hasExtra(ConstantValues.RECIPE_INTENT_EXTRA)) {
String title = getIntent().getStringExtra(ConstantValues.RECIPE_INTENT_EXTRA);
String titleBar = title + " - Tutorial";
setActionBarTitle(titleBar);
}
isFromWidget = intent.getStringExtra(ConstantValues.WIDGET_EXTRA) != null;
}
// If there is no saved state, instantiate fragment
if (savedInstanceState == null) {
playVideo(stepList.get(videoNumber));
}
ButterKnife.bind(this);
handleUiForDevice();
}
// Initialize fragment
public void playVideo(Step step) {
VideoFragment videoPlayerFragment = new VideoFragment();
Bundle stepsBundle = new Bundle();
stepsBundle.putParcelable(ConstantValues.STEP_SINGLE, step);
videoPlayerFragment.setArguments(stepsBundle);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.fl_player_container, videoPlayerFragment)
.addToBackStack(null)
.commit();
}
// Initialize fragment
public void playVideoReplace(Step step) {
VideoFragment videoPlayerFragment = new VideoFragment();
Bundle stepsBundle = new Bundle();
stepsBundle.putParcelable(ConstantValues.STEP_SINGLE, step);
videoPlayerFragment.setArguments(stepsBundle);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fl_player_container, videoPlayerFragment)
.addToBackStack(null)
.commit();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STEP_LIST_STATE, stepList);
outState.putString(STEP_LIST_JSON_STATE, jsonResult);
outState.putInt(STEP_NUMBER_STATE, videoNumber);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
//If it's last step show cooking is over
if (videoNumber == stepList.size() - 1) {
Toast.makeText(this, R.string.end_tutorial, Toast.LENGTH_SHORT).show();
} else {
if (v.getId() == previousStep.getId()) {
videoNumber--;
if (videoNumber < 0) {
Toast.makeText(this, R.string.next_step, Toast.LENGTH_SHORT).show();
} else
playVideoReplace(stepList.get(videoNumber));
} else if (v.getId() == nextStep.getId()) {
videoNumber++;
playVideoReplace(stepList.get(videoNumber));
}
}
}
@Override
public void onStepClick(int position) {
videoNumber = position;
playVideoReplace(stepList.get(position));
}
public void handleUiForDevice() {
if (!isTablet) {
// Set button listeners
nextStep.setOnClickListener(this);
previousStep.setOnClickListener(this);
} else {//Tablet view
StepAdapter stepAdapter = new StepAdapter(this, stepList, this, videoNumber);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(stepAdapter);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
stepList = savedInstanceState.getParcelableArrayList(STEP_LIST_STATE);
jsonResult = savedInstanceState.getString(STEP_LIST_JSON_STATE);
videoNumber = savedInstanceState.getInt(STEP_NUMBER_STATE);
}
}
public void setActionBarTitle(String title) {
Objects.requireNonNull(getSupportActionBar()).setTitle(title);
}
}
| true |
93f9dd53884ecbd768a7798196e1c57381ea8e4b | Java | seerdaryilmazz/OOB | /order-service/src/main/java/ekol/orders/transportOrder/domain/VehicleFeature.java | UTF-8 | 6,311 | 2.21875 | 2 | [] | no_license | package ekol.orders.transportOrder.domain;
import ekol.exceptions.ValidationException;
import ekol.json.serializers.common.ConverterType;
import ekol.orders.transportOrder.dto.VehicleFeatureFilter;
import ekol.resource.json.annotation.EnumSerializableToJsonAsLookup;
import org.apache.commons.lang.StringUtils;
import javax.persistence.AttributeConverter;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
@EnumSerializableToJsonAsLookup(ConverterType.INITIAL_CASE)
public enum VehicleFeature {
/**
* TODO: Bu değerler, Crm'deki tekliflerde de kullanılıyor. Özellikle isim değişikliği yapıldığında Crm tarafında etkilenen yerler de güncellenmeli.
* TODO: Bu değerler, Crm'deki değerler ve sales-price-service'teki değerler (CrmTrailerType) ortaklaştırılsa iyi olur.
*/
CURTAIN_SIDER,
BOX_BODY,
MEGA,
SUITABLE_FOR_TRAIN,
XL_CERTIFICATE,
FRIGO,
ISOLATED,
DOUBLE_DECK,
SUITABLE_FOR_HANGING_LOADS,
LIFTING_ROOF,
SLIDING_ROOF,
SECURITY_SENSOR,
TAIL_LIFT,
TRAILER,
CONTAINER,
SWAP_BODY;
private static List<VehicleFeature> boxFeatures = Arrays.asList(BOX_BODY, FRIGO, ISOLATED, SUITABLE_FOR_HANGING_LOADS);
private static List<VehicleFeature> curtainSideFeatures = Arrays.asList(CURTAIN_SIDER, LIFTING_ROOF, SLIDING_ROOF);
private static List<VehicleFeature> trailerTypes = Arrays.asList(TRAILER);
private static List<VehicleFeature> containerTypes = Arrays.asList(CONTAINER, SWAP_BODY);
public static void validateCooccurence(List<VehicleFeature> featureList) {
List<VehicleFeature> requiredBoxFeatures = featureList.stream()
.filter(vehicleFeature -> boxFeatures.contains(vehicleFeature)).collect(toList());
List<VehicleFeature> requiredCurtainSideFeatures = featureList.stream()
.filter(vehicleFeature -> curtainSideFeatures.contains(vehicleFeature)).collect(toList());
if(!requiredBoxFeatures.isEmpty() && !requiredCurtainSideFeatures.isEmpty()){
throw new ValidationException("Following features can not exist together: " + requiredCurtainSideFeatures.get(0).name() + " - " + requiredBoxFeatures.get(0).name());
}
List<VehicleFeature> requiredTrailerTypes = featureList.stream()
.filter(vehicleFeature -> trailerTypes.contains(vehicleFeature)).collect(toList());
List<VehicleFeature> requiredContainerTypes = featureList.stream()
.filter(vehicleFeature -> containerTypes.contains(vehicleFeature)).collect(toList());
if(!requiredTrailerTypes.isEmpty() && !requiredContainerTypes.isEmpty()){
throw new ValidationException("Following features can not exist together: " + requiredTrailerTypes.get(0).name() + " - " + requiredContainerTypes.get(0).name());
}
}
public static void validateCooccurence(List<VehicleFeature> required, List<VehicleFeature> notAllowed) {
//error: when any feature exist in both required and not allowed
required.stream().filter(feature -> notAllowed.contains(feature)).findFirst().ifPresent(vehicleFeature -> {
throw new ValidationException("Following feature exist in both required and not allowed filters: " + vehicleFeature.name());
});
validateCooccurence(required);
validateCooccurence(notAllowed);
List<VehicleFeature> requiredBoxFeatures = required.stream()
.filter(vehicleFeature -> boxFeatures.contains(vehicleFeature)).collect(toList());
List<VehicleFeature> requiredCurtainSideFeatures = required.stream()
.filter(vehicleFeature -> curtainSideFeatures.contains(vehicleFeature)).collect(toList());
if(notAllowed.contains(BOX_BODY) && !requiredBoxFeatures.isEmpty()){
throw new ValidationException("There shouldn't be a required box feature when 'BOX' is not allowed");
}
if(notAllowed.contains(CURTAIN_SIDER) && !requiredCurtainSideFeatures.isEmpty()){
throw new ValidationException("There shouldn't be a required curtain side feature when 'CURTAIN SIDE' is not allowed");
}
}
public static class DBConverter implements AttributeConverter<Set<VehicleFeature>, String> {
@Override
public String convertToDatabaseColumn(Set<VehicleFeature> list) {
return String.join(",", list.stream().map(elem -> elem.name()).collect(toList()));
}
@Override
public Set<VehicleFeature> convertToEntityAttribute(String enumString) {
if(StringUtils.isEmpty(enumString)) {
return new HashSet<>();
}
return Arrays.stream(enumString.split(",")).map(elem -> VehicleFeature.valueOf(elem)).collect(Collectors.toSet());
}
}
public static List<VehicleFeature> fromVehicleFeatureFilter(VehicleFeatureFilter vehicleFeatureFilter) {
List<VehicleFeature> features = new ArrayList<>();
if(vehicleFeatureFilter.isCurtainSider()) { features.add(VehicleFeature.CURTAIN_SIDER);}
if(vehicleFeatureFilter.isBox()) { features.add(VehicleFeature.BOX_BODY);}
if(vehicleFeatureFilter.isMega()) { features.add(VehicleFeature.MEGA);}
if(vehicleFeatureFilter.isDoubleDeck()) { features.add(VehicleFeature.DOUBLE_DECK);}
if(vehicleFeatureFilter.isFrigoTrailer()) { features.add(VehicleFeature.FRIGO);}
if(vehicleFeatureFilter.isIsolated()) { features.add(VehicleFeature.ISOLATED);}
if(vehicleFeatureFilter.isLiftingRoof()) { features.add(VehicleFeature.LIFTING_ROOF);}
if(vehicleFeatureFilter.isSecuritySensor()) { features.add(VehicleFeature.SECURITY_SENSOR);}
if(vehicleFeatureFilter.isSlidingRoof()) { features.add(VehicleFeature.SLIDING_ROOF);}
if(vehicleFeatureFilter.isSuitableForHangingLoads()) { features.add(VehicleFeature.SUITABLE_FOR_HANGING_LOADS);}
if(vehicleFeatureFilter.isSuitableForTrain()) { features.add(VehicleFeature.SUITABLE_FOR_TRAIN);}
if(vehicleFeatureFilter.isTailLift()) { features.add(VehicleFeature.TAIL_LIFT);}
if(vehicleFeatureFilter.isXlCertificate()) { features.add(VehicleFeature.XL_CERTIFICATE);}
return features;
}
}
| true |
e95e9014ddebf06ced11394918b9ce3bed44b36e | Java | dwyanecf/for-fan | /mind/src/main/java/com/fanchen/clearmind/leetcode/binarysearch/PeakIndexInAMountainArray.java | UTF-8 | 918 | 3.875 | 4 | [] | no_license | package com.fanchen.clearmind.leetcode.binarysearch;
/**
* Let's call an array A a mountain if the following properties hold:
*
* A.length >= 3 There exists some 0 < i < A.length - 1 such that A[0] < A[1] <
* ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] Given an array that is
* definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i]
* > A[i+1] > ... > A[A.length - 1].
*
* Example 1:
*
* Input: [0,1,0] Output: 1
*
* Example 2:
*
* Input: [0,2,1,0] Output: 1
*
* Note:
*
* 3 <= A.length <= 10000 0 <= A[i] <= 10^6 A is a mountain, as defined above.
*
* @author Fan Chen
*
*/
public class PeakIndexInAMountainArray {
public int peakIndexInMountainArray(int[] A) {
int lo = 0;
int hi = A.length - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (A[mid] < A[mid + 1]) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
}
| true |
3e357227df632fcb0a87e9b04b44004e3f99b176 | Java | liujinyuann/test | /workspace/pms/src/Pms.java | UTF-8 | 14,023 | 2.046875 | 2 | [] | no_license |
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
public class Pms extends Thread {
// 進捗
public static Date dateYMD;
// 進捗を設定
public static void setStrYMD(Date dareYmd) {
dateYMD = dareYmd;
}
public void run() {
DataFrom dataFrom = MainFrame.dataFrom;
try {
mainTest();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
// メッセージを設定
// dataFrom.setStrMsg(e.getMessage());
dataFrom.setStrMsg("入力失敗。");
// コードを設定
dataFrom.setStrCode("1");
} catch (Exception e) {
e.printStackTrace();
// メッセージを設定
// dataFrom.setStrMsg(e.getMessage());
dataFrom.setStrMsg("入力失敗。");
// コードを設定
dataFrom.setStrCode("1");
}
}
public static DataFrom mainTest() throws IOException, InterruptedException, Exception {
// 進捗を設定する
MainFrame.setIntProgress(1);
DataFrom dataFrom = MainFrame.dataFrom;
// Excel読み込み
ReadExcel.readExcel(dataFrom);
// 進捗を設定する
MainFrame.setIntProgress(25);
// chromedriverサービスアドレス
System.setProperty("webdriver.chrome.driver", "D:\\PMSInput\\chromedriver.exe");
// WebDriverの対象
WebDriver driver;
// アクションの対象
Actions action;
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
// WebDriverの対象を新規に作成します
driver = new ChromeDriver(chromeOptions);
// アクションの対象を新規に作成します
action = new Actions(driver);
// 指定されたサイトを開く
driver.get("http://pms.dhc.com.cn/");
action.sendKeys(driver.findElement(By.id("txtUserName")), dataFrom.getStrUserId()).perform();
action.sendKeys(driver.findElement(By.id("txtPassword")), dataFrom.getStrPwd()).perform();
String inputValue = JOptionPane.showInputDialog("確認コードを入力ください。");
MainFrame.jf_1.setExtendedState(JFrame.ICONIFIED);
action.sendKeys(driver.findElement(By.name("CaptchaControl1")), inputValue).perform();
action.moveToElement(driver.findElement(By.name("btnLogin"))).perform();
action.click().perform();
try {
action.moveToElement(driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_lblSceneClose"))).perform();
action.click().perform();
Thread.sleep(100);
} catch (Exception e) {
Thread.sleep(100);
}
String strKozinKanri = "";
String strKintaiShinsei = "";
String strKyuukalbl = "";
String strYukyuKyuka = "";
String strNisshiNyuryoku = "";
WebElement eleLanguage = driver.findElement(By.id("quickdemoLanguage"));
String selectedSale = eleLanguage.getText();
if (!"日本語".equals(selectedSale)) {
strKozinKanri = "个人管理";
strKintaiShinsei = "考勤申请";
strKyuukalbl = "休假";
strYukyuKyuka = "年休假";
strNisshiNyuryoku = "日志录入";
} else {
strKozinKanri = "個人管理";
strKintaiShinsei = "勤怠申請";
strKyuukalbl = "休暇";
strYukyuKyuka = "有給休暇";
strNisshiNyuryoku = "日誌入力";
}
action.moveToElement(driver.findElement(By.linkText(strKozinKanri))).perform();
action.click().perform();
Thread.sleep(500);
action.moveToElement(driver.findElement(By.linkText(strKintaiShinsei))).perform();
action.click().perform();
// Excel情報を取得する
List<List> listAll = dataFrom.getList();
// 日
String strNiti = "";
// 出社
String strShussha = "";
// 退社
String strTaisha = "";
// 休暇
String strKyuuka = "";
// 正常
String strNormalHour = "";
// 夜間
String strNightHour = "";
// 徹夜
String strMidNightHour = "";
// Excel情報
Map<String, String> dataMap = new HashMap<String, String>();
File file;
// 進捗を設定する
int intPro = 30;
MainFrame.setIntProgress(intPro);
String[] strShusshaArr;
String[] strTaishaArr;
String strStartTimeHour;
int intStartTimeMinute;
String strStartTimeMinute;
String strEndTimeHour;
int intEndTimeMinute;
String strEndTimeMinute;
String strHiduke;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Calendar calc = Calendar.getInstance();
for (int i = 0; i < listAll.size(); i++) {
List<Map> list = listAll.get(i);
for (int j = 0; j < list.size(); j++) {
dataMap = list.get(j);
// 日
strNiti = dataMap.get("Niti").toString();
// 出社
strShussha = dataMap.get("Shussha").toString();
// 退社
strTaisha = dataMap.get("Taisha").toString();
// 休暇
strKyuuka = dataMap.get("Kyuuka").toString();
if ((!"0.0".equals(strShussha) && !"0.0".equals(strTaisha)) || strKyuuka != "") {
Select selectPjName = new Select(
driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_ddlProjectName")));
selectPjName.selectByVisibleText(dataFrom.getStrPjName());
if (strKyuuka == "") {
strShusshaArr = strShussha.split("\\.");
strTaishaArr = strTaisha.split("\\.");
strStartTimeHour = String.format("%0" + 2 + "d", Integer.parseInt(strShusshaArr[0]));
if (Integer.parseInt(strShusshaArr[1]) > 10) {
intStartTimeMinute = Integer.parseInt(strShusshaArr[1]) / 10 * 6;
} else {
intStartTimeMinute = Integer.parseInt(strShusshaArr[1]) * 6;
}
strStartTimeMinute = String.format("%0" + 2 + "d", intStartTimeMinute);
strEndTimeHour = String.format("%0" + 2 + "d", Integer.parseInt(strTaishaArr[0]));
if (Integer.parseInt(strTaishaArr[1]) > 10) {
intEndTimeMinute = Integer.parseInt(strTaishaArr[1]) / 10 * 6;
} else {
intEndTimeMinute = Integer.parseInt(strTaishaArr[1]) * 6;
}
strEndTimeMinute = String.format("%0" + 2 + "d", intEndTimeMinute);
Select selectDdlKind = new Select(
driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_ddlKind")));
selectDdlKind.selectByVisibleText("外出");
} else {
Select selectDdlKind = new Select(
driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_ddlKind")));
selectDdlKind.selectByVisibleText(strKyuukalbl);
Select selectDdlHOLIDAY = new Select(
driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_ddlHOLIDAY_CODE")));
selectDdlHOLIDAY.selectByVisibleText(strYukyuKyuka);
strStartTimeHour = "09";
strStartTimeMinute = "00";
strEndTimeHour = "18";
strEndTimeMinute = "00";
}
calc.setTime(dateYMD);
calc.add(calc.DATE, j);
strHiduke = sdf.format(calc.getTime());
Thread.sleep(500);
action.sendKeys(driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_txtStartDate")),
strHiduke).perform();
Thread.sleep(100);
action.sendKeys(driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_txtEndDate")), strHiduke)
.perform();
Thread.sleep(100);
action.sendKeys(driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_txtStartTime")),
strStartTimeHour + strStartTimeMinute).perform();
Thread.sleep(100);
action.sendKeys(driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_txtEndTime")),
strEndTimeHour + strEndTimeMinute).perform();
Thread.sleep(100);
action.moveToElement(driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_btnCreat")))
.perform();
action.click().perform();
Thread.sleep(500);
try {
action.moveToElement(driver.findElement(By.id("popup_ok"))).perform();
action.click().perform();
Thread.sleep(100);
action.moveToElement(driver.findElement(By.linkText(strKintaiShinsei))).perform();
action.click().perform();
Thread.sleep(100);
} catch (Exception e) {
Thread.sleep(100);
}
dealPotentialAlert(driver, true);
}
intPro = intPro + 5;
// 進捗を設定する
if (intPro < 55) {
MainFrame.setIntProgress(intPro);
}
}
// ブラウザを閉じる
// driver.quit();
}
action.moveToElement(driver.findElement(By.linkText(strNisshiNyuryoku))).perform();
action.click().perform();
WebElement ele;
for (int i = 0; i < listAll.size(); i++) {
List<Map> list = listAll.get(i);
for (int j = 0; j < list.size(); j++) {
dataMap = list.get(j);
// 日
strNiti = dataMap.get("Niti").toString();
// 出社
strShussha = dataMap.get("Shussha").toString();
// 退社
strTaisha = dataMap.get("Taisha").toString();
// 休暇
strKyuuka = dataMap.get("Kyuuka").toString();
// 正常
strNormalHour = dataMap.get("NormalHour").toString();
// 夜間
strNightHour = dataMap.get("NightHour").toString();
// 徹夜
strMidNightHour = dataMap.get("MidNightHour").toString();
if (!"0.0".equals(strShussha) && !"0.0".equals(strTaisha)) {
strShusshaArr = strShussha.split("\\.");
strTaishaArr = strTaisha.split("\\.");
strStartTimeHour = String.format("%0" + 2 + "d", Integer.parseInt(strShusshaArr[0]));
if (Integer.parseInt(strShusshaArr[1]) > 10) {
intStartTimeMinute = Integer.parseInt(strShusshaArr[1]) / 10 * 6;
} else {
intStartTimeMinute = Integer.parseInt(strShusshaArr[1]) * 6;
}
strStartTimeMinute = String.format("%0" + 2 + "d", intStartTimeMinute);
strEndTimeHour = String.format("%0" + 2 + "d", Integer.parseInt(strTaishaArr[0]));
if (Integer.parseInt(strTaishaArr[1]) > 10) {
intEndTimeMinute = Integer.parseInt(strTaishaArr[1]) / 10 * 6;
} else {
intEndTimeMinute = Integer.parseInt(strTaishaArr[1]) * 6;
}
strEndTimeMinute = String.format("%0" + 2 + "d", intEndTimeMinute);
calc.setTime(dateYMD);
calc.add(calc.DATE, j);
strHiduke = sdf.format(calc.getTime());
Thread.sleep(500);
ele = driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_txtDate"));
ele.clear();
Thread.sleep(100);
action.sendKeys(ele, strHiduke).perform();
Thread.sleep(100);
action.moveToElement(driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_ddlProject")))
.perform();
action.click().perform();
Thread.sleep(100);
action.click().perform();
Select selectPjName = new Select(
driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_ddlProject")));
selectPjName.selectByVisibleText(dataFrom.getStrPjName());
Thread.sleep(1500);
if (!"".equals(driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_txtTotalNormalHour"))
.getText())) {
Thread.sleep(100);
continue;
}
if (!"".equals(
driver.findElement(By.xpath(".//*[@id='77702483-367b-45bd-8a34-aadc3beaab16']/td[8]"))
.getText())) {
Thread.sleep(100);
continue;
}
if (!"0.0".equals(strNormalHour)) {
driver.findElement(By.xpath(".//*[@id='77702483-367b-45bd-8a34-aadc3beaab16']/td[8]")).click();
Thread.sleep(200);
action.sendKeys(driver.findElement(By.id("1_NormalHour")), strNormalHour).perform();
Thread.sleep(200);
}
if (!"0.0".equals(strNightHour)) {
driver.findElement(By.xpath(".//*[@id='77702483-367b-45bd-8a34-aadc3beaab16']/td[9]")).click();
Thread.sleep(200);
action.sendKeys(driver.findElement(By.id("1_NightHour")), strNightHour).perform();
Thread.sleep(200);
}
if (!"0.0".equals(strMidNightHour)) {
driver.findElement(By.xpath(".//*[@id='77702483-367b-45bd-8a34-aadc3beaab16']/td[10]")).click();
Thread.sleep(200);
action.sendKeys(driver.findElement(By.id("1_MidNightHour")), strMidNightHour).perform();
Thread.sleep(200);
}
if (j == list.size() - 1) {
action.moveToElement(driver.findElement(By.id("ctl00_ctl00_userContent_mainBody_rbtFace_1"))).perform();
Thread.sleep(200);
action.click().perform();
Thread.sleep(200);
}
action.moveToElement(driver.findElement(By.id("ctl00_ctl00_userContent_topToolBar_btnSave")))
.perform();
action.click().perform();
Thread.sleep(1500);
dealPotentialAlert(driver, true);
}
intPro = intPro + 5;
// 進捗を設定する
if (intPro < 95) {
MainFrame.setIntProgress(intPro);
}
}
// ブラウザを閉じる
// driver.quit();
}
// if (!"日本語".equals(selectedSale)) {
// Select selectLanguage = new Select(
// driver.findElement(By.id("quickdemoLanguage")));
// selectLanguage.selectByVisibleText(selectedSale);
// }
// 進捗を設定する
MainFrame.setIntProgress(100);
dataFrom.setStrMsg("入力完了。");
dataFrom.setStrCode("0");
return dataFrom;
}
public static boolean dealPotentialAlert(WebDriver driver, boolean option) {
boolean flag = false;
try {
Alert alert = driver.switchTo().alert();
if (null == alert)
throw new NoAlertPresentException();
try {
if (option) {
alert.accept();
System.out.println("Accept the alert: " + alert.getText());
} else {
alert.dismiss();
System.out.println("Dismiss the alert: " + alert.getText());
}
flag = true;
} catch (WebDriverException ex) {
if (ex.getMessage().startsWith("Could not find"))
System.out.println("There is no alert appear!");
else
throw ex;
}
} catch (NoAlertPresentException e) {
System.out.println("There is no alert appear!");
}
return flag;
}
}
| true |
6597004eaf33efae96759117251dd440e4166fa3 | Java | torebre/Encodings | /raster/src/main/java/com/kjipo/visualization/RasterRun.java | UTF-8 | 243 | 2 | 2 | [
"MIT"
] | permissive | package com.kjipo.visualization;
public interface RasterRun<T extends CellType> {
boolean[][] getRawInput();
boolean hasNext();
int getColumns();
int getRows();
T getCell(int row, int column);
void next();
}
| true |
5ae5fe5ec10de8833529d2bcbd7685e1c34f08fd | Java | MrOwlie/ProjectNBVE | /src/server/Snowball.java | UTF-8 | 2,201 | 2.4375 | 2 | [
"MIT"
] | 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 server;
import com.jme3.bullet.collision.shapes.SphereCollisionShape;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.math.Vector3f;
import packets.Packet.DestroyEntity;
/**
*
* @author Anton
*/
public class Snowball extends MovingEntity{
public final float SPEED = 160f;
public final float MASS = 10f;
private RigidBodyControl controller;
private int idOwner;
private boolean impact;
public Snowball(Vector3f startPos, Vector3f direction, int idOwner)
{
this.idOwner = idOwner;
this.name = "Snowball";
this.setLocalTranslation(startPos);
this.direction = direction.normalizeLocal();
controller = new RigidBodyControl(new SphereCollisionShape(0.25f), MASS);
this.addControl(controller);
Main.bulletAppState.getPhysicsSpace().add(controller);
Main.refRootNode.attachChild(this);
controller.setLinearVelocity(direction.mult(SPEED));
controller.setCcdMotionThreshold(0f);
controller.setCcdSweptSphereRadius(1f);
Modeling.addEntity(this);
}
public int getOwnerId()
{
return idOwner;
}
@Override
public void setViewDirection(Vector3f dir) {
}
@Override
public Vector3f getViewDirection() {
return Vector3f.UNIT_X;
}
@Override
public void update(float tpf) {
direction = controller.getLinearVelocity();
}
@Override
public void destroyEntity()
{
Modeling.removeEntity(entityId);
Main.refRootNode.detachChild(this);
Main.bulletAppState.getPhysicsSpace().remove(controller);
Networking.server.broadcast(new DestroyEntity(entityId));
}
public void setImpact(boolean impact)
{
this.impact = impact;
}
public boolean hasImpacted()
{
return impact;
}
}
| true |
0e73862c838a319e15f254436a5f6ef190062cd0 | Java | Fgdou/LaCueillette | /Back/java/tests/serveur/sql/TokenTest.java | UTF-8 | 2,199 | 2.5 | 2 | [] | no_license | package serveur.sql;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import serveur.DataBase;
import serveur.DateTime;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class TokenTest {
static int id;
@BeforeAll
static void init() throws Exception {
DataBase.createInstance();
List<Token> tokens = Token.getByUser(null);
for(Token t : tokens)
t.delete();
DateTime date = new DateTime();
date = date.add(0, 0, 0, 2, 0, 0);
Token t = Token.create(0, null, date, "test");
id = Token.getByValue(t.getValue()).getId();
}
@AfterAll
static void delete() throws Exception {
List<Token> tokens = Token.getByUser(null);
for(Token t : tokens)
t.delete();
}
@Test
void create() throws Exception {
DateTime date = new DateTime();
date = date.add(0, 0, 0, 2, 0, 0);
Token t = Token.create(0, null, date, "test");
assertTrue(Token.exist(t.getValue()));
t = Token.getById(t.getId());
assertEquals(0, t.getType());
assertNull(t.getUser());
t.delete();
assertFalse(Token.exist(t.getValue()));
}
@Test
void use() throws Exception {
Token t = Token.getById(id);
assertTrue(t.isValid());
t.use();
t = Token.getById(id);
assertFalse(t.isValid());
t.delete();
DateTime date = new DateTime();
date = date.add(0, 0, 0, 2, 0, 0);
t = Token.create(0, null, date, "test");
id = t.getId();
}
@Test
void getTokens() throws Exception {
Token t1 = Token.getById(id);
List<Token> tokens = Token.getByUser(null);
assertEquals(1, tokens.size());
assertEquals(t1, tokens.get(0));
Token t2 = Token.create(0, null, new DateTime(), "test");
tokens = Token.getByUser(null);
assertEquals(2, tokens.size());
assertTrue(tokens.contains(t1));
assertTrue(tokens.contains(t2));
t2.delete();
}
} | true |
4823fb1b63e9fb856429f5f9102e28cd71224025 | Java | xing614/AlgorithmProblem | /leetcodeWrite/src/easy/RemoveDuplicatesFromSortedArray_26.java | UTF-8 | 2,199 | 4.375 | 4 | [] | no_license | package easy;
/**
* 26. 删除排序数组中的重复项
* 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
示例 1:
给定数组 nums = [1,1,2],
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
你不需要考虑数组中超出新长度后面的元素。
示例 2:
给定 nums = [0,0,1,1,1,2,2,3,3,4],
函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。
你不需要考虑数组中超出新长度后面的元素。
说明:
为什么返回数值是整数,但输出的答案是数组呢?
请注意,输入数组是以“引用”方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。
你可以想象内部操作如下:
// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
int len = removeDuplicates(nums);
// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
for (int i = 0; i < len; i++) {
print(nums[i]);
}
* @author liang
*
*/
public class RemoveDuplicatesFromSortedArray_26 {
/**
* 返回的是数组长度
* 维护current作为返回数组长度,每次出现不重复元素,就在nums[current]改变数据,并current++
* 维护pre = nums[index],之后index++,每次用pre与nums[index]比较
* @param nums
* @return
*/
public int removeDuplicates(int[] nums) {
if(nums.length == 0) {
return 0;
}
int current = 1;
int index = 1;
int pre = nums[0];
while(index<nums.length) {
if(!(nums[index] == pre)) {//如果不等,说明不是重复的了
nums[current++] = nums[index];
}
pre = nums[index];
index++;
}
return current;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| true |
b6f3c2bf29dcf4851433237f69a7618042107652 | Java | kevinstar9527/KaoLas | /app/src/main/java/kaola/zhanchengguo/com/kaola/download/ui/DownloadFragment.java | UTF-8 | 519 | 1.71875 | 2 | [] | no_license | package kaola.zhanchengguo.com.kaola.download.ui;
import kaola.zhanchengguo.com.kaola.R;
import kaola.zhanchengguo.com.kaola.other.ui.BaseFragment;
/**
* Created by Administrator on 2016/6/7.
*/
public class DownloadFragment extends BaseFragment {
@Override
protected int getLayoutId() {
return R.layout.fragment_download;
}
@Override
protected void initViews() {
}
@Override
protected void initEvents() {
}
@Override
protected void initDatas() {
}
}
| true |
0c026df9a01704b37dd1c10e3823e77b0de35716 | Java | sunce2019/myGitHub | /pay/src/main/java/com/pay/model/Discounts.java | UTF-8 | 2,483 | 2.09375 | 2 | [] | no_license | package com.pay.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Transient;
import org.springframework.stereotype.Repository;
/**
* 银行卡类, 基类
*@author star
*@version 创建时间:2019年6月1日下午1:14:19
*/
@Entity(name="discounts")
@Repository
public class Discounts implements Serializable{
private static final long serialVersionUID = -5604579225527613307L;
private int id;
private String theme;
private String vipAccount;
private String specialField;
private Integer status;
private String disTime;
private boolean editClick;
private boolean delClick;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="theme")
public String gettheme() {
return theme;
}
public void settheme(String theme) {
this.theme = theme;
}
@Column(name="vipAccount")
public String getvipAccount() {
return vipAccount;
}
public void setvipAccount(String vipAccount) {
this.vipAccount = vipAccount;
}
@Column(name="specialField")
public String getspecialField() {
return specialField;
}
public void setspecialField(String specialField) {
this.specialField = specialField;
}
@Column(name="status")
public Integer getstatus() {
return status;
}
public void setstatus(Integer status) {
this.status = status;
}
@Transient
public boolean isEditClick() {
return editClick;
}
public void setEditClick(boolean editClick) {
this.editClick = editClick;
}
@Transient
public boolean isDelClick() {
return delClick;
}
public void setDelClick(boolean delClick) {
this.delClick = delClick;
}
@Column(name="disTime")
public String getDisTime() {
return disTime;
}
public void setDisTime(String disTime) {
this.disTime = disTime;
}
/*
* @ManyToMany(fetch=FetchType.LAZY) //增加一张表,维护之间的关系
*
* @JoinTable( name="groupsuser",//中间表的名字 //关联当前表的外键名
* joinColumns=@JoinColumn(name="userid"), //关联对方表的外键名
* inverseJoinColumns=@JoinColumn(name="groupsid") ) public Set<Groups>
* getGroupsList() { return groupsList; }
*
*
* public void setGroupsList(Set<Groups> groupsList) { this.groupsList =
* groupsList; }
*/
}
| true |
a70d2eaf23b9350ce2f9e71cb1b12bbe7936fb89 | Java | Stoux/LijstrBackend | /src/main/java/nl/lijstr/security/util/JwtTokenHandler.java | UTF-8 | 4,443 | 2.703125 | 3 | [] | no_license | package nl.lijstr.security.util;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.time.LocalDateTime;
import java.util.function.Consumer;
import nl.lijstr.exceptions.security.AccessExpiredException;
import nl.lijstr.exceptions.security.TokenExpiredException;
import nl.lijstr.security.model.AuthenticationToken;
import nl.lijstr.security.model.JwtUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
/**
* A JSON Web Tokens Spring component that has various methods that ease the JWT flow.
*/
@Component
public class JwtTokenHandler {
private static final long ACCESS_MINUTES = 30L;
private static final long REMEMBER_ME_MINUTES = 60L * 24L * 30L;
private static final String JSON_PREFIX = "-";
private static final int JSON_PREFIX_LENGTH = JSON_PREFIX.length();
private final Gson gsonInstance;
@Value("${jwt.secret}")
private String secret;
@Autowired
private UserDetailsService userDetailsService;
/**
* Create a new {@link JwtTokenHandler}.
*/
public JwtTokenHandler() {
gsonInstance = new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer())
.create();
}
/**
* Parse a token into a validated JwtUser.
* This method throws {@link RuntimeException}s if the authentication failed.
*
* @param token The token
*
* @return the user
*/
public JwtUser parseToken(String token) {
//Parse the token & convert it
return parseTokenIntoUser(token, true, null);
}
private JwtUser parseTokenIntoUser(String token, boolean checkAccess, Consumer<String> usernameCallback) {
Jws<String> jws = Jwts.parser()
.setSigningKey(secret)
.parsePlaintextJws(token);
JwtUser user = gsonInstance.fromJson(jws.getBody().substring(JSON_PREFIX_LENGTH), JwtUser.class);
if (usernameCallback != null) {
usernameCallback.accept(user.getUsername());
}
//Check if expired
if (user.getValidTill().isBefore(LocalDateTime.now())) {
throw new TokenExpiredException();
}
//Check if still access
if (checkAccess && user.getAccessTill().isBefore(LocalDateTime.now())) {
throw new AccessExpiredException();
}
return user;
}
/**
* Generate a token based on a JwtUser.
*
* @param user The user
* @param rememberMe Should be active for a rememberMe length
*
* @return the token
*/
public AuthenticationToken generateToken(JwtUser user, boolean rememberMe) {
user.setAccessTill(LocalDateTime.now().plusMinutes(ACCESS_MINUTES));
user.setValidTill(rememberMe ? LocalDateTime.now().plusMinutes(REMEMBER_ME_MINUTES) : user.getAccessTill());
String token = generateToken(user);
return new AuthenticationToken(token, user.getAccessTill(), user.getValidTill(), user.getId());
}
private String generateToken(JwtUser user) {
return Jwts.builder()
.setPayload(JSON_PREFIX + gsonInstance.toJson(user))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
/**
* Refresh a token.
*
* @param token The token
* @param usernameCallback A callback that can be called if a valid username is detected
*
* @return The new token
*/
public AuthenticationToken refreshToken(String token, Consumer<String> usernameCallback) {
//Validate the token
JwtUser user = parseTokenIntoUser(token, false, usernameCallback);
//Refresh the user (updates permissions etc)
JwtUser refreshedUser = (JwtUser) userDetailsService.loadUserByUsername(user.getUsername());
//Check the validating key
if (user.getValidatingKey() != refreshedUser.getValidatingKey()) {
throw new TokenExpiredException();
}
boolean rememberMe = !(user.getAccessTill().isEqual(user.getValidTill()));
return generateToken(refreshedUser, rememberMe);
}
}
| true |
e43dfdf7b555305c8ccfb7aa531a00c208859013 | Java | GeoscienceAustralia/earthsci | /plugins/au.gov.ga.earthsci.worldwind/src/au/gov/ga/earthsci/worldwind/common/render/FrameBufferTexture.java | UTF-8 | 3,268 | 2.25 | 2 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*******************************************************************************
* Copyright 2012 Geoscience Australia
*
* 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 au.gov.ga.earthsci.worldwind.common.render;
import java.awt.Dimension;
import javax.media.opengl.GL2;
/**
* Class used by the {@link FrameBuffer} to generate/store the texture.
*
* @author Michael de Hoog (michael.dehoog@ga.gov.au)
*/
public class FrameBufferTexture
{
private int id = 0;
private int target = GL2.GL_TEXTURE_2D;
private int minificationFilter = GL2.GL_LINEAR;
private int magnificationFilter = GL2.GL_LINEAR;
private int internalFormat = GL2.GL_RGBA8;
private int format = GL2.GL_RGBA;
private int type = GL2.GL_UNSIGNED_BYTE;
protected void create(GL2 gl, Dimension dimensions)
{
delete(gl);
int[] textures = new int[1];
gl.glGenTextures(1, textures, 0);
if (textures[0] <= 0)
{
throw new IllegalStateException("Error generating texture for frame buffer");
}
id = textures[0];
gl.glBindTexture(getTarget(), id);
gl.glTexParameteri(getTarget(), GL2.GL_TEXTURE_MAG_FILTER, getMagnificationFilter());
gl.glTexParameteri(getTarget(), GL2.GL_TEXTURE_MIN_FILTER, getMinificationFilter());
gl.glTexParameteri(getTarget(), GL2.GL_TEXTURE_WRAP_S, GL2.GL_CLAMP);
gl.glTexParameteri(getTarget(), GL2.GL_TEXTURE_WRAP_T, GL2.GL_CLAMP);
gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_MODULATE);
gl.glTexImage2D(getTarget(), 0, getInternalFormat(), dimensions.width, dimensions.height, 0, getFormat(),
getType(), null);
gl.glBindTexture(getTarget(), 0);
}
protected void delete(GL2 gl)
{
if (isCreated())
{
gl.glDeleteTextures(1, new int[] { id }, 0);
id = 0;
}
}
public boolean isCreated()
{
return id > 0;
}
public int getId()
{
return id;
}
public int getTarget()
{
return target;
}
public void setTarget(int target)
{
this.target = target;
}
public int getMinificationFilter()
{
return minificationFilter;
}
public void setMinificationFilter(int minificationFilter)
{
this.minificationFilter = minificationFilter;
}
public int getMagnificationFilter()
{
return magnificationFilter;
}
public void setMagnificationFilter(int magnificationFilter)
{
this.magnificationFilter = magnificationFilter;
}
public int getInternalFormat()
{
return internalFormat;
}
public void setInternalFormat(int internalFormat)
{
this.internalFormat = internalFormat;
}
public int getFormat()
{
return format;
}
public void setFormat(int format)
{
this.format = format;
}
public int getType()
{
return type;
}
public void setType(int type)
{
this.type = type;
}
}
| true |
2e53c778d8dfee3bb3f71deacefe7f0a9e039171 | Java | Xiermires/agent-tools | /src/test/java/org/agenttools/Onomatopoeia.java | UTF-8 | 4,269 | 2.015625 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 2017, Xavier Miret Andres <xavier.mires@gmail.com>
*
* 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 org.agenttools;
import java.io.IOException;
import java.io.Serializable;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
class Onomatopoeia implements ClassFileTransformer, Serializable
{
private static final long serialVersionUID = 1L;
private final String sound;
private final String[] acceptTheseOnly;
Onomatopoeia(String sound, String... acceptTheseOnly)
{
this.sound = sound;
this.acceptTheseOnly = acceptTheseOnly;
}
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer)
throws IllegalClassFormatException
{
if (Objects.nonNull(className) && accept(className))
{
CtClass clazz = null;
try
{
clazz = getCtClass(className.replace('/', '.'), classfileBuffer);
if (clazz.isFrozen())
{
clazz.defrost();
}
makeSound(clazz);
return clazz.toBytecode();
}
catch (NotFoundException | IOException | CannotCompileException e)
{
System.err.println(e.getMessage());
}
finally
{
clazz.detach();
}
}
return classfileBuffer;
}
private CtClass getCtClass(String className, byte[] classByteCode) throws NotFoundException
{
final ClassPool classPool = new ClassPool();
classPool.appendSystemPath();
return classPool.get(className);
}
private void makeSound(CtClass clazz)
{
for (CtMethod method : clazz.getDeclaredMethods())
{
try
{
method.insertBefore("System.out.println(\"" + sound + "\");");
}
catch (CannotCompileException e)
{
System.err.println(e.getMessage());
}
}
}
// Using a predicate parameter throws serialization errors due to the owner of the anonymous class.
// Use a lazy initialization approach to filter.
/*private Predicate<String> remoteClasses()
{
return (Predicate<String> & Serializable) cn -> "org/testremote/Cat".equals(cn) || "org/testremote/Dog".equals(cn);
}*/
private Set<String> set = null;
private boolean accept(String className)
{
if (set == null)
{
set = new HashSet<>(Arrays.asList(acceptTheseOnly));
}
return set.contains(className);
}
}
| true |
ee25e1c4418a70bf092e75abd8b1487f01068191 | Java | hanifsgy/PantauPilkada | /app/src/main/java/panawaapps/pantaupilkada/adapter/CardKontestanAdapter.java | UTF-8 | 12,132 | 2.015625 | 2 | [] | no_license | package panawaapps.pantaupilkada.adapter;
/**
* Created by hanifsugiyanto on 04/11/15.
*/
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import panawaapps.pantaupilkada.R;
import panawaapps.pantaupilkada.activity.DariKandidatActivity;
import panawaapps.pantaupilkada.activity.KabupatenActivity;
import panawaapps.pantaupilkada.activity.KandidatActivity;
import panawaapps.pantaupilkada.model.CardKontestan;
public class CardKontestanAdapter extends RecyclerView.Adapter<CardKontestanAdapter.CardKontestanViewHolder> {
Context context;
List<CardKontestan> cardKotestans;
public CardKontestanAdapter(Context context, List<CardKontestan> cardKotestans) {
this.context = context;
this.cardKotestans = cardKotestans;
}
// public void delete(int position){
// kandidats.remove(position);
// notifyItemRemoved(position);
// }
public class CardKontestanViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
LinearLayout card_kontestan;
TextView daerahKontestan;
TextView jmlTps;
ImageView btnCollapse;
FrameLayout childCardKontestan;
ImageView fotoCalon1;
ImageView fotoWakil1;
TextView namaCalon1;
TextView namaWakil1;
ImageView fotoCalon2;
ImageView fotoWakil2;
TextView namaCalon2;
TextView namaWakil2;
ImageView fotoCalon3;
ImageView fotoWakil3;
TextView namaCalon3;
TextView namaWakil3;
ImageView fotoCalon4;
ImageView fotoWakil4;
TextView namaCalon4;
TextView namaWakil4;
ImageView fotoCalon5;
ImageView fotoWakil5;
TextView namaCalon5;
TextView namaWakil5;
ImageView fotoCalon6;
ImageView fotoWakil6;
TextView namaCalon6;
TextView namaWakil6;
TextView jmlPemilih1;
TextView jmlPemilih2;
TextView jmlPemilih3;
TextView jmlPemilih4;
TextView jmlPemilih5;
TextView jmlPemilih6;
TextView jmlPengamat;
TextView jmlPengawas;
TextView jmlSaksi;
TextView tglPemilihan;
TextView btn_pengawas;
CardKontestanViewHolder(View itemView) {
super(itemView);
card_kontestan = (LinearLayout)itemView.findViewById(R.id.card_kontestan);
daerahKontestan = (TextView) itemView.findViewById(R.id.tv_daerahCardKontestan);
jmlTps = (TextView) itemView.findViewById(R.id.tv_jmlTps);
btnCollapse = (ImageView) itemView.findViewById(R.id.iv_btnCollapse);
btnCollapse.setOnClickListener(this);
childCardKontestan = (FrameLayout) itemView.findViewById(R.id.layoutChildCardKontestan);
fotoCalon1 = (ImageView) itemView.findViewById(R.id.iv_fotoCalon1);
fotoCalon1.setOnClickListener(this);
fotoCalon2 = (ImageView) itemView.findViewById(R.id.iv_fotoCalon2);
fotoCalon3 = (ImageView) itemView.findViewById(R.id.iv_fotoCalon3);
fotoCalon4 = (ImageView) itemView.findViewById(R.id.iv_fotoCalon4);
fotoCalon5 = (ImageView) itemView.findViewById(R.id.iv_fotoCalon5);
fotoCalon6 = (ImageView) itemView.findViewById(R.id.iv_fotoCalon6);
fotoWakil1 = (ImageView) itemView.findViewById(R.id.iv_fotoWakil1);
fotoWakil2 = (ImageView) itemView.findViewById(R.id.iv_fotoWakil2);
fotoWakil3 = (ImageView) itemView.findViewById(R.id.iv_fotoWakil3);
fotoWakil4 = (ImageView) itemView.findViewById(R.id.iv_fotoWakil4);
fotoWakil5 = (ImageView) itemView.findViewById(R.id.iv_fotoWakil5);
fotoWakil6 = (ImageView) itemView.findViewById(R.id.iv_fotoWakil6);
namaCalon1 = (TextView) itemView.findViewById(R.id.tv_namaCalon1);
namaCalon2 = (TextView) itemView.findViewById(R.id.tv_namaCalon2);
namaCalon3 = (TextView) itemView.findViewById(R.id.tv_namaCalon3);
namaCalon4 = (TextView) itemView.findViewById(R.id.tv_namaCalon4);
namaCalon5 = (TextView) itemView.findViewById(R.id.tv_namaCalon5);
namaCalon6 = (TextView) itemView.findViewById(R.id.tv_namaCalon6);
namaWakil1 = (TextView) itemView.findViewById(R.id.tv_namaWakil1);
namaWakil2 = (TextView) itemView.findViewById(R.id.tv_namaWakil2);
namaWakil3 = (TextView) itemView.findViewById(R.id.tv_namaWakil3);
namaWakil4 = (TextView) itemView.findViewById(R.id.tv_namaWakil4);
namaWakil5 = (TextView) itemView.findViewById(R.id.tv_namaWakil5);
namaWakil6 = (TextView) itemView.findViewById(R.id.tv_namaWakil6);
jmlPemilih1 = (TextView) itemView.findViewById(R.id.tv_jmlPemilih1);
jmlPemilih2 = (TextView) itemView.findViewById(R.id.tv_jmlPemilih2);
jmlPemilih3 = (TextView) itemView.findViewById(R.id.tv_jmlPemilih3);
jmlPemilih4 = (TextView) itemView.findViewById(R.id.tv_jmlPemilih4);
jmlPemilih5 = (TextView) itemView.findViewById(R.id.tv_jmlPemilih5);
jmlPemilih6 = (TextView) itemView.findViewById(R.id.tv_jmlPemilih6);
jmlPengamat = (TextView) itemView.findViewById(R.id.tv_jmlPengamat);
jmlPengawas = (TextView) itemView.findViewById(R.id.tv_jmlPengawas);
jmlSaksi = (TextView) itemView.findViewById(R.id.tv_jmlSaksi);
tglPemilihan = (TextView) itemView.findViewById(R.id.tv_tglPemilihan);
btn_pengawas = (TextView) itemView.findViewById(R.id.btn_pengawas);
btn_pengawas.setOnClickListener(this);
/*
personName = (TextView)itemView.findViewById(R.id.person_name);
personAge = (TextView)itemView.findViewById(R.id.person_age);
personPhoto1 = (ImageView)itemView.findViewById(R.id.person_photo1);
personPhoto2 = (ImageView)itemView.findViewById(R.id.person_photo2);
*/
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.iv_btnCollapse:
if (childCardKontestan.getVisibility()== View.VISIBLE) {
childCardKontestan.setVisibility(View.GONE);
btnCollapse.setImageResource(R.drawable.accordion_white);
} else {
childCardKontestan.setVisibility(View.VISIBLE);
btnCollapse.setImageResource(R.drawable.accordion_up_white);
}
//membuat collapse layoutChildCardKontestan
break;
case R.id.iv_fotoCalon1:
//tak ganti
Intent pilihKandidat = new Intent(context, KandidatActivity.class);
context.startActivity(pilihKandidat);
break;
case R.id.btn_pengawas:
//start activity kabupaten and give TPS location id with "kind" from JSON. ex: if(kind=province) then start kabupaten activity. if(kind=kabupaten) then start kecamatan activity.
Intent PilihTPS = new Intent(context, KabupatenActivity.class);
context.startActivity(PilihTPS);
break;
// case R.id.buttonCloseCard:
// delete(getAdapterPosition());
// break;
}
}
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public CardKontestanViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_kontestan, viewGroup, false);
CardKontestanViewHolder ckvh = new CardKontestanViewHolder(v);
return ckvh;
}
@Override
public void onBindViewHolder(CardKontestanViewHolder cardKontestanViewHolder, int i) {
cardKontestanViewHolder.daerahKontestan.setText(cardKotestans.get(i).daerahCardKontestan);
cardKontestanViewHolder.jmlTps.setText(cardKotestans.get(i).jmlTps);
cardKontestanViewHolder.fotoCalon1.setImageResource(cardKotestans.get(i).fotoCalon1);
cardKontestanViewHolder.fotoCalon2.setImageResource(cardKotestans.get(i).fotoCalon2);
cardKontestanViewHolder.fotoCalon3.setImageResource(cardKotestans.get(i).fotoCalon3);
cardKontestanViewHolder.fotoCalon4.setImageResource(cardKotestans.get(i).fotoCalon4);
cardKontestanViewHolder.fotoCalon5.setImageResource(cardKotestans.get(i).fotoCalon5);
cardKontestanViewHolder.fotoCalon6.setImageResource(cardKotestans.get(i).fotoCalon6);
cardKontestanViewHolder.fotoWakil1.setImageResource(cardKotestans.get(i).fotoWakil1);
cardKontestanViewHolder.fotoWakil2.setImageResource(cardKotestans.get(i).fotoWakil2);
cardKontestanViewHolder.fotoWakil3.setImageResource(cardKotestans.get(i).fotoWakil3);
cardKontestanViewHolder.fotoWakil4.setImageResource(cardKotestans.get(i).fotoWakil4);
cardKontestanViewHolder.fotoCalon5.setImageResource(cardKotestans.get(i).fotoCalon5);
cardKontestanViewHolder.fotoCalon6.setImageResource(cardKotestans.get(i).fotoCalon6);
cardKontestanViewHolder.namaCalon1.setText(cardKotestans.get(i).namaCalon1);
cardKontestanViewHolder.namaCalon2.setText(cardKotestans.get(i).namaCalon2);
cardKontestanViewHolder.namaCalon3.setText(cardKotestans.get(i).namaCalon3);
cardKontestanViewHolder.namaCalon4.setText(cardKotestans.get(i).namaCalon4);
cardKontestanViewHolder.namaCalon5.setText(cardKotestans.get(i).namaCalon5);
cardKontestanViewHolder.namaCalon6.setText(cardKotestans.get(i).namaCalon6);
cardKontestanViewHolder.namaWakil1.setText(cardKotestans.get(i).namaWakil1);
cardKontestanViewHolder.namaWakil2.setText(cardKotestans.get(i).namaWakil2);
cardKontestanViewHolder.namaWakil3.setText(cardKotestans.get(i).namaWakil3);
cardKontestanViewHolder.namaWakil4.setText(cardKotestans.get(i).namaWakil4);
cardKontestanViewHolder.namaCalon5.setText(cardKotestans.get(i).namaCalon5);
cardKontestanViewHolder.namaCalon6.setText(cardKotestans.get(i).namaCalon6);
cardKontestanViewHolder.jmlPemilih1.setText(cardKotestans.get(i).jmlPemilih1);
cardKontestanViewHolder.jmlPemilih2.setText(cardKotestans.get(i).jmlPemilih2);
cardKontestanViewHolder.jmlPemilih3.setText(cardKotestans.get(i).jmlPemilih3);
cardKontestanViewHolder.jmlPemilih4.setText(cardKotestans.get(i).jmlPemilih4);
cardKontestanViewHolder.jmlPemilih5.setText(cardKotestans.get(i).jmlPemilih5);
cardKontestanViewHolder.jmlPemilih6.setText(cardKotestans.get(i).jmlPemilih6);
cardKontestanViewHolder.jmlPengamat.setText(cardKotestans.get(i).jmlPengamat);
cardKontestanViewHolder.jmlPengawas.setText(cardKotestans.get(i).jmlPengawas);
cardKontestanViewHolder.jmlSaksi.setText(cardKotestans.get(i).jmlSaksi);
cardKontestanViewHolder.tglPemilihan.setText(cardKotestans.get(i).tglPemilihan);
/*
cardKontestanViewHolder.personName.setText(kandidats.get(i).name);
cardKontestanViewHolder.personAge.setText(kandidats.get(i).age);
cardKontestanViewHolder.personPhoto1.setImageResource(kandidats.get(i).photoId1);
cardKontestanViewHolder.personPhoto2.setImageResource(kandidats.get(i).photoId2);
*/
}
@Override
public int getItemCount() {
return cardKotestans == null ? 0 : cardKotestans.size();
}
// @Override
// public int getItemCount() {
// return cardKotestans.size();
// }
} | true |
90ee3b5a03692dbd738446ddb8c36407c77b4641 | Java | fpadojino/TourApp | /src/com/example/tourapp/DivisionActivity.java | UTF-8 | 918 | 2.484375 | 2 | [] | no_license | package com.example.tourapp;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;
public class DivisionActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.divisionactivity);
Database database = new Database(this);
SQLiteDatabase db = database.getDatabase();
int index = 2;
String object = database.place(db, "idPlace", index) + " " + database.place(db, "name", index) + " " + database.place(db, "lon", index) + " " +database.place(db, "lat", index)+ " " + database.place(db, "description", index)+ " " +database.place(db, "directionsFromPrevious", index)+ " " +database.place(db, "directionsToNext", index);
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(object);
}
}
| true |
1abfc43a4121e872436f7c4212039ffa35f06e36 | Java | toanphamtrong/Team2-ITSol | /io_mock/src/main/java/itsol_project/itsolwebserver/entity/Cart.java | UTF-8 | 453 | 2.0625 | 2 | [] | no_license | package itsol_project.itsolwebserver.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
@Setter
@Getter
@Entity
public class Cart extends BaseEntity{
@ManyToOne
private User user;
private Long totalMonneyCart; //tong gia tri all don hang
private Long totalNumber; //tong so luong san pham
@ManyToOne
private Product product ;
public Cart() {
}
}
| true |
583abf5e00746d7237698714a1f3d4da5ccd30f4 | Java | aziendazero/ecm | /src/main/java/it/tredi/ecm/web/bean/SedutaWrapper.java | UTF-8 | 848 | 1.695313 | 2 | [] | no_license | package it.tredi.ecm.web.bean;
import java.util.Map;
import java.util.Set;
import it.tredi.ecm.dao.entity.Accreditamento;
import it.tredi.ecm.dao.entity.Seduta;
import it.tredi.ecm.dao.entity.ValutazioneCommissione;
import it.tredi.ecm.dao.enumlist.AccreditamentoStatoEnum;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class SedutaWrapper {
private Seduta seduta;
private boolean canEdit;
private boolean canValidate;
private boolean canConfirmEvaluation;
private String motivazioneDaInserire;
private Long idAccreditamentoDaInserire;
private Set<Accreditamento> domandeSelezionabili;
private Set<Seduta> seduteSelezionabili;
private Seduta sedutaTarget;
private ValutazioneCommissione valutazioneTarget;
private Map<Long, Set<AccreditamentoStatoEnum>> mappaStatiValutazione;
private boolean canBloccaSeduta;
}
| true |
ed754d8e59ff9cfa327e008a049692a8eb1ca50e | Java | 523499159/kettle-web | /MGRSite_COM/src/main/java/com/thinkgem/jeesite/mybatis/modules/arithmetic/util/ConsecdaysTemp.java | UTF-8 | 2,944 | 2.484375 | 2 | [
"Apache-2.0"
] | permissive | package com.thinkgem.jeesite.mybatis.modules.arithmetic.util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class ConsecdaysTemp {
public static void main(String[] args){
ConsecdaysTemp.getConsecdaysTemp();
}
public static Object getConsecdaysTemp() {
List date = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.println("请输入起始日期,格式:yyyyMMdd");
Long dbtime2 = Long.valueOf(input.nextLine()); //第一个日期
date.add(dbtime2);
System.out.println("请输入终止日期,格式:yyyyMMdd");
Long dbtime1 = Long.valueOf(input.nextLine()); //第二个日期
date.add(dbtime1);
System.out.println(date);
HashMap<String, Object> params = new HashMap<String, Object>();
String result = HttpClientUtil.get("http://121.36.14.224:8085/temperaturedata/selectStaTemp", params);
JSONObject jsonObj = JSONObject.fromObject(result);
System.out.println(jsonObj);
JSONArray ja = jsonObj.getJSONArray("data");
JSONArray array1 = new JSONArray();
JSONArray index = new JSONArray();
String time;
int n=0,m=1;
for (int i = 0; i < ja.size(); i++) {
if(ja.getJSONObject(i).getDouble("highest_temperature")>(-1.0)) {
index.add(i);
}
}System.out.println(index);
for (int j = 0;j < index.size();j++){
time =ja.getJSONObject(index.getInt(j)).getString("information_time");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
Date aa = dateFormat.parse(time);
array1.add(aa);
}catch (ParseException e){
e.printStackTrace();
}
System.out.println(time);
}System.out.println(array1);
/* try {
List<Long> longList = array1.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
System.out.println(longList);
}catch (NumberFormatException e){
e.fillInStackTrace();
}*/
/*for (int t = 0;t <num.length;t++){
if(num[t]<date.get(0)){
}
}*/
/* List<Integer> c = new LinkedList<Integer>(); // 连续的子数组
c.add(index.getInt(0));
for (int j = 0; j < index.size() - 1; ++j) {
if (index.getInt(j)+ 1 == ns[i+1]) {
c.add(ns[i+1]);
} else {
if (c.size() > 1) {
System.out.println(c);
}
c.clear();
c.add(ns[i+1]);
}
}
if (c.size() > 1) {
System.out.println(c);
}
}
}*/
return params;
}
}
| true |
101be2cc1ecf4658958da5458dc2c1ca84b00bc1 | Java | danielixmax/Demostracion | /src/java/controlador/ControlNumeros.java | UTF-8 | 742 | 1.890625 | 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 controlador;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* @author axel_
*/
@ManagedBean
@RequestScoped
public class ControlNumeros {
// @ManagedProperty(value = "#{numerosBean}")
//private NumerosBean numerosBean = new NumerosBean();
// public void sumarNumeros(){
// this.numerosBean.getNumeros().setResultado(
// + this.numerosBean.getNumeros().getNumero1()
//+ this.numerosBean.getNumeros.getNumero2());
//}
}
| true |
963727b7ffd1b5cbe1700c57a84a197122db1d16 | Java | DRV2EGR/Flats.io | /src/test/java/io/flats/JWT_AUTH/controller/AuthenticationControllerTest.java | UTF-8 | 9,038 | 1.945313 | 2 | [] | no_license | package io.flats.JWT_AUTH.controller;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyLong;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.when;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.flats.JWT_AUTH.dto.AuthenticationRequestDto;
import io.flats.JWT_AUTH.dto.JwtAuthDto;
import io.flats.JWT_AUTH.jwt.JwtTokenProvider;
import io.flats.JWT_AUTH.service.UserService;
import io.flats.entity.Comments;
import io.flats.entity.Likes;
import io.flats.entity.Role;
import io.flats.entity.User;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Optional;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@ContextConfiguration(classes = {AuthenticationController.class})
@ExtendWith(SpringExtension.class)
public class AuthenticationControllerTest {
@Autowired
private AuthenticationController authenticationController;
@MockBean
private AuthenticationManager authenticationManager;
@MockBean
private JwtTokenProvider jwtTokenProvider;
@MockBean
private UserService userService;
@Test
public void testLogin() throws Exception {
Role role = new Role();
role.setId(123L);
role.setName("Name");
User user = new User();
user.setLastName("Doe");
user.setEmail("jane.doe@example.org");
user.setPassword("iloveyou");
user.setActivationCode("Activation Code");
user.setId(123L);
user.setPhoneNumber("4105551212");
user.setTimeOfAccountCreation(LocalDateTime.of(1, 1, 1, 1, 1));
user.setUserProfileImageUrl("https://example.org/example");
user.setFirstName("Jane");
user.setReceivedCommentsToFlats(new ArrayList<Comments>());
user.setUsername("janedoe");
user.setSecondName("Second Name");
user.setPuttedLikesToFlats(new ArrayList<Likes>());
user.setPuttedCommentsToFlats(new ArrayList<Comments>());
user.setRating(10.0f);
user.setRole(role);
Optional<User> ofResult = Optional.<User>of(user);
when(this.userService.findByEmail(anyString())).thenReturn(ofResult);
when(this.jwtTokenProvider.createRefreshToken(anyLong())).thenReturn("foo");
when(this.jwtTokenProvider.createAccessToken((User) any())).thenReturn("foo");
when(this.authenticationManager.authenticate((org.springframework.security.core.Authentication) any()))
.thenReturn(new TestingAuthenticationToken("Principal", "Credentials"));
AuthenticationRequestDto authenticationRequestDto = new AuthenticationRequestDto();
authenticationRequestDto.setEmail("jane.doe@example.org");
authenticationRequestDto.setPassword("iloveyou");
String content = (new ObjectMapper()).writeValueAsString(authenticationRequestDto);
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/api/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(content);
MockMvcBuilders.standaloneSetup(this.authenticationController)
.build()
.perform(requestBuilder)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType("application/json"))
.andExpect(MockMvcResultMatchers.content()
.string(Matchers
.containsString("{\"username\":\"janedoe\",\"accessToken\":\"foo\",\"refreshToken\":\"foo\"}")));
}
@Test
public void testLogin2() throws Exception {
Role role = new Role();
role.setId(123L);
role.setName("Name");
User user = new User();
user.setLastName("Doe");
user.setEmail("jane.doe@example.org");
user.setPassword("iloveyou");
user.setActivationCode("Activation Code");
user.setId(123L);
user.setPhoneNumber("4105551212");
user.setTimeOfAccountCreation(LocalDateTime.of(1, 1, 1, 1, 1));
user.setUserProfileImageUrl("https://example.org/example");
user.setFirstName("Jane");
user.setReceivedCommentsToFlats(new ArrayList<Comments>());
user.setUsername("janedoe");
user.setSecondName("Second Name");
user.setPuttedLikesToFlats(new ArrayList<Likes>());
user.setPuttedCommentsToFlats(new ArrayList<Comments>());
user.setRating(10.0f);
user.setRole(role);
Optional<User> ofResult = Optional.<User>of(user);
when(this.userService.findByEmail(anyString())).thenReturn(ofResult);
when(this.jwtTokenProvider.createRefreshToken(anyLong())).thenThrow(new IllegalArgumentException("foo"));
when(this.jwtTokenProvider.createAccessToken((User) any())).thenReturn("foo");
when(this.authenticationManager.authenticate((org.springframework.security.core.Authentication) any()))
.thenReturn(new TestingAuthenticationToken("Principal", "Credentials"));
AuthenticationRequestDto authenticationRequestDto = new AuthenticationRequestDto();
authenticationRequestDto.setEmail("jane.doe@example.org");
authenticationRequestDto.setPassword("iloveyou");
String content = (new ObjectMapper()).writeValueAsString(authenticationRequestDto);
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/api/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(content);
ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(this.authenticationController)
.build()
.perform(requestBuilder);
actualPerformResult.andExpect(MockMvcResultMatchers.status().isForbidden());
}
@Test
public void testLogin3() throws Exception {
when(this.userService.findByEmail(anyString())).thenReturn(Optional.<User>empty());
when(this.jwtTokenProvider.createRefreshToken(anyLong())).thenReturn("foo");
when(this.jwtTokenProvider.createAccessToken((User) any())).thenReturn("foo");
when(this.authenticationManager.authenticate((org.springframework.security.core.Authentication) any()))
.thenReturn(new TestingAuthenticationToken("Principal", "Credentials"));
AuthenticationRequestDto authenticationRequestDto = new AuthenticationRequestDto();
authenticationRequestDto.setEmail("jane.doe@example.org");
authenticationRequestDto.setPassword("iloveyou");
String content = (new ObjectMapper()).writeValueAsString(authenticationRequestDto);
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/api/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(content);
ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(this.authenticationController)
.build()
.perform(requestBuilder);
actualPerformResult.andExpect(MockMvcResultMatchers.status().isForbidden());
}
@Test
public void testRefresh() throws Exception {
when(this.jwtTokenProvider.refreshPairOfTokens(anyString())).thenReturn(new JwtAuthDto());
JwtAuthDto jwtAuthDto = new JwtAuthDto();
jwtAuthDto.setRefreshToken("ABC123");
jwtAuthDto.setAccessToken("ABC123");
jwtAuthDto.setUsername("janedoe");
String content = (new ObjectMapper()).writeValueAsString(jwtAuthDto);
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/api/auth/refresh")
.contentType(MediaType.APPLICATION_JSON)
.content(content);
MockMvcBuilders.standaloneSetup(this.authenticationController)
.build()
.perform(requestBuilder)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType("application/json"))
.andExpect(MockMvcResultMatchers.content()
.string(Matchers.containsString("{\"username\":null,\"accessToken\":null,\"refreshToken\":null}")));
}
}
| true |
6728259264ef727c08cefd702891d7e7632f9a03 | Java | ybujiabei/project | /src/com/ten/project/bean/Type.java | UTF-8 | 1,345 | 2.0625 | 2 | [] | no_license | package com.ten.project.bean;
import java.util.Date;
public class Type {
// `goodid` int(11) NOT NULL AUTO_INCREMENT,
// `color` varchar(5) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
// `brand` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
// `goodtype` int(1) NULL DEFAULT NULL,
// `gtime` date NULL DEFAULT NULL,
// `gflag` int(1) NULL DEFAULT NULL,
private Integer goodid;
private String color;
private String brand;
private Integer goodtype;
private Date gtime;
private Integer gflag;
public Integer getGoodid() {
return goodid;
}
public void setGoodid(Integer goodid) {
this.goodid = goodid;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getGoodtype() {
return goodtype;
}
public void setGoodtype(Integer goodtype) {
this.goodtype = goodtype;
}
public Date getGtime() {
return gtime;
}
public void setGtime(Date gtime) {
this.gtime = gtime;
}
public Integer getGflag() {
return gflag;
}
public void setGflag(Integer gflag) {
this.gflag = gflag;
}
} | true |
64df21f4430c875d1286a73033ff68dfed3a6a72 | Java | yangbaoyi/AddWidget | /AddWidget/src/com/example/addwidget/myWidgetProvider.java | UTF-8 | 1,477 | 2.015625 | 2 | [] | no_license | package com.example.addwidget;
import android.annotation.SuppressLint;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class myWidgetProvider extends AppWidgetProvider {
@SuppressLint("NewApi") @Override
public void onAppWidgetOptionsChanged(Context context,
AppWidgetManager appWidgetManager, int appWidgetId,
Bundle newOptions) {
// TODO Auto-generated method stub
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId,
newOptions);
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onDeleted(context, appWidgetIds);
}
@Override
public void onDisabled(Context context) {
// TODO Auto-generated method stub
super.onDisabled(context);
}
@Override
public void onEnabled(Context context) {
// TODO Auto-generated method stub
super.onEnabled(context);
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
super.onReceive(context, intent);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
Toast.makeText(context, "appWidgetIds = " + appWidgetIds.length, 0).show();
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
}
| true |
1a7472b0b76987c5b625b060942e218061bc6d91 | Java | jbroot/AdvancedAlgorithms | /cs5420-6/src/main/java/RegExMatcher.java | UTF-8 | 4,173 | 3.15625 | 3 | [] | no_license | /* Adapted from the textbook's site at
* https://algs4.cs.princeton.edu/54regexp/NFA.java.html
*/
import java.util.LinkedList;
import java.util.Stack;
public class RegExMatcher {
public static Graph graph;
private static Graph constructNFA(final String pattern, final int M) {
Stack<Integer> ops = new Stack<Integer>();
Graph g = new Graph(M + 1); // Using a directed graph
for (int i = 0; i < M; i++) {
char ichar = pattern.charAt(i);
int lp = i;
if (ichar == '(' || ichar == '|') {
ops.push(i);
} else if (ichar == ')') {
//get place of '(' or '|'
int or = ops.pop();
// ORs
if(pattern.charAt(or)=='|'){
int[] arr = new int[ops.capacity()];
int arri=0;
//arr = places of |s to first (
for(arr[0] = or; pattern.charAt(arr[arri])=='|'; arr[++arri]=ops.pop()){}
//lp = place of (
lp = arr[arri];
for(int ori=0; arr[ori]!=lp; ++ori){
//add edges from ( to node after each |
g.addEdge(lp, arr[ori]+1);
//add edges from each | to )
g.addEdge(arr[ori], i);
}
}
else if (pattern.charAt(or) == '(') {
lp = or;
}
else assert false;
}
if (i < M - 1){
//if meta doesn't apply to () then lp = i
if(ichar != ')') lp = i;
// Closure *
if(pattern.charAt(i + 1) == '*') {
//can skip or go back
g.addEdge(lp, i + 1);
g.addEdge(i + 1, lp);
}
else if(pattern.charAt(i+1)=='+'){
//possible to go back but not skip
g.addEdge(i+1,lp);
}
else if(pattern.charAt(i+1)=='?'){
//possible to skip
g.addEdge(lp, i+1);
}
}
//if metachar then add edge to next state
if (ichar == '(' || ichar == '*' || ichar == '+' ||
ichar == ')' || ichar == '?') {
g.addEdge(i, i + 1);
}
}
if (ops.size() != 0) {
throw new IllegalArgumentException("Invalid regular expression");
}
graph = g;
return g;
}
//if the char in text matches the correct position in pattern check if the node
//that the matching char virtually points to is reachable given previous conditions
public static boolean recognizes(String pattern, String text) {
final int M = pattern.length();
Graph g = constructNFA(pattern, M);
DepthFirstSearch dfs = new DepthFirstSearch(g, 0);
//pc = list of reachable vertices
LinkedList<Integer> pc = new LinkedList<Integer>();
for (int v = 0; v < g.V(); v++) {
if (dfs.reachable(v)) {
pc.add(v);
}
}
for (int i = 0; i < text.length(); i++) {
// Don't allow metacharacters (used in specifying patterns) in text
if (text.charAt(i) == '*' || text.charAt(i) == '|' ||
text.charAt(i) == '(' || text.charAt(i) == ')'||
text.charAt(i) == '.' || text.charAt(i) == '?'||
text.charAt(i) == '+') {
throw new IllegalArgumentException("Metacharacters (, *, |, and ) not allowed.");
}
//match = all reachable vertex (pc) + 1 that == text[i]
LinkedList<Integer> match = new LinkedList<Integer>();
//for reachable vertex in list
for (int v : pc) {
if (v == M) continue;
if ((pattern.charAt(v) == text.charAt(i)) || pattern.charAt(v) == '.')
match.add(v + 1);
}
//do dfs for all in match (set of matching char plus one node)
//all nodes reachable by any in match are black
dfs = new DepthFirstSearch(g, match);
pc = new LinkedList<Integer>();
//pc = all in matches if reachable--if accept state in here then return true later
for (int v = 0; v < g.V(); v++) {
if (dfs.reachable(v)) pc.add(v);
}
// Return if no states reachable
if (pc.size() == 0) {
return false;
}
}
// Check for accept state
for (int v : pc) {
if (v == M) {
return true;
}
}
return false;
}
}
| true |
329bdeda3d201fb39c91b1d4cfca9327739dcf01 | Java | enriquesleon/SDSUClassSchedule | /SdsuScheduleViewer/src/com/enrique/leon/RequestService/JsoupRequest.java | UTF-8 | 1,729 | 2.53125 | 3 | [] | no_license | package com.enrique.leon.RequestService;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.*;
import org.jsoup.nodes.Document;
import com.enrique.leon.ClassModel.QueryPair;
public class JsoupRequest extends Request{
private Connection connection;
public JsoupRequest(String host) throws ScheduleRequestException{
this(host,new ArrayList<QueryPair>());
}
public JsoupRequest(String host,List<QueryPair> params) throws ScheduleRequestException {
super(host,params);
}
@Override
protected Request buildRequest() throws ScheduleRequestException {
String connectionUrl = host;
if(path!=null||!path.equals("")){
connectionUrl = host+path;
}
connection = Jsoup.connect(connectionUrl);
if(this.params.size()!=0){
for(QueryPair getQuery:params){
this.connection.data(getQuery.getKey(), getQuery.getValue());
}
}
return this;
}
@Override
public RequestContent getRequestContent() throws ScheduleRequestException {
try {
Document doc = connection.get();
String body = doc.body().outerHtml();
String code = String.valueOf(connection.response().statusCode());
String url = doc.location();
return new JsoupRequestContent(body, code, url, doc);
} catch(MalformedURLException e){
throw new ScheduleRequestException("Malformed Url",e);
}catch (UnsupportedMimeTypeException e){
throw new ScheduleRequestException("Mime Type Error",e);
}catch (SocketTimeoutException e){
//TODO
throw new ScheduleRequestException("Socket Timeout",e);
}catch (IOException e){
throw new ScheduleRequestException("Fatal Connection Error",e);
}
}
}
| true |
029ada12178c18f627eea2f643defff33a9731f3 | Java | shreerai001/ecommerce-android | /app/src/main/java/com/shree/ecom/activityPasswordChange/service/ChangePasswordApiService.java | UTF-8 | 648 | 2.125 | 2 | [] | no_license | package com.shree.ecom.activityPasswordChange.service;
import com.shree.ecom.utils.values.BaseResponseEntity;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Header;
import retrofit2.http.POST;
public interface ChangePasswordApiService {
@POST("my-account/change-password")
@FormUrlEncoded
Call<BaseResponseEntity> changePassword(
@Header("Authorization") String auth,
@Field("current_password") String currentPassword,
@Field("password") String password,
@Field("password_confirmation") String passwordConfirmation);
}
| true |
d0a59f2a7b7d6bd869f1e23402af49b1a972d1ed | Java | daleran/GroupThinq | /backend/src/main/java/org/psu/edu/sweng/capstone/backend/exception/ExceptionResolver.java | UTF-8 | 2,841 | 2.296875 | 2 | [] | no_license | package org.psu.edu.sweng.capstone.backend.exception;
import org.psu.edu.sweng.capstone.backend.dto.ResponseEntity;
import org.psu.edu.sweng.capstone.backend.dto.ResponseError;
import org.psu.edu.sweng.capstone.backend.enumeration.ErrorEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class ExceptionResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionResolver.class);
@ExceptionHandler(value = EntityConflictException.class)
@ResponseStatus(value = HttpStatus.CONFLICT)
public @ResponseBody ResponseEntity<String> handleEntityConflict(final EntityConflictException e) {
ResponseEntity<String> response = new ResponseEntity<>();
LOGGER.error(e.getMessage(), e);
response.setSuccess(false);
response.setStatus(HttpStatus.CONFLICT.value());
response.getErrors().add(new ResponseError(ErrorEnum.RESOURCE_CONFLICT, e.getMessage()));
return response;
}
@ExceptionHandler(value = EntityNotFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public @ResponseBody ResponseEntity<String> handleEntityNotFound(final EntityNotFoundException e) {
ResponseEntity<String> response = new ResponseEntity<>();
LOGGER.error(e.getMessage(), e);
response.setSuccess(false);
response.setStatus(HttpStatus.NOT_FOUND.value());
response.getErrors().add(new ResponseError(ErrorEnum.ENTITY_NOT_FOUND, e.getMessage()));
return response;
}
@ExceptionHandler(value = AccessDeniedException.class)
@ResponseStatus(value = HttpStatus.FORBIDDEN)
public @ResponseBody ResponseEntity<String> handleUnauthorizedAccess(final AccessDeniedException e) {
ResponseEntity<String> response = new ResponseEntity<>();
LOGGER.error(e.getMessage(), e);
response.setSuccess(false);
response.setStatus(HttpStatus.FORBIDDEN.value());
response.getErrors().add(new ResponseError(ErrorEnum.UNAUTHORIZED_ACTION, e.getMessage()));
return response;
}
@ExceptionHandler(value = Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public @ResponseBody ResponseEntity<String> handleSystemException(final Exception e) {
ResponseEntity<String> response = new ResponseEntity<>();
LOGGER.error("Exception thrown:", e);
response.setSuccess(false);
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.getErrors().add(new ResponseError(ErrorEnum.EXCEPTION_THROWN, e.getMessage()));
return response;
}
}
| true |
2dcd8c367d43ac6ce3743d5f16c8967a216b128a | Java | Dev222-sys/Razing365 | /domain/src/main/java/com/razinggroups/domain/model/leave/FetchSingleEmployeeLeave.java | UTF-8 | 710 | 2.234375 | 2 | [] | no_license | package com.razinggroups.domain.model.leave;
import java.util.List;
public class FetchSingleEmployeeLeave {
public String count;
public List<FetchSingleEmployeeLeaveRecord> records = null;
public FetchSingleEmployeeLeave(String count, List<FetchSingleEmployeeLeaveRecord> records) {
this.count = count;
this.records = records;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public List<FetchSingleEmployeeLeaveRecord> getRecords() {
return records;
}
public void setRecords(List<FetchSingleEmployeeLeaveRecord> records) {
this.records = records;
}
}
| true |
301a9122821ed38a841a47ed0ea4b986c5593d29 | Java | darshanhs90/Java-Coding | /src/yelpInterview/_BT10LevelOrderSpiralForm.java | UTF-8 | 1,106 | 3.375 | 3 | [
"MIT"
] | permissive | package yelpInterview;
public class _BT10LevelOrderSpiralForm {
static class Node{
Node left,right;
int value;
public Node(int value) {
this.value=value;
}
}
public static void main(String a[]){
Node n=new Node(1);
n.left=new Node(2);
n.right=new Node(3);
n.left.left=new Node(4);
n.left.right=new Node(5);
n.right.left=new Node(6);
n.right.right=new Node(7);
levelOrderSpiral(n);System.out.println();
}
private static void levelOrderSpiral(Node n) {
if(n!=null)
{
boolean flag=true;
for (int i = 0; i < getHeight(n); i++) {
printNodes(n,i,flag);
flag=!flag;
}
}
}
private static void printNodes(Node n, int i, boolean flag) {
if(n!=null)
{
if(i==0)
System.out.println(n.value);
else if(i>0)
{
if(flag)
{
printNodes(n.left, i-1, flag);
printNodes(n.right, i-1, flag);
}else{
printNodes(n.right, i-1, flag);
printNodes(n.left, i-1, flag);
}
}
}
}
private static int getHeight(Node n) {
if(n!=null)
{
return 1+Math.max(getHeight(n.left), getHeight(n.right));
}
return 0;
}
}
| true |
2b991aa26c2ff6a4a3a0c685180d33209ca25a79 | Java | madtrax/generator-angular-spring | /app/templates/base-project/src/test/java/package/controller/ApplicationControllerTest.java | UTF-8 | 833 | 1.875 | 2 | [
"Apache-2.0"
] | permissive | package <%= properties.packageName %>.controller;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/application-config.xml", "classpath:spring/mvc-config.test.xml" })
public class ApplicationControllerTest {
@Autowired
private ApplicationController applicationController;
@Test
public void testConfigEndpoint() {
Map<String, String> res = applicationController.config();
Assert.notNull(res);
Assert.notEmpty(res);
Assert.isTrue(res.size() == 3);
}
}
| true |
0f5a89cbf18ce314a9e064f90b79ea2fbae7a927 | Java | lvfangmin/algorithms | /detail/ZigZagConversion.java | UTF-8 | 1,477 | 3.546875 | 4 | [] | no_license | /**
* The string "PAYPALISHIRING" is written in a zigzag pattern on a given number
* of rows like this:
* you may want to display this pattern in a fixed font for better legibility
*
* P A H N
* A P L S I I G
* Y I R
* And then read line by line: "PAHNAPLSIIGYIR"
* Write the code that will take a string and make this conversion given a
* number of rows:
*
* string convert(string text, int nRows);
* convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
*
* convert("PAYPALISHIRING", 4) should return "PINALSIGYAHRPI".
*
* P I N
* A L S I G
* Y A H R
* P I
*/
public class Solution {
public String convert(String s, int nRows) {
int len = s.length();
if (len <= nRows || nRows <= 1) {
return s;
}
// check the sample to find the rule for each row
int steps = 2 * nRows - 2;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nRows; i++) {
int step = steps - i * 2;
if (step == 0) {
step = steps;
}
// the steps for each round is:
// (steps - 2i), (2i), (steps - 2i), (2i)...
int j = i;
while (j < s.length()) {
sb.append(s.charAt(j));
j += step;
if (step != steps) {
step = steps - step;
}
}
}
return sb.toString();
}
}
| true |
4e9296673f7f1f2236d79f77d2f368675992d13e | Java | corporaterat/springjdbc-iterable | /src/main/java/com/alexkasko/springjdbc/iterable/IterableNamedParameterJdbcTemplate.java | UTF-8 | 3,425 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | package com.alexkasko.springjdbc.iterable;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import javax.sql.DataSource;
import java.util.Map;
/**
* {@code NamedParameterJdbcTemplate} extension. All methods, that return {@code List}
* mirrored with {@code queryForIter} methods that return {@link CloseableIterator}.
*
* @author alexkasko
* Date: 11/7/12
*/
public class IterableNamedParameterJdbcTemplate extends NamedParameterJdbcTemplate implements IterableNamedParameterJdbcOperations {
/**
* Constructor
*
* @param dataSource data source
*/
public IterableNamedParameterJdbcTemplate(DataSource dataSource) {
super(new IterableJdbcTemplate(dataSource));
}
/**
* Constructor, takes {@code fetchSize}
*
* @param dataSource data source
* @param fetchSize <a href=http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/jdbc/core/JdbcTemplate.html#setFetchSize%28int%29>fetchSize</a> property value
*/
public IterableNamedParameterJdbcTemplate(DataSource dataSource, int fetchSize) {
super(new IterableJdbcTemplate(dataSource, fetchSize));
}
/**
* {@inheritDoc}
*/
@Override
public IterableJdbcOperations getIterableJdbcOperations() {
return (IterableJdbcOperations) getJdbcOperations();
}
/**
* {@inheritDoc}
*/
@Override
public <T> CloseableIterator<T> queryForIter(String sql, SqlParameterSource paramSource, RowMapper<T> rowMapper) throws DataAccessException {
return getIterableJdbcOperations().queryForIter(getPreparedStatementCreator(sql, paramSource), rowMapper);
}
/**
* {@inheritDoc}
*/
@Override
public <T> CloseableIterator<T> queryForIter(String sql, Map<String, ?> paramMap, RowMapper<T> rowMapper) throws DataAccessException {
return queryForIter(sql, new MapSqlParameterSource(paramMap), rowMapper);
}
/**
* {@inheritDoc}
*/
@Override
public <T> CloseableIterator<T> queryForIter(String sql, SqlParameterSource paramSource, Class<T> elementType) throws DataAccessException {
return queryForIter(sql, paramSource, new SingleColumnRowMapper<T>(elementType));
}
/**
* {@inheritDoc}
*/
@Override
public <T> CloseableIterator<T> queryForIter(String sql, Map<String, ?> paramMap, Class<T> elementType) throws DataAccessException {
return queryForIter(sql, new MapSqlParameterSource(paramMap), elementType);
}
/**
* {@inheritDoc}
*/
@Override
public CloseableIterator<Map<String, Object>> queryForIter(String sql, SqlParameterSource paramSource) throws DataAccessException {
return queryForIter(sql, paramSource, new ColumnMapRowMapper());
}
/**
* {@inheritDoc}
*/
@Override
public CloseableIterator<Map<String, Object>> queryForIter(String sql, Map<String, ?> paramMap) throws DataAccessException {
return queryForIter(sql, new MapSqlParameterSource(paramMap));
}
}
| true |
4c30d4b8cc865c4fe8b3766cda8e86673032f390 | Java | JetBrains/intellij-community | /java/java-tests/testData/ipp/com/siyeh/ipp/exceptions/detail/PolyadicParentheses.java | UTF-8 | 355 | 2.390625 | 2 | [
"Apache-2.0"
] | permissive | package com.siyeh.ipp.exceptions.detail;
import java.io.IOException;
public class PolyadicParentheses {
void box() {
try {
System.out.println(one() && (two()) && one());
} c<caret>atch (Exception e) {}
}
boolean one() throws IOException {
return false;
}
boolean two() throws NoSuchFieldException {
return false;
}
} | true |
245a28e2b9044ac79032516e8021728370214b94 | Java | serendin/BookingSystem | /src/com/service/impl/UserServiceImpl.java | UTF-8 | 649 | 2.328125 | 2 | [] | no_license | package com.service.impl;
import java.util.List;
import com.bean.User;
import com.dao.UserDao;
import com.service.UserService;
public class UserServiceImpl implements UserService{
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao=userDao;
}
public void save(User user){
userDao.save(user);
}
public void update(User user){
userDao.update(user);
}
public User check(User user){
User existUser=userDao.findByUsernameAndPassword(user);
return existUser;
}
public List<User> findAll() {
return userDao.findAll();
}
public User findById(Integer userid) {
return userDao.findById(userid);
}
}
| true |
d8de65c4d39499805574ef4fc317970cac2f1079 | Java | ananthoju24/angular8 | /vts/src/main/java/com/vts/beans/TaxDetails.java | UTF-8 | 524 | 1.96875 | 2 | [] | no_license | package com.vts.beans;
import java.io.Serializable;
import java.util.List;
import org.springframework.stereotype.Component;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@NoArgsConstructor
@ToString
@Component
public class TaxDetails implements Serializable {
private static final long serialVersionUID = 1L;
private String ownerName;
private String hno;
private List<TaxData> taxDataList;
private TaxData currentTaxData;
private TaxData dueTaxData;
private String date;
}
| true |
f9cb78c2ae21e2387efbd2916232bb665db1f222 | Java | ivanduarte16/Figura2 | /src/main/java/Lienzo.java | UTF-8 | 6,234 | 3.484375 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.Collections;
public class Lienzo {
private static ArrayList<Figura> figuras = new ArrayList<>();
public static void Aleatorio(){
String[] colores = {"rojo", "amarillo", "verde", "azul", "blanco", "negro"};
for (int i = 0; i < 10; i++) {
switch ((int) Math.random()*3){
case 0:
Cuadrado cua = new Cuadrado(i, colores[(int) (Math.random()*6)],colores[(int) (Math.random()*6)],new Punto(Math.random()*10,Math.random()*10), (int) (Math.random()*10));
figuras.add(cua);
break;
case 1:
Rectangulo rec = new Rectangulo(i, colores[(int) (Math.random()*6)],colores[(int) (Math.random()*6)],new Punto(Math.random()*10,Math.random()*10), (int) (Math.random()*10),(int) (Math.random()*10));
figuras.add(rec);
break;
case 2:
Triangulo tria = new Triangulo(i, colores[(int) (Math.random()*6)],colores[(int) (Math.random()*6)],new Punto(Math.random()*10,Math.random()*10), (int) (Math.random()*10),(int) (Math.random()*10));
figuras.add(tria);
break;
case 3:
Circulo cir = new Circulo(i, colores[(int) (Math.random()*6)],colores[(int) (Math.random()*6)],new Punto(Math.random()*10,Math.random()*10), (int) (Math.random()*10));
figuras.add(cir);
}
}
}
public static void dibujar() {
for (Figura f : figuras) {
f.dibujar();
}
}
public static void area() {
for (Figura f : figuras) {
f.area();
}
}
public static void perimetro() {
for (Figura f : figuras) {
f.perimetro();
}
}
public static void distancia(int id) {
Figura fig = buscarID(id);
for (Figura f : figuras) {
f.dibujar();
}
}
public static void listar() {
for (Figura f : figuras) {
System.out.println(f);
}
}
public static void escalar(int id, int porcentaje) {
Figura fig = buscarID(id);
fig.escalar(porcentaje);
}
public static void mover(int id, Punto p) {
Figura fig = buscarID(id);
fig.mover(p);
}
public static void desplazarh(int id, int x) {
Figura fig = buscarID(id);
fig.desplazarh(x);
}
public static void desplazarv(int id, int y) {
Figura fig = buscarID(id);
fig.desplazarv(y);
}
public static Figura buscarID(int id) {
for (Figura i : figuras) {
if (i.getId() == id) {
return i;
}
}
return null;
}
public static void Orden() {
System.out.println("Porque criterio quieres ordenar?");
System.out.println();
System.out.println("1. Area");
System.out.println("2. Perimetro");
System.out.println("3. Posicion");
int respuestaOrdenar = Leer.leerEntero("Elige la opcion: ");
ClearConsole();
switch (respuestaOrdenar) {
case 1:
System.out.println("1. Ascendente");
System.out.println("2. Descendente");
int repu = Leer.leerEntero("Elige una opcion: ");
ClearConsole();
switch (repu) {
case 1:
Collections.sort(figuras, Figura::compareTo);
break;
case 2:
Collections.sort(figuras, Figura::compareTo);
Collections.reverse(figuras);
break;
default:
System.out.println("Opcion incorrecta");
Lienzo.area();
}
break;
case 2:
System.out.println("1. Ascendente");
System.out.println("2. Descendente");
int respu = Leer.leerEntero("Elige una opcion: ");
ClearConsole();
switch (respu) {
case 1:
Collections.sort(figuras,Figura::compareToPerimetro);
break;
case 2:
Collections.sort(figuras, Figura::compareToPerimetro);
Collections.reverse(figuras);
break;
default:
System.out.println("Opcion incorrecta");
Lienzo.perimetro();
}
break;
case 3:
System.out.println("1. Ascendente");
System.out.println("2. Descendente");
int rep = Leer.leerEntero("Elige una opcion: ");
ClearConsole();
switch (rep){
case 1:
Collections.sort(figuras, Figura::compareToDistancia);
break;
case 2:
Collections.sort(figuras, Figura::compareToDistancia);
Collections.reverse(figuras);
break;
default:
System.out.println("Opcion incorrecta");
}
break;
default:
System.out.println("Opcion incorrecta");
}
}
public static void ClearConsole() {
try {
String operatingSystem; //Check the current operating system
operatingSystem = System.getProperty("os.name");
if (operatingSystem.contains("Windows")) {
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "cls");
Process startProcess = pb.inheritIO().start();
startProcess.waitFor();
} else {
ProcessBuilder pb = new ProcessBuilder("clear");
Process startProcess = pb.inheritIO().start();
startProcess.waitFor();
}
} catch (Exception e) {
System.out.println(e);
}
}
}
| true |
d30aabac45d92eece26d7bd3a742196ff89b4ee2 | Java | p-hingorae/OtterEJ | /src/main/java/net/otterbase/oframework/common/interceptor/RequestInterceptor.java | UTF-8 | 1,202 | 1.773438 | 2 | [] | no_license | package net.otterbase.oframework.common.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import net.otterbase.oframework.common.UAgentInfo;
import net.otterbase.oframework.common.wrapper.ServletContextHolder;
import net.otterbase.oframework.vo.ParamData;
public class RequestInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
ServletContextHolder.instance().sync(request, response);
ParamData.sync(request);
// request.setAttribute("http_url", pm.get("webapp.site_web_url"));
// request.setAttribute("https_url", pm.get("webapp.site_ssl_url"));
UAgentInfo uaInfo = new UAgentInfo(request.getHeader("user-agent"), null);
request.setAttribute("_xs", uaInfo.isMobilePhone);
request.setAttribute("_sm", uaInfo.isMobilePhone || uaInfo.isTierTablet);
request.setAttribute("_cpx", request.getContextPath());
request.setCharacterEncoding("UTF-8");
return super.preHandle(request, response, handler);
}
}
| true |
8ea9fed8399ef80f7bef614a36c746ee6b5bf983 | Java | fracz/refactor-extractor | /results-java/JetBrains--kotlin/81c623a15681cccccf22fe0f82b0e0ca0ae9923a/after/CallableMethod.java | UTF-8 | 851 | 2.515625 | 3 | [] | no_license | package org.jetbrains.jet.codegen;
import org.objectweb.asm.commons.InstructionAdapter;
import org.objectweb.asm.commons.Method;
/**
* @author yole
*/
public class CallableMethod {
private final String owner;
private final Method descriptor;
private final int invokeOpcode;
public CallableMethod(String owner, Method descriptor, int invokeOpcode) {
this.owner = owner;
this.descriptor = descriptor;
this.invokeOpcode = invokeOpcode;
}
public String getOwner() {
return owner;
}
public Method getDescriptor() {
return descriptor;
}
public int getInvokeOpcode() {
return invokeOpcode;
}
void invoke(InstructionAdapter v) {
v.visitMethodInsn(getInvokeOpcode(), getOwner(), getDescriptor().getName(), getDescriptor().getDescriptor());
}
} | true |
08e13a61504e6ab796e2dd636420bb2898f2e02f | Java | mohanadElmaghrby1/mobiquity_packer | /src/main/java/com/mobiquity/model/Package.java | UTF-8 | 519 | 2.578125 | 3 | [] | no_license | package com.mobiquity.model;
import java.util.List;
/**
* @author Mohannad Elmagharby
* on 6/15/2021
*/
public class Package {
private final double totalWeight;
private final List<Item> availableItems;
public Package(double totalWeight, List<Item> availableItems) {
this.totalWeight = totalWeight;
this.availableItems = availableItems;
}
public double getTotalWeight() {
return totalWeight;
}
public List<Item> getAvailableItems() {
return availableItems;
}
}
| true |
289d6ca96800e3999c79bc17b007cb681f7e75ce | Java | garysweaver/nerot | /src/main/java/nerot/spring/IntervalScheduler.java | UTF-8 | 2,254 | 2.734375 | 3 | [
"MIT"
] | permissive | package nerot.spring;
import nerot.Nerot;
import nerot.store.Storer;
import nerot.task.Task;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
/**
* This bean lets you schedule Nerot by just defining a bean (e.g. in the root context of your application). The
* properties that must be set on the bean are the same as the ones on the corresponding schedule method in Nerot:
* <p>
* nerot.schedule(jobId, task, cronSchedule);
* </p>
* The following are properties that must be set on this bean:
* <ul>
* <li>jobId</li>
* <li>task</li>
* <li>intervalInMillis</li>
* </ul>
* It also has a "nerot" property, but that is @Autowired.
* <p/>
* (See the corresponding schedule method in Nerot for more details on the types and functions of that method.)
*/
public class IntervalScheduler implements InitializingBean, Storer {
@Autowired
private Nerot nerot;
private String jobId;
private Task task;
private long intervalInMillis;
public void afterPropertiesSet() throws Exception {
nerot.schedule(jobId, task, intervalInMillis);
}
protected void finalize() throws Throwable {
try {
nerot.unschedule(jobId);
}
finally {
super.finalize();
}
}
public Nerot getNerot() {
return nerot;
}
public void setNerot(Nerot nerot) {
this.nerot = nerot;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
public long getIntervalInMillis() {
return intervalInMillis;
}
public void setIntervalInMillis(long intervalInMillis) {
this.intervalInMillis = intervalInMillis;
}
/**
* Gets the store key from task, if it implements Storer. Otherwise returns null.
*
* @return store key
*/
public String getStoreKey() {
String storeKey = null;
if (task instanceof Storer) {
storeKey = ((Storer) task).getStoreKey();
}
return storeKey;
}
}
| true |
4c673a417071df3cf4227a578569acc19a2c6a05 | Java | Z1298174226/Algorithm | /src/mst/MST.java | UTF-8 | 107 | 1.953125 | 2 | [] | no_license | package mst;
public interface MST {
public Iterable<Edge> edges();
public double weight();
}
| true |
75b30eb07c61a6bdc21b730ee500f562dd9a3bf8 | Java | bullhorn/starter-kit-spring-maven | /src/main/java/com/client/core/dlmtasks/service/AbstractDateLastModifiedTasksService.java | UTF-8 | 3,426 | 2.0625 | 2 | [
"MIT"
] | permissive | package com.client.core.dlmtasks.service;
import com.bullhornsdk.data.model.entity.core.type.BullhornEntity;
import com.client.core.base.util.Utility;
import com.client.core.dlmtasks.model.helper.DateLastModifiedEventTaskHelper;
import com.client.core.dlmtasks.model.helper.impl.StandardDateLastModifiedEventTaskHelper;
import com.client.core.dlmtasks.workflow.node.DateLastModifiedEventTask;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.extern.log4j.Log4j2;
import org.joda.time.DateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
@Log4j2
public abstract class AbstractDateLastModifiedTasksService<T extends BullhornEntity> implements DateLastModifiedTasksService<T> {
private static final Set<String> ID = Sets.newHashSet("id");
private final List<DateLastModifiedEventTaskHelper<T>> helpers;
private final Class<T> type;
public AbstractDateLastModifiedTasksService(Optional<List<DateLastModifiedEventTask<T>>> eventTasks, Class<T> type) {
this.helpers = eventTasks.orElseGet(Lists::newArrayList).parallelStream().map(eventTask -> {
return new StandardDateLastModifiedEventTaskHelper<T>(eventTask);
}).collect(Collectors.toList());
this.type = type;
}
@Override
public Class<T> getType() {
return type;
}
@Override
public void process(DateTime start) {
Map<Boolean, List<DateLastModifiedEventTaskHelper<T>>> helpersByShouldProcess = helpers.parallelStream().collect(Collectors.groupingBy(helper -> {
return helper.shouldProcess(start);
}));
List<DateLastModifiedEventTaskHelper<T>> toProcess = helpersByShouldProcess.getOrDefault(Boolean.TRUE, Lists.newArrayList());
if (toProcess.isEmpty()) {
log.debug("Not executing any " + type.getSimpleName() + " DLM Event Tasks as none should process");
} else {
log.info("Processing " + toProcess.size() + " " + type.getSimpleName() + " DLM tasks ");
process(start, toProcess);
}
}
private void process(DateTime start, List<DateLastModifiedEventTaskHelper<T>> toProcess) {
Map<String, List<DateLastModifiedEventTaskHelper<T>>> helpersByClause = toProcess.parallelStream().collect(Collectors.groupingBy(helper -> {
return this.getClause(helper, start);
}));
helpersByClause.forEach((clause, helpers) -> {
Set<String> fields = getAllFields(helpers);
process(clause, fields, entity -> {
helpers.parallelStream().forEach(helper -> {
helper.process(entity);
});
});
helpers.parallelStream().forEach(helper -> {
helper.updateLastRun(start);
});
});
}
protected abstract String getClause(DateLastModifiedEventTaskHelper<T> eventTask, DateTime start);
protected abstract void process(String where, Set<String> fields, Consumer<T> process);
private Set<String> getAllFields(List<DateLastModifiedEventTaskHelper<T>> helpers) {
return Sets.union(ID, Utility.mergeNestedFields(helpers.parallelStream().flatMap(helper -> {
return helper.getFields().stream();
}).collect(Collectors.toSet())));
}
}
| true |
fff84eb2f58bee06c7e1c3956836d1739b6e17cb | Java | Tiyanak/ROVKP | /Java8WordCount/src/hr/fer/tel/rovkp/topic9/example1/WordCountUglyMain.java | UTF-8 | 1,919 | 3.375 | 3 | [] | no_license | package hr.fer.tel.rovkp.topic9.example1;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.AbstractMap.SimpleEntry;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Stream;
import java.util.stream.Collectors;
/**
*
* @author Krešimir Pripužić <kresimir.pripuzic@fer.hr>
*/
public class WordCountUglyMain {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: WordCountUglyMain <input file> <output file>");
System.exit(-1);
}
//read lines into the stream
try (Stream<String> lines = Files.lines(Paths.get(args[0]))) {
//get a stream of words
Stream<String> words = lines.flatMap(line -> Arrays.stream(line.trim().split("\\s")));
//filter non-letters from the stream of words
Stream<String> alphaWords = words.map(word -> word.replaceAll("[^a-zA-Z]", "").toLowerCase().trim());
Stream<String> filteredWords = alphaWords.filter(word -> word.length() > 0);
//create a stream of word-count entries
Stream<SimpleEntry<String, Long>> entries = filteredWords.map(word -> new SimpleEntry<>(word, 1L));
//aggragate entries by words and sum their counts
Map<String, Long> result = entries.collect(Collectors.groupingBy(SimpleEntry::getKey, Collectors.counting()));
//write aggregated entries to a file
FileWriter fw = new FileWriter(args[1]);
result.forEach((k, v) -> writeToFile(fw, k + "," + v + "\n"));
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeToFile(FileWriter fw, String line) {
try {
fw.write(line);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
| true |
a3cc9eba4cc2cd6bfb06247b8c268a408e155fbf | Java | mcherif/bitmovinexp | /src/main/java/com/bitmovin/api/sdk/model/H264Partition.java | UTF-8 | 1,434 | 2.234375 | 2 | [
"MIT"
] | permissive | package com.bitmovin.api.sdk.model;
import java.util.Objects;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
public enum H264Partition {
/**
* Consider no macroblocks
*/
NONE("NONE"),
/**
* Consider P-macroblocks with size 8x8, 16X8, 8X16
*/
P8X8("P8X8"),
/**
* Consider P-macroblocks with size 4x4, 8X4, 4x8
*/
P4X4("P4X4"),
/**
* Consider B-macroblocks with size 8x8, 16X8, 8X16
*/
B8X8("B8X8"),
/**
* Consider I-macroblocks with size 8x8
*/
I8X8("I8X8"),
/**
* Consider I-macroblocks with size 4x4
*/
I4X4("I4X4"),
/**
* Consider all possible sizes of macroblocks
*/
ALL("ALL");
private String value;
H264Partition(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static H264Partition fromValue(String text) {
for (H264Partition b : H264Partition.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
}
| true |
ca3c8460857b2f0d4db06d8c787423953c0f3ac0 | Java | schnell18/java-honing | /src/main/java/org/home/hone/io/TempFile.java | UTF-8 | 458 | 2.90625 | 3 | [] | no_license | package org.home.hone.io;
import java.io.File;
public class TempFile {
public static void main(String[] args) {
File dir = new File(System.getProperty("java.io.tmpdir"), "poifiles");
System.out.println("target dir: " + dir.getPath());
boolean r = dir.mkdir();
System.out.println("first call of mkdir() returns: " + r);
r = dir.mkdir();
System.out.println("second call of mkdir() returns: " + r);
}
}
| true |
e000007d66274b845ee888d7c15d13324f7db474 | Java | ongjingwen/240845_A2 | /src/test/java/writeExcel/WriteExcelTest.java | UTF-8 | 2,060 | 2.703125 | 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 writeExcel;
import java.io.File;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author user
*/
public class WriteExcelTest {
public WriteExcelTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of WriteExcel method, of class WriteExcel.
*/
@Test
public void testWriteExcel() {
System.out.println("WriteExcel");
String filename1= "TestFIle\\Assignment2_TestFiles\\MyThread1.java";
String filename2= "TestFIle\\Assignment2_TestFiles\\MyThread2.java";
String workingDirectory = System.getProperty("user.dir");
//****************//
String absoluteFilePath = "";
String absoluteFilePath2 = "";
//absoluteFilePath = workingDirectory + System.getProperty("file.separator") + filename;
absoluteFilePath = workingDirectory + File.separator + filename1;
absoluteFilePath2 = workingDirectory + File.separator + filename2;
String[] result1 = new String[]{"A171","STIW3054","A", "Assignment1", "898989", "24", "4", "6", "14", "1",
"1","1","2", "2", "1","1", "23"};
String[] result2 = new String[]{"A171","STIW3054","A", "Assignment1", "898989", "24", "4", "6", "14", "1",
"1","1","2", "2", "1","1", "23"};
WriteExcel instance = new WriteExcel();
instance.WriteExcel(result1, result2);
// TODO review the generated test code and remove the default call to fail.
}
}
| true |
1f5b51c33975c34b6dcca83b4dc62fadc07a5059 | Java | xeppaka/LentaReader | /lentaru/lentareader/src/main/java/com/xeppaka/lentareader/ui/fragments/ListFragmentBase.java | UTF-8 | 11,153 | 1.984375 | 2 | [] | no_license | package com.xeppaka.lentareader.ui.fragments;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.Toast;
import com.xeppaka.lentareader.async.AsyncListener;
import com.xeppaka.lentareader.data.NewsObject;
import com.xeppaka.lentareader.data.Rubrics;
import com.xeppaka.lentareader.data.dao.Dao;
import com.xeppaka.lentareader.data.dao.async.AsyncNODao;
import com.xeppaka.lentareader.data.dao.daoobjects.DaoObserver;
import com.xeppaka.lentareader.ui.adapters.listnews.NewsObjectAdapter;
import com.xeppaka.lentareader.utils.PreferencesConstants;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Created by kacpa01 on 3/19/14.
*/
public abstract class ListFragmentBase<T extends NewsObject> extends ListFragment implements AbsListView.OnScrollListener {
private Rubrics currentRubric = Rubrics.LATEST;
private NewsObjectAdapter<T> newsAdapter;
private AsyncNODao<T> dao;
private boolean scrolled;
private String autoRefreshToast;
// expanded items for each rubric
protected Set<Long>[] expandedItemIds = new Set[Rubrics.values().length];
protected ScrollerPosition[] scrollPositions = new ScrollerPosition[Rubrics.values().length];
protected long[] latestNewsTime = new long[Rubrics.values().length];
private ItemSelectionListener itemSelectionListener;
private boolean active;
public interface ItemSelectionListener {
void onItemSelected(int position, long id);
}
private static class ScrollerPosition {
private int item;
private int top;
}
private Dao.Observer<T> daoObserver = new DaoObserver<T>(new Handler()) {
@Override
public void onDataChanged(boolean selfChange, T dataObject) {
refresh();
}
@Override
public void onDataChanged(boolean selfChange) {
refresh();
}
};
public ListFragmentBase() {
for (Rubrics rubric : Rubrics.values()) {
expandedItemIds[rubric.ordinal()] = new HashSet<Long>();
scrollPositions[rubric.ordinal()] = new ScrollerPosition();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
active = savedInstanceState.getBoolean("active", false);
currentRubric = Rubrics.valueOf(savedInstanceState.getString("rubric", Rubrics.LATEST.name()));
}
final Context context = getActivity();
autoRefreshToast = createAutoRefreshToast(context);
dao = createDao(context);
setListAdapter(newsAdapter = createAdapter(context));
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("active", isActive());
outState.putString("rubric", getCurrentRubric().name());
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setOnScrollListener(this);
}
@Override
public void onPause() {
super.onPause();
dao.unregisterContentObserver(daoObserver);
saveScrollPosition();
}
@Override
public void onResume() {
super.onResume();
dao.registerContentObserver(daoObserver);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
newsAdapter.setDownloadImages(preferences.getBoolean(PreferencesConstants.PREF_KEY_DOWNLOAD_IMAGE_THUMBNAILS, PreferencesConstants.DOWNLOAD_IMAGE_THUMBNAILS_DEFAULT));
newsAdapter.setTextSize(preferences.getInt(PreferencesConstants.PREF_KEY_NEWS_LIST_TEXT_SIZE, PreferencesConstants.NEWS_LIST_TEXT_SIZE_DEFAULT));
scrolled = false;
refresh();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final Activity activity = getActivity();
if (activity instanceof ItemSelectionListener) {
setItemSelectionListener((ItemSelectionListener)activity);
}
}
public Rubrics getCurrentRubric() {
return currentRubric;
}
public void setCurrentRubric(Rubrics currentRubric) {
saveScrollPosition();
this.currentRubric = currentRubric;
refresh();
}
public Set<Long> getExpandedItemIds() {
return expandedItemIds[currentRubric.ordinal()];
}
public void saveScrollPosition() {
final int item = getListView().getFirstVisiblePosition();
final View childView = getListView().getChildAt(0);
final int top = childView == null ? 0 : childView.getTop();
scrollPositions[currentRubric.ordinal()].item = item;
scrollPositions[currentRubric.ordinal()].top = top;
}
public void restoreScrollPosition() {
if (scrollPositions[currentRubric.ordinal()].item < getListAdapter().getCount()) {
getListView().setSelectionFromTop(scrollPositions[currentRubric.ordinal()].item, scrollPositions[currentRubric.ordinal()].top);
} else {
clearScrollPosition();
}
}
public void clearScrollPosition() {
scrollPositions[currentRubric.ordinal()].item = scrollPositions[currentRubric.ordinal()].top = 0;
}
public Long getLatestPubDate() {
return latestNewsTime[currentRubric.ordinal()];
}
public void setLatestPubDate(long date) {
latestNewsTime[currentRubric.ordinal()] = date;
}
public void setItemSelectionListener(ItemSelectionListener itemSelectionListener) {
this.itemSelectionListener = itemSelectionListener;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public NewsObjectAdapter<T> getDataObjectsAdapter() {
return newsAdapter;
}
public void refresh() {
scrolled = false;
dao.readAllIdsAsync(getCurrentRubric(), new AsyncListener<List<Long>>() {
@Override
public void onSuccess(List<Long> result) {
if (!isResumed()) {
return;
}
final List<T> news = newsAdapter.getNewsObjects();
final Iterator<T> iter = news.iterator();
while (iter.hasNext()) {
final T next = iter.next();
final int resultIndex = result.indexOf(next.getId());
if (resultIndex < 0) {
iter.remove();
} else {
result.remove(resultIndex);
}
}
if (result.isEmpty()) {
// result is empty means we don't have new news
if (news.isEmpty()) {
setLatestPubDate(0);
} else {
setLatestPubDate(news.get(0).getPubDate().getTime());
}
dao.readReadFlagAsync(getCurrentRubric(), new AsyncListener<List<Boolean>>() {
@Override
public void onSuccess(List<Boolean> result) {
int min = Math.min(result.size(), news.size());
for (int i = 0; i < min; ++i) {
news.get(i).setRead(result.get(i));
}
showData(news, countAndClearUpdatedInBackground(news));
}
@Override
public void onFailure(Exception e) {}
});
} else {
dao.readBriefAsync(getCurrentRubric(), new AsyncListener<List<T>>() {
@Override
public void onSuccess(List<T> result) {
if (isResumed()) {
showData(result, countAndClearUpdatedInBackground(result));
}
if (result.isEmpty()) {
setLatestPubDate(0);
} else {
setLatestPubDate(result.get(0).getPubDate().getTime());
}
}
@Override
public void onFailure(Exception e) {}
});
}
}
@Override
public void onFailure(Exception e) {}
});
}
private int countAndClearUpdatedInBackground(List<T> news) {
int result = 0;
for (T n : news) {
if (n.isUpdatedInBackground()) {
++result;
n.setUpdatedInBackground(false);
}
}
clearUpdatedInBackgroundFlag();
return result;
}
private void clearUpdatedInBackgroundFlag() {
dao.clearUpdatedInBackgroundFlagAsync(new AsyncListener<Integer>() {
@Override
public void onSuccess(Integer value) {}
@Override
public void onFailure(Exception e) {}
});
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (itemSelectionListener != null) {
itemSelectionListener.onItemSelected(position, id);
}
final T news = newsAdapter.getItem(position);
if (!news.isRead()) {
news.setRead(true);
}
}
private void showData(List<T> data, int updatedInBackground) {
if (updatedInBackground <= 0 && !data.isEmpty() && getLatestPubDate() != data.get(0).getPubDate().getTime()) {
clearScrollPosition();
}
newsAdapter.setNewsObjects(data, getExpandedItemIds());
newsAdapter.notifyDataSetChanged();
if (!scrolled) {
restoreScrollPosition();
}
if (updatedInBackground > 0) {
Toast.makeText(getActivity(), String.format(autoRefreshToast, updatedInBackground), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (!scrolled) {
scrolled = true;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {}
protected abstract AsyncNODao<T> createDao(Context context);
protected abstract NewsObjectAdapter<T> createAdapter(Context context);
protected abstract String createAutoRefreshToast(Context context);
}
| true |
233c324211c6967132a3d5b4be1bb2318db1f967 | Java | hhharsh/TreeCP | /src/finalTree/BfsLike.java | UTF-8 | 1,135 | 3.140625 | 3 | [] | no_license | package finalTree;
import java.util.*;
class Node66{
int data;
Node66 left;
Node66 right;
Node66(int d){
data=d;
}
}
public class BfsLike {
static Node66 root;
public static void Bfs(Node66 root) {
Queue<Node66> qq=new LinkedList<>();
qq.add(root);
while(!qq.isEmpty())
{
Node66 t=qq.poll();
System.out.print(t.data+" ");
if(t.left!=null) {
qq.add(t.left);
}
if(t.right!=null) {
qq.add(t.right);
}
}
}
public static void inOrder(Node66 root) {
if(root==null)
return;
inOrder(root.left);
System.out.print(root.data+" ");
inOrder(root.right);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
root=new Node66(1);
root.left=new Node66(2);
root.left.left=new Node66(4);
root.left.right=new Node66(5);
root.left.right.right=new Node66(9);
root.left.right.right.left=new Node66(10);
root.right=new Node66(3);
root.right.right=new Node66(7);
root.right.left=new Node66(6);
root.right.right.right=new Node66(8);
inOrder(root);
System.out.println();
Bfs(root);
}
}
| true |
eef40e471ea747d811ce508585048e049af65f30 | Java | potomy/client | /src/main/java/net/minecraft/entity/projectile/EntityC4.java | UTF-8 | 3,888 | 2.328125 | 2 | [
"MIT"
] | permissive | package net.minecraft.entity.projectile;
import net.minecraft.block.material.Material;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
/**
* Created by David on 17/12/2016.
*/
public class EntityC4 extends EntityThrowable
{
public int fuse = 100;
public EntityC4(World world) {
super(world);
}
public EntityC4(World world, EntityLivingBase thrower)
{
super(world, thrower);
}
public EntityC4(World world, double x, double y, double z)
{
super(world, x, y, z);
}
@Override
public void onUpdate() {
super.onUpdate();
if (this.isInWater()) {
if (!this.worldObj.isClient) {
float vel = 0.7F;
double x = (double)(rand.nextFloat() * vel) + (double)(1.0F - vel) * 0.5D;
double y = (double)(rand.nextFloat() * vel) + (double)(1.0F - vel) * 0.5D;
double z = (double)(rand.nextFloat() * vel) + (double)(1.0F - vel) * 0.5D;
EntityItem var13 = new EntityItem(worldObj, posX + x, posY + y, posZ + z, new ItemStack(Items.c4));
var13.delayBeforeCanPickup = 10;
worldObj.spawnEntityInWorld(var13);
}
this.setDead();
return;
}
if (this.fuse-- <= 0)
{
this.setDead();
if (!this.worldObj.isClient)
{
this.explode();
}
}
}
private void explode() {
float power = 3.0F;
this.worldObj.createExplosion(this, this.posX, this.posY, this.posZ, power, true);
}
@Override
protected void onImpact(MovingObjectPosition movingObj) {
if (movingObj.typeOfHit == MovingObjectPosition.MovingObjectType.ENTITY) {
this.motionX *= -0.10000000149011612D;
this.motionY *= -0.10000000149011612D;
this.motionZ *= -0.10000000149011612D;
} else {
this.xTile = movingObj.blockX;
this.yTile = movingObj.blockY;
this.zTile = movingObj.blockZ;
this.inTile = this.worldObj.getBlock(this.xTile, this.yTile, this.zTile);
this.motionX = (double)((float)(movingObj.hitVec.xCoord - this.posX));
this.motionY = (double)((float)(movingObj.hitVec.yCoord - this.posY));
this.motionZ = (double)((float)(movingObj.hitVec.zCoord - this.posZ));
//double var20 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ);
//this.posX -= this.motionX / var20 * 0.05000000074505806D;
//this.posY -= this.motionY / var20 * 0.05000000074505806D;
//this.posZ -= this.motionZ / var20 * 0.05000000074505806D;
//this.playSound("random.bowhit", 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F));
this.inGround = true;
this.throwableShake = 7;
if (this.inTile.getMaterial() != Material.air) {
this.inTile.onEntityCollidedWithBlock(this.worldObj, this.xTile, this.yTile, this.zTile, this);
}
}
}
@Override
protected float getScope() {
return 0.75F;
}
@Override
public void readEntityFromNBT(NBTTagCompound tagCompound) {
super.readEntityFromNBT(tagCompound);
fuse = tagCompound.getShort("Fuse");
}
@Override
public void writeEntityToNBT(NBTTagCompound tagCompound) {
super.writeEntityToNBT(tagCompound);
tagCompound.setShort("Fuse", (short)fuse);
}
@Override
public boolean interactFirst(EntityPlayer player) {
if (!this.worldObj.isClient) {
float vel = 0.7F;
double x = (double)(rand.nextFloat() * vel) + (double)(1.0F - vel) * 0.5D;
double y = (double)(rand.nextFloat() * vel) + (double)(1.0F - vel) * 0.5D;
double z = (double)(rand.nextFloat() * vel) + (double)(1.0F - vel) * 0.5D;
EntityItem var13 = new EntityItem(worldObj, posX + x, posY + y, posZ + z, new ItemStack(Items.c4));
var13.delayBeforeCanPickup = 10;
worldObj.spawnEntityInWorld(var13);
}
this.setDead();
return true;
}
}
| true |
4a2ca89c46e46ee7b263486a64818a381bc9da48 | Java | owel09/JavaPractice | /src/main/java/Fundamentals/Arrays/Finonacci.java | UTF-8 | 609 | 3.5 | 4 | [] | no_license | package Fundamentals.Arrays;
public class Finonacci {
public static void main(String[] args) {
int fibArr[] = new int[9];
int prevTerm = 0;
int currentTerm = 1;
int nextTerm = 2;
fibArr[0] = 0;
fibArr[1] = 1;
for (int x = nextTerm ; x <= fibArr.length-1 ; x++){
int sumTerm = fibArr [prevTerm] + fibArr [currentTerm];
fibArr [nextTerm] = sumTerm;
prevTerm++;
currentTerm++;
nextTerm++;
}
for(int t: fibArr){
System.out.println(t);
}
}
}
| true |
6b21a6b8ffb1a4908ce43b18f1bdf5e574b4b318 | Java | torr-penn/gow | /core/src/main/java/com/gtasoft/godofwind/game/entity/Player.java | UTF-8 | 14,458 | 2.09375 | 2 | [] | no_license | package com.gtasoft.godofwind.game.entity;
import box2dLight.RayHandler;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.*;
import com.badlogic.gdx.utils.Array;
import com.gtasoft.godofwind.GodOfWind;
import com.gtasoft.godofwind.game.Level;
import com.gtasoft.godofwind.game.WindManager;
import com.gtasoft.godofwind.game.utils.LevelUtil;
import com.gtasoft.godofwind.ressource.Constants;
public class Player {
int prevval = 0;
GodOfWind gow;
long lastbong = 0;
private TextureAtlas atlas;
private float hp, mp;
private float SPEED = 15f;
private TextureRegion current;
private TextureRegion[] boomAnim;
private Body body;
private float animState;
private Animation wLeft[], wUp[], wDown[], wIn[], aboom;
private boolean applyWind = false;
private int collisionNb = 0;
private WindManager windManager = null;
private boolean victory = false;
private int nbpush = 0;
private float boompX = 0f;
private float boompY = 0f;
private int playerDirection = 0;
private boolean windIsNew = false;
private boolean noWindIsNew = false;
private int masterDirectionColor = 0;
public Player(World world, GodOfWind gow, int level) {
this.gow = gow;
this.setBody(createTwoCircle(world, gow.getLu().getPosX(level), gow.getLu().getPosY(level), 16, 160, 200, 16));
SPEED = gow.getLu().getPlayerSpeed(level);
this.getBody().setLinearDamping(0.1f);
this.getBody().setAngularDamping(0.1f);
victory = false;
hp = 100;
mp = 100;
wDown = new Animation[5];
wIn = new Animation[5];
wUp = new Animation[5];
wLeft = new Animation[5];
initAnimations();
}
// 0 - nocol
// 1 - red
// 2 - green
//3 - pink
// 4 yellow
private void initAnimations() {
animState = 0;
atlas = new TextureAtlas(Gdx.files.internal("img/atlas/egg_runner.atlas"));
Array<TextureAtlas.AtlasRegion> ta;
ta = atlas.findRegions("wfront");
wDown[0] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wDown[0].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wleft");
wLeft[0] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wLeft[0].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wback");
wUp[0] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wUp[0].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wfrontred");
wDown[1] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wDown[1].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wleftred");
wLeft[1] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wLeft[1].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wbackred");
wUp[1] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wUp[1].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wfrontgreen");
wDown[2] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wDown[2].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wleftgreen");
wLeft[2] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wLeft[2].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wbackgreen");
wUp[2] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wUp[2].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wfrontp");
wDown[3] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wDown[3].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wleftp");
wLeft[3] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wLeft[3].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wbackp");
wUp[3] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wUp[3].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wfronty");
wDown[4] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wDown[4].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wlefty");
wLeft[4] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wLeft[4].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("wbacky");
wUp[4] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wUp[4].setPlayMode(Animation.PlayMode.LOOP);
ta = atlas.findRegions("sploutch");
wIn[0] = new Animation<TextureAtlas.AtlasRegion>(.15f, ta);
wIn[0].setPlayMode(Animation.PlayMode.LOOP_PINGPONG);
current = (TextureRegion) wDown[0].getKeyFrame(animState);
Texture boom1;
TextureRegion boomAnim1Aux[][];
boom1 = new Texture(Gdx.files.internal("img/board/boom/boom.png"));
boomAnim1Aux = TextureRegion.split(boom1, boom1.getWidth() / 4, boom1.getHeight() / 4); // #10
boomAnim = new TextureRegion[16];
int k = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
boomAnim[k++] = boomAnim1Aux[i][j];
}
}
aboom = new Animation<TextureRegion>(1f / 32f, boomAnim);
aboom.setPlayMode(Animation.PlayMode.NORMAL);
}
public void controller(float delta, int pushX, int pushY) {
float x = 0, y = 0;
if (victory) {
animState += delta;
current = (TextureRegion) wIn[0].getKeyFrame(animState, true);
return;
}
boolean refresh = false;
// if (applyWind && masterDirectionColor == 0) {
// masterDirectionColor = windManager.getMasterDirectionColor();
// refresh = true;
// }
if (applyWind && masterDirectionColor != windManager.getMasterDirectionColor()) {
masterDirectionColor = windManager.getMasterDirectionColor();
refresh = true;
}
if (!applyWind && masterDirectionColor != 0) {
masterDirectionColor = 0;
refresh = true;
}
if (Gdx.input.isKeyPressed(Input.Keys.LEFT) || pushX < 0) {
x -= 1;
playerDirection = 0;
current = (TextureRegion) wLeft[masterDirectionColor].getKeyFrame(animState, true);
if (current.isFlipX())
current.flip(true, false);
}
if (Gdx.input.isKeyPressed((Input.Keys.RIGHT)) || pushX > 0) {
x += 1;
playerDirection = 1;
current = (TextureRegion) wLeft[masterDirectionColor].getKeyFrame(animState, true);
if (!current.isFlipX())
current.flip(true, false);
}
if (Gdx.input.isKeyPressed((Input.Keys.UP)) || pushY > 0) {
y += 1;
playerDirection = 2;
current = (TextureRegion) wUp[masterDirectionColor].getKeyFrame(animState, true);
}
if (Gdx.input.isKeyPressed((Input.Keys.DOWN)) || pushY < 0) {
y -= 1;
playerDirection = 3;
current = (TextureRegion) wDown[masterDirectionColor].getKeyFrame(animState, true);
}
if (refresh) {
if (playerDirection == 0) {
current = (TextureRegion) wLeft[masterDirectionColor].getKeyFrame(animState, true);
}
if (playerDirection == 1) {
current = (TextureRegion) wLeft[masterDirectionColor].getKeyFrame(animState, true);
if (!current.isFlipX())
current.flip(true, false);
}
if (playerDirection == 2) {
current = (TextureRegion) wUp[masterDirectionColor].getKeyFrame(animState, true);
}
if (playerDirection == 3) {
current = (TextureRegion) wDown[masterDirectionColor].getKeyFrame(animState, true);
}
}
x = x + pushX;
if (x == 2) x = 1;
if (x == -2) x = -1;
if (x != 0) {
getBody().setLinearVelocity(getBody().getLinearVelocity().x + x * SPEED * delta, getBody().getLinearVelocity().y);
}
y = y + pushY;
if (y == 2) y = 1;
if (y == -2) y = -1;
if (y != 0) {
getBody().setLinearVelocity(getBody().getLinearVelocity().x, y * SPEED * delta + getBody().getLinearVelocity().y);
}
animState += delta;
}
public void moveit() {
if (isApplyWind()) {
if (prevval != (int) (Math.cos(windManager.getMainWindDirection()) * windManager.getWindPower())) {
prevval = (int) (Math.cos(windManager.getMainWindDirection()) * windManager.getWindPower());
}
applyForce(new Vector2((float) Math.cos(windManager.getMainWindDirection()) * windManager.getWindPower(), (float) Math.sin(windManager.getMainWindDirection()) * windManager.getWindPower()));
}
}
public void applyForce(Vector2 force) {
Vector2 vcenter = body.getWorldCenter();
body.applyForce(force, vcenter, true);
}
public void render(Batch batch) {
float w = current.getRegionWidth();
float h = current.getRegionHeight();
TextureRegion explosion = (TextureRegion) aboom.getKeyFrame(animState, true);
float aw = explosion.getRegionWidth();
float ah = explosion.getRegionHeight();
batch.begin();
batch.draw(current, getBody().getPosition().x * Constants.PPM - w, getBody().getPosition().y * Constants.PPM - h, 0, 0, w, h, 2, 2, 0);
if (System.currentTimeMillis() - lastbong < 500) {
batch.draw(explosion, boompX - aw / 4, boompY - ah / 4,
0, 0, aw / 2, ah / 2, 1, 1, 0);
}
batch.end();
}
public Vector2 getPosition() {
return getBody().getPosition();
}
public void dispose() {
atlas.dispose();
}
private Body createTwoCircle(World world, float xA, float yA, float radiusA, float xB, float yB, float radiusB) {
Body pBody;
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.DynamicBody;
def.position.set(xA / Constants.PPM, yA / Constants.PPM);
def.fixedRotation = true;
pBody = world.createBody(def);
CircleShape shape = new CircleShape();
shape.setRadius(radiusA / Constants.PPM);
shape.setPosition(new Vector2(0 / Constants.PPM, -14 / Constants.PPM));
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.density = 1.0f;
fd.restitution = 0.95f;
fd.friction = 0.1f;
fd.filter.categoryBits = Constants.BIT_PLAYER;
fd.filter.maskBits = Constants.BIT_WALL | Constants.BIT_COLORZONE | Constants.BIT_SENSOR;
fd.filter.groupIndex = 0;
CircleShape shape2 = new CircleShape();
shape2.setRadius(radiusB / Constants.PPM);
shape2.setPosition(new Vector2(0 / Constants.PPM, 14 / Constants.PPM));
FixtureDef fd2 = new FixtureDef();
fd2.shape = shape2;
fd2.density = 1.0f;
fd2.restitution = 0.9f;
fd2.friction = 0.1f;
fd2.filter.categoryBits = Constants.BIT_PLAYER;
fd2.filter.maskBits = Constants.BIT_WALL | Constants.BIT_COLORZONE | Constants.BIT_SENSOR;
fd2.filter.groupIndex = 0;
pBody.createFixture(fd).setUserData(this);
pBody.createFixture(fd2).setUserData(this);
shape.dispose();
shape2.dispose();
return pBody;
}
public Body getBody() {
return body;
}
public void setBody(Body body) {
this.body = body;
}
public int getCollisionNb() {
return collisionNb;
}
public void setCollisionNb(int collisionNb) {
this.collisionNb = collisionNb;
}
public void addCollision() {
if (isVictorious() && gow.getScore().getBounce() == 0) {
if (gow.isAudible()) {
long time = System.currentTimeMillis();
if (time - lastbong > 200) {
int i = (int) (Math.random() * 4);
if (i == 0) {
gow.snd_top1.play();
} else if (i == 1) {
gow.snd_top2.play();
} else if (i == 2) {
gow.snd_top3.play();
} else if (i == 3) {
gow.snd_top5.play();
}
lastbong = time;
}
}
return;
}
long time = System.currentTimeMillis();
if (time - lastbong > 20) {
if (!isVictorious()) {
this.collisionNb = getCollisionNb() + 1;
}
if (gow.isAudible()) {
if (time - lastbong > 200) {
int i = (int) (Math.random() * 6);
gow.snd_bong[i].play();
}
}
lastbong = time;
}
}
public void collisionOccured(float x, float y) {
//System.out.println(" collision occured : " + x + " y :" + y);
boompX = x * Constants.PPM;
boompY = y * Constants.PPM;
}
public WindManager getWindManager() {
return windManager;
}
public void setWindManager(WindManager windManager) {
this.windManager = windManager;
}
public void setVictory(boolean b) {
victory = b;
}
public boolean isVictorious() {
return victory;
}
public void addNbpush() {
if (nbpush == 0)
setApplyWind(true);
nbpush = nbpush + 1;
}
public void substractNbpush() {
if (nbpush == 0) {
setApplyWind(false);
return;
}
if (nbpush == 1) {
setApplyWind(false);
}
nbpush = nbpush - 1;
}
public boolean isApplyWind() {
return applyWind;
}
public void setApplyWind(boolean applyWind) {
this.applyWind = applyWind;
}
}
| true |
aa8025a50972914ea1cb5b049a9aaee14d8ee89c | Java | piece-the-world/inspect | /Inspect/talkingdata/src/main/java/com/tendcloud/tenddata/by.java | UTF-8 | 1,340 | 1.625 | 2 | [] | no_license | /*
* Decompiled with CFR 0_115.
*
* Could not load the following classes:
* android.content.ComponentName
* android.content.Context
* android.content.Intent
*/
package com.tendcloud.tenddata;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import com.apptalkingdata.push.service.PushService;
import com.tendcloud.tenddata.az;
import com.tendcloud.tenddata.bh;
import com.tendcloud.tenddata.bk;
public class by {
private static String a = by.class.getName();
public static void a(Context context, String string) {
try {
bk.putCodePreferences(context);
bk.putGatewayPreferences(context);
Intent intent = new Intent(context, (Class)PushService.class);
if (!az.a(string)) {
intent.putExtra("service-cmd", string);
}
context.startService(intent);
}
catch (Throwable var2_3) {
bh.b(a, "start service err" + var2_3.toString());
}
}
public static void stop(Context context) {
try {
Intent intent = new Intent(context, (Class)PushService.class);
context.stopService(intent);
}
catch (Throwable var1_2) {
bh.b(a, "start service err" + var1_2.toString());
}
}
}
| true |
8c23c7913c023ec0f0d9ecfb8b78700f6a8698f0 | Java | saakai-dev/Judge-Girl | /Domain/Problem/src/main/java/tw/waterball/judgegirl/problem/domain/usecases/RestoreProblemUseCase.java | UTF-8 | 616 | 2.21875 | 2 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | package tw.waterball.judgegirl.problem.domain.usecases;
import tw.waterball.judgegirl.commons.exceptions.NotFoundException;
import tw.waterball.judgegirl.problem.domain.repositories.ProblemRepository;
import javax.inject.Named;
/**
* @author - wally55077@gmail.com
*/
@Named
public class RestoreProblemUseCase extends BaseProblemUseCase {
public RestoreProblemUseCase(ProblemRepository problemRepository) {
super(problemRepository);
}
public void execute(int problemId) throws NotFoundException {
var problem = findProblem(problemId);
problemRepository.restoreProblem(problem);
}
}
| true |
ab86d56367a3edb67f779c2c27b0c987336cd2e8 | Java | canfengyiyang/spring_boot_test | /spring_boot_web_test/src/main/java/com/suyang/web/threadPool/CachedThreadPoolTest.java | UTF-8 | 462 | 2.671875 | 3 | [] | no_license | package com.suyang.web.threadPool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CachedThreadPoolTest {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 1; i< 5 ; i++) {
pool.submit(myThread);
Thread.sleep(1000);
}
}
}
| true |
6ca90ca34b49f3eff35f409d86dda528567cb0e1 | Java | mariam2202/microcommerce | /src/main/java/com/ecommerce/microcommerce/DTO/ProductDTO.java | UTF-8 | 1,102 | 2.71875 | 3 | [] | no_license | package com.ecommerce.microcommerce.DTO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "Product Model")
public class ProductDTO implements Comparable<ProductDTO>{
@ApiModelProperty(value = "Product id")
private Integer id;
@ApiModelProperty(value = "Nom Product")
private String nom;
@ApiModelProperty(value = "Prix Product")
private int prix;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public int getPrix() {
return prix;
}
public void setPrix(int prix) {
this.prix = prix;
}
public ProductDTO() {
}
public ProductDTO(Integer id, String nom, int prix) {
super();
this.id = id;
this.nom = nom;
this.prix = prix;
}
@Override
public int compareTo(ProductDTO o) {
return nom.compareToIgnoreCase(o.nom);
}
}
| true |
be6eebc912e9a3053f54a9195b789cdaa22098ea | Java | FullStackOliveiraGilberto/projeto-java | /projetofinal/rec_004/src/model/LerInt.java | ISO-8859-1 | 2,697 | 2.96875 | 3 | [] | no_license | package model;
public class LerInt {
public double nota1;
public double nota2;
public double nota3;
public double nota4;
public double mediaAlu;
public double notarec1;
public double notarec2;
public double notarec3;
public double notarec4;
public double mediaAlurec;
public double getNota1() {
return nota1;
}
public void setNota1(double nota1) {
this.nota1 = nota1;
}
public double getNota2() {
return nota2;
}
public void setNota2(double nota2) {
this.nota2 = nota2;
}
public double getNota3() {
return nota3;
}
public void setNota3(double nota3) {
this.nota3 = nota3;
}
public double getNota4() {
return nota4;
}
public void setNota4(double nota4) {
this.nota4 = nota4;
}
public double getNotarec1() {
return notarec1;
}
public void setNotarec1(double notarec1) {
this.notarec1 = notarec1;
}
public double getNotarec2() {
return notarec2;
}
public void setNotarec2(double notarec2) {
this.notarec2 = notarec2;
}
public double getNotarec3() {
return notarec3;
}
public void setNotarec3(double notarec3) {
this.notarec3 = notarec3;
}
public double getNotarec4() {
return notarec4;
}
public void setNotarec4(double notarec4) {
this.notarec4 = notarec4;
}
public double getMediaAlu() {
double mediaAlu = (nota1 + nota2 + nota3 + nota4) / 4;
return mediaAlu;
}
public double getMediaAlurec() {
double mediaAlurec = (notarec1 + notarec2 + notarec3 + notarec4) / 4;
return mediaAlurec;
}
public void setMediaAlurec(double mediaAlurec) {
this.mediaAlurec = mediaAlurec;
}
public void setMediaAlu(double mediaAlu) {
this.mediaAlu = mediaAlu;
}
@Override
public String toString() {
double media = (nota1 + nota2 + nota3 + nota4) / 4;
String situacaoAluno;
if (media >= 7) {
situacaoAluno = "Aprovado";
} else {
situacaoAluno = "Em Recuperao";
}
return "Aluno " + situacaoAluno + "\r Media: " + media + " [nota1=" + nota1 + ", nota2=" + nota2 + ", nota3="
+ nota3 + ", nota4=" + nota4 + "]";
}
public String toStringRecup() {
double mediarec = (getNotarec1() + getNotarec2() + getNotarec3() + getNotarec4()) / 4;
// System.out.println(getMediaAlurec());
String situacaoAluno;
if (mediarec >= 7) {
situacaoAluno = "Recuperado/Aprovado!";
} else {
situacaoAluno = "Norecuperado/Reprovado!";
}
return "Aluno " + situacaoAluno + "\r Media: " + mediarec + " [nota1=" + notarec1 + ", nota2=" + notarec2 + ", nota3=" + notarec3 + ", nota4=" + notarec4 + "]";
}
}
| true |
d6422275e2d854d7a579b34681195c82c7e24ff6 | Java | moutainhigh/ibas.thirdpartyapp | /ibas.thirdpartyapp.webapi/src/main/java/org/colorcoding/ibas/thirdpartyapp/client/LightApp.java | UTF-8 | 546 | 1.9375 | 2 | [] | no_license | package org.colorcoding.ibas.thirdpartyapp.client;
import java.util.Map;
import org.colorcoding.ibas.bobas.common.IOperationResult;
import org.colorcoding.ibas.thirdpartyapp.bo.user.IUser;
public class LightApp extends WebApp {
@Override
protected IUser fetchUser(Map<String, Object> params) throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public <P> IOperationResult<P> execute(String instruct, Map<String, Object> params) throws NotImplementedException {
throw new NotImplementedException();
}
}
| true |
91e51f1340bf5dfe760df24026105afce4cbcbdd | Java | semnala/HumanResourceManagementSystem | /hrms/src/main/java/com/miris/hrms/service/com/impl/Com0101ServiceImpl.java | UTF-8 | 1,110 | 1.945313 | 2 | [] | no_license | package com.miris.hrms.service.com.impl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.miris.hrms.service.com.Com0101Service;
import com.miris.hrms.service.com.mapper.Com0101Mapper;
import com.miris.hrms.service.com.vo.ManagerVO;
@Service("com0101Service")
public class Com0101ServiceImpl implements Com0101Service {
public static Logger logger = LogManager.getLogger(Com0101ServiceImpl.class);
@Autowired
BCryptPasswordEncoder passwordEncoder;
@Autowired
Com0101Mapper mapper;
@Override
public boolean userLoginIn(ManagerVO manager) throws Exception {
logger.debug("userLoginIn");
boolean result;
String encPasswd = passwordEncoder.encode(manager.getAdm_pw());
manager.setAdm_pw(encPasswd);
ManagerVO resultVO = mapper.selectManagerInfo(manager);
if(resultVO != null) {
result = true;
} else {
result = false;
}
return result;
}
} | true |
573cd4fa7e6f08f44fec441fd1f3ac6d723f8abc | Java | linsir6/Android-Advance | /algorithm/nowcoder/JZ42.java | UTF-8 | 1,001 | 3.125 | 3 | [] | no_license | package nowcoder;
import java.util.ArrayList;
/**
* JZ42, https://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
*/
public class JZ42 {
public ArrayList<Integer> FindNumbersWithSum(int[] array, int sum) {
ArrayList<Integer> list = new ArrayList();
if (array == null) {
return list;
}
int l = 0;
int r = array.length - 1;
while (l < r) {
if (array[l] + array[r] == sum) {
list.add(array[l]);
list.add(array[r]);
System.out.println(array[l] + " " + array[r]);
return list;
} else if (array[l] + array[r] > sum) {
r--;
} else {
l++;
}
}
return list;
}
public static void main(String[] args) {
JZ42 jz42 = new JZ42();
jz42.FindNumbersWithSum(new int[]{1, 2, 4, 7, 11, 15}, 15);
}
}
| true |
dce7b506e185fa0d947084872b17c5236e67cfa9 | Java | ylaichenkov/infopulse-test-automation | /src/lesson4/Program.java | UTF-8 | 906 | 3.03125 | 3 | [] | no_license | package lesson4;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Program {
public static void main(String[] args) {
FileReader fr = null;
File f = new File("/wrong/path/name");
try {
fr = new FileReader(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
simpleWaiter(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println("STARTED");
int i = 10 / 0;
} catch (Exception e) {
System.out.println("EXCEPTION ---->" + e.toString());
} finally {
System.out.println("FINISHED");
}
}
public static void simpleWaiter(long timeout) throws InterruptedException {
Thread.sleep(timeout);
}
}
| true |
525ee6c7d78be551850d2261902f8fb0d96765de | Java | Asadullah-1998/Hapi-Rest-App | /src/main/java/com/rest/Main/Monitor/HighPressure/HighPressureController.java | UTF-8 | 2,165 | 2.15625 | 2 | [] | no_license | package com.rest.Main.Monitor.HighPressure;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import java.util.HashMap;
import java.util.Map;
@Controller
@SessionAttributes({"practitioner","monitorList","patients","monitorCheck","monitorPatientList","patientCheck","record"})
public class HighPressureController {
@GetMapping("/highPressure")
public String loadHighPressure(Model model, @ModelAttribute("record") HighPressureRecord record){
return "high-pressure";
}
@PostMapping("/build-graph")
public String buildGraph(Model model, @ModelAttribute("record") HighPressureRecord record){
record.setPressureValues(record.getPressureValuesString().split(",", 0));
record.setPressureDates(record.getPressureDatesString().split(",", 0));
Map<String, String> patientMap = new HashMap<String, String>();
Double[] systolicValues = new Double[record.getPressureValues().length - 1];
String[] systolicDates = new String[record.getPressureDates().length - 1];
int k = 0;
for (int j = record.getPressureValues().length -1; j >= 0; j--) {
if (!(record.getPressureValues()[j].isBlank() ||
record.getPressureDates()[j].isBlank())) {
systolicValues[k] = Double.parseDouble(record.getPressureValues()[j]);
systolicDates[k] = record.getPressureDates()[j];
k++;
}
}
patientMap.put("Name", record.getName());
model.addAttribute("PatientMap", patientMap);
model.addAttribute("SystolicValues", systolicValues);
model.addAttribute("SystolicDates", systolicDates);
return "line-graph";
}
}
| true |
e890eaf0ae561180c58790f3b93847e0f8214527 | Java | marialzr/Zoowsome | /Zoowsome/src/javasmmr/zoowsome/models/animals/Butterfly.java | UTF-8 | 1,108 | 2.703125 | 3 | [] | no_license | package javasmmr.zoowsome.models.animals;
import javasmmr.zoowsome.repositories.AnimalRepository;
import javasmmr.zoowsome.services.factories.constants.Constants;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamException;
public class Butterfly extends Insect {
public Butterfly(double maintenance, double danger){
super(maintenance, danger);
super.nrOfLegs=8;
super.name="";
super.canFly=true;
super.isDangerous=false;
}
public Butterfly(int nrOfLegs, String name, boolean canFly, boolean isDangerous, double maintenance, double danger){
super(maintenance, danger);
super.nrOfLegs=nrOfLegs;
super.name=name;
super.canFly=canFly;
super.isDangerous=isDangerous;
}
@Override
public void encodeToXml(XMLEventWriter eventWriter) throws XMLStreamException{
System.out.println("in encode in butterfly");
super.encodeToXml(eventWriter);
AnimalRepository.createNode(eventWriter, Constants.XML_TAGS.DISCRIMINANT, Constants.Animals.Insects.Butterfly);
}
}
| true |
af1de847ebf7e54f082b4947bc716050e5aa1f98 | Java | skony/SecurityProject | /SecurityProject/jif/jif-classes/jif/principals/Manager.java | UTF-8 | 12,954 | 1.632813 | 2 | [] | no_license | package jif.principals;
public class Manager extends jif.lang.ExternalPrincipal {
public Manager jif$principals$Manager$() {
this.jif$init();
{ this.jif$lang$ExternalPrincipal$("Manager"); }
return this;
}
private static Manager P;
public static jif.lang.Principal getInstance() {
if (Manager.P == null) {
Manager.P = new Manager().jif$principals$Manager$();
}
return Manager.P;
}
public static final String jlc$CompilerVersion$jif = "3.4.3";
public static final long jlc$SourceLastModified$jif = 1450279343000L;
public static final String jlc$ClassType$jif =
("H4sIAAAAAAAAALVYe2wUxxkfH/bZZxzbmLcxtrENiXn4AiWgxFAeZ8AmR3y1" +
"DYVD4Vjvztlr7+0uu3P2AU1FIqWkjepKhGcDNJGwFFICbdqUKq+iqG0gIVHT" +
"Rk2aiiR/ValS0oLUVqhN229m9n1n0j/ak252d+b7vpnv9Ztv5tx1VGIaaO6Q" +
"nG4je3Vstm2W0wnBMLGU0JS9fdCVEm89fVU6vkP/KITCSVQmm1tVU0jjOIoI" +
"WTKoGTLZS1B1fEgYEaJZIivRuGyS9jiaLGqqSQxBVom5B30dFcVRtQw9gkpk" +
"gWBpo6FlCJoX12GiAUUjUZwjUV0whEyULSWaiCmCaYKkMOu1hZTphjYiS9gg" +
"qCEOC7eoFaEfK9GENRanX+05AzXa4i39uHJMMtfuyKLo4WO7qp+fhKqSqEpW" +
"e4lAZDGmqQTWk0QVGZzpx4a5TpKwlERTVIylXmzIgiLvA0JNTaIaUx5QBZI1" +
"sNmDTU0ZoYQ1ZlaHJdI57c44quAmyYpEM2x1wmkZK5L9VZJWhAGToBmuWbh6" +
"G2k/2KIczImNtCBim6V4WFYlaosAh6Njy/1AAKylGQz+cqYqVgXoQDXcc4qg" +
"DkR7iSGrA0BaomUJNXDthELbqSMEcVgYwCmCZgXpEnwIqCLMEJSFoOlBMiYJ" +
"vFQb8JLHP9cfWDW2X+1UQ2zNEhYVuv4yYKoPMPXgNDawKmLOWLEwflSY8cpj" +
"IYSAeHqAmNNc/NqNtYvrL13mNHMK0HT3D2GRpMQz/ZXv1MVa753EQ1AzZep8" +
"n+Ys+BPWSHtOh8Sa4Uikg2324KWeX+448Cz+NITKu1BY1JRsBuJoiqhldFnB" +
"xiasYoOmSBeKYFWKsfEuVArvcVnFvLc7nTYx6ULFCusKa+wbTJQGEdREpfAu" +
"q2nNftcFMsjeczpCqBT+aBr8J8F/ifVsJKgvOqhlcFSXNWLg4eiATKK9WMzS" +
"LIfcorbI+6Y5CP8lpiFGdQggUdYFxYxuEVSIAKMNhvT/k9wc1ad6tKgITF0X" +
"THQFcqRTUwAMUuLh7PoNN86n3gw5gW9ZAjKNYp8rvs0Sj4qKmNhpNDu498D2" +
"w5DFgG4Vrb0Pbt79WBPYLKePFoPlKGmTD0Vjbqp3MdQTId5+s0bfPXbPnFUh" +
"VJIENDQ7cFrIKiQRW69lVUCNaU5XDwZAURmMFYTSUl1kPATNzANBDn7AZrhC" +
"KNsciPGWYKYVWmbVwU/+duHoQ5qbcwS15EFBPidN5aagHwxNxBKAoyt+YaPw" +
"QuqVh1pCqBjwAXQjoBmFm/rgHL6UbrfhkepSAuqlNSMjKHTItko5GTS0UbeH" +
"BUgle58CXppsB30J/FPWcxsdnarTdhoPKOr2gBYMflf36qfef/uPXwqhkIvU" +
"VZ6drxeTdg86UGFVDAemuFHUZ2AMdNeOJ544cv3gThZCQNFcaMIW2sYAFWD/" +
"AzM/ennP7z768My7ITfsCGyO2X5FFnOOkrQflVvKbbWe3R4lYbYF7noAXRTI" +
"Nliu2bJVzWiSnJaFfgXTOP9n1fylL/xprJrHgQI93KoGWvzFAtz+2evRgTd3" +
"/b2eiSkS6e7m2swl45A51ZW8zjCEvXQduYd/PffE68IpAF8APFPehxmGIWYD" +
"xJx2N9N/EWujgbFltGmEdA4OwnRz3KRlyQMFgsyrh5Q442ZTVN/Y8THzdznE" +
"aRqKIlmEcqcuL+dizihNPLpJD9jEc/OIu9xhmjIzg2uw5i9+sFG62di0k+XJ" +
"ZAmboiHrdmABpJebckZXwNxYYukNxQTRNoP5nMrIEFRTgZ2EQ0IfG9yQ0w26" +
"L48IBvMTs0pzjgaps4wELbhS4srHDxpa87dWhCxDVtJmXg7KPYmjVKMuNio2" +
"vNxHw5jJsKd1jelOnRJPTT/2cs33D63jm26DnyOPetXdsW+klv/wrZCVKDOD" +
"gNwpmIOQUO8r7yWPXFtYz6V6Es4af7Hj0SNHf3pxOcfsCnB/9Zq1CNlxUB/0" +
"QQ8WYOvgTkqJN09/gHvuufUZT31tVA2Wn84OAiWo9UYrV4NJodaJwapm5QWb" +
"JX7Ft5+6cP3DxFqWIR630voir8S14sbjENpu9O9Aznra+jTdWVJK3DXjV4vq" +
"Xt7xTa/xAwwe6rGzJ0v/vPjWU0xtJ7iaA8HlMNw2wGh7L18vQyCf272L9Hp/" +
"5vRr714e6fyMLzcYXYU41iyb9uons2bvZ/Gis7k3WbPSx/16IWd/FeoO19mN" +
"bfHXflba84bH2cyDYIJRRsj9SdsO1wFfAcHzC9lzvUaIlvFYdXXzB0Ptn7/z" +
"YzutOh2rtPoVDHB61QwvfGn22O8PdNsy4lzVHo+qfbxruZ5juL+dfa1i7Zpg" +
"AtDO9TqTtJML0n1CAp8JTrqbm1d3TOv/5M9ZToFU5yuQNtJzj1sUiPtW/+HQ" +
"v/ZAUTApiSoHBbNLhU2UHrPgNEcR1fkiaIonKRhU0dJA8ZY5wbNBYLJk9NzJ" +
"2tiXP2X55lYglLshl19LbhM8xdGyZzN/DTWFfxFCpVDDscoMjrTbBCVL9/Uk" +
"nNDMmNUZR3f4xv2nLX60aHcqrLpg9eOZNlj7uDUsvFNq+l4eKHemUt82wz8C" +
"/+9Zz+94y50ixF4UxtLE2vm0uYv5LESgzDRkSHlYedhkB+NAnVFjSR2zngc8" +
"0gkqSpi+3Y2BO5b42Wv8mXPn2yvOjrMsizDvgS+JtZOVUQ77myt2h1+xRmvK" +
"k4UU45HvMNQWYjjqZWCP0S9MEdrk2Gr2u/mW86dKflfCWcgcKqvBWsCT1vNY" +
"sAI9wBPJz1VnUR8vxOVLQIevvtBs3y3Ax8pe1vCAGOUDTbRZ4Ihjv7B1Vmyw" +
"nrO9laWb72xTnTvRsZ5dSZx55PBpqXt8Kcf2Gv9ReYOazTz328+vth3/+EqB" +
"U1uEaPoSBY9gJYAx/qusLezGw83dlU93tNS9tmfsf3f+ssK10FGrIaB9cDFn" +
"t5y7smmBeAgQz8GAvFscP1O7P/PL+ax9vvyvd/xFkxPdaZ17LlvPHwWDrXqC" +
"5KevrbTZE8h5+yT1vPUcD0ZA4Sr8xG3GnqTNEwRNHsDE1pUREmdqdmFRy5Oh" +
"eJX1bIUzoykPsCsCuiUwXHX2S+vq4T5+9TCEpeioZgwzQglOFezl9tw5d+Oc" +
"DuBNY4sSuZUHKnCo8EMPtT+7YKGmett2Rh70nPmvoGecLegZF2fG86FnfALo" +
"uYvKWmwt4C3reSUYDc8FIIRxtVrUbxTiKgw9iwrNdnUC6NkOR4pS6+KF1mez" +
"8i5t+UWjeP50VdnM01vfYyci5zIwAttFOqso3j3R8x7WDZyWmXYRvkPy6uUi" +
"QZX+yx+Cyt0Ptr6fcNIXCZoEpPT1Jd0Oh1onHDbkoChUBcUJixzyQ+HEkX/J" +
"v0NSzMryi++U+JdlSztevbzgdav4dYyCc6SNXYnbwOJwXDi9+YH9N1bwPbVE" +
"VIR9++gkZYBX/LLEuhYx0LwJpdmywp2t/6j8QWS+7/BX44EMn3Ye1G/IO+V4" +
"L+VT4jB66PGfH6x5GBaZRBHZ7DOyJqHX4xHR3h/85x56m+bcO7MFrLRq2isw" +
"3Z3BQ4FnMm/FXDR0ojte+u/ttj6rC+ZaEdPvPydixXUYGQAA");
public Manager() { super(); }
public void jif$invokeDefConstructor() { this.jif$principals$Manager$(); }
private void jif$init() { }
public static final String jlc$CompilerVersion$jl = "2.7.0";
public static final long jlc$SourceLastModified$jl = 1450279343000L;
public static final String jlc$ClassType$jl =
("H4sIAAAAAAAAALVZWewsWVmve+fOvbMxG/swDJeZy8hQzK2u6urNcateqruW" +
"rq7u2rqKwKX2ru7a9y4cRaOAEAcjA2Ii+AKJ4ggJhvhgSHhRIRATjXF5UHgw" +
"UYM88KC+qFjV//X+753BFzs5S5/zne9853e+7zvnfPXKD4B7kxi4Hgbu3naD" +
"9Ga6D83kJqvGiWmMXDVJ+Lrhlv5pEHr5tz7w6FfvAR5RgEccn0vV1NFHgZ+a" +
"ZaoAD3mmp5lxghmGaSjAY75pGpwZO6rrVDVh4CvA44lj+2qaxWayMpPAzRvC" +
"x5MsNOPDnCeNNPCQHvhJGmd6GsRJCjxKb9VchbLUcSHaSdIXaOCq5ZiukUTA" +
"LwCXaOBey1XtmvBN9MkqoANHCG/aa/IHnFrM2FJ182TIlZ3jGynwjosjTld8" +
"g6oJ6qHXPDPdBKdTXfHVugF4/EgkV/VtiEtjx7dr0nuDrJ4lBZ54VaY10X2h" +
"qu9U27yVAm+5SMceddVU9x9gaYakwBsvkh04lTHwxIU9O7dbP2B+6qUP+TP/" +
"8kFmw9TdRv5760FPXRi0Mi0zNn3dPBr40Hvoz6hv+vrHLgNATfzGC8RHNH/8" +
"8z/8ufc+9Y1vHtG87S40C21r6ukt/Qvaw3/55Oi5wT2NGPeFQeI0qnDbyg+7" +
"yh73vFCGtS6+6ZRj03nzpPMbqz+TP/wl8/uXgQcI4KoeuJlXa9VjeuCFjmvG" +
"U9M3YzU1DQK43/SN0aGfAK7VddrxzaPWhWUlZkoAV9xD09Xg8L+GyKpZNBBd" +
"qeuObwUn9VBNN4d6GQIAcK1OwBvqdE+dnj8ur6cAD20Cz4RCJ0hjcwfZTgpx" +
"pp7FTrpn46DB4o7/W8dq0vNJrENhrUC6E6puAs1Vv9aA+GbdFf4/8S2b9byu" +
"uHSphvrJi2bv1jYyC1zDjG/pL2fDyQ+/fOvbl08V/xiJ2tJqPjfP2N88Zg9c" +
"unRg+4bGOo52r8Z+V9t0bbYPPce9n/zgx56uMSvD4kqNXEN646ISn5k+UdfU" +
"WjNv6Y989F/+4yufeTE4U+cUuHGHld05srGSpy8uMQ5006i90Bn791xXv3br" +
"6y/euNxs+f2180nVWj1qS37q4hy3WcsLJ56ngeUyDTxoBbGnuk3Xibt4IN3E" +
"QXHWcsD+wUP94R/Vv0t1+p8mNYrVNDRl7V5Gx0p9/VSrw/Bo3xp0L6zo4OV+" +
"mgs/93d/8a/ty40kJw7xkXOekzPTF84ZYcPsoYO5PXa2WXxsmjXdP3yW/dSn" +
"f/DR9x12qqZ45m4T3mjyRk61li+If/Wb0d9/9x+/8NeXz3Y3Ba6GmeY6+kHy" +
"J2tGz55NVdunW+trLUlyQ/C9wHAsR9Vcs9GU/3rkXfDX/u2lR4+2261bjsCL" +
"gff+eAZn7W8dAh/+9gf+86kDm0t6cz6cwXFGduR0Xn/GGYtjdd/IUf7SX739" +
"t/9c/VztvmqXkTiVefACwGF5wGFV4GEvnz3k77nQ93yTva089L3x0H4ludMB" +
"481JdqaLCvTK7zwx+pnvH4Q+08WGxxPlnQYrqufMBPmS9++Xn776p5eBawrw" +
"6OEQVf1UVN2s2VWlPgaT0XEjDbzutv7bj7Qj//3Cqa09edEOzk170QrOHEVd" +
"b6ib+rXzil8D8foGpGfqdH+dfve4/GTT+2jY5I+Vl4BDpX0Y8tQhf2eT3TgA" +
"eTkFrtXuJ68to9ay5HAXKU+5H7bg8WOuLx2XHz7HPQUusQdrOjKpJocOOlpe" +
"qrX23vZN9Ga7+f/C3We/p6m+q8n6NbXl+Kp7pOIp8Oatq984sV6xvhDVCnaj" +
"dpYHFo/Xd5mDmjUg3zy6N9xFglpJHj4jo4P6cvGJf/qN73zyme/WSkEC9+bN" +
"htW6cI4XkzW3r4+88um3P/jy9z5xsMHaAJd/oH3qsw3XUZP9dH0zaaTjgizW" +
"TVpN0vnBaEzjIOCdmsnGjlf7ivz4amB+7OWP/+jmSy9fPnd/euaOK8z5MUd3" +
"qAM0Dxwtrp7lna81y2EE/s9fefFPfu/Fjx7dLx6//TYw8TPvD//mv79z87Pf" +
"+9ZdDqYrbnBXTNOHr8zQhMBOfrQom0ghlOXOmkGaopSV5tF6mcYTxln7KOZI" +
"doljptLHvFV7D49lcYyK27xK3bgHtrKszSKYAONEJO22ZkhtpvqYIacFjhMj" +
"zYgEKgKdaNqyCXHGr3aI6jir2mZcrhXQghhtGAQZeAMf9ltbSN0hHcQAtV4e" +
"+vlASfNOWsLilFDVRXfpT9Gt2RaT1EOkVuEP5/RUaJHcwDJG4sTrDyxR6OY7" +
"FqIIfsSJS8+DU1FobbcLIiAkngqmPK1w8BC2JrY8UUmFcPJVNt1zg62j0tMo" +
"4pblUAy8zrDdMnBdXKXLYmDvwp0tDcOgi7sjMljDyNTBBGErKMVWEFvFZrIX" +
"aE5SnZE3UmVqN19k8Ebhw81WdriBbUejyWLUMwNcnVjUYDphVqq/BlsdrFqr" +
"qNMeZDNyPk+tbE/RASotelEIWhsq4qJJKJmoiynjqRcteWnXWopTpQpLVO3w" +
"IVW4kxUvEnt37VWE7dA51iIZXiVUoewshwoBJ4w35oWWEshLWHHVGWkQnZ6O" +
"olGGeXs5nMyREi68nUJ16IGokNIGm/LB0MskbdOdIjsIoQi9IjwmHQ0dryui" +
"Ei67apBgmy6z3UMwhlF7d7qsQD2SI9FeB8vxWtfRyB7vVj2Hm8ZYa6gGnkAy" +
"63G6mdBaxM0numjLRY2TYq/DiV8Q0YieT0gODxbucO7IZI4vtT5Jz9iBbklj" +
"CVmDsLBEKmaykcUsR/cyFbBzdm0zY7WgPHoh0ZPCcjm5r4dbQuYwcxZhHsPo" +
"EBMxqZzHNNz2mNmcas349hiZrsL5soKUdQ7PRbXXaU+WMFYpZtj3QTkBh6zE" +
"zdLFps+pqODsbKSNoJRkrkEU7Y8qkCF4KoOHMkyukmFGBk60cQ3cH5aOmsjB" +
"wuOGJiXjEpVYk0zE4lwXfTyn9Z7Py2VXoPFRllAqWGg8uZxOjNUktLAsQnzG" +
"SnV8ntQHTBWOoiEPqsO4T/ZxyLHEhKTsfFHPo+PcmpFoGzUdjKeogTSvOJqw" +
"9CDWCLArd0Zs3w0dfGosbVswZLyUy2wicgRGzZlNzkO7QaHDqtFNKZvg8daa" +
"ny1xPVrxQoHNhYze9NiAYfpdv20XHVsaKNiWYuSwH+dJi9uiEeUxm5AZZ+ig" +
"P0aKzhi3p6gYay1WS3sDacjKNGWyeMC61NTjxy1xq0Vhe24secLogElLs9i1" +
"xvq4sBFJYsKMlz0djwnKWa6k7sAVhRGjCp31uFAwYeXNcZnnBBfesRjPVBgz" +
"HPs9TIk3I4pJdIedSjIli5KniYUAgUY2C5adSNMLDu5M8CHrGExHVe1ZUTLl" +
"kMKCfQrKKlsss0jcwA2+2wJbL7e1nuMeFNszuitosbXZmSFX74bLcPMtNeOJ" +
"dBd0pjzXEjRzNhRs1+z0R+swTGq/QEI4K9WHq+GrMW9sApZaxIg9lOeWa7W7" +
"kWVaUMaui2izI3JBVLpGXJq8Yfe7whQXx5jpZfhMUBBsbjDmguygqJ63bX6j" +
"jJYMrqtzQkISGcOlMYRVc8j0fbZX9br9+b5H8FYymu4XyLqD4/5isYuXlivm" +
"lKZJZnuFurIm4z0/wNYrnmBcJ0M0Uqwkh/NJFbfsNb9gaw9r7V0aKsOYjGf2" +
"khi0a5co5RWOpRWImPnK5o02pCGmw+24rtnzkKRw0Q7WgRWpX21Hk3y9NDLZ" +
"gFjLmnT7RIjhfYzFWXNTelNCksclWSLMgIEmUra1NdxNp97EwNBF4a+qNrVy" +
"98s5bif7eNNZoiii8CIDyX1+VhmVP1FXEUW43kSP9IwGDadyNgxLh+R4sJ3o" +
"0ILIBuXG2xKVjWRFxxmACT7tIobT2oFrUsE8LXBmseFhw5A0NX2nrAumlOVs" +
"x5RLfsUEbMefx8QEX/G2gkyWLcKaDvbLVoF0abRPDPM5n7TCamurYYIWtbfa" +
"cGgSz8ZlqPZ7hrQZlWMxJb213aNY2duK1DxjnADJmXJWdLZkQhnw1nQX/opk" +
"eR5C9KTdHnfbWw/pjv39gjXTtZFI4M7NoSJWRiI1Xoxtpgg9YrEUFv24t5fY" +
"NZ7KVVfsThJUtXqzbYtjZlY7LBd6ve/+EBooETxi3FIYQq3lsi/Ji9zmdxHJ" +
"tAaQPcuzzBIUvl0feBgi+X10UZ/ZwUCQYxFlyMBQyUINvc5S0sh1D087YFdn" +
"2+MSjyRi1W238sCJ+xyMJtp2woTZYDHAKj9WwS1vSCJJtcfrrYjm0TrtlbwK" +
"lVhRmN14WpGtHMrZrSS0ypTsOSrWn7lzpkCK6aZHw/18uR9ZSA+hB7MQ6uSr" +
"uAejZtfaz+lKl9eygMLOXhtk9cUb0XIFmjpJb9eWNJYrIbhLSAaEm8ECHniM" +
"Zs3WlqupfVSbIfp+LBPkapVsB5yRLOACtzB9Vo0GbpULKuHmuGys19WwxaZ+" +
"D6rkKqudOhKnbCCOZ8MuvCxya+ojyKLPGkyyR91KnAVgZGllnCmdbaN8lgo7" +
"PSW0sXS8GPARn5JzuuXDIyzsk3wcaR5stPlFDnXmA4UPcKGzz5ZMSlZbOBEc" +
"NpUgcLbModqf8VjocMFsqDH0RkCEWczazERfwdbOUYnAp1YboWWQWF+RO4XG" +
"DGWa3A2YikRSZ83Wht5xZdulk40LD2qVnPdLY7pXKgYa8xJulfgoFMfjRA/m" +
"25jXhiORHkDCzmfGc48RlFXbQssc8el1t6XO9CimQ3tgLhTG3faysZDkOBOB" +
"LmpSM9MT0j5SVP0RBA6UChyg+07LKXFUKFN6guReK5PzDj3h7Gq82nEzVzaN" +
"zW4IMpgv4ltuhVS+rfdb9i7iQgdsy8hw0dFQRMr73pr1kX2+2Mbz+rk4zm0O" +
"JFNlIQrLXs/bp8gGBsuVl1M7VBDQziyfM0tJ3m4jRRqxLW4wnxjxDpnGSAZ5" +
"Ur9rULWPHUm6rVNRPpSSEQ/njJxgxKAYsmQFi76w6uflQqSXhJnn6TBp79tY" +
"2Q9NOB9h04Uw5rWVghKbbd4bwqK3L/x4MXBVSeshJe/z+SpROganlJ0OOwxr" +
"Ze9TuoVM88HKlBdqxVdtpA/m6aYNgZNoKMDZRGUDbigPbFLGSijKEtqspkW/" +
"bbjCoJ0y3CD1rMRqW2CSUHALn8aEOhzoY9xPO/te4nlDE7OXVX+K5Xiis/Ci" +
"x0IsDarlIM/3uQGV+K5kDVWBe7Sbs7NCGsfraNShzDzWeGXS33TAfQ0BK+jj" +
"loKhXNwvp+2pH/HMpFgxs2Q8gUNhNfGMyPDw1b6z2JjkGtYIoQr2OzYZJaPM" +
"EYr1bI1wYB6hfAcc8KNJaDqBYhfV0nYXuFm5g7ToGOBCH2dDRkYTLlOEGeWP" +
"gv5kzqY82JPrQ99MU2S16bV81suDqanTpq3giDXtd3Hfwuig1h9K8ooUHbVj" +
"kxPksd7HCWJVpmIsaCXvUHYxcIqYMXxh1GV2ixUacl2QwmHPrPpOJwUFaWuy" +
"nZZo+PMWnFvyXnc6FVFgaYovoiRob9urftmTxspe8tbyqn4D7LuZ4CyVNbgv" +
"wdE+rZ1B3LV0hliPlGASsjxMGq3FBg782VjbBaONMNQF0imr/RKcTXZriMxb" +
"DFfN470DggJIGi5XpWauVbah5qgh70d6l2PWsq8VC7JYj+sDSZ4NGFgrWE2c" +
"iMRqAIL2TpGHa4imJ9lGLlt0QYZGrXQhkkLdbX8pcWAPGq5RdDL327IJTyFi" +
"AYooDYo8uh12u+zUmnXLznSoKqvhTOmNF3symq3RcrZqb6B+p+x0PVDTF705" +
"HtOrCHGSoq20h0sU9+cehK/Hq1awTU0wg9J0241HoKJODDZn94ZTrgV5usSw" +
"5jm4OH4MP3Z4qp/G++s3cNNxIHndUSzhqSZ7+jSscPhdPY76vuO4fOu5sMK5" +
"SA/QPHXf/moB+sMz9wu//PLnjcUX4cvH4SI6Be5Pg/B518xN90LQ6B0XOM0P" +
"HyXOIj+/P3/lW9Nn9d+8DNxzGrS549vG7YNeuD1U80Bsplns87cFbN56uvYH" +
"TyLf99bp1nEpng/YnD26L8B2gOOB4yHCcbm4CNvdQ2gffI0+rcne14RcHOvG" +
"WSz6xnEs+saZQPKpLE1QCPiJ4/V887j8o1dZxh1Bp7Owz4VY02PHnL56XH7x" +
"/7a67Wv0HT7YGCnwoG2mJ1t2EkR6vIm+H+I+7Omyb1/n4UPFs00Q9lhtLx0F" +
"ljd3BpZ/8nqUqYkTZUFqvvsoXnu9vh0Z1xtYHT8PdubYtM4F19/93PUPpRsn" +
"ufkquL/7uRdefO40XP1adnSbcE1vXD85Xh2S/DX6DlmYAm95NakPo2bHUaim" +
"oFLgSrPOC8jdd7KfF5D72R+H3FE08jx0TtpAdf197+euXwTkompdaqq98naI" +
"rt0Nol98TYh+5TX6PtJkL6bAfSfSNf+rMgWuHe9cEwZ/yx3fgY++Vupf/vwj" +
"973588LfHr6RnH5RvEoD91mZ656P+Z6rXw1j03IOs189igAfofDxFHj49i9I" +
"KfDA2Z+D+L92RPrrKXDPsWt+KTwxgCdODWBSpmbsq+6pIZT/C5c60L/RHgAA");
}
| true |
0acf3b2ee4f68567113cbc79a096aa75621f9f79 | Java | superStyle205/FFSE1801_1802_Java_core | /Lab/TuNguyen/Lap1/src/Lap2/PtBac2.java | UTF-8 | 914 | 2.921875 | 3 | [] | no_license | package Lap2;
import java.util.Scanner;
public class PtBac2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Nhap so a:");
int a = scan.nextInt();
System.out.println("Nhap so b:");
int b = scan.nextInt();
System.out.println("Nhap so c:");
int c = scan.nextInt();
if (a == 0) {
System.out.println("Phuong trinh co nghiem la:" + (-b / a));
}
else if (a != 0) {
double x1;
double x2;
double delta = Math.pow(b, 2)- 4 * a * c;
if (delta < 0) {
System.out.println("Phuong trinh vo nghiem");
}
else if (delta > 0) {
x1 = (-b + Math.sqrt(delta))/(2*a);
x2 = (-b - Math.sqrt(delta))/(2*a);
System.out.println("Phuong trinh co nghiem x1 la:" + x1);
System.out.println("Phuong trinh co nghiem x2 la:" + x2);
}
else {
System.out.println("Phuong trinh co nghiem kep la:" + (-b/(2*a)));
}
}
}
}
| true |
185af481d0b8672ce1070d8ee351a6cf732acc05 | Java | yossigruner/AndroidMVC | /src/com/mika/cheggmeout/utils/image/cache/IImageCache.java | UTF-8 | 592 | 2.515625 | 3 | [
"MIT"
] | permissive | package com.mika.cheggmeout.utils.image.cache;
import android.graphics.Bitmap;
public interface IImageCache {
/**
* Put.
*
* @param key
* the key
* @param value
* the value
*/
public abstract void put(String key, Bitmap value);
/**
* Contains key.
*
* @param key
* the key
* @return true, if successful
*/
public abstract boolean containsKey(String key);
/**
* Gets the.
*
* @param key
* the key
* @return the bitmap
*/
public abstract Bitmap get(String key);
} | true |
77d27911b1fcf57b12cfd75de30d12e5297a3487 | Java | heleilei32/gameHall | /service/src/main/com/service/SystemService.java | UTF-8 | 402 | 1.71875 | 2 | [] | no_license | package com.service;
import com.entity.Admin;
import com.model.DTParams;
import com.model.Result;
import java.util.List;
public interface SystemService {
/**
* 根据用户名查找系统用户
* @param userName
* @return
*/
Admin findAdmin(String userName);
/**
* 获取所有的系统用户
* @return
*/
Result getAllAdmin(DTParams dtParams);
}
| true |
b630e8411d2095c94d2aa51e78f932f2ded523e8 | Java | wsgan001/OnlineParticipation | /SImpleChallenges/codeforces/src/design.java | UTF-8 | 245 | 1.539063 | 2 | [] | no_license | import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: shiwangi
* Date: 15/12/13
* Time: 3:09 PM
* To change this template use File | Settings | File Templates.
*/
public class design {
private JButton button1;
}
| true |
d4e572ce9ea67693b9d451719b5955ae1147b26f | Java | P-Karthik/Milestone-3 | /microservices/stock-exchange-service/src/main/java/com/wellsfargo/stockexchangeservice/service/StockExchangeService.java | UTF-8 | 1,287 | 2.4375 | 2 | [] | no_license | package com.wellsfargo.stockexchangeservice.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wellsfargo.stockexchangeservice.models.StockExchange;
@Service
public class StockExchangeService {
@Autowired
private StockExchangeRepository stockExchangeRepository;
public List<StockExchange> getAllStockExchanges() {
List<StockExchange> se = new ArrayList<>();
stockExchangeRepository.findAll().forEach(se::add);
return se;
}
public void addStockExchange(StockExchange stockExchange) {
stockExchangeRepository.save(stockExchange);
}
public void updateStockExchange(StockExchange stockExchange) {
stockExchangeRepository.save(stockExchange);
}
public StockExchange getStockExchangeByName(String se_name) {
return stockExchangeRepository.findBySeName(se_name);
}
public void deleteStockExchangeById(int id) {
stockExchangeRepository.deleteById(id);
}
public void deleteStockExchangeByName(String se_name) {
stockExchangeRepository.deleteBySeName(se_name);
}
public StockExchange getStockExchangeById(int id) {
return stockExchangeRepository.findById(id).orElse(null);
}
}
| true |
340193d6d26d2547fcf3624755b7ebebecfd4572 | Java | cckmit/bigdata | /BdBiProcSrvShEduOmc/BdBiProcSrvShEduOmc/src/main/java/com/tfit/BdBiProcSrvShEduOmc/dto/optanl/SumDataKwInfo.java | UTF-8 | 374 | 1.648438 | 2 | [] | no_license | package com.tfit.BdBiProcSrvShEduOmc.dto.optanl;
import lombok.Data;
/**
* 厨房垃圾/废弃油脂
* @author fengyang_xie
* @date 2019/01/25
*
*/
@Data
public class SumDataKwInfo {
/**
* 学校回收桶数
*/
private Float schRecNum;
/**
* 团餐公司回收桶数
*/
private Float rmcRecNum;
/**
* 合计回收桶数
*/
private Float totalRec;
}
| true |
f947fb5cb8c9c747b5a2c0b9dd97488348d1e2b2 | Java | BAT6188/A11WatchLauncher | /app/src/main/java/fise/feng/com/beautifulwatchlauncher/view/LanTingTextView.java | UTF-8 | 891 | 1.835938 | 2 | [] | no_license | package fise.feng.com.beautifulwatchlauncher.view;
import android.content.Context;
import android.util.AttributeSet;
import fise.feng.com.beautifulwatchlauncher.KApplicationContext;
public class LanTingTextView extends ScrollerTextView {
private final static String TAG = LanTingTextView.class.getSimpleName();
//public static final int LANTIN_STYLE_MIDDLE = R.string.lantin_middle;
//public static final int LANTIN_STYLE_SMALL = R.string.lantin_small;
public LanTingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
//TypedArray a = context.obtainStyledAttributes(null, null);
//KctLog.d(TAG, "LanTinTextView_style=" + a.getString(R.styleable.LanTinTextView_style));
//a.recycle();
init(context);
}
private void init(Context context){
setTypeface(KApplicationContext.lanTingBoldBlackTypeface);
}
}
| true |
47b1557d2ead9e8e1b52ef4c4ab46aa8549a2058 | Java | joumenharzli/serverless-aws-java | /serverless/src/main/java/com/serverless/handlers/ListClientsHandler.java | UTF-8 | 467 | 1.828125 | 2 | [
"Apache-2.0"
] | permissive | package com.serverless.handlers;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.serverless.handlers.models.ApiGatewayResponse;
import java.util.Map;
public class ListClientsHandler implements RequestHandler<Map<String, Object>, ApiGatewayResponse> {
@Override
public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) {
return null;
}
}
| true |
14b8ce7d69a6af111ed5fa26efd9114b7d8ee93b | Java | qiuye1pian/todo-list | /todo/src/main/java/com/command/CommandBase.java | UTF-8 | 312 | 2.125 | 2 | [] | no_license | package com.command;
import com.todo.list.TodoList;
public abstract class CommandBase {
String action;
public CommandBase(String action) {
this.action = action;
}
public String getAction() {
return this.action;
}
public abstract String doAction(TodoList todoList);
}
| true |
0cfd5847cb8067d3cf33d2d11524bf822652e692 | Java | aworld1/FinalProjectCompSci | /Shapes/src/handlers/InventorySlot.java | UTF-8 | 631 | 2.84375 | 3 | [] | no_license | package handlers;
import superclasses.*;
public class InventorySlot {
private Shape shape;
private double cooldown;
public long lastUse;
public InventorySlot(Shape s, double c) {
shape = s;
cooldown = c;
lastUse = 0;
}
public Shape getShape() {
return shape;
}
public double getCooldown() {
return cooldown;
}
public void use(Game game) {
if (System.currentTimeMillis() - lastUse >= cooldown && shape.getOwner().getEnergy() >= shape.getCost()) {
game.spawnShape(shape.clone());
shape.getOwner().loseEnergy(shape.getCost());
lastUse = System.currentTimeMillis();
}
}
}
| true |
3670961d20a1ca5ecffb401be47df696f2977c67 | Java | mmchengzi/master | /master/auth-server/src/main/java/com/masterchengzi/authserver/security/RevokeTokenEndpoint.java | UTF-8 | 1,060 | 2.21875 | 2 | [] | no_license | package com.masterchengzi.authserver.security;
import com.masterchengzi.mastercommon.common.JsonResult;
import com.masterchengzi.mastercommon.common.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@FrameworkEndpoint
public class RevokeTokenEndpoint {
@Autowired
private ConsumerTokenServices consumerTokenServices;
@RequestMapping(value = "/oauth/token", method= RequestMethod.DELETE)
public @ResponseBody
JsonResult revokeToken(String access_token){
JsonResult msg = null;
if (consumerTokenServices.revokeToken(access_token)){
msg=new JsonResult(ResultCode.SUCCESS,"注销成功");
}else {
msg=new JsonResult(ResultCode.FAIL,"注销失败");
}
return msg;
}
}
| true |