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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b27557703a83bf0e964ea3e9c865122c1b91eaaf
|
Java
|
ITOPEducation/apiscol-previews
|
/src/fr/ac_versailles/crdp/apiscol/previews/workers/RemotePDFConversionWorker.java
|
UTF-8
| 1,271
| 2.34375
| 2
|
[] |
no_license
|
package fr.ac_versailles.crdp.apiscol.previews.workers;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.List;
import java.util.UUID;
import fr.ac_versailles.crdp.apiscol.previews.Conversion;
import fr.ac_versailles.crdp.apiscol.utils.FileUtils;
public class RemotePDFConversionWorker extends PDFConversionWorker {
private String url;
public RemotePDFConversionWorker(String url, File outputDir,
List<String> outputMimeTypeList, int pageLimit,
Conversion conversion) {
super(null, outputDir, outputMimeTypeList, pageLimit, conversion);
this.url = url;
}
@Override
public void run() {
if (downLoadPdf() == true) {
convertPdfToImage();
}
}
protected boolean downLoadPdf() {
conversion.setState(Conversion.States.INITIATED,
"Pdf file will be downloaded");
incomingFile = new File(String.format("%s/%s.pdf",
System.getProperty("java.io.tmpdir"), UUID.randomUUID()));
conversion.setState(
Conversion.States.INITIATED,
String.format("Trying to dump pdf file to %s",
incomingFile.getAbsolutePath()));
return FileUtils.downloadFileFromURL(url, incomingFile);
}
}
| true
|
131280ef1901e6853a89b112149ce6c1ee305283
|
Java
|
OmarAouini/Spring-boot-crud
|
/springboot-crud/src/main/java/com/aouin/springbootcrud/model/Article.java
|
UTF-8
| 716
| 1.945313
| 2
|
[
"MIT"
] |
permissive
|
package com.aouin.springbootcrud.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(collection = "articles")
public class Article {
@Id
private Integer id;
private String name;
private Float price;
private String description;
private List<String> categories;
private ManufactureDetails manufactureDetails;
private ShippingDetails shippingDetails;
private Integer stockQuantity;
private boolean isAvaliable;
}
| true
|
d481b21d784d80ab923f3c6b2bea137424e1e06d
|
Java
|
ravikiranvelpula/spring-orm-hibernate-demo
|
/ReadCSV.java
|
UTF-8
| 2,197
| 3.421875
| 3
|
[] |
no_license
|
package test;
import java.io.*;
import java.util.*;
public class ReadCSV {
public static void main(String[] args) throws FileNotFoundException {
List<String> arr = new ArrayList<String>();
//HDFC-Input-Case1.csv
//ICICI-Input-Case2.csv
//Axis-Input-Case3.csv
//IDFC-Input-Case4.csv
Scanner sc = new Scanner(new File("C:\\Users\\Anshul\\Documents\\manuscripts\\Assignment\\Dot Net Developer\\HDFC-Input-Case1.csv"));
sc.useDelimiter(","); //sets the delimiter pattern
while (sc.hasNext()) //returns a boolean value
{
String temp = sc.next();
arr.add(temp); //find and returns the next complete token from this scanner
}
sc.close(); //closes the scanner
arr.remove(0);
int flag = 0;
if(arr.contains("Debit"))
flag = 1;
if(flag == 0)
{
for(int i = 1; i< arr.size();)
{
List<String> out = new ArrayList<String>();
//Date TrancDicr Amt
String tranc = "";
String cardName = arr.get(4);
if(arr.get(i).contains("Domestic Transactions"))
{
tranc = "Domestic Transactions";
}
if(arr.get(i).contains("International Transactions"))
{
tranc = "International Transactions";
}
if(arr.get(i).contains("-"))
{
out.add(arr.get(i));
out.add(arr.get(i+1));
if(arr.get(i+2).contains("cr"))
{
out.add("0");
out.add((arr.get(i+2).split(" "))[0]);
}
else
{
out.add(arr.get(i+2));
out.add("0");
}
if(tranc.equals("Domestic Transactions"))
{
out.add("INR");
}
else if(tranc.equals("International Transactions"))
{
out.add(arr.get(i+1).substring(arr.get(i+1).length()-3, arr.get(i+1).length()));
}
out.add(cardName);
out.add(tranc);
if(tranc.equals("Domestic Transactions"))
{
String[] t = arr.get(i+1).split(" ");
out.add(t[t.length-2]);
}
else if(tranc.equals("International Transactions"))
{
out.add(arr.get(i+1).substring(arr.get(i+1).length()-3, arr.get(i+1).length()));
}
System.out.println(out);
}
i += 3;
}
}
}
}
| true
|
d479734915cca3cfabca94ac4cd51e3225752500
|
Java
|
shangy/QLearning
|
/src/main/java/examples/trading/domain/TradingAction.java
|
UTF-8
| 1,384
| 3.203125
| 3
|
[] |
no_license
|
package examples.trading.domain;
import domain.Action;
import domain.State;
public class TradingAction extends Action {
public enum Type {
BUY,
SELL,
NOTHING
}
private final int volume;
private final Type type;
public TradingAction(int index, int volume, Type type) {
super(index);
this.volume = volume;
this.type = type;
}
public int getVolume() {
return volume;
}
public Type getType() {
return type;
}
@Override
public State apply(State state) {
TradingState tradingState = (TradingState) state;
if(type == Type.NOTHING) {
return tradingState.copy();
}
double money = tradingState.getMoney();
int commodity = tradingState.getCommodity();
double lastPrice = tradingState.getLastPrice();
TradingState newState = (TradingState) tradingState.copy();
if(type == Type.BUY) {
tradingState.setMoney(money - lastPrice * volume);
tradingState.setCommodity(commodity + volume);
} else if(type == Type.SELL) {
tradingState.setMoney(money + lastPrice * volume);
tradingState.setCommodity(commodity - volume);
} else {
throw new IllegalStateException("Don't mess with domain.");
}
return newState;
}
}
| true
|
79e208c4bfb6663e045d8e122e42e92f8afe6a60
|
Java
|
zzznavarrete/JavaIntegracion
|
/src/java/Entidades/TipoHabitaciones.java
|
UTF-8
| 4,221
| 2.0625
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Entidades;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author nicomscr
*/
@Entity
@Table(name = "TIPO_HABITACIONES")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "TipoHabitaciones.findAll", query = "SELECT t FROM TipoHabitaciones t")
, @NamedQuery(name = "TipoHabitaciones.findById", query = "SELECT t FROM TipoHabitaciones t WHERE t.id = :id")
, @NamedQuery(name = "TipoHabitaciones.findByDescripcion", query = "SELECT t FROM TipoHabitaciones t WHERE t.descripcion = :descripcion")
, @NamedQuery(name = "TipoHabitaciones.findByPrecio", query = "SELECT t FROM TipoHabitaciones t WHERE t.precio = :precio")
, @NamedQuery(name = "TipoHabitaciones.findByCantMinHoras", query = "SELECT t FROM TipoHabitaciones t WHERE t.cantMinHoras = :cantMinHoras")})
public class TipoHabitaciones implements Serializable {
private static final long serialVersionUID = 1L;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Id
@Basic(optional = false)
@Column(name = "ID")
private BigDecimal id;
@Basic(optional = false)
@Column(name = "DESCRIPCION")
private String descripcion;
@Basic(optional = false)
@Column(name = "PRECIO")
private BigInteger precio;
@Basic(optional = false)
@Column(name = "CANT_MIN_HORAS")
private BigInteger cantMinHoras;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idtipo")
private Collection<Habitaciones> habitacionesCollection;
public TipoHabitaciones() {
}
public TipoHabitaciones(BigDecimal id) {
this.id = id;
}
public TipoHabitaciones(BigDecimal id, String descripcion, BigInteger precio, BigInteger cantMinHoras) {
this.id = id;
this.descripcion = descripcion;
this.precio = precio;
this.cantMinHoras = cantMinHoras;
}
public BigDecimal getId() {
return id;
}
public void setId(BigDecimal id) {
this.id = id;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public BigInteger getPrecio() {
return precio;
}
public void setPrecio(BigInteger precio) {
this.precio = precio;
}
public BigInteger getCantMinHoras() {
return cantMinHoras;
}
public void setCantMinHoras(BigInteger cantMinHoras) {
this.cantMinHoras = cantMinHoras;
}
@XmlTransient
public Collection<Habitaciones> getHabitacionesCollection() {
return habitacionesCollection;
}
public void setHabitacionesCollection(Collection<Habitaciones> habitacionesCollection) {
this.habitacionesCollection = habitacionesCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof TipoHabitaciones)) {
return false;
}
TipoHabitaciones other = (TipoHabitaciones) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Entidades.TipoHabitaciones[ id=" + id + " ]";
}
}
| true
|
3fccece4110efca665b4f4a44f9c087c7a31a60c
|
Java
|
OverengineeredCodingDuo/ASMUtils
|
/src/main/java/ocd/asmutil/injectors/LocalIndexedVarCapture.java
|
UTF-8
| 2,405
| 1.984375
| 2
|
[
"MIT"
] |
permissive
|
/*
* MIT License
*
* Copyright (c) 2017-2018 OverengineeredCodingDuo
*
* 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 ocd.asmutil.injectors;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.objectweb.asm.tree.analysis.AnalyzerException;
import org.objectweb.asm.tree.analysis.Frame;
import org.objectweb.asm.tree.analysis.Interpreter;
import ocd.asmutil.InsnInjector;
import ocd.asmutil.frame.TrackingValue;
public class LocalIndexedVarCapture implements InsnInjector
{
private final Type type;
private final int index;
public LocalIndexedVarCapture(final Type type, final int index)
{
this.type = type;
this.index = index;
}
public LocalIndexedVarCapture(final String className, final int index)
{
this(Type.getObjectType(className), index);
}
@Override
public void inject(
final String className,
final MethodNode methodNode,
final AbstractInsnNode insn,
final Frame<TrackingValue> frame,
final Interpreter<TrackingValue> interpreter
) throws AnalyzerException
{
final AbstractInsnNode varInsn = new VarInsnNode(this.type.getOpcode(Opcodes.ILOAD), this.index);
methodNode.instructions.insertBefore(insn, varInsn);
frame.execute(varInsn, interpreter);
}
}
| true
|
4e3fabae5824f8aaa0d702040c2bfea78f4bda77
|
Java
|
zhouwenshuo/lemonJava20
|
/src/com/lemon/class0706/inherit/God.java
|
UTF-8
| 1,263
| 2.765625
| 3
|
[] |
no_license
|
package com.lemon.class0706.inherit;
/**
* @time: 2020/7/7 8:59
* @author: Mr.Right
* @contact: 348533713@qq.com
* @file: God
* @desc: ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████ ┃+
* ┃ ┃ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃
* ┃ ┃ + + + +
* ┃ ┃ Codes are far away from bugs with the animal protecting
* ┃ ┃ + 神兽保佑,代码无bug
* ┃ ┃
* ┃ ┃ +
* ┃ ┗━━━┓ + +
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/
public class God {
public int weight;
public God() {
super();
System.out.println("God 无参构造");
}
}
| true
|
8265e82a27fbe170ff384a18265906efbb84176b
|
Java
|
gochanghai/CCIMS
|
/ccims-demo/src/main/java/com/lch/ccims/demo/Lottery.java
|
UTF-8
| 1,042
| 2.75
| 3
|
[] |
no_license
|
package com.lch.ccims.demo;
import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Set;
/**
* 抽奖实例demo
*/
public class Lottery {
// 参与抽奖手机号码
static String[] phone = {"13144800360","13144800361","13144800362","13144800363","13144800364","13144800365"
,"13144800366","13144800367","13144800368","13144800369","13144800376","13144800386","13144800396"
,"13144800466","13144800566","13144800666","13144800766","13144800866","13144800966","13144800066"};
// 中奖人数
static int num = 2;
/**
* 开始抽奖方法
* @return
*/
public static Set<String> start(){
Set<String> set = new HashSet<>();
for (; ; ){
if (set.size() == num){
break;
}
int random = new SecureRandom().nextInt(phone.length);
set.add(phone[random]);
}
return set;
}
public static void main(String[] args) {
System.out.println(start());
}
}
| true
|
7e534c5d95952ee9e1f3c52882051a4bda582e35
|
Java
|
skafetzo/BackendCourse
|
/src/gr/cosmote/firstexercise/Customer.java
|
UTF-8
| 1,318
| 2.859375
| 3
|
[] |
no_license
|
package gr.cosmote.firstexercise;
public class Customer {
public static void main(String args[]) {
Accountant george = new Accountant("George", new Calculator());
Accountant nick = new Accountant("Nick", new Calculator());
george.calculate("sum", 52, 45);
george.calculate("subtraction", 15, 5);
george.calculate("product", 5, 2);
george.calculate("division", 10, 3);
george.calculate("showDivision", 10, 3);
george.calculate("exponent", 2, 4);
george.calculate("productOfPrimes", 95);
george.calculate("Sum", 5, 6);
george.calculate("product", 5, 106);
george.showAmountOfCredit();
george.calculate("showDivision", 10, 3);
george.showAmountOfCredit();
nick.calculate("sum", 14, 45);
nick.calculate("subtraction", 20, 5);
nick.calculate("product", 63, 2);
nick.calculate("division", 42, 5);
nick.calculate("showDivision", 42, 5);
nick.calculate("exponent", 5, 4);
nick.calculate("productOfPrimes", 63);
nick.calculate("Not valid", 5, 6);
nick.calculate("productOfPrimes", 0);
nick.calculate("showDivision", 124, -1);
nick.showAmountOfCredit();
Accountant.getTotalNumberOfOperations();
}
}
| true
|
496f152e6061887fcd6519e9474ef38aaf01b2d4
|
Java
|
OdysseyProtocol/OCPay
|
/OCPay_app_android/app/src/main/java/com/ocpay/wallet/widget/dialog/LoadingDialog.java
|
UTF-8
| 1,530
| 2.296875
| 2
|
[] |
no_license
|
package com.ocpay.wallet.widget.dialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import com.ocpay.wallet.R;
/**
* Created by Avazu Holding on 2017/12/11.
*/
public class LoadingDialog extends Dialog {
// private ImageView progressImg;
private TextView tvTxt;
//帧动画
// private AnimationDrawable animation;
public LoadingDialog(Context context) {
super(context, R.style.CustomDialog);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_layout);
//点击imageview外侧区域,动画不会消失
setCanceledOnTouchOutside(false);
// progressImg = (ImageView) findViewById(R.id.imgLoading);
tvTxt=(TextView)findViewById(R.id.tvTxt);
// //加载动画资源
// animation = (AnimationDrawable) progressImg.getDrawable();
}
public void setCance(boolean isCance){
setCancelable(isCance);
}
public void setText(String txt){
tvTxt.setText(txt);
}
/**
* 在AlertDialog的 onStart() 生命周期里面执行开始动画
*/
@Override
protected void onStart() {
super.onStart();
// animation.start();
}
/**
* 在AlertDialog的onStop()生命周期里面执行停止动画
*/
@Override
protected void onStop() {
super.onStop();
// animation.stop();
}
}
| true
|
747471786d648ea2a943cdc092d33c6fdc190591
|
Java
|
Kowah/GameOfLife
|
/src/gui/RandomDialog.java
|
UTF-8
| 4,186
| 2.859375
| 3
|
[] |
no_license
|
package gui;
import command.GameRequestCommand;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
/**
* Created by Kovvah on 31/12/2017.
*/
public class RandomDialog extends JDialog{
GameRequestCommand requestCommand;
private JFormattedTextField width, height, delay, numbersToGenerate;
public RandomDialog(JFrame parent, String title, boolean modal){
super(parent, title, modal);
this.setSize(550, 270);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
this.initComponent();
}
public GameRequestCommand showRandomDialog(){
this.setVisible(true);
return this.requestCommand;
}
private void initComponent(){
NumberFormat integerFieldFormatter;
integerFieldFormatter = NumberFormat.getIntegerInstance();
integerFieldFormatter.setMaximumFractionDigits(0);
integerFieldFormatter.setGroupingUsed(false);
//Width
JPanel panWidth = new JPanel();
panWidth.setBackground(Color.white);
panWidth.setPreferredSize(new Dimension(220, 60));
width = new JFormattedTextField(integerFieldFormatter);
width.setText("200");
width.setPreferredSize(new Dimension(100, 25));
width.setColumns(10);
panWidth.setBorder(BorderFactory.createTitledBorder("Width"));
panWidth.add(width);
//Height
JPanel panHeight = new JPanel();
panHeight.setBackground(Color.white);
panHeight.setPreferredSize(new Dimension(220, 60));
height = new JFormattedTextField(integerFieldFormatter);
height.setText("200");
height.setColumns(10);
height.setPreferredSize(new Dimension(100, 25));
panHeight.setBorder(BorderFactory.createTitledBorder("Height"));
panHeight.add(height);
//Delay
JPanel panDelay = new JPanel();
panDelay.setBackground(Color.white);
panDelay.setPreferredSize(new Dimension(220, 60));
delay = new JFormattedTextField(integerFieldFormatter);
delay.setText("500");
delay.setColumns(10);
delay.setPreferredSize(new Dimension(100, 25));
panDelay.setBorder(BorderFactory.createTitledBorder("Delay (ms)"));
panDelay.add(delay);
//Numbers to generate
JPanel panNmbrsToGenerate = new JPanel();
panNmbrsToGenerate.setBackground(Color.white);
panNmbrsToGenerate.setPreferredSize(new Dimension(220, 60));
numbersToGenerate = new JFormattedTextField(integerFieldFormatter);
numbersToGenerate.setText("15000");
numbersToGenerate.setColumns(10);
numbersToGenerate.setPreferredSize(new Dimension(100, 25));
panNmbrsToGenerate.setBorder(BorderFactory.createTitledBorder("Number of pixels to generate"));
panNmbrsToGenerate.add(numbersToGenerate);
JPanel content = new JPanel();
content.setBackground(Color.white);
content.add(panWidth);
content.add(panHeight);
content.add(panDelay);
content.add(panNmbrsToGenerate);
JPanel control = new JPanel();
JButton okBouton = new JButton("OK");
okBouton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
requestCommand = new GameRequestCommand(Integer.parseInt(width.getText()),
Integer.parseInt(height.getText()),Integer.parseInt(delay.getText()),Integer.parseInt(numbersToGenerate.getText()));
setVisible(false);
}
});
JButton cancelBouton = new JButton("Annuler");
cancelBouton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
}
});
control.add(okBouton);
control.add(cancelBouton);
this.getContentPane().add(content, BorderLayout.CENTER);
this.getContentPane().add(control, BorderLayout.SOUTH);
}
}
| true
|
5c7dd15355701caf11861dc233abcc62972eebd3
|
Java
|
VectorWen/Netty4.0.xStudy
|
/src/main/java/com/vector/study/task/day1/Day1PackClient.java
|
UTF-8
| 2,122
| 2.609375
| 3
|
[] |
no_license
|
package com.vector.study.task.day1;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
/**
* author: vector.huang
* date: 2016/12/17 09:34
*/
public class Day1PackClient {
public static void run(int port){
EventLoopGroup work = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(work)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringDecoder())
.addLast(new StringEncoder())
.addLast(new ChannelInboundHandlerAdapter(){
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
for (int i = 0; i < 100; i++) {
ctx.channel().writeAndFlush(i + "");
}
}
});
}
})
.option(ChannelOption.TCP_NODELAY,true)
.option(ChannelOption.SO_KEEPALIVE,true);
ChannelFuture future = bootstrap.connect("127.0.0.1",port).sync();
future.channel().closeFuture().sync();
}catch (Exception e){
e.printStackTrace();
}finally {
work.shutdownGracefully();
}
}
public static void main(String[] args) {
run(8080);
}
}
| true
|
2b8c9b565639f3bdfe5ee9adc1efff1045631a92
|
Java
|
DrRing/Allure-TestNG-Java-Framework
|
/src/test/java/com/cc/test/shared/datafactory/CaseData.java
|
UTF-8
| 1,048
| 2.296875
| 2
|
[] |
no_license
|
package com.cc.test.shared.datafactory;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CaseData extends CaseCommonFields{
private Map<String, Object> caseData = new HashMap<String, Object>();
public Map<String, Object> getCaseData() {
return caseData;
}
public void setCaseData(Map<String, Object> caseData) {
this.caseData = caseData;
}
public <T> T getTestData(Class<T> typeParameterClass) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.convertValue(caseData, typeParameterClass);
}
public CaseCommonFields getCommonFields() {
return getTestData(CaseCommonFields.class);
}
public CaseCommonFields getCaseFields() {
return getTestData(CaseCommonFields.class);
}
}
| true
|
6045e3b2d05240a39497fe0bcca48c3625a5bb16
|
Java
|
chamoddissanayake/SchoolManagementSystem
|
/src/main/java/com/itp/exception/QueryLoadingException.java
|
UTF-8
| 287
| 1.890625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.itp.exception;
public class QueryLoadingException extends Exception{
private static final long serialVersionUID = 1L;
public QueryLoadingException(String string, Exception e) {
super(string,e);
}
public QueryLoadingException(String string) {
super(string);
}
}
| true
|
37e88ab03a54da9ff624c259fa6d63be9fac6261
|
Java
|
BeYkeRYkt/nubia_cam_smali
|
/com/android/common/appService/C0350z.java
|
UTF-8
| 3,711
| 1.648438
| 2
|
[] |
no_license
|
package com.android.common.appService;
import android.app.Activity;
import android.content.Context;
import android.provider.Settings.System;
import com.android.common.C0616j;
import com.android.common.camerastate.DeviceState;
import com.android.common.setting.C0706f;
import com.p010a.C0090a;
public class C0350z extends Thread {
private Activity RJ = null;
private C0329e RK = null;
private C0147A RL = null;
private volatile boolean RM = false;
private int[] RN = null;
private long RO = 0;
public C0350z(Activity activity, C0329e c0329e, C0147A c0147a, int[] iArr) {
this.RJ = activity;
this.RK = c0329e;
this.RL = c0147a;
this.RN = iArr;
}
public void cancel() {
this.RM = true;
}
public void run() {
this.RO = System.currentTimeMillis();
ZW();
}
private void ZW() {
if (this.RL != null) {
this.RL.ZZ();
}
if (this.RN == null || this.RN.length == 0) {
ZV(CameraStartUpThread$CameraOpenState.FAIL_CAMERAID_ERROR);
return;
}
try {
if (!this.RM) {
ZX();
if (!this.RM) {
int[] iArr = this.RN;
int length = iArr.length;
int i = 0;
while (i < length) {
int i2 = iArr[i];
C0616j.apZ(this.RJ, i2);
if (!this.RM) {
this.RK.UM(i2).tW();
if (!this.RM) {
boolean arE;
C0706f UV = this.RK.UV();
Context SN = this.RK.SN();
CameraMember SP = this.RK.SP();
if (this.RK.SM() != null) {
arE = this.RK.SM().arE();
} else {
arE = false;
}
UV.uo(SN, i2, SP, arE);
i++;
} else {
return;
}
}
return;
}
if (!this.RM) {
this.RK.SX().Kd(DeviceState.PREVIEW_STOPPED);
if (!this.RM) {
ZV(CameraStartUpThread$CameraOpenState.SUCCESS);
}
}
}
}
} catch (Throwable e) {
ZV(CameraStartUpThread$CameraOpenState.FAIL_CAMERA_ERROR);
C0090a.bvi("CameraStartUpThread", "fail", e);
} catch (Throwable e2) {
ZV(CameraStartUpThread$CameraOpenState.FAIL_CAMERA_DISABLED);
C0090a.bvi("CameraStartUpThread", "disable", e2);
}
}
private void ZV(CameraStartUpThread$CameraOpenState cameraStartUpThread$CameraOpenState) {
if (this.RL != null) {
this.RL.ZY(this.RN, cameraStartUpThread$CameraOpenState);
}
}
private void ZX() {
while (ZU()) {
if (System.currentTimeMillis() - this.RO >= 3000) {
break;
}
}
if (System.currentTimeMillis() - this.RO > 3000) {
C0090a.m1e("CameraStartUpThread", "Wait captureCamera release failed!");
}
}
private boolean ZU() {
if (1 == System.getInt(this.RJ.getContentResolver(), "capture_service_camera_on", 0)) {
return true;
}
return false;
}
}
| true
|
4a89e45ac7062aad679f0560897d0612247793f7
|
Java
|
LegBill/bscs2b
|
/Legaspi/Shape.Abstract.Legaspi/MainClass.java
|
UTF-8
| 1,135
| 4.125
| 4
|
[] |
no_license
|
import java.util.*;
public class MainClass {
public static void main (String[] args)
{
Shape h1 = new Circle();
Shape h2 = new Square();
System.out.println("Welcome to Simple Abstraction! \n\n"
+ "\t Please type your number in order in diamater/length \n"
+ "\t in order to compute the areas in circle/square\n");
System.out.print("\t Your number: ");
Scanner skaner = new Scanner(System.in);
double number = skaner.nextInt();
System.out.print("\n\n\n");
System.out.println("----------YOUR NUMBER AS A CIRCLE----------");
h1.getArea(number);
h1.getShapeUsage();
h1.shapeSummary(number);
h1.inGeneral();
h1.shapeDrawing();
System.out.print("\n\n");
System.out.println("----------YOUR NUMBER AS A SQUARE----------");
h2.getArea(number);
h2.getShapeUsage();
h2.shapeSummary(number);
h2.inGeneral();
h2.shapeDrawing();
System.out.print("\n\n");
}
}
| true
|
4042005f1c0bb927489896df191936b9621b56e7
|
Java
|
MinecraftU/MinecraftByExample
|
/src/main/java/minecraftbyexample/mbe70_configuration/MBEConfiguration.java
|
UTF-8
| 12,061
| 2.953125
| 3
|
[
"Unlicense"
] |
permissive
|
package minecraftbyexample.mbe70_configuration;
import minecraftbyexample.MinecraftByExample;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Holds the configuration information and synchronises the various copies of it.
* The configuration information is stored in three places:
* 1) in the configuration file on disk, as text.
* 2) in the Configuration object config (accessed by the mod GUI), as text.
* 3) in the MBEConfiguration variables (fields), as native values (integer, double, etc).
*
* Setup:
* (1) During your mod preInit(), call MBEConfiguration.preInit() to:
* a) set up the format of the configuration file.
* b) load the settings from the existing file, or if it doesn't exist yet - create it with default values.
* (2) On the client proxy (not dedicated server), call clientPreInit() to register an OnConfigChangedEvent handler-
* your GUI will modify the config object, and when it is closed it will trigger a OnConfigChangedEvent,
* which should call syncFromGUI().
*
* Usage:
* (3) You can read the fields such as myInteger directly.
* (4) If you modify the configuration fields, you can save them to disk using syncFromFields().
* (5) To reload the values from disk, call syncFromFile().
* (6) If you have used a GUI to alter the config values, call syncFromGUI()
* (If you called clientPreInit(), this will happen automatically).
*
* => See ForgeModContainer for more examples.
*/
public class MBEConfiguration {
// Declare all configuration fields used by the mod here
public static int myInteger;
public static boolean myBoolean;
public static double myDouble;
public static int[] myIntList;
public static String myString;
public static String myColour;
public static final String CATEGORY_NAME_GENERAL = "category_general";
public static final String CATEGORY_NAME_OTHER = "category_other";
public static void preInit()
{
/*
* Here is where you specify the location from where your config file
* will be read, or created if it is not present.
*
* Loader.instance().getConfigDir() returns the default config directory
* and you specify the name of the config file, together this works
* similar to the old getSuggestedConfigurationFile() function.
*/
File configFile = new File(Loader.instance().getConfigDir(), "MinecraftByExample.cfg");
// initialize your configuration object with your configuration file values.
config = new Configuration(configFile);
// load config from file (see mbe70 package for more info)
syncFromFile();
}
public static void clientPreInit() {
/*
* Register the save config handler to the Forge event bus, creates an
* instance of the static class ConfigEventHandler and has it listen on
* the core Forge event bus (see Notes and ConfigEventHandler for more information).
*/
MinecraftForge.EVENT_BUS.register(new ConfigEventHandler());
}
public static Configuration getConfig() {
return config;
}
/**
* load the configuration values from the configuration file
*/
public static void syncFromFile() {
syncConfig(true, true);
}
/**
* save the GUI-altered values to disk
*/
public static void syncFromGUI() {
syncConfig(false, true);
}
/**
* save the MBEConfiguration variables (fields) to disk
*/
public static void syncFromFields() {
syncConfig(false, false);
}
/**
* Synchronise the three copies of the data
* 1) loadConfigFromFile && readFieldsFromConfig -> initialise everything from the disk file.
* 2) !loadConfigFromFile && readFieldsFromConfig --> copy everything from the config file (altered by GUI).
* 3) !loadConfigFromFile && !readFieldsFromConfig --> copy everything from the native fields.
*
* @param loadConfigFromFile if true, load the config field from the configuration file on disk.
* @param readFieldsFromConfig if true, reload the member variables from the config field.
*/
private static void syncConfig(boolean loadConfigFromFile, boolean readFieldsFromConfig)
{
/*
* ---- step 1 - load raw values from config file (if loadFromFile true) -------------------
*
* Check if this configuration object is the main config file or a child
* configuration For simple configuration setups, this only matters if
* you enable global configuration for your configuration object by
* using config.enableGlobalConfiguration(), this will cause your config
* file to be 'global.cfg' in the default configuration directory and
* use it to read/write your configuration options
*/
if (loadConfigFromFile) {
config.load();
}
/*
* Using language keys are a good idea if you are using a config GUI
* This allows you to provide "pretty" names for the config properties
* in a .lang file as well as allow others to provide other
* localizations for your mod.
*
* The language key is also used to get the tooltip for your property,
* the language key for each properties tooltip is langKey + ".tooltip"
* If no tooltip lang key is specified in a .lang file, it will default
* to the property's comment field.
*
* prop.setRequiresWorldRestart(true); and
* prop.setRequiresMcRestart(true); can be used to tell Forge if that
* specific property requires a world or complete Minecraft restart,
* respectively.
*
* Note: if a property requires a world restart it cannot be edited in
* the in-world mod settings (which hasn't been implemented yet by
* Forge), only when a world isn't loaded.
*
* -See the function definitions for more info
*/
/*
* ---- step 2 - define the properties in the configuration file -------------------
*
* The following code is used to define the properties in the
* configuration file: their name, type, default / min / max values, a
* comment. These affect what is displayed on the GUI. If the file
* already exists, the property values will already have been read from
* the file, otherwise they will be assigned the default value.
*/
// integer
final int MY_INT_MIN_VALUE = 3;
final int MY_INT_MAX_VALUE = 12;
final int MY_INT_DEFAULT_VALUE = 10;
Property propMyInt = config.get(CATEGORY_NAME_GENERAL, "myInteger", MY_INT_DEFAULT_VALUE,
"Configuration integer (myInteger)", MY_INT_MIN_VALUE, MY_INT_MAX_VALUE);
propMyInt.setLanguageKey("gui.mbe70_configuration.myInteger");
// boolean
final boolean MY_BOOL_DEFAULT_VALUE = true;
Property propMyBool = config.get(CATEGORY_NAME_GENERAL, "myBoolean", MY_BOOL_DEFAULT_VALUE);
propMyBool.setComment("Configuration boolean (myBoolean)");
propMyBool.setLanguageKey("gui.mbe70_configuration.myBoolean").setRequiresMcRestart(true);
// double
final double MY_DOUBLE_MIN_VALUE = 0.0;
final double MY_DOUBLE_MAX_VALUE = 1.0;
final double MY_DOUBLE_DEFAULT_VALUE = 0.80;
Property propMyDouble = config.get(CATEGORY_NAME_GENERAL, "myDouble", MY_DOUBLE_DEFAULT_VALUE,
"Configuration double (myDouble)", MY_DOUBLE_MIN_VALUE, MY_DOUBLE_MAX_VALUE);
propMyDouble.setLanguageKey("gui.mbe70_configuration.myDouble");
// string
final String MY_STRING_DEFAULT_VALUE = "default";
Property propMyString = config.get(CATEGORY_NAME_GENERAL, "myString", MY_STRING_DEFAULT_VALUE);
propMyString.setComment("Configuration string (myString)");
propMyString.setLanguageKey("gui.mbe70_configuration.myString").setRequiresWorldRestart(true);
// list of integer values
final int[] MY_INT_LIST_DEFAULT_VALUE = new int[] { 1, 2, 3, 4, 5 };
Property propMyIntList = config.get(CATEGORY_NAME_GENERAL, "myIntList", MY_INT_LIST_DEFAULT_VALUE,
"Configuration integer list (myIntList)");
propMyIntList.setLanguageKey("gui.mbe70_configuration.myIntList");
// a string restricted to several choices - located on a separate category tab in the GUI
final String COLOUR_DEFAULT_VALUE = "red";
final String[] COLOUR_CHOICES = { "blue", "red", "yellow" };
Property propColour = config.get(CATEGORY_NAME_OTHER, "myColour", COLOUR_DEFAULT_VALUE);
propColour.setComment("Configuration string (myColour): blue, red, yellow");
propColour.setLanguageKey("gui.mbe70_configuration.myColour").setRequiresWorldRestart(true);
propColour.setValidValues(COLOUR_CHOICES);
// By defining a property order we can control the order of the
// properties in the config file and GUI. This is defined on a per config-category basis.
List<String> propOrderGeneral = new ArrayList<String>();
propOrderGeneral.add(propMyInt.getName()); // push the config value's name into the ordered list
propOrderGeneral.add(propMyBool.getName());
propOrderGeneral.add(propMyDouble.getName());
propOrderGeneral.add(propMyString.getName());
propOrderGeneral.add(propMyIntList.getName());
config.setCategoryPropertyOrder(CATEGORY_NAME_GENERAL, propOrderGeneral);
List<String> propOrderOther = new ArrayList<String>();
propOrderOther.add(propColour.getName());
config.setCategoryPropertyOrder(CATEGORY_NAME_OTHER, propOrderOther);
/*
* ---- step 3 - read the configuration property values into the class's -------------------
* variables (if readFieldsFromConfig)
*
* As each value is read from the property, it should be checked to make
* sure it is valid, in case someone has manually edited or corrupted
* the value. The get() methods don't check that the value is in range
* even if you have specified a MIN and MAX value of the property.
*/
if (readFieldsFromConfig)
{
// If getInt() cannot get an integer value from the config file
// value of myInteger (e.g. corrupted file).
// It will set it to the default value passed to the function.
myInteger = propMyInt.getInt(MY_INT_DEFAULT_VALUE);
if (myInteger > MY_INT_MAX_VALUE || myInteger < MY_INT_MIN_VALUE) {
myInteger = MY_INT_DEFAULT_VALUE;
}
myBoolean = propMyBool.getBoolean(MY_BOOL_DEFAULT_VALUE); // can also use a literal (see integer example) if desired
myDouble = propMyDouble.getDouble(MY_DOUBLE_DEFAULT_VALUE);
if (myDouble > MY_DOUBLE_MAX_VALUE || myDouble < MY_DOUBLE_MIN_VALUE) {
myDouble = MY_DOUBLE_DEFAULT_VALUE;
}
myString = propMyString.getString();
myIntList = propMyIntList.getIntList();
myColour = propColour.getString();
boolean matched = false;
for (String entry : COLOUR_CHOICES) {
if (entry.equals(myColour)) {
matched = true;
break;
}
}
if (!matched) {
myColour = COLOUR_DEFAULT_VALUE;
}
}
/*
* ---- step 4 - write the class's variables back into the config -------------------
* properties and save to disk
*
* This is done even for a 'loadFromFile==true', because some of the
* properties may have been assigned default values if the file was empty or corrupt.
*/
propMyInt.set(myInteger);
propMyBool.set(myBoolean);
propMyDouble.set(myDouble);
propMyString.set(myString);
propMyIntList.set(myIntList);
propColour.set(myColour);
if (config.hasChanged()) {
config.save();
}
}
// Define your configuration object
private static Configuration config = null;
public static class ConfigEventHandler
{
/*
* This class, when instantiated as an object, will listen on the Forge
* event bus for an OnConfigChangedEvent
*/
@SubscribeEvent(priority = EventPriority.NORMAL)
public void onEvent(ConfigChangedEvent.OnConfigChangedEvent event)
{
if (MinecraftByExample.MODID.equals(event.getModID()) && !event.isWorldRunning())
{
if (event.getConfigID().equals(CATEGORY_NAME_GENERAL) || event.getConfigID().equals(CATEGORY_NAME_OTHER))
{
syncFromGUI();
}
}
}
}
}
| true
|
65cd972183df0ed3ce76c0225f7a294c30104004
|
Java
|
AlphaWang/alpha-demo
|
/alpha-concurrency/src/main/java/com/alphawang/concurrency/common/c3_publish/UnsafePublish.java
|
UTF-8
| 886
| 2.796875
| 3
|
[] |
no_license
|
package com.alphawang.concurrency.common.c3_publish;
import com.alphawang.concurrency.common.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
/**
* 23:52:53 [main] INFO c.a.c.c3_publish.UnsafePublish - INIT: [a, b, c]
* 23:52:53 [main] INFO c.a.c.c3_publish.UnsafePublish - MODIFIED: [d, b, c]
*/
@Slf4j
@NotThreadSafe
public class UnsafePublish {
private String[] states = { "a", "b", "c" };
public String[] getStates() {
return states;
}
public static void main(String[] args) {
UnsafePublish unsafePublish = new UnsafePublish();
log.info("INIT: {}", Arrays.toString(unsafePublish.getStates()));
// 其他线程可以直接修改field,造成状态错误
unsafePublish.getStates()[0] = "d";
log.info("MODIFIED: {}", Arrays.toString(unsafePublish.getStates()));
}
}
| true
|
3ee8e4d44d372234cd06749d9cb1e6963eb8f796
|
Java
|
leodemo/Crawler
|
/HouseCrawler/src/com/spider/main/SpiderControlMain.java
|
UTF-8
| 1,304
| 3.296875
| 3
|
[] |
no_license
|
package com.spider.main;
import java.util.*;
/**
* 使用线程池自动启动和结束爬虫线程,防止爬虫线程僵死
* 爬虫程序的主入口
* 每3个小时重启一次所有的爬行线程
* @author Liang Guo
*
*/
public class SpiderControlMain extends TimerTask{
public static List<Thread> threadlist=new ArrayList<Thread>();
public static void main(String[] args) {
// TODO Auto-generated method stub
Timer timer = new Timer();
SpiderControlMain task = new SpiderControlMain();
timer.schedule(task, 0,3*60*60*1000);
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(new Date()+"程序重置启动");
if(threadlist!=null&&threadlist.size()!=0){
int size=threadlist.size();
for (int i=0;i<size;i++){
Thread th=threadlist.get(0);
System.out.println("线程结束:"+th.getName());
try{
th.stop();
threadlist.remove(th);
}catch(Exception e){
e.printStackTrace();
}
}
System.out.println(new Date()+"关完没有:"+threadlist.size());
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(new Date()+"开始爬虫。。。");
StartNewsSpider.start();
}
}
| true
|
c5ec08f21faae58284037eef89d485597d9d7c28
|
Java
|
omibo/ut-se-online-laboratory
|
/src/RequestInsuranceControl.java
|
UTF-8
| 452
| 2.359375
| 2
|
[] |
no_license
|
public class RequestInsuranceControl {
private static final RequestInsuranceControl instance = new RequestInsuranceControl();
private RequestInsuranceControl() { }
public static RequestInsuranceControl getInstance() {
return instance;
}
public InsuranceReply submitRequestToInsuranceAPI(String insuranceName, String IID) {
// Insurance API call should be here
return new InsuranceReply(true, 0.1f);
}
}
| true
|
185609bea3acf2efec90ee9deb7b6431c0b42017
|
Java
|
qiango/yesmywine
|
/baseRecord/src/main/java/com/yesmywine/base/record/error/BaseRecordError.java
|
UTF-8
| 1,218
| 2.421875
| 2
|
[] |
no_license
|
package com.yesmywine.base.record.error;
import com.yesmywine.base.record.bean.VerifyType;
/**
* Created by WANG, RUIQING on 12/20/16
* Twitter : @taylorwang789
* E-mail : i@wrqzn.com
*/
public class BaseRecordError extends Exception {
private String code;
private String field;
private VerifyType verifyType;
public BaseRecordError() {
}
public BaseRecordError(String code, String field, VerifyType verifyType) {
this.code = code;
this.field = field;
this.verifyType = verifyType;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public VerifyType getVerifyType() {
return verifyType;
}
public void setVerifyType(VerifyType verifyType) {
this.verifyType = verifyType;
}
@Override
public void printStackTrace() {
super.printStackTrace();
System.out.println("code:" + code);
System.out.println("field:" + field);
System.out.println("verifyType:" + verifyType.name());
}
}
| true
|
d01f247d3bfdd9656f0763dcf359eef7804bec73
|
Java
|
marioples/spring
|
/src/main/java/hr/vsite/validator/PasswordValidator.java
|
UTF-8
| 1,417
| 2.578125
| 3
|
[] |
no_license
|
package hr.vsite.validator;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@FacesValidator("passwordValidator")
public class PasswordValidator implements Validator{
@Override
public void validate(FacesContext context, UIComponent component, Object object) throws ValidatorException {
ResourceBundle bundl = ResourceBundle.getBundle("validation");
String password = object.toString();
UIInput uiConfirmePassword = (UIInput) component.getAttributes().get("input_confirmpass");
String confirmPassword = uiConfirmePassword.getSubmittedValue().toString();
if(password == null || password.isEmpty() || confirmPassword == null || confirmPassword.isEmpty()){
FacesMessage msg = new FacesMessage("Empty password",
bundl.getString("Not.empty"));
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
if(!password.equals(confirmPassword)){
FacesMessage msg = new FacesMessage("Must match two passwords",
bundl.getString("Diff.password"));
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
}
| true
|
1e8d662bb2b2956933b25e1f4867587c53290da5
|
Java
|
polpokpoi/facebookSchedule
|
/schedule/src/main/java/kr/ac/mis/mapper/User_EventMapper.java
|
UTF-8
| 573
| 1.882813
| 2
|
[] |
no_license
|
package kr.ac.mis.mapper;
import java.util.Date;
import java.util.List;
import kr.ac.mis.model.Event;
import kr.ac.mis.model.EUser;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface User_EventMapper {
@Insert("INSERT INTO user_event(userId, eventId) values (#{userId}, #{eventId})")
public void insertUser_Event(@Param("userId") String userId,@Param("eventId") int eventId);
}
| true
|
48df5662ea14143d2e3143cc1cfe34b4a68eac88
|
Java
|
diegopablomansilla/msapi
|
/src/main/java/z/services/MiTareaSave.java
|
UTF-8
| 3,117
| 2.125
| 2
|
[] |
no_license
|
package z.services;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.StringReader;
import javax.json.Json;
import javax.json.JsonObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ms.back.EnvironmentVariables;
import com.ms.back.commons.services.AbstractService;
import z.dao.MiTareaSaveDAO;
public class MiTareaSave extends AbstractService {
private MiTareaSaveDAO dao = new MiTareaSaveDAO();
public MiTareaSave(EnvironmentVariables vars) {
super(vars);
}
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// String db = request.getHeader("db");
//
// if (db == null) {
// response.sendError(HttpServletResponse.SC_BAD_REQUEST);
// return;
// }
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String body = buffer.toString();
JsonObject jo = Json.createReader(new StringReader(body)).readObject();
if (jo == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
if (jo.isEmpty()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
String comentarioString = null;
String tareaIdString = null;
String personaIdString = null;
String att = "tarea";
if (jo.containsKey(att) && !jo.isNull(att)) {
tareaIdString = jo.getString(att);
}
att = "persona";
if (jo.containsKey(att) && !jo.isNull(att)) {
personaIdString = jo.getString(att);
}
att = "comentario";
if (jo.containsKey(att) && !jo.isNull(att)) {
comentarioString = jo.getString(att);
}
// --------------------------
String comentario = null;
String tareaId = null;
Integer personaId = null;
// ---
if (tareaIdString == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
tareaIdString = tareaIdString.trim();
if (tareaIdString.length() == 0) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
tareaId = tareaIdString;
// ---
if (personaIdString == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
personaIdString = personaIdString.trim();
if (personaIdString.length() == 0) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
try {
personaId = Integer.parseInt(personaIdString);
} catch (NumberFormatException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
// ---
if (comentarioString != null) {
comentarioString = comentarioString.trim();
}
comentario = comentarioString;
// ---
JsonObject item = dao.exec(vars.getDataBases().get(0), comentario, tareaId, personaId);
if (item == null) {
response.sendError(HttpServletResponse.SC_NO_CONTENT);
return;
}
response.setContentType(CONTENT_TYPE_JSON);
response.setStatus(HttpServletResponse.SC_CREATED);
String res = item.toString();
PrintWriter out = response.getWriter();
out.print(res);
out.flush();
}
}
| true
|
5bc7114bb7a45c6a9f5f4bf4f574c252e15b0143
|
Java
|
HypeOrg/OresomeInfected
|
/com/oresome/OresomeInfection/Listeners/ListMotdListener.java
|
UTF-8
| 731
| 2.125
| 2
|
[] |
no_license
|
package com.oresome.OresomeInfection.Listeners;
import com.oresome.OresomeInfection.Infection;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.ServerListPingEvent;
import org.bukkit.plugin.PluginManager;
public class ListMotdListener
implements Listener
{
public Infection plugin;
public ListMotdListener(Infection plugin)
{
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority=EventPriority.MONITOR)
public void onServerListPing(ServerListPingEvent event) {
event.setMotd(ChatColor.RED + "Oresome Infection!");
}
}
| true
|
b4699069c3bfa5678e9d96346db2011a2d384f63
|
Java
|
Prashant1293/sprinBoot-handsOn
|
/src/main/java/edu/knoldus/com/handsonspringboot/exceptions/InvalidNameException.java
|
UTF-8
| 214
| 2.3125
| 2
|
[] |
no_license
|
package edu.knoldus.com.handsonspringboot.exceptions;
public class InvalidNameException extends RuntimeException {
public InvalidNameException(String name) {
super(name + " is invalid.");
}
}
| true
|
f12108e9fd0ea79eb37b2c8e5b8f94d95871ea5b
|
Java
|
travelersun/query-filtering
|
/src/main/java/com/tianzhu/filtering/utils/SQLFilter.java
|
UTF-8
| 420
| 1.859375
| 2
|
[] |
no_license
|
package com.tianzhu.filtering.utils;
import java.util.Map;
import java.util.Set;
/**
* @Author: liaoyq
* @Desrition:
* @Created: 2018/10/9 14:30
* @Modified: 2018/10/9 14:30
* @Modified By: liaoyq
*/
public abstract interface SQLFilter {
public static final String FILTER_PREFIX = "F__QV_";
public abstract String getParameter(Object paramObject, Set<String> paramSet, Map<String, Object> paramMap);
}
| true
|
ce178f808c6e418f76412f669144467fb0a7fad5
|
Java
|
AnastasiyaVrublevskaya/HT0
|
/Prj01/src/com/training/Item.java
|
UTF-8
| 1,489
| 3.640625
| 4
|
[] |
no_license
|
package com.training;
//класс Item наследуют классы, представляющие произвольные предметы в помещении
public abstract class Item {
private int square;
private String name;
private String material;
public Item(String name, int square){
this.name = name;
this.square = square;
}
public int getSquare() {
return square;
}
//задание площади возможно только при добавлении предмета в помещение
//последующее изменение площади предмета не предусмотрено
//(нет проверки, что не будет превышено значение в 70%)
private void setSquare(int square) {
this.square = square;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMaterial() {
return material;
}
public void setMaterial(String material) {
this.material = material;
}
//метод, необходимый для переопределения подклассами
public abstract String getItemName();
//метод, общий для всех подклассов
public String getItemInfo(){
return String.valueOf("square: "+getSquare()+" m^2, material: "+getMaterial());
};
}
| true
|
a7c9e2a75850ad8b99d130e74e14a49ffde64914
|
Java
|
OliverS87/PDB123
|
/src/GUI/Main/PDB123Presenter.java
|
UTF-8
| 18,690
| 2.453125
| 2
|
[] |
no_license
|
package GUI.Main;
import Charts.PDBBarChart;
import PDBParser.PDB123LoadingTask;
import GUI.LogMessagesUI.PDB123PrintLog;
import GUI.ProgressUI.PDB123ProgressPresenter;
import GUI.SettingsUI.PDB123SettingsPresenter;
import SelectionModel.PDB123SelectionModel;
;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.SubScene;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Scale;
import javafx.scene.transform.Translate;
import javafx.stage.*;
import java.io.File;
import java.util.ArrayList;
/**
* Created by oliver on 19.01.16.
* Presenter class for PDB123 MVP design pattern
* Adds functionality to view elements
*/
public class PDB123Presenter {
// View elements
private GUI.Main.PDB123View PDB123View;
// 2D and 3D transformations
private Rotate rotateTertStructureX, rotateTertStructureY, rotateSecStructure;
private Translate translateTertCam, translateSecStructure;
private Scale scaleSecStructure;
// Mouse position coordinates
private double mouseXold, mouseXnew, mouseYold, mouseYNew, mouseXDelta, mouseYDelta;
// Message output
private PDB123PrintLog printLog;
// Booleanproperties to select 3D components to show
private BooleanProperty showBackbone, showSugar, showNucleoBase, showHBonds;
// Settings window
private PDB123SettingsPresenter settingsWindow;
// Barchart plot window
private PDBBarChart barChart;
// Path to currently loaded PDB file
private String path;
// Constructor
public PDB123Presenter(Stage primaryStage) {
// Initialize class variables
initClassVariables();
// Add functionality to menubar elements
// Set functions to menu items of file menu
loadFileFunction();
exitFunction();
// Set functions for menu items of edit menu
editFunctions();
// Set functions for menu items of view menu
viewFunctions();
// Set 3D camera
set3DCamera();
// Initialize 2D and 3D transformations
set2DTransformations();
set3DTransformations();
// Set 2D and 3D subscene Mouse actions
setMouseActions2D();
setMouseActions3D();
// Set checkbox actions
setCheckboxes();
// Set center-button actions
setCenterButtons();
// Set redraw bindings
redrawStructureBindings();
}
// Initialize class variables
private void initClassVariables() {
// Init. UI components
this.PDB123View = new PDB123View();
this.printLog = new PDB123PrintLog(PDB123View.getLog());
printLog.showInitalMessage();
this.barChart = new PDBBarChart();
this.settingsWindow = new PDB123SettingsPresenter();
// Init. boolean bindings
this.showNucleoBase = new SimpleBooleanProperty(true);
this.showSugar = new SimpleBooleanProperty(true);
this.showBackbone = new SimpleBooleanProperty(true);
this.showHBonds = new SimpleBooleanProperty(true);
// Init. selection model
PDB123SelectionModel.initSelectionModel();
}
// Menu File -> Load file
private void loadFileFunction() {
PDB123View.getMenuItemOpen().setOnAction(event -> {
// Try to load a file
// If file loading canceled -> print message
// else: print file name
// Save previous path
String oldPath = path;
path = null;
try {
path = showFileChooser();
} catch (Exception e) {
printLog.printLogMessage("No file loaded");
}
// If no valid path was returned by FileChooser
// set path back to old path (if existing)
// Do not proceed with file parsing
if (path == null){
if (oldPath != null) path = oldPath;
return;
}
String fileName = path.substring(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1);
printLog.printLogMessage("File loaded: " + fileName);
// Reset any applied transformation in 2D and 3D
reset2DTransformations();
reset3DTransformations();
// Employ a background task to load 1,2 and 3D structure from PDB file
loadStructureTask();
});
}
// Menu File -> exit
private void exitFunction() {
PDB123View.getMenuItemExit().setOnAction(event -> System.exit(0));
}
// Menu Edit -> Unselect all
// Menu Edit -> Settings
private void editFunctions()
{
// Unselect all nucleotides
PDB123View.getMenuItemClearSelection().setOnAction(event -> PDB123SelectionModel.unselectAll());
// Show settings window
PDB123View.getMenuItemSettings().setOnAction(event -> {
settingsWindow.getSettingsStage().show();
});
}
// Menu View -> Show statistics
private void viewFunctions()
{
// Show bar chart window
PDB123View.getMenuItemStats().setOnAction(event -> {
barChart.getBarChartStage().show();
});
}
// Set 3D perspective camera
// Set the near and farclip
// Fix the camera XYZ position at the center of the subscene
private void set3DCamera()
{
PerspectiveCamera cam = PDB123View.get3DCamera();
SubScene subScene3D = PDB123View.get3DSubScene();
// Set the near and farclip
cam.setNearClip(0.0000001);
cam.setFarClip(1000.0);
// Keep camera in the center of the subscene
// by binding camera XYZ to subscene width and height.
// Does not affect user-defined translations
// as these translations are added "on-top" of
// the defined camera position
cam.translateXProperty().bind(subScene3D.widthProperty().divide(-2));
cam.translateYProperty().bind(subScene3D.heightProperty().divide(-2));
cam.translateZProperty().bind(subScene3D.widthProperty().add(subScene3D.heightProperty()).divide(1.7));
}
// Set 2D transformations: translate, scale and rotate
private void set2DTransformations()
{
// Apply transformations to Group containing all 2nd structure shapes
Group secStructure = PDB123View.getSecStructureElements();
// Translate in XY direction
translateSecStructure = new Translate();
// Scale Group. Scaling needs a pivot point. Pivot point is bound to the center of the
// 2D subscene.
scaleSecStructure = new Scale();
scaleSecStructure.pivotXProperty().bind(PDB123View.getSubScene2D().widthProperty().divide(2.));
scaleSecStructure.pivotYProperty().bind(PDB123View.getSubScene2D().heightProperty().divide(2.));
// Rotate Group. Rotating needs a pivot point. Pivot point is bound to the center of the
// 2D subscene.
rotateSecStructure = new Rotate();
rotateSecStructure.pivotXProperty().bind(PDB123View.getSubScene2D().widthProperty().divide(2.));
rotateSecStructure.pivotYProperty().bind(PDB123View.getSubScene2D().heightProperty().divide(2.));
// Add all transformations to 2nd structure Group
secStructure.getTransforms().addAll(translateSecStructure, scaleSecStructure, rotateSecStructure);
}
// Set 3D transformations: translate and rotate.
// Unlike for 2D transformations, a scaling transformation is not needed.
// Zooming is instead facilitated by translating on the Z-Axis.
// Rotation is applied to the 3D shapes.
// Translation is applied to the camera.
private void set3DTransformations()
{
Group structure = PDB123View.getTertStructureElements();
// Rotation of Group structure
rotateTertStructureY = new Rotate(0, Rotate.Y_AXIS);
rotateTertStructureX = new Rotate(0, Rotate.X_AXIS);
structure.getTransforms().addAll(rotateTertStructureX, rotateTertStructureY);
// Translation of camera
PerspectiveCamera cam = PDB123View.get3DCamera();
translateTertCam = new Translate();
cam.getTransforms().add(translateTertCam);
}
// Mouse actions applied to 2D subscene
// Detect mouse clicks on the 2D subscene
// Action performed depends on the state of the
// shift and ctrl key
private void setMouseActions2D() {
// Save initial mouseX/Y
PDB123View.getSubScene2D().setOnMousePressed(event -> {
mouseXold = mouseXnew = event.getX();
mouseYold = mouseYNew = event.getY();
mouseXDelta = 0;
mouseYDelta = 0;
});
// Dimension of the transformation depends on the
// difference between the initial and new mouse position
// -> mouseXDelta
// -> mouseYDelta
// Empiric correction factors are applied to mouseXDelta
// and mouseYDelta to reduce mouse movement sensitivity
PDB123View.getSubScene2D().setOnMouseDragged(event -> {
mouseXold = mouseXnew;
mouseYold = mouseYNew;
mouseXnew = event.getX();
mouseYNew = event.getY();
mouseXDelta = mouseXnew - mouseXold;
mouseYDelta = mouseYNew - mouseYold;
// If shift key pressed: Apply scale transformation
if (event.isShiftDown()) {
scaleSecStructure.setX(scaleSecStructure.getX()+mouseYDelta*0.4);
scaleSecStructure.setY(scaleSecStructure.getY()+mouseYDelta*0.4);
}
// If ctrl key pressed: Apply translate transformation
if (event.isControlDown()) {
translateSecStructure.setX(translateSecStructure.getX()+mouseXDelta*0.6);
translateSecStructure.setY(translateSecStructure.getY()+mouseYDelta*0.6);
}
// If no key pressed: Rotate structure
if (!event.isShiftDown() && ! event.isControlDown()){
rotateSecStructure.setAngle(rotateSecStructure.getAngle()+mouseXDelta*-0.2);
}
});
}
// Mouse actions applied to 3D subscene
// Detect mouse clicks on the 3D subscene
// Action performed depends on the state of the
// shift and ctrl key
private void setMouseActions3D() {
PerspectiveCamera cam = PDB123View.get3DCamera();
// Save initial mouseX/Y
PDB123View.get3DSubScene().setOnMousePressed(event -> {
mouseXold = mouseXnew = event.getX();
mouseYold = mouseYNew = event.getY();
mouseXDelta = 0;
mouseYDelta = 0;
});
// Dimension of the transformation depends on the
// difference between the initial and new mouse position
// -> mouseXDelta
// -> mouseYDelta
// Empiric correction factors are applied to mouseXDelta
// and mouseYDelta to reduce mouse movement sensitivity
PDB123View.get3DSubScene().setOnMouseDragged(event -> {
mouseXold = mouseXnew;
mouseYold = mouseYNew;
mouseXnew = event.getX();
mouseYNew = event.getY();
mouseXDelta = mouseXnew - mouseXold;
mouseYDelta = mouseYNew - mouseYold;
// If shift key pressed: Apply Z-translation to camera
if (event.isShiftDown()) {
translateTertCam.setZ(translateTertCam.getZ()+mouseYDelta);
}
// If ctrl key pressed: Apply X,Y-translate to camera
if (event.isControlDown()) {
translateTertCam.setX(translateTertCam.getX()-mouseXDelta*0.2);
translateTertCam.setY(translateTertCam.getY()-mouseYDelta*0.2);
}
// If no key pressed: Rotate 3D structure group
if (!event.isShiftDown() && !event.isControlDown()) {
rotateTertStructureY.setAngle(rotateTertStructureY.getAngle() + mouseXDelta * 0.2);
rotateTertStructureX.setAngle(rotateTertStructureX.getAngle() - mouseYDelta * 0.2);
}
});
}
// Buttons stacked on top of the 2D and 3D subscene
// Click resets all applied 2D or 3D transformations
private void setCenterButtons()
{
PDB123View.getCenter3D().setOnAction(event -> {
reset3DTransformations();
});
PDB123View.getCenter2D().setOnAction(event -> {
reset2DTransformations();
});
}
// Set default values to checkboxes stacked on top of
// 3D subscene. Value of checkbox decides if 3D structure element
// (nucleobase, sugar, h-bonds, backbone) are shown
private void setCheckboxes()
{
PDB123View.getcBnucleoBase3D().setSelected(true);
showNucleoBase.bind(PDB123View.getcBnucleoBase3D().selectedProperty());
PDB123View.getcBsugar3D().setSelected(true);
showSugar.bind(PDB123View.getcBsugar3D().selectedProperty());
PDB123View.getcBpBB3D().setSelected(false);
showBackbone.bind(PDB123View.getcBpBB3D().selectedProperty());
PDB123View.getcBhDB().setSelected(true);
showHBonds.bind(PDB123View.getcBhDB().selectedProperty());
}
// Some changed values in settings window require a redrawing of the 2D and 3D structure.
// Add a listener to the settings Boolean property redrawProperty. If value is changed to true
// and a valid file is currently loaded, reload that file to apply the new settings.
private void redrawStructureBindings()
{
settingsWindow.redrawProperty().addListener((observable, oldValue, newValue) -> {
if (newValue && path != null) loadStructureTask();
});
}
// Reset user-defined 2D translations,
// scaling and rotations back to zero.
private void reset2DTransformations()
{
translateSecStructure.setX(0);
translateSecStructure.setY(0);
rotateSecStructure.setAngle(0);
scaleSecStructure.setX(1);
scaleSecStructure.setY(1);
}
// Reset user-defined 3D translations
// and rotations back to zero.
private void reset3DTransformations()
{
translateTertCam.setX(0);
translateTertCam.setY(0);
translateTertCam.setZ(0);
rotateTertStructureX.setAngle(0);
rotateTertStructureY.setAngle(0);
}
// Load a PDB file and derive a 1D, 2D and 3D RNA structure representation from it
// This task is done in a background thread to prevent the freezing of the UI
// while this complex task is performed.
// To show the progress of the background task, a progress window is shown.
private void loadStructureTask()
{
// Define the background task
// Parameters are:
// 1. log-window to output messages
// 2. Path to PDB file
// 3. 2D subscene (required to set up bindings for proper resize of that subscene)
PDB123LoadingTask task1 = new PDB123LoadingTask(printLog, path, PDB123View.getSubScene2D());
// Set references to boolean properties
task1.setBooleanProperties(showBackbone, showSugar, showNucleoBase, showHBonds);
// Set reference to settings window to derive current settings
task1.setSettings(settingsWindow);
// Set actions to perform once task returns values
// Task returns an ArrayList of objects of length 4
// 1. Text nodes for primary structure as ArrayList<Text>
// 2. Group of 2D shapes for secondary structure representation
// 3. Group of 3D shapes for tertiary structure representation
// 4. Statistics as int[][]: Nr. of nucleotides ACGU and Nr. of base-paired nucleotides
task1.valueProperty().addListener((observable, oldValue, newValue) -> {
// Add 1D representation to UI
// Textflow requires that all Text nodes are added sequentielly to the parent node
// Adding Text nodes as group causes them to stack upon each other
ArrayList<Text> primStructure = (ArrayList<Text>) newValue.get(0);
TextFlow primStructureNode = PDB123View.getPrimStructure();
primStructureNode.getChildren().clear();
for (Text t: primStructure
) {
primStructureNode.getChildren().add(t);
}
// Add 2D representation to UI
PDB123View.getSecStructureElements().getChildren().clear();
PDB123View.getSecStructureElements().getChildren().add((Group)newValue.get(1));
// Add 3D representation to UI
PDB123View.getTertStructureElements().getChildren().clear();
PDB123View.getTertStructureElements().getChildren().add((Group)newValue.get(2));
// Show nucleotide counts on bar chart plot
int[][] ntCounts = (int[][]) newValue.get(3);
barChart.updateData(ntCounts[0], ntCounts[1]);
});
// Setup stage to show progress window
// Stage does not need any decorations
Stage progressStage = new Stage(StageStyle.UNDECORATED);
// Block access to any other window while progress stage is shown
progressStage.initModality(Modality.APPLICATION_MODAL);
// Keep progress stage on top
progressStage.setAlwaysOnTop(true);
// Setup scene for progress bar stage
PDB123ProgressPresenter progressPresenter = new PDB123ProgressPresenter(task1, progressStage);
Scene progressScene = new Scene(progressPresenter.getProgressView(), 200,100);
progressScene.getStylesheets().add("GUI/progressBarStyle.css");
progressStage.setScene(progressScene);
progressStage.show();
// Create a new Thread from Task and start thread
Thread structureThread = new Thread(task1);
structureThread.start();
}
// FileChooser dialog
private String showFileChooser() throws Exception {
String prevPath = this.path;
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("PDB Files", "*.pdb"),
new FileChooser.ExtensionFilter("All Files", "*.*"));
File selectedFile = fileChooser.showOpenDialog(null);
return selectedFile.getAbsolutePath();
}
// Getter for view
public GUI.Main.PDB123View getPDB123View() {
return PDB123View;
}
}
| true
|
0fdaf578233e333e308c6e75c3b6aac14904f3d8
|
Java
|
maryangrb/IntermedioSeleniumMR
|
/src/test/java/practico4_findBy/FindBysEjemplos.java
|
UTF-8
| 2,925
| 2.640625
| 3
|
[] |
no_license
|
package practico4_findBy;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindAll;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class FindBysEjemplos {
String URL = "https://www.netflix.com";
public WebDriver driver;
@BeforeMethod
public void setup(){
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.get(URL);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
PageFactory.initElements(driver, this);
}
/*Ingresar a netflix
Mostrar la cantidad de párrafos
Mostrar la cantidad de links
Imprimir los links que tienen texto
Mostrar el texto de todos los botones*/
@FindBy (tagName = "p")
public List<WebElement> listaParrafos;
@FindBy (tagName = "a")
public List<WebElement> listaLinks;
@FindBy (tagName = "button")
public List<WebElement> listaBtns;
@Test
public void ejercicio1(){
Assert.assertNotEquals(listaParrafos.size(), 0); //para asegurarnos q la lista tenga elementos
Assert.assertNotEquals(listaLinks.size(), 0);
Assert.assertNotEquals(listaBtns.size(), 0);
System.out.println("La cant de parrafos es " + listaParrafos.size());
System.out.println("La cant de links es " + listaLinks.size());
for (WebElement link : listaLinks){
if (link.getText().isEmpty() == false){
System.out.println("-->" + link.getText());
}
}
System.out.println("Los botones:");
for (WebElement btn : listaBtns){
if (btn.getText().isEmpty() == false){
System.out.println("-->" + btn.getText());
}
}
}
@Test
public void searchLoginBtn(){
for(WebElement btn : listaBtns){
if(btn.getText().equals("Login")){
//...
}
}
}
@Test
public void searchLinks(){
//Olvide mi contraseña
//Login
for(WebElement link : listaLinks){
if(link.getText().equals("Olvide mi contraseña")){
link.click();
}
if(link.getText().contains("contraseña")){
link.click();
}
}
}
@FindAll({
@FindBy(how = How.TAG_NAME, using = "h1"),
@FindBy(how = How.TAG_NAME, using = "h2"),
@FindBy(how = How.TAG_NAME, using = "h3")
})
public List<WebElement> getAllHs;
}
| true
|
39feb550d114e183b3e06a5ee98d2dbd52128ec1
|
Java
|
Arasz/Head-First-Android-Development
|
/Stopwatch/app/src/main/java/com/example/raraszkiewicz/stopwatch/model/IStopwatch.java
|
UTF-8
| 237
| 2.296875
| 2
|
[
"MIT"
] |
permissive
|
package com.example.raraszkiewicz.stopwatch.model;
/**
* Created by r.araszkiewicz on 01.09.2016.
*/
public interface IStopwatch
{
void Start();
void Stop();
void Reset();
String getFormatedTime();
}
| true
|
a47b8bb1a3d7d68889cb5c53c1e846bc69fc25c3
|
Java
|
hanbioinformatica/owe5a
|
/demoGUI/src/MyGUI.java
|
UTF-8
| 1,669
| 3.8125
| 4
|
[] |
no_license
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyGUI extends JFrame implements ActionListener {
JTextField field; //declaratie van een tekstveld
JButton button; // declaratie van button
JPanel panel; // declaratie van een panel om op te tekenen
public static void main(String[] args) {
MyGUI frame = new MyGUI();
frame.setSize(400,400);
frame.createGUI();
frame.setVisible(true);
}
private void createGUI(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setBackground(Color.CYAN);
window.setLayout(new FlowLayout());
field = new JTextField("Typ hier iets"); // initialisatie
window.add(field); // plaatsen van het tekstveld in de container(window)
field.setBackground(Color.magenta);
button = new JButton("Klik"); // init button
window.add(button); // plaats op window
button.addActionListener(this); // koppelen actionlistener aan button
panel = new JPanel(); // init panel
panel.setPreferredSize(new Dimension(300,300));
panel.setBackground(Color.YELLOW);
window.add(panel);
}
@Override
public void actionPerformed(ActionEvent e) {
Graphics paper = panel.getGraphics();
paper.setColor(Color.RED);
paper.drawLine(10,10,100,100);
paper.setColor(Color.BLACK);
paper.fillOval(200,200,20,20);
field.setText("Hello World!");
button.setBackground(Color.blue);
System.out.println("Actie ");
}
}
| true
|
99f7a8427490ef89c9a30f0fa4da935393760545
|
Java
|
FelixOngati/ebm-web
|
/src/main/java/ebm/web/model/persistence/Role.java
|
UTF-8
| 118
| 1.726563
| 2
|
[] |
no_license
|
package ebm.web.model.persistence;
/**
* Created by the_fegati on 4/26/16.
*/
public enum Role {
USER, ADMIN
}
| true
|
d9e410a863d0af817d710d7f3a4101f67d661aef
|
Java
|
MarkShen1992/Mashibing_High_Concurrency
|
/src/main/java/com/basic/chapter0400/Chapter0403SortAlgorithm.java
|
UTF-8
| 2,358
| 3.953125
| 4
|
[] |
no_license
|
package com.basic.chapter0400;
/**
* 排序数组: 选择排序(Selection Sort)
* 写程序先跑主流程,主流程跑通后再考虑程序的细节
*
* 如何分析一个你不熟悉的算法呢?
* 在纸上 画图分析,分析i等于0, 1, 2, ...的情况, 找规律
*
* 十大经典排序算法(动图演示)
* https://www.cnblogs.com/onepixel/articles/7674659.html
*
* @author MarkShen
* @since 20191123
*/
public class Chapter0403SortAlgorithm {
// selection algorithm
private static int[] arr = {6, 9, 5, 4, 9, 12};
private static double[] arr2 = {0.1, 0.2, 0.3, 0.1};
// bubble sort algorithm
private static int[] arr3 = {1, 2, 4, 3, 9, 2};
public static void main(String[] args) {
int[] array = selectionSort(arr);
for (int i : array) {
System.out.println(i);
}
double[] arr = selectionSort(arr2);
for (double d : arr) {
System.out.println(d);
}
}
/**
* algorithm implementation method
* algorithm thinking:
*
* @param arr
* @return
*/
private static int[] selectionSort(int[] arr) {
if (arr == null) {
return new int[0];
}
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
int tmp = 0;
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
return arr;
}
/**
* 选择排序算法
*
* @param arr
* @return
*/
private static double[] selectionSort(double[] arr) {
if (arr == null) {
return new double[0];
}
double len = arr.length;
int minIndex;
double temp;
for (int i = 0; i < len - 1; i++) {
minIndex = i;
for (int j = i + 1; j < len; j++) {
if (arr[j] < arr[minIndex]) { // 寻找最小的数
minIndex = j; // 将最小数的索引保存
}
}
if (minIndex != i) {
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
return arr;
}
}
| true
|
70835624f136b2c1ac373d66fc75236c2a811e21
|
Java
|
bulison/test
|
/ops-biz/src/main/java/cn/fooltech/fool_ops/domain/analysis/service/CostAnalysisBilldetailService.java
|
UTF-8
| 14,648
| 1.84375
| 2
|
[] |
no_license
|
package cn.fooltech.fool_ops.domain.analysis.service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import cn.fooltech.fool_ops.utils.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import com.google.common.base.Strings;
import cn.fooltech.fool_ops.component.core.PageParamater;
import cn.fooltech.fool_ops.component.core.RequestResult;
import cn.fooltech.fool_ops.domain.analysis.entity.CostAnalysisBill;
import cn.fooltech.fool_ops.domain.analysis.entity.CostAnalysisBilldetail;
import cn.fooltech.fool_ops.domain.analysis.repository.CostAnalysisBilldetailRepository;
import cn.fooltech.fool_ops.domain.analysis.vo.CostAnalysisBilldetailVo;
import cn.fooltech.fool_ops.domain.base.service.BaseService;
import cn.fooltech.fool_ops.domain.basedata.entity.AuxiliaryAttr;
import cn.fooltech.fool_ops.domain.basedata.entity.Supplier;
import cn.fooltech.fool_ops.domain.basedata.entity.TransportPrice;
import cn.fooltech.fool_ops.domain.basedata.service.AuxiliaryAttrService;
import cn.fooltech.fool_ops.domain.basedata.service.SupplierService;
import cn.fooltech.fool_ops.domain.basedata.service.TransportPriceService;
import cn.fooltech.fool_ops.domain.freight.entity.FreightAddress;
import cn.fooltech.fool_ops.domain.freight.service.FreightAddressService;
import cn.fooltech.fool_ops.domain.report.entity.SysReportSql;
import cn.fooltech.fool_ops.domain.report.entity.UserTemplateDetail;
import cn.fooltech.fool_ops.utils.DateUtils;
import cn.fooltech.fool_ops.utils.SecurityUtil;
import cn.fooltech.fool_ops.utils.VoFactory;
import cn.fooltech.fool_ops.validator.ValidatorUtils;
/**
* 服务类
*/
@Service
public class CostAnalysisBilldetailService
extends BaseService<CostAnalysisBilldetail, CostAnalysisBilldetailVo, String> {
@PersistenceContext
private EntityManager em;
@Autowired
private CostAnalysisBilldetailRepository repository;
@Autowired
private CostAnalysisBillService billService;
@Autowired
private TransportPriceService priceService;
@Autowired
private SupplierService supplierService;
@Autowired
private FreightAddressService addressService;
@Autowired
private AuxiliaryAttrService attrService;
/**
* 实体转换VO
*
* @param entity
* @return
*/
@Override
public CostAnalysisBilldetailVo getVo(CostAnalysisBilldetail entity) {
CostAnalysisBilldetailVo vo = VoFactory.createValue(CostAnalysisBilldetailVo.class, entity);
CostAnalysisBill bill = entity.getBill();
if(bill!=null){
vo.setBillId(bill.getId());
}
TransportPrice transportPrice = entity.getTransportBill();
if(transportPrice!=null){
vo.setTransportBillId(transportPrice.getId());
}
vo.setBillDate(DateUtils.getStringByFormat(entity.getBillDate(), "yyyy-MM-dd HH:mm:ss"));
vo.setUpdateTime(DateUtils.getStringByFormat(entity.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
FreightAddress deliveryPlace = entity.getDeliveryPlace();
if(deliveryPlace!=null){
vo.setDeliveryPlaceId(deliveryPlace.getFid());
vo.setDeliveryPlaceName(deliveryPlace.getName());
}
FreightAddress receiptPlace = entity.getReceiptPlace();
if(receiptPlace!=null){
vo.setReceiptPlaceId(receiptPlace.getFid());
vo.setReceiptPlaceName(receiptPlace.getName());
}
AuxiliaryAttr shipmentType = entity.getShipmentType();
if(shipmentType!=null){
vo.setShipmentTypeId(shipmentType.getFid());
vo.setShipmentTypeName(shipmentType.getName());
}
Supplier supplier = entity.getSupplier();
if(supplier!=null){
vo.setSupplierId(supplier.getFid());
vo.setSupplierName(supplier.getName());
}
AuxiliaryAttr transportType = entity.getTransportType();
if(transportType!=null){
vo.setTransportTypeId(transportType.getFid());
vo.setTransportTypeName(transportType.getName());
}
AuxiliaryAttr unit = entity.getTransportUnit();
if(unit!=null){
vo.setTransportUnitId(unit.getFid());
vo.setTransportUnitName(unit.getName());
}
return vo;
}
@Override
public CrudRepository<CostAnalysisBilldetail, String> getRepository() {
return repository;
}
/**
* 查找分页
*
* @param vo
* @param paramater
* @return
*/
public Page<CostAnalysisBilldetailVo> query(CostAnalysisBilldetailVo vo, PageParamater paramater) {
String accId = SecurityUtil.getFiscalAccountId();
Sort sort = new Sort(Sort.Direction.DESC, "billDate");
PageRequest pageRequest = getPageRequest(paramater, sort);
Page<CostAnalysisBilldetail> page = repository.findPageBy(accId,vo, pageRequest);
return getPageVos(page, pageRequest);
}
public List<CostAnalysisBilldetailVo> query(String billId) {
PageParamater paramater = new PageParamater();
paramater.setPage(1);
paramater.setStart(0);
paramater.setRows(Integer.MAX_VALUE);
String accId = SecurityUtil.getFiscalAccountId();
Sort sort = new Sort(Sort.Direction.DESC, "billDate");
PageRequest pageRequest = getPageRequest(paramater, sort);
CostAnalysisBilldetailVo vo = new CostAnalysisBilldetailVo();
vo.setBillId(billId);
Page<CostAnalysisBilldetail> page = repository.findPageBy(accId,vo, pageRequest);
Page<CostAnalysisBilldetailVo> vos = getPageVos(page, pageRequest);
return vos.getContent();
}
/**
* 查询报表的所有数据
* @param billId 主表id
* @param sql
* @return
*/
@SuppressWarnings("unchecked")
public List<Object[]> queryAll(String billId,String sql){
Query query = em.createNativeQuery(sql);
query.setParameter("billId", billId);
// setPageForProcedure(query, 0, Integer.MAX_VALUE);
List<Object[]> datas = query.getResultList();
return datas;
}
/**
* 设置分页参数
* @param query
* @param start 起始位置
* @param maxResult 分页大小
*/
private void setPageForProcedure(Query query, int start, int maxResult){
query.setParameter("COUNTFLAG", 0);
query.setParameter("START", start);
query.setParameter("MAXRESULT", maxResult);
}
/**
* 修改或新增
*
* @param vo
* @return
*/
@Transactional
public RequestResult save(CostAnalysisBilldetailVo vo) {
String inValid = ValidatorUtils.inValidMsg(vo);
if (inValid != null) {
return new RequestResult(RequestResult.RETURN_FAILURE, inValid);
}
CostAnalysisBilldetail entity = null;
if (Strings.isNullOrEmpty(vo.getId())) {
entity = new CostAnalysisBilldetail();
entity.setFiscalAccount(SecurityUtil.getFiscalAccount());
entity.setCreator(SecurityUtil.getCurrentUser());
entity.setCreateTime(new Date());
entity.setUpdateTime(new Date());
entity.setOrg(SecurityUtil.getCurrentOrg());
} else {
entity = repository.findOne(vo.getId());
if (entity.getUpdateTime().compareTo(DateUtils.getDateFromString(vo.getUpdateTime())) != 0) {
return buildFailRequestResult("数据已被其他用户修改,请刷新再试");
}
// Date billDate = DateUtils.getDateFromString(vo.getBillDate());
// //当前时间,用于修改时判断单据日期是否当天,如果不是,不允许修改记录
// Date date = DateUtils.getDateFromString(DateUtils.getCurrentDate());
//
// if(date.compareTo(billDate)!=0){
// return buildFailRequestResult("只能修改当天的有效数据!");
// }
entity.setUpdateTime(new Date());
}
String billId = vo.getBillId();
CostAnalysisBill analysisBill=null;
if(!Strings.isNullOrEmpty(billId)){
analysisBill = billService.findOne(billId);
entity.setBill(analysisBill);
}
entity.setNo(vo.getNo());
if(!Strings.isNullOrEmpty(vo.getTransportBillId())){
entity.setTransportBill(priceService.findOne(vo.getTransportBillId()));
}
entity.setBillDate(DateUtils.getDateFromString(vo.getBillDate()));
if(!Strings.isNullOrEmpty(vo.getSupplierId())){
entity.setSupplier(supplierService.findOne(vo.getSupplierId()));
}
if(!Strings.isNullOrEmpty(vo.getDeliveryPlaceId())){
entity.setDeliveryPlace(addressService.findOne(vo.getDeliveryPlaceId()));
}
if(!Strings.isNullOrEmpty(vo.getReceiptPlaceId())){
entity.setReceiptPlace(addressService.findOne(vo.getReceiptPlaceId()));
}
if(!Strings.isNullOrEmpty(vo.getTransportTypeId())){
entity.setTransportType(attrService.findOne(vo.getTransportTypeId()));
}
if(!Strings.isNullOrEmpty(vo.getShipmentTypeId())){
entity.setShipmentType(attrService.findOne(vo.getShipmentTypeId()));
}
if(!Strings.isNullOrEmpty(vo.getTransportUnitId())){
entity.setTransportUnit(attrService.findOne(vo.getTransportUnitId()));
}
//折算运输单价【基本运费】
BigDecimal basePrice = vo.getBasePrice()==null?BigDecimal.ZERO:vo.getBasePrice();
//调整折算运输单价【对外基本运费】
BigDecimal publishBasePrice = vo.getPublishBasePrice()==null?BigDecimal.ZERO:vo.getPublishBasePrice();
//换算关系 运输单位与货品基本单位的换算关系
BigDecimal conversionRate2 = vo.getConversionRate()==null?new BigDecimal(1):vo.getConversionRate();
entity.setConversionRate(conversionRate2);
//折算运输单价【基本运费】
entity.setBasePrice(basePrice);
//调整折算运输单价【对外基本运费】
entity.setPublishBasePrice(publishBasePrice);
//运输费用
entity.setFreightPrice(conversionRate2.multiply(basePrice));
//调整运输费用
entity.setPublishFreightPrice(conversionRate2.multiply(publishBasePrice));
//可执行标识(1-可执行 2-难执行 3-无法执行)
entity.setExecuteSign(vo.getExecuteSign());
//预计天数
entity.setExpectedDays(vo.getExpectedDays());
//场地费用单价
entity.setGroundCostPrice(vo.getGroundCostPrice()==null?BigDecimal.ZERO:vo.getGroundCostPrice());
entity.setRemark(vo.getRemark());//备注
repository.save(entity);
/*注:修改明细表对外运费,按换算率自动计算对外基本运费,相反当修改对外基本运费自动计算对外运费;
举例:如果换算率为28,外运费为2800,则计算对外基本运费=2800/28;
主表的对外运费由明细表的对外基本运费汇总得出,主表的预计时间由明细表的预计时间汇出得出;
主表的对外总价=对外出厂价+对外运费;*/
//注:对外总价==对外总价
if(analysisBill!=null){
//明细表总运输费用
BigDecimal freightPrice = BigDecimal.ZERO;
//明细表总对外运输费用
BigDecimal publishFreightPrice = BigDecimal.ZERO;
//总预计时间
Integer expectedDays=0;
//可执行标识最大值,主表可执行标识等于从表可执行标识的最大值
Integer maxExecuteSign=0;
List<CostAnalysisBilldetail> list = repository.findByBillId(analysisBill.getId());
for (CostAnalysisBilldetail billdetail : list) {
BigDecimal basePrice2 = billdetail.getBasePrice();
BigDecimal publishBasePrice2 = billdetail.getPublishBasePrice();
freightPrice=freightPrice.add(basePrice2);
publishFreightPrice=publishFreightPrice.add(publishBasePrice2);
//预计时间
Integer days = billdetail.getExpectedDays();
expectedDays = expectedDays+days;
Integer executeSign = billdetail.getExecuteSign();
//主表可执行标识等于从表可执行标识的最大值
if(executeSign>maxExecuteSign) {
maxExecuteSign=executeSign;
}
}
//设置主表运输费用
analysisBill.setFreightPrice(freightPrice);
//设置主表对外运输费用
analysisBill.setPublishFreightPrice(publishFreightPrice);
//设置主表预计时间
analysisBill.setExpectedDays(expectedDays);
//对外出厂价
BigDecimal publishFactoryPrice = analysisBill.getPublishFactoryPrice();
//主表的对外总价=对外出厂价+对外运费;
BigDecimal publishTotalPrice = publishFactoryPrice.add(publishFreightPrice);
analysisBill.setPublishTotalPrice(publishTotalPrice);
//设置主表可执行标识
analysisBill.setExecuteSign(maxExecuteSign);
billService.save(analysisBill);
}
return buildSuccessRequestResult(getVo(entity));
}
/**
* 查询其他运输公司在有效期内的报价记录
* @param vo
* @param paramater
* @return
*/
public Page<CostAnalysisBilldetailVo> findOtherCompany(CostAnalysisBilldetailVo vo,PageParamater paramater){
String accId = SecurityUtil.getFiscalAccountId();
String deliveryPlaceId=vo.getDeliveryPlaceId();
String receiptPlaceId=vo.getReceiptPlaceId();
String transportTypeId=vo.getTransportTypeId();
String shipmentTypeId=vo.getShipmentTypeId();
String supplierId = vo.getSupplierId();
Sort sort = new Sort(Sort.Direction.DESC, "billDate");
PageRequest request = getPageRequest(paramater, sort);
Page<CostAnalysisBilldetail> page = repository.findOtherCompany(accId, deliveryPlaceId, receiptPlaceId, transportTypeId, shipmentTypeId,supplierId, request);
return getPageVos(page, request);
}
/**
* 查询运输公司在有效期内的报价记录
* @param deliveryPlaceId 发货地ID 关联场地表
* @param receiptPlaceId 收货地ID 关联场地表
* @param transportTypeId 运输方式ID(关联辅助属性运输方式)
* @param shipmentTypeId 装运方式ID(关联辅助属性装运方式)
* @param shipmentTypeId 装运方式ID(关联辅助属性装运方式)
* @return
*/
public CostAnalysisBilldetailVo findByCompany(String deliveryPlaceId,String receiptPlaceId,String transportTypeId,String shipmentTypeId,String supplierId){
String accId = SecurityUtil.getFiscalAccountId();
CostAnalysisBilldetail entity = repository.findByCompany(accId, deliveryPlaceId, receiptPlaceId, transportTypeId, shipmentTypeId, supplierId);
if(entity!=null){
return getVo(entity);
}else{
return null;
}
}
/**
* 根据单据ID查询明细
* @param billId 单据id
* @return
*/
public List<CostAnalysisBilldetailVo> findVosByBillId(String billId){
List<CostAnalysisBilldetail> list = repository.findByBillId(billId);
List<CostAnalysisBilldetailVo> vos = getVos(list);
return vos;
}
/**
* 根据单据ID查询明细
* @param billId 单据id
* @return
*/
public List<CostAnalysisBilldetail> findByBillId(String billId){
List<CostAnalysisBilldetail> list = repository.findByBillId(billId);
return list;
}
}
| true
|
080db5bfe2a5ee2fec2e8cbeb3233a8394dded7d
|
Java
|
zhanghaoxuan184/Covid19
|
/backend/src/main/java/com/covid19/backend/controller/prescription/DeletePrescription.java
|
UTF-8
| 2,008
| 2.234375
| 2
|
[] |
no_license
|
package com.covid19.backend.controller.prescription;
import com.covid19.backend.controller.BaseController;
import com.covid19.backend.model.Result;
import com.covid19.backend.model.Prescription;
import com.covid19.backend.service.prescription.DeletePrescriptionService;
import com.covid19.backend.service.prescription.GetPrescriptionInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
@RestController
@Api(tags = "用药控制器", value = "和用药有关的控制器")
public class DeletePrescription {
@Autowired
public DeletePrescriptionService deletePrescriptionService;
@Autowired
public GetPrescriptionInfoService getPrescriptionInfoService;
@PostMapping("/prescription/deletePrescriptionByID")
@ApiOperation(value = "删除用药信息",notes = "可以删除用药的信息")
@ApiImplicitParam(name = "prescription_id",value = "用药ID")
public Result deletePrescriptionByID(
@RequestParam(value = "prescription_id") long prescription_id,
HttpServletRequest request)
{
if(deletePrescriptionService.checkCurrentUserInfo(request) == -1) return Result.error(Result.CODE_UNAUTHORIZED, "账号信息错误。");
Prescription prescription = getPrescriptionInfoService.getPrescriptionInfoByID(prescription_id);
if(prescription == null) return Result.error(2012,"不存在该用药记录");
deletePrescriptionService.deletePrescriptionByID(prescription_id);
return Result.ok();
}
}
| true
|
c2683fee70143af616ff9ae218f47559a7928156
|
Java
|
Harshbhama/Tbs-Nascomm
|
/TbsGuiMysql/src/com/Tbs/gui/TbsGuiUserDebitCard.java
|
UTF-8
| 6,418
| 2.375
| 2
|
[] |
no_license
|
package com.Tbs.gui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import com.Tbs.model.TbsBillHistoryVo;
import com.Tbs.service.TbsBillHistoryService;
public class TbsGuiUserDebitCard implements ActionListener, KeyListener {
public JLabel headingLabel, cardNumberLabel, expiryDateLabel, cvvLabel, payableLabel;
public JTextField cardNumberTextField, expiryDateTextField, cvvTextField;
public float payable;
public JButton payButton, clearButton, backButton;
public JFrame frame;
public int customerId;
public TbsGuiUserDebitCard(int customerId, float payable) {
this.customerId = customerId;
this.payable = payable;
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Debit Card");
frame.setLayout(null);
Image bg = null;
try {
bg = ImageIO.read(TbsGuiUserDebitCard.class.getResource("look.com.ua-35320.jpg"));
} catch (IOException exception) {
exception.printStackTrace();
}
frame.setContentPane(new JLabel(new ImageIcon(bg)));
frame.setSize(1366, 768);
payableLabel = new JLabel("Payable amount is " + payable);
payableLabel.setForeground(Color.WHITE);
payableLabel.setFont(new Font("Serif", Font.ITALIC, 35));
headingLabel = new JLabel("Paying through Debit Card");
headingLabel.setFont(new Font("Serif", Font.ITALIC, 65));
cardNumberLabel = new JLabel("Card Number");
cardNumberLabel.setFont(new Font("Aerial", Font.ITALIC, 25));
expiryDateLabel = new JLabel("Expiry Date");
expiryDateLabel.setFont(new Font("Aerial", Font.ITALIC, 25));
cvvLabel = new JLabel("CVV No.");
cvvLabel.setFont(new Font("Aerial", Font.ITALIC, 25));
payButton = new JButton("Pay");
payButton.setFont(new Font("Aerial", Font.ITALIC, 25));
clearButton = new JButton("Clear");
clearButton.setFont(new Font("Aerial", Font.ITALIC, 25));
backButton = new JButton("Back");
backButton.setFont(new Font("Aerial", Font.ITALIC, 25));
cardNumberTextField = new JTextField();
expiryDateTextField = new JTextField();
cvvTextField = new JTextField();
cardNumberTextField.setFont(new Font("Aerial", Font.ITALIC, 20));
expiryDateTextField.setFont(new Font("Aerial", Font.ITALIC, 20));
cvvTextField.setFont(new Font("Aerial", Font.ITALIC, 20));
headingLabel.setBounds(250, 40, 800, 100);
payableLabel.setBounds(350, 140, 800, 100);
cardNumberLabel.setBounds(350, 250, 160, 40);
expiryDateLabel.setBounds(350, 320, 160, 40);
cvvLabel.setBounds(350, 390, 160, 40);
payButton.setBounds(400, 550, 140, 50);
clearButton.setBounds(580, 550, 140, 50);
backButton.setBounds(760, 550, 140, 50);
cardNumberTextField.setBounds(550, 250, 400, 40);
expiryDateTextField.setBounds(550, 320, 400, 40);
cvvTextField.setBounds(550, 390, 400, 40);
payButton.addActionListener(this);
clearButton.addActionListener(this);
backButton.addActionListener(this);
headingLabel.setForeground(Color.WHITE);
cardNumberLabel.setForeground(Color.WHITE);
expiryDateLabel.setForeground(Color.WHITE);
cvvLabel.setForeground(Color.WHITE);
frame.add(headingLabel);
frame.add(payableLabel);
frame.add(cardNumberLabel);
frame.add(cardNumberTextField);
frame.add(expiryDateLabel);
frame.add(expiryDateTextField);
frame.add(cvvLabel);
frame.add(cvvTextField);
frame.add(payButton);
frame.add(clearButton);
frame.add(backButton);
cardNumberTextField.addKeyListener(this);
expiryDateTextField.addKeyListener(this);
cvvTextField.addKeyListener(this);
payButton.addKeyListener(this);
clearButton.addKeyListener(this);
backButton.addKeyListener(this);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent.getSource() == payButton) {
TbsBillHistoryService tbsBillHistoryService = new TbsBillHistoryService();
TbsBillHistoryVo tbsBillHistoryVo = new TbsBillHistoryVo();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
tbsBillHistoryVo.setAmount(payable);
tbsBillHistoryVo.setCustomerId(customerId);
tbsBillHistoryVo.setPaymentMode("Debit Card");
tbsBillHistoryVo.setPaymentDate(dateFormat.format(date));
int x = tbsBillHistoryService.payBillService(tbsBillHistoryVo);
if (x > 0) {
JOptionPane.showMessageDialog(payButton, "Congratulations");
frame.setVisible(false);
new TbsGuiUserHome(customerId);
}
} else if (actionEvent.getSource() == clearButton) {
cardNumberTextField.setText("");
expiryDateTextField.setText("");
cvvTextField.setText("");
} else {
frame.setVisible(false);
new TbsGuiUserPayBill(customerId);
}
}
@Override
public void keyPressed(KeyEvent keyEvent) {
if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
TbsBillHistoryService tbsBillHistoryService = new TbsBillHistoryService();
TbsBillHistoryVo tbsBillHistoryVo = new TbsBillHistoryVo();
DateFormat dateFormat = new SimpleDateFormat("dd/MMMM/yy");
Date date = new Date();
tbsBillHistoryVo.setAmount(payable);
tbsBillHistoryVo.setCustomerId(customerId);
tbsBillHistoryVo.setPaymentMode("Debit Card");
tbsBillHistoryVo.setPaymentDate(dateFormat.format(date));
int x = tbsBillHistoryService.payBillService(tbsBillHistoryVo);
if (x > 0) {
JOptionPane.showMessageDialog(payButton, "Congratulations");
frame.setVisible(false);
new TbsGuiUserHome(customerId);
}
} else if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE) {
frame.setVisible(false);
new TbsGuiUserPayBill(customerId);
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
| true
|
a6ecafe9da216754f11e7ad25a8eb6aa5b9710d0
|
Java
|
alexbelij/driver
|
/driver-service/src/main/java/com/driver/web/model/BasicResponse.java
|
UTF-8
| 538
| 1.828125
| 2
|
[] |
no_license
|
package com.driver.web.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;
import java.util.List;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
@Data
@JsonInclude(NON_NULL)
@AllArgsConstructor
@NoArgsConstructor
public class BasicResponse {
@JsonIgnore
HttpStatus httpStatus;
List<String> errors;
}
| true
|
28b45b980719d754346c35cd4437f2e0ceaf151b
|
Java
|
2Hours/myproject
|
/src/main/java/com/hzq/ssmboot/manage/model/User.java
|
UTF-8
| 2,442
| 2.28125
| 2
|
[] |
no_license
|
package com.hzq.ssmboot.manage.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class User {
private String user_id;
private String user_name;
private String password;
private Integer user_type;
private String nickname;
private String mobile;
private Integer sex;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date create_time;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date modify_time;
public User() {
}
public User(String user_id, String user_name, String password, Integer user_type, String nickname,
String mobile, Integer sex, Date create_time, Date modify_time) {
this.user_id = user_id;
this.user_name = user_name;
this.password = password;
this.user_type = user_type;
this.nickname = nickname;
this.mobile = mobile;
this.sex = sex;
this.create_time = create_time;
this.modify_time = modify_time;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getUser_type() {
return user_type;
}
public void setUser_type(Integer user_type) {
this.user_type = user_type;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
public Date getModify_time() {
return modify_time;
}
public void setModify_time(Date modify_time) {
this.modify_time = modify_time;
}
}
| true
|
dcbfce0cd6bb32053db77b7f529721a31a8cd6f1
|
Java
|
HungFoolishry/ysvsys_demo
|
/hungry-java/src/main/java/lee/search/BinarySearch.java
|
UTF-8
| 3,261
| 4.25
| 4
|
[] |
no_license
|
package lee.search;
/**
* description: 二分查找 正常版本,左边界,右边界
*
* @author JunchaoYao
* @date 2021-01-22 15:16
**/
public class BinarySearch {
public int binarySearch(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
// 因为搜索区间是[left, right],极限情况 left = right的时候 还是要搜索的
while (left <= right) {
// 防止溢出
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
//数字在mid的左边
} else if (nums[mid]>target) {
right = mid - 1;
//在mid的右边
} else if (nums[mid]<target) {
left = mid + 1;
}
}
return -1;
}
public int leftBinarySearch(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] == target) {
// 别返回,锁定左侧边界
right = mid - 1;
}
}
// 最后要检查 left 越界的情况 在所有数值<target, left= length+1 / 在所有数值>target,left = right = 0
// 在right 没有移动的情况下,left=len-1 +1,溢出了数组的下标
if (left >= nums.length || nums[left] != target) {
return -1;
}
return left;
}
public int rightBinarySearch(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] == target) {
// 别返回,锁定右侧边界
left = mid + 1;
}
}
// 最后要检查 right 越界的情况, 在所有数值< target, left=right = len-1/all >target, right=left-1=-1
// 因为是右边界,所以返回right。在left没有移动的情况下,跳出循环的时候right = left-1 = -1,会溢出,所以必须判断
if (right < 0 || nums[right] != target)
return -1;
return right;
}
public static void main(String[] args) {
BinarySearch binarySearch = new BinarySearch();
System.out.println(binarySearch.rightSearch(new int[]{1, 2, 2, 2, 3,}, -11));
}
public int rightSearch(int[] nums, int target) {
int len = nums.length;
int l = 0;
int r = len - 1;
while (l <= r) {
int mid = l + (r - l)/2;
if (target == nums[mid]) {
l = mid + 1;
} else if (target > nums[mid]) {
l = mid + 1;
} else if (target < nums[mid]) {
r = mid - 1;
}
}
if (r < 0 || nums[r] != target) {
return -1;
}
return r;
}
}
| true
|
b978ce1f23b73228e87ac99d429f215fada315a1
|
Java
|
cxdyyt/main
|
/src/Sorting/BucketSort.java
|
UTF-8
| 502
| 3.203125
| 3
|
[] |
no_license
|
package Sorting;
public class BucketSort extends CommonSort<Integer> {
int maxValue;
public BucketSort(int maxValue) {
super();
this.maxValue = maxValue;
}
@Override
public void sortInner(Integer[] arrs) {
int[] tmpArr = new int[maxValue];
for(int item : arrs) {
tmpArr[item]++;
}
int j=0;
for(int i=0;i<tmpArr.length;i++) {
int itm = tmpArr[i];
if(itm > 0) {
while(itm >0 ) {
arrs[j] = i;
itm--;
j++;
}
}
}
}
}
| true
|
0e43fd3dd90a8834928763fb41be092c2f3b5f7f
|
Java
|
nbourses/DeploymentBranch
|
/Oyeok/app/src/main/java/com/nbourses/oyeok/RPOT/OkBroker/UI/Rental_Broker_Requirement.java
|
UTF-8
| 10,609
| 1.671875
| 2
|
[] |
no_license
|
package com.nbourses.oyeok.RPOT.OkBroker.UI;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.text.Layout;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.github.clans.fab.FloatingActionButton;
import com.nbourses.oyeok.Database.DBHelper;
import com.nbourses.oyeok.Database.DatabaseConstants;
import com.nbourses.oyeok.R;
import com.nbourses.oyeok.RPOT.ApiSupport.services.AcceptOkCall;
import com.nbourses.oyeok.RPOT.ApiSupport.services.OnAcceptOkSuccess;
import com.nbourses.oyeok.RPOT.OkBroker.CircularSeekBar.CircularSeekBarNew;
import com.nbourses.oyeok.RPOT.OyeOkBroker.AutoOkIntentSpecs;
import com.nbourses.oyeok.RPOT.PriceDiscovery.MainActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DecimalFormat;
public class Rental_Broker_Requirement extends Fragment implements CircularSeekBarNew.imageAction,OnAcceptOkSuccess {
CircularSeekBarNew cbn;
//TextView mTitle;
LinearLayout mNotClicked;
TextView rentText;
TextView displayOkText;
Button mOkbutton;
private Button pickContact;
private TextView contactName;
private JSONArray values = new JSONArray();
DBHelper dbHelper;
JSONArray dummyData = new JSONArray();
String oyeId,specCode,oyeUserId,reqAvl;
JSONArray p= new JSONArray();
int j;
Ok_Broker_MainScreen ok_broker_mainScreen;
Button droom;
FloatingActionButton autoOk;
// View popup;
// private PopupWindow pw;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_rental_ok__broker, container, false);
//mTitle = (TextView) v.findViewById(R.id.title);
mNotClicked = (LinearLayout) v.findViewById(R.id.notClicked);
rentText = (TextView) v.findViewById(R.id.rentText);
displayOkText = (TextView) v.findViewById(R.id.displayOkText);
mOkbutton = (Button) v.findViewById(R.id.okButton);
ok_broker_mainScreen=(Ok_Broker_MainScreen)getParentFragment();
pickContact = (Button) v.findViewById(R.id.pickContact);
contactName = (TextView) v.findViewById(R.id.contactText);
rentText.setText("Rent : 50k Rs/month");
dbHelper = new DBHelper(getContext());
droom= (Button) v.findViewById(R.id.droom);
View z= inflater.inflate(R.layout.broker_main_screen,container,false);
autoOk= (FloatingActionButton) z.findViewById(R.id.fab);
autoOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((MainActivity)getActivity()).changeFragment(new AutoOkIntentSpecs(), null,"");
}
});
mOkbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!dbHelper.getValue(DatabaseConstants.user).equals("Broker"))
{
ok_broker_mainScreen=(Ok_Broker_MainScreen)getParentFragment();
ok_broker_mainScreen.replaceWithSignUp(p,j);
}
else
{
AcceptOkCall a = new AcceptOkCall();
a.setmCallBack(Rental_Broker_Requirement.this);
a.acceptOk(p,j,dbHelper, getActivity());
}
}
});
droom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ok_broker_mainScreen.openDroomList();
}
});
pickContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
getActivity().startActivityForResult(intent, 302);
}
});
cbn = (CircularSeekBarNew) v.findViewById(R.id.circularseekbar);
cbn.setmImageAction(this);
for(int i=0;i<2;i++) {
JSONObject element= new JSONObject();
try {
element.put("oye_id", "vhdhCMSDMz");
} catch (JSONException e) {
e.printStackTrace();
}
try {
element.put("req_avl", "req");
} catch (JSONException e) {
e.printStackTrace();
}
try {
element.put("size", i+1+"bhk");
} catch (JSONException e) {
e.printStackTrace();
}
try {
element.put("price", (1+i)*(100000));
} catch (JSONException e) {
e.printStackTrace();
}
try {
if(i%2==0)
element.put("oye_status", "active");
else
element.put("oye_status","inactive");
} catch (JSONException e) {
e.printStackTrace();
}
try {
element.put("user_id", "vhdhCMSDMz");
} catch (JSONException e) {
e.printStackTrace();
}
try {if(i%2==0)
element.put("user_role", "client");
else
element.put("user_role","broker");
} catch (JSONException e) {
e.printStackTrace();
}
try {
dummyData.put(i, element);
} catch (JSONException e) {
e.printStackTrace();
}
}
if(dbHelper.getValue(DatabaseConstants.offmode).equalsIgnoreCase("null"))
cbn.setValues(dbHelper.getValue(DatabaseConstants.reqLl));
else
cbn.setValues(dummyData.toString());
return v;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
/*switch (reqCode) {
case (PICK_CONTACT):*/
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = getActivity().getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// TODO Fetch other Contact details as you want to use
contactName.setText(name);
// mOkbutton.setBackgroundColor(Color.parseColor("#B2DFDB"));
mOkbutton.setText("Ok(4290)");
Log.i("start droom", "name=" + name);
}
}
//break;
}
@Override
public void onclick(int position, JSONArray m, String show, int x_c, int y_c) {
// Toast.makeText(getActivity(),"The value is"+m.get(position),Toast.LENGTH_LONG).show();
// YoPopup yoPopup = new YoPopup();
// yoPopup.inflateYo(getActivity(), "LL-3BHK-20K", "broker");
try {
p=m;
j=position;
rentText.setText("Rs "+ m.getJSONObject(position).getString("price")+" /per m");
DecimalFormat formatter = new DecimalFormat();
//pw.showAtLocation(cbn, Gravity.CENTER,x_c,y_c);
//rentText.setText("Price : Rs "+ formatter.format(Double.parseDouble(m.getJSONObject(position).getString("price")))+"\n"+m.getJSONObject(position).getString("property_type")+"\n"+m.getJSONObject(position).getString("property_subtype"));
/*oyeId=m.getJSONObject(position).getString("oye_id");
oyeUserId= m.getJSONObject(position).getString("user_id");
specCode=m.getJSONObject(position).getString("tt")+"-"+m.getJSONObject(position).getString("size")+"-"+m.getJSONObject(position).getString("price");
reqAvl=m.getJSONObject(position).getString("req_avl");*/
} catch (JSONException e) {
e.printStackTrace();
}
if(show.equals("show"))
{
mNotClicked.setVisibility(View.GONE);
//mTitle.setVisibility(View.VISIBLE);
//mOkbutton.setBackgroundColor(Color.parseColor("#B2DFDB"));
//mOkbutton.setText("Ok(4290)");
rentText.setVisibility(View.VISIBLE);
displayOkText.setVisibility(View.VISIBLE);
pickContact.setVisibility(View.GONE);
contactName.setVisibility(View.GONE);
}else if(show.equals("hide"))
{
mNotClicked.setVisibility(View.VISIBLE);
//mTitle.setVisibility(View.GONE);
//mOkbutton.setBackgroundColor(Color.parseColor("#E0E0E0"));
rentText.setVisibility(View.GONE);
displayOkText.setVisibility(View.GONE);
pickContact.setVisibility(View.GONE);
contactName.setVisibility(View.GONE);
//mOkbutton.setText("Auto Ok");
//pw.dismiss();
}else
{
mNotClicked.setVisibility(View.GONE);
//mTitle.setVisibility(View.VISIBLE);
//mOkbutton.setBackgroundColor(Color.parseColor("#E0E0E0"));
rentText.setVisibility(View.VISIBLE);
displayOkText.setVisibility(View.VISIBLE);
//mOkbutton.setText("Auto Ok");
pickContact.setVisibility(View.VISIBLE);
contactName.setVisibility(View.VISIBLE);
}
}
@Override
public void replaceFragment(Bundle args) {
ok_broker_mainScreen.openChat(args);
}
}
| true
|
e11266e739fd5bb89ae9800d4e065830c1c84d2a
|
Java
|
changhwa/reserve
|
/reserve/src/main/java/com/narratage/reserve/inform/service/AirportService.java
|
UTF-8
| 1,367
| 2.59375
| 3
|
[] |
no_license
|
package com.narratage.reserve.inform.service;
import java.util.List;
import com.narratage.reserve.inform.domain.Airport;
/**
* 구글맵에서 표시될 도시를 가져오기 위해서 사용합니다. 동시에 DB에 저장된 모든 도시를 가져오는 경우 가독성이 떨어지며, DB에 지나친
* IO를 발생시킬 가능성이 있습니다. 구글맵의 왼쪽상단의 점과 오른쪽 하단의 점2개를 통해 직사각형을 그릴 수 있고 해당 직사각형 내부의
* 주요도시만 가져올 수 있도록 합니다. 도시들을 검색할 때 마다, 테이블의 검색횟수 컬럼이 늘어나며, 해당 횟수에 따라 우선순위를 부여한다.
* (미구현) 몇개의 도시를 불러올건지를 정하는 부분은 XML을 이용해서, 또는 DB에 정보를 가져오는 형태로 구현합니다.
*
* @author StevePak
**/
public interface AirportService {
public static final int MAXIMUM_CITIES_NUMBER = 20;
/**
* @param topLeftLat 왼쪽상단의 위도
* @param topLeftLong 왼쪽상단의 경도
* @param botRightLat 오른쪽 하단의 위도
* @param botRightLong 오른쪽 하단의 경도
* @return 공항의 리스트를 반환합니다.
*/
public List<Airport> getCitiesForMap(double topLeftLat, double topLeftLong, double botRightLat, double botRightLong);
}
| true
|
1c25790ef5c640544595d3a70fffa28fe02bc8d4
|
Java
|
zhilien-tech/juyo-visa
|
/visa/src/main/java/io/znz/jsite/visa/service/TravelService.java
|
UTF-8
| 698
| 1.84375
| 2
|
[] |
no_license
|
package io.znz.jsite.visa.service;
import io.znz.jsite.base.BaseService;
import io.znz.jsite.base.HibernateDao;
import io.znz.jsite.visa.bean.Travel;
import io.znz.jsite.visa.dao.TravelDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by Chaly on 2017/3/7.
*/
@Service
@Transactional(readOnly = true)
public class TravelService extends BaseService<Travel, Integer> {
@Autowired
private TravelDao travelDao;
@Override
public HibernateDao<Travel, Integer> getEntityDao() {
return travelDao;
}
}
| true
|
585e1fedb0a64f42afbbd1e1156f16f9936681df
|
Java
|
trannys/mygit
|
/TestCloud/Test-auth/src/main/java/com/lucq/service/impl/AccountServiceImpl.java
|
UTF-8
| 1,689
| 2.25
| 2
|
[] |
no_license
|
package com.lucq.service.impl;
import com.lucq.entity.Account;
import com.lucq.mapper.AccountMapper;
import com.lucq.oauth.CustomUserDetails;
import com.lucq.service.AccountService;
import com.lucq.util.EncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
/**
* Created by dell on 2019/1/24.
*/
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
@Override
public Account findById(Integer accountid) {
return accountMapper.selectByPrimaryKey(accountid);
}
@Override
public Account findByName(String username) {
if (StringUtils.isEmpty(username)) {
return null;
}
Account account = new Account();
account.setAccountName(username);
System.out.println(EncryptUtils.getRamdomStr(10));
return accountMapper.selectOne(account);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Account account = new Account();
account.setAccountName(username);
Account accountData = accountMapper.selectOne(account);
CustomUserDetails userDetails = new CustomUserDetails();
userDetails.setUsername(accountData.getAccountName());
userDetails.setPassword(accountData.getPassword());
userDetails.setAccount(accountData);
return userDetails;
}
}
| true
|
ebd662729e1ea6a619aa3690f8af28df7350be03
|
Java
|
nemanja1007/Nemanja_JavaEE
|
/JEE_uebungen/src/Webshop/Products.java
|
UTF-8
| 525
| 2.9375
| 3
|
[] |
no_license
|
package Webshop;
import java.util.ArrayList;
import java.util.List;
public class Products {
List<Item> items = new ArrayList<>();
static Products products = null;
public static Products getProducts() {
if(products == null)
products = new Products();
return products;
}
public boolean addItem(Item item) {
if(items.add(item))
return true;
return false;
}
public List<Item> getItems(){
return items;
}
}
| true
|
f0cd210d8e6fb6aec77e78ac478a1a5ea0995c88
|
Java
|
fabianschilling/settlers-of-catan
|
/src/gui/BuildingCostsMenu.java
|
IBM852
| 9,561
| 2.90625
| 3
|
[] |
no_license
|
package gui;
import java.awt.*;
import javax.swing.*;
/**
* Diese Klasse stellt das Baukostenmenü aus der GUI dar
*
* @author Florian Weiss, Fabian Schilling
*
*/
@SuppressWarnings("serial")
public class BuildingCostsMenu extends JPanel {
/**
* Die Breite des Panels
*/
private int width;
/**
* Die Höhe des Panels
*/
private int height;
/**
* Das Hintergrundpanel
*/
private ImagePanel bgpanel;
/**
* Ein Siedlungs-Icon
*/
private ImagePanel settlementpanel;
/**
* Ein Straßen-Icon
*/
private ImagePanel roadpanel;
/**
* Ein Stadt-Icon
*/
private ImagePanel citypanel;
/**
* Ein EntwicklungskartenIcon
*/
private ImagePanel cardpanel;
/**
* Istgleichzeichen
*/
private JLabel costs1;
/**
* Istgleichzeichen
*/
private JLabel costs2;
/**
* Istgleichzeichen
*/
private JLabel costs3;
/**
* Istgleichzeichen
*/
private JLabel costs4;
/**
* Wolle-Icon
*/
private ImagePanel wool;
/**
* Wolle-Icon
*/
private ImagePanel wool1;
/**
* Erz-Icon
*/
private ImagePanel ore;
/**
* Erz-Icon
*/
private ImagePanel ore1;
/**
* Erz-Icon
*/
private ImagePanel ore2;
/**
* Erz-Icon
*/
private ImagePanel ore3;
/**
* Lehm-Icon
*/
private ImagePanel brick;
/**
* Lehm-Icon
*/
private ImagePanel brick1;
/**
* Holz-Icon
*/
private ImagePanel lumber;
/**
* Holz-Icon
*/
private ImagePanel lumber1;
/**
* Getreide-Icon
*/
private ImagePanel grain;
/**
* Getreide-Icon
*/
private ImagePanel grain1;
/**
* Getreide-Icon
*/
private ImagePanel grain2;
/**
* Getreide-Icon
*/
private ImagePanel grain3;
/**Konstruktor der Anzeige des Baukostenmenus
* @param width Breite
* @param height Höhe
*/
public BuildingCostsMenu(int width, int height) {
this.width = width;
this.height = height;
this.setPreferredSize(new Dimension(width, height));
this.setOpaque(false);
init();
}
/**
* Initialisierung
*/
public void init() {
createWidgets();
setupInteraction();
addWidgets();
}
private void createWidgets() {
int size = (int) (height / 13);
bgpanel = new ImagePanel(ImportImages.chatBg, width, height);
roadpanel = new ImagePanel(ImportImages.roadBtn, size, size);
settlementpanel = new ImagePanel(ImportImages.settlementBtn, size, size);
citypanel = new ImagePanel(ImportImages.cityBtn, size, size);
cardpanel = new ImagePanel(ImportImages.cardBtn, size, size);
wool = new ImagePanel(ImportImages.woolBtn, size, size);
wool1 = new ImagePanel(ImportImages.woolBtn, size, size);
ore = new ImagePanel(ImportImages.oreBtn, size, size);
ore1 = new ImagePanel(ImportImages.oreBtn, size, size);
ore2 = new ImagePanel(ImportImages.oreBtn, size, size);
ore3 = new ImagePanel(ImportImages.oreBtn, size, size);
brick = new ImagePanel(ImportImages.brickBtn, size, size);
brick1 = new ImagePanel(ImportImages.brickBtn, size, size);
lumber = new ImagePanel(ImportImages.lumberBtn, size, size);
lumber1 = new ImagePanel(ImportImages.lumberBtn, size, size);
grain = new ImagePanel(ImportImages.grainBtn, size, size);
grain1 = new ImagePanel(ImportImages.grainBtn, size, size);
grain2 = new ImagePanel(ImportImages.grainBtn, size, size);
grain3 = new ImagePanel(ImportImages.grainBtn, size, size);
Font f = new Font("Times New Roman", Font.BOLD, 50); //$NON-NLS-1$
costs1 = new JLabel("="); //$NON-NLS-1$
costs1.setFont(f);
costs2 = new JLabel("="); //$NON-NLS-1$
costs2.setFont(f);
costs3 = new JLabel("="); //$NON-NLS-1$
costs3.setFont(f);
costs4 = new JLabel("="); //$NON-NLS-1$
costs4.setFont(f);
}
private void setupInteraction() {
wool.setToolTipText(Messages.getString("BuildingCostsMenu.Wolle")); //$NON-NLS-1$
wool1.setToolTipText(Messages.getString("BuildingCostsMenu.Wolle")); //$NON-NLS-1$
ore.setToolTipText(Messages.getString("BuildingCostsMenu.Eisen")); //$NON-NLS-1$
ore1.setToolTipText(Messages.getString("BuildingCostsMenu.Eisen")); //$NON-NLS-1$
ore2.setToolTipText(Messages.getString("BuildingCostsMenu.Eisen")); //$NON-NLS-1$
ore3.setToolTipText(Messages.getString("BuildingCostsMenu.Eisen")); //$NON-NLS-1$
brick.setToolTipText(Messages.getString("BuildingCostsMenu.Lehm")); //$NON-NLS-1$
brick1.setToolTipText(Messages.getString("BuildingCostsMenu.Lehm")); //$NON-NLS-1$
lumber.setToolTipText(Messages.getString("BuildingCostsMenu.Holz")); //$NON-NLS-1$
lumber1.setToolTipText(Messages.getString("BuildingCostsMenu.Holz")); //$NON-NLS-1$
grain.setToolTipText(Messages.getString("BuildingCostsMenu.Weizen")); //$NON-NLS-1$
grain1.setToolTipText(Messages.getString("BuildingCostsMenu.Weizen")); //$NON-NLS-1$
grain2.setToolTipText(Messages.getString("BuildingCostsMenu.Weizen")); //$NON-NLS-1$
grain3.setToolTipText(Messages.getString("BuildingCostsMenu.Weizen")); //$NON-NLS-1$
roadpanel.setToolTipText(Messages.getString("BuildingCostsMenu.Strasse")); //$NON-NLS-1$
settlementpanel.setToolTipText(Messages.getString("BuildingCostsMenu.Siedlung")); //$NON-NLS-1$
citypanel.setToolTipText(Messages.getString("BuildingCostsMenu.Stadt")); //$NON-NLS-1$
cardpanel.setToolTipText(Messages.getString("BuildingCostsMenu.Entwicklungskarte")); //$NON-NLS-1$
}
private void addWidgets() {
add(bgpanel);
bgpanel.setLayout(new GridBagLayout());
/**
* Strae
*/
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(roadpanel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 20, 0, 20);
bgpanel.add(costs1, c);
c = new GridBagConstraints();
c.gridx = 5;
c.gridy = 0;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(brick, c);
c = new GridBagConstraints();
c.gridx = 6;
c.gridy = 0;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(lumber, c);
/**
* Siedlung
*/
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(settlementpanel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 20, 0, 20);
bgpanel.add(costs2, c);
c = new GridBagConstraints();
c.gridx = 3;
c.gridy = 1;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(grain, c);
c = new GridBagConstraints();
c.gridx = 4;
c.gridy = 1;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(wool, c);
c = new GridBagConstraints();
c.gridx = 5;
c.gridy = 1;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(brick1, c);
c = new GridBagConstraints();
c.gridx = 6;
c.gridy = 1;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(lumber1, c);
/**
* Stadt
*/
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(citypanel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 20, 0, 20);
bgpanel.add(costs3, c);
c = new GridBagConstraints();
c.gridx = 2;
c.gridy = 2;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(grain2, c);
c = new GridBagConstraints();
c.gridx = 3;
c.gridy = 2;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(grain1, c);
c = new GridBagConstraints();
c.gridx = 4;
c.gridy = 2;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(ore1, c);
c = new GridBagConstraints();
c.gridx = 5;
c.gridy = 2;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(ore2, c);
c = new GridBagConstraints();
c.gridx = 6;
c.gridy = 2;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(ore, c);
/**
* Entwicklungskarte
*/
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 3;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(cardpanel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 3;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 20, 0, 20);
bgpanel.add(costs4, c);
c = new GridBagConstraints();
c.gridx = 4;
c.gridy = 3;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(grain3, c);
c = new GridBagConstraints();
c.gridx = 5;
c.gridy = 3;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(wool1, c);
c = new GridBagConstraints();
c.gridx = 6;
c.gridy = 3;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10, 0, 0, 5);
bgpanel.add(ore3, c);
}
}
| true
|
b32e498984f4ddab31cac6bdcc8043d3abfbeeae
|
Java
|
selena-groh/billsplitter
|
/app/src/main/java/io/github/selena_groh/tinyapp/MainActivity.java
|
UTF-8
| 2,732
| 2.1875
| 2
|
[
"MIT"
] |
permissive
|
package io.github.selena_groh.tinyapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public static final String SPLIT_AMOUNT = "io.github.selena-groh.SPLITAMOUNT";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSplitMyBill(View view) {
Log.d("**** In MainActivity", "SPLITTING BILL");
// Step 1: get the text view that is in the layout
EditText amountTxt = (EditText) findViewById(R.id.amount);
EditText numPeopleTxt = (EditText) findViewById(R.id.numPeople);
if (amountTxt.getText().toString().equals("") || numPeopleTxt.getText().toString().equals("")) {
TextView splitAmountText = (TextView) findViewById(R.id.splitAmountText);
splitAmountText.setText("Required Field Empty");
splitAmountText.setVisibility(1);
return;
}
Float amount = new Float(amountTxt.getText().toString());
Integer numPeople = new Integer(numPeopleTxt.getText().toString());
if (amount > 0 && numPeople > 0) {
Intent intent = new Intent(this, DisplaySplitAmount.class);
Float splitAmount = amount / numPeople;
Log.d("**** In MainActivity", String.format("%.2f", splitAmount));
intent.putExtra(SPLIT_AMOUNT, splitAmount);
startActivity(intent);
}
}
}
| true
|
8c2d6b68c608bb1a5c84c5eddd68af7a6c6662f3
|
Java
|
Al-ain-Developers/indesing_plugin
|
/devtools/idmltools/src/com/adobe/idml/samples/Notes.java
|
UTF-8
| 7,590
| 2.34375
| 2
|
[] |
no_license
|
//========================================================================================
//
// $File: //depot/devtech/16.0.x/devtools/idmltools/src/com/adobe/idml/samples/Notes.java $
//
// Owner: Joe Stinson
//
// $Author: vans $
//
// $DateTime: 2020/11/06 05:06:09 $
//
// $Revision: #1 $
//
// $Change: 1088554 $
//
// Copyright 2008 Adobe Systems Incorporated. All rights reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
// with the terms of the Adobe license agreement accompanying it. If you have received
// this file from a source other than Adobe, then your use, modification, or
// distribution of it requires the prior written permission of Adobe.
//
//========================================================================================
package com.adobe.idml.samples;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.ListIterator;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.xpath.XPathExpressionException;
import com.adobe.idml.FileTransformer;
import com.adobe.idml.FileUtils;
import com.adobe.idml.Package;
import com.adobe.idml.PackageException;
import com.adobe.idml.PackageXmlLocator;
import com.adobe.idml.PackageXslLocator;
import com.adobe.idml.XmlUtils;
/**
* This class contains tools for removing and extracting notes from an IDML package.
*/
public class Notes
{
private PackageXslLocator fXslLocator;
/**
* The default constructor.
*/
public Notes() { }
/**
* This constructor sets up an XSL Locator object.
* @param xslPath The path to the XSL files needed for transforms.
* @throws IOException
*/
public Notes(String xslPath) throws IOException
{
fXslLocator = new PackageXslLocator(xslPath);
}
/**
* Copies notes from an IDML file to a separate text file.
* @param idmlSource The IDML file to extract notes from.
* @param outputFile The location to write the output file containing notes to.
* @throws PackageException
* @throws IOException
* @throws XPathExpressionException
*/
public void extractNotes(String idmlSource, String outputFile) throws PackageException, IOException, XPathExpressionException
{
//Ensure the idmlSource is a valid IDML file.
Package.verifyPackage(idmlSource);
//Create a new output file and get a writer for that file.
FileUtils.deleteFile(outputFile);
File txtOutputFile = FileUtils.createFile(outputFile);
BufferedWriter txtOutputFileWriter = FileUtils.getFileWriter(txtOutputFile);
//Get story files from the idmlSouce package
File expandedIdmlDir = Package.decompress(idmlSource);
PackageXmlLocator xmlLoc = new PackageXmlLocator(expandedIdmlDir);
ArrayList<String> storyFiles = xmlLoc.getStoriesXmlFiles();
ListIterator<String> storyFilesItr = storyFiles.listIterator();
//Iterate through story files.
int totalNoteCount = 1;
while (storyFilesItr.hasNext())
{
//Iterate through notes in the story file.
String storyFile = storyFilesItr.next();
int fileNoteCount = XmlUtils.getNodeListCount(storyFile, "//Note");
for (int i = 1; i <= fileNoteCount; i++)
{
//Write Note Heading.
String noteHeading = String.format("=============== Note %d ===============", totalNoteCount);
txtOutputFileWriter.write(noteHeading);
txtOutputFileWriter.newLine();
//Iterate through each content tag in the Note
String expr = String.format("//Note[%d]//Content", i);
ArrayList<String> noteContents = XmlUtils.getElements(storyFile, expr);
ListIterator<String> noteContentsItr = noteContents.listIterator();
while (noteContentsItr.hasNext())
{
String content = noteContentsItr.next();
txtOutputFileWriter.write(content);
//When a single note has multiple content elements they are typically separated by a <BR> tag.
//For that reason a new line is added here to format the notes as they appear in InDesign.
txtOutputFileWriter.newLine();
}
//Add space between notes in the output file.
totalNoteCount++;
txtOutputFileWriter.newLine();
}
}
//Complete and cleanup
txtOutputFileWriter.close();
FileUtils.DeleteDirectory(expandedIdmlDir);
}
/**
* Creates a copy of an IDML file with the notes removed.
* @param idmlSource The IDML file to remove notes from.
* @param outputFile The IDML copy of idmlSource with the notes removed.
* @throws IOException
* @throws TransformerFactoryConfigurationError
* @throws TransformerException
*/
public void removeNotes(String idmlSource, String outputFile) throws IOException, TransformerFactoryConfigurationError, TransformerException
{
//Ensure the idmlSource is a valid IDML file.
Package.verifyPackage(idmlSource);
//Ensure the outputFile has an IDML extension.
Package.verifyPackage(outputFile);
//Get story files from the idmlSouce package
File expandedIdmlDir = Package.decompress(idmlSource);
PackageXmlLocator xmlLoc = new PackageXmlLocator(expandedIdmlDir);
ArrayList<String> storyFiles = xmlLoc.getStoriesXmlFiles();
ListIterator<String> storyFilesItr = storyFiles.listIterator();
try
{
//Iterate through story files.
while (storyFilesItr.hasNext())
{
String storyFilePath = storyFilesItr.next();
File storyFile = new File(storyFilePath);
String xslFilePath = fXslLocator.getCorrespondingXslFilePath(storyFilePath);
File xslFile = new File(xslFilePath);
//Transform each story file with the appropriate XSL file.
FileTransformer fileTransformer = new FileTransformer(xslFile, null);
fileTransformer.transformFile(storyFile, storyFile); // overwrites xmlFile
}
//Create the output IDML Package.
Package.compress(expandedIdmlDir, outputFile);
}
finally
{
//Cleanup
FileUtils.DeleteDirectory(expandedIdmlDir);
}
}
private static void usage()
{
System.out.println("Usage: Notes [operation] [Source IDML File] [Output File]");
System.out.println("\nOperations:");
System.out.println("\t-e\tExtracts or copies the notes from an IDML file to a text file.");
System.out.println("\t-r\tCreates a copy of an IDML file with the notes removed.");
System.out.println("\nExamples: ");
System.out.println("\tNotes -e SampleNote.idml SampleNote_Notes.txt");
System.out.println("\tNotes -r SampleNote.idml SampleNote_NotesRemoved.idml");
System.exit(-1);
}
/**
* The main method used to initialize the Notes class.
* @param args parameters provided by the console application.
*/
public static void main(String[] args)
{
if(args.length < 3)
{
usage();
}
String operation = args[0];
String idmlSource = args[1];
String outputFile = args[2];
try
{
//The output files have not yet been created.
//This ensures the parent directory which will
//contain the file exists.
FileUtils.ensureParentDirectory(outputFile);
if ( operation.equalsIgnoreCase("-e"))
{
Notes en = new Notes();
en.extractNotes(idmlSource, outputFile);
}
else if ( operation.equalsIgnoreCase("-r"))
{
String xslPath = "xsl/remove";
Notes en = new Notes(xslPath);
en.removeNotes(idmlSource, outputFile);
}
else {
usage();
}
}
catch( Exception e)
{
String err = "Remove Notes Failure.\nError Message:\t%s\nStack Trace:\t%s\n";
System.err.printf(err, e.getMessage(), e.getStackTrace());
}
}
}
| true
|
b46e2d7a16080a8d7cc2e899d012dc33be43e311
|
Java
|
carldibert/Book-Keeping
|
/src/AuthorButtonPanel.java
|
UTF-8
| 2,773
| 2.96875
| 3
|
[] |
no_license
|
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JToolBar;
/**
*
* @author Andrey
*
*/
public class AuthorButtonPanel extends JToolBar {
// ********************************
// ATTRIBUTES
// ********************************
private JButton buttonNewAuthor;
private JButton buttonUpdateAuthor;
private JButton buttonDeleteAuthor;
private JButton buttonCancelAuthor;
// ********************************
// CONSTRUCTOR
// ********************************
public AuthorButtonPanel() {
this.setFloatable(false);
this.setAlignmentY(LEFT_ALIGNMENT);
buttonNewAuthor = new JButton("New");
buttonNewAuthor.setMnemonic('N');
buttonNewAuthor.setIcon(new ImageIcon("images/new.png"));
buttonNewAuthor.setFocusPainted(false);
buttonUpdateAuthor = new JButton("Update");
buttonUpdateAuthor.setMnemonic('U');
buttonUpdateAuthor.setIcon(new ImageIcon("images/accept.png"));
buttonUpdateAuthor.setFocusPainted(false);
buttonDeleteAuthor = new JButton("Delete");
buttonDeleteAuthor.setMnemonic('D');
buttonDeleteAuthor.setIcon(new ImageIcon("images/discard.png"));
buttonDeleteAuthor.setFocusPainted(false);
buttonCancelAuthor = new JButton("Cancel");
buttonCancelAuthor.setMnemonic('C');
buttonCancelAuthor.setIcon(new ImageIcon("images/cancel.png"));
buttonCancelAuthor.setFocusPainted(false);
this.add(buttonNewAuthor);
this.add(buttonUpdateAuthor);
this.add(buttonDeleteAuthor);
this.add(buttonCancelAuthor);
this.NewState();
}//end of Constructor
// ********************************
// GETS/SETS
// ********************************
/**
* @return the buttonNewAuthor
*/
public JButton getButtonNewAuthor() {
return buttonNewAuthor;
}
/**
* @return the buttonUpdateAuthor
*/
public JButton getButtonUpdateAuthor() {
return buttonUpdateAuthor;
}
/**
* @return the buttonDeleteAuthor
*/
public JButton getButtonDeleteAuthor() {
return buttonDeleteAuthor;
}
/**
* @return the buttonCancelAuthor
*/
public JButton getButtonCancelAuthor() {
return buttonCancelAuthor;
}
// ********************************
// METHODS
// ********************************
/**
* Used when the list has no items selected
*/
public void NewState(){
this.buttonNewAuthor.setEnabled(true);
this.buttonUpdateAuthor.setEnabled(false);
this.buttonDeleteAuthor.setEnabled(false);
this.buttonCancelAuthor.setEnabled(false);
}
/**
* Used when the list has an item selected
*/
public void UpdateState(){
this.buttonNewAuthor.setEnabled(false);
this.buttonUpdateAuthor.setEnabled(true);
this.buttonDeleteAuthor.setEnabled(true);
this.buttonCancelAuthor.setEnabled(true);
}
} // end of class
| true
|
3680dff93d5255836e9eea08a9675298873aebba
|
Java
|
ohdoking/Dansoon
|
/app/src/main/java/com/ohdoking/dansoondiary/DansoonApplication.java
|
UTF-8
| 440
| 1.882813
| 2
|
[] |
no_license
|
package com.ohdoking.dansoondiary;
import android.app.Application;
import com.tsengvn.typekit.Typekit;
public class DansoonApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Typekit.getInstance()
.addNormal(Typekit.createFromAsset(this, "fonts/thejunggodic130.ttf"))
.addBold(Typekit.createFromAsset(this, "fonts/thejunggodic.ttf"));
}
}
| true
|
ba46becaaf024993c2c5f4272c9766b8051e97f6
|
Java
|
bigblue311/zhaile
|
/zhaile.app.biz/src/com/zhaile/biz/scheduler/task/DeleteInvalidCommentTask.java
|
UTF-8
| 773
| 2.171875
| 2
|
[] |
no_license
|
package com.zhaile.biz.scheduler.task;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import com.victor.framework.batch.thread.ScheduledTask;
import com.victor.framework.common.tools.LogTools;
import com.zhaile.dal.dao.CustomerCommentDAO;
public class DeleteInvalidCommentTask extends ScheduledTask{
private static LogTools log = new LogTools(RecycleCustomerFavTask.class);
public DeleteInvalidCommentTask() {
super(60L,TimeUnit.MINUTES);
}
@Autowired
private CustomerCommentDAO customerCommentDAO;
@Override
public void doWork() {
System.out.println("删除非法评论结果:"+customerCommentDAO.deleteInvalid());
log.error("删除非法评论结果:"+customerCommentDAO.deleteInvalid());
}
}
| true
|
9782eddd34796d27d05ae2fc3749e8668263e66d
|
Java
|
firak01/Projekt_Kernel02using_JAZVideoInternetArchive
|
/JAZVideoInternetArchive/src/use/via/client/DlgAboutVIA.java
|
UTF-8
| 2,130
| 2.5625
| 3
|
[] |
no_license
|
package use.via.client;
import java.awt.Frame;
import basic.zKernelUI.component.KernelJDialogExtendedZZZ;
import basic.zKernelUI.component.KernelJFrameCascadedZZZ;
import basic.zKernelUI.component.KernelJPanelCascadedZZZ;
import basic.zKernel.IKernelZZZ;
/**Dialogbox "Help/About". Wird aus dem Men� des Hauptframes gestartet.
* @author 0823
*
*/
public class DlgAboutVIA extends KernelJDialogExtendedZZZ {
/**
* @param owner
* @param bModal
* @param bSnappedToScreen
* @param panelCenter
*/
public DlgAboutVIA(IKernelZZZ objKernel, KernelJFrameCascadedZZZ frameOwner) {
super(objKernel, frameOwner, true, null); //true, d.h. modal, gehtl leider nur im Konstruktor zu �bergeben, weil JDialog diesen Parameter im Konstruktor braucht und Super(...) kann keinen Code beinhalten, der auf eigene Properties etc. zugreift.
}
public boolean isCentered(){
return true;
}
public boolean isJComponentSnappedToScreen(){
return true;
}
public boolean isButtonCancelAvailable(){
return false;
}
public boolean isButtonOKAvailable(){
return true;
}
public KernelJPanelCascadedZZZ getPanelButton(){
PanelDlgAboutButtonAlternativeVIA panelButton = new PanelDlgAboutButtonAlternativeVIA(this.getKernelObject(), this, true, false);//ok-button=true, cancel-button = false
return panelButton;
}
public KernelJPanelCascadedZZZ getPanelContent(){
PanelDlgAboutVIA panelContent = new PanelDlgAboutVIA(this.getKernelObject(), this);
return panelContent;
}
public String getText4ContentDefault(){
return "Das Panel f�r diese Dialogbox scheint zu fehlen, wenn Sie dies lesen k�nnen";
}
/* NICHT L�SCHEN: !!! Testweise die Methoden mit null �berschreiben. Es m�ssen nur die Default Einstellungen angezigt werden.
public KernelJPanelCascadedZZZ getPanelButton(){
return null;
}
public KernelJPanelCascadedZZZ getPanelContent(){
return null;
}
public String getText4ContentDefault(){
return "Das ist ein Test f�r den Default Text.(" + ReflectionZZZ.getMethodCurrentName() + ")";
}
*/
}//END Class
| true
|
f11ca22640dbf70993ba62ebeb1606733503b141
|
Java
|
GauravPandey123/MusicLibrary
|
/app/src/main/java/android/musicsigner/android/resources/SignUpRequest/ForgotPassword/GetOtpRequest.java
|
UTF-8
| 518
| 2.015625
| 2
|
[] |
no_license
|
package android.musicsigner.android.resources.SignUpRequest.ForgotPassword;
import android.musicsigner.android.web.BaseRequest;
/**
* Created by Editsoft on 12/27/16.
*/
public class GetOtpRequest extends BaseRequest {
/**
* email : jeevan@editsoft.in
*/
private String email;
@Override
public boolean isValid(String Scenario) {
return true;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
| true
|
2a26177928cb9ec4db13bed631c118329f58acdc
|
Java
|
markzha/future
|
/app/src/main/java/com/jnhyxx/html5/activity/web/PaymentActivity.java
|
UTF-8
| 3,994
| 1.90625
| 2
|
[] |
no_license
|
package com.jnhyxx.html5.activity.web;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebView;
import com.jnhyxx.html5.R;
import com.jnhyxx.html5.activity.WebViewActivity;
import com.jnhyxx.html5.domain.account.UserInfo;
import com.jnhyxx.html5.domain.local.LocalUser;
import com.jnhyxx.html5.net.API;
import com.jnhyxx.html5.utils.ToastUtil;
import com.johnz.kutils.Launcher;
import java.net.URISyntaxException;
public class PaymentActivity extends WebViewActivity {
//充值失败
public static final int REQ_PAYMENT_FAIL = 383;
/**
* 银行卡支付的标志
*/
public static final String BANK_CARD_PAYMENT = "BANK_CARD_PAYMENT";
private boolean mIsBankCardPayment;
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
Intent intent = getIntent();
mIsBankCardPayment = intent.getBooleanExtra(BANK_CARD_PAYMENT, false);
}
@Override
protected boolean onShouldOverrideUrlLoading(WebView view, String url) {
Log.d("recharge", "onShouldOverrideUrlLoading: " + url);
if (!TextUtils.isEmpty(url)) {
if (url.contains(API.Finance.getRechargeSuccessUrl())) {
if (mIsBankCardPayment) {
LocalUser.getUser().getUserInfo().setCardState(UserInfo.BANKCARD_STATUS_BOUND);
}
if (url.contains("result=1")) {
finish();
return true;
}
setResult(RESULT_OK);
finish();
return true;
} else if (TextUtils.equals(url, API.Finance.getRechargeFailUrl())) {
setResult(REQ_PAYMENT_FAIL);
finish();
return true;
} else if (url.equalsIgnoreCase(API.Finance.getMineWebPageUrl())) {
// setResult(RESULT_OK);
finish();
return true;
} else if (url.equalsIgnoreCase(API.Finance.getRechargeFailProfileUrl())) {
finish();
return true;
} else if (url.startsWith("alipays:") || url.contains("Intent;scheme=alipays")) {
openAlipay(view, url);
return true;
} else if (url.contains(API.Finance.getUserAggressPaymentConfirmPagePath())) {
setResult(RESULT_OK);
finish();
return true;
} else if (url.contains(API.Finance.getBankcardPaymentPagePartUrl())) {
getWebView().loadUrl(API.appendUrlNoHead(url));
return true;
} else if (url.contains(API.Finance.getBankcardPaymentErrorPartUrl())) {
getWebView().loadUrl(API.appendUrlNoHead(url));
return true;
} else if (url.equalsIgnoreCase(API.Finance.getBankcardPaymentAgreememtUrl())) {
Launcher.with(getActivity(), PaymentActivity.class)
.putExtra(PaymentActivity.EX_URL, API.appendUrlNoHead(url))
.putExtra(PaymentActivity.EX_TITLE, getString(R.string.payment_service_agreement))
.execute();
return true;
}
}
return super.onShouldOverrideUrlLoading(view, url);
}
@Override
public void onBackPressed() {
finish();
}
private void openAlipay(WebView webView, String url) {
try {
Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
ToastUtil.show(R.string.install_alipay_first);
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
| true
|
3da11d183512f07fbfd22403dc9361e8aecc38cf
|
Java
|
yhmatg/TerminalSmartBox
|
/app/src/main/java/com/android/terminalbox/uhf/UhfTag.java
|
UTF-8
| 1,154
| 2.3125
| 2
|
[] |
no_license
|
package com.android.terminalbox.uhf;
public class UhfTag {
public byte AntennaID;
private String epc;
private String tid;
private int rssi;
public UhfTag() {
}
public UhfTag(byte antennaID, String epc, String tid, int rssi) {
AntennaID = antennaID;
this.epc = epc;
this.tid = tid;
this.rssi = rssi;
}
public byte getAntennaID() {
return AntennaID;
}
public void setAntennaID(byte antennaID) {
AntennaID = antennaID;
}
public String getEpc() {
return epc;
}
public void setEpc(String epc) {
this.epc = epc;
}
public String getTid() {
return tid;
}
public void setTid(String tid) {
this.tid = tid;
}
public int getRssi() {
return rssi;
}
public void setRssi(int rssi) {
this.rssi = rssi;
}
@Override
public String toString() {
return "UhfTag{" +
"AntennaID=" + AntennaID +
", epc='" + epc + '\'' +
", tid='" + tid + '\'' +
", rssi=" + rssi +
'}';
}
}
| true
|
1da6081130f3f29c9eeed4c23960eec37cd90f67
|
Java
|
CCMForCCH/CCM
|
/cohoman/src/org/cohoman/model/business/EventManager.java
|
UTF-8
| 4,343
| 1.914063
| 2
|
[] |
no_license
|
package org.cohoman.model.business;
import java.util.Date;
import java.util.List;
import org.cohoman.model.business.MealSchedule.MealScheduleText;
import org.cohoman.model.dto.CohoEventDTO;
import org.cohoman.model.dto.MealEventDTO;
import org.cohoman.model.dto.PizzaEventDTO;
import org.cohoman.model.dto.PotluckEventDTO;
import org.cohoman.model.dto.PrivateEventDTO;
import org.cohoman.model.dto.SignupMealDTO;
import org.cohoman.model.dto.SignupPizzaDTO;
import org.cohoman.model.dto.SignupPotluckDTO;
import org.cohoman.model.integration.persistence.beans.CohoEvent;
import org.cohoman.model.integration.persistence.beans.MainCalendarEvent;
import org.cohoman.model.integration.persistence.beans.MealEvent;
import org.cohoman.model.integration.persistence.beans.PizzaEvent;
import org.cohoman.model.integration.persistence.beans.PotluckEvent;
import org.cohoman.model.integration.persistence.beans.PrivateEvent;
import org.cohoman.model.integration.persistence.beans.SpaceBean;
import org.cohoman.view.controller.CohomanException;
import org.cohoman.view.controller.utils.CalendarUtils.MealDate;
public interface EventManager {
public void createMealEvent(MealEventDTO mealEventDTO, String leaderFullname)
throws CohomanException;
// Meal events
public void editMealEvent(MealEvent mealEvent) throws CohomanException;
public void deleteMealEvent(MealEvent mealEvent);
public List<MealDate> getMealDaysForPeriod();
public List<MealEvent> getCurrentMealEvents();
public List<MealEvent> getAllMealEvents();
public MealEvent getMealEvent(Long eventId);
// Pizza Events
public void createPizzaEvent(PizzaEventDTO pizzaEventDTO, String leaderFullname)
throws CohomanException;
public void editPizzaEvent(PizzaEvent pizzaEvent) throws CohomanException;
public void deletePizzaEvent(PizzaEvent pizzaEvent);
public List<MealDate> getPizzaDaysForPeriod();
public List<PizzaEvent> getCurrentPizzaEvents();
public PizzaEvent getPizzaEvent(Long eventId);
// Potluck Events
public void createPotluckEvent(PotluckEventDTO potluckEventDTO, String leaderFullname)
throws CohomanException;
public void editPotluckEvent(PotluckEvent potluckEvent) throws CohomanException;
public void deletePotluckEvent(PotluckEvent potluckEvent);
public List<MealDate> getPotluckDaysForPeriod();
public List<PotluckEvent> getCurrentPotluckEvents();
public PotluckEvent getPotluckEvent(Long eventId);
// Coho Events
public void createCohoEvent(CohoEventDTO cohoEventDTO)
throws CohomanException;
public void editCohoEvent(CohoEvent cohoEvent) throws CohomanException;
public void deleteCohoEvent(CohoEvent cohoEvent);
public List<CohoEvent> getCurrentCohoEvents();
public CohoEvent getCohoEvent(Long eventId);
// Private Events
public void createPrivateEvent(PrivateEventDTO privateEventDTO)
throws CohomanException;
public void editPrivateEvent(PrivateEvent privateEvent)
throws CohomanException;
public void deletePrivateEvent(Long privateEventId);
public List<PrivateEvent> getMyPrivateEvents();
public List<PrivateEvent> getUpcomingPrivateEvents();
public List<PrivateEvent> getPendingPrivateEvents();
public List<PrivateEvent> getAllPrivateEvents();
public PrivateEvent getPrivateEvent(Long eventId);
// meal sign-ups
public void signupForMeal(SignupMealDTO dto) throws CohomanException;
public List<SignupMealDTO> getAllMealSignups(Long eventid) throws CohomanException;
public void deleteSignupForMeal(SignupMealDTO dto) throws CohomanException;
// pizza/potluck sign-ups
public void signupForPizza(SignupPizzaDTO dto) throws CohomanException;
public List<SignupPizzaDTO> getAllPizzaSignups(Long eventid) throws CohomanException;
public void deleteSignupForPizza(SignupPizzaDTO dto) throws CohomanException;
// potluck sign-ups
public void signupForPotluck(SignupPotluckDTO dto) throws CohomanException;
public List<SignupPotluckDTO> getAllPotluckSignups(Long eventid) throws CohomanException;
public void deleteSignupForPotluck(SignupPotluckDTO dto) throws CohomanException;
// Other special Getters
public List<List<MealScheduleText>> getCurrentMealScheduleRows();
public List<MainCalendarEvent> getMonthsCalendarEvents(Date theMonth);
public List<MainCalendarEvent> getMainCalendarEventsForDay(Date dateOfDay);
public List<SpaceBean> getAllSpaces();
}
| true
|
ec002e7d684a2185d6206b5b4a01b55e4f8a0e36
|
Java
|
zangliguang/DawnLightApp_Test
|
/DawnLightApp/app/src/main/java/com/liguang/app/activity/MainActivity.java
|
UTF-8
| 5,736
| 1.890625
| 2
|
[] |
no_license
|
package com.liguang.app.activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.liguang.app.R;
import com.liguang.app.adapter.YoutubeVideoPageAdapter;
import com.liguang.app.fragment.YoutubeVideoFragment;
import com.liguang.app.po.youtube.YoutubeVideoCategoryItem;
import com.liguang.app.utils.DemoData;
import com.liguang.library.RecyclerTabLayout;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,YoutubeVideoFragment.OnFragmentInteractionListener {
@InjectView(R.id.recycler_tab_layout)
RecyclerTabLayout recyclerTabLayout;
@InjectView(R.id.view_pager)
ViewPager viewPager;
@InjectView(R.id.nav_view)
NavigationView navView;
@InjectView(R.id.drawer_layout)
DrawerLayout drawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setElevation(0);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
List<YoutubeVideoCategoryItem> youtubeVideoCategoryItems = DemoData.loadDemoYoutubeVideoCategoryItems(this);
List<Fragment> mListFragment = new ArrayList<>();
for (int i = 0; i < youtubeVideoCategoryItems.size(); i++) {
mListFragment.add(new YoutubeVideoFragment().newInstance(youtubeVideoCategoryItems.get(i).id,youtubeVideoCategoryItems.get(i).snippet.getTitle()));
}
YoutubeVideoPageAdapter youtubeVideoPageAdapter = new YoutubeVideoPageAdapter(getSupportFragmentManager(), mListFragment);
viewPager.setOffscreenPageLimit(10);
viewPager.setAdapter(youtubeVideoPageAdapter);
recyclerTabLayout.setUpWithViewPager(viewPager);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Toast.makeText(this, "toast被点击", Toast.LENGTH_SHORT);
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
if (id == android.R.id.home) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)
) {
drawerLayout.closeDrawers();
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camara) {
Intent intent = new Intent(this, ItemListActivity.class);
startActivity(intent);
// Handle the camera action
} else if (id == R.id.nav_gallery) {
Intent intent = new Intent(this, ScrollingActivity.class);
startActivity(intent);
} else if (id == R.id.nav_slideshow) {
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
} else if (id == R.id.nav_manage) {
Intent intent = new Intent(this, FullscreenActivity.class);
startActivity(intent);
} else if (id == R.id.nav_share) {
Intent intent = new Intent(this, ScrollingActivity.class);
startActivity(intent);
} else if (id == R.id.nav_send) {
Intent intent = new Intent(this, ScrollingActivity.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onFragmentInteraction(Uri uri) {
}
}
| true
|
7841f620e7eb548b8da2032afe3defa1fdfb2e1a
|
Java
|
lemsviat/lemstudy
|
/src/main/java/com/lemsviat/javacore/chapter09/MyIFImpl.java
|
UTF-8
| 163
| 2.390625
| 2
|
[] |
no_license
|
package main.java.com.lemsviat.javacore.chapter09;
public class MyIFImpl implements MyIF {
@Override
public int getNumber() {
return 100;
}
}
| true
|
274afb48eb75738218a6a198fd01a3bc1b365996
|
Java
|
rinaldo-santana/emissor-fiscal-api
|
/src/main/java/com/everest/emissorfiscal/api/entities/Cidade.java
|
UTF-8
| 1,232
| 2.203125
| 2
|
[
"MIT"
] |
permissive
|
package com.everest.emissorfiscal.api.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.Table;
import com.everest.emissorfiscal.api.enums.Pais;
import com.everest.emissorfiscal.api.enums.UF;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Entity @Table(name = "cidades")
@Getter @Setter @ToString @EqualsAndHashCode
@NoArgsConstructor(access = AccessLevel.PUBLIC)
// @RequiredArgsConstructor(access = AccessLevel.PUBLIC)
@DynamicUpdate @DynamicInsert
public class Cidade implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "cidade_codigo")
private String codigoIbge;
@Column(name = "cidade_nome")
private String nome;
@Enumerated(EnumType.STRING)
@Column(name = "cidade_uf")
private UF uf;
@Enumerated(EnumType.STRING)
@Column(name = "cidade_pais")
private Pais pais;
}
| true
|
b514b8bf58c113bfbed8f3eb32f81074a64eca5c
|
Java
|
puga1chev/JMCrud1
|
/src/main/java/jmCrud/servlet/DeleteServlet.java
|
UTF-8
| 791
| 2.359375
| 2
|
[] |
no_license
|
package jmCrud.servlet;
import jmCrud.service.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/admin/delete")
public class DeleteServlet extends HttpServlet {
private ObjectService userService = new UserServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String deleteUser = req.getParameter("id");
if (deleteUser != null) {
userService.delete(Long.parseLong(deleteUser));
}
resp.sendRedirect(req.getContextPath() + "/admin");
}
}
| true
|
6fa09668016278791154ae983c8247cfff639386
|
Java
|
Jim-Robbins/xyz-reader
|
/XYZReader/src/main/java/com/example/xyzreader/Utils.java
|
UTF-8
| 1,395
| 2.5625
| 3
|
[] |
no_license
|
package com.example.xyzreader;
import android.text.format.DateUtils;
import android.util.Log;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* Created by jim on 6/12/17.
*/
public class Utils {
private static final String TAG = Utils.class.toString();;
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss");
// Use default locale format
private static SimpleDateFormat outputFormat = new SimpleDateFormat();
// Most time functions can only handle 1902 - 2037
private static GregorianCalendar START_OF_EPOCH = new GregorianCalendar(2,1,1);
public static String getFormattedDate(String date) {
Date publishedDate = parsePublishedDate(date);
return (!publishedDate.before(START_OF_EPOCH.getTime())) ?
DateUtils.getRelativeTimeSpanString(publishedDate.getTime(), System.currentTimeMillis(), DateUtils.HOUR_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL).toString()
: outputFormat.format(publishedDate);
}
private static Date parsePublishedDate(String date) {
try {
return dateFormat.parse(date);
} catch (ParseException ex) {
Log.e(TAG, ex.getMessage());
Log.i(TAG, "passing today's date");
return new Date();
}
}
}
| true
|
68ab29c864e9ea11815c87b2fdd74fe79535b904
|
Java
|
Major-Issue/majorIssue
|
/app/src/main/java/majorissue/com/gravity/screens/SettingsScreen.java
|
UTF-8
| 4,845
| 2.375
| 2
|
[] |
no_license
|
package majorissue.com.gravity.screens;
import com.majorissue.game.R;
import java.util.List;
import majorissue.com.framework.Game;
import majorissue.com.framework.Graphics;
import majorissue.com.framework.Input.TouchEvent;
import majorissue.com.gravity.GravityGame;
import majorissue.com.gravity.util.Assets;
import majorissue.com.gravity.util.Settings;
public class SettingsScreen extends MenuScreen {
private String[][] settingsTouchAreas = null;
private String touchedSettingsEntry = null;
public SettingsScreen(Game game) {
super(game);
}
@Override
public void update(float deltaTime) {
if(settingsTouchAreas == null) return;
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if (event.type == TouchEvent.TOUCH_DOWN) {
checkTouchDown(event);
}
if (event.type == TouchEvent.TOUCH_UP) {
touchedSettingsEntry = null;
checkTouchUp(event);
}
}
}
private void checkTouchDown(TouchEvent event) {
for(int i = 0; i < settingsTouchAreas.length; i++){
try {
if(inBounds(event, settingsTouchAreas, i)) {
touchedSettingsEntry = settingsTouchAreas[i][0];
playSound(touchedSettingsEntry);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void checkTouchUp(TouchEvent event) {
for(int i = 0; i < settingsTouchAreas.length; i++){
try {
if(inBounds(event, settingsTouchAreas, i)) {
handleInput(settingsTouchAreas[i][0]);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void present(float deltaTime) {
Graphics g = game.getGraphics();
g.drawPixmap(Assets.main_menu, 0, 0);
settingsTouchAreas = drawMenu(new String[]{ ((GravityGame)game).getResources().getString(R.string.music),
((GravityGame)game).getResources().getString(R.string.sound),
((GravityGame)game).getResources().getString(R.string.intro),
((GravityGame)game).getResources().getString(R.string.autoretry),
((GravityGame)game).getResources().getString(R.string.aidline),
((GravityGame)game).getResources().getString(R.string.previous),
((GravityGame)game).getResources().getString(R.string.vibration),
((GravityGame)game).getResources().getString(R.string.back)
}, touchedSettingsEntry);
}
@Override
public void pause() {
Settings.save(game.getFileIO());
super.pause();
}
private void handleInput(String entry) {
if(entry.equals(((GravityGame)game).getResources().getString(R.string.music))) {
Settings.toggleMusic();
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.sound))) {
Settings.toggleSound();
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.intro))) {
Settings.toggleIntro();
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.autoretry))) {
Settings.toggleAutoRetry();
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.aidline))) {
Settings.toggleAidline();
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.previous))) {
Settings.togglePrevious();
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.vibration))) {
Settings.toggleVibration();
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.back))) {
Settings.save(game.getFileIO());
game.setScreen(new MainMenuScreen(game));
}
}
private void playSound(String entry) {
if(entry == null || !Settings.soundEnabled) {
return;
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.music))) {
Assets.menu_click.play(1);
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.sound))) {
Assets.menu_click.play(1);
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.intro))) {
Assets.menu_click.play(1);
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.autoretry))) {
Assets.menu_click.play(1);
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.aidline))) {
Assets.menu_click.play(1);
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.previous))) {
Assets.menu_click.play(1);
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.vibration))) {
Assets.menu_click.play(1);
}
if(entry.equals(((GravityGame)game).getResources().getString(R.string.back))) {
Assets.menu_click.play(1);
}
}
}
| true
|
9579fab8dd7961f030bbd8b1365dcf1fd013d1fe
|
Java
|
PrasadPatharkar/FirstGitRepo
|
/src/my/udemy/exercise/PracticeDynamicValues.java
|
UTF-8
| 1,258
| 2.484375
| 2
|
[] |
no_license
|
package my.udemy.exercise;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class PracticeDynamicValues {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C:\\Software\\chromedriver_win32\\chromedriver.exe");
WebDriver driver;
driver = new ChromeDriver();
driver.get("http://qaclickacademy.com/practice.php");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("checkBoxOption2")).click();
String strCheck = driver.findElement(By.xpath("//label[@for='benz']")).getText();
Select dropEx = new Select(driver.findElement(By.xpath("//select[@id='dropdown-class-example']")));
dropEx.selectByVisibleText(strCheck);
driver.findElement(By.xpath("//input[@id='name']")).sendKeys(strCheck);
driver.findElement(By.xpath("//input[@id='alertbtn']")).click();
String alertText = driver.switchTo().alert().getText();
if (alertText.contains(strCheck)) {
System.out.println("Pass");
}
// driver.close();
}
}
| true
|
c16bd5d009600dfdf926019829cf2f604645f29d
|
Java
|
Zanobos/shareride-android
|
/app/src/main/java/com/zano/shareride/adapters/ExampleAdapter.java
|
UTF-8
| 1,233
| 2.28125
| 2
|
[] |
no_license
|
package com.zano.shareride.adapters;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.zano.shareride.R;
import java.util.Map;
import butterknife.BindView;
/**
* Created by Zano on 07/06/2017, 18:47.
*/
public class ExampleAdapter extends FirebaseRecyclerAdapter<ExampleAdapter.ViewHolder, String> {
public ExampleAdapter(Context context, int listItemLayoutId, Map<String, String> data) {
super(context, listItemLayoutId, data, "prova/examples",String.class);
}
@Override
protected ViewHolder createViewHolder(View itemView) {
return new ViewHolder(itemView);
}
@Override
protected void onBindViewHolder(ViewHolder holder, String data) {
holder.textViewExample.setText(data);
}
@Override
protected String setTag() {
return "ExampleAdapter";
}
@Override
protected void updatedData(String value) {
Log.d(TAG,"Changed: " + value);
}
class ViewHolder extends BaseRecyclerAdapter.ViewHolder {
@BindView(R.id.my_textview_example) TextView textViewExample;
ViewHolder(View itemView) {
super(itemView);
}
}
}
| true
|
675f04cf8961f0237f7df5fc2797863b9ad61b48
|
Java
|
chris346/Java
|
/3_ifElseStatements.java
|
UTF-8
| 280
| 3.453125
| 3
|
[] |
no_license
|
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 5;
if(x>y){
System.out.println("x is bigger than y");
}else if(x==y){
System.out.println("x is equal to y");
}else {
System.out.println("x is less than y");
}
}
}
| true
|
07019d4468b29e1982bbd04bc137fba41173b9f8
|
Java
|
Felipe3003p/Etec-ct
|
/exerc4.java
|
ISO-8859-1
| 973
| 3.640625
| 4
|
[] |
no_license
|
import java.util.Scanner;
public class exerc4 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a[],b=0,i;
a = new int [10];
//Entrada de dados
for(i=0;i<10;i++) {
System.out.println("Entre com o "+ (i+1)+" valor:");
a[i]=sc.nextInt();
b = b + a[i];
}
//Imprimir sada para o usurio
System.out.print("Os dez valores = " );
for(i=0;i<10;i++) {
System.out.print(a[i]+" ");
}
double res = b / 10;
System.out.println();
System.out.println();
System.out.println(" Frmula: ");
System.out.println();
System.out.println(" " + b + " (soma dos valores)");
System.out.println("-------------------");
System.out.println(" 10 (total de valores)");
System.out.println();
System.out.print(" = " + res + " resultado");
sc.close();
}
}
| true
|
b82819a6fffac47100c300b600210e0fd0065d16
|
Java
|
huyang2100/cool
|
/app/src/main/java/com/example/cool/activity/InstallApkActivity.java
|
UTF-8
| 2,214
| 1.945313
| 2
|
[] |
no_license
|
package com.example.cool.activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import com.example.cool.BuildConfig;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.os.EnvironmentCompat;
import android.os.Environment;
import android.view.View;
import android.widget.Toast;
import com.example.cool.R;
import java.io.File;
import java.net.URI;
public class InstallApkActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_install_apk);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "package: "+InstallApkActivity.this.getPackageName(), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
Intent i = new Intent(Intent.ACTION_VIEW);
String apkPath = "/mnt/sdcard/Download/scheduleBj20190820.apk";
Uri apkUri;
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
apkUri = Uri.parse("file://" + apkPath);
} else {
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
File file = new File(apkPath);
apkUri = FileProvider.getUriForFile(InstallApkActivity.this, BuildConfig.APPLICATION_ID + ".provider", file);
}
i.setDataAndType(apkUri, "application/vnd.android.package-archive");
startActivity(i);
}
});
}
}
| true
|
8bdab4922b804e61abdbb56af7f853fbde93499f
|
Java
|
eothmal/example
|
/generics/src/com/mycompany/parameters/h/convention/Main.java
|
UTF-8
| 644
| 3.125
| 3
|
[] |
no_license
|
package com.mycompany.parameters.h.convention;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
Employee<Integer> employee1 = new Employee<>(123, 1000, 100);
System.out.println(employee1);
Employee<BigInteger> employee2 = new Employee<>(
BigInteger.valueOf(123456),
BigInteger.valueOf(1234567),
BigInteger.valueOf(123456) );
System.out.println(employee2);
Employee<Double> employee3 = new Employee<>(1230000.0, 100000.34, 10000.34);
System.out.println(employee3);
}
}
| true
|
e44b3674be979ff174cd5d408e3017f0c769b07e
|
Java
|
julianhyde/pentaho-aggdesigner
|
/pentaho-aggdesigner-core/src/main/java/org/pentaho/aggdes/model/mondrian/MondrianMeasure.java
|
UTF-8
| 2,795
| 1.742188
| 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.
*
*
* Copyright 2006 - 2013 Pentaho Corporation. All rights reserved.
*/
package org.pentaho.aggdes.model.mondrian;
import java.util.List;
import mondrian.rolap.RolapAggregator;
import mondrian.rolap.RolapStar;
import org.pentaho.aggdes.Main;
import org.pentaho.aggdes.model.Attribute;
import org.pentaho.aggdes.model.Dialect;
import org.pentaho.aggdes.model.Measure;
public class MondrianMeasure implements Measure {
private final MondrianTable table;
private final RolapStar.Measure measure;
public MondrianMeasure(MondrianTable table, RolapStar.Measure measure) {
this.table = table;
this.measure = measure;
}
public RolapStar.Measure getRolapStarMeasure() {
return measure;
}
public boolean isDistinct() {
return measure.getAggregator().isDistinct();
}
public String getLabel() {
return table.getLabel() + "." + measure.getName();
}
public MondrianTable getTable() {
return table;
}
public double estimateSpace() {
return MondrianSchemaLoader.estimateSpaceForColumn(measure);
}
public String getCandidateColumnName() {
return Main.depunctify(getLabel());
}
public String getDatatype(Dialect dialect) {
final RolapAggregator aggregator = measure.getAggregator();
String aggregatorName = aggregator.getName().toUpperCase();
final mondrian.spi.Dialect mondrianDialect =
((MondrianDialect) dialect).getMondrianDialect();
if (aggregator == RolapAggregator.Min
|| aggregator == RolapAggregator.Max) {
return measure.getDatatypeString(mondrianDialect);
} else if (aggregator == RolapAggregator.Count
|| aggregator == RolapAggregator.DistinctCount) {
return dialect.getIntegerTypeString();
} else if (aggregator == RolapAggregator.Sum
|| aggregator == RolapAggregator.Avg) {
return dialect.getDoubleTypeString();
} else {
throw new RuntimeException(
"Unknown aggregator " + aggregatorName);
}
}
public List<Attribute> getAncestorAttributes() {
// measures contain no ancestor attributes
return null;
}
}
| true
|
0efef2c70be9a8bc05aab2b72d0a69391e534e04
|
Java
|
Indivikar/WacherTreeView
|
/src/app/TreeViewWatchService/PathTreeCell.java
|
ISO-8859-1
| 13,788
| 2.09375
| 2
|
[
"BSD-2-Clause"
] |
permissive
|
package app.TreeViewWatchService;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import app.StartWacherDemo;
import app.TreeViewWatchService.contextMenu.CellContextMenu;
import app.controller.CTree;
import app.interfaces.ILockDir;
import app.interfaces.IOpenFile;
import app.interfaces.ISuffix;
import app.interfaces.ISystemIcon;
import javafx.application.Platform;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.SelectionModel;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
public class PathTreeCell extends TreeCell<PathItem> implements ISuffix, ISystemIcon, IOpenFile, ILockDir{
private Stage primaryStage;
private CTree cTree;
private CellContextMenu cellContextMenu;
private TextField textField;
private Path editingPath;
private StringProperty messageProp;
// private ContextMenu dirMenu = new ContextMenu();
private ContextMenu fileMenu;
private ExecutorService service = Executors.newFixedThreadPool(1);
private ObservableList<String> listAllLockedFiles = FXCollections.observableArrayList();
private int index;
private TreeItem<PathItem> levelOneItem;
private DragNDropInternal dragNDropInternal;
public PathTreeCell(CTree cTree, Stage primaryStage) {
// System.out.println("Load -> PathTreeCell");
this.cTree = cTree;
this.fileMenu = new CellContextMenu(this, primaryStage, cTree, listAllLockedFiles);
this.dragNDropInternal = new DragNDropInternal(primaryStage, service, this);
setListenerRefreshTree();
}
public void selectCell() {
System.err.println("CellIndex: " + getIndex());
// System.err.println("CellName: " + getTreeItem().getValue().getPath());
getTreeView().getSelectionModel().clearSelection();
getTreeView().getSelectionModel().select(getIndex());
}
@Override
protected void updateItem(PathItem item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
setContextMenu(null);
} else {
// getTreeItem().getValue().setRefreshTree(cTree.getPropDisBoolOpen().get());
setLevelOneItem(getTreeItem());
item.setRow(getIndex());
item.setLevel(getTreeView().getTreeItemLevel(getTreeItem()));
setText(getString() + " (" + getIndex() + " - " + item.getLevel() + " -> " + item.isLocked() + ")");
setContextMenu(fileMenu);
setListenerLockedContextMenu(getTreeItem());
// setListenerRefreshTree();
setStartPropertiesContextMenu(item);
setGraphic(getImage(this.getTreeItem()));
mouseOver(this);
mouseClick(this);
// setListenerRefreshTree();
// this.setOnDragDetected(dragNDropInternal.eventDragDetected);
// this.setOnDragOver(dragNDropInternal.eventDragOver);
// this.setOnDragEntered(dragNDropInternal.eventDragEntered);
// this.setOnDragDropped(dragNDropInternal.eventDragDropped);
// this.setOnDragDone(dragNDropInternal.eventDragDone);
// if (item.getPath().toString().contains("A0")) {
// System.out.println(item.toString2());
// }
}
}
private void setListenerRefreshTree() {
EventHandler<MouseEvent> mouseMoved = event -> {
if (this.getOnDragDetected() == null) {
System.out.println(" Drag N Drop -> set Mouse Moved");
this.setOnDragDetected(dragNDropInternal.eventDragDetected);
this.setOnDragOver(dragNDropInternal.eventDragOver);
this.setOnDragEntered(dragNDropInternal.eventDragEntered);
this.setOnDragExited(dragNDropInternal.eventDragExited);
this.setOnDragDropped(dragNDropInternal.eventDragDropped);
this.setOnDragDone(dragNDropInternal.eventDragDone);
}
};
// cTree.getTree().getRoot().getValue().getIsRefreshTreeProp().addListener((var, oldVar, newVar) -> {
cTree.getPropBoolRefresh().addListener((var, oldVar, newVar) -> {
// System.err.println("Root Item Refresh Tree 1 " + cTree.getPropDisBoolOpen().get());
if (newVar) {
// Context Menu deaktivieren, bei refresh Tree
if (!cTree.getPropDisBoolNewFile().get()) {
cTree.setMenuItemsReload(newVar);
}
// Drag N Drop blocken, bei refresh Tree
if (this.getOnDragDetected() != null) {
// System.out.println(" Drag N Drop -> null");
cTree.getTree().removeEventFilter(MouseEvent.MOUSE_MOVED, mouseMoved);
this.setOnDragDetected(null);
this.setOnDragOver(null);
this.setOnDragEntered(null);
this.setOnDragExited(null);
this.setOnDragDropped(null);
this.setOnDragDone(null);
}
} else {
// System.out.println(" Drag N Drop -> set");
// Context Menu wird nach refresh Tree wieder neu geladen, also muss keine Aktion zum aktivieren ausgefhrt werden
// Drag N Drop wieder frei geben, nach refresh Tree
cTree.getTree().addEventHandler(MouseEvent.MOUSE_MOVED, mouseMoved);
}
});
}
private void setListenerLockedContextMenu(TreeItem<PathItem> treeItem) {
PathItem item = treeItem.getValue();
boolean isLocked = item.isLocked();
if (getTreeView().getTreeItemLevel(getTreeItem()) == 1) {
item.getIsLockedProp().addListener((var, oldVar, newVar) -> {
item.setLocked(newVar);
Platform.runLater(() -> {
// Image und ContextMenu wechsel
setGraphic(getImage(this.getTreeItem()));
});
});
}
if (getTreeView().getTreeItemLevel(getTreeItem()) > 1) {
levelOneItem.getValue().getIsLockedProp().addListener((var, oldVar, newVar) -> {
// System.out.println(item + " -> " + newVar);
item.setLocked(newVar);
Platform.runLater(() -> {
// Image und ContextMenu wechsel
setGraphic(getImage(this.getTreeItem()));
});
});
}
}
private void setStartPropertiesContextMenu(PathItem item) {
if (getTreeView().getTreeItemLevel(getTreeItem()) == 0) {
System.out.println("setRootMenuItems()");
cellContextMenu.setRootMenuItems();
// setGraphic(getImage(this.getTreeItem()));
} else {
if (item.isDirectoryItem()) {
cellContextMenu.setMenuItemsDir();
} else {
cellContextMenu.setMenuItemsFile();
}
}
if (getTreeView().getTreeItemLevel(getTreeItem()) == 1) {
boolean b = isDirLocked(getTreeView().getRoot(), getTreeItem().getValue().getPath().toFile());
if (item.isDirectoryItem()) {
cellContextMenu.setLockedDir(b);
} else {
cellContextMenu.setLockedFile(b);
}
// setGraphic(getImage(this.getTreeItem()));
}
if (getTreeView().getTreeItemLevel(getTreeItem()) > 1) {
item.setLocked(levelOneItem.getValue().isLocked());
// setGraphic(getImage(this.getTreeItem()));
}
}
public void setLevelOneItem(TreeItem<PathItem> treeItem) {
// set Root-Ordner oder LevelOne-Ordner -> um spter diese Ordner zu Locken
if (getTreeView().getTreeItemLevel(getTreeItem()) <= 1) {
getTreeItem().getValue().setLevelOneItem(treeItem);
}
if (getTreeView().getTreeItemLevel(getTreeItem()) > 1) {
getLevelOneItem(getTreeItem());
getTreeItem().getValue().setLevelOneItem(levelOneItem);
}
}
private void getLevelOneItem(TreeItem<PathItem> treeItem) {
TreeItem<PathItem> parentItem = treeItem.getParent();
if (getTreeView().getTreeItemLevel(parentItem) == 1) {
// System.out.println("getLevelOneItem(): " + parentItem);
levelOneItem = parentItem;
treeItem.getValue().setLevelOneItem(levelOneItem);
return;
} else {
getLevelOneItem(parentItem);
}
}
private void mouseClick(PathTreeCell pathTreeCell) {
pathTreeCell.setOnMouseClicked(event -> {
File file = pathTreeCell.getTreeItem().getValue().getPath().toFile();
if (event.getClickCount() == 2 && !pathTreeCell.isEmpty() && !file.isDirectory()) {
open(file);
}
});
}
private void mouseOver(PathTreeCell pathTreeCell) {
pathTreeCell.setOnDragEntered(event -> {
pathTreeCell.setStyle(
"-fx-background: -fx-selection-bar-non-focused;\r\n" +
"-fx-table-cell-border-color: derive(-fx-selection-bar-non-focused, 20%);");
});
pathTreeCell.setOnDragExited(event -> {
pathTreeCell.setStyle("");
});
}
public ImageView getImage(TreeItem<PathItem> treeItem) {
ImageView imageView = new ImageView();
if (treeItem != null) {
File file = treeItem
.getValue()
.getPath()
.toFile();
if (file.isDirectory()) {
imageView.setImage(getDirectoryItem(treeItem));
} else {
if (file.exists()) {
setContextMenuFileProperties(treeItem);
imageView.setImage(ISystemIcon.getSystemImage(file));
} else {
String itemSuffix = ISuffix.getSuffix(file.getName());
if (!itemSuffix.equals("")) {
for (Entry<String, Image> item : CTree.getSuffixIcon().entrySet()) {
if (item.getKey().equalsIgnoreCase(itemSuffix)) {
imageView.setImage(item.getValue());
return imageView;
}
}
// Default File-Icon
setContextMenuFileProperties(treeItem);
imageView.setImage(getDefaultDocumentIcon());
} else {
imageView.setImage(getDirectoryItem(treeItem));
}
}
}
}
return imageView;
}
private Image getDirectoryItem(TreeItem<PathItem> treeItem) {
boolean isLocked = treeItem.getValue().isLocked();
if (treeItem.isExpanded() && treeItem.getChildren().size() != 0) {
if (isLocked) {
cellContextMenu.setLockedDir(true);
return getOpenKeyIcon();
} else {
cellContextMenu.setLockedDir(false);
return getOpenIcon();
}
} else {
if (isLocked) {
cellContextMenu.setLockedDir(true);
return getCloseKeyIcon();
} else {
cellContextMenu.setLockedDir(false);
return getCloseIcon();
}
}
}
private void setContextMenuFileProperties(TreeItem<PathItem> treeItem) {
boolean isLocked = treeItem.getValue().isLocked();
System.out.println(treeItem + " -> " + isLocked);
if (treeItem.isExpanded()) {
if (isLocked) {
cellContextMenu.setLockedFile(true);
} else {
cellContextMenu.setLockedFile(false);
}
} else {
if (isLocked) {
cellContextMenu.setLockedFile(true);
} else {
cellContextMenu.setLockedFile(false);
}
}
}
private Image getOpenIcon() {
return new Image(StartWacherDemo.class.getResourceAsStream("view/images/folderOpen.png"));
}
private Image getCloseIcon() {
return new Image(StartWacherDemo.class.getResourceAsStream("view/images/folderClose.png"));
}
private Image getOpenKeyIcon() {
return new Image(StartWacherDemo.class.getResourceAsStream("view/images/folderOpen_key.png"));
}
private Image getCloseKeyIcon() {
return new Image(StartWacherDemo.class.getResourceAsStream("view/images/folderClose_key.png"));
}
private Image getDefaultDocumentIcon() {
return new Image(StartWacherDemo.class.getResourceAsStream("view/images/document.png"));
}
// @Override
// public void startEdit() {
// super.startEdit();
// if (textField == null){
// createTextField();
// }
// setText(null);
// setGraphic(textField);
// textField.selectAll();
// if (getItem() == null) {
// editingPath = null;
// } else {
// editingPath =getItem().getPath();
// }
// }
@Override
public void commitEdit(PathItem pathItem) {
// rename the file or directory
if (editingPath != null) {
try {
Files.move(editingPath, pathItem.getPath());
} catch (IOException ex) {
cancelEdit();
messageProp.setValue(String.format("Renaming %s filed", editingPath.getFileName()));
}
}
super.commitEdit(pathItem);
}
@Override
public void cancelEdit() {
super.cancelEdit();
setText(getString());
setGraphic(null);
}
private String getString() {
return getItem().toString();
}
// private void createTextField() {
// textField = new TextField(getString());
// textField.setOnKeyReleased((KeyEvent t) -> {
// if (t.getCode() == KeyCode.ENTER){
// Path path = Paths.get(getItem().getPath().getParent().toAbsolutePath().toString(), textField.getText());
// commitEdit(new PathItem(path));
// } else if (t.getCode() == KeyCode.ESCAPE) {
// cancelEdit();
// }
// });
// }
// Getter
public CTree getcTree() {return cTree;}
public CellContextMenu getCellContextMenu() {return cellContextMenu;}
public void set(CellContextMenu cellContextMenu) {
this.cellContextMenu = cellContextMenu;
}
}
| true
|
04f4a639094c03e7d0d1c353234382c331d6821c
|
Java
|
Harsh0786/FullStack-DesignPatterns
|
/src/com/behavioral/designpattern/memento/MementoDemoPattern.java
|
UTF-8
| 215
| 2.125
| 2
|
[] |
no_license
|
package com.behavioral.designpattern.memento;
public class MementoDemoPattern {
public static void main(String[] args) {
Originator originator = new Originator();
CareTaker careTaker = new CareTaker();
}
}
| true
|
75615d229c8055ada5fdef157d1ef96454672bf2
|
Java
|
jdmr/mateo
|
/src/main/java/mx/edu/um/mateo/contabilidad/facturas/web/FacturasController.java
|
UTF-8
| 802
| 1.820313
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mx.edu.um.mateo.contabilidad.facturas.web;
import mx.edu.um.mateo.inscripciones.web.*;
import mx.edu.um.mateo.general.web.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*
* @author semdariobarbaamaya
*
*/
@Controller
@RequestMapping("/factura")
public class FacturasController extends BaseController {
private static final Logger log = LoggerFactory
.getLogger(FacturasController.class);
@RequestMapping
public String index() {
log.debug("Mostrando indice de facturas");
return "factura/index";
}
}
| true
|
d95d8b14975571bf096f0aa24732644e2785c491
|
Java
|
KorallTheCoral/MatchlockGuns-Mod
|
/java/com/korallkarlsson/matchlockweapons/items/NewReloadGunWheellock.java
|
UTF-8
| 12,710
| 1.695313
| 2
|
[] |
no_license
|
package com.korallkarlsson.matchlockweapons.items;
import java.util.List;
import com.korallkarlsson.matchlockweapons.init.ModItems;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.init.SoundEvents;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
public class NewReloadGunWheellock extends NewReloadGun {
int minSpring = 5;
public NewReloadGunWheellock(String name, float inAccuracy, float damage, int maxShots, int cooldown,
double kickback, double failRate, int reloadCooldown, boolean useRamRod, Item ammoItem, int gunPowderAmount,
Item cartridgeItem, int springAmount, int durabillity) {
super(name, inAccuracy, damage, maxShots, cooldown, kickback, failRate, reloadCooldown, useRamRod, ammoItem,
gunPowderAmount, cartridgeItem, durabillity);
this.minSpring = springAmount;
}
public NewReloadGunWheellock(String name, float inAccuracy, float damage, int maxShots, int cooldown,
double kickback, double failRate, int reloadCooldown, boolean useRamRod, Item ammoItem, int gunPowderAmount,
Item cartridgeItem, int springAmount, boolean canDual, int durabillity) {
super(name, inAccuracy, damage, maxShots, cooldown, kickback, failRate, reloadCooldown, useRamRod, ammoItem,
gunPowderAmount, cartridgeItem, canDual, durabillity);
this.minSpring = springAmount;
}
public NewReloadGunWheellock(String name, float inAccuracy, float damage, int maxShots, int cooldown,
double kickback, double failRate, int reloadCooldown, boolean useRamRod, Item ammoItem, int gunPowderAmount,
Item cartridgeItem, int springAmount, int numberOfShots, int durabillity) {
super(name, inAccuracy, damage, maxShots, cooldown, kickback, failRate, reloadCooldown, useRamRod, ammoItem,
gunPowderAmount, cartridgeItem, durabillity);
this.numberOfShots = numberOfShots;
this.minSpring = springAmount;
}
@Override
public void addInformation(ItemStack stack, World worldIn, List<String> tooltip, ITooltipFlag flagIn) {
if(stack.hasTagCompound())
{
if(stack.getTagCompound().hasKey("loadedshots") && stack.getTagCompound().hasKey("step"))
{
AddLore(stack, tooltip, flagIn);
}
else
{
stack.getTagCompound().setInteger("loadedshots", 0);
stack.getTagCompound().setInteger("step", 0);
}
}
else
{
NBTTagCompound nbt = new NBTTagCompound();
nbt.setInteger("loadedshots", 0);
nbt.setInteger("step", 0);
nbt.setInteger("spring", 0);
stack.setTagCompound(nbt);
}
}
@Override
public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) {
EnumHand otherHand = EnumHand.OFF_HAND;
if(handIn == EnumHand.MAIN_HAND)
{
otherHand = EnumHand.OFF_HAND;
}
else if(handIn == EnumHand.OFF_HAND)
{
otherHand = EnumHand.MAIN_HAND;
}
ItemStack mainItem = playerIn.getHeldItem(handIn);
ItemStack offHand = playerIn.getHeldItem(otherHand);
int load1 = 0;
int load2 = 0;
int cooldown = 0;
boolean changedW = false;
if(mainItem.hasTagCompound() && offHand.hasTagCompound() && mainItem.getItem() instanceof NewReloadGun && offHand.getItem() instanceof NewReloadGun)
{
load1 = offHand.getTagCompound().getInteger("loadedshots");
load2 = mainItem.getTagCompound().getInteger("loadedshots");
cooldown = offHand.getTagCompound().getInteger("cooldown");
changedW = true;
}
int maxCooldown = 0;
if(offHand.getItem() instanceof RepairItem)
{
RepairItem kit = (RepairItem) offHand.getItem();
if(kit.type == this.getType())
{
mainItem.getTagCompound().setInteger("damage", 0);
offHand.setCount(0);
Vec3d pos = playerIn.getPositionVector();
worldIn.playSound(null, pos.x, pos.y, pos.z, SoundEvents.BLOCK_ANVIL_USE, SoundCategory.PLAYERS, 0.5f, 1.3f);
}
}
if(offHand.getItem() instanceof NewReloadGun)
{
NewReloadGun gun = (NewReloadGun) offHand.getItem();
maxCooldown = gun.cooldown;
}
if(load2 > load1 && cooldown == 0)
{
preFire(handIn, playerIn, mainItem, worldIn, offHand);
}
else if(load2 > load1 && maxCooldown != 0)
{
if(cooldown != maxCooldown)
{
preFire(handIn, playerIn, mainItem, worldIn, offHand);
}
}
else if(load1 == load2 && handIn == EnumHand.MAIN_HAND)
{
preFire(handIn, playerIn, mainItem, worldIn, offHand);
}
else if(changedW == false)
{
preFire(handIn, playerIn, mainItem, worldIn, offHand);
}
return new ActionResult<ItemStack>(EnumActionResult.PASS, playerIn.getHeldItem(handIn));
}
EnumActionResult preFire(EnumHand handIn, EntityPlayer playerIn, ItemStack mainItem, World worldIn, ItemStack offHand)
{
if(handIn == EnumHand.MAIN_HAND || canDual)
{
if(!playerIn.isInWater() && mainItem.hasTagCompound() && !worldIn.isRemote)
{
if(!containsReloadItem(offHand.getItem()) && mainItem.getTagCompound().getInteger("loadedshots") > 0 && mainItem.getTagCompound().getInteger("cooldown") <= 0 && (!playerIn.isSneaking() || mainItem.getTagCompound().getInteger("step") != 3) && !playerIn.isSneaking() && mainItem.getTagCompound().getInteger("spring") >= minSpring)
{
if(Math.random() > failRate && mainItem.getItemDamage() < this.getMaxDamage())
{
mainItem.getTagCompound().setInteger("spring", 0);
Fire(worldIn, playerIn, handIn);
}
else
{
mainItem.getTagCompound().setInteger("spring", 0);
Jam(worldIn, playerIn, handIn);
}
}
else if(playerIn.getHeldItemOffhand().isEmpty() && !worldIn.isRemote && mainItem.getTagCompound().getInteger("cooldown") <= 0 && playerIn.isSneaking() && mainItem.getTagCompound().getInteger("spring") < minSpring)
{
int spring = mainItem.getTagCompound().getInteger("spring");
mainItem.getTagCompound().setInteger("spring", spring + 1);
worldIn.playSound(null, playerIn.getPositionVector().x, playerIn.getPositionVector().y, playerIn.getPositionVector().z, SoundEvents.BLOCK_TRIPWIRE_CLICK_ON, SoundCategory.PLAYERS, 0.2f, 0.5f);
}
else if(mainItem.getTagCompound().getInteger("loadedshots") < this.maxShots && mainItem.getTagCompound().getInteger("cooldown") <= 0 && !playerIn.isSneaking())
{
if(!Load(playerIn, worldIn) && offHand.isEmpty() && mainItem.getTagCompound().getInteger("loadedshots") == 0)
{
mainItem.getTagCompound().setInteger("spring", 0);
worldIn.playSound(null, playerIn.getPositionVector().x, playerIn.getPositionVector().y, playerIn.getPositionVector().z, SoundEvents.BLOCK_WOOD_BUTTON_CLICK_ON, SoundCategory.PLAYERS, 1, 1);
}
}
else if(!playerIn.isSneaking() && !worldIn.isRemote && mainItem.getTagCompound().getInteger("loadedshots") == 0)
{
mainItem.getTagCompound().setInteger("spring", 0);
worldIn.playSound(null, playerIn.getPositionVector().x, playerIn.getPositionVector().y, playerIn.getPositionVector().z, SoundEvents.BLOCK_WOOD_BUTTON_CLICK_ON, SoundCategory.PLAYERS, 1, 1);
}
}
}
return EnumActionResult.FAIL;
}
@Override
public void onUpdate(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) {
if(stack.hasTagCompound() && !worldIn.isRemote)
{
if(stack.getTagCompound().hasKey("lit"))
{
if(stack.getTagCompound().getBoolean("lit") && Math.random() > 0.8)
{
Entity player = entityIn;
Vec3d pos = player.getPositionVector();
WorldServer server = worldIn.getMinecraftServer().getWorld(player.dimension);
server.spawnParticle(EnumParticleTypes.FLAME, pos.x + player.getLookVec().x, pos.y + player.getLookVec().y + 1, pos.z + player.getLookVec().z, 1, 0d, 0d, 0d, 0d, 0);
if(Math.random() > 0.95 || entityIn.isWet())
{
worldIn.playSound(null, player.getPositionVector().x, player.getPositionVector().y, player.getPositionVector().z, SoundEvents.BLOCK_FIRE_EXTINGUISH, SoundCategory.PLAYERS, 0.5f, 1.5f);
server.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, pos.x + player.getLookVec().x, pos.y + player.getLookVec().y + 1, pos.z + player.getLookVec().z, 5, 0d, 0d, 0d, 0.01d, 0);
stack.getTagCompound().setBoolean("lit", false);
}
}
}
}
super.onUpdate(stack, worldIn, entityIn, itemSlot, isSelected);
}
@Override
boolean Load(EntityPlayer player, World worldIn)
{
ItemStack item = player.getHeldItemMainhand();
ItemStack offHandItem = player.getHeldItemOffhand();
boolean changed = false;
int step = item.getTagCompound().getInteger("step");
if(step == 0 && offHandItem.getItem() == this.cartridgeItem && this.cartridgeItem != null)
{
if(this.useRamRod)
{
step += 2;
}
else
{
step += 3;
}
changed = true;
player.setItemStackToSlot(EntityEquipmentSlot.OFFHAND, new ItemStack(this.cartridgeItem, offHandItem.getCount() - 1));
}
else if(step == 0 && offHandItem.getItem() == Items.GUNPOWDER && offHandItem.getCount() == this.gunPowderAmount)
{
step ++;
changed = true;
player.setItemStackToSlot(EntityEquipmentSlot.OFFHAND, ItemStack.EMPTY);
worldIn.playSound(null, player.getPositionVector().x, player.getPositionVector().y, player.getPositionVector().z, SoundEvents.BLOCK_SAND_PLACE, SoundCategory.PLAYERS, 1, 1);
}
else if(step == 0 && offHandItem.getItem() == ModItems.GUNPOWDER_BAG && offHandItem.hasTagCompound())
{
if(offHandItem.getTagCompound().getInteger("gunpowder") >= this.gunPowderAmount)
{
int value = offHandItem.getTagCompound().getInteger("gunpowder");
offHandItem.getTagCompound().setInteger("gunpowder", value - this.gunPowderAmount);
player.setItemStackToSlot(EntityEquipmentSlot.OFFHAND, offHandItem);
step ++;
changed = true;
worldIn.playSound(null, player.getPositionVector().x, player.getPositionVector().y, player.getPositionVector().z, SoundEvents.BLOCK_SAND_PLACE, SoundCategory.PLAYERS, 1, 1);
}
}
else if(step == 1 && offHandItem.getItem() == this.ammoItem)
{
if(this.useRamRod)
{
step ++;
}
else
{
step += 2;
}
changed = true;
player.setItemStackToSlot(EntityEquipmentSlot.OFFHAND, new ItemStack(this.ammoItem, offHandItem.getCount() - 1));
worldIn.playSound(null, player.getPositionVector().x, player.getPositionVector().y, player.getPositionVector().z, SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.PLAYERS, 1, 1f);
}
else if(step == 2 && offHandItem.getItem() == ModItems.GUN_RAM_ROD)
{
step += 2;
changed = true;
worldIn.playSound(null, player.getPositionVector().x, player.getPositionVector().y, player.getPositionVector().z, SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.PLAYERS, 1, 0.5f);
}
else if(step == 3 && player.isSneaking() && offHandItem.isEmpty())
{
step ++;
changed = true;
worldIn.playSound(null, player.getPositionVector().x, player.getPositionVector().y, player.getPositionVector().z, SoundEvents.BLOCK_TRIPWIRE_CLICK_OFF, SoundCategory.PLAYERS, 1, 1);
}
if(changed)
{
if(step > 3)
{
step = 0;
int loadedShots = item.getTagCompound().getInteger("loadedshots") + 1;
item.getTagCompound().setInteger("loadedshots", loadedShots);
PotionEffect slow = new PotionEffect(MobEffects.SLOWNESS, this.reloadCooldown, 2, true, false);
player.addPotionEffect(slow);
item.getTagCompound().setInteger("cooldown", this.reloadCooldown);
}
else
{
PotionEffect slow = new PotionEffect(MobEffects.SLOWNESS, this.reloadCooldown, 2, true, false);
if(this.gunPowderAmount != 1)
{
slow = new PotionEffect(MobEffects.SLOWNESS, this.reloadCooldown, 254, true, false);
}
player.addPotionEffect(slow);
item.getTagCompound().setInteger("cooldown", this.reloadCooldown);
}
item.getTagCompound().setInteger("step", step);
player.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, item);
}
return changed;
}
}
| true
|
91d7e72cab3b25279831ff65ba148288a838fb9d
|
Java
|
fakemonk1/DataStructures-And-Algorithms-IB
|
/src/linkedlists/IntersectionOfLinkedLists.java
|
UTF-8
| 1,763
| 4.09375
| 4
|
[] |
no_license
|
package linkedlists;
/**
* https://www.interviewbit.com/problems/intersection-of-linked-lists/
*
* Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
*/
public class IntersectionOfLinkedLists {
public static ListNode getIntersectionNode(ListNode a, ListNode b) {
int aLength = getLength(a);
int bLength = getLength(b);
ListNode tempA = a;
ListNode tempB = b;
if(aLength == 0 | bLength == 0) return null;
if (aLength >= bLength) {
int forward = aLength - bLength;
int counter = 0;
while (counter < forward) {
tempA = tempA.next;
counter++;
}
} else {
int forward = bLength - aLength;
int counter = 0;
while (counter < forward) {
tempB =tempB.next;
counter++;
}
}
while (true) {
if (tempA == tempB)
return tempA;
tempA = tempA.next;
tempB = tempB.next;
}
}
public static int getLength(ListNode node) {
if(node == null) return 0;
if(node.next == null) return 1;
int length = 1;
ListNode temp = node;
while (temp.next != null) {
temp = temp.next;
length++;
}
return length;
}
}
| true
|
eb8ebb1204fd4224c2bcf5a7fccce3eb4cbcda1e
|
Java
|
kalapriyakannan/UMLONT
|
/com.ibm.ccl.soa.deploy.was/src/com/ibm/ccl/soa/deploy/was/validator/resolution/CreateDefaultNodeGroupUnitIntoCellUnitResolution.java
|
UTF-8
| 3,303
| 1.539063
| 2
|
[] |
no_license
|
/***************************************************************************************************
* Copyright (c) 2003, 2007 IBM Corporation Licensed Material - Property of IBM. All rights
* reserved.
*
* US Government Users Restricted Rights - Use, duplication or disclosure v1.0 restricted by GSA ADP
* Schedule Contract with IBM Corp.
*
* Contributors: IBM Corporation - initial API and implementation
**************************************************************************************************/
package com.ibm.ccl.soa.deploy.was.validator.resolution;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import com.ibm.ccl.soa.deploy.core.Requirement;
import com.ibm.ccl.soa.deploy.core.util.DeployNLS;
import com.ibm.ccl.soa.deploy.core.validator.ValidatorUtils;
import com.ibm.ccl.soa.deploy.core.validator.matcher.LinkFactory;
import com.ibm.ccl.soa.deploy.core.validator.resolution.DeployResolution;
import com.ibm.ccl.soa.deploy.core.validator.resolution.IDeployResolutionContext;
import com.ibm.ccl.soa.deploy.core.validator.resolution.IDeployResolutionGenerator;
import com.ibm.ccl.soa.deploy.core.validator.resolution.ResolutionUtils;
import com.ibm.ccl.soa.deploy.was.IWasTemplateConstants;
import com.ibm.ccl.soa.deploy.was.WasCellUnit;
import com.ibm.ccl.soa.deploy.was.WasNodeGroup;
import com.ibm.ccl.soa.deploy.was.WasNodeGroupUnit;
import com.ibm.ccl.soa.deploy.was.WasPackage;
import com.ibm.ccl.soa.deploy.was.internal.validator.WasDomainMessages;
public class CreateDefaultNodeGroupUnitIntoCellUnitResolution extends DeployResolution {
private final WasCellUnit _cellUnit;
public CreateDefaultNodeGroupUnitIntoCellUnitResolution(IDeployResolutionContext context,
IDeployResolutionGenerator generator, WasCellUnit cellUnit) {
super(context, generator, DeployNLS
.bind(WasDomainMessages.Resolution_create_Default_Was_NodeGroup_Unit_for_CellUnit_0,
cellUnit));
_cellUnit = cellUnit;
}
public IStatus resolve(IProgressMonitor monitor) {
WasNodeGroupUnit defaultNodeGroupUnit = null;
String templateId = _cellUnit.isConceptual() ? IWasTemplateConstants.WAS_6_NODE_GROUP_UNIT_CONCEPTUAL
: IWasTemplateConstants.WAS_6_NODE_GROUP_UNIT;
defaultNodeGroupUnit = (WasNodeGroupUnit) ResolutionUtils.addFromTemplate(templateId,
_cellUnit.getEditTopology());
List<Requirement> requireCellUnitL = ValidatorUtils.getRequirements(defaultNodeGroupUnit,
WasPackage.eINSTANCE.getWasCellUnit());
if (requireCellUnitL == null || defaultNodeGroupUnit == null) {
return null;
}
defaultNodeGroupUnit
.setDescription(WasDomainMessages.Resolution_create_default_node_group_description);
LinkFactory.createMemberLink(_cellUnit, defaultNodeGroupUnit);
WasNodeGroup ngCap = (WasNodeGroup) ValidatorUtils.getCapability(defaultNodeGroupUnit,
WasPackage.eINSTANCE.getWasNodeGroup());
if (ngCap != null) {
ngCap.setIsDefaultType(true);
ngCap.setNodeGroupName(WasDomainMessages.Resolution_create_default_node_group_name);
ngCap.setDescription(WasDomainMessages.Resolution_create_default_node_group_description);
}
return Status.OK_STATUS;
}
}
| true
|
1260083db05ea3a9154b12c7c2e5817b3347df2d
|
Java
|
govorovsky/LastfmClient
|
/app/src/main/java/com/techpark/lastfmclient/network/Method.java
|
UTF-8
| 123
| 1.828125
| 2
|
[] |
no_license
|
package com.techpark.lastfmclient.network;
/**
* Created by andrew on 28.10.14.
*/
public enum Method {
GET, POST
}
| true
|
6618ec78a2c4984d8b7d6c2c42848e19fd5110ea
|
Java
|
13klove/wba
|
/src/main/java/web/boostcourse/api/wba/productImage/repository/ProductImageRepository.java
|
UTF-8
| 531
| 1.640625
| 2
|
[] |
no_license
|
package web.boostcourse.api.wba.productImage.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import web.boostcourse.api.wba.productImage.model.entity.ProductImage;
import web.boostcourse.api.wba.productImage.repository.queryDsl.dto.ProductImageDtoRepository;
import web.boostcourse.api.wba.productImage.repository.queryDsl.entity.ProductImageEntityRepository;
public interface ProductImageRepository extends JpaRepository<ProductImage, Long>, ProductImageDtoRepository, ProductImageEntityRepository {
}
| true
|
5f2585e7d901cd2e449a158490ed30a41df4d148
|
Java
|
FilipHusnjak/JavaCourseProjects
|
/hw11-0036506711/src/main/java/hr/fer/zemris/java/hw11/jnotepadpp/local/LocalizableAction.java
|
UTF-8
| 1,157
| 2.9375
| 3
|
[] |
no_license
|
package hr.fer.zemris.java.hw11.jnotepadpp.local;
import javax.swing.AbstractAction;
import javax.swing.Action;
/**
* Represents AbstractAction which retrieves its name from the given
* {@link ILocalizationProvider}.
*
* @author Filip Husnjak
*/
public abstract class LocalizableAction extends AbstractAction {
private static final long serialVersionUID = 5991512482803088003L;
/**
* Constructs new {@link LocalizableAction} with the given {@link ILocalizationProvider}
* and key used to retrieve its name.
*
* @param key
* key for the localization
* @param lp
* {@link ILocalizationProvider} used to retrieve name
*/
public LocalizableAction(String key, ILocalizationProvider lp) {
setValues(key, lp);
lp.addLocalizationListener(() -> setValues(key, lp));
}
/**
* Sets name and description for this action.
*
* @param key
* key for string
* @param lp
* localization provider used for localization
*/
private void setValues(String key, ILocalizationProvider lp) {
putValue(Action.NAME, lp.getString(key));
putValue(Action.SHORT_DESCRIPTION, lp.getString(key + "Desc"));
}
}
| true
|
e463c98689c9e90317f69c123f23e19051fbe8e5
|
Java
|
jxxiaoxi/ME_DEMO
|
/Telephony/ext/src/com/mediatek/phone/ext/IPhoneMiscExt.java
|
UTF-8
| 2,771
| 2.078125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.mediatek.phone.ext;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import com.android.internal.telephony.Phone;
import com.mediatek.calloption.CallOptionHandlerFactory;
public interface IPhoneMiscExt {
/**
* plugin should check the hostReceiver class, to check whether this
* API call belongs to itself
* if (hostReceiver.getClass().getSimpleName() == "PhoneGlobalsBroadcastReceiver") {}
*
* @param context the received context
* @param intent the received intent
* @return true if plug-in decide to skip host execution
*/
boolean onPhoneGlobalsBroadcastReceive(Context context, Intent intent);
/**
* called when PhoneGlobals.onCreate()
*
* @param context the application context
* @param phone the Phone instance
*/
void onPhoneGlobalsCreate(Context context, Phone phone);
/**
* called when PhoneCallOptionHandlerFactory.createHandlerPrototype()
* if plug-in need add new CallOptionHandler, it can do in this API
*
* @param callOptionHandlerFactory
*/
void createHandlerPrototype(CallOptionHandlerFactory callOptionHandlerFactory);
/**
* called before a text containing sub-string "SIM" shows to end user.
* usually be shown via Toast, Dialog, etc
* plug-in can change the text if necessary. e.g. replace "SIM" with "UIM"
*
* @param originalText the original text string
* @param slotId the slotId according to the text
* @return the text which would be shown to end user.
*/
String changeTextContainingSim(String originalText, int slotId);
/**
* called in NetworkQueryService.onBind()
* google default behavior defined a LocalBinder to prevent NetworkQueryService
* being accessed by outside components.
* but, there is a situation that plug-in need the mBinder. LocalBinder can't be
* accessed by plug-in.
* it would be risky if plug-in really returns true directly without any security check.
* if this happen, other 3rd party component can access this binder, too.
*
* @return true if Plug-in need to get the binder
*/
boolean publishBinderDirectly();
/**
* called when the NetworkSelect notification is about to show.
* plugin can customize the notification text or PendingIntent
*
* @param notification the notification to be shown
* @param titleText the title
* @param expandedText the expanded text
* @param pi the PendingIntent when click the notification
*/
void customizeNetworkSelectionNotification(Notification notification, String titleText, String expandedText, PendingIntent pi);
}
| true
|
ea6d7d4dd2731cbbb2ac3b838d89c23e3fbc7e36
|
Java
|
lukasz1985/JMindMaps
|
/src/map/ViewModel.java
|
UTF-8
| 821
| 2.65625
| 3
|
[] |
no_license
|
package map;
import java.util.ArrayList;
public class ViewModel {
public ArrayList<Connection> connections = new ArrayList<>();
public ArrayList<Node> nodes = new ArrayList<>();
public void clear() {
this.connections.clear();
this.nodes.clear();
}
public void addNode(Node node) {
this.nodes.add(node);
}
public void removeNode(Node node) {
this.nodes.remove(node);
}
public void addConnection(Connection connection) {
this.connections.add(connection);
}
public void removeConnection(Connection connection) {
this.connections.remove(connection);
}
public ArrayList<Connection> getConnections() {
return this.connections;
}
public ArrayList<Node> getNodes() {
return this.nodes;
}
}
| true
|
3f1033363e4c0e265b2a57ad7fd68f3cc21afd5e
|
Java
|
DevBoost/EMFText-Zoo
|
/BreedingStation/NLP/edu.stanford.nlp/src/edu/stanford/nlp/stats/Counter.java
|
UTF-8
| 11,042
| 2.09375
| 2
|
[] |
no_license
|
/*******************************************************************************
* Copyright (C) 2012
* The Stanford Natural Language Processing Group
* http://nlp.stanford.edu/
* This Eclipse plugin matches the Stanford CoreNLP version 1.3.3
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
******************************************************************************/
// Stanford JavaNLP support classes
// Copyright (c) 2004-2008 The Board of Trustees of
// The Leland Stanford Junior University. All Rights Reserved.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// For more information, bug reports, fixes, contact:
// Christopher Manning
// Dept of Computer Science, Gates 1A
// Stanford CA 94305-9010
// USA
// java-nlp-support@lists.stanford.edu
// http://nlp.stanford.edu/software/
package edu.stanford.nlp.stats;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import edu.stanford.nlp.util.Factory;
import edu.stanford.nlp.util.logging.PrettyLoggable;
/**
* An Object to double map used for keeping weights or counts for objects.
* Utility functions are contained in
* {@link Counters}. The class previously known as Counter has been
* renamed to {@link ClassicCounter}. An alternative Counter
* implementation, which is more memory efficient but not necessarily faster,
* is {@link OpenAddressCounter}.
* <p>
* <i>Implementation note:</i> You shouldn't casually add further methods to
* this interface. Rather, they should be added to the {@link Counters} class.
*
* @author dramage
* @author cer
* @author pado
*/
public interface Counter<E> extends PrettyLoggable {
/**
* Returns a factory that can create new instances of this kind of Counter.
*
* @return A factory that can create new instances of this kind of Counter.
*/
public Factory<Counter<E>> getFactory();
/**
* Sets the default return value. This value is returned when you get
* the value for keys that are not in the Counter. It is zero by
* default, but can sometimes usefully by set to other values like
* Double.NaN or Double.NEGATIVE_INFINITY.
*
* @param rv The default value
*/
public void setDefaultReturnValue(double rv) ;
/**
* Returns the default return value.
*
* @return The default return value.
*/
public double defaultReturnValue() ;
/**
* Returns the count for this key as a double. This is the
* defaultReturnValue (0.0, if it hasn't been set) if the key hasn't
* previously been seen.
*
* @param key The key
* @return The count
*/
public double getCount(Object key);
/**
* Sets the count for the given key to be the given value.
* This will replace any existing count for the key.
* To add to a count instead of replacing it, use
* {@link #incrementCount(Object,double)}.
*
* @param key The key
* @param value The count
*/
public void setCount(E key, double value);
/**
* Increments the count for the given key by the given value. If the key
* hasn't been seen before, it is assumed to have count 0.0, and thus this
* method will set its count to the given amount. <i>Note that this is
* true regardless of the setting of defaultReturnValue.</i>
* Negative increments are equivalent to calling <tt>decrementCount</tt>.
* To more conveniently increment the count by 1.0, use
* {@link #incrementCount(Object)}.
* To set a count to a specific value instead of incrementing it, use
* {@link #setCount(Object,double)}.
*
* @param key The key to increment
* @param value The amount to increment it by
* @return The value associated with they key, post-increment.
*/
public double incrementCount(E key, double value);
/**
* Increments the count for this key by 1.0. If the key hasn't been seen
* before, it is assumed to have count 0.0, and thus this method will set
* its count to 1.0. <i>Note that this is
* true regardless of the setting of defaultReturnValue.</i>
* To increment the count by a value other than 1.0, use
* {@link #incrementCount(Object,double)}.
* To set a count to a specific value instead of incrementing it, use
* {@link #setCount(Object,double)}.
*
* @param key The key to increment by 1.0
* @return The value associated with they key, post-increment.
*/
public double incrementCount(E key);
/**
* Decrements the count for this key by the given value.
* If the key hasn't been seen before, it is assumed to have count 0.0, and
* thus this method will set its count to the negative of the given amount.
* <i>Note that this is true regardless of the setting of defaultReturnValue.</i>
* Negative increments are equivalent to calling <code>incrementCount</code>.
* To more conveniently decrement the count by 1.0, use
* {@link #decrementCount(Object)}.
* To set a count to a specific value instead of decrementing it, use
* {@link #setCount(Object,double)}.
*
* @param key The key to decrement
* @param value The amount to decrement it by
* @return The value associated with they key, post-decrement.
*/
public double decrementCount(E key, double value);
/**
* Decrements the count for this key by 1.0.
* If the key hasn't been seen before, it is assumed to have count 0.0,
* and thus this method will set its count to -1.0. <i>Note that this is
* true regardless of the setting of defaultReturnValue.</i>
* To decrement the count by a value other than 1.0, use
* {@link #decrementCount(Object,double)}.
* To set a count to a specific value instead of decrementing it, use
* {@link #setCount(Object,double)}.
*
* @param key The key to decrement by 1.0
* @return The value of associated with they key, post-decrement.
*/
public double decrementCount(E key);
/**
* Increments the count stored in log space for this key by the given
* log-transformed value.
* If the current count for the key is v1, and you call
* logIncrementCount with a value of v2, then the new value will
* be log(e^v1 + e^v2). If the key
* hasn't been seen before, it is assumed to have count
* Double.NEGATIVE_INFINITY, and thus this
* method will set its count to the given amount. <i>Note that this is
* true regardless of the setting of defaultReturnValue.</i>
* To set a count to a specific value instead of incrementing it, you need
* to first take the log yourself and then to call
* {@link #setCount(Object,double)}.
*
* @param key The key to increment
* @param value The amount to increment it by, in log space
* @return The value associated with they key, post-increment, in log space
*/
public double logIncrementCount(E key, double value);
/**
* Adds the counts in the given Counter to the counts in this Counter.
* This is identical in effect to calling Counters.addInPlace(this, counter).
*
* @param counter The Counter whose counts will be added. For each key in
* counter, if it is not in this, then it will be added with value
* <code>counter.getCount(key)</code>. Otherwise, it will have value
* <code>this.getCount(key) + counter.getCount(key)</code>.
*/
public void addAll(Counter<E> counter);
/**
* Removes the given key and its associated value from this Counter.
* Its count will now be returned as the defaultReturnValue and it
* will no longer be considered previously seen. If a key not contained in
* the Counter is given, no action is performed on the Counter and the
* defaultValue is returned. This behavior echoes that of HashMap, but differs
* since a HashMap returns a Double (rather than double) and thus returns null
* if a key is not present. Any future revisions of Counter should preserve
* the ability to "remove" a key that is not present in the Counter.
*
* @param key The key
* @return The value removed from the map or the default value if no
* count was associated with that key.
*/
public double remove(E key);
/** Returns whether a Counter contains a key.
*
* @param key The key
* @return true iff key is a key in this Counter.
*/
public boolean containsKey(E key);
/**
* Returns the Set of keys in this counter.
*
* @return The Set of keys in this counter.
*/
public Set<E> keySet();
/**
* Returns a copy of the values currently in this counter.
* (You should regard this Collection as read-only for forward
* compatibility; at present implementations differ on how they
* respond to attempts to change this Collection.)
*
* @return A copy of the values currently in this counter.
*/
public Collection<Double> values();
/**
* Returns a view of the entries in this counter. The values
* can be safely modified with setValue().
*
* @return A view of the entries in this counter
*/
public Set<Map.Entry<E,Double>> entrySet();
/**
* Removes all entries from the counter.
*/
public void clear();
/**
* Returns the number of entries stored in this counter.
* @return The number of entries in this counter.
*/
public int size();
/**
* Computes the total of all counts in this counter, and returns it
* as a double. (Existing implementations cache this value, so that this
* operation is cheap.)
*
* @return The total (arithmetic sum) of all counts in this counter.
*/
public double totalCount();
}
| true
|
c8548a7641707d4d553af158aa80da28c545b10e
|
Java
|
fcu-d0577613/Android-HW4-2
|
/app/src/main/java/com/example/acc0752001/fakeapplication/NotiActivity.java
|
UTF-8
| 776
| 2.3125
| 2
|
[] |
no_license
|
package com.example.acc0752001.fakeapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class NotiActivity extends AppCompatActivity {
TextView sh_name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_noti);
sh_name = (TextView)findViewById(R.id.textView2);
String hello = "Hello ";
Intent intent = getIntent();
if(intent != null) {
String name = intent.getStringExtra("KEY_NAME");
if(name != null) {
hello = hello + name;
}
}
sh_name.setText(hello);
}
}
| true
|
460a65e24aacb75f6791a48ffd1e24dab7512fbb
|
Java
|
luffy7718/Proxiservices
|
/app/src/main/java/com/example/a77011_40_05/proxiservices/BroadcastReceivers/InternetBroadcastReceiver.java
|
UTF-8
| 1,346
| 2.3125
| 2
|
[] |
no_license
|
package com.example.a77011_40_05.proxiservices.BroadcastReceivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.example.a77011_40_05.proxiservices.Entities.Erreur;
import com.example.a77011_40_05.proxiservices.Utils.App;
import com.example.a77011_40_05.proxiservices.Utils.Functions;
public class InternetBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager
.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if(App.erreurs.size() > 0)
{
for(Erreur erreur:App.erreurs)
{
Functions.addErreur(erreur,context);
}
App.deleteErreur(context);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true
|
3200e0ae3074a2aa67131ae76383a0d97ebbb18e
|
Java
|
marvuchko/betting-bull
|
/infrastructure-microservice/src/main/java/com/marvuchko/infrastructuremicroservice/exception/core/UnauthorizedException.java
|
UTF-8
| 509
| 2.453125
| 2
|
[] |
no_license
|
package com.marvuchko.infrastructuremicroservice.exception.core;
import com.marvuchko.infrastructuremicroservice.exception.base.BaseException;
public class UnauthorizedException extends BaseException {
public static final String DEFAULT_ERROR_MESSAGE = "Unauthorized access!";
public UnauthorizedException() {
super(DEFAULT_ERROR_MESSAGE, 401);
}
public UnauthorizedException(String defaultMessage, int defaultErrorCode) {
super(defaultMessage, defaultErrorCode);
}
}
| true
|
b715ee78de2e02d35410c3f08fa51551d6a37d34
|
Java
|
huankai/hk-core
|
/hk-core-poi/src/main/java/com/hk/commons/poi/excel/style/CustomCellStyle.java
|
UTF-8
| 5,176
| 2.671875
| 3
|
[] |
no_license
|
package com.hk.commons.poi.excel.style;
import lombok.Data;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import com.hk.commons.poi.excel.model.DataFormat;
import com.hk.commons.poi.excel.util.CellStyleBuilder;
/**
* @author kevin
*/
@Data
public class CustomCellStyle implements StyleSheet {
/**
* 背景颜色
*/
protected short backgroundColor;
/**
* 前景颜色
*/
protected short fillForegroundColor;
/**
* 背景颜色填充类型
*/
private FillPatternType fillPatternType;
/**
* 垂直方向对齐方式
*/
protected VerticalAlignment verticalAlignment;
/**
* 水平方向对齐方式
*/
protected HorizontalAlignment horizontalAlignment;
/**
* 上边框
*/
protected BorderStyle borderTop;
/**
* 上边框颜色
*/
protected short borderTopColor;
/**
* 左边框
*/
protected BorderStyle borderLeft;
/**
* 左边框颜色
*/
protected short borderLeftColor;
/**
* 右边框
*/
protected BorderStyle borderRight;
/**
* 右边框颜色
*/
protected short borderRightColor;
/**
* 下边框
*/
protected BorderStyle borderBottom;
/**
* 下边框颜色
*/
protected short borderBottomColor;
/**
* 自动换行
*/
protected boolean autoWrap;
/**
* 字体名称
*/
protected Fonts fontName;
/**
* 字体大小
*/
protected short fontSize;
/**
* 字体颜色
*/
protected short fontColor;
/**
* 是否斜体
*/
protected boolean italic;
/**
* 是否粗体
*/
protected boolean bold;
/**
* 下划线
*/
protected UnderLineStyle underline;
/**
* 是否有删除线
*/
protected boolean strikeout;
/**
* 设置cell所引用的样式是否锁住
*/
protected boolean locked;
/**
* <table BORDER CELLPADDING=3 CELLSPACING=1> <caption>默认工作表样式</caption>
* <tr>
* <td ALIGN=CENTER><b>样式名称</b></td>
* <td ALIGN=CENTER><b>样式值</b></td>
* </tr>
* <tr>
* <td ALIGN=CENTER>自动换行</td>
* <td ALIGN=CENTER>false</td>
* </tr>
* <tr>
* <td ALIGN=CENTER>字体大小</td>
* <td ALIGN=CENTER>12</td>
* </tr>
* <tr>
* <td ALIGN=CENTER>是否粗体</td>
* <td ALIGN=CENTER>false</td>
* </tr>
* <tr>
* <td ALIGN=CENTER>是否斜体</td>
* <td ALIGN=CENTER>false</td>
* </tr>
* <tr>
* <td ALIGN=CENTER>下划线</td>
* <td ALIGN=CENTER>无</td>
* </tr>
* <tr>
* <td ALIGN=CENTER>字体颜色</td>
* <td ALIGN=CENTER>灰色50%</td>
* </tr>
* <tr>
* <td ALIGN=CENTER>垂直方向对齐方式</td>
* <td ALIGN=CENTER>居中对齐</td>
* </tr>
* <tr>
* <td ALIGN=CENTER>水平方向对齐方式</td>
* <td ALIGN=CENTER>居中对齐</td>
* </tr>
* <tr>
* <td ALIGN=CENTER>背景颜色</td>
* <td ALIGN=CENTER>无</td>
* </tr>
* <tr>
* <td ALIGN=CENTER>边框颜色</td>
* <td ALIGN=CENTER>上、下、左、右无样式</td>
* </tr>
* <tr>
* <td ALIGN=CENTER>边框</td>
* <td ALIGN=CENTER>上、下、左、右无样式</td>
* </tr>
* </table>
*/
public CustomCellStyle() {
autoWrap = false;
fontSize = 12;
fontName = Fonts.SONTTI;
bold = false;
underline = UnderLineStyle.U_NONE;
fontColor = NONE_STYLE;
fillForegroundColor = NONE_STYLE;
verticalAlignment = VerticalAlignment.CENTER;
horizontalAlignment = HorizontalAlignment.CENTER;
backgroundColor = NONE_STYLE;
fillPatternType = FillPatternType.NO_FILL;
setBorderColor(NONE_STYLE);
setBorder(BorderStyle.NONE);
}
/**
* 设置上、下、左、右边框
*
* @param border border
*/
public void setBorder(BorderStyle border) {
this.borderTop = border;
this.borderLeft = border;
this.borderRight = border;
this.borderBottom = border;
}
/**
* 设置上、下、左、右边框颜色
*
* @param borderColor borderColor
*/
public void setBorderColor(short borderColor) {
this.borderTopColor = borderColor;
this.borderLeftColor = borderColor;
this.borderRightColor = borderColor;
this.borderBottomColor = borderColor;
}
/**
* 构建Excel单元格样式
*
* @param workbook workbook
* @param dataFormat dataFormat
* @return {@link CellStyle}
*/
public CellStyle toCellStyle(Workbook workbook, DataFormat dataFormat) {
return CellStyleBuilder.buildCellStyle(workbook, this, dataFormat);
}
}
| true
|
66e5499d0941d28c272d069c7fe3c9a81007bd51
|
Java
|
andrempo/tech-gallery
|
/src/main/java/com/ciandt/techgallery/service/SkillServiceImpl.java
|
UTF-8
| 6,822
| 2.234375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.ciandt.techgallery.service;
import java.util.Date;
import java.util.logging.Logger;
import com.ciandt.techgallery.persistence.dao.SkillDAO;
import com.ciandt.techgallery.persistence.dao.SkillDAOImpl;
import com.ciandt.techgallery.persistence.dao.TechGalleryUserDAO;
import com.ciandt.techgallery.persistence.dao.TechGalleryUserDAOImpl;
import com.ciandt.techgallery.persistence.dao.TechnologyDAO;
import com.ciandt.techgallery.persistence.dao.TechnologyDAOImpl;
import com.ciandt.techgallery.persistence.model.Skill;
import com.ciandt.techgallery.persistence.model.TechGalleryUser;
import com.ciandt.techgallery.persistence.model.Technology;
import com.ciandt.techgallery.service.enums.ValidationMessageEnums;
import com.ciandt.techgallery.service.model.Response;
import com.ciandt.techgallery.service.model.SkillResponse;
import com.ciandt.techgallery.service.util.SkillConverter;
import com.google.api.server.spi.response.BadRequestException;
import com.google.api.server.spi.response.InternalServerErrorException;
import com.google.api.server.spi.response.NotFoundException;
import com.google.appengine.api.oauth.OAuthRequestException;
import com.google.appengine.api.users.User;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Ref;
/**
* Services for Skill Endpoint requests.
*
* @author Felipe Goncalves de Castro
*
*/
public class SkillServiceImpl implements SkillService {
private static final Logger log = Logger.getLogger(SkillServiceImpl.class.getName());
SkillDAO skillDAO = new SkillDAOImpl();
TechGalleryUserDAO techGalleryUserDAO = new TechGalleryUserDAOImpl();
TechnologyDAO technologyDAO = new TechnologyDAOImpl();
/** tech gallery user service for getting PEOPLE API user. */
UserServiceTG userService = new UserServiceTGImpl();
@Override
public Response addOrUpdateSkill(SkillResponse skill, User user)
throws InternalServerErrorException, BadRequestException {
log.info("Starting creating or updating skill");
validateInputs(skill, user);
Technology technology = technologyDAO.findById(skill.getTechnology());
TechGalleryUser techUser = techGalleryUserDAO.findByGoogleId(user.getUserId());
Skill skillEntity = skillDAO.findByUserAndTechnology(techUser, technology);
// if there is a skillEntity, it is needed to inactivate it and create a new one
if (skillEntity != null) {
log.info("Inactivating skill: " + skillEntity.getId());
skillEntity.setInactivatedDate(new Date());
skillEntity.setActive(Boolean.FALSE);
skillDAO.update(skillEntity);
}
Skill newSkill = addNewSkill(skill, techUser, technology);
SkillResponse ret = SkillConverter.fromEntityToTransient(newSkill);
return ret;
}
/**
* Validate inputs of SkillResponse.
*
* @param skill inputs to be validate
* @param user info about user from google
* @throws BadRequestException
*/
private void validateInputs(SkillResponse skill, User user) throws BadRequestException {
log.info("Validating inputs of skill");
if (user == null || user.getUserId() == null || user.getUserId().isEmpty()) {
throw new BadRequestException(ValidationMessageEnums.USER_GOOGLE_ENDPOINT_NULL.message());
}
TechGalleryUser techUser = techGalleryUserDAO.findByGoogleId(user.getUserId());
if (techUser == null) {
throw new BadRequestException(ValidationMessageEnums.USER_NOT_EXIST.message());
}
if (skill == null) {
throw new BadRequestException(ValidationMessageEnums.SKILL_CANNOT_BLANK.message());
}
if (skill.getValue() == null || skill.getValue() < 0 || skill.getValue() > 5) {
throw new BadRequestException(ValidationMessageEnums.SKILL_RANGE.message());
}
if (skill.getTechnology() == null || skill.getTechnology().isEmpty()) {
throw new BadRequestException(ValidationMessageEnums.TECHNOLOGY_ID_CANNOT_BLANK.message());
}
Technology technology = technologyDAO.findById(skill.getTechnology());
if (technology == null) {
throw new BadRequestException(ValidationMessageEnums.TECHNOLOGY_NOT_EXIST.message());
}
}
private Skill addNewSkill(SkillResponse skill, TechGalleryUser techUser, Technology technology) {
log.info("Adding new skill...");
Skill newSkill = new Skill();
newSkill.setTechGalleryUser(Ref.create(techUser));
newSkill.setTechnology(Ref.create(technology));
newSkill.setValue(skill.getValue());
newSkill.setActive(Boolean.TRUE);
Key<Skill> newSkillKey = skillDAO.add(newSkill);
newSkill.setId(newSkillKey.getId());
log.info("New skill added: " + newSkill.getId());
return newSkill;
}
@Override
public Response getUserSkill(String techId, User user) throws BadRequestException,
OAuthRequestException, NotFoundException, InternalServerErrorException {
// user google id
String googleId;
// user from techgallery datastore
TechGalleryUser tgUser;
// User from endpoint can't be null
if (user == null) {
throw new OAuthRequestException("OAuth error, null user reference!");
} else {
googleId = user.getUserId();
}
// TechGalleryUser can't be null and must exists on datastore
if (googleId == null || googleId.equals("")) {
throw new NotFoundException("Current user was not found!");
} else {
// get the TechGalleryUser from datastore or PEOPLE API
tgUser = techGalleryUserDAO.findByGoogleId(googleId);
// userService.getUserSyncedWithProvider(userEmail.replace("@ciandt.com", ""));
if (tgUser == null) {
throw new BadRequestException("Endorser user do not exists on datastore!");
}
}
// Technology can't be null
Technology technology = technologyDAO.findById(techId);
if (technology == null) {
throw new BadRequestException("Technology do not exists!");
}
Skill userSkill = skillDAO.findByUserAndTechnology(tgUser, technology);
if (userSkill == null) {
throw new NotFoundException("User skill do not exist!");
} else {
return SkillConverter.fromEntityToTransient(userSkill);
}
}
@Override
public Response getUserSkill(String techId, TechGalleryUser user) throws BadRequestException,
OAuthRequestException, NotFoundException, InternalServerErrorException {
// User can't be null
if (user == null) {
throw new OAuthRequestException("Null user reference!");
}
// Technology can't be null
Technology technology = technologyDAO.findById(techId);
if (technology == null) {
throw new BadRequestException("Technology do not exists!");
}
Skill userSkill = skillDAO.findByUserAndTechnology(user, technology);
if (userSkill == null) {
return null;
} else {
return SkillConverter.fromEntityToTransient(userSkill);
}
}
}
| true
|
a076e1167c6ef2f3edf93a3530c8dc237ef8ba01
|
Java
|
sdd031215/crowd
|
/src/main/java/com/crowd/tools/MonitorThread.java
|
UTF-8
| 8,303
| 2.40625
| 2
|
[] |
no_license
|
package com.crowd.tools;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.FileSystems;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.HashMap;
import java.util.Map;
//import org.json.JSONArray;
//import org.json.JSONObject;
public class MonitorThread implements Runnable {
private String path;
public MonitorThread() {
}
public MonitorThread(String path) {
this.path = path;
}
public void run(){
LogUtils.logInfo("---------------》enter monitor《----------------------");
WatchService watchService;
try {
watchService = FileSystems.getDefault().newWatchService();
Paths.get(path).register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
while(true)
{
//多长时间检测一次
try {
Thread.currentThread().sleep(1000*60*10);
} catch (InterruptedException e) {
e.printStackTrace();
}
WatchKey key = null;
try {
key = watchService.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
for(WatchEvent<?> event:key.pollEvents())
{
LogUtils.logInfo(event.context()+"发生了"+ event.kind() +"事件");
//多长时间检测一次
try {
Thread.currentThread().sleep(1000*60*5);
} catch (InterruptedException e) {
e.printStackTrace();
}
if("hotel_revenue_hotel_info_dwd".equals(event.context().toString())
&& ("ENTRY_MODIFY".equals(event.kind().toString())
|| "ENTRY_CREATE".equals(event.kind().toString()))){
LogUtils.logInfo(event.context()+"发生了"+ event.kind() +"事件");
BigVar.hid2area.clear();
BigVar.hid2city.clear();
BigVar.hid2star.clear();
BigVar.hid2group.clear();
BigVar.hid2iseoc.clear();
BigVar.hid2city.clear();
readBigFile_hotel(path+"/hotel_revenue_hotel_info_dwd");
//TODO:清空,然后重新加载数据到内存
}
if("user_hist_cvthotel_info".equals(event.context().toString())
&& ("ENTRY_MODIFY".equals(event.kind().toString())
|| "ENTRY_CREATE".equals(event.kind().toString()))){
LogUtils.logInfo(event.context()+"发生了"+ event.kind() +"事件");
BigVar.user2cvthid.clear();
readBigFile_cvt(path+"/user_hist_cvthotel_info");
//TODO:清空,然后重新加载数据到内存
}
if("cvr_feat_weight".equals(event.context().toString())
&& ("ENTRY_MODIFY".equals(event.kind().toString())
|| "ENTRY_CREATE".equals(event.kind().toString()))){
LogUtils.logInfo(event.context()+"发生了"+ event.kind() +"事件");
BigVar.feat2w.clear();
readBigFile_weight(path+"/cvr_feat_weight");
//TODO:清空,然后重新加载数据到内存
}
}
if(!key.reset())
{
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readBigFile_hotel(String inputFile) {
long start = System.currentTimeMillis();// 开始时间
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(inputFile)));
BufferedReader in = new BufferedReader(new InputStreamReader(bis, "utf-8"), 10 * 1024 * 1024);// 10M缓存
while (in.ready()) {
String line = in.readLine();
line = line.replaceAll("\t", ";&");
String[] strs = line.split(";&");
if (strs.length != 15) continue;
String s_hotelid = strs[0];
String hid = strs[1];
String hotel_name = strs[2];
String g_group_id = strs[3];
String g_group_name = strs[4];
String province_id = strs[5];
String a_province_name = strs[6];
String city_id = strs[7];
String a_city_name = strs[8];
String area_id = strs[9];
String a_area_name = strs[10];
String star = strs[11];
String m_iseconomic = strs[12];
String m_isapartment = strs[13];
String m_address = strs[14];
hid = hid.replaceFirst("[0]*", "");
if(a_area_name != null && !"NULL".equals(a_area_name)){
String area = a_city_name.trim() + "_" + a_area_name.trim();
BigVar.hid2area.put(hid, area);
BigVar.hid2city.put(hid, Integer.parseInt(city_id) + "");
}
if(star.trim()!="" )
BigVar.hid2star.put(hid, star);
if(g_group_id.trim()!="" )
BigVar.hid2group.put(hid, g_group_id);
BigVar.hid2iseoc.put(hid, m_iseconomic);
//BigVar.hid2city.put(hid, city_id);
}
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
long end = System.currentTimeMillis();// 结束时间
LogUtils.logWarn("readBigFile_hotel,总共耗时:" + (end - start) + "ms" + ",文件hotel_revenue_hotel_info_dwd,BigVar.hid2star个数"+ BigVar.hid2star.size());
}
public static void readBigFile_cvt(String inputFile) {
long start = System.currentTimeMillis();// 开始时间
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(inputFile)));
BufferedReader in = new BufferedReader(new InputStreamReader(bis, "utf-8"), 10 * 1024 * 1024);// 10M缓存
while (in.ready()) {
String line = in.readLine();
String[] strs = line.split(" ");
if (strs.length < 4) continue;
String deviceid = strs[0];
String listtime = strs[1];
String cvthid = strs[2];
Integer price = Integer.parseInt(strs[3]);
//价格为0的过滤掉
if(price == 0) continue;
if(deviceid == "" ||deviceid == "||" || listtime == "" || cvthid=="" ){
LogUtils.logInfo(line);
}
//拼装成python三维数组
Map deviceidMap = BigVar.user2cvthid.get(deviceid);
if(deviceidMap != null){
Map listtimeMap = (Map) deviceidMap.get(listtime);
if(listtimeMap != null){
listtimeMap.put(cvthid, price);
deviceidMap.remove(listtime);
deviceidMap.put(listtime, deviceidMap);
}else{
Map<String, Integer> map = new HashMap<String, Integer>();
map.put(cvthid, price);
deviceidMap.put(listtime, map);
}
BigVar.user2cvthid.remove(deviceid);
BigVar.user2cvthid.put(deviceid, deviceidMap);
}else{
Map<String, Integer> map = new HashMap<String, Integer>();
map.put(cvthid, price);
Map<String, Map> map2 = new HashMap<String, Map>();
map2.put(listtime, map);
BigVar.user2cvthid.put(deviceid, map2);
}
//BigVar.user2cvthid.put(deviceid, map2);
}
in.close();
int i = 0;
int j = 0;
for (Map.Entry<String, Map> mm : BigVar.user2cvthid.entrySet()) {
if(mm.getValue().size()>1){
i += mm.getValue().size();
j++;
}
}
LogUtils.logInfo(i+"---"+j);
LogUtils.logInfo(BigVar.user2cvthid.size() + "");
} catch (IOException ex) {
ex.printStackTrace();
}
long end = System.currentTimeMillis();// 结束时间
LogUtils.logWarn("readBigFile_cvt,总共耗时:" + (end - start) + "ms" + ",文件user_hist_cvthotel_info,BigVar.user2cvthid个数"+ BigVar.user2cvthid.size());
}
public static void readBigFile_weight(String inputFile) {
long start = System.currentTimeMillis();// 开始时间
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(inputFile)));
BufferedReader in = new BufferedReader(new InputStreamReader(bis, "utf-8"), 10 * 1024 * 1024);// 10M缓存
while (in.ready()) {
String line = in.readLine();
String[] strs = line.trim().split(" ");
if(strs.length < 2) continue;
BigVar.feat2w.put(strs[0], strs[1]);
}
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
long end = System.currentTimeMillis();// 结束时间
LogUtils.logWarn("readBigFile_weight,总共耗时:" + (end - start) + "ms"+ ",文件cvr_feat_weight,BigVar.feat2w个数"+ BigVar.feat2w.size());
}
// public static void main(String[] args) {
// MonitorThread.readBigFile_hotel("/Users/user/Downloads/reranktest/"+"/hotel_revenue_hotel_info_dwd");
// }
}
| true
|
0e7ae43fa47577be72d6672b7232e2498eee1007
|
Java
|
luckyQing/demo
|
/design-patterns/src/main/java/com/liyulin/design/patterns/chain/LoginReqVO.java
|
UTF-8
| 148
| 1.640625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.liyulin.design.patterns.chain;
import lombok.Data;
@Data
public class LoginReqVO {
private String username;
private String pwd;
}
| true
|
1e26ce36fc3b06333c771d8aadba46cdc0d713c3
|
Java
|
Okami-Kato/jwd-critics
|
/src/main/java/com/epam/jwd_critics/dao/EntityTransaction.java
|
UTF-8
| 1,673
| 2.453125
| 2
|
[] |
no_license
|
package com.epam.jwd_critics.dao;
import com.epam.jwd_critics.entity.BaseEntity;
import com.epam.jwd_critics.pool.ConnectionPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.SQLException;
public class EntityTransaction {
private Connection connection;
private final AbstractBaseDao<?, ? extends BaseEntity>[] daos;
private static final Logger logger = LoggerFactory.getLogger(EntityTransaction.class);
@SafeVarargs
public EntityTransaction(AbstractBaseDao<?, ? extends BaseEntity>... daos) {
this.daos = daos;
try {
connection = ConnectionPool.getInstance().getConnection();
connection.setAutoCommit(false);
for (AbstractBaseDao<?, ? extends BaseEntity> dao : daos) {
dao.setConnection(connection);
}
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
}
public void commit() {
try {
connection.commit();
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
}
public void rollback() {
try {
connection.rollback();
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
}
public void close() {
try {
for (AbstractBaseDao<?, ? extends BaseEntity> dao : daos) {
dao.setConnection(null);
}
connection.setAutoCommit(true);
connection.close();
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
connection = null;
}
}
| true
|
82b12bca0eca29646120dc38e16e308488f1c9a3
|
Java
|
arvindhmk/basicsSelenium
|
/src/Dragndrop.java
|
UTF-8
| 2,464
| 2.640625
| 3
|
[] |
no_license
|
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Dragndrop
{
public static void main(String[] args) throws InterruptedException
{
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver", "C:\\Users\\user\\Downloads\\Compressed\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://jqueryui.com/droppable/");
Actions act = new Actions(driver);
driver.switchTo().frame(0);
WebElement drag = driver.findElement(By.id("draggable"));
WebElement drop = driver.findElement(By.id("droppable"));
act.doubleClick(drop).build().perform();//double click
Thread.sleep(3000);
act.contextClick().build().perform();//right click
Thread.sleep(3000);
act.dragAndDrop(drag, drop).build().perform();//drag and drop
//act.clickAndHold(drag).moveToElement(drop).release(drag).build().perform();
Thread.sleep(1000);
driver.navigate().to("https://jqueryui.com/resizable/");
driver.switchTo().frame(0);
WebElement resize = driver.findElement(By.xpath("//div[@id='resizable']/div[3]"));
act.clickAndHold(resize).moveByOffset(417, 147).release(resize).build().perform();
//act.dragAndDropBy(resize, 60, 30);
Thread.sleep(3000);
driver.navigate().to("https://jqueryui.com/slider/#colorpicker");
driver.switchTo().frame(0);
WebElement slider = driver.findElement(By.xpath("//div[@id='green']/span"));
act.clickAndHold(slider).moveByOffset(100, 0).release(slider).build().perform();
//act.dragAndDropBy(slider, 100, 0);
Thread.sleep(4000);
WebDriverWait wait = new WebDriverWait(driver,30);
driver.get("https://jqueryui.com/slider/#multiple-vertical");
driver.switchTo().frame(0);
WebElement slider1 = driver.findElement(By.xpath("//div[@id='eq']/span[2]/span"));
wait.until(ExpectedConditions.visibilityOf(slider1));
act.clickAndHold(slider1).pause(Duration.ofSeconds(5)).moveByOffset(0, 100).release(slider1).build().perform();
//act.dragAndDropBy(slider1, 60, 0);
Thread.sleep(2000);
driver.close();
}
}
| true
|
621044ffe1d0a4a654c94efd9a717dc2eedee7e9
|
Java
|
Dynamit88/Room-Finding-App-Android
|
/app/src/main/java/team16/project/team/orbis/global/objectclass/BuildingMapNodeType.java
|
UTF-8
| 186
| 1.859375
| 2
|
[] |
no_license
|
package team16.project.team.orbis.global.objectclass;
/**
* This defines the types a node can be
*/
public enum BuildingMapNodeType {
LIFT, STAIRS, ROOM, LEFT_TURN, RIGHT_TURN
}
| true
|
b05bf08b17a6b5fe9af2dc541d7294e28cda56c2
|
Java
|
Eriflow/obm_slemaistre
|
/java/sync/common/src/main/java/org/obm/sync/auth/OBMConnectorVersionException.java
|
UTF-8
| 433
| 2.3125
| 2
|
[] |
no_license
|
package org.obm.sync.auth;
public class OBMConnectorVersionException extends Exception {
private AccessToken token;
private Version requiredVersion;
public OBMConnectorVersionException(AccessToken token, Version requiredVersion) {
this.token = token;
this.requiredVersion = requiredVersion;
}
public AccessToken getToken() {
return token;
}
public Version getConnectorVersion() {
return requiredVersion;
}
}
| true
|
5c091a7b825ab8c59ac53ecedc0b1c47dbf03100
|
Java
|
rao1219/elight
|
/elight/src/jspservlet/dao/OrderDAO.java
|
UTF-8
| 491
| 1.960938
| 2
|
[] |
no_license
|
package jspservlet.dao;
import java.util.ArrayList;
import java.util.List;
import jspservlet.vo.Cart;
import jspservlet.vo.Order;
import jspservlet.vo.Product;
public interface OrderDAO {
public ArrayList<Cart> query(String userId) throws Exception;
public int add(Cart cart) throws Exception;
public void addOrder(Order order) throws Exception;
public ArrayList<Order> quetyOrder(String username) throws Exception;
public int getCurrentIndex();
public void updateCurrentIndex();
}
| true
|
3367a4a0d5bfb3a17e3ad63ad6e81572d9d848bc
|
Java
|
emccarthy3/Homework6Halfway
|
/HW6Runtime/src/edu/elon/math/FunctionInterface.java
|
UTF-8
| 5,706
| 3.015625
| 3
|
[] |
no_license
|
/**
* FunctionInterface.java 1.0 November 17, 2016
*
* Copyright (c) 2016 Dawn Winsor, Betsey McCarthy, Jen Rhodes
* Elon, North Carolina, 27244 U.S.A.
* All Rights Reserved
*/
package edu.elon.math;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
/**
* This class extends Remote. It acts as the remote interface for the proxy
* pattern.
*
* @author emccarthy3, dwinsor, jrhodes
*
*/
public interface FunctionInterface extends Remote {
public String getEnvironmentalVariables() throws RemoteException;
/**
* Gets the strategy from the name passed to the method and creates and
* instance of strategy
*
* @param type
* - the name of the strategy that gets passed and later created
* @return strategy - the strategy created from the Factory
*/
public Strategy callStrategy(String type) throws RemoteException;
/**
* Evaluates the current set of input values to calculate the function value.
* We currently consider one output value for a function. If the function has
* multiple output values then the function must have these combined into a
* single value.
*
* @return Double of function result from evaluation at current point.
*/
public abstract Double evaluate() throws RemoteException;
/**
* Returns an ArrayList of String for the names of each input parameter. This
* allows the class creator to make the names meaningful to a user instead of
* X1, X2, ...
*
* @return ArrayList<String> of names for each input parameter
*/
public ArrayList<String> getInputNames() throws RemoteException;
/**
* Returns the current value of each input for the function. All function
* inputs are treated as Double
*
* @return ArrayList<Double> of values representing current point.
*/
public ArrayList<Double> getInputValues() throws RemoteException;
/**
* Gets the full package qualified classname of the currently set optimization
* technique
*
* @return String representing package qualified classname of optimization
* technique
*/
public String getOptimizationTechnique() throws RemoteException;
/**
* Gets the function output value resulting from the evaluation of the current
* input set.
*
* @return Double representing function result
*/
public Double getOutput() throws RemoteException;
/**
* Gets the name of the function
*
* @return String representing the user friendly name of the function.
*/
public String getTitle() throws RemoteException;
/**
* Gets the direction of the optimization problem. If true then we have a
* minimization problem otherwise a maximization problem
*
* @return boolean value of true if minimization
*/
public boolean isMinimize() throws RemoteException;
public String getOptimizersString() throws RemoteException;
/**
* Optimizes uses the Strategy interface to calculate the optimal value by
* passing a function to calculateOptimizationValues().
*
* @return Double representing best achieved function value.
*/
public Double optimize() throws RemoteException;
/**
* Sets the optimization technique (which implements the strategy interface).
*
* @param s
* Represents the optimization technique to be passed to the method
*/
public void setStrategy(Strategy s) throws RemoteException;
/**
* Set the current set of input names for the input parameters to the
* inputNames passed as a parameter.
*
* @param inputNames
* ArrayList<String> of names for set of input parameters for the
* function.
*/
public void setInputNames(ArrayList<String> inputNames) throws RemoteException;
/**
* Sets the current value of the input set for the function.
*
* @param inputValues
* ArrayList<Double> representing the value of each input parameter.
* The input set is assumed to be all Doubles.
*/
public void setInputValues(ArrayList<Double> inputValues) throws RemoteException;
/**
* Sets function to be a minimization or a maximization
*
* @param minimize
* boolean of true if minimization
*/
public void setMinimize(boolean minimize) throws RemoteException;
/**
* Sets internal field to the value of the passed parameter which represents
* the package qualified class name of the optimization technique to use.
*
* @param optimizationTechnique
* String representing package and class name of the optimizer to use
* for the problem.
*/
public void setOptimizationTechnique(String optimizationTechnique) throws RemoteException;
/**
* Sets the value of the function result.
*
* @param output
* Double instance of function result
*/
public void setOutput(Double output) throws RemoteException;
/**
* Sets the user friendly name of the function
*
* @param title
* String representing function name
*/
public void setTitle(String title) throws RemoteException;
/**
* Registers the observers to the function
*
* @param o
* @throws RemoteException
*/
public abstract void registerObserver(Observer o) throws RemoteException;
/**
* Removes an observer from the function
*
* @param o
* @throws RemoteException
*/
public abstract void removeObserver(Observer o) throws RemoteException;
/**
* Notifies the observers when changes in the function values have occurred
*
* @throws RemoteException
*/
public abstract void notifyObservers() throws RemoteException;
/**
* Get the environmental variables that will be used to create individual
* functions
*
* @return
* @throws RemoteException
*/
public String getEnvironmentVariables() throws RemoteException;
}
| true
|
71d51315954826521995dba58488765af0270b54
|
Java
|
chandrabipin/dsAndAlgos
|
/src/com/bipin/algo/greedy/G03ComparatorDensityDesc.java
|
UTF-8
| 336
| 2.9375
| 3
|
[] |
no_license
|
package com.bipin.algo.greedy;
import java.util.*;
public class G03ComparatorDensityDesc implements Comparator<G03GoldType>{
public int compare(G03GoldType g1, G03GoldType g2){
// since density is in double
// and we want to reverse the order -> multiply by -1
return -1*Double.compare(g1.getDensity(), g2.getDensity());
}
}
| true
|
5cd2859fdb9f07d4f5130ed09a9e57e68f63504b
|
Java
|
ElectroMechByte/brighterBeeProject
|
/src/main/java/com/projectBee/brighterBee/BrighterBeeApplication.java
|
UTF-8
| 659
| 1.875
| 2
|
[] |
no_license
|
package com.projectBee.brighterBee;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("com.projectBee")
@EnableAutoConfiguration
@EntityScan(basePackages = {"com.projectBee.model"}) // scan JPA entities
public class BrighterBeeApplication {
public static void main(String[] args) {
SpringApplication.run(BrighterBeeApplication.class, args);
}
}
| true
|
b80fa2e8fea8e336ef072ba92059cac9a7394101
|
Java
|
agarrharr/code-rush-101
|
/something-learned/Algorithms and Data-Structures/java/sorting/AlmostSortedArrSearch.java
|
UTF-8
| 367
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
package sorting;
/**
* Given an array which is sorted, but after sorting some elements are moved to
* either of the adjacent positions, i.e., arr[i] may be present at arr[i+1] or
* arr[i-1].
*
* Link: http://www.geeksforgeeks.org/search-almost-sorted-array/
*
* @author shivam.maharshi
*/
public class AlmostSortedArrSearch {
// TODO:
}
| true
|
e01c24c00802e947cb498fde9d25cfd679d86100
|
Java
|
Zweanslord/Stersectas
|
/src/main/java/stersectas/domain/common/Id.java
|
UTF-8
| 865
| 2.34375
| 2
|
[] |
no_license
|
package stersectas.domain.common;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.MappedSuperclass;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.experimental.Accessors;
import stersectas.documentation.HibernateConstructor;
@MappedSuperclass
@Embeddable
@EqualsAndHashCode
@Accessors(fluent = true)
public abstract class Id implements Serializable {
private static final long serialVersionUID = 1L;
private static final int MINIMUM_LENGTH = 10;
@Column(nullable = false, unique = true)
@Getter private String id;
@HibernateConstructor
protected Id() {
}
public Id(String id) {
if (id.trim().length() < MINIMUM_LENGTH) {
throw new IllegalArgumentException(String.format("Id must be at least %s long.", MINIMUM_LENGTH));
}
this.id = id;
}
}
| true
|
e5f3f65ffa7ed77a9878d95ab248fba9776aff75
|
Java
|
rajnibebo/warfile
|
/Generics/src/com/rajni/wildcards/TypeParameter.java
|
UTF-8
| 1,962
| 3.1875
| 3
|
[] |
no_license
|
/**
*
*/
package com.rajni.wildcards;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author rajni.ubhi
*
*/
public class TypeParameter {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Object obj = "one";
List<Object> objs = Arrays.<Object>asList("Rajni",1,3,502.23);
List<Integer> ints = Arrays.asList(1,3);
System.out.println(objs.contains(objs));
System.out.println(objs.containsAll(ints));
System.out.println(ints.contains(obj));
System.out.println(ints.containsAll(ints));
//List<?> types = new ArrayList<?>();
ArrayList<String> str = new ArrayList<>();
str.add("Rajni");
str.add("Ubhi");
ArrayList<String> str1 = new ArrayList<>();
str1.add("Rajni1");
str1.add("Ubhi1");
ArrayList<Integer> str3 = new ArrayList<>();
str3.add(1);
str3.add(2);
List<List<String>> list = new ArrayList<List<String>>();
list.add(str);
list.add(str1);
List<List<String>> list1 = new ArrayList<List<String>>();
list1.add(str);
list1.add(str1);
List<List<Integer>> list3 = new ArrayList<List<Integer>>();
list3.add(str3);
list3.add(str3);
List<Object> listObj = TypeParameter.<Object>listE(list,list1,list3);
List<Number> nums = new ArrayList<Number>();
nums.add(3);
nums.add(25);
List<Object> objects = new ArrayList<Object>();
objects.add("Rajni");
objects.add(25);
List<? super Integer> nums1 = nums;
nums1.add(1);
System.out.println(objects);
}
public static void reverse(List<?> list) {
List<Object> objs = new ArrayList<>(list);
for(int i = 0 ; i < list.size() ; i++) {
//list.set(i, objs.get(list.size()-i-1));
}
}
public static <T> List<T> listE(T... ts) {
List<T> list = new ArrayList<>();
for(T t : ts) {
list.add(t);
}
return list;
}
}
| true
|