text stringlengths 10 2.72M |
|---|
package raghad12_1_2016.spy;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class SignIn extends AppCompatActivity {
private EditText etEmail;
private EditText etPassword;
private Button btnForgotPassword;
private Button btnLetsSpy;
private FirebaseAuth auth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
if (FirebaseAuth.getInstance().getCurrentUser()!=null)
{
Intent i= new Intent(SignIn.this,AddNumbers.class);
startActivity(i);
finish();
}
etEmail=(EditText)findViewById(R.id.etEmail);
etPassword=(EditText)findViewById(R.id.etPassword);
btnForgotPassword=(Button)findViewById(R.id.btnForgotPassword);
btnLetsSpy=(Button)findViewById(R.id.btnLetsSpy);
auth=FirebaseAuth.getInstance();
eventHandlrer();
}
private void dataHandler()
{
boolean isok=true;
String stEmail=etEmail.getText().toString();
String stPassword=etPassword.getText().toString();
if (stEmail.length()==0){
etEmail.setError("Wrong Email");
isok=false;}
if (stPassword.length()==0) {
etPassword.setError("Wrong Password");
isok = false;}
if (isok)
signIn(stPassword,stEmail);
}
/**
* puttind event handler for (listeners)
*/
private void eventHandlrer()
{
btnForgotPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
dataHandler();
}
});
btnLetsSpy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
Intent i= new Intent(SignIn.this, AddNumbers.class);
startActivity(i);
}
});
dataHandler();
}
private void signIn(String email, String passw) {
auth.signInWithEmailAndPassword(email,passw).addOnCompleteListener(SignIn.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
Toast.makeText(SignIn.this, "signIn Successful.", Toast.LENGTH_SHORT).show();
Intent i= new Intent(SignIn.this, AddNumbers.class);
startActivity(i);
// Intent intent=new Intent(LogInActivity.this,MainFCMActivity.class);
// startActivity(intent);
// finish();
}
else
{
Toast.makeText(SignIn.this, "signIn failed."+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
task.getException().printStackTrace();
}
}
});
}
}
|
/*
Copyright (c) 2014, Student group C in course TNM082 at Linköpings University
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.example.kartela;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class DisplaySettingsActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getFragmentManager().beginTransaction().replace(android.R.id.content,
new SettingsActivity()).commit();
}
//Dubbelt bakåtklick för att avsluta appen.
private boolean doubleBackToExitPressedOnce = false;
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Tryck på tillbaka igen för att avsluta", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
} |
package com.examples.io.arrays;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class DuplicateNumber {
public static void main(String[] args) {
int array [] = {5,6,6,7,2,1,7};
findDuplicate(array);
}
public static void findDuplicate(int [] array) {
List<Integer> list = new ArrayList<>();
for(int i = 0;i<array.length;i++) {
int index = Math.abs(array[i]) -1;
if(array[index] < 0) {
list.add(index+1);
} else {
array[index] = -array[index];
System.out.println(array[index]);
}
}
System.out.println(list.toString());
}
}
|
import java.util.Scanner;
import javax.swing.JOptionPane;
public class ExerciseTwoPtTwo {
public static void main(String[]args){
Scanner input= new Scanner(System.in);
String name = JOptionPane.showInputDialog("What is your name?");
String message= String.format("Hello, my name is %s.",name);
JOptionPane.showMessageDialog(null,message);
}
}
|
package edu.uiowa.icts.spring;
import java.util.Collection;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
public class Security {
public static boolean hasRole( String role ) {
Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
Collection<? extends GrantedAuthority> currentAuthorities = currentAuth.getAuthorities();
for ( GrantedAuthority ga : currentAuthorities ) {
if ( ga.getAuthority().equals( role ) ) {
return true;
}
}
return false;
}
}
|
package vistas;
import java.util.Observable;
import objetos.aeronaves.Algo42;
import ar.uba.fi.algo3.titiritero.ControladorJuego;
/*
* Vista del Algo42
*/
public class VistaAlgo42 extends VistaAeronave {
public VistaAlgo42(Algo42 algo42, ControladorJuego controlador) {
super(algo42, controlador);
}
@Override
public void update(Observable objeto, Object args) {
if (this.getObjeto().estaDestruido()) {
this.dibujarExplosion();
this.removerVistaDeControlador();
} else if (this.getObjeto().getCantidadEnergia() <= 0) {
dibujarExplosion();
} else {
this.setearImagen();
}
}
@Override
public void setearImagen() {
if (this.getObjeto().getVelocidad().getComponenteY() > 0) {
this.setNombreArchivoImagen("../images/aeronaves/algo42Abajo.png");
} else {
this.setNombreArchivoImagen("../images/aeronaves/algo42Arriba.png");
}
}
}
|
package com.jacaranda.services;
import java.util.Collections;
import java.util.List;
import org.springframework.stereotype.Service;
import com.jacaranda.entity.Customer;
import com.jacaranda.entity.Film;
import com.jacaranda.entity.comparator.ComparatorCustomerFullName;
import com.jacaranda.entity.comparator.ComparatorCustomerId;
import com.jacaranda.entity.comparator.ComparatorFilmCategory;
import com.jacaranda.entity.comparator.ComparatorFilmId;
import com.jacaranda.entity.comparator.ComparatorFilmOriginalTitle;
import com.jacaranda.entity.comparator.ComparatorFilmYear;
@Service
public class SortService {
public List<Customer> orderCustomers(List<Customer> customers, String param){
if(param.equalsIgnoreCase("fullName")) {
Collections.sort(customers, new ComparatorCustomerFullName());
}
else {
Collections.sort(customers, new ComparatorCustomerId());
}
return customers;
}
public List<Film> orderFilms(List<Film> films, String param){
if(param.equalsIgnoreCase("categoryId")) {
Collections.sort(films, new ComparatorFilmCategory());
}
else if(param.equalsIgnoreCase("originalTitle")) {
Collections.sort(films, new ComparatorFilmOriginalTitle());
}
else if(param.equalsIgnoreCase("year")) {
Collections.sort(films, new ComparatorFilmYear());
}
else {
Collections.sort(films, new ComparatorFilmId());
}
return films;
}
}
|
public class Parallelogram {
String name;
double length;
double height;
double result;
Parallelogram(String name,double length, double height) {
this.name = name;
this.length = length;
this.height = height;
}
public void width() {
double result = length * height;
System.out.println("넓이 : " + result+"\n");
}
}
|
package ir.shayandaneshvar.jottery.models;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.List;
@Entity
@Data
@EqualsAndHashCode(exclude = {"customer"})
@NoArgsConstructor
@Table(name = "levels")
public class Level {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String tag;
private Integer minimum;
private Integer maximum;
@OneToMany(mappedBy = "level",cascade = CascadeType.ALL)
private List<Customer> customer;
} |
package f.star.iota.milk.ui.mmonly.only;
import android.os.Bundle;
import f.star.iota.milk.base.ScrollImageFragment;
public class OnlyFragment extends ScrollImageFragment<OnlyPresenter, OnlyAdapter> {
public static OnlyFragment newInstance(String url) {
OnlyFragment fragment = new OnlyFragment();
Bundle bundle = new Bundle();
bundle.putString("base_url", url);
bundle.putString("page_suffix", ".html");
fragment.setArguments(bundle);
return fragment;
}
@Override
protected OnlyPresenter getPresenter() {
return new OnlyPresenter(this);
}
@Override
protected OnlyAdapter getAdapter() {
return new OnlyAdapter();
}
@Override
protected boolean isHideFab() {
return false;
}
}
|
package com.example.landrouter.config;
import com.example.landrouter.service.algorithms.custom.CustomGraph;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import one.util.streamex.StreamEx;
import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DefaultUndirectedGraph;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
@Configuration
@Slf4j
public class LandGraphConfiguration {
@Bean
@ConditionalOnProperty(name = "routing-algorithm", havingValue = "jgrapht-dijkstra")
public Graph<String, DefaultEdge> jGraph() {
log.info("Initializing jGraph graph...");
List<CountryItem> countries = loadCountryData();
DefaultUndirectedGraph<String, DefaultEdge> graph = new DefaultUndirectedGraph<>(DefaultEdge.class);
StreamEx.of(countries)
.map(CountryItem::getCca3)
.forEach(graph::addVertex);
StreamEx.of(countries)
.mapToEntry(CountryItem::getCca3, CountryItem::getBorders)
.flatMapValues(Collection::stream)
.forKeyValue(graph::addEdge);
return graph;
}
@Bean
@ConditionalOnProperty(name = "routing-algorithm", havingValue = "custom-dijkstra")
public CustomGraph<String> customGraph() {
log.info("Initializing custom graph...");
List<CountryItem> countries = loadCountryData();
var graph = new CustomGraph<String>();
StreamEx.of(countries)
.map(CountryItem::getCca3)
.forEach(graph::addNode);
StreamEx.of(countries)
.mapToEntry(CountryItem::getCca3, CountryItem::getBorders)
.flatMapValues(Collection::stream)
.forKeyValue(graph::addEdge);
return graph;
}
@SneakyThrows
private List<CountryItem> loadCountryData() {
InputStream is = LandGraphConfiguration.class.getClassLoader().getResourceAsStream("countries.json");
List<CountryItem> countries = new ObjectMapper().readerFor(new TypeReference<List<CountryItem>>() {})
.readValue(is);
log.info("Loaded {} countries", countries.size());
return countries;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
private static class CountryItem {
private String cca3;
private List<String> borders;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ChessLeague.ChessLib;
/**
*
* @author D3zmodos
*/
import java.awt.Point;
import java.awt.Image;
import javax.swing.ImageIcon;
import java.util.Iterator;
import java.util.LinkedList;
public class ChessPiece {
private LinkedList<Point> possibleMoves;
private int piece;
private final ChessGame game;
private final ChessPlayer owner;
private int moveCount;
private int x = 0;
private int y = 0;
private Point previousLoc;
ChessPiece(int pieceType, ChessPlayer pieceOwner, int startX, int startY){
piece = pieceType;
owner = pieceOwner;
game = owner.game();
moveCount = 0;
x = startX;
y = startY;
previousLoc = new Point(x,y);
if(pieceType != ChessGame.PIECE_TYPE_PAWN
&& pieceType != ChessGame.PIECE_TYPE_BISHOP
&& pieceType != ChessGame.PIECE_TYPE_KNIGHT
&& pieceType != ChessGame.PIECE_TYPE_ROOK
&& pieceType != ChessGame.PIECE_TYPE_QUEEN
&& pieceType != ChessGame.PIECE_TYPE_KING){
throw new IllegalArgumentException("Invalid chess piece type specified.");
}
updateMoves();
}
void move(int newX, int newY){
previousLoc.x = x;
previousLoc.y = y;
moveCount++;
x = newX;
y = newY;
}
void updateMoves(){
possibleMoves = game.listMoves(this);
}
void remove(){
owner.removePiece(this);
}
void promote(int pieceType){
piece = pieceType;
//Recalculate Possible moves
possibleMoves = game.listMoves(this);
}
public LinkedList<Point> possibleMoves(){
return (LinkedList<Point>)possibleMoves.clone();
}
public Image getImage(){
String filename = "images/";
if(owner == game.PLAYER_WHITE){
filename += "white";
}else if(owner == game.PLAYER_BLACK){
filename += "black";
}else{
return null;
}
switch(piece){
case (ChessGame.PIECE_TYPE_PAWN):
filename += "pawn";
break;
case (ChessGame.PIECE_TYPE_BISHOP):
filename += "bishop";
break;
case (ChessGame.PIECE_TYPE_KNIGHT):
filename += "knight";
break;
case (ChessGame.PIECE_TYPE_ROOK):
filename += "rook";
break;
case (ChessGame.PIECE_TYPE_QUEEN):
filename += "queen";
break;
case (ChessGame.PIECE_TYPE_KING):
filename += "king";
break;
default:
return null;
}
return new ImageIcon(filename+".png").getImage();
}
public int previousX(){
return previousLoc.x;
}
public int previousY(){
return previousLoc.y;
}
public int x(){
return x;
}
public int y(){
return y;
}
public int piece(){
return piece;
}
public ChessPlayer owner(){
return owner;
}
public int moveCount(){
return moveCount;
}
void moveMinusOne(){
moveCount--;
}
public boolean hasMoved(){
return moveCount != 0;
}
public boolean canAccessPoint(int x, int y){
Iterator<Point> j = possibleMoves.iterator();
while(j.hasNext()){
Point p = j.next();
if(p.x == x && p.y == y){
return true;
}
}
return false;
}
}
|
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.sql.SQLException;
import java.util.*;
public class ViewAssignmentControl {
private DataManager dataManager;
public ViewAssignmentControl(DataManager dm) {
this.dataManager = dm;
}
public void downloadFile(String assignmentName) {
Assignment assignment = retrieveAssignmentFile(assignmentName);
try {
InputStream is = assignment.assignmentFile.getBinaryStream();
ReadableByteChannel rbc = Channels.newChannel(is);
FileOutputStream fos = new FileOutputStream(System.getProperty("user.home") + "/Downloads/" + assignment.assignmentName);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
} catch (SQLException e) {
}
}
public ArrayList<String> getAssignmentNames(){
return dataManager.requestAssignmentNames();
}
public Assignment retrieveAssignmentFile(String assignmentName) {
return dataManager.requestAssignment(assignmentName);
}
}
|
import org.graphstream.graph.Graph;
import org.graphstream.graph.Node;
import java.util.ArrayList;
import java.util.Collections;
/**
* Created by Gizem on 03.03.2017.
*/
public class DPBEAPopulation {
private ArrayList<DPBEAParent> parents;
private final DPBEAGraph dpbeaGraph;
private final Graph graph;
/* Constructor */
public DPBEAPopulation(DPBEAGraph dpbeaGraph) {
this.parents = new ArrayList<>();
this.dpbeaGraph = dpbeaGraph;
graph = dpbeaGraph.getGraph();
}
public void initializePopulation(int numberofParents) {
for (int i = 0; i < numberofParents; i++) {
DPBEAParent newParent = createParent();
parents.add(newParent);
}
}
public void initializePopulation2(int numberofParents) {
for (int i = 0; i < numberofParents; i++) {
DPBEAParent newParent = new DPBEAParent();
graph.getNodeSet().forEach(node -> {
ArrayList<Node> nodes = new ArrayList<>();
nodes.add(node);
DPBEAColor color = new DPBEAColor(nodes);
newParent.addColor(color);
});
Collections.shuffle(newParent.getColors());
parents.add(newParent);
}
}
public DPBEAParent createParent(){
DPBEAParent newParent = new DPBEAParent();
graph.getNodeSet().forEach(node -> {
if(newParent.numberofColors() == 0){
ArrayList<Node> nodes = new ArrayList<Node>();
nodes.add(node);
DPBEAColor color = new DPBEAColor(nodes);
newParent.addColor(color);
}
else {
Collections.shuffle(newParent.getColors());
boolean isPlace = true;
for (DPBEAColor color: newParent.getColors()) {
isPlace = true;
for(Node node2 : color.getNodes()){
if(node.hasEdgeBetween(node2)){
isPlace = false;
break;
}
}
if (isPlace){
color.addNode(node);
break;
}
}
if(!isPlace){
ArrayList<Node> nodes = new ArrayList<Node>();
nodes.add(node);
DPBEAColor color = new DPBEAColor(nodes);
newParent.addColor(color);
}
}
});
return newParent;
}
public ArrayList<DPBEAParent> getParents(){
return parents;
}
}
|
package com.example.event_project.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User implements UserDetails {
public User(String login, String email, String showName, String password) {
this.login = login;
this.password = password;
this.email = email;
this.showName = showName;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String login;
private String password;
@Column(unique = true)
private String email;
@Column(unique = true)
private String showName;
@ManyToMany(fetch = FetchType.EAGER)
private Set<Role> roles = new HashSet<>();
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
@JsonIgnore
@ToString.Exclude
private List<Participant> participant;
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
@JsonIgnore
@ToString.Exclude
private List<Organizer> organizer;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles.stream()
.map(role -> new SimpleGrantedAuthority(role.getName()
.name()))
.collect(Collectors.toList());
}
@Override
public String getUsername() {
return login;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
|
package com.adventurpriseme.castme.TriviaGame;
/**
* Base enumeration for enumerating strings.
* <p/>
* Created by Timothy on 1/3/2015.
* Copyright 1/3/2015 adventurpriseme.com
*/
public enum EBaseStringEnum
{
E_INVALID ("invalid"); // This must go first
// **************************
// Functionality to provite toString() ability to get string values for the enums
// **************************
private final String text;
private EBaseStringEnum (final String text)
{
this.text = text;
}
/**
* Get the enumeration that matches the given string.
*
* @param str
* (required) String whose enum we need to find
*
* @return ETriviaMessagesToServer The enum whose string value matches str
*/
public static EBaseStringEnum getEnumFromString (String str)
{
for (EBaseStringEnum eMsg : EBaseStringEnum.values ())
{
if (str.equals (eMsg.toString ()))
{
return eMsg;
}
}
return null;
}
@Override
public String toString ()
{
return text;
}
}
|
package com.wang.search.service;
/**
* 基本service工具类
*
* @author wangjunhao
* @version 1.0
* @date 2020/6/4 23:09
* @since JDK 1.8
*/
public class BaseService {
}
|
package org.growit.kz.dao;
import org.growit.kz.model.UsersEntity;
import java.util.List;
/**
* Created by Администратор on 10.11.2014.
*/
public interface UserDAO {
public List<UsersEntity> getAllRecordsUserEntity();
public void addRecordsUsers(UsersEntity usersEntity);
public void deleteRecordUsers(UsersEntity usersEntity);
public UsersEntity findByIdUser(int id);
public String updateRecordsUsers(UsersEntity usersEntity);
}
|
package com.cisc181.eNums;
public enum eTitle {
Professor, President, Janitor
}
|
package co.sblock.chat;
import co.sblock.Sblock;
import co.sblock.chat.ai.CleverHal;
import co.sblock.chat.ai.Halculator;
import co.sblock.chat.channel.Channel;
import co.sblock.chat.message.Message;
import co.sblock.chat.message.MessageBuilder;
import co.sblock.events.event.SblockAsyncChatEvent;
import co.sblock.module.Module;
import co.sblock.users.Users;
import co.sblock.utilities.DummyPlayer;
import co.sblock.utilities.PermissionUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import net.md_5.bungee.api.ChatColor;
public class Chat extends Module {
private final ChannelManager channelManager;
private final DummyPlayer buffer;
private Language lang;
private Users users;
private CleverHal cleverHal;
private Halculator halculator;
public Chat(Sblock plugin) {
super(plugin);
this.channelManager = new ChannelManager(this);
this.buffer = new DummyPlayer();
// Permission to use >greentext
PermissionUtils.getOrCreate("sblock.chat.greentext", PermissionDefault.TRUE);
// Legacy support: old node as parent
PermissionUtils.addParent("sblock.chat.greentext", "sblockchat.greentext");
// Permission for messages to automatically color using name color
PermissionUtils.getOrCreate("sblock.chat.color", PermissionDefault.FALSE);
// Legacy support: old node as parent
PermissionUtils.getOrCreate("sblockchat.color", PermissionDefault.FALSE);
PermissionUtils.addParent("sblock.chat.color", "sblockchat.color", PermissionDefault.FALSE);
// Permission to bypass chat filtering
PermissionUtils.addParent("sblock.chat.unfiltered", "sblock.felt");
PermissionUtils.addParent("sblock.chat.unfiltered", "sblock.spam");
// Permission to be recognized as a moderator in every channel
PermissionUtils.addParent("sblock.chat.channel.moderator", "sblock.felt");
// Permission to be recognized as an owner in every channel
PermissionUtils.addParent("sblock.chat.channel.owner", "sblock.denizen");
// Permission to have name a certain color
Permission parentPermission;
Permission childPermission;
for (ChatColor chatColor : ChatColor.values()) {
// Legacy support: old node as parent
String color = chatColor.name().toLowerCase();
parentPermission = PermissionUtils.getOrCreate("sblockchat." + color, PermissionDefault.FALSE);
childPermission = PermissionUtils.getOrCreate("sblock.chat.color." + color, PermissionDefault.FALSE);
childPermission.addParent(parentPermission, true);
}
}
@Override
protected void onEnable() {
this.lang = this.getPlugin().getModule(Language.class);
this.users = this.getPlugin().getModule(Users.class);
this.cleverHal = new CleverHal(this.getPlugin());
this.halculator = new Halculator(this.getPlugin());
this.channelManager.loadAllChannels();
this.channelManager.createDefaultSet();
}
@Override
protected void onDisable() {
this.channelManager.saveAllChannels();
}
public ChannelManager getChannelManager() {
return this.channelManager;
}
public MessageBuilder getHalBase() {
return new MessageBuilder(this.getPlugin()).setSender(lang.getValue("core.bot_name"))
.setNameClick("/report ").setNameHover(lang.getValue("core.bot_hover"))
.setChannel(this.channelManager.getChannel("#"));
}
public CleverHal getHal() {
return this.cleverHal;
}
/**
* @return the halculator
*/
public Halculator getHalculator() {
return this.halculator;
}
@Override
public boolean isRequired() {
return true;
}
@Override
public String getName() {
return "Chat";
}
public boolean testForMute(Player sender) {
return this.testForMute(sender, "Mute test.", "@test@");
}
public synchronized boolean testForMute(Player sender, String msg, String channelName) {
if (sender == null || msg == null || channelName == null) {
throw new IllegalArgumentException("Null values not allowed for mute testing!");
}
if (Bukkit.getPluginManager().isPluginEnabled("GriefPrevention")
&& me.ryanhamshire.GriefPrevention.GriefPrevention.instance.dataStore.isSoftMuted(sender.getUniqueId())) {
return true;
}
Channel channel = this.getChannelManager().getChannel(channelName);
if (channel == null) {
throw new IllegalArgumentException("Given channel does not exist!");
}
MessageBuilder builder = new MessageBuilder(this.getPlugin())
.setSender(this.users.getUser(sender.getUniqueId())).setChannel(channel)
.setMessage(msg).setChannel(channel);
Message message = builder.toMessage();
SblockAsyncChatEvent event = new SblockAsyncChatEvent(false, sender, message, false);
// Add a dummy player so WG doesn't cancel the event if there are no recipients
event.getRecipients().add(this.buffer);
Bukkit.getPluginManager().callEvent(event);
return event.isCancelled() && !event.isGlobalCancelled();
}
}
|
package com.xnarum.thonline.entity.idd002;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@XmlAccessorType(XmlAccessType.FIELD)
public class WelcomeQueryResponseBody {
// @XmlElement(name="THPrimaryICNo")
// private String icNo;
//
@XmlElement(name="THPrimaryAcct", nillable=true)
private String accountNo;
// @XmlElement(name="THPrimaryName")
// private String name;
//
@XmlElement(name="THPrimaryBalance", nillable=true)
private String balance;
// @XmlElement(name="THPhoneNo")
// private String phoneNumber;
//
// @XmlElement(name="THEmail")
// private String email;
//
@XmlElement(name="THHajjStatus", nillable=true)
private String hajjStatus;
@XmlElement(name="THHajjYear", nillable=true)
private String hajjYear;
// @XmlElement(name="THTrusteeCount")
// private int trusteeCount;
//
@XmlElement(name="Records", nillable=true)
private List<WelcomeQueryResponseRecord> records;
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getIcNo() {
// return icNo;
// }
// public void setIcNo(String icNo) {
// this.icNo = icNo;
// }
public String getBalance() {
return balance;
}
public void setBalance(String balance) {
this.balance = balance;
}
// public String getPhoneNumber() {
// return phoneNumber;
// }
//
// public void setPhoneNumber(String phoneNumber) {
// this.phoneNumber = phoneNumber;
// }
public String getHajjStatus() {
return hajjStatus;
}
public void setHajjStatus(String hajjStatus) {
this.hajjStatus = hajjStatus;
}
public String getHajjYear() {
return hajjYear;
}
public void setHajjYear(String hajjYear) {
this.hajjYear = hajjYear;
}
// public int getTrusteeCount() {
// return trusteeCount;
// }
//
// public void setTrusteeCount(int trusteeCount) {
// this.trusteeCount = trusteeCount;
// }
public List<WelcomeQueryResponseRecord> getRecords() {
return records;
}
public void setRecords(List<WelcomeQueryResponseRecord> records) {
this.records = records;
}
}
|
package com.Gacy.gacyProject;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Map;
public class InicioAppActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
private EditText mCorreoLogin, mContrasenaLogin;
private TextView aRegistro;
private Button mBotonLogin;
private DatabaseReference mAnfitrionReference;
private String userType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inicio_app);
//estas lineas se inicializan liganolas con el edit text de la IU
mCorreoLogin = (EditText) findViewById(R.id.correoLogin);
mContrasenaLogin = (EditText) findViewById(R.id.contrasenaLogin);
mBotonLogin = (Button) findViewById(R.id.botonInicioS);
aRegistro = (TextView) findViewById(R.id.accesoRegistro);
mAuth = FirebaseAuth.getInstance(); // verifica si tiene inicio de sesión o no
//metodo para obtener el usuario
firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();//obtiene la info del usuario actual.
mAnfitrionReference = FirebaseDatabase.getInstance().getReference().child("Usuario");
getTipoUsuario();
if(user != null){
if(userType == "Anfitrion"){
//Intent intent = new Intent(Register.this, AnfitrionMapsActivity.class);
Intent intent = new Intent(getApplicationContext(), MenuDrawerActivity.class);
startActivity(intent);
finish();
return;
}else{
//Intent intent = new Intent(Register.this, AnfitrionMapsActivity.class);
Intent intent = new Intent(getApplicationContext(), AnfitrionMapsActivity.class);
startActivity(intent);
finish();
return;
}
}
}
};
//metodo para el inicio de sesión
mBotonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//obtener los datos que ingreso el usuario : correo e email
String correo = mCorreoLogin.getText().toString();
String contrasena = mContrasenaLogin.getText().toString();
// se trata de hacer el login con correo y contraeña
mAuth.signInWithEmailAndPassword(correo,contrasena).addOnCompleteListener(InicioAppActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
//si no se se encuentra el usuario con esos datos no se puede iniciar sesión
if(!task.isSuccessful()){
//mensaje al usuario
Toast.makeText(InicioAppActivity.this, "Error en el inicio de sesión", Toast.LENGTH_SHORT).show();
}
}
});
}
});
aRegistro.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Register.class);
startActivity(intent);
}
});
}
//metodo para parar la accion
@Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthListener);
}
@Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthListener);
}
private void getTipoUsuario(){
mAnfitrionReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String,Object>) dataSnapshot.getValue();
if(map.get("Anfitrion") != null){
userType = "Anfitrion";
//Toast.makeText(InicioAppActivity.this, userType, Toast.LENGTH_SHORT).show();
}
if(map.get("Ciclista") != null){
userType = "Ciclista";
//Toast.makeText(InicioAppActivity.this, userType, Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
|
package JavaBean;
import java.sql.*;
public class UserDao {
public Boolean logon(User user){
Boolean exist=true;
Connection conn=DButil.getConn();
PreparedStatement pstmt=null;
try{
User user1=checkLogin(user.getId());
if (user!=user1){
String sql="INSERT INTO `user`(`id`,`password`) VALUES (?,?);";
pstmt=conn.prepareStatement(sql);
pstmt.setString(1,user.getId());
pstmt.setString(2,user.getPassword());
pstmt.executeUpdate();
exist=false;
}
}catch (SQLException e){
System.out.println("添加账户异常:"+e.getMessage());
}finally {
DButil.release(pstmt,conn);
}
return exist;
}
//检验账号密码是否正确,按账号找对象
public User checkLogin(String id){
Connection conn =DButil.getConn();
Statement stmt =null;
ResultSet rs=null;
User user=null;
String sql="select * from user where id='" +id+ "'";
try{
stmt =conn.createStatement();
rs=stmt.executeQuery(sql);
if(rs.next()){
user=new User();
user.setId(rs.getString("id"));
user.setPassword(rs.getString("password"));
user.setPower(rs.getString("power"));
}
}catch(SQLException e){
System.out.println("根据id找账户异常:"+e.getMessage());
}finally {
DButil.release(rs,stmt,conn);
}
return user;
}
}
|
package negocio.vo;
import java.time.LocalDate;
/**
* @author eserrano
*
*/
public class Persona {
private String nombre;
private String dni;
private LocalDate fechaNacimiento;
private Float peso;
private Boolean titulado;
public Persona() {
super();
// TODO Auto-generated constructor stub
}
public Persona(String nombre, String dni, LocalDate fechaNacimiento, Float peso, Boolean titulado) {
this.nombre = nombre;
this.dni = dni;
this.fechaNacimiento = fechaNacimiento;
this.peso = peso;
this.titulado = titulado;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDni() {
return dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public LocalDate getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(LocalDate fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public Float getPeso() {
return peso;
}
public void setPeso(Float peso) {
this.peso = peso;
}
public Boolean getTitulado() {
return titulado;
}
public void setTitulado(Boolean titulado) {
this.titulado = titulado;
}
}
|
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Setting up match...");
boolean keepPlaying = true;
// set up board and pieces
Board board = new Board();
Player p1 = new Player('W');
Player p2 = new Player('B');
board.displayBoard();
while (keepPlaying) {
boolean won = false;
board.takeTurn(p1, p2);
won = board.isWon(p1, p2);
board.takeTurn(p2, p1);
won = board.isWon(p1, p2);
/* if (board.checkCheck()) {
* board.checkCheckmate();
*/
if (won) {
System.out.println("Would you want to play another game?");
String input = sc.nextLine().toLowerCase();
if (input.equals("no")) {
keepPlaying = false;
}
}
}
}
}
|
package com.example.qiumishequouzhan.Utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.example.qiumishequouzhan.ExampleApplication;
import com.example.qiumishequouzhan.MainView.MainActivity;
import java.io.*;
public class FileUtils
{
public static String Bytes2String(byte[] Buffer)
{
return Bytes2String(Buffer, "UTF-8");
}
public static String Bytes2String(byte[] Buffer, String CharSet)
{
String Result = "";
if(Buffer != null)
{
try
{
Result = new String(Buffer, CharSet);
}
catch (UnsupportedEncodingException e) {
LogUitls.WriteLog("FileUtils", "Bytes2String", "{Buffer}", e);
}
}
return Result;
}
public static File WriteFile2Store(String path,String fileName,InputStream inputStream)
{
File file = null;
OutputStream output=null;
String FileName = path + File.separator + fileName;
try
{
CreateDir(path);
file = CreateFile(FileName);
if(file != null)
{
output = new FileOutputStream(file);
int length = inputStream.available();
byte buffer[] = new byte[length];
int readCount = 0;
while (readCount < length)
{
readCount += inputStream.read(buffer, readCount, length - readCount);
}
output.write(buffer);
output.flush();
output.close();
output = null;
}
}
catch (Exception e)
{
LogUitls.WriteLog("FileUtils", "WriteFile2Store", FileName, e);
}
return file;
}
private static String GetStorePath()
{
return ExampleApplication.GetInstance().getFilesDir().getPath();
}
public static String GetFileRealPath(String FileName)
{
String realPath = GetStorePath() + File.separator + FileName;
return realPath;
}
public static Bitmap ReadFile2Bitmap(String path,String fileName)
{
String Path = path + File.separator + fileName;
String RealPath = GetFileRealPath(Path);
Bitmap Result = null;
if(IsFileExist(Path)== true)
{
try
{
FileInputStream inStream = new FileInputStream(RealPath);
Result = BitmapFactory.decodeStream(inStream);
inStream.close();
inStream = null;
}
catch (Exception e)
{
LogUitls.WriteLog("FileUtils", "ReadFile2String", Path, e);
}
}
return Result;
}
private static File CreateDir(String dirName)
{
String CreatPath = GetStorePath() + File.separator + dirName;
File dir=new File(CreatPath);
if (!dir.exists())
{
dir.mkdir();
}
return dir;
}
private static File CreateFile(String fileName) throws IOException
{
String Path = GetStorePath() + File.separator + fileName;
File file = new File(Path);
file.createNewFile();
return file;
}
public static Boolean IsFileExist(String fileName)
{
String Path = GetStorePath() + File.separator + fileName;
File file = new File(Path);
return file.exists();
}
}
|
package pieza;
import excepciones.*;
import java.util.ArrayList;
import ajedrez.*;
/**
* El peon viene dado por un celda y un equipo
* @author Carlos
*
*/
public class Peon extends Pieza {
/* Constructores */
public Peon(Celda celda, Equipo equipo) {
super(celda, equipo);
this.setPuntos(1);
}
/* Metodos */
@Override
/**
* Se calculan los movimientos posibles de la Pieza Peon:
* Este metodo devuelve una lista de Celdas.
* Esta lista contiene todas las celdas en las que se puede mover la Pieza Peon.
* Segun la logica de movimiento del peon este puede moverse:
* 2 casillas hacia delante si es su primer movimiento. No puede comer con este movimiento.
* 1 casilla hacia adelante que es su movimiento normal. No puede comer con este movimiento.
* 1 casilla en diagonal delantera para poder comer. No puede moverse si no es para comer.
* Si puede comer, ademas de enlistar en la lista que retorna, tambien agrega esta celda
* en la lista de jugadas con prioridad del equipo.
*/
public ArrayList<Celda> getMovimientosPosibles() {
ArrayList<Celda> listaCelda = new ArrayList<Celda>();
boolean sePuede = true;
String blancas= Ajedrez.getSingletoneInstancia().BLANCA;
Tablero tablero = this.getTablero();// Tramos al tablero
Celda celdaActual = this.getCelda();// Celda origen donde esta la pieza actualmente
Celda mov = new Celda(0, 0);// Celda a la que se mueve el Peon
int movimientoNormal, primerMovimiento,filaInicial;
if (this.getEquipo().getNombre()==blancas) {
primerMovimiento = -2; // si el equipo es el de las piezas blancas se decrementa
movimientoNormal = -1;
filaInicial = 6;
} else {
primerMovimiento = 2; // si el equipo es el de las piezas negras se incrementa
movimientoNormal = 1;
filaInicial = 1;
}
// Movimiento Normal de a una celda
try {
mov = tablero.getCelda(celdaActual.getFila() + movimientoNormal, celdaActual.getColumna());
try {
if (mov.puedeIngresar(this)) {
listaCelda.add(mov);
}
} catch (PiezaAliadaException e) {// No puede ingresar
// System.out.println("Pieza aliada en celda no se puede ingresar");
sePuede = false;
} catch (PiezaEnemigaException e) {
// System.out.println("Pieza enemiga en celda no se puede ingresar");
sePuede = false;
}
} catch (FueraDeTableroException e) {
sePuede = false;
}
// Movimiento de a 2 celdas
try {
if (filaInicial == celdaActual.getFila()) {
if (sePuede) {
mov = tablero.getCelda(celdaActual.getFila() + primerMovimiento, celdaActual.getColumna());
try {
if (mov.puedeIngresar(this)) {//Celda vacia
listaCelda.add(mov);
}
} catch (PiezaAliadaException e) {// No puede ingresar
// System.out.println("Pieza aliada en celda no se puede ingresar");
} catch (PiezaEnemigaException e) {
// System.out.println("Pieza enemiga en celda no se puede ingresar");
}
}
}
} catch (FueraDeTableroException e) {
}
// Movimiento para comer a la DERECHA
try {
mov = tablero.getCelda(celdaActual.getFila() + movimientoNormal, celdaActual.getColumna() + 1);
try {
if (mov.puedeIngresar(this)) {//Celda vacia
// System.out.println("No hay enemigo");
}
} catch (PiezaAliadaException e) {// No puede ingresar
// System.out.println("Pieza aliada en celda no se puede ingresar");
} catch (PiezaEnemigaException e) {
this.getEquipo().agregarJugadaConPrioridad(mov, mov.getPieza(), this);// Se genera una jugada con Prioridad
listaCelda.add(mov);
}
} catch (FueraDeTableroException e) {
}
// Movimiento para comer a la IZQUIERDA
try {
mov = tablero.getCelda(celdaActual.getFila() + movimientoNormal, celdaActual.getColumna() - 1);
try {
if (mov.puedeIngresar(this)) {
}
} catch (PiezaAliadaException e) {// No puede ingresar
} catch (PiezaEnemigaException e) {
this.getEquipo().agregarJugadaConPrioridad(mov, mov.getPieza(), this);// Se genera una jugada con
// Prioridad
listaCelda.add(mov);
}
} catch (FueraDeTableroException e) {
}
return listaCelda;
}
@Override
public String toString() {
return super.toString() + "P";
}
}
|
package com.codingchili.instance.model.entity;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import com.codingchili.core.benchmarking.BenchmarkImplementationBuilder;
/**
* Benchmark implementation for spatial grid/hashing.
*/
public class GridBenchmark extends BenchmarkImplementationBuilder {
private List<Entity> entities = new ArrayList<>();
private Grid<Entity> grid;
private AtomicInteger index = new AtomicInteger(0);
public GridBenchmark(String name) {
super(name);
//add("add", this::add);
add("tick", this::tick);
//add("remove", this::remove);
// add 1k entities for default load.
for (int i = 0; i < 1000; i++) {
entities.add(new FakeVectorEntity());
}
}
@Override
public void reset(Handler<AsyncResult<Void>> future) {
index.set(0);
future.handle(Future.succeededFuture());
}
public GridBenchmark setGrid(Grid<Entity> grid) {
this.grid = grid;
entities.forEach(grid::add);
return this;
}
private void add(Future<Void> future) {
grid.add(entities.get(index()));
future.complete();;
}
private int index() {
int current = index.getAndIncrement();
if (current >= entities.size()) {
index.set(0);
current = 0;
}
return current;
}
public void tick(Future<Void> future) {
grid.update(null);
//future.complete();
}
private void remove(Future<Void> future) {
grid.add(entities.get(index()));
future.complete();
}
/**
* Supplier for a mocked vector class. The vector is unstable meaning
* the cells it is positioned within changes with each call to #cells();
* this simulates maximum activity and is the worst case scenario for the
* spatial hashing algorithm.
*/
private static class FakeVectorEntity extends PlayerCreature {
private UnstableVector vector = new UnstableVector();
public FakeVectorEntity() {
super(UUID.randomUUID().toString());
}
@Override
public Vector getVector() {
return vector;
}
}
}
|
package cn.senlin.jiaoyi.service.impl;
import cn.senlin.jiaoyi.entity.Message;
import cn.senlin.jiaoyi.mapper.MessageMapper;
import cn.senlin.jiaoyi.service.ChatService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service("chatService")
public class ChatServiceimpl implements ChatService {
@Resource
private MessageMapper messageMapper;
public List<Message> getMessage(String sendUser, String acceptUser) {
List<Message> message;
message = messageMapper.getMessage(sendUser, acceptUser);
if(message != null) {
messageMapper.updateState(sendUser, acceptUser);
}
return message;
}
public List<Message> getUser(String acceptUser) {
List<Message> message;
message = messageMapper.getUser(acceptUser);
return message;
}
public String addMessage(Message message) {
int i = messageMapper.addMessage(message);
if(i == 0) {
return "服务器错误";
} else {
return "success";
}
}
public int getCount(String acceptUser) {
String messageState = "未读";
return messageMapper.getCount(acceptUser, messageState);
}
}
|
package com.webmets.forceop.anvilgui.nms;
public class AnvilInterface {
}
|
//jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//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 3 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, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
@HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "onf.ca" }, urls = { "https?://(www\\.)?(onf|nfb)\\.ca/film/[a-z0-9\\-_]+" })
public class OnfCa extends PluginForHost {
public OnfCa(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "https://www.nfb.ca/about/important-notices/";
}
@SuppressWarnings("deprecation")
public void correctDownloadLink(final DownloadLink link) {
link.setUrlDownload(link.getDownloadURL().replace("http://", "https://"));
}
private static final String app = "a8908/v5";
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.getPage(link.getDownloadURL());
if (br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
String filename = br.getRegex("class=\"title\">([^<>\"]*?)<").getMatch(0);
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
link.setFinalFileName(Encoding.htmlDecode(filename.trim()) + ".mp4");
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
br.getPage(br.getURL() + "/player_config");
if (br.toString().equals("No htmlCode read")) {
/* Media is only available as paid-version. */
try {
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_ONLY);
} catch (final Throwable e) {
if (e instanceof PluginException) {
throw (PluginException) e;
}
}
throw new PluginException(LinkStatus.ERROR_FATAL, "This file can only be downloaded by premium users");
}
final String[] playpaths = br.getRegex("<url>(mp4:[^<>\"]*?)</url>").getColumn(0);
if (playpaths == null || playpaths.length == 0) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
final String currentdomain = new Regex(br.getURL(), "https?://(?:www\\.)?([^<>\"/]+)/").getMatch(0);
final String filmtitle_url = new Regex(br.getURL(), "/film/([^<>/\"]+)/").getMatch(0);
final String rtmpurl = "rtmp://nfbca-stream-rtmp.nfbcdn.ca/" + app;
final String pageurl = "http://www." + currentdomain + "/film/" + filmtitle_url + "/embed/player?player_mode=&embed_mode=0&context_type=film";
try {
dl = new RTMPDownload(this, downloadLink, rtmpurl);
} catch (final NoClassDefFoundError e) {
throw new PluginException(LinkStatus.ERROR_FATAL, "RTMPDownload class missing");
}
/* Setup rtmp connection */
jd.network.rtmp.url.RtmpUrlConnection rtmp = ((RTMPDownload) dl).getRtmpConnection();
rtmp.setPageUrl(pageurl);
rtmp.setUrl(rtmpurl);
/* Chose highest quality available */
final String playpath = playpaths[playpaths.length - 1];
rtmp.setPlayPath(playpath);
rtmp.setApp(app);
rtmp.setFlashVer("WIN 16,0,0,235");
rtmp.setSwfUrl("http://media1.nfb.ca/medias/flash/NFBVideoPlayer.swf");
rtmp.setResume(true);
((RTMPDownload) dl).startDownload();
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(DownloadLink link) {
}
} |
package serpis.ad;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class PedidoLinea {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private float precio;
private float unidades;
private float importe;
private int pedido;
private int articulo;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public float getPrecio() {
return precio;
}
public void setPrecio(float precio) {
this.precio = precio;
}
public float getUnidades() {
return unidades;
}
public void setUnidades(float unidades) {
this.unidades = unidades;
}
public float getImporte() {
return importe;
}
public void setImporte(float importe) {
this.importe = importe;
}
public int getPedido() {
return pedido;
}
public void setPedido(int pedido) {
this.pedido = pedido;
}
public int getArticulo() {
return articulo;
}
public void setArticulo(int articulo) {
this.articulo = articulo;
}
}
|
package com.datastax.autoloader;
import com.datastax.driver.core.CodecRegistry;
import com.datastax.driver.core.ProtocolVersion;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.exceptions.AlreadyExistsException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by alexandergauthier on 1/4/18.
*/
public class TableCreator {
public TableCreator() {
}
public String create(Session session, String tableSpace, String tableName, List<String> columns) throws Exception {
Iterator<String> it = columns.iterator();
String strColumns = new String();
while (it.hasNext()) {
strColumns += String.format("%s varchar, \n", it.next());
}
String primaryKey = columns.get(0);
String statement = String.format("create table if not exists %s.%s (\n%sprimary key (%s));", tableSpace, tableName, strColumns, primaryKey);
try {
if (session != null) {
session.execute(statement);
}
} catch (AlreadyExistsException e) {
e.getMessage();
}
return statement;
}
}
|
/*
* 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 jc.fog.presentation.commands;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jc.fog.data.DataFacade;
import jc.fog.data.DataFacadeImpl;
import jc.fog.data.DbConnector;
import jc.fog.exceptions.FogException;
import jc.fog.logic.dto.UsersDTO;
import jc.fog.logic.dto.ZipcodeDTO;
import jc.fog.presentation.Pages;
/**
*
* @author Jespe
*/
public class ShowRegisterCommand extends Command {
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws FogException
{
try
{
HttpSession session = request.getSession();
UsersDTO user = (UsersDTO)session.getAttribute("user");
// Har vi en user i session, er denne logget ind, gå til index side.
if(user != null && user.getId() > 0)
{
return Pages.INDEX;
}
DataFacade dataFacade = new DataFacadeImpl(DbConnector.getConnection());
//får fast i zipcodes.
List<ZipcodeDTO> zipcodes = dataFacade.getZipcodes();
//Fremviser form for opret bruger delen.
request.setAttribute("register", register(zipcodes));
//Siden som skal bliver vist.
return Pages.REGISTER;
}
catch(Exception e)
{
throw new FogException("Opret bruger side kan ikke vises, prøv igen.", e.getMessage(), e);
}
}
/**
* Form som bliver vist til bruger når man skal oprette sig.
* @param zipcodes - Få zipcodes som skal bruge til dropdown.
* @return
*/
private String register(List<ZipcodeDTO> zipcodes)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<form action=\"FrontController\" method=\"POST\">");
stringBuilder.append("E-mail (Brugernavn):<br /><input type=\"email\" pattern=\"[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}\" required name=\"email\" class=\"form-control\" placeholder=\"Din Email\" /><br />");
stringBuilder.append("Adgangskode<br /><input type=\"password\" required name=\"password\" class=\"form-control\" placeholder=\"Din adgangskode\" /><br />");
stringBuilder.append("Navn:<br /><input type=\"text\" name=\"name\" minLength=\"2\" required class=\"form-control\" placeholder=\"Dit navn\" /><br />");
stringBuilder.append("Telefon nr:<br /><input type=\"number\" minLength=\"8\" maxLength=\"8\" required name=\"phone\" class=\"form-control\" placeholder=\"Dit telefon nr - fx 11111111\" /><br />");
//Dropdown
String Dropdown = "Post nr:<br /><select class=\"form-control\" name=\"zipcode\">$body</select>";
String rows = "";
rows = zipcodesDropdown(zipcodes, rows);
Dropdown = Dropdown.replace("$body", rows);
stringBuilder.append(Dropdown);
stringBuilder.append("<br/>");
stringBuilder.append("<input type=\"submit\"formaction=\"/Fog/FrontController?command=" + Commands.ADD_REGISTER + "\" class=\"btn btn-info btn-block\" value=\"Opret bruger\" \">");
stringBuilder.append("</form><br/>");
return stringBuilder.toString();
}
/**
* For langt dvs værdier ind i option.
* @param zipcodes
* @param rows
* @return
*/
private String zipcodesDropdown(List<ZipcodeDTO> zipcodes, String rows) {
for(ZipcodeDTO value : zipcodes)
{
String row = "<option value=\"$1\">$2</option>";
row = row.replace("$1", String.valueOf(value.getZip()));
row = row.replace("$2", value.getCity());
rows += row;
}
return rows;
}
}
|
package com.flyingh.vo;
import java.text.Collator;
import android.content.pm.PackageStats;
import android.graphics.drawable.Drawable;
public class App implements Comparable<App> {
private Drawable icon;
private String label;
private String totalSize;
private String packageName;
private boolean isSystemApp;
private long totalSizeLong;
private PackageStats packageStats;
public static class Builder {
private Drawable icon;
private String label;
private String totalSize;
private String packageName;
private boolean isSystemApp;
public Builder icon(Drawable icon) {
this.icon = icon;
return this;
}
public Builder label(String label) {
this.label = label;
return this;
}
public Builder totalSize(String totalSize) {
this.totalSize = totalSize;
return this;
}
public Builder packageName(String packageName) {
this.packageName = packageName;
return this;
}
public Builder isSystemApp(boolean isSystemApp) {
this.isSystemApp = isSystemApp;
return this;
}
public App build() {
return new App(icon, label, totalSize, packageName, isSystemApp);
}
}
private App() {
super();
}
private App(Drawable icon, String label, String totalSize, String packageName, boolean isSystemApp) {
super();
this.icon = icon;
this.totalSize = totalSize;
this.packageName = packageName;
setLabel(label);
this.isSystemApp = isSystemApp;
}
public Drawable getIcon() {
return icon;
}
public void setIcon(Drawable icon) {
this.icon = icon;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = (label != null ? label : packageName);
}
public String getTotalSize() {
return totalSize;
}
public void setTotalSize(String totalSize) {
this.totalSize = totalSize;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public boolean isSystemApp() {
return isSystemApp;
}
public void setSystemApp(boolean isSystemApp) {
this.isSystemApp = isSystemApp;
}
public void setTotalSizeLong(long totalSizeLong) {
this.totalSizeLong = totalSizeLong;
}
public long getTotalSizeLong() {
return totalSizeLong;
}
public void setPackageStats(PackageStats packageStats) {
this.packageStats = packageStats;
}
public PackageStats getPackageStats() {
return packageStats;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((packageName == null) ? 0 : packageName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
App other = (App) obj;
if (packageName == null) {
if (other.packageName != null)
return false;
} else if (!packageName.equals(other.packageName))
return false;
return true;
}
@Override
public String toString() {
return "App [icon=" + icon + ", label=" + label + ", totalSize=" + totalSize + ", packageName=" + packageName + ", isSystemApp="
+ isSystemApp + "]";
}
@Override
public int compareTo(App another) {
return Collator.getInstance().compare(label, another.label);
}
}
|
package NovelDownloader.downloaders;
import NovelDownloader.abstRunner.*;
import NovelDownloader.translator.*;
import NovelDownloader.extra.*;
import NovelDownloader.outputFormat.FileFormat;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
//*********T-int,M-String
public class LNMTLThread<T,M> extends NotifyingThread<T,M> {
String title="";
ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> lines2 = new ArrayList<String>();
String url;
int orderNo= -1;
static Random random = new Random();
synchronized static int getRand()
{
return random.nextInt();
}
static int fileno=0;
synchronized int getFileno()
{
return ++fileno;
}
public void doRun(T indata)
{
Pair<Integer,String> in = (Pair<Integer,String>)indata;
orderNo = in.getOne();
url = in.getTwo();
System.out.println("URL : "+url);
Document doc=null;
try {
doc = Jsoup.connect(url).get();
} catch (IOException e1) {
e1.printStackTrace();
}
Element titleElement = doc.getElementsByAttributeValue("class","chapter-title").first();
title=titleElement.wholeText();
Elements inputElements = doc.getElementsByAttributeValue("class", "original");
for (Element inputElement : inputElements) {
Elements elements=inputElement.getElementsByTag("t");
for(Element element : elements)
{
String e=element.attr("data-title");
String j=element.text();
element.attr("data-title",j);
element.text(e);
}
lines.add(inputElement.wholeText()+"\n");
}
inputElements = doc.getElementsByAttributeValue("class", "translated");
for (Element inputElement : inputElements) {
lines2.add(inputElement.wholeText());
}
StringBuffer outp = new StringBuffer();
outp.append("<?xml version='1.0' encoding='utf-8'?>\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n <title>"+"LNMTL Novel"+"</title>\n</head><body><h3>"+title+"</h3>\n<div>\n");
Translator http = new Translator();
for(int i=0;i<lines.size();i++)
{
String line=lines.get(i);
String line2=lines2.get(i);
if(line.length()>0)
{
//String p1[]=null;
String p1="";
try
{
final int maximum = 500;
final int minimum = 1500;
int n = maximum - minimum + 1;
int k = getRand() % n;
int randomNum = minimum + k;
try {
Thread.sleep(randomNum);
} catch (InterruptedException e) {
e.printStackTrace();
}
//p1 = GoogleTranslator.translate("en", line);
//p1 = GoogleTranslate2.translate(line);
p1 = http.callUrlAndParseResult("zh-CN", "en", line);
}
catch( Exception exp)
{
exp.printStackTrace();
}
//outp.append(p1[0]+"<br>"+p1[1]+"<br>"+line2+"<br><br>");
//System.out.println("translated : "+p1[0]);
outp.append(p1+"<br>"+line+"<br>"+line2+"<br><br>");
//outp.append(line+"<br>"+line2+"<br><br>");
}
else
outp.append("<br>");
}
outp.append("</div></body></html>");
try {
this.setOutData((M) new Triplet<Integer,String,String>(orderNo,title ,FileFormat.writeFiles(outp.toString().replace("\\\"","\""), this.getFileno()) ) );
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopThread()
{
}
}
|
final -> must be initialized
protect > default
subclass -> subclass from different package, also could find the protected field.
private field may not need getter /setter, eg, we may not want this field viewed by outside.
abstract class 不一定有 abstract method. but it is still abstract class, not be initialized
can have constructor
Abstract class: base class implementation to derived class
base class -> interface, abstract class and concrete class
file system -> read, write -> only provide interface -> memory, disk, distributed system file system
interface -> no data field
|
import java.util.Scanner;
public class WeekNumber {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int choice;
System.out.println("Enter the number of the week");
choice=in.nextInt();
switch(choice){
case 1:
System.out.println("This day is Sunday");
break;
case 2:
System.out.println("This day is Monday");
break;
case 3:
System.out.println("This day is Tuesday");
break;
case 4:
System.out.println("This day is Wednesday");
break;
case 5:
System.out.println("This day is Thursday");
break;
case 6:
System.out.println("This day is Friday");
break;
case 7:
System.out.println("This month is Saturday");
break;
}
}
}
|
package remote;
import java.io.IOException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import management.OutputGenerator;
/**
* remote interface handles all commands valid for companies
* @author babz
*
*/
public interface ICompanyMode extends Remote, IUser {
/**
* get the credits of a company
* @return amount of credits the company owns
* @throws RemoteException
*/
int getCredit() throws RemoteException;
/**
* buys the given amount of credits
* @param amount number of credits that a company wants to buy
* @return message
* @throws RemoteException thrown if amount is negative
* @throws ManagementException
*/
int buyCredits(int amount) throws RemoteException, ManagementException;
/**
* company credits are reduced for the preparation of the task
* @param taskName name of task
* @param taskType either "low", "middle" or "high"
* @return unique id for the task is returned; preparation successful
* @throws RemoteException thrown if company doesn't have enough credits and task is being ignored
* @throws ManagementException
*/
int prepareTask(String taskName, String taskType) throws RemoteException, ManagementException;
/**
* executes task by forwarding to an engine
* @param taskId unique id of task
* @param startScript "java -jar task<id>.jar"
* @throws RemoteException thrown if either there is no free engine for execution or the task belongs to another company
* @throws ManagementException
*/
void executeTask(int taskId, String startScript, INotifyClientCallback cb) throws RemoteException, ManagementException;
/**
* prints out information for the specified task
* @param taskId
* @return message
* @throws RemoteException thrown if task id unknown or task doesn't belong to the logged in company
* @throws ManagementException
*/
String getInfo(int taskId) throws RemoteException, ManagementException;
/**
* output of a finished task from the management component
* @param taskId id of task for which the output is required
* @return output printed if task belongs to company and task has been finished and paid;
* otherwise make the user pay first
* @throws RemoteException if not enough credit or task doesn't belong to company
* @throws ManagementException
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
OutputGenerator getOutput(int taskId) throws RemoteException, ManagementException, IOException, InvalidKeyException, NoSuchAlgorithmException;
}
|
package com.meehoo.biz.core.basic.dao.security;
import com.meehoo.biz.core.basic.domain.security.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
/**
* Created by CZ on 2017/10/19.
*/
public interface IUserDao extends JpaRepository<User, String> {
@Query("FROM User u WHERE u.userName = ?1")
List<User> queryByUserName(String username);
@Query("FROM User u WHERE u.code = ?1")
List<User> queryByNumber(String number);
User getByPhone(String phone);
User getByUserNameAndPassword(String userName, String password);
}
|
/*
* 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.
*/
/**
*
* @author Ibrhaim
*/
public class Book extends Publication {
private int Page_Count;
public Book() {
}
public Book(int Page_Count){
this.Page_Count = Page_Count;
}
public void setPage_Count(int Page_Count){
this.Page_Count = Page_Count;
}
public int getPage_Count(){
return Page_Count;
}
@Override
public void display(){
super.display();
System.out.println("Page count : " + getPage_Count());
}
} |
package com.example.BSD;
import java.util.ArrayList;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.example.BSD.tasks.NieuwsAdapter;
import com.example.slide_menu.R;
public class NieuwsLijstFragment extends Fragment
{
private static View view;
@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
{
View v = inflater.inflate( R.layout.nieuwslijstfragment, container, false );
//Sla de view op
view = v;
//Ververs de listview wanneer de fragment wordt aangeroepen
refreshListview();
return v;
}
public static void refreshListview()
{
//Haal de nieuws items op als arraylist
ArrayList<NieuwsListItem> NieuwsOmschrijving = NieuwsDatabaseData.getNieuwsData();
//Defineer de listview
ListView omschrijvingview = (ListView) view.findViewById(R.id.nieuwslijst);
//Koppel de adapter aan de listview
NieuwsAdapter omschrijvingadapter = new NieuwsAdapter(view.getContext(), NieuwsOmschrijving);
omschrijvingview.setAdapter(omschrijvingadapter);
}
}
|
package com.application.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.SimpMessagingTemplate;
@Configuration
public class CommunicationConfig {
public static CommunicationConfig instance;
@Autowired SimpMessagingTemplate template;
public CommunicationConfig() {
instance = this;
}
public void currentDataControl() {
template.convertAndSend("/topic/control", true);
}
public void ThreadIsEnd() {
template.convertAndSend("/topic/threadIsEnd", true);
}
public void sendErrorMessage(String message) {
template.convertAndSend("/topic/error", message);
}
}
|
package com.ecjtu.hotel.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ecjtu.hotel.dao.ReserveMapper;
import com.ecjtu.hotel.pojo.Reserve;
import com.ecjtu.hotel.service.IReserveService;
@Service
public class ReserveService implements IReserveService {
@Autowired
ReserveMapper reserveMapper;
public ReserveService() {
// TODO Auto-generated constructor stub
}
@Override
public int addReserve(Reserve reserve) {
// TODO Auto-generated method stub
return reserveMapper.addReserve(reserve);
}
@Override
public int deleteReserveById(Integer id) {
// TODO Auto-generated method stub
return reserveMapper.deleteReserveById(id);
}
@Override
public int updateReserve(Reserve reserve) {
// TODO Auto-generated method stub
return reserveMapper.updateReserve(reserve);
}
@Override
public List<Reserve> getAllReserve() {
// TODO Auto-generated method stub
return reserveMapper.getAllReserve();
}
@Override
public Reserve getReserveById(Integer id) {
// TODO Auto-generated method stub
return reserveMapper.getReserveById(id);
}
}
|
package com.nextLevel.hero.mngWorkAttitude.model.dto;
public class MngWorkCommuteDTO {
private String yearAndMonth; //연도월
private String workStartTime; //시작시간
private String workEndTime; //퇴근시간
private int commuteNo; //출티근번호
private char todayStatus; //지각여부
private char earlyLeaveStatus; //조퇴여부
private char absentStatus; //결근여부
private int holidayNo; //휴일번호
public MngWorkCommuteDTO() {
super();
}
public MngWorkCommuteDTO(String yearAndMonth, String workStartTime, String workEndTime, int commuteNo,
char todayStatus, char earlyLeaveStatus, char absentStatus, int holidayNo) {
super();
this.yearAndMonth = yearAndMonth;
this.workStartTime = workStartTime;
this.workEndTime = workEndTime;
this.commuteNo = commuteNo;
this.todayStatus = todayStatus;
this.earlyLeaveStatus = earlyLeaveStatus;
this.absentStatus = absentStatus;
this.holidayNo = holidayNo;
}
public String getYearAndMonth() {
return yearAndMonth;
}
public void setYearAndMonth(String yearAndMonth) {
this.yearAndMonth = yearAndMonth;
}
public String getWorkStartTime() {
return workStartTime;
}
public void setWorkStartTime(String workStartTime) {
this.workStartTime = workStartTime;
}
public String getWorkEndTime() {
return workEndTime;
}
public void setWorkEndTime(String workEndTime) {
this.workEndTime = workEndTime;
}
public int getCommuteNo() {
return commuteNo;
}
public void setCommuteNo(int commuteNo) {
this.commuteNo = commuteNo;
}
public char getTodayStatus() {
return todayStatus;
}
public void setTodayStatus(char todayStatus) {
this.todayStatus = todayStatus;
}
public char getEarlyLeaveStatus() {
return earlyLeaveStatus;
}
public void setEarlyLeaveStatus(char earlyLeaveStatus) {
this.earlyLeaveStatus = earlyLeaveStatus;
}
public char getAbsentStatus() {
return absentStatus;
}
public void setAbsentStatus(char absentStatus) {
this.absentStatus = absentStatus;
}
public int getHolidayNo() {
return holidayNo;
}
public void setHolidayNo(int holidayNo) {
this.holidayNo = holidayNo;
}
@Override
public String toString() {
return "MngWorkCommuteDTO [yearAndMonth=" + yearAndMonth + ", workStartTime=" + workStartTime + ", workEndTime="
+ workEndTime + ", commuteNo=" + commuteNo + ", todayStatus=" + todayStatus + ", earlyLeaveStatus="
+ earlyLeaveStatus + ", absentStatus=" + absentStatus + ", holidayNo=" + holidayNo + "]";
}
}
|
/*
* Copyright (C) 2008-2010 Martin Riesz <riesz.martin at gmail.com>
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package org.petrinator.editor.commands;
import org.petrinator.petrinet.PetriNet;
import org.petrinator.petrinet.PlaceNode;
import org.petrinator.petrinet.ReferenceArc;
import org.petrinator.petrinet.ReferencePlace;
import org.petrinator.petrinet.Subnet;
import org.petrinator.util.Command;
/**
*
* @author Martin Riesz <riesz.martin at gmail.com>
*/
public class AddReferenceArcCommand implements Command {
private Subnet parentSubnet;
private PlaceNode placeNode;
private Subnet nestedSubnet;
private ReferenceArc createdReferenceArc;
private ReferencePlace referencePlace;
private PetriNet petriNet;
public AddReferenceArcCommand(PlaceNode placeNode, Subnet nestedSubnet, PetriNet petriNet) {
this.parentSubnet = placeNode.getParentSubnet();
this.placeNode = placeNode;
this.nestedSubnet = nestedSubnet;
this.petriNet = petriNet;
}
public void execute() {
referencePlace = new ReferencePlace(placeNode);
referencePlace.setCenter(
placeNode.getCenter().x - nestedSubnet.getCenter().x,
placeNode.getCenter().y - nestedSubnet.getCenter().y
);
petriNet.getNodeSimpleIdGenerator().setUniqueId(referencePlace);
createdReferenceArc = new ReferenceArc(placeNode, nestedSubnet);
redo();
}
public void undo() {
new DeleteElementCommand(createdReferenceArc).execute();
}
public void redo() {
nestedSubnet.addElement(referencePlace);
parentSubnet.addElement(createdReferenceArc);
}
@Override
public String toString() {
return "Add reference arc";
}
}
|
package com.lesson.androidversions;
public class AndroidInfo
{
int logo;
String name, version, level, date;
public AndroidInfo(int logo, String name, String version, String level, String date)
{
this.logo = logo;
this.name = name;
this.version = version;
this.level = level;
this.date = date;
}
public int getLogo() {
return logo;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public String getLevel() {
return level;
}
public String getDate() {
return date;
}
}
|
package com.kun.security.browser;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
/**
* @author CaoZiye
* @version 1.0 2017/11/16 19:37
*/
@Component
public class MyUserDetailService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 查询数据库,通过用户名得到密码及权限
return new User(
"kun", // 用户名
"$2a$10$COHPGeNDbIC/QZGIH3339.N8S391mZaj5B5/MyfhilHQ4GnEmcTh6", // 加密密码
true, // 有效
true, // 账户未过期
true, // 密码未过期
true, // 账户未锁定
AuthorityUtils.commaSeparatedStringToAuthorityList("admin")); // 权限
}
}
|
package org.obiz.sdtd.tool.rgwmap;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
public class ImageMath {
/**
* Clamp a value to an interval.
* @param a the lower clamp threshold
* @param b the upper clamp threshold
* @param x the input parameter
* @return the clamped value
*/
public static float clamp(float x, float a, float b) {
return (x < a) ? a : (x > b) ? b : x;
}
/**
* Clamp a value to an interval.
* @param a the lower clamp threshold
* @param b the upper clamp threshold
* @param x the input parameter
* @return the clamped value
*/
public static int clamp(int x, int a, int b) {
return (x < a) ? a : (x > b) ? b : x;
}
public static int getIntFromRaster(Raster raster, int x, int y) {
return raster.getSample(x, y, 0)|(raster.getSample(x, y, 1)<<8)|(raster.getSample(x, y, 0)<<16);
}
public static void setIntToRaster(WritableRaster raster, int x, int y, int rgb) {
int R = rgb >> 16;
int G = rgb >> 8;
int B = rgb;
raster.setSample(x, y, 0, R);
raster.setSample(x, y, 1, G);
raster.setSample(x, y, 2, B);
}
public static Color getRGBFromInt(int rgb) {
int R = (rgb >> 16) & 0xff;
int G = (rgb >> 8 ) & 0xff;
int B = (rgb & 0xff);
return new Color(R, G, B);
}
public static int getFullIntFromRGB(int red, int green, int blue) {
return getFillIntFromPureInt(getPureIntFromRGB(red, green, blue));
}
public static int getFullIntFromRGB(Color color) {
return getFillIntFromPureInt(getPureIntFromRGB(color.getRed(), color.getGreen(), color.getBlue()));
}
public static int getPureIntFromRGB(int red, int green, int blue) {
int result = 0;
result |= red<<16;
result |= green<<8;
result |= blue;
return result;
}
public static int getPureIntFromRGB(Color color) {
return getPureIntFromRGB(color.getRed(), color.getGreen(), color.getBlue());
}
public static int getFillIntFromPureInt(int rgb) {
return rgb | 0xff<<24;
}
public static int xy2i(BufferedImage image, int x, int y, int c) {
return image.getHeight()*y*4 + x*4 + c;
}
public static int xy2i(BufferedImage image, int x, int y) {
return image.getHeight()*y + x;
}
public static int i2x(BufferedImage image, int i) {
return i%image.getHeight();
}
public static int i2y(BufferedImage image, int i) {
return i/image.getHeight();
}
}
|
package uk.nhs.hee.web.security.web.servlet.support;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import uk.nhs.hee.web.security.config.oauth2.azure.AzureOAuth2ClientSecurityConfig;
import uk.nhs.hee.web.security.config.oauth2.azure.MvcWebConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
@Order(1)
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
public void onStartup(@NotNull ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
/*
* Needed to support a "request" scope in Spring Security filters,
* since they're configured as a Servlet Filter. But not necessary
* if they're configured as interceptors in Spring MVC.
*/
servletContext.addListener(new RequestContextListener());
}
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{
AzureOAuth2ClientSecurityConfig.class,
MvcWebConfig.class
};
}
@Override
protected String @NotNull [] getServletMappings() {
return new String[]{"/"};
}
}
|
package object.device;
import java.util.HashSet;
import object.graph.Room;
public class EffectorAirConditioner extends EffectorAbstract {
// DEFAULT SETTINGS
private static final double DEFAULT_POWER = 2000.0; // in [W]
private static final boolean DEFAULT_STATE = false;
private static final double DEFAULT_TEMPERATURE = 22.0; // in [C]
private static final double DEFAULT_OUTPUT = 0.0; // [%]
private double efficiency;
// ********** CONSTRUCTOR **********
/**
* constructor for the device
*/
public EffectorAirConditioner() {
this.reset_data_out();
this.state = DEFAULT_STATE;
this.set_temp = DEFAULT_TEMPERATURE;
this.output = DEFAULT_OUTPUT;
this.power = DEFAULT_POWER;
this.compatibility = new HashSet<Integer>();
this.compatibility.add(2); // temperature sensor compatibility
}
// *********** UTILITY FUNCTIONS ***********
/**
* returns the name of the device
*
* @return name of the device
*/
public String get_name() {
StringBuilder name = new StringBuilder();
name.append("Air Conditioner\n");
name.append("Device ID: ");
name.append(this.device.get_id());
return name.toString();
}
/**
* returns information about the status of the device
*
* @return current info of the device
*/
@Override
public String get_info() {
StringBuilder info = new StringBuilder();
info.append(this.get_name());
info.append("Set Temperature: ");
info.append(Double.toString(this.set_temp));
info.append("\n");
info.append("Max Power: ");
info.append(Double.toString(this.power));
info.append("\n");
info.append("Current Power: ");
info.append(Double.toString(this.output * this.power));
info.append("\n");
info.append("Energy Usage [kJ]: ");
info.append(Double.toString(this.get_energy_usage()));
info.append("\n");
return info.toString();
}
// ********** SIMULATION FUNCTIONS **********
/**
* steps the device for the simulation
*/
public void step(double duration) {
this.reset_data_out();
this.calc_energy_usage(duration);
this.read_data();
this.effect();
this.prev_time += duration;
}
/**
* reads the data to configure the device
*/
private void read_data() {
// TODO reads the data send to the device and responds accordingly
}
/**
* performs the effect
* @param time time of the system
*/
public void effect() {
Room r = this.get_room();
if (this.state && r != null) {
double ambient_k = r.get_ambient_temperature() + 273.15;
double internal_k = r.get_temp() + 273.15;
}
}
/**
*
* @param power desired power output of the device in [W]
*/
public void set_power(double power) {
if (power < 0) {
this.set_state(false);
return;
}
else if (power >= this.power) {
this.set_state(true);
this.output = 1.0;
return;
}
else {
this.set_state(true);
this.output = (power/this.power);
}
}
/**
* @return state of the component
*/
public boolean get_state() {
return this.state;
}
public void set_state(boolean state) {
this.state = state;
}
/**
* @return output percentage of the heater
*/
public double get_output() {
return this.output;
}
public void set_output(double output) {
this.output = output;
}
/**
* @return set temperature of the heater
*/
public double get_set_temp() {
return this.set_temp;
}
public void set_set_temp(double temperature) {
this.set_temp = temperature;
}
@Override
public void set_efficiency(double efficiency) {
this.efficiency = efficiency;
}
}
|
package msip.go.kr.member.web;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.cmm.LoginVO;
import egovframework.com.cmm.service.EgovFileMngService;
import egovframework.com.cmm.service.EgovFileMngUtil;
import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import msip.go.kr.member.entity.HeadMember;
import msip.go.kr.member.entity.Member;
import msip.go.kr.member.entity.MemberVO;
import msip.go.kr.member.service.HeadMemberService;
/**
* 본부 사용자 관련 Controller Class
*
* @author 정승철
* @since 2015.07.06
* @see <pre>
* == 개정이력(Modification Information) ==
*
* 수정일 수정자 수정내용
* ---------------------------------------------------------------------------------
* 2015.07.06 정승철 최초생성
*
* </pre>
*/
@Controller
public class HeadMemberController {
/** headMemberService */
@Resource(name = "headMemberService")
private HeadMemberService headMemberService;
/** EgovPropertyService */
@Resource(name = "propertiesService")
protected EgovPropertyService propertiesService;
@Resource(name="egovMessageSource")
EgovMessageSource egovMessageSource;
@Resource(name = "EgovFileMngUtil")
private EgovFileMngUtil fileUtil;
@Resource(name = "EgovFileMngService")
private EgovFileMngService fileMngService;
private static final Logger LOGGER = LoggerFactory.getLogger(HeadMemberController.class);
/**
* 약관동의 화면 이동
* @param request
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value = "/member/signup/head/terms")
public String terms(HttpServletRequest request, ModelMap model) throws Exception {
return "msip/member/head.terms";
}
/**
* 최초 로그인 후 비밀번호 초기화 화면 이동
* @param request
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value = "/member/signup/head/password")
public String password(HttpServletRequest request, ModelMap model) throws Exception {
return "msip/member/pwd.init";
}
/**
* 주소록 - 본부 유효 회원 목록을 출력
*
* @param model
* @return "/orgMemberHead"
* @throws Exception
*/
@RequestMapping(value = "/member/head/list/{param}", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> findListForAddressBook(@PathVariable String param, ModelMap model) throws Exception {
MemberVO vo = new MemberVO(param);
vo.setStatus(Member.APPROVED);
vo.setPageUnit(propertiesService.getInt("pageUnit"));
vo.setPageSize(propertiesService.getInt("pageSize"));
/** pageing */
PaginationInfo paginationInfo = new PaginationInfo();
paginationInfo.setCurrentPageNo(vo.getPageIndex());
paginationInfo.setRecordCountPerPage(vo.getPageUnit());
paginationInfo.setPageSize(vo.getPageSize());
vo.setFirstIndex(paginationInfo.getFirstRecordIndex());
vo.setLastIndex(paginationInfo.getLastRecordIndex());
List<Member> list = headMemberService.findList(vo);
int count = headMemberService.count(vo);
Map<String, Object> result = new HashMap<String, Object>();
result.put("count", count);
result.put("data", list);
return result;
}
/**
* 주소록 - 본부 조직별 회원 카운트 조회
*
* @param model
* @return "/orgMemberHeadCnt/{id}"
* @throws Exception
*/
@RequestMapping(value = "/member/head/count/{id}", method = RequestMethod.GET)
@ResponseBody
public int countByHeadMember(@PathVariable Long id, @ModelAttribute("commonVO") MemberVO vo, ModelMap model) throws Exception {
// 선택된 조직 일련번호
vo.setStatus(Member.APPROVED);
vo.setNodeId(id);
int result = headMemberService.count(vo);
return result;
}
/**
* 주소록 - 일시정지 회원 목록을 출력
*
* @param model
* @throws Exception
*/
@RequestMapping(value = "/member/head/suspend/list/{param}", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> findSuspendedLIst(@PathVariable String param, ModelMap model) throws Exception {
MemberVO vo = new MemberVO(param);
vo.setStatus(Member.SUSPENDED);
vo.setPageUnit(propertiesService.getInt("pageUnit"));
vo.setPageSize(propertiesService.getInt("pageSize"));
/** pageing */
PaginationInfo paginationInfo = new PaginationInfo();
paginationInfo.setCurrentPageNo(vo.getPageIndex());
paginationInfo.setRecordCountPerPage(vo.getPageUnit());
paginationInfo.setPageSize(vo.getPageSize());
vo.setFirstIndex(paginationInfo.getFirstRecordIndex());
vo.setLastIndex(paginationInfo.getLastRecordIndex());
List<Member> list = headMemberService.findList(vo);
int count = headMemberService.count(vo);
Map<String, Object> result = new HashMap<String, Object>();
result.put("count", count);
result.put("data", list);
return result;
}
/**
* 회원 정보 수정
*
* @param entity
* @param bindingResult
* @param model
* @param status
* @return "redirect:/member/registInstMember.do"
* @throws Exception
*/
@RequestMapping(value = "/member/head/update", method = RequestMethod.POST)
public String update(final MultipartHttpServletRequest multiRequest, @ModelAttribute HeadMember entity, Model model) throws Exception {
String message = egovMessageSource.getMessage("success.common.update");
try {
LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
String uniqId = loginVO.getUniqId();
int i=0;
final Map<String, MultipartFile> files = multiRequest.getFileMap();
if (!files.isEmpty()) {
Iterator<Entry<String, MultipartFile>> itr = files.entrySet().iterator();
MultipartFile file;
while (itr.hasNext()) {
if(i == 0)
{
Entry<String, MultipartFile> entry = itr.next();
file = entry.getValue();
if(!file.isEmpty()) {
fileUtil.uploadWithThumnail(file, "profile", uniqId);
}
}
i++;
}
}
headMemberService.update(entity);
} catch (net.coobird.thumbnailator.tasks.UnsupportedFormatException fe) {
message = egovMessageSource.getMessage("unsupported.file");
LOGGER.error("/member/head/update Exception", fe.getCause(), fe);
} catch (Exception e) {
message = egovMessageSource.getMessage("fail.common.update");
LOGGER.error("/member/head/update Exception", e.getCause(), e);
}
model.addAttribute("message", message);
return "msip/member/head.edit";
}
}
|
package com.cs.administration.payment;
import com.cs.administration.player.BackOfficeWalletDto;
import com.cs.administration.security.BackOfficeUser;
import com.cs.administration.security.CurrentUser;
import com.cs.payment.AwaitingWithdrawPageableDto;
import com.cs.payment.BankAccountDto;
import com.cs.payment.DCPaymentTransaction;
import com.cs.payment.EventCode;
import com.cs.payment.Operation;
import com.cs.payment.PaymentPageableDto;
import com.cs.payment.PaymentService;
import com.cs.payment.PaymentStatus;
import com.cs.payment.PaymentTransaction;
import com.cs.payment.devcode.DevcodePaymentService;
import com.cs.payment.transaction.PaymentTransactionFacade;
import com.cs.user.User;
import com.cs.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import static com.cs.persistence.Constants.BO_DEFAULT_SIZE;
import static org.springframework.http.HttpStatus.NO_CONTENT;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
/**
* @author Marcus Wass
*/
@RestController
@RequestMapping(value = "/api/payments", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
public class PaymentController {
private final Logger logger = LoggerFactory.getLogger(PaymentController.class);
private final DevcodePaymentService devcodePaymentService;
private final PaymentService paymentService;
private final PaymentTransactionFacade paymentTransactionFacade;
private final UserService userService;
@Autowired
public PaymentController(final DevcodePaymentService devcodePaymentService, final PaymentService paymentService,
final PaymentTransactionFacade paymentTransactionFacade, final UserService userService) {
this.devcodePaymentService = devcodePaymentService;
this.paymentService = paymentService;
this.paymentTransactionFacade = paymentTransactionFacade;
this.userService = userService;
}
@RequestMapping(method = GET)
@ResponseStatus(OK)
public PaymentPageableDto getPaymentTransactions(@RequestParam(value = "startDate", required = true) @DateTimeFormat(iso = ISO.DATE) final Date startDate,
@RequestParam(value = "endDate", required = true) @DateTimeFormat(iso = ISO.DATE) final Date endDate,
@RequestParam(value = "playerId", required = false) final Long playerId,
@RequestParam(value = "code", required = false) final EventCode eventCode,
@RequestParam(value = "status", required = false) final PaymentStatus paymentStatus,
@RequestParam(value = "page", required = false, defaultValue = "0") final Integer page,
@RequestParam(value = "size", required = false, defaultValue = BO_DEFAULT_SIZE) final Integer size) {
// TODO:Joakim Remove the size parameter when Adyen is removed form the system, the size is necessary for returning the correct number of elements
// final Page<PaymentTransaction> transactions = paymentTransactionFacade.getPayments(playerId, eventCode, paymentStatus, startDate, endDate, page, size);
// final Page<DCPaymentTransaction> dcPaymentTransactions = devcodePaymentService.getPayments(playerId, startDate, endDate, page, size);
final Page<PaymentTransaction> transactions = paymentTransactionFacade.getPayments(playerId, eventCode, paymentStatus, startDate, endDate, 0, 1000);
final Page<DCPaymentTransaction> dcPaymentTransactions = devcodePaymentService.getPayments(playerId, startDate, endDate, 0, 1000);
return new PaymentPageableDto(transactions, dcPaymentTransactions, page, size);
}
@RequestMapping(method = GET, value = "/refund/{playerId}")
@ResponseStatus(OK)
public List<RefundCancelDetailDto> getPlayerRefundDetail(@PathVariable("playerId") final Long playerId) {
return RefundCancelDetailDto.getList(paymentService.getPaymentsContainingOperation(playerId, Operation.REFUND));
}
@RequestMapping(method = PUT, value = "/refund/{playerId}/{originalReference}")
@ResponseStatus(NO_CONTENT)
public void sendRefundRequest(@PathVariable("playerId") final Long playerId, @PathVariable("originalReference") final String originalReference,
@CurrentUser final BackOfficeUser currentUser) {
final User user = userService.getUser(currentUser.getId());
paymentService.refundDeposit(originalReference, playerId, user);
}
@RequestMapping(method = GET, value = "/cancel/{playerId}")
@ResponseStatus(OK)
public List<RefundCancelDetailDto> getPlayerCancelDetail(@PathVariable("playerId") final Long playerId) {
return RefundCancelDetailDto.getList(paymentService.getPaymentsContainingOperation(playerId, Operation.CANCEL));
}
@RequestMapping(method = PUT, value = "/cancel/{playerId}/{originalReference}")
@ResponseStatus(NO_CONTENT)
public void sendCancelRequest(@PathVariable("playerId") final Long playerId, @PathVariable("originalReference") final String originalReference,
@CurrentUser final BackOfficeUser currentUser) {
final User user = userService.getUser(currentUser.getId());
paymentService.cancelDeposit(originalReference, playerId, user);
}
@RequestMapping(method = PUT, value = "/{playerId}")
@ResponseStatus(OK)
public BackOfficeWalletDto updatePlayerWallet(@PathVariable("playerId") final Long playerId, @CurrentUser final BackOfficeUser currentUser,
@RequestBody(required = true) final BackOfficeWalletDto walletDto) {
logger.info("Received a request to update wallet for player: {} from user: {} with money amount: {}", playerId, currentUser.getId(), walletDto.getMoneyBalance());
final User user = userService.getUser(currentUser.getId());
return new BackOfficeWalletDto(paymentService.updatePlayerWallet(playerId, user, walletDto.asWallet()));
}
@RequestMapping(method = POST, value = "/confirm")
@ResponseStatus(OK)
public ConfirmDeclineWithdrawDto confirmWithdrawals(@RequestBody(required = true) final ConfirmDeclineWithdrawDto confirmDeclineWithdrawDto,
@CurrentUser final BackOfficeUser currentUser) {
final User user = userService.getUser(currentUser.getId());
return new ConfirmDeclineWithdrawDto(paymentService.confirmWithdrawals(confirmDeclineWithdrawDto.getWithdrawReferences(), user));
}
@RequestMapping(method = POST, value = "/decline")
@ResponseStatus(OK)
public ConfirmDeclineWithdrawDto declineWithdraws(@RequestBody(required = true) final ConfirmDeclineWithdrawDto declineWithdrawDto,
@CurrentUser final BackOfficeUser currentUser) {
final User user = userService.getUser(currentUser.getId());
return new ConfirmDeclineWithdrawDto(paymentService.declineWithdrawals(declineWithdrawDto.getWithdrawReferences(), user));
}
@RequestMapping(method = GET, value = "/awaiting")
@ResponseStatus(OK)
public AwaitingWithdrawPageableDto getAwaitingPayouts(@RequestParam(value = "page", required = false, defaultValue = "0") final Integer page,
@RequestParam(value = "size", required = false, defaultValue = BO_DEFAULT_SIZE) final Integer size) {
final Page<PaymentTransaction> awaitingWithdraws = paymentService.getAwaitingWithdrawals(page, size);
return new AwaitingWithdrawPageableDto(awaitingWithdraws);
}
@RequestMapping(method = POST, value = "/bank/{playerId}")
@ResponseStatus(OK)
public void storeBankAccountForWithdrawal(@PathVariable("playerId") final Long playerId, @CurrentUser final BackOfficeUser currentUser,
@RequestBody @Valid final BankAccountDto bankAccountDto) {
paymentService.backOfficeStoreBankAccountForWithdrawal(userService.getUser(currentUser.getId()), playerId, bankAccountDto.getIban(), bankAccountDto.getBic(),
bankAccountDto.getBankName(), bankAccountDto.getName());
}
}
|
package com.example.administrator.cookman.ui.component.twinklingrefreshlayout.dataView;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.administrator.cookman.R;
import com.example.administrator.cookman.ui.component.ProgressWheel;
/**
* Created by Administrator on 2017/3/17.
*/
public class DataKnifeView extends RelativeLayout {
public static final int Mode_Loading = 0;
public static final int Mode_NetworkErr = 1;
public static final int Mode_Exception = 2;
public static final int Mode_DataEmpty = 3;
public static final int Mode_Visi_Gone = 4;
private Context context;
private RelativeLayout viewData;
private ProgressWheel progressWheel;
private ImageView imgvIcon;
private TextView textInfo;
private int mode = Mode_Loading;
private int imgIdNetworkErr;
private int imgIdException;
private int imgIdDataEmpty;
public DataKnifeView(Context context) {
this(context, null);
}
public DataKnifeView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DataKnifeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
private void initView(Context context){
this.context = context;
View view = LayoutInflater.from(context).inflate(R.layout.common_view_pe_data_kinfe, this);
viewData = (RelativeLayout)view.findViewById(R.id.view_data);
progressWheel = (ProgressWheel)view.findViewById(R.id.progress_wheel);
imgvIcon = (ImageView)view.findViewById(R.id.imgv_icon);
textInfo = (TextView)view.findViewById(R.id.text_info);
imgIdNetworkErr = R.mipmap.icon_data_view_net_err;
imgIdException = R.mipmap.icon_data_view_exception;
imgIdDataEmpty = R.mipmap.icon_data_view_null;
viewData.setClickable(true);
}
public int getMode(){
return mode;
}
public void setModeLoading(){
mode = Mode_Loading;
imgvIcon.setVisibility(GONE);
textInfo.setVisibility(GONE);
progressWheel.setVisibility(VISIBLE);
}
public void setModeLoading(String msg){
mode = Mode_Loading;
imgvIcon.setVisibility(GONE);
textInfo.setVisibility(VISIBLE);
progressWheel.setVisibility(VISIBLE);
textInfo.setText(msg);
}
public void setModeNetworkErr(){
mode = Mode_NetworkErr;
textInfo.setVisibility(GONE);
progressWheel.setVisibility(GONE);
imgvIcon.setVisibility(VISIBLE);
imgvIcon.setImageResource(imgIdNetworkErr);
}
public void setModeNetworkErr(String msg){
mode = Mode_NetworkErr;
progressWheel.setVisibility(GONE);
textInfo.setVisibility(VISIBLE);
imgvIcon.setVisibility(VISIBLE);
imgvIcon.setImageResource(imgIdNetworkErr);
textInfo.setText(msg);
}
public void setModeException(){
mode = Mode_Exception;
textInfo.setVisibility(GONE);
progressWheel.setVisibility(GONE);
imgvIcon.setVisibility(VISIBLE);
imgvIcon.setImageResource(imgIdException);
}
public void setModeException(String msg){
mode = Mode_Exception;
progressWheel.setVisibility(GONE);
textInfo.setVisibility(VISIBLE);
imgvIcon.setVisibility(VISIBLE);
imgvIcon.setImageResource(imgIdException);
textInfo.setText(msg);
}
public void setModeDataEmpty(){
mode = Mode_DataEmpty;
textInfo.setVisibility(GONE);
progressWheel.setVisibility(GONE);
imgvIcon.setVisibility(VISIBLE);
imgvIcon.setImageResource(imgIdDataEmpty);
}
public void setModeDataEmpty(String msg){
mode = Mode_DataEmpty;
progressWheel.setVisibility(GONE);
textInfo.setVisibility(VISIBLE);
imgvIcon.setVisibility(VISIBLE);
imgvIcon.setImageResource(imgIdDataEmpty);
textInfo.setText(msg);
}
public void setDataKnifeViewListener(OnClickListener dataKnifeViewListener){
viewData.setOnClickListener(dataKnifeViewListener);
}
}
|
package state;
/**
* Date: 2019/3/5
* Created by LiuJian
*
* @author LiuJian
*/
class HasElecState implements IState {
PersonNight mPersonNight;
public HasElecState(PersonNight mPersonNight) {
this.mPersonNight = mPersonNight;
}
public PersonNight getPersonNight() {
return mPersonNight;
}
public void setPersonNight(PersonNight mPersonNight) {
this.mPersonNight = mPersonNight;
}
@Override
public void watchTv() {
mPersonNight.setIState(mPersonNight.getHasElecState());
System.out.println("watch the TV");
}
@Override
public void takeBath() {
System.out.println("do not take bath");
}
@Override
public void sleep() {
System.out.println("do not sleep");
}
}
|
package extension;
import gearth.extensions.ExtensionForm;
import gearth.extensions.ExtensionInfo;
import gearth.extensions.parsers.HEntity;
import gearth.extensions.parsers.HEntityType;
import gearth.protocol.HMessage;
import gearth.protocol.HPacket;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import java.util.*;
import java.util.stream.Collectors;
import gordon.EffectMap;
@ExtensionInfo(
Title = "Clientside Effects",
Description = "Make any user effect appear clientside",
Version = "0.3",
Author = "WiredSpast"
)
public class ClientsideEffect extends ExtensionForm {
// FX-Components
public ChoiceBox<User> usersBox;
public ChoiceBox<Effect> effectsBox;
public CheckBox onTeleportCheckBox;
public CheckBox onRoomChangeCheckBox;
private Map<Integer, Effect> keepOnTeleport = new HashMap<>(); // key = userId
private Map<Integer, Effect> keepOnRoomChange = new HashMap<>(); // key = userId
@Override
protected void initExtension() {
intercept(HMessage.Direction.TOCLIENT, "OpenConnection", this::onOpenOrCloseConnection);
intercept(HMessage.Direction.TOCLIENT, "CloseConnection", this::onOpenOrCloseConnection);
intercept(HMessage.Direction.TOCLIENT, "Users", this::onUsers);
intercept(HMessage.Direction.TOCLIENT, "UserRemove", this::onUserRemove);
intercept(HMessage.Direction.TOCLIENT, "AvatarEffect", this::onAvatarEffect);
fetchEffects();
}
private void onOpenOrCloseConnection(HMessage hMessage) {
Platform.runLater(() -> usersBox.getItems().clear());
}
private void onUsers(HMessage hMessage) {
User[] users = User.parse(hMessage.getPacket());
Platform.runLater(() -> {
usersBox.getItems().addAll(Arrays.stream(users).filter(user -> user.getEntityType() != HEntityType.PET).collect(Collectors.toList()));
usersBox.getItems().sorted();
});
for(User user : users) {
if(keepOnRoomChange.containsKey(user.getId())) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
sendToClient(new HPacket("AvatarEffect", HMessage.Direction.TOCLIENT, user.getIndex(), keepOnRoomChange.get(user.getId()).id, 0));
}
}, 500);
}
}
}
private void onUserRemove(HMessage hMessage) {
int index = Integer.parseInt(hMessage.getPacket().readString());
Platform.runLater(() -> usersBox.getItems().removeIf(user -> user.getIndex() == index));
}
private void onAvatarEffect(HMessage hMessage) {
HPacket packet = hMessage.getPacket();
int userIndex = packet.readInteger();
Optional<User> optUser = usersBox
.getItems()
.stream()
.filter(user -> user.getIndex() == userIndex)
.findAny();
if(optUser.isPresent()) {
User user = optUser.get();
if(keepOnTeleport.containsKey(user.getId())) {
sendToClient(new HPacket("AvatarEffect", HMessage.Direction.TOCLIENT, user.getIndex(), keepOnTeleport.get(user.getId()).id, 0));
}
}
}
private void fetchEffects() {
new Thread(() -> {
List<Effect> effects = EffectMap.getAllEffects()
.stream()
.filter(effect -> effect.type.equals("fx"))
.map(Effect::new)
.collect(Collectors.toList());
effectsBox.getItems().add(Effect.NONE);
effectsBox.getItems().addAll(effects);
sendToClient(new HPacket("{in:NotificationDialog}{s:\"\"}{i:3}{s:\"display\"}{s:\"BUBBLE\"}{s:\"message\"}{s:\"Clientside Effect: Effectmap loaded!\"}{s:\"image\"}{s:\"https://raw.githubusercontent.com/WiredSpast/G-ExtensionStore/repo/1.5/store/extensions/Clientside%20Effect/icon.png\"}"));
}).start();
}
public void onSetButton(ActionEvent actionEvent) {
if(usersBox.getValue() != null) {
if(effectsBox.getValue() == null || effectsBox.getValue().id == 0) {
sendToClient(new HPacket("AvatarEffect", HMessage.Direction.TOCLIENT, usersBox.getValue().getIndex(), 0, 0));
keepOnTeleport.remove(usersBox.getValue().getId());
keepOnRoomChange.remove(usersBox.getValue().getId());
} else {
sendToClient(new HPacket("AvatarEffect", HMessage.Direction.TOCLIENT, usersBox.getValue().getIndex(), effectsBox.getValue().id, 0));
if(onTeleportCheckBox.isSelected()) {
keepOnTeleport.put(usersBox.getValue().getId(), effectsBox.getValue());
} else keepOnTeleport.remove(usersBox.getValue().getId());
if(onRoomChangeCheckBox.isSelected()) {
keepOnRoomChange.put(usersBox.getValue().getId(), effectsBox.getValue());
} else keepOnTeleport.remove(usersBox.getValue().getId());
}
}
}
public void onClearButton(ActionEvent actionEvent) {
keepOnTeleport.clear();
keepOnRoomChange.clear();
usersBox.getItems().forEach(user -> sendToClient(new HPacket("AvatarEffect", HMessage.Direction.TOCLIENT, user.getIndex(), 0, 0)));
}
private static class User extends HEntity {
public User(HPacket packet) {
super(packet);
}
public static User[] parse(HPacket packet) {
User[] entities = new User[packet.readInteger()];
for(int i = 0; i < entities.length; ++i) {
entities[i] = new User(packet);
}
return entities;
}
@Override
public String toString() {
return (this.getEntityType() == HEntityType.BOT || this.getEntityType() == HEntityType.OLD_BOT ? "[BOT] " : "") + this.getName();
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof User)) {
return false;
}
User otherUser = (User) obj;
return this.getId() == otherUser.getId() || this.getIndex() == otherUser.getIndex();
}
}
private static class Effect {
public final int id;
public final String name;
public static Effect NONE = new Effect();
public Effect() {
this.id = 0;
this.name = "None";
}
public Effect(EffectMap.Effect effect) {
this.id = Integer.parseInt(effect.id);
this.name = effect.name;
}
@Override
public String toString() {
return this.name;
}
}
private void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package Recursion;
import java.util.Scanner;
public class NumOfDig {
static int noOfDig(int n/*, int i*/){
/*if(n==0 && i==0)
return 1;
if(n==0)
return i;
return noOfDig(n/10, i+1);*/
if(n<10 && n>-10)
return 1;
return 1+noOfDig(n/10);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the value of n: ");
int n = in.nextInt();
System.out.println("Number of digits in the given number is: "+noOfDig(n/*, 0*/));
in.close();
}
}
|
/**
*/
package Metamodell.model.metamodell.provider;
import Metamodell.model.metamodell.util.MetamodellAdapterFactory;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.edit.provider.ChangeNotifier;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.IChangeNotifier;
import org.eclipse.emf.edit.provider.IDisposable;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.INotifyChangedListener;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
/**
* This is the factory that is used to provide the interfaces needed to support Viewers.
* The adapters generated by this factory convert EMF adapter notifications into calls to {@link #fireNotifyChanged fireNotifyChanged}.
* The adapters also support Eclipse property sheets.
* Note that most of the adapters are shared among multiple instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class MetamodellItemProviderAdapterFactory extends MetamodellAdapterFactory implements ComposeableAdapterFactory, IChangeNotifier, IDisposable {
/**
* This keeps track of the root adapter factory that delegates to this adapter factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ComposedAdapterFactory parentAdapterFactory;
/**
* This is used to implement {@link org.eclipse.emf.edit.provider.IChangeNotifier}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IChangeNotifier changeNotifier = new ChangeNotifier();
/**
* This keeps track of all the supported types checked by {@link #isFactoryForType isFactoryForType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection supportedTypes = new ArrayList();
/**
* This constructs an instance.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MetamodellItemProviderAdapterFactory() {
supportedTypes.add(IEditingDomainItemProvider.class);
supportedTypes.add(IStructuredItemContentProvider.class);
supportedTypes.add(ITreeItemContentProvider.class);
supportedTypes.add(IItemLabelProvider.class);
supportedTypes.add(IItemPropertySource.class);
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.System} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SystemItemProvider systemItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.System}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createSystemAdapter() {
if (systemItemProvider == null) {
systemItemProvider = new SystemItemProvider(this);
}
return systemItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.Hardware} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected HardwareItemProvider hardwareItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.Hardware}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createHardwareAdapter() {
if (hardwareItemProvider == null) {
hardwareItemProvider = new HardwareItemProvider(this);
}
return hardwareItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.Software} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SoftwareItemProvider softwareItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.Software}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createSoftwareAdapter() {
if (softwareItemProvider == null) {
softwareItemProvider = new SoftwareItemProvider(this);
}
return softwareItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.Brick} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected BrickItemProvider brickItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.Brick}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createBrickAdapter() {
if (brickItemProvider == null) {
brickItemProvider = new BrickItemProvider(this);
}
return brickItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.Motor} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected MotorItemProvider motorItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.Motor}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createMotorAdapter() {
if (motorItemProvider == null) {
motorItemProvider = new MotorItemProvider(this);
}
return motorItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.Sensor} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SensorItemProvider sensorItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.Sensor}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createSensorAdapter() {
if (sensorItemProvider == null) {
sensorItemProvider = new SensorItemProvider(this);
}
return sensorItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.OSEKSystem} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected OSEKSystemItemProvider osekSystemItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.OSEKSystem}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createOSEKSystemAdapter() {
if (osekSystemItemProvider == null) {
osekSystemItemProvider = new OSEKSystemItemProvider(this);
}
return osekSystemItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.Event} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EventItemProvider eventItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.Event}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createEventAdapter() {
if (eventItemProvider == null) {
eventItemProvider = new EventItemProvider(this);
}
return eventItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.Task} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected TaskItemProvider taskItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.Task}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createTaskAdapter() {
if (taskItemProvider == null) {
taskItemProvider = new TaskItemProvider(this);
}
return taskItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.Alarm} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected AlarmItemProvider alarmItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.Alarm}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createAlarmAdapter() {
if (alarmItemProvider == null) {
alarmItemProvider = new AlarmItemProvider(this);
}
return alarmItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.Connection} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ConnectionItemProvider connectionItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.Connection}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createConnectionAdapter() {
if (connectionItemProvider == null) {
connectionItemProvider = new ConnectionItemProvider(this);
}
return connectionItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.SWC} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SWCItemProvider swcItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.SWC}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createSWCAdapter() {
if (swcItemProvider == null) {
swcItemProvider = new SWCItemProvider(this);
}
return swcItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.Triggerport} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected TriggerportItemProvider triggerportItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.Triggerport}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createTriggerportAdapter() {
if (triggerportItemProvider == null) {
triggerportItemProvider = new TriggerportItemProvider(this);
}
return triggerportItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.SenderReceiverport} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SenderReceiverportItemProvider senderReceiverportItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.SenderReceiverport}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createSenderReceiverportAdapter() {
if (senderReceiverportItemProvider == null) {
senderReceiverportItemProvider = new SenderReceiverportItemProvider(this);
}
return senderReceiverportItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link Metamodell.model.metamodell.Runnable} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected RunnableItemProvider runnableItemProvider;
/**
* This creates an adapter for a {@link Metamodell.model.metamodell.Runnable}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createRunnableAdapter() {
if (runnableItemProvider == null) {
runnableItemProvider = new RunnableItemProvider(this);
}
return runnableItemProvider;
}
/**
* This returns the root adapter factory that contains this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ComposeableAdapterFactory getRootAdapterFactory() {
return parentAdapterFactory == null ? this : parentAdapterFactory.getRootAdapterFactory();
}
/**
* This sets the composed adapter factory that contains this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setParentAdapterFactory(ComposedAdapterFactory parentAdapterFactory) {
this.parentAdapterFactory = parentAdapterFactory;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isFactoryForType(Object type) {
return supportedTypes.contains(type) || super.isFactoryForType(type);
}
/**
* This implementation substitutes the factory itself as the key for the adapter.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter adapt(Notifier notifier, Object type) {
return super.adapt(notifier, this);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object adapt(Object object, Object type) {
if (isFactoryForType(type)) {
Object adapter = super.adapt(object, type);
if (!(type instanceof Class) || (((Class)type).isInstance(adapter))) {
return adapter;
}
}
return null;
}
/**
* This adds a listener.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void addListener(INotifyChangedListener notifyChangedListener) {
changeNotifier.addListener(notifyChangedListener);
}
/**
* This removes a listener.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void removeListener(INotifyChangedListener notifyChangedListener) {
changeNotifier.removeListener(notifyChangedListener);
}
/**
* This delegates to {@link #changeNotifier} and to {@link #parentAdapterFactory}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void fireNotifyChanged(Notification notification) {
changeNotifier.fireNotifyChanged(notification);
if (parentAdapterFactory != null) {
parentAdapterFactory.fireNotifyChanged(notification);
}
}
/**
* This disposes all of the item providers created by this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void dispose() {
if (systemItemProvider != null) systemItemProvider.dispose();
if (hardwareItemProvider != null) hardwareItemProvider.dispose();
if (softwareItemProvider != null) softwareItemProvider.dispose();
if (brickItemProvider != null) brickItemProvider.dispose();
if (motorItemProvider != null) motorItemProvider.dispose();
if (sensorItemProvider != null) sensorItemProvider.dispose();
if (osekSystemItemProvider != null) osekSystemItemProvider.dispose();
if (eventItemProvider != null) eventItemProvider.dispose();
if (taskItemProvider != null) taskItemProvider.dispose();
if (alarmItemProvider != null) alarmItemProvider.dispose();
if (connectionItemProvider != null) connectionItemProvider.dispose();
if (swcItemProvider != null) swcItemProvider.dispose();
if (triggerportItemProvider != null) triggerportItemProvider.dispose();
if (senderReceiverportItemProvider != null) senderReceiverportItemProvider.dispose();
if (runnableItemProvider != null) runnableItemProvider.dispose();
}
}
|
package org.point85.domain.rmq;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import org.point85.domain.collector.CollectorDataSource;
import org.point85.domain.collector.DataSourceType;
import org.point85.domain.dto.RmqSourceDto;
@Entity
@DiscriminatorValue(DataSourceType.RMQ_VALUE)
public class RmqSource extends CollectorDataSource {
public RmqSource() {
super();
setDataSourceType(DataSourceType.RMQ);
}
public RmqSource(String name, String description) {
super(name, description);
setDataSourceType(DataSourceType.RMQ);
}
public RmqSource(RmqSourceDto dto) {
super(dto);
setDataSourceType(DataSourceType.RMQ);
}
@Override
public String getId() {
return getName();
}
@Override
public void setId(String id) {
setName(id);
}
}
|
/**
* Description: Generalized Rounding Routines
* Implements Micah Altman code for rounding Numbers
* The implementation is in method Genround
* Input: int with number of digits including the decimal point,
* Object obj to apply the rounding routine;
* obj is of class Number and any of its derived sub-classes.
*
* Output: String representation of Object obj in canonical form.
* Example :/*
* Canonical form:
* -leading + or -
* -leading digit
* -decimal point
* -up to digits-1 no trailing 0
* -'e'
* -sign either + or -
* -exponent digits no leading 0
* Number -2.123498e+22, +1.56e+1, -1.3456e-, +3.4222e+
* mantissa= digits after the decimal point & decimal point
* exponent= digits after 'e' and the sign that follows
*
* Usage: For Number, e.g Double number and int digits
* roundRoutines<Double> rout = new roundRoutines<Double>();
* rout.Genround(number,digits);
* For BigDecimal number,
* roundRoutines<BigDecimal> routb = new roundRoutines<BigDecimal>();
* routb.Genround(new BigDecimal(number),digits);
*
* For String of chars, e.g. String ss = "news from ado";
* roundRoutines.Genround(ss,digits);
*
* @Author: Elena Villalon
* <a heref= email: evillalon@iq.harvard.edu/>
*
*/
package edu.harvard.iq.vdcnet;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RoundRoutines<T extends Number> implements UnfCons{
public static final long serialVersionUID=1111L;
private static Logger mLog = Logger.getLogger(RoundRoutines.class.getName());
/**number of digits with decimal point*/
private int digits;
/**the Locale language and country*/
private Locale loc;
/**some formatting for special numbers*/
private FormatNumbSymbols symb = new FormatNumbSymbols();
/**no leading and trailing 0 digits in exponent and mantissa*/
private static final boolean nozero=true; //default is true
/** radix for numbers*/
private int radix=10;
/**unicode characters*/
private static final char dot=Ucnt.dot.getUcode();//decimal separator "."
private static final char plus=Ucnt.plus.getUcode(); //"+" sign
private static final char min=Ucnt.min.getUcode(); //"-"
private static final char e=Ucnt.e.getUcode(); //"e"
private static final char percntg= Ucnt.percntg.getUcode(); //"%"
private static final char pndsgn=Ucnt.pndsgn.getUcode(); //"#"
private static final char zero =Ucnt.zero.getUcode();
private static final char s =Ucnt.s.getUcode();//"s"
private static final char ffeed = Ucnt.frmfeed.getUcode();
private static final char creturn =Ucnt.psxendln.getUcode();
/** whether to append the null byte ('\0') the end of string */
private static boolean nullbyte=true;
/** check conversion from string to numeric for mix
* columns values (i.e. column can have chars and numbers)
* */
private static boolean convertToNumber = false;
/**
* Default constructor
*/
public RoundRoutines(){
if(!DEBUG)
mLog.setLevel(Level.WARNING);
this.digits=DEF_NDGTS;
this.symb = new FormatNumbSymbols();
}
public RoundRoutines(boolean no){
this();
nullbyte = no;
}
/**
*
* @param digitsint
* Number of decimal digits including the decimal point
*/
public RoundRoutines(int digits,boolean no){
this(no);
if(digits < 1) digits=1; //count for decimal separator
//upper value is limited
this.digits = digits <= INACCURATE_SPRINTF_DIGITS ? digits : INACCURATE_SPRINTF_DIGITS;
}
/**
*
* @param digitsint
* @param loc the default locale
*/
public RoundRoutines(int digits, boolean no,Locale loc){
this(digits,no);
this.loc = loc;
}
/**
*
* @return boolean indicating if null byte
* is appended end of String
*/
public boolean getNullbyte(){
return nullbyte;
}
public void setNullbyte(boolean b){
nullbyte = b;
}
/**
* @param obj Object of class Number and sub-classes
* @param digits int total decimal digits including decimal point
* @return String with canonical formatting
*/
public String Genround(T obj, int digits){
return Genround(obj, digits, nullbyte);
}
/**
* @param obj Object of class Number and sub-classes
* @param digits int Number of decimal digits with decimal point
* @param no boolean indicating whether null byte ('\0') is appended
*/
public String Genround(T obj, int digits, boolean no) {
RoundRoutines.nullbyte=no;
// TODO Auto-generated method stub
BigDecimal objbint=null;
boolean bigNumber = (obj instanceof BigDecimal) ? true:false;
if(obj instanceof BigInteger){
bigNumber = true;
objbint = new BigDecimal((BigInteger) obj);
}
StringBuilder build = new StringBuilder();
String fmt, fmtu, tmp;
//the decimal separator symbol locally
char sep = symb.getDecimalSep();
if(digits< 0) digits = this.digits;
Double n = obj.doubleValue();
if(sep != dot){
mLog.warning("RoundRoutines: Decimal separator is not " +
"'\u002E' or a dot:.");
sep='.';
}
//check infinity or NaN for Double inputs
if(!(obj instanceof BigDecimal) && (objbint==null) &&
(tmp = RoundRoutinesUtils.specialNumb(n)) != null)
return tmp;
char[] str= {percntg, plus,pndsgn,sep}; //{'%','+', '#', '.'}
int dgt=(INACCURATE_SPRINTF)?INACCURATE_SPRINTF_DIGITS:(digits-1);
fmt= new String("%+#."+dgt+"e");
//using the Unicode character symbols
build.append(str);
build.append(dgt);
build.append(e);
fmtu = build.toString();
build = null;
if(!fmtu.equalsIgnoreCase(fmt)&& loc==new Locale("en", "US"))
mLog.severe("RoundRoutines: Unicode & format strings do not agree");
if(obj instanceof BigDecimal)
tmp = String.format(loc, fmtu, obj);
else if (objbint != null)
tmp= String.format(loc, fmtu, objbint);
else
tmp = String.format(loc, fmtu, n);//double representation with full precision
//check infinity or NaN for BigDecimal
if(tmp.equalsIgnoreCase("Infinity") ||
tmp.equalsIgnoreCase("-Infinity") ||
tmp.equalsIgnoreCase("NaN")){
mLog.warning("RoundRoutines: infinite or nan encounter");
return tmp;
}
String atoms [] =tmp.split(e+"");
//e.g., Number -2.123498e+22; atoms[0]=-2.123498 & atoms[1]=+22
build= calcMantissa(atoms[0],sep);
build.append(e);
build.append(atoms[1].charAt(0)); //sign of exponent
build.append(calcExponent(atoms[1]));
return build.toString();
}
/**
*
* @param obj Object of class Number and sub-classes
* @param digits int number of decimal digits to keep
* @param charsetString with optional charset to encode bytes
* @return byte array encoded with charset
*/
public byte[] GenroundBytes(T obj, int digits, String... charset)
throws UnsupportedEncodingException{
String str = Genround(obj, digits);
String finstr = charset[0];
if(str==null || str.equals(""))
return null;
Charset original= Charset.defaultCharset();
Charset to = original;
if(charset.length>0 && Charset.isSupported(charset[0])){
to = Charset.forName(charset[0]);
if(!to.canEncode()) {
finstr = textencoding;
to=original;
}
}
return str.getBytes(finstr);
}
/**
*
* @param atom String with the exponent including the sign
* @return StringBuffer representing exponent with no leading 0
* and appending the end of line.
*/
private StringBuffer calcExponent(String atom){
StringBuffer build = new StringBuffer();
String expnt = atom.substring(1);
long lngmant = Long.parseLong(expnt);//remove leading 0's
if(lngmant > 0 || (lngmant == 0 && !nozero))
build.append(lngmant);
//adding end-line :"\n"
// String nl = System.getProperty("line.separator");
//build.append(nl); //end of line
//build.append(ffeed);
/**
* per specs append the end of line "\n" and
* null terminator
*/
build.append(creturn);
if(nullbyte)
build.append(nil);
return build;
}
/**
*
* @param atom String with the mantissa
* @param sep char the decimal point
* @param f boolean for number between (-1,1)
* @return StringBuilder with mantissa after removing trailing 0
*/
private StringBuilder calcMantissa(String atom, char sep){
StringBuilder build = new StringBuilder();
//sign and leading digit before decimal separator
char mag[] = {atom.charAt(0), atom.charAt(1)};
//canon[] :double check you have correct results
String canon[] = atom.split("\\"+sep);
if(!canon[0].equalsIgnoreCase(new String(mag)))
mLog.severe("RoundRoutines:decimal separator no in right place");
build.append(mag);//sign and leading digit
build.append(sep);//decimal separator
String dec = atom.substring(3);//decimal part
if(!dec.equalsIgnoreCase(canon[1]))
mLog.severe("RoundRoutines: decimal separator not right");
String tmp= new StringBuffer(dec).reverse().toString();
long tmpl = Long.parseLong(tmp); //remove trailing 0's
tmp = new StringBuffer((Long.toString(tmpl))).reverse().toString();
//removing trailing 0
if(tmpl== 0 && nozero) return build;
return build.append(tmp);
}
/**
* @param cobj CharSequence to format
* @param digitsint number of characters to keep
* @return String formatted
*/
public String Genround(CharSequence cobj, int digits){
return Genround(cobj,digits, nullbyte);
}
public static String Genround(CharSequence cobj, int digits, boolean no){
if((((String)cobj).trim()).equals("")){
String res=null;
if(cobj.length() > digits)
res = (String) cobj.subSequence(0, digits-1);
res+=creturn;
if(no) res+= nil;
return res;
}
boolean numeric =false;
if(convertToNumber)
numeric=RoundRoutinesUtils.checkNumeric(cobj);
if(numeric){
//only digits in obj use a BigInteger representation
BigInteger bg = new BigInteger(cobj.toString());
RoundRoutines<BigInteger> rout = new RoundRoutines<BigInteger>();
return rout.Genround(bg, digits,no);
}
//if is not digits
return (new RoundString().Genround((String) cobj, digits,no));
}
private static void testme() throws Exception {
RoundRoutines<Double> rout = new RoundRoutines<Double>();
mLog.info("*********************");
mLog.info(rout.Genround(3344556677.786549,15, false));
RoundRoutines<BigDecimal> routb = new RoundRoutines<BigDecimal>();
mLog.info("**********************");
mLog.info(routb.Genround(new BigDecimal(3344556677.786549),15,false));
RoundRoutines<BigInteger> routn = new RoundRoutines<BigInteger>();
mLog.info("**********************");
mLog.info(routn.Genround(new BigInteger("334455667788991122"),15,false));
rout = new RoundRoutines<Double>();
mLog.info("**********************");
mLog.info(rout.Genround(23.78,7,false));
rout = new RoundRoutines<Double>();
mLog.info("***********************");
mLog.info(rout.Genround(3.78,7,false));
mLog.info("***********************");
mLog.info(rout.Genround(3d,7,false));
mLog.info("**************************");
mLog.info(rout.Genround(0.000345,7,false));
mLog.info("**************************");
mLog.info(rout.Genround(-0.000345,7,false));
mLog.info("**************************");
mLog.info(rout.Genround(-1.0,7,false));
mLog.info("**************************");
mLog.info(rout.Genround(1.0,-1,false));
String ss = "news from ado";
mLog.info(RoundRoutines.Genround(ss,7, false));
mLog.info(rout.Genround(1.0,-1,false));
mLog.info("**************************");
ss = "1122334455 6677";
mLog.info(ss);
mLog.info(RoundRoutines.Genround(ss,7,false));
byte[] issb ={'\u0073', 101, 119, 115, 32};
byte [] nb = {111,(byte) 222,(byte) 333,(byte) 444};
mLog.info(""+ new String(issb));
mLog.info(""+ new String(nb));
String str = "mmmm ggggg hhhh jjj";
mLog.info("*********************");
BigDecimal bd = new BigDecimal(12345678.12345678);
mLog.info("Eng String: "+ bd.toEngineeringString());
mLog.info("String: "+ bd.unscaledValue());
mLog.info("*********************");
MathContext mth = new MathContext(7);
mLog.info("Mth Context: "+ mth.getRoundingMode());
mLog.info("*********************");
String strt ="000012345678";
mLog.info(RoundRoutinesUtils.trimZeros(strt,true));
mLog.info(RoundRoutinesUtils.trimZeros(strt,false));
mLog.info("*********************");
String strr ="123456780000";
mLog.info(RoundRoutinesUtils.trimZeros(strr,true));
mLog.info(RoundRoutinesUtils.trimZeros(strr,false));
mLog.info("**********************");
mLog.info(rout.Genround(367.89345e8,7,false));
mLog.info("**********************");
mLog.info(rout.Genround(367.89345,7,false));
mLog.info("**********************");
mLog.info(rout.Genround(23.78e-10,7,false));
rout = new RoundRoutines<Double>();
}
//checking some inputs. Need some JUnit Tests
public static void main(String args[]) throws Exception{
testme();
}
}
|
package core.client.game.operations.basics;
import cards.Card;
import cards.basics.Peach;
import cards.basics.Wine;
import commands.server.ingame.InGameServerCommand;
import commands.server.ingame.RescueReactionInGameServerCommand;
import core.client.game.operations.AbstractSingleCardReactionOperation;
import core.player.PlayerInfo;
public class RescueReactionOperation extends AbstractSingleCardReactionOperation {
private final PlayerInfo dyingPlayer;
public RescueReactionOperation(PlayerInfo dyingPlayer, String message) {
super(message);
this.dyingPlayer = dyingPlayer;
}
@Override
protected boolean isCancelEnabled() {
return true;
}
@Override
protected boolean isCardActivatable(Card card) {
if (this.getSelf().getPlayerInfo().equals(dyingPlayer)) {
// may use Wine or Peach to save oneself
return card instanceof Wine || card instanceof Peach;
} else {
// may use Peach to save others
return card instanceof Peach;
}
}
@Override
protected void onLoadedCustom() {
// TODO send event to activate skills
}
@Override
protected void onUnloadedCustom() {
// TODO send event to deactivate skills
}
@Override
protected InGameServerCommand getCommandOnConfirm() {
return new RescueReactionInGameServerCommand(this.getFirstCardUI().getCard());
}
@Override
protected InGameServerCommand getCommandOnInaction() {
return new RescueReactionInGameServerCommand(null);
}
}
|
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.scheduling.quartz;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.quartz.SchedulerConfigException;
import org.quartz.impl.jdbcjobstore.JobStoreCMT;
import org.quartz.impl.jdbcjobstore.SimpleSemaphore;
import org.quartz.spi.ClassLoadHelper;
import org.quartz.spi.SchedulerSignaler;
import org.quartz.utils.ConnectionProvider;
import org.quartz.utils.DBConnectionManager;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.jdbc.support.MetaDataAccessException;
import org.springframework.lang.Nullable;
/**
* Subclass of Quartz's {@link JobStoreCMT} class that delegates to a Spring-managed
* {@link DataSource} instead of using a Quartz-managed JDBC connection pool.
* This JobStore will be used if SchedulerFactoryBean's "dataSource" property is set.
* You may also configure it explicitly, possibly as a custom subclass of this
* {@code LocalDataSourceJobStore} or as an equivalent {@code JobStoreCMT} variant.
*
* <p>Supports both transactional and non-transactional DataSource access.
* With a non-XA DataSource and local Spring transactions, a single DataSource
* argument is sufficient. In case of an XA DataSource and global JTA transactions,
* SchedulerFactoryBean's "nonTransactionalDataSource" property should be set,
* passing in a non-XA DataSource that will not participate in global transactions.
*
* <p>Operations performed by this JobStore will properly participate in any
* kind of Spring-managed transaction, as it uses Spring's DataSourceUtils
* connection handling methods that are aware of a current transaction.
*
* <p>Note that all Quartz Scheduler operations that affect the persistent
* job store should usually be performed within active transactions,
* as they assume to get proper locks etc.
*
* @author Juergen Hoeller
* @since 1.1
* @see SchedulerFactoryBean#setDataSource
* @see SchedulerFactoryBean#setNonTransactionalDataSource
* @see SchedulerFactoryBean#getConfigTimeDataSource()
* @see SchedulerFactoryBean#getConfigTimeNonTransactionalDataSource()
* @see org.springframework.jdbc.datasource.DataSourceUtils#doGetConnection
* @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
*/
@SuppressWarnings("unchecked") // due to a warning in Quartz 2.2's JobStoreCMT
public class LocalDataSourceJobStore extends JobStoreCMT {
/**
* Name used for the transactional ConnectionProvider for Quartz.
* This provider will delegate to the local Spring-managed DataSource.
* @see org.quartz.utils.DBConnectionManager#addConnectionProvider
* @see SchedulerFactoryBean#setDataSource
*/
public static final String TX_DATA_SOURCE_PREFIX = "springTxDataSource.";
/**
* Name used for the non-transactional ConnectionProvider for Quartz.
* This provider will delegate to the local Spring-managed DataSource.
* @see org.quartz.utils.DBConnectionManager#addConnectionProvider
* @see SchedulerFactoryBean#setDataSource
*/
public static final String NON_TX_DATA_SOURCE_PREFIX = "springNonTxDataSource.";
@Nullable
private DataSource dataSource;
@Override
public void initialize(ClassLoadHelper loadHelper, SchedulerSignaler signaler) throws SchedulerConfigException {
// Absolutely needs thread-bound DataSource to initialize.
this.dataSource = SchedulerFactoryBean.getConfigTimeDataSource();
if (this.dataSource == null) {
throw new SchedulerConfigException("No local DataSource found for configuration - " +
"'dataSource' property must be set on SchedulerFactoryBean");
}
// Configure transactional connection settings for Quartz.
setDataSource(TX_DATA_SOURCE_PREFIX + getInstanceName());
setDontSetAutoCommitFalse(true);
// Register transactional ConnectionProvider for Quartz.
DBConnectionManager.getInstance().addConnectionProvider(
TX_DATA_SOURCE_PREFIX + getInstanceName(),
new ConnectionProvider() {
@Override
public Connection getConnection() throws SQLException {
// Return a transactional Connection, if any.
return DataSourceUtils.doGetConnection(dataSource);
}
@Override
public void shutdown() {
// Do nothing - a Spring-managed DataSource has its own lifecycle.
}
@Override
public void initialize() {
// Do nothing - a Spring-managed DataSource has its own lifecycle.
}
}
);
// Non-transactional DataSource is optional: fall back to default
// DataSource if not explicitly specified.
DataSource nonTxDataSource = SchedulerFactoryBean.getConfigTimeNonTransactionalDataSource();
final DataSource nonTxDataSourceToUse = (nonTxDataSource != null ? nonTxDataSource : this.dataSource);
// Configure non-transactional connection settings for Quartz.
setNonManagedTXDataSource(NON_TX_DATA_SOURCE_PREFIX + getInstanceName());
// Register non-transactional ConnectionProvider for Quartz.
DBConnectionManager.getInstance().addConnectionProvider(
NON_TX_DATA_SOURCE_PREFIX + getInstanceName(),
new ConnectionProvider() {
@Override
public Connection getConnection() throws SQLException {
// Always return a non-transactional Connection.
return nonTxDataSourceToUse.getConnection();
}
@Override
public void shutdown() {
// Do nothing - a Spring-managed DataSource has its own lifecycle.
}
@Override
public void initialize() {
// Do nothing - a Spring-managed DataSource has its own lifecycle.
}
}
);
// No, if HSQL is the platform, we really don't want to use locks...
try {
String productName = JdbcUtils.extractDatabaseMetaData(this.dataSource,
DatabaseMetaData::getDatabaseProductName);
productName = JdbcUtils.commonDatabaseName(productName);
if (productName != null && productName.toLowerCase().contains("hsql")) {
setUseDBLocks(false);
setLockHandler(new SimpleSemaphore());
}
}
catch (MetaDataAccessException ex) {
logWarnIfNonZero(1, "Could not detect database type. Assuming locks can be taken.");
}
super.initialize(loadHelper, signaler);
}
@Override
protected void closeConnection(Connection con) {
// Will work for transactional and non-transactional connections.
DataSourceUtils.releaseConnection(con, this.dataSource);
}
}
|
package tw.com.rex.springsecuritypractice.handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component("securityHandler")
public class AppSecurityHandler extends SavedRequestAwareAuthenticationSuccessHandler {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private RequestCache requestCache = new HttpSessionRequestCache();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
authentication.getAuthorities().forEach(
authority -> logger.info("handler authority: {}", authority.getAuthority()));
redirectStrategy.sendRedirect(request, response, "/user/main");
}
}
|
package it.polito.tdp.borders.model;
import java.util.HashMap;
import java.util.Map;
import org.jgrapht.Graph;
import org.jgrapht.event.ConnectedComponentTraversalEvent;
import org.jgrapht.event.EdgeTraversalEvent;
import org.jgrapht.event.TraversalListener;
import org.jgrapht.event.VertexTraversalEvent;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import org.jgrapht.traverse.BreadthFirstIterator;
import org.jgrapht.traverse.GraphIterator;
public class AlberoDiVisita {
private Graph<Country, DefaultEdge> grafo = new SimpleGraph<>(DefaultEdge.class);
private Map<Country, Country> albero;
public Map<Country, Country> alberoVisita(Country source, Graph<Country, DefaultEdge> graph){
this.grafo = graph;
albero = new HashMap<>();
albero.put(source, null);
GraphIterator<Country, DefaultEdge> bfv = new BreadthFirstIterator<>(grafo, source);
bfv.addTraversalListener(new TraversalListener<Country, DefaultEdge>(){
@Override
public void connectedComponentFinished(ConnectedComponentTraversalEvent e) {
// TODO Auto-generated method stub
}
@Override
public void connectedComponentStarted(ConnectedComponentTraversalEvent e) {
// TODO Auto-generated method stub
}
@Override
public void edgeTraversed(EdgeTraversalEvent<DefaultEdge> e) {
DefaultEdge edge = e.getEdge();
Country a = grafo.getEdgeSource(edge);
Country b = grafo.getEdgeSource(edge);
if(albero.containsKey(a) && !albero.containsKey(b)) {
albero.put(b, a);
}else {
albero.put(a, b);
}
}
@Override
public void vertexTraversed(VertexTraversalEvent<Country> e) {
// TODO Auto-generated method stub
}
@Override
public void vertexFinished(VertexTraversalEvent<Country> e) {
// TODO Auto-generated method stub
}
});
while(bfv.hasNext()) {
bfv.next();
}
return albero;
}
}
|
package com.loneless;
import com.github.javafaker.Faker;
import java.util.Random;
public class DataGenerator {
private static final DataGenerator instance =new DataGenerator();
private static final Faker faker =new Faker();// прикольная "генерация" объектов - это для базовых значений
private static final Random random=new Random();
private DataGenerator(){}
public static DataGenerator getInstance() {
return instance;
}
public Faker getFaker(){
return faker;
}
public Random getRandom(){
return random;
}
}
|
package com.trump.auction.reactor.ext.repository;
import com.google.common.collect.Collections2;
import com.google.common.collect.Maps;
import com.trump.auction.reactor.api.model.Bidder;
import com.trump.auction.reactor.common.repository.AbstractRedisRepository;
import com.trump.auction.reactor.api.model.AccountCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* {@link BidCostRepository} 实现类
*
* @author Owen
* @since 2018/1/24
*/
@Component
public class DefaultBidCostRepository extends AbstractRedisRepository implements BidCostRepository {
@Autowired
private StringRedisTemplate redisTemplate;
@Override
public void increase(String auctionNo, Bidder bidder, AccountCode accountCode) {
redisTemplate.opsForHash().increment(key(auctionNo), field(bidder, accountCode), 1);
}
@Override
public int get(String auctionNo, Bidder bidder, AccountCode accountCode) {
Object result = redisTemplate.opsForHash().get(key(auctionNo), field(bidder, accountCode));
return parseInt(result);
}
private int parseInt(Object result) {
return parseInt((String) result);
}
private int parseInt(String result) {
return StringUtils.isEmpty(result) ? 0 : Integer.valueOf(result);
}
@Override
public Map<AccountCode, Integer> get(String auctionNo, Bidder bidder) {
List<Object> cost = redisTemplate.opsForHash().multiGet(key(auctionNo), Collections2.transform(
AccountCode.ALL_OF, (code) -> field(bidder, code)));
if (CollectionUtils.isEmpty(cost)) {
return Collections.EMPTY_MAP;
}
Map<AccountCode, Integer> result = Maps.newHashMap();
int index = 0;
for (AccountCode accountCode : AccountCode.ALL_OF) {
result.put(accountCode, parseInt(cost.get(index)));
index++;
}
return result;
}
protected String key(String auctionNo) {
return makeKey(auctionNo, "bid-cost");
}
protected String field(Bidder bidder, AccountCode accountCode) {
return bidder.getId() + ":" + accountCode.val();
}
}
|
package com.huawei.account.service.impl;
import com.huawei.account.domain.Account;
import com.huawei.account.domain.Bill;
import com.huawei.account.domain.Bill_Code;
import com.huawei.account.domain.Services;
import com.huawei.account.mapper.AccountMapper;
import com.huawei.account.service.AccountService;
import com.huawei.base.utils.PageBean;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by dllo on 17/11/16.
*/
@Service
public class AccountServiceImpl implements AccountService {
@Resource
private AccountMapper accountMapper;
public PageBean<Account> findAllAccount(Integer pageNum, int pageSize, Account account) {
int totalCount = accountMapper.findAccountCount(account);
PageBean<Account> pageBean = new PageBean(pageNum, pageSize, totalCount);
pageBean.setT(account);
List<Account> roles = accountMapper.findAllAccount(pageBean);
pageBean.setData(roles);
return pageBean;
}
public int setState(Account account) {
return accountMapper.setState(account);
}
public int deleteAccount(Account account) {
accountMapper.deleteAcc_Ser(account);
return accountMapper.deleteAccount(account);
}
public int findSingle(String re_idcard) {
return accountMapper.findSingle(re_idcard);
}
public int addAccount(Account account) {
return accountMapper.addAccount(account);
}
public PageBean<Services> findAllService(Integer pageNum, int pageSize) {
int totalCount = accountMapper.findServiceCount();
PageBean<Services> pageBean = new PageBean(pageNum, pageSize, totalCount);
List<Services> services = accountMapper.findAllService(pageBean);
pageBean.setData(services);
return pageBean;
}
public PageBean<Bill> findAllBill(Integer pageNum, int pageSize) {
int totalCount = accountMapper.findBillCount();
PageBean<Bill> pageBean = new PageBean(pageNum, pageSize, totalCount);
List<Bill> bills = accountMapper.findAllBill(pageBean);
pageBean.setData(bills);
return pageBean;
}
public Account findAccountById(int account_id) {
return accountMapper.findAccountById(account_id);
}
public PageBean<Bill_Code> findAllBill_code(Integer pageNum, int pageSize) {
int totalCount = accountMapper.findBill_CodeCount();
PageBean<Bill_Code> pageBean = new PageBean(pageNum, pageSize, totalCount);
List<Bill_Code> bill_codes = accountMapper.findAllBill_Code(pageBean);
pageBean.setData(bill_codes);
return pageBean;
}
}
|
package com.esum.wp.as2.sslsetup.base;
import com.esum.appframework.dmo.BaseDMO;
public class BaseSSLInfo extends BaseDMO {
public static String REF = "SSLInfo";
public static String PROP_KEYSTORE_FILE = "KeyStoreFile";
public static String PROP_KEYSTORE_TYPE = "KeyStoreType";
public static String PROP_KEYSTORE_PASSWORD = "KeyStorePassword";
public static String PROP_CLIENT_AUTH_USE = "ClientAuthUse";
public static String PROP_TRUSTSTORE_FILE = "TrustStoreFile";
public static String PROP_TRUSTSTORE_PASSWORD = "TrustStorePassword";
public static String PROP_FLAG = "Flag";
protected java.lang.String keyStoreFile;
protected java.lang.String keyStoreType;
protected java.lang.String keyStorePassword;
protected java.lang.String clientAuthUse;
protected java.lang.String trustStoreFile;
protected java.lang.String trustStorePassword;
protected java.lang.String flag;
protected java.lang.String node_name;
// constructors
public BaseSSLInfo() {
initialize();
}
protected void initialize() {
keyStoreFile = "";
keyStoreType = "";
keyStorePassword = "";
clientAuthUse = "";
trustStoreFile = "";
trustStorePassword = "";
flag = "";
node_name = "";
}
public java.lang.String getNode_name() {
return node_name;
}
public void setNode_name(java.lang.String node_name) {
this.node_name = node_name;
}
/**
*
*
* @return Returns the clientAuthUse.
*/
public java.lang.String getClientAuthUse() {
return clientAuthUse;
}
/**
*
*
* @param clientAuthUse
* The clientAuthUse to set.
*/
public void setClientAuthUse(java.lang.String clientAuthUse) {
this.clientAuthUse = clientAuthUse;
}
/**
*
*
* @return Returns the keyStoreFile.
*/
public java.lang.String getKeyStoreFile() {
return keyStoreFile;
}
/**
*
*
* @param keyStoreFile
* The keyStoreFile to set.
*/
public void setKeyStoreFile(java.lang.String keyStoreFile) {
this.keyStoreFile = keyStoreFile;
}
/**
*
*
* @return Returns the keyStorePassword.
*/
public java.lang.String getKeyStorePassword() {
return keyStorePassword;
}
/**
*
*
* @param keyStorePassword
* The keyStorePassword to set.
*/
public void setKeyStorePassword(java.lang.String keyStorePassword) {
this.keyStorePassword = keyStorePassword;
}
/**
*
*
* @return Returns the keyStoreType.
*/
public java.lang.String getKeyStoreType() {
return keyStoreType;
}
/**
*
*
* @param keyStoreType
* The keyStoreType to set.
*/
public void setKeyStoreType(java.lang.String keyStoreType) {
this.keyStoreType = keyStoreType;
}
/**
*
*
* @return Returns the trustStoreFile.
*/
public java.lang.String getTrustStoreFile() {
return trustStoreFile;
}
/**
*
*
* @param trustStoreFile
* The trustStoreFile to set.
*/
public void setTrustStoreFile(java.lang.String trustStoreFile) {
this.trustStoreFile = trustStoreFile;
}
/**
*
*
* @return Returns the trustStorePassword.
*/
public java.lang.String getTrustStorePassword() {
return trustStorePassword;
}
/**
*
*
* @param trustStorePassword
* The trustStorePassword to set.
*/
public void setTrustStorePassword(java.lang.String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
public java.lang.String getFlag() {
return flag;
}
public void setFlag(java.lang.String flag) {
this.flag = flag;
}
} |
package raig.org;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.runner.RunWith;
import org.junit.Test;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
@RunWith(DataProviderRunner.class)
public class FizzBuzzTest {
private static Logger logger = Logger.getLogger(FizzBuzzTest.class);
private FizzBuzzComponent createFizzBuzz() {
FbNumber fbNumber = new FbNumber();
FizzDecorator fizzDecorator = new FizzDecorator(fbNumber,3,"Fizz");
FizzDecorator buzzDecorator = new FizzDecorator(fizzDecorator,5,"Buzz");
FizzDecorator fizzbuzzDecorator = new FizzDecorator(buzzDecorator,15,"FizzBuzz");
return fizzbuzzDecorator;
}
@Test
@UseDataProvider("dataProviderFizzBuzz")
public void sayTest(int number, String expectedResult) {
logger.info("Testing " + number );
FizzBuzzComponent fizzBuzz = createFizzBuzz();
String result = fizzBuzz.say(number);
Assert.assertEquals(expectedResult, result);
}
@DataProvider
public static Object[][] dataProviderFizzBuzz() {
// @formatter:off
return new Object[][] {
{1, "1"},
{2, "2"},
{3, "Fizz"},
{3 * 2, "Fizz"},
{5, "Buzz"},
{5 * 2, "Buzz"},
{5 * 3, "FizzBuzz"},
};
// @formatter:on
}
}
|
package ProjectAeroDTO;
import java.util.ArrayList;
public class Voo {
private String city_orig;
private int identificacao;
private String city_dest;
private ArrayList<Programacao> programacoes = new ArrayList<Programacao>();
private ArrayList<Passagem> passagens = new ArrayList<Passagem>();
public Voo(String city_orig, int identificacao, String city_dest) {
this.city_orig = city_orig;
this.identificacao = identificacao;
this.city_dest = city_dest;
}
public String getCity_orig() {
return city_orig;
}
public void setCity_orig(String city_orig) {
this.city_orig = city_orig;
}
public String getCity_dest() {
return city_dest;
}
public void setCity_dest(String city_dest) {
this.city_dest = city_dest;
}
public int getIdentificacao() {
return identificacao;
}
public void setIdentificacao(int identificacao) {
this.identificacao = identificacao;
}
}
|
public class Book {
String title;
String year;
String ISBN;
public Book(String title, String year, String ISBN) {
this.title = title;
this.year = year;
this.ISBN = ISBN;
}
public String getTitle() {
return title;
}
public String getYear() {
return year;
}
public String getISBN() {
return ISBN;
}
public void setTitle(String title) {
this.title = title;
}
public void setYear(String year) {
this.year = year;
}
public void setISBN(String ISBN) {
this.ISBN = ISBN;
}
}
|
package handlers.creep;
import DAO.MentorDAO;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import DAO.CreepDAO;
import helpers.CookieHandler;
import models.Mentor;
import models.User;
import org.jtwig.JtwigModel;
import org.jtwig.JtwigTemplate;
import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
public class CreepAddMentorHandler implements HttpHandler {
User user = null;
CookieHandler cookieHandler = new CookieHandler();
@Override
public void handle(HttpExchange httpExchange) throws IOException {
user = cookieHandler.cookieChecker(httpExchange);
if(user == null || user.getUserType() != 3){
httpExchange.getResponseHeaders().set("Location", "/login");
httpExchange.sendResponseHeaders(303, 0);
}
MentorDAO mentorDAO = new MentorDAO();
String method = httpExchange.getRequestMethod();
String response = "";
if (method.equals("GET")){
JtwigTemplate template = JtwigTemplate.classpathTemplate("templates/creep/addMentor.twig");
JtwigModel model = JtwigModel.newModel();
response = template.render(model);
}
if (method.equals("POST")){
InputStreamReader isr = new InputStreamReader(httpExchange.getRequestBody(),"utf-8");
BufferedReader br = new BufferedReader(isr);
String formData = br.readLine();
Map inputs = parseFormData(formData);
String login = inputs.get("login").toString();
String password = inputs.get("password").toString();
String firstName = inputs.get("firstName").toString();
String lastName = inputs.get("lastName").toString();
System.out.println(login +password+ firstName+lastName);
Mentor mentorToAdd = new Mentor(login,password,2,true,firstName,lastName);
System.out.println(mentorToAdd.getLastname());
mentorDAO.addMentor(mentorToAdd);
httpExchange.getResponseHeaders().set("Location", "/cyberStore/creep/showMentors");
httpExchange.sendResponseHeaders(303, 0);
}
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
private Map<String, String> parseFormData(String formData) {
Map<String, String> map = new HashMap<String, String>();
String[] pairs = formData.split("&");
for(String pair : pairs){
String[] keyValue = pair.split("=");
String value = null;
try {
value = new URLDecoder().decode(keyValue[1], "UTF-8");
map.put(keyValue[0], value);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return map;
}
}
|
package com.bruggy.collection;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private final int mSpanCount;
private final int mSpacing;
public GridSpacingItemDecoration(int spanCount, int spacing) {
mSpanCount = spanCount;
mSpacing = spacing;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view);
int column = position % mSpanCount;
outRect.left = column * mSpacing / mSpanCount;
outRect.right = mSpacing - (column + 1) * mSpacing / mSpanCount;
if (position >= mSpanCount) {
outRect.top = mSpacing;
}
}
}
|
package net.awesomekorean.podo.lesson.lessons;
import net.awesomekorean.podo.R;
import java.io.Serializable;
public class Lesson42 extends LessonInit_Lock implements Lesson, LessonItem, Serializable {
private String lessonId = "L_42";
private String lessonTitle = "asking1";
private String lessonSubTitle = "~(으)ㄹ래요?";
private String[] wordFront = {"배고프다", "갑자기", "맵다", "다르다"};
private String[] wordBack = {"hungry", "suddenly", "spicy", "different"};
private String[] wordPronunciation = {"-", "[갑짜기]", "[맵따]", "-"};
private String[] sentenceFront = {
"먹을래요?",
"뭐 좀 먹을래요?",
"매운 음식이 먹고 싶어요.",
"갑자기 매운 음식이 먹고 싶어요.",
"저 식당으로 갈래요?",
"저 식당은 맛없어요.",
"다른 곳으로 가요."
};
private String[] sentenceBack = {
"Do you want to eat?",
"Do you want to eat something?",
"I want to eat spicy food.",
"Suddenly I want to eat spicy food.",
"Would you like to go to that restaurant?",
"That restaurant is not tasty.",
"Let's go other place."
};
private String[] sentenceExplain = {
"You can ask your close friend a opinion of your suggestion by using '(으)ㄹ래요?' form.\n'먹다' -> '먹' + '을래요'\nThe answer is the same.\n\nex)\n'먹을래요?'\n'네, 먹을래요.'",
"-",
"'맵다' -> '매워요' -> '매운'",
"-",
"'가다' -> '가' + 'ㄹ래요?' = '갈래요?'",
"-",
"'다르다' means 'different' but \n'다른' can also be used not only 'different' but also 'other'.\n\n'아/어요' form is '달라요' (irregular)"
};
private String[] dialog = {
"뭐 좀 먹을래요?",
"배고파요?",
"네, 갑자기 매운 음식이 먹고 싶어요.",
"그래요. 저 식당으로 갈래요?",
"아니요. 저 식당은 맛없어요. 다른 곳으로 가요."
};
private int[] peopleImage = {R.drawable.male_b,R.drawable.female_p};
private int[] reviewId = {1,4,6};
@Override
public String getLessonSubTitle() {
return lessonSubTitle;
}
@Override
public String getLessonId() {
return lessonId;
}
@Override
public String[] getWordFront() {
return wordFront;
}
@Override
public String[] getWordPronunciation() {
return wordPronunciation;
}
@Override
public String[] getSentenceFront() {
return sentenceFront;
}
@Override
public String[] getDialog() {
return dialog;
}
@Override
public int[] getPeopleImage() {
return peopleImage;
}
@Override
public String[] getWordBack() {
return wordBack;
}
@Override
public String[] getSentenceBack() {
return sentenceBack;
}
@Override
public String[] getSentenceExplain() {
return sentenceExplain;
}
@Override
public int[] getReviewId() {
return reviewId;
}
// 레슨어뎁터 아이템
@Override
public String getLessonTitle() {
return lessonTitle;
}
}
|
package main.repository;
import main.employees.Contractor;
import main.employees.Employee;
import main.employees.Intern;
import main.employees.PermanentEmployee;
import java.util.ArrayList;
public class EmployeeRepository {
private static final ArrayList<Employee> employeeList = new ArrayList<>();
public EmployeeRepository() {
employeeList.add(new PermanentEmployee("John", "Doe", 75000));
employeeList.add(new PermanentEmployee("Jason", "Bourne", 95000));
employeeList.add(new PermanentEmployee("Xavier", "Abraham", 65000));
employeeList.add(new Intern("Rebecca", "Johnson", 45000));
employeeList.add(new Intern("Michael", "Richards", 40000));
employeeList.add(new Contractor("Jerry", "Seinfeld", 40000));
}
public ArrayList<Employee> getEmployees() {
return employeeList;
}
public void addEmployee(Employee employee) throws NullPointerException {
if (employee != null) {
employeeList.add(employee);
} else {
throw new NullPointerException("Employee cannot be null");
}
}
}
|
/**
* Created by robin on 2017/8/6.
*/
public class HomeView {
public void show(){
System.out.println("Displaying Home Page");
}
}
|
package Model;
import Interfaces.Entity;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
public class CFolder extends Entity{
private boolean isDirectory;
private HashMap<UUID,Entity> containedFiles ;
private HashMap<UUID,Entity> globalHashMap ;
private DirectoryAdder directoryAdder;
private CFolder parentNode ;
public CFolder(Path directory,CFolder parentNode,int treeDepth) {
super();
this.setTreeDeph(treeDepth);
this.setDirectory(directory);
this.setFile(new File(directory.toString()));
this.parentNode = parentNode;
if(getFile().isDirectory())
{
isDirectory = true;
this.directoryAdder = new DirectoryAdder(this);
directoryAdder.start();
}
else
{
System.out.println("Its not a directory ");
throw new IllegalArgumentException("Problem with directory path");
}
}
private class DirectoryAdder extends Thread
{
CFolder cFolder;
DirectoryAdder(CFolder cFolder)
{
this.cFolder = cFolder;
directoryAdder.start();
}
public void run()
{
System.out.println("Directory Adder started !" + cFolder.getTreeDeph() );
Path path;
Entity entity;
String pathExt;
for (File fileEntry: cFolder.getFile().listFiles() )
{
if(fileEntry.isDirectory())
{
path = Paths.get(fileEntry.getPath());
entity = new CFolder(path, cFolder, getTreeDeph() + 1);
cFolder.getContainedFiles().put(entity.getId(),entity);
}
else
{
path = Paths.get(fileEntry.getPath());
pathExt = path.toString().substring(path.toString().lastIndexOf("."));
entity = new CFile(path,cFolder,pathExt,getTreeDeph()+1);
cFolder.getContainedFiles().put(entity.getId(),entity);
}
}
}
}
public HashMap<UUID, Entity> getContainedFiles() {
return containedFiles;
}
public void setContainedFiles(HashMap<UUID, Entity> containedFiles) {
this.containedFiles = containedFiles;
}
public DirectoryAdder getDirectoryAdder() {
return directoryAdder;
}
public void setDirectoryAdder(DirectoryAdder directoryAdder) {
this.directoryAdder = directoryAdder;
}
public void addToGlobalHashList(Entity hashObject)
{
globalHashMap.put(hashObject.getId(),hashObject);
}
}
|
package com.igs.qhrzlc.presenter;
import android.content.Context;
/**
* 晒单详情
*/
public class PresenterOrderDetail extends BasePresenter {
private Context context;
public PresenterOrderDetail(Context context) {
this.context = context;
initDialog(context);
}
}
|
package com.edu.realestate.dao;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import com.edu.realestate.model.Apartment;
@Repository
public class ApartmentDaoHib extends AbstractDaoHib implements ApartmentDao {
@Override
public void create(Apartment ap) {
Session session = getSession();
session.save(ap);
}
@Override
public Apartment read(Integer id) {
Session session = getSession();
Apartment apartment = null;
apartment = session.load(Apartment.class, id);
return apartment;
}
@Override
public void update(Apartment ap) {
Session session = getSession();
session.save(ap);
}
@Override
public void delete(Apartment ap) {
Session session = getSession();
session.delete(ap);
}
}
|
package Chapter3.T2;
// 2. Which of the following are output by this code? (Choose all that apply)
// A. one
// C. three
// D. four
public class Test {
public static void main(String[] args) {
String s = "Hello";
String t = new String(s);
if ("Hello".equals(s)) System.out.println("one");
if (t == s) System.out.println("two");
if (t.equals(s)) System.out.println("three");
if ("Hello" == s) System.out.println("four");
if ("Hello" == t) System.out.println("five");
}
}
// A. one
// B. two
// C. three
// D. four
// E. five
// F. The code does not compile.
|
package com.ytdsuda.management.entity;
import lombok.Data;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;
@Entity
@Data
@DynamicUpdate
public class DrugCategory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer categoryId;
// 类名
private String categoryName;
//描述
private String categoryDesc;
public DrugCategory() {
}
public DrugCategory(String categoryName, String categoryDesc) {
this.categoryName = categoryName;
this.categoryDesc = categoryDesc;
}
}
|
package id.mbingweb.iso8583.helper;
/**
*
* @author fqodry
*/
public class DecimalHexBinaryConverter {
public static String decimalToHexa(Integer decimalNum) {
return Integer.toHexString(decimalNum);
}
public static String decimalToBinary(Integer decimalNum) {
StringBuilder binaryNumber = new StringBuilder();
StringBuilder sbBinary = new StringBuilder();
String binaryString = Integer.toBinaryString(decimalNum);
char[] binary = binaryString.toCharArray();
int counter = 0;
// ambil dari index karakter terakhir
for (int i=binary.length-1; i>=0; i--) {
counter++;
sbBinary.append(binary[i]);
// reset counter ke nol jika berhasil mengambil 4 digit karakter
if (counter == 4) counter = 0;
}
// 4 adalah panjang karakter tiap blok di binary
// ex: dec [100] == binary [0110 0100]
for (int i=0; i<4-counter; i++) {
if (counter > 0) sbBinary.append("0");
}
// sekarang dibalik
for (int i=sbBinary.length()-1; i>=0;i--) {
binaryNumber.append(sbBinary.toString().charAt(i));
}
return binaryNumber.toString();
}
public static Integer binaryToDecimal(String binaryNumber) {
return Integer.parseInt(binaryNumber, 2);
}
public static String binaryToHexa(String binaryNumber) {
return decimalToHexa(binaryToDecimal(binaryNumber));
}
public static Integer hexaToDecimal(String hexaNumber) {
return Integer.parseInt(hexaNumber, 16);
}
public static String hexaToBinary(String hexaNumber) {
return decimalToBinary(hexaToDecimal(hexaNumber));
}
}
|
package dev.fujioka.eltonleite.infrastructure.persistence.hibernate.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import dev.fujioka.eltonleite.domain.model.order.Order;
public interface OrderRepository extends JpaRepository<Order, Long>{
}
|
package by.academy.homework.homework4.task3;
import java.util.Iterator;
public class TwoDimArrayIterator <T> implements Iterator <T> {
private T [][] twoDimArray;
private int indexRow = 0;
private int indexColumn = 0;
public TwoDimArrayIterator (T [][] twoDimArray) {
super ();
this.twoDimArray = twoDimArray;
}
@Override
public boolean hasNext() {
if (twoDimArray == null || indexRow >= twoDimArray.length || indexColumn >= twoDimArray [indexRow].length) {
return false;
}
return twoDimArray [indexRow][indexColumn] != null;
}
@Override
public T next() {
T element = twoDimArray [indexRow][indexColumn++];
if (indexColumn >= twoDimArray[indexRow].length) {
indexRow++;
indexColumn = 0;
}
return element;
}
public T[][] getTwoDimArray() {
return twoDimArray;
}
public void setTwoDimArray(T[][] twoDimArray) {
this.twoDimArray = twoDimArray;
}
}
|
package net.maizegenetics.util;
import com.google.common.collect.SetMultimap;
import java.util.Map;
/**
* Provide generalized annotations (descriptors) for a taxon or site.
*
*/
public interface GeneralAnnotation {
/**
* Returns all annotation value for a given annotation key
* @param annoName annotation key
* @return array of annotation values (if not present new String[0])
*/
public Object[] getAnnotation(String annoName);
/**
* Returns all annotation value for a given annotation key
* @param annoName annotation key
* @return array of annotation values (if not present new String[0])
*/
public String[] getTextAnnotation(String annoName);
/**
* Returns all annotation value for a given annotation key
* @param annoName annotation key
* @return array of annotation values (if not present new String[0])
*/
public String getConsensusAnnotation(String annoName);
/**
* Returns all annotation value for a given annotation key
* @param annoName annotation key
* @return array of annotation values (if not present new double[0])
*/
public double[] getQuantAnnotation(String annoName);
/**
* Returns average annotation for a given annotation key
* @param annoName annotation key
* @return average value (if not present - return Double.NaN)
*/
public double getAverageAnnotation(String annoName);
/**
* Returns all annotation Map.Entries.
* @return array of Map.Entry
*/
public Map.Entry<String, String>[] getAllAnnotationEntries();
/**
* Returns all annotations in a TreeMap.
* @return Map of annotations
*/
public SetMultimap<String, String> getAnnotationAsMap();
//should we provide methods, to average the quantitative annotations, the first annotation
//
}
|
package interfaceClass;
/**
* Created by qq65827 on 2015/2/28.
*/
public class CharSequenceImpl implements CharSequence {
@Override
public int length() {
return 0;
}
@Override
public char charAt(int index) {
return 0;
}
@Override
public CharSequence subSequence(int start, int end) {
return null;
}
}
|
/*
* (C) Mississippi State University 2009
*
* The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is
* a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries
* and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in
* http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in
* all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html.
*/
//FabryPerot.java
//Defines the applet class for the Fabry-Perot Interferometer Module.
//Rhett Maxwell and Davis Herring
//Updated April 18 2005
//Version 2.3.1
package org.webtop.module.fabryperot;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import org.webtop.component.*;
import org.webtop.wsl.script.WSLNode;
import org.webtop.x3d.widget.*;
import org.webtop.x3d.output.*;
import org.web3d.x3d.sai.*;
import org.webtop.util.*;
import org.webtop.util.script.*;
import org.webtop.util.script.*;
//WSL imports
import org.webtop.wsl.client.*;
import org.webtop.wsl.event.*;
import org.webtop.wsl.script.*;
import org.sdl.gui.numberbox.*;
import org.sdl.math.FPRound;
import org.webtop.x3d.widget.Widget;
public class FabryPerot extends WApplication implements ActionListener, StateButton.Listener,
NumberBox.Listener, Widget.Listener, SpatialWidget.Listener {
public static final int HIGH_RES = 150, HIGH_RES_CHOICE = 0;
public static final int LOW_RES = 60, LOW_RES_CHOICE = 1;
public static final int LINE_RES = 300;
//float[][][] color = {new float[(HIGH_RES + 1) * (HIGH_RES + 1)][3], new float[(LOW_RES + 1) * (LOW_RES + 1)][3]};
float[][][] color = {new float[(HIGH_RES + 1) * (HIGH_RES + 1)][3], new float[(LOW_RES + 1) * (LOW_RES + 1)][3]};
protected String getModuleName() {
return "Fabry-Perot Interferometer";
}
protected int getMajorVersion() {
return 6;
}
protected int getMinorVersion() {
return 1;
}
protected int getRevision() {
return 1;
}
protected String getDate() {
return "April 14 2004";
}
protected String getAuthor() {
return "Rhett Maxwell, Davis Herring";
}
protected Component getFirstFocus() {
return indexField;
}
private static final short WAVELENGTH_WHEEL = 0, INDEX_WHEEL = 1,
DEPTH_DRAGGER = 2, REFLECTIVITY_DRAGGER = 3,
SCREEN_TOUCH = 4;
private static final float SCREEN_SIZE = 7;
private static final float DEF_WAVELENGTH = 550, MIN_INDEX = 1, MAX_INDEX = 3,
DEF_INDEX = 1.5f, MIN_DEPTH = 0, MAX_DEPTH = 2,
DEF_DEPTH = 1, MIN_REFLECTIVITY = 0, MAX_REFLECTIVITY = 1,
DEF_REFLECTIVITY = 0.5f;
private static final float INTENSITY_SCALE = 2 / 3f; // for color model
// Math Constants
private static final float L = 25.0f, Lp = 150.0f, n = 1.0f;
//private float intensity_dx;
//private float icache[];radius
// Physics Variables
private double F;
private double smThCONST;
//private double u1,u2,u3;
//private double wOver2d;
private double n_primeSqr;
private double Imin /*,Imax*/;
//**************************************
// GUI Elements
//**************************************
private FloatBox wavelengthField, indexField, depthField, reflectivityField;
private Panel buttonPanel;
private JButton resetButton;
private StateButton toggleAxisButton, toggleWidgetsButton;
private NumberBoxScripter wavelengthScripter,indexScripter, depthScripter,reflectivityScripter;
private ButtonScripter resetScripter;
private StateButtonScripter widgetsScripter,axisScripter;
//********************************************//
// VRML Interface Objects //
//********************************************//
//========Widgets========
private WheelWidget wavelengthWidget, indexWidget;
private XDragWidget depthWidget, reflectivityWidget;
//========Output========
private MultiGrid observationScreen;
private LinePlot observationLine;
//========Control========
private SFInt32 widgetToggler, axisToggler;
private ScalarCoupler wavelengthCoupler;
private ScalarCoupler indexCoupler;
private ScalarCoupler depthCoupler;
private ScalarCoupler reflectCoupler;
public FabryPerot(String title, String world)
{
super(title,world,true,false);//ALWAYS true,false...need the statusBar (3rd argument)
//getSAI().disableDraw(introductionChoice);
evaluate();
}
private static int getResolution(boolean high) {
return high ? HIGH_RES : LOW_RES;
}
public void setupGUI() {
wavelengthField = new FloatBox(WApplication.MIN_WAVELENGTH, WApplication.MAX_WAVELENGTH, DEF_WAVELENGTH, 5);
indexField = new FloatBox(MIN_INDEX, MAX_INDEX, DEF_INDEX, 5);
depthField = new FloatBox(MIN_DEPTH, MAX_DEPTH, DEF_DEPTH, 5);
reflectivityField = new FloatBox(MIN_REFLECTIVITY, MAX_REFLECTIVITY, DEF_REFLECTIVITY, 5);
controlPanel.setLayout(new VerticalLayout());
JPanel inputPanel = new JPanel();
inputPanel.add(new JLabel("Index of Refraction"));
inputPanel.add(indexField);
//setTooltip(indexField,"index_tooltip");
inputPanel.add(new JLabel("d:"));
inputPanel.add(depthField);
inputPanel.add(new JLabel("cm"));
//setTooltip(depthField, "depth_label");
inputPanel.add(new JLabel("R:"));
inputPanel.add(reflectivityField);
//(reflectivityField, "r_tooltip");
inputPanel.add(new JLabel("Wavelength:"));
inputPanel.add(wavelengthField);
inputPanel.add(new JLabel("nm"));
//setTooltip(wavelengthField, "wavelength_tooltip");
wavelengthField.addNumberListener(this);
indexField.addNumberListener(this);
depthField.addNumberListener(this);
reflectivityField.addNumberListener(this);
controlPanel.add(inputPanel);
buttonPanel = new Panel(new FlowLayout(FlowLayout.CENTER, 10, 2));
buttonPanel.add(resetButton = new JButton("Reset"));
buttonPanel.add(toggleAxisButton = new StateButton("Axis"));
buttonPanel.add(toggleWidgetsButton = new StateButton("Widgets"));
resetButton.addActionListener(this);
toggleAxisButton.addListener(this);
toggleWidgetsButton.addListener(this);
//setTooltip(resetButton, "resetButton_tooltip");
//setTooltip(toggleAxisButton, "toggleAxisButton_tooltip");
//setTooltip(toggleWidgetsButton, "toggleWidgetsButton_tooltip");
//buttonPanel.add(new Label("Resolution:", Label.RIGHT));
controlPanel.add(buttonPanel);
/* getStatusBar().setPreferredSize(new Dimension(636, 20));
add(getStatusBar());
getStatusBar().setFont(helv(11)); */
wavelengthScripter=new NumberBoxScripter(wavelengthField,getWSLPlayer(),null,"wavelength",new Float(DEF_WAVELENGTH));
indexScripter=new NumberBoxScripter(indexField,getWSLPlayer(),null,"indexOfRefraction",new Float(DEF_INDEX));
depthScripter=new NumberBoxScripter(depthField,getWSLPlayer(),null,"d",new Float(DEF_DEPTH));
reflectivityScripter=new NumberBoxScripter(reflectivityField,getWSLPlayer(),null,"reflectivity",new Float(DEF_REFLECTIVITY));
resetScripter = new ButtonScripter(resetButton,getWSLPlayer(),null,"reset");
final String hideValues[]={"visible","hidden"};
widgetsScripter=new StateButtonScripter(toggleWidgetsButton,getWSLPlayer(),null,"widgets",hideValues,StateButton.VISIBLE);
axisScripter=new StateButtonScripter(toggleAxisButton,getWSLPlayer(),null,"axis",hideValues,StateButton.VISIBLE);
wavelengthCoupler = new ScalarCoupler(wavelengthWidget, wavelengthField, 4);
indexCoupler = new ScalarCoupler(indexWidget, indexField, 4);
depthCoupler = new ScalarCoupler(depthWidget, depthField, 4);
reflectCoupler = new ScalarCoupler(reflectivityWidget, reflectivityField, 4);
//Set up the toolbar
ToolBar toolBar = getToolBar();
toolBar.addBrowserButton("Directions", "/org/webtop/html/fabryperot/directions.html");
toolBar.addBrowserButton("Theory","/org/webtop/html/fabryperot/theory.html");
toolBar.addBrowserButton("Examples","/org/webtop/html/fabryperot/examples.html");
toolBar.addBrowserButton("Exercises", "/org/webtop/html/fabryperot/exercises.html");
toolBar.addBrowserButton("Images","/org/webtop/html/fabryperot/topimages.html");
toolBar.addBrowserButton("About", "/org/webtop/html/license.html");
}
public void setupX3D() {
// show the "loading please wait" message
//introductionChoice = (SFInt32) getSAI().getInputField("IntroductionSwitch","set_whichChoice");
//getSAI().enableDraw(introductionChoice);
//icache=new float[3*HIGH_RES];
//Imax=1;
//Imin=0;
IFSScreen ifsHigh = new IFSScreen(new IndexedSet(getSAI(), getSAI().getNode("ifsNode")), new int[][] {{HIGH_RES, HIGH_RES}},
SCREEN_SIZE / 2, SCREEN_SIZE / 2);
ifsHigh.setup();
IFSScreen ifsLow = new IFSScreen(new IndexedSet(getSAI(), getSAI().getNode("ifsNode_low")), new int[][] {{LOW_RES, LOW_RES}},
SCREEN_SIZE / 2, SCREEN_SIZE / 2);
ifsLow.setup();
observationScreen = new MultiGrid(new Switch(getSAI(), getSAI().getNode("ResolutionSwitch"), 2), new Grid[] {ifsHigh, ifsLow});
observationScreen.showGrid(0);
observationLine = new LinePlot(new IndexedSet(getSAI(), getSAI().getNode("ilsNode")),SCREEN_SIZE, LINE_RES);
widgetToggler = (SFInt32) getSAI().getInputField("WidgetSwitch", "whichChoice");
axisToggler = (SFInt32) getSAI().getInputField("AxisSwitch", "whichChoice");
wavelengthWidget = new WheelWidget(getSAI(), getSAI().getNode("WavelengthWidget"),
WAVELENGTH_WHEEL, "Spin to change the wavelength.");
indexWidget = new WheelWidget(getSAI(), getSAI().getNode("RefractionWidget"), INDEX_WHEEL,
"Spin to change the index of refraction.");
depthWidget = new XDragWidget(getSAI(), getSAI().getNode("DepthWidget"), DEPTH_DRAGGER,
"Slide to change the thickness of the etalon.");
reflectivityWidget = new XDragWidget(getSAI(), getSAI().getNode("ReflectivityWidget"),
REFLECTIVITY_DRAGGER,
"Slide to change the reflectivity of the coating.");
final TouchSensor ts = new TouchSensor(getSAI(), getSAI().getNode("ScreenTouch"),
SCREEN_TOUCH, null);
wavelengthWidget.addListener(this);
indexWidget.addListener(this);
depthWidget.addListener(this);
reflectivityWidget.addListener(this);
//ts.addListener((Widget.Listener)this);
ts.setOver(true);
ts.addListener((SpatialWidget.Listener)this);
//getManager().addHelper(new ScalarCoupler(wavelengthWidget, wavelengthField, 4));
//getManager().addHelper(new ScalarCoupler(indexWidget, indexField, 4));
//getManager().addHelper(new ScalarCoupler(depthWidget, depthField, 4));
//getManager().addHelper(new ScalarCoupler(reflectivityWidget, reflectivityField, 4));
//new DragSilencer(wavelengthWidget, wavelengthScripter);
//new DragSilencer(indexWidget, indexScripter);
//new DragSilencer(depthWidget, depthScripter);
//new DragSilencer(reflectivityWidget, reflectivityScripter);
//getManager().addHelper(new ScalarScripter(wavelengthWidget, getWSLPlayer(), null,
//"wavelength", DEF_WAVELENGTH));
//getManager().addHelper(new ScalarScripter(indexWidget, getWSLPlayer(), null,
//"indexOfRefraction", DEF_INDEX));
//getManager().addHelper(new ScalarScripter(depthWidget, getWSLPlayer(), null, "d", DEF_DEPTH));
//getManager().addHelper(new ScalarScripter(reflectivityWidget, getWSLPlayer(), null,
//"reflectivity", DEF_REFLECTIVITY));
}
protected void scriptCleanup() {
evaluate(true);
}
protected void setDefaults() {
depthField.setValue(DEF_DEPTH);
wavelengthField.setValue(DEF_WAVELENGTH);
indexField.setValue(DEF_INDEX);
reflectivityField.setValue(DEF_REFLECTIVITY);
evaluate(true);
}
private void evaluate() {
evaluate(true);
//evaluate(!draggingWidget());
}
private void evaluate(boolean high) {
//getStatusBar().setText("Calculating - please wait...");
final int cells = getResolution(high);
cacheIntensities(cells);
final double math_dx = SCREEN_SIZE / 2 / (cells - 1),
math_dy = SCREEN_SIZE / 2 / (cells - 1);
color = new float[][][] {new float[(HIGH_RES + 1) * (HIGH_RES + 1)][3], new float[(LOW_RES + 1) * (LOW_RES + 1)][3]};
if(color == null)
System.out.println("FabryPerot.evaluate()::color is null");
final float[][] array = color[high?HIGH_RES_CHOICE:LOW_RES_CHOICE];
for (int x = 0; x < cells; x++)
for (int y = 0; y < cells; y++)
array[x + y * cells] = getRGB(intensity(x * math_dx, y * math_dy) * INTENSITY_SCALE);
System.out.println("FabryPerot.evaluate()::array.length = " + array.length);
observationScreen.setColors(array);
observationScreen.setup();
final float line_values[] = new float[LINE_RES];
for (int i = 0; i < LINE_RES; i++) {
final float x = -SCREEN_SIZE / 2 + i * SCREEN_SIZE / (LINE_RES - 1);
line_values[i] = intensity(x, 0);
}
observationLine.setValues(line_values);
resetStatus();
}
/*************************************************************/
/* this function precalculates intensity for radial symmetry */
/*************************************************************/
private void cacheIntensities(int cells) {
//We make the casts only once:
final double r = reflectivityField.getValue(), w = wavelengthField.getValue(),
n = indexField.getValue(), d = depthField.getValue();
// initial calculations
F = 4 * r / ((1 - r) * (1 - r));
Imin = 1 / (1 + F);
smThCONST = (4.0 * Math.PI * d) / (w * 1e-7f);
// Dr. Foley's calculations of a1, a2, and a3 are actually Imin
// with the values of 0.02, 0.17, and 0.47 added, respectively.
// Therefore this will be the manner of how u1, u2, and u3, will be
// defined.
/*u1 = Math.asin( Math.sqrt( (1-Imin+0.02) / F /
(Imin+0.02) ))/Math.PI;
u2 = Math.asin( Math.sqrt( (1-Imin+0.17) / F /
(Imin+0.17) ))/Math.PI;
u3 = Math.asin( Math.sqrt( (1-Imin+0.47) / F /
(Imin+0.47) ))/Math.PI;*/
// optimize math
//wOver2d = (w*1e-7f)/(2*d);
n_primeSqr = n * n;
//intensity_dx=SCREEN_SIZE/(cells-1);
// //calculate preliminary value, then the real thing
// double th=(Math.floor(2*n*d/(w*1e-7f))-0.5)*(w*1e-7f)/(2*d);
// th=Math.asin(Math.sqrt(n*n-th*th));
// final int valleyCutOff=(int) Math.floor(((L+d+Lp)*Math.tan(th))/intensity_dx);
// final int cutOff=(int) Math.ceil(3.5/intensity_dx);
// // Calculate Intensities
// for(int i=0;i<cutOff;i++) {
// icache[i]=trueIntensity(i*intensity_dx);
// if(r>0.65 && i>valleyCutOff && icache[i]>=0.25) icache[i]=1.0f;
// if(r>0.80 && i>valleyCutOff && icache[i]>0.10) icache[i]=1.0f;
// if(Imax<icache[i]) Imax=icache[i];
// if(Imin>icache[i]) Imin=icache[i];
// }
// // Normalize icache
// for(int i=0;i<cutOff;i++) icache[i]=(float) icache[i];
// for(int i=cutOff;i<3*cells;i++) icache[i]=0;
}
private double theta(double r) {
return Math.atan(r / (L + Lp + depthField.getValue()));
}
private float trueIntensity(double radius) {
if (radius > SCREEN_SIZE / 2)return 0;
final double theta = theta(radius),
smTheta = smThCONST * Math.sqrt(n_primeSqr - n * n * Math.sin(theta) *
Math.sin(theta));
return 1 / (float) (1 + F * Math.sin(smTheta / 2) * Math.sin(smTheta / 2));
}
private float intensity(double X, double Z) {
// float f=(float) (Math.sqrt(X*X+Z*Z)/intensity_dx);
// float f1=(float) Math.floor(f);
// float f2=(float) Math.ceil(f);
// int n1=(int) f1;
// int n2=(int) f2;
// return icache[n1]+(f-f1)*(icache[n2]-icache[n1]);
return trueIntensity(Math.sqrt(X * X + Z * Z));
}
private float[] getRGB(float light) {
float[] rgb = new float[3];
WTMath.hls2rgb(rgb, WTMath.hue(wavelengthField.getValue()),
light, WTMath.SATURATION);
return rgb;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == resetButton) {
setDefaults();
} else System.err.println("FabryPerot: unexpected ActionEvent " + e);
}
public void stateChanged(StateButton sb, int state) {
//This still seems a bit clumsy -- is there a better way to check for
//'visibility of a hide/show object button'? Perhaps a special
//StateButton function? [Davis]
if (sb == toggleWidgetsButton)
getSAI().setDraw(widgetToggler, state == StateButton.VISIBLE);
else if (sb == toggleAxisButton)
getSAI().setDraw(axisToggler, state == StateButton.VISIBLE);
}
public void numChanged(NumberBox source, Number newVal) {
//Is there some better way to check for an 'expected' NumberBox? [Davis]
if (source == indexField);
else if (source == depthField);
else if (source == reflectivityField);
else if (source == wavelengthField);
else {
System.err.println("Engine: unexpected numChanged from " + source);
return;
}
evaluate();
}
public void boundsForcedChange(NumberBox source, Number oldVal) {} //never happens
public void invalidEntry(NumberBox source, Number badVal) {
if (source == indexField)
getStatusBar().setWarningText("index_warning" + MIN_INDEX + "and" + MAX_INDEX + ".");
else if (source == depthField)
getStatusBar().setWarningText("depth_warning" + MIN_DEPTH + "and" + MAX_DEPTH + ".");
else if (source == reflectivityField)
getStatusBar().setWarningText("reflectivity_warning" + MIN_REFLECTIVITY + "and" +
MAX_REFLECTIVITY + ".");
else if (source == wavelengthField)
getStatusBar().setWarningText("wavelength_warning" + WApplication.MIN_WAVELENGTH +
" and " + WApplication.MAX_WAVELENGTH + "nanometers");
else System.err.println("FabryPerot: unexpected invalidEntry from " + source);
}
protected void setWidgetDragging(Widget w, boolean drag) {
observationScreen.showGrid(drag ? LOW_RES_CHOICE : HIGH_RES_CHOICE);
evaluate();
}
public void valueChanged(SpatialWidget src, float x, float y, float z) {
final float r = (float) Math.sqrt(x * x + y * y);
//This assumes that the only SpatialWidget is the screen TouchSensor
getStatusBar().setText("\u03b8 = " + FPRound.toFixVal(WTMath.toDegs(theta(r)), 3) +
"\u00b0 " + " Intensity = " + FPRound.toFixVal(trueIntensity(r), 3));
}
// ----------------------------------------------------------------------
// WSL Methods
// ----------------------------------------------------------------------
public String getWSLModuleName() {
return "fabryperot";
}
protected void setupMenubar() {
}
public void invalidEvent(String node, String event) {
}
public void toolTip(Tooltip src, String tip) {
}
public void mousePressed(Widget src) {
}
public void mouseReleased(Widget src) {
}
public void mouseEntered(Widget src) {
}
public void mouseExited(Widget src) {
}
public static void main(String args[])
{
FabryPerot fp = new FabryPerot("Fabry Perot","/org/webtop/x3dscene/fabryperot.x3dv");
}
protected void toWSLNode(WSLNode node) {
super.toWSLNode(node);
wavelengthScripter.addTo(node);
indexScripter.addTo(node);
depthScripter.addTo(node);
reflectivityScripter.addTo(node);
widgetsScripter.addTo(node);
axisScripter.addTo(node);
}
}
|
package com.gsccs.sme.api.service;
import java.util.List;
import com.gsccs.sme.api.domain.Sitemeval;
import com.gsccs.sme.api.domain.shop.EvalGoods;
import com.gsccs.sme.api.domain.shop.EvalItem;
import com.gsccs.sme.api.domain.shop.EvalOrder;
import com.gsccs.sme.api.exception.ApiException;
/**
* 评价服务接口
*
* @author x.d zhang
*
*/
public interface EvalServiceI {
/**
* 增加评价描述
*
* @param detail
*/
public void addEvalRemark(Long siteid, EvalGoods detail);
/**
* 增加评价打分
*
* @param scores
*/
public void addEvalScores(Long siteid, List<EvalOrder> scoreList,
EvalGoods detail) throws ApiException;
/**
* 删除评分项目
*
* @param id
*/
public void delEvalType(Long id);
/**
* 添加打分项
*
* @param evalItem
*/
public Long addEvalItem(EvalItem evalItem);
/**
* 编辑打分项
*
* @param evalItem
*/
public void editEvalItem(EvalItem evalItem);
/**
* 删除打分项
*
* @param id
*/
public void delEvalItem(Long id);
/**
* 根据条件查询打分项
*
* @param evalItem
* @return
*/
public List<EvalItem> getEvalItems(EvalItem evalItem);
}
|
package com.xxglpt.xtgl.bean;
import java.io.Serializable;
import java.util.Date;
/**
* 用户实体
* @author xnq
*
*/
public class Master implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private String password;
private String roleid;
private String idcard;
private String truename;
private String tel;
private String phone;
private String unit;
private String sex;
private String role;
private String dist;
private Date czsj;
private int page;
private int rows;
private int max;
private int min;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRoleid() {
return roleid;
}
public void setRoleid(String roleid) {
this.roleid = roleid;
}
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
public String getTruename() {
return truename;
}
public void setTruename(String truename) {
this.truename = truename;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getDist() {
return dist;
}
public void setDist(String dist) {
this.dist = dist;
}
public Date getCzsj() {
return czsj;
}
public void setCzsj(Date czsj) {
this.czsj = czsj;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
}
|
package com.fred.sandboxrabbitmq;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
@Value("${rabbitmq.queue.name}")
private String queueName;
@Value("${rabbitmq.exchange.name}")
private String exchangeName;
@Value("${rabbitmq.key.name}")
private String keyName;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public Queue queue(){
return new Queue(queueName, true);
}
@Bean
public DirectExchange exchange(){
return new DirectExchange(exchangeName);
}
@Bean
public Binding binding(Queue queue, DirectExchange exchange){
return BindingBuilder.bind(queue).to(exchange).with(keyName);
}
}
|
package miniProgram.omok.Exception;
public class SelectedSpace extends Exception{
public SelectedSpace() {
super("Selected Space");
}
}
|
package com.beike.biz.service.trx.impl;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.beike.biz.service.trx.OrderFilmService;
import com.beike.common.bean.trx.FilmApiOrderParam;
import com.beike.common.entity.trx.FilmGoodsOrder;
import com.beike.common.exception.StaleObjectStateException;
import com.beike.core.service.trx.FilmApiGoodsOrderService;
import com.beike.dao.goods.GoodsDao;
import com.beike.dao.trx.FilmGoodsOrderDao;
import com.beike.dao.trx.soa.proxy.GoodsSoaDao;
import com.beike.entity.goods.Goods;
import com.beike.util.Amount;
import com.beike.util.StringUtils;
/**
* @desc 网上选坐电影票的处理服务类
* @author ljp
*
*/
@Repository("orderFilmService")
public class OrderFilmServiceImpl implements OrderFilmService{
@Autowired
private GoodsSoaDao goodsSoaDao;
@Autowired
private GoodsDao goodsDao;
private final Log logger = LogFactory.getLog(OrderFilmServiceImpl.class);
@Autowired
private FilmGoodsOrderDao filmGoodsOrderDao;
@Autowired
private FilmApiGoodsOrderService filmApiGoodsOrderService;
@Override
public Goods createFilmGoods(String seatInfo, Long id) {
//seatInfo 格式格式:11:12。其中11 表示11 排,12 表示12 座, 多个座位用|分隔。如: 11:12|11:11|11:13
Map<String, Object> filmShow = goodsSoaDao.getFilmShowByShowIndex(id);
int filmCount = seatInfo.split("\\|").length;
Goods goods = goodsDao.getGoodsDaoById(Long.valueOf("2000001"));
goods.setSourcePrice(Amount.mul(((BigDecimal)filmShow.get("c_price")).doubleValue(),filmCount));
goods.setPayPrice(Amount.mul(((BigDecimal)filmShow.get("v_price")).doubleValue(),filmCount));
goods.setRebatePrice(0);
goods.setDividePrice(0);
goods.setMerchantname("网票网");
return goods;
}
@SuppressWarnings("unchecked")
@Override
public Map<String, String> addFilmGoodsOrder(FilmGoodsOrder filmGoodsOrder, String sid, String mobile)
throws Exception {
if(filmGoodsOrder != null){
filmGoodsOrderDao.addFilmGoodsOrder(filmGoodsOrder);
Long filmId = filmGoodsOrderDao.getLastInsertId();
FilmApiOrderParam filmApiOrderParam = new FilmApiOrderParam();
filmApiOrderParam.setFilmSid(sid);//锁坐唯一号
filmApiOrderParam.setPayType("9990");//下单支付方式
filmApiOrderParam.setMobile(mobile);//下单手机号
filmApiOrderParam.setMsgType("1");//验票码发送方式1需要系统发送验票码; 2不需要系统发送验票码
filmApiOrderParam.setAmount(Amount.mul(filmGoodsOrder.getFilmPrice().doubleValue(),filmGoodsOrder.getFilmCount()));//下单金额
filmApiOrderParam.setGoodsType("1");//商品类型,默认为1
String result = filmApiGoodsOrderService.createFilmOrder(filmApiOrderParam);
logger.info("----------this is wpw applyTicket------output---"+result);
if(!StringUtils.validNull(result)){
logger.info("----------this is wpw applyTicket------output---is null;");
throw new Exception();
}
Map<String, String> res = (Map<String, String>)new JSONParser().parse(result);
if(!StringUtils.validNull(res.get("PayNo"))||!StringUtils.validNull(res.get("SID"))){
logger.info("----------this is wpw applyTicket------output---is not value--------;");
throw new Exception();
}
Map<String, String> map = new HashMap<String, String>();
map.put("filmId", filmId+"");//网票网下单记录表主键ID
map.put("filmPayno", res.get("PayNo"));//网票网下单成功回传订单号
map.put("filmSid", sid);
return map;
}else{
throw new IllegalArgumentException("filmGoodsOrder not null");
}
}
@Override
public void updateFilmGoodsOrderById(Long filmId, String filmPayNo,
Long trxOrderId, Long trxGoodsId) throws StaleObjectStateException{
FilmGoodsOrder filmGoodsOrder = filmGoodsOrderDao.queryFilmGoodsOrderById(filmId);
if(filmGoodsOrder != null){
filmGoodsOrder.setFilmPayNo(filmPayNo);
filmGoodsOrder.setTrxGoodsId(trxGoodsId);
filmGoodsOrder.setTrxOrderId(trxOrderId);
}
filmGoodsOrderDao.updateFilmGoodsOrderById(filmGoodsOrder);
}
@Override
public Map<String, Object> queryFilmShowByShowIndex(Long showIndex) throws Exception {
return goodsSoaDao.getFilmShowByShowIndex(showIndex);
}
@Override
public Map<String, Object> queryCinemaInfoByCinemaId(Long cinemaId) throws Exception {
return goodsSoaDao.getCinemaByCinemaId(cinemaId) ;
}
public void updateStatusByTrxGoodsId(Long trxGoodsId){
filmGoodsOrderDao.updateStatusByTrxGoodsId(trxGoodsId);
}
@Override
public Long queryCinemaIdByTrxGoodsId(Long trxGoodsId) throws Exception {
Long cinemaId=(Long)goodsSoaDao.getCinemaIdByTrxGoodsId(trxGoodsId).get("cinema_id");
if(cinemaId==null){
return null;
}else{
return goodsSoaDao.queryQianpinCinemaByWpId(cinemaId);
}
}
}
|
package com.example.server.data;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Pet {
private static final String IMAGE_PROPERTY="image";
private static final String PET_NAME_JSON_PROPERTY="name";
private static final String PET_PRIMARY_BREED="primaryBreed";
private static final String PET_GENDER_PROPERTY="gender";
private static final String PET_AGE_PROPERTY= "age";
private static final String PET_ANIMAL_TYPE= "type";
private String image;
private String name;
private String primaryBreed;
private String gender;
private String age;
private String type;
public Pet(@JsonProperty(IMAGE_PROPERTY) String image,
@JsonProperty(PET_NAME_JSON_PROPERTY) String name,
@JsonProperty(PET_PRIMARY_BREED) String primaryBreed,
@JsonProperty(PET_GENDER_PROPERTY) String gender,
@JsonProperty(PET_AGE_PROPERTY) String age,
@JsonProperty(PET_ANIMAL_TYPE) String type) {
this.image = image;
this.name = name;
this.primaryBreed = primaryBreed;
this.gender = gender;
this.age = age;
this.type=type;
}
public String getImage() {
return image;
}
public String getName() {
return name;
}
public String getPrimaryBreed() {
return primaryBreed;
}
public String getGender() {
return gender;
}
public String getAge() {
return age;
}
public void setImage(String image) {
this.image = image;
}
public void setName(String name) {
this.name = name;
}
public void setPrimaryBreed(String primaryBreed) {
this.primaryBreed = primaryBreed;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setAge(String age) {
this.age = age;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
package com.junoyaya.jukebox.controllers;
import com.junoyaya.jukebox.entities.Juke;
import com.junoyaya.jukebox.servises.JukeboxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.PagedModel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class JukeboxController {
@Autowired
private JukeboxService jukeboxService;
@Autowired
private PagedResourcesAssembler<Juke> jukePagedResourcesAssembler;
@GetMapping("/api/jukes")
@ResponseBody
public PagedModel<EntityModel<Juke>> findJukesMatchesSetting(@RequestParam(required = false, name = "settingId") String settingId,
@RequestParam(required = false, name = "model") String model,
Pageable pageable) {
if (settingId != null) {
return jukePagedResourcesAssembler.toModel(jukeboxService.findJukesMatchesSetting(settingId, pageable));
}
if (model != null) {
return jukePagedResourcesAssembler.toModel(jukeboxService.findJukesMatchesModel(model, pageable));
}
return jukePagedResourcesAssembler.toModel(jukeboxService.findAllJukes(pageable));
}
}
|
package com.sai.one.algorithms.arrays;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by shravan on 24/8/16.
* http://www.programcreek.com/2012/12/leetcode-3sum/
*/
public class ThreeSum {
public static void main(String[] args) {
int[] arr = {-2, 0, 0, 2, 2};
System.out.print(threeSum(arr, 0));
}
public static List<List<Integer>> threeSum(int[] numbers, int target) {
Arrays.sort(numbers);
List<List<Integer>> lsres = new ArrayList<List<Integer>>();
for (int l = 0; l < numbers.length; l++) {
if (l == 0 || numbers[l] > numbers[l - 1]) {
int i = l + 1;
int j = numbers.length - 1;
while (i < j) {
int val = numbers[l] + numbers[i] + numbers[j];
if (val == target) {
List<Integer> num = new ArrayList<Integer>();
num.add(numbers[l]);
num.add(numbers[i]);
num.add(numbers[j]);
lsres.add(num);
i++;
j--;
while (i < j && numbers[i] == numbers[i - 1])
i++;
while (i < j && numbers[j] == numbers[j + 1])
j--;
} else if (val < target) {
i++;
} else if (val > target) {
j--;
}
}
}
}
return lsres;
}
}
|
package cz.cvut.panskpe1.rssfeeder.model;
/**
* Created by petr on 4/12/16.
*/
public class FeedEntry {
private Feed mFeed;
private String mTitle;
private long mId;
private String mLink;
private long mUpdated;
private String mSummary;
private String mContent;
private String mAuthor;
public FeedEntry(Feed feed, String title, long id, String link) {
mFeed = feed;
mTitle = title;
mId = id;
mLink = link;
}
public Feed getFeed() {
return mFeed;
}
public void setFeed(Feed mFeed) {
this.mFeed = mFeed;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String mTitle) {
this.mTitle = mTitle;
}
public long getId() {
return mId;
}
public void setId(long mId) {
this.mId = mId;
}
public String getLink() {
return mLink;
}
public void setLink(String mLink) {
this.mLink = mLink;
}
public long getUpdated() {
return mUpdated;
}
public void setUpdated(long mUpdated) {
this.mUpdated = mUpdated;
}
public String getSummary() {
return mSummary;
}
public void setSummary(String mSummary) {
this.mSummary = mSummary;
}
public String getContent() {
return mContent;
}
public void setContent(String mContent) {
this.mContent = mContent;
}
public String getAuthor() {
return mAuthor;
}
public void setAuthor(String mAuthor) {
this.mAuthor = mAuthor;
}
}
|
package com.company;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.boot.*;
@SpringBootApplication
public class Main {
public static void main(String[] args) throws Exception {
SpringApplication.run(Main.class, args);
}
} |
import java.util.*;
/** PROGRAMMKOPF
* Modul Buchung
*
* @version 1.0 vom 20.04.2017
*
* Klasse: FS 63
* Name: Lukas Wuestenhagen
*
PROGRAMMKOPF ENDE*/
public class Modul_BuchungUebersicht {
public static void uebersicht(int jahr, String[][] Buchungsdaten) { // Beginn der Hauptfunktion
char Auswahl;
int anfangsdatum,dauer;
boolean belegt = false;
do {
System.out.println("\nAnfangsdatum der Buchung bitte eingeben.");
anfangsdatum = Modul_Datumrechner.Datum(jahr); //Abfrage des Datums
belegt = false;
} while (belegt == true); // end of do-while
do {
System.out.print("\nWie lange soll gebucht werden? ");
dauer = Tastatur.liesInt(); //Abfrage der Buchungsdauer
belegt = false;
boolean allefrei = true; //Ueberpruefung ob alle Wohnungen frei sind
if (dauer <= 0) {
belegt = true; //Ueberpruefung des angegebenen Datums
System.out.println("\nDies ist keine gueltiges Datum da es kleiner oder gleich gross als das Anfangsdatum ist.");
}
else {
int Belegatarray[]= new int [100];
for (int i=0;i<Buchungsdaten.length ;i++ ) {
for (int k = anfangsdatum;k<(anfangsdatum+dauer) ;k++ ) {
if (Buchungsdaten[i][k] != null && dauer > 0) {
Belegatarray[i] = i+1; //Eintragung der jewilig belegten Wohnung in einem Array, i+1 zur korrekten Ausgabe
}
} // end of for
} // end of for
System.out.println();
for (int i=0;i<Belegatarray.length ;i++ ) {
if (Belegatarray[i] != 0) {
System.out.println("Wohnung " + Belegatarray[i] + " belegt."); //Ausgabe der belegten Wohnungen in diesem Zeitraum
allefrei = false; //Variable wird false gesetzt da eine Wohnung belegt ist
} // end of if
} // end of for
if (allefrei == false) {
System.out.println("Alle anderen Wohnungen sind in diesem Zeitraum frei."); //Ausgabe falls mindestens eine Wohnung belegt ist
} // end of if
else {
System.out.println("Alle Wohnungen sind in diesem Zeitraum frei."); //Ausgabe falls alle Wohnungen in dem Zeitraum frei sind
} // end of if-else
} // end of if-else
} while (belegt == true); // end of do-while
} // Ender der Hauptfunktion
} // end of class EAngestellte
|
//designpatterns.abstractfactory.SummerComboBox.java
package designpatterns.abstractfactory;
public class SummerComboBox implements ComboBox {
public void display() {
System.out.println("ÏÔʾÀ¶É«±ß¿ò×éºÏ¿ò¡£");
}
} |
package org.nhnnext.restaurant.lab2.menu;
public class Coffee {
private String name;
private int price;
public Coffee(MenuItem menuItem) {
this.name = menuItem.getName();
this.price = menuItem.cost();
}
public String getName() {
return name;
}
public int cost() {
return price;
}
public void prepare() {
boilWater();
brew();
pourInCup();
addCondiments();
}
private void boilWater() {
System.out.println("- 물 끓이는 중");
}
private void brew() {
System.out.println("- 필터로 커피를 우려내는 중");
}
private void pourInCup() {
System.out.println("- 컵에 따르는 중");
}
private void addCondiments() {
System.out.println("- 설탕과 커피를 추가하는 중");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.