text stringlengths 10 2.72M |
|---|
package com.duanc.web.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.duanc.api.web.RegistService;
import com.duanc.model.base.BaseUser;
import com.duanc.utils.MD5Util;
@Controller
public class RegistController {
@Autowired
private RegistService registService;
@RequestMapping("/regist-page")
public String getRegistPage() {
return "regist";
}
@RequestMapping(value = "/checkUser")
@ResponseBody
public String checkUser(BaseUser baseUser){
List<BaseUser> list = registService.selectUser(baseUser);
if(list != null && list.size() > 0) {
return JSON.toJSONString(false
);
}
return JSON.toJSONString(true);
}
@RequestMapping(value = "/regist")
public String checkAndSendEmail(BaseUser baseUser, Model model, HttpServletRequest request){
if(baseUser.getEmail() != null && baseUser.getEmail().trim() != "" && baseUser.getUsername() != null && baseUser.getUsername().trim() != ""
&& baseUser.getPhoneNo()!=null && baseUser.getPhoneNo().trim() != "" && baseUser.getPassword()!= null && baseUser.getPassword().trim() != ""){
baseUser.setPassword(MD5Util.getMd5(baseUser.getPassword()));
if(registService.regist(baseUser) == true) {
request.getSession().setAttribute("current_user", baseUser);
return "redirect:/index/index";
}
model.addAttribute("regist_message", "系统繁忙请稍后再试");
} else {
model.addAttribute("regist_message", "请写完整信息再试");
}
return "regist";
}
}
|
import java.util.Scanner;
public class recurpalindrome {
public static void main(String[] args) {
int n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
int t=palin(arr,0,n-1);
if(t==1)
{
System.out.print("Palindrome");
}
else if(t==0)
{
System.out.print("Not Palindrome");
}
}
public static int palin(int arr[],int first,int last)
{
if(first==last||first>last)
{
return 1;
}
else if(arr[first]==arr[last])
{
first=first+1;
last=last-1;
return palin(arr,first,last);
}
return 0;
}
}
|
package io.nuls.consensus;
import io.nuls.common.INerveCoreBootstrap;
import io.nuls.common.NerveCoreConfig;
import io.nuls.consensus.constant.ConsensusConstant;
import io.nuls.consensus.constant.PocbftConstant;
import io.nuls.consensus.model.bo.Chain;
import io.nuls.consensus.utils.enumeration.ConsensusStatus;
import io.nuls.consensus.utils.manager.ChainManager;
import io.nuls.core.core.annotation.Autowired;
import io.nuls.core.core.annotation.Component;
import io.nuls.core.core.config.ConfigurationLoader;
import io.nuls.core.core.ioc.SpringLiteContext;
import io.nuls.core.log.Log;
import io.nuls.core.rockdb.service.RocksDBService;
import io.nuls.core.rpc.model.ModuleE;
import io.nuls.core.rpc.modulebootstrap.Module;
import java.io.File;
/**
* 共识模块启动及初始化管理
* Consensus Module Startup and Initialization Management
*
* @author tag
* 2018/3/4
*/
@Component
public class ConsensusBootStrap implements INerveCoreBootstrap {
@Autowired
private NerveCoreConfig consensusConfig;
@Autowired
private ChainManager chainManager;
@Override
public int order() {
return 4;
}
/**
* 初始化模块,比如初始化RockDB等,在此处初始化后,可在其他bean的afterPropertiesSet中使用
* 在onStart前会调用此方法
*/
private void init() {
try {
initDB();
initProtocolUpdate();
chainManager.initChain();
} catch (Exception e) {
Log.error(e);
}
}
private void initProtocolUpdate() {
ConfigurationLoader configurationLoader = SpringLiteContext.getBean(ConfigurationLoader.class);
try {
long heightVersion1_19_0 = Long.parseLong(configurationLoader.getValue(ModuleE.Constant.PROTOCOL_UPDATE, "height_1_19_0"));
PocbftConstant.VERSION_1_19_0_HEIGHT = heightVersion1_19_0;
} catch (Exception e) {
Log.error("Failed to get height_1_19_0", e);
throw new RuntimeException(e);
}
}
@Override
public Module moduleInfo() {
return new Module(ModuleE.CS.abbr, ConsensusConstant.RPC_VERSION);
}
@Override
public void mainFunction(String[] args) {
this.init();
}
@Override
public void onDependenciesReady() {
try {
chainManager.runChain();
for (Chain chain : chainManager.getChainMap().values()) {
chain.setConsensusStatus(ConsensusStatus.RUNNING);
}
Log.debug("cs onDependenciesReady");
} catch (Exception e) {
Log.error(e);
}
}
/**
* 初始化数据库
* Initialization database
*/
private void initDB() throws Exception {
RocksDBService.init(consensusConfig.getDataPath() + File.separator + ModuleE.CS.name);
RocksDBService.createTable(ConsensusConstant.DB_NAME_AWARD_SETTLE_RECORD);
RocksDBService.createTable(ConsensusConstant.DB_NAME_VIRTUAL_AGENT_CHANGE);
}
}
|
import java.util.Arrays;
import java.util.HashMap;
class TwoSums {
public static void main(String a[]){
int[] out = twoSum(new int[]{3,3}, 6);
Arrays.stream(out).forEach(System.out::println);
}
public static int[] twoSum(int[] nums, int target) {
int[] output = new int[2];
HashMap<Integer, Integer> map = new HashMap<>();
for (int i =0; i<nums.length; i++){
map.put(nums[i], i);
}
for (int i =0; i<nums.length; i++){
if(map.containsKey(target- nums[i]) && map.get(target- nums[i]) != i){
output[0] = i;
output[1] = map.get(target - nums[i]);
}
}
return output;
}
public int[] twoSum2(int[] nums, int target) {
int[] output = new int[2];
for (int i=0 ; i<nums.length-1; i++){
int number1 = nums[i];
for(int j= i+1; j<nums.length; j++){
int number2 = nums[j];
if(number1+number2 == target){
output[0] = i;
output[1] = j;
}
}
}
return output;
}
} |
package com.wandercoder.model;
import com.wandercoder.controller.ScoreAlgorithmBase;
public class SquareBalloon extends ScoreAlgorithmBase {
@Override
public int calculateScore(int taps, int multiplier) {
return (taps * multiplier) + 40;
}
}
|
//package uk.ac.qub.eeecs.gage.screenTests;
//
//import android.text.method.Touch;
//
//import org.junit.Before;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.mockito.Mock;
//import org.mockito.Mockito;
//import org.mockito.runners.MockitoJUnitRunner;
//
//import java.util.ArrayList;
//import java.util.List;
//
//import uk.ac.qub.eeecs.gage.Game;
//import uk.ac.qub.eeecs.gage.engine.AssetManager;
//import uk.ac.qub.eeecs.gage.engine.ElapsedTime;
//import uk.ac.qub.eeecs.gage.engine.ScreenManager;
//import uk.ac.qub.eeecs.gage.world.GameScreen;
//import uk.ac.qub.eeecs.game.matchAttax.screens.MainMenu;
//import uk.ac.qub.eeecs.game.matchAttax.screens.OptionsScreen;
//import uk.ac.qub.eeecs.gage.engine.input.Input;
//import uk.ac.qub.eeecs.gage.engine.input.TouchEvent;
//import static org.junit.Assert.assertEquals;
//import static org.mockito.Mockito.when;
////James Earls
//@RunWith(MockitoJUnitRunner.class)
//public class MainMenuTest {
// String menuScreenName = "Menu Screen";
// String matchGameScreenName = "Match Game Screen";
// String cardsScreenName = "Cards Screen";
// String optionsScreenName = "Options Screen";
// @Mock
// Game aGame = Mockito.mock(Game.class);
// @Mock
// AssetManager assetManager = Mockito.mock(AssetManager.class);
// @Mock
// private Input input;
// @Mock
// GameScreen menuScreen = Mockito.mock(GameScreen.class);
// @Mock
// GameScreen matchGameScreen = Mockito.mock(GameScreen.class);
// @Mock
// GameScreen cardsScreen = Mockito.mock(GameScreen.class);
// @Mock
// GameScreen optionsScreen = Mockito.mock(GameScreen.class);
//
// @Before
// public void setUp() {
// when(menuScreen.getName()).thenReturn(menuScreenName);
// when(matchGameScreen.getName()).thenReturn(matchGameScreenName);
// when(cardsScreen.getName()).thenReturn(cardsScreenName);
// when(optionsScreen.getName()).thenReturn(optionsScreenName);
// when(aGame.getInput()).thenReturn(input);
// }
// // Test to see if the instance creates
// @Test
// public void mainMenu_CreateInstance(){
// when(aGame.getAssetManager()).thenReturn(assetManager);
// MainMenu mainMenu = new MainMenu((aGame));
// assertEquals(aGame, mainMenu.getGame());
// }
//
// // Tests to check if buttons will go to correct screens
// @Test
// public void play_button_TestSuccess() throws Exception {
// MainMenu mainMenu = new MainMenu(aGame);
// float buttonPositionX = mainMenu.getmPlayButton().position.x;
// float buttonPositionY = mainMenu.getmPlayButton().position.y;
// when(aGame.getInput()).thenReturn(input);
// List testTouches = testTouch(buttonPositionX, buttonPositionY);
//
// when(input.getTouchEvents()).thenReturn(testTouches);
// mainMenu.update(new ElapsedTime());
// assertEquals(matchGameScreen,aGame.getScreenManager().getCurrentScreen() );
// }
// @Test
// public void cards_button_TestSuccess() throws Exception {
// MainMenu mainMenu = new MainMenu(aGame);
// float buttonPositionX = mainMenu.getmCardsButton().position.x;
// float buttonPositionY = mainMenu.getmCardsButton().position.y;
// when(aGame.getInput()).thenReturn(input);
// List testTouches = testTouch(buttonPositionX, buttonPositionY);
//
// when(input.getTouchEvents()).thenReturn(testTouches);
// mainMenu.update(new ElapsedTime());
// assertEquals(cardsScreen,aGame.getScreenManager().getCurrentScreen() );
// }
// @Test
// public void settings_button_TestSuccess() throws Exception {
// MainMenu mainMenu = new MainMenu(aGame);
// float buttonPositionX = mainMenu.getmSettingsButton().position.x;
// float buttonPositionY = mainMenu.getmSettingsButton().position.y;
// when(aGame.getInput()).thenReturn(input);
// List testTouches = testTouch(buttonPositionX, buttonPositionY);
//
// when(input.getTouchEvents()).thenReturn(testTouches);
// mainMenu.update(new ElapsedTime());
// assertEquals(optionsScreen,aGame.getScreenManager().getCurrentScreen() );
// }
//
// // Method to set up touch events and return a list with a touch at the correct locations
// private List testTouch(float touchX, float touchY){
// TouchEvent touchEvent = new TouchEvent();
// touchEvent.type = TouchEvent.TOUCH_UP;
// touchEvent.x = touchX;
// touchEvent.y = touchY;
// List<TouchEvent> touchEvents = new ArrayList<TouchEvent>();
// touchEvents.add(touchEvent);
// return touchEvents;
// }
//}
//
|
package bnogent.m;
public class Easing {
// no easing, no acceleration
public static double linear(double t) {
return t;
}
// accelerating from zero velocity
public static double easeInQuad(double t) {
return t * t;
}
// decelerating to zero velocity
public static double easeOutQuad(double t) {
return t * (2 - t);
}
// acceleration until halfway, then deceleration
public static double easeInOutQuad(double t) {
return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
}
// accelerating from zero velocity
public static double easeInCubic(double t) {
return t * t * t;
}
// decelerating to zero velocity
public static double easeOutCubic(double t) {
return (--t) * t * t + 1;
}
// acceleration until halfway, then deceleration
public static double easeInOutCubic(double t) {
return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
}
// accelerating from zero velocity
public static double easeInQuart(double t) {
return t * t * t * t;
}
// decelerating to zero velocity
public static double easeOutQuart(double t) {
return 1 - (--t) * t * t * t;
}
// acceleration until halfway, then deceleration
public static double easeInOutQuart(double t) {
return t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t;
}
// accelerating from zero velocity
public static double easeInQuint(double t) {
return t * t * t * t * t;
}
// decelerating to zero velocity
public static double easeOutQuint(double t) {
return 1 + (--t) * t * t * t * t;
}
// acceleration until halfway, then deceleration
public static double easeInOutQuint(double t) {
return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t;
}
}
|
public class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof Pair))
return false;
Pair p = (Pair) o;
return x == p.x && y == p.y;
}
} |
package Entyties.Responses;
import Entyties.Entity;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by Александр on 21.06.2017.
*/
public class CreateProjectResponse extends Entity
{
@JsonProperty("savedProjectID")
private String savedProjectID;
public CreateProjectResponse() {
}
public CreateProjectResponse(String savedProjectID) {
this.savedProjectID = savedProjectID;
}
public String getSavedProjectID() {
return savedProjectID;
}
public void setSavedProjectID(String savedProjectID) {
this.savedProjectID = savedProjectID;
}
@Override
public String toString() {
return "CreateProjectResponse{" +
"savedProjectID='" + savedProjectID + '\'' +
'}';
}
}
|
/*
* Copyright 2002-2018 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.web.reactive.result.method.annotation;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.lang.Nullable;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.result.method.SyncHandlerMethodArgumentResolver;
import org.springframework.web.server.ServerWebExchange;
/**
* An extension of {@link AbstractNamedValueArgumentResolver} for named value
* resolvers that are synchronous and yet non-blocking. Subclasses implement
* the synchronous {@link #resolveNamedValue} to which the asynchronous
* {@link #resolveName} delegates to by default.
*
* @author Rossen Stoyanchev
* @since 5.0
*/
public abstract class AbstractNamedValueSyncArgumentResolver extends AbstractNamedValueArgumentResolver
implements SyncHandlerMethodArgumentResolver {
/**
* Create a new {@link AbstractNamedValueSyncArgumentResolver}.
* @param factory a bean factory to use for resolving {@code ${...}}
* placeholder and {@code #{...}} SpEL expressions in default values;
* or {@code null} if default values are not expected to have expressions
* @param registry for checking reactive type wrappers
*/
protected AbstractNamedValueSyncArgumentResolver(
@Nullable ConfigurableBeanFactory factory, ReactiveAdapterRegistry registry) {
super(factory, registry);
}
@Override
public Mono<Object> resolveArgument(
MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) {
// Flip the default implementation from SyncHandlerMethodArgumentResolver:
// instead of delegating to (sync) resolveArgumentValue,
// call (async) super.resolveArgument shared with non-blocking resolvers;
// actual resolution below still sync...
return super.resolveArgument(parameter, bindingContext, exchange);
}
@Override
public Object resolveArgumentValue(
MethodParameter parameter, BindingContext context, ServerWebExchange exchange) {
// This won't block since resolveName below doesn't
return resolveArgument(parameter, context, exchange).block();
}
@Override
protected final Mono<Object> resolveName(String name, MethodParameter param, ServerWebExchange exchange) {
return Mono.justOrEmpty(resolveNamedValue(name, param, exchange));
}
/**
* Actually resolve the value synchronously.
*/
@Nullable
protected abstract Object resolveNamedValue(String name, MethodParameter param, ServerWebExchange exchange);
}
|
package com.shahinnazarov.gradle.models.enums;
public enum ExpressionSourceType {
ENVIRONMENT,
LOCAL,
GLOBAL,
SYSTEM,
NONE
;
}
|
package multithreading.demo4_sync;
public class MyRunnable implements Runnable {
public int counter = 0;
ThreadLocal<Integer> treadLocal = new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return 0;
}
};
public MyRunnable() {
super();
//treadLocal.set(0);
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
counter = counter + 1;
int val = treadLocal.get() + 1;
treadLocal.set(val);
// System.out.println("Thread Local Value = " + treadLocal.get());
//System.out.println(Thread.currentThread().getName() + " has inc i = " + i + " -- counter = " + counter);
System.out.println(Thread.currentThread().getName() + " has inc i = " + i + " -- treadLocal = " + treadLocal.get());
}
}
}
|
package com.example.findwitness;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.Thread.sleep;
public class AccountSignUpFragment extends Fragment {
Button signUn_Btn, email_same_check_Btn, nickname_same_check_Btn;
EditText signUp_email, signUp_password, signUp_password_check, sighUp_Nickname;
String email, password="", password_check="", nickname, message = "", response = "", email_Check_Result = "false", nickname_Check_Result = "false", password_Check_Result = "false";
TextView password_check_result_Tv;
private Context context;
public AccountSignUpFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = container.getContext();
return inflater.inflate(R.layout.fragment_sign_up, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
email_same_check_Btn = view.findViewById(R.id.btn_same_email_check);
nickname_same_check_Btn = view.findViewById(R.id.btn_same_nickname_check);
signUp_email = view.findViewById(R.id.signup_email);
signUp_password = view.findViewById(R.id.signup_password);
signUp_password_check = view.findViewById(R.id.signup_check_password);
sighUp_Nickname = view.findViewById(R.id.signup_nickname);
password_check_result_Tv = view.findViewById(R.id.TextView_password_check_result);
final String pwPattern = "^(?=.*\\d)(?=.*[~`!@#$%\\^&*()-])(?=.*[a-z])(?=.*[A-Z]).{9,12}$";
final String pwPattern_two = "(.)\\1\\1\\1";
email_same_check_Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
email = signUp_email.getText().toString();
if(email.equals("")){
Toast.makeText(context, "이메일을 입력하세요.", Toast.LENGTH_SHORT).show();
}else {
//message = "CHECK_ID : " + email;
message = "SAMECHECKID:" + email+ "\n";
new Thread(new Runnable() {
@Override
public void run() {
socket_connect.sendMessage(message);
}
}).start();
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
response = socket_connect.getMessage();
if (response.equals("OK")) {
Toast.makeText(context, "사용 가능한 아이디입니다.", Toast.LENGTH_SHORT).show();
email_Check_Result = "true";
} else if(response.equals("NO")){
Toast.makeText(context, "이미 사용중인 아이디입니다.", Toast.LENGTH_SHORT).show();
signUp_email.setText("");
email_Check_Result = "false";
}
}
}
});
nickname_same_check_Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
nickname = sighUp_Nickname.getText().toString();
if(nickname.equals("")){
Toast.makeText(context, "닉네임을 입력하세요.", Toast.LENGTH_SHORT).show();
}else {
//message = "CHECK_ID : " + nickname;
message = "SAMECHECKNICKNAME:" + nickname+ "\n";
new Thread(new Runnable() {
@Override
public void run() {
socket_connect.sendMessage(message);
}
}).start();
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
response = socket_connect.getMessage();
if (response.equals("OK")) {
Toast.makeText(context, "사용 가능한 닉네임입니다.", Toast.LENGTH_SHORT).show();
nickname_Check_Result = "true";
}else if(response.equals("NO")){
Toast.makeText(context, "이미 사용중인 닉네임입니다.", Toast.LENGTH_SHORT).show();
sighUp_Nickname.setText("");
nickname_Check_Result = "false";
}
}
}
});
signUp_password.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Matcher matcher = Pattern.compile(pwPattern).matcher(password);
Matcher matcher_two = Pattern.compile(pwPattern_two).matcher(password);
if(!matcher.matches()){
password_check_result_Tv.setText("영문(대소문자 구분), 숫자, 특수문자를 조합하여주세요.");
password_check_result_Tv.setTextColor(Color.parseColor("#FF0000"));
password_Check_Result = "false";
}else if(matcher.matches()){
password_check_result_Tv.setText("조건을 만족하였습니다.");
password_check_result_Tv.setTextColor(Color.parseColor("#00FF00"));
password_Check_Result = "true";
}
if(matcher_two.find()){
password_check_result_Tv.setText("같은 문자를 4개이상 사용하실 수 없습니다.");
password_check_result_Tv.setTextColor(Color.parseColor("#FF0000"));
password_Check_Result = "false";
}
if(!password_check.equals("")){
password_equal_check();
}
}
@Override
public void afterTextChanged(Editable editable) {
password = signUp_password.getText().toString();
if(!password_check.equals("")){
password_equal_check();
}
}
});
signUp_password_check.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(!password.equals("")){
password_equal_check();
}
}
@Override
public void afterTextChanged(Editable editable) {
password_check = signUp_password_check.getText().toString();
if(!password.equals("")){
password_equal_check();
}
}
});
signUn_Btn = view.findViewById(R.id.signup_button);
signUn_Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(email_Check_Result.equals("false")){
Toast.makeText(context, "email 중복 체크를 해주십시오.", Toast.LENGTH_SHORT).show();
}else if(nickname_Check_Result.equals("false")){
Toast.makeText(context, "닉네임 중복 체크를 해주십시오.", Toast.LENGTH_SHORT).show();
}else if(password_Check_Result.equals("false")){
Toast.makeText(context, "비밀번호가 일치하지 않습니다.", Toast.LENGTH_SHORT).show();
}else{
password = Hashing.hashing(password);
//message = "ID : "+email+", PASSWORD : " +password+", NICKNAME : "+nickname;
message = "SIGNUP:"+email+","+password+","+nickname+ "\n";
new Thread(new Runnable() {
@Override
public void run() {
socket_connect.sendMessage(message);
}
}).start();
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
response = socket_connect.getMessage();
if(response.equals("success") || response.equals("succes")){
Toast.makeText(context, "회원가입 성공", Toast.LENGTH_SHORT).show();
((AccountActivity) getActivity()).replaceFragment(((AccountActivity) getActivity()).signInFragment);
((AccountActivity) getActivity()).txt.setText("SIGN IN");
}else if(response.equals("fail")){
Toast.makeText(context, "회원가입 실패", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "오류가 발생했습니다.", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void password_equal_check()
{
if(!password_check.equals("")){
if(password.equals(password_check)){
password_check_result_Tv.setText("비밀번호가 일치합니다.");
password_check_result_Tv.setTextColor(Color.parseColor("#00FF00"));
password_Check_Result = "true";
}else{
password_check_result_Tv.setText("비밀번호가 일치하지 않습니다.");
password_check_result_Tv.setTextColor(Color.parseColor("#FF0000"));
password_Check_Result = "false";
}
}
}
}
|
package com.gxtc.huchuan.utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/08/02
* desc : 键盘相关工具类
* </pre>
*/
public final class KeyboardUtils {
private static int sContentViewInvisibleHeightPre;
public static int KEYBOARD_OPEN = 1;
public static int KEYBOARD_CLOSE = 0;
private KeyboardUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/*
避免输入法面板遮挡
<p>在 manifest.xml 中 activity 中设置</p>
<p>android:windowSoftInputMode="adjustPan"</p>
*/
/**
* 动态显示软键盘
*
* @param activity activity
*/
public static void showSoftInput(final Activity activity) {
if(activity != null){
InputMethodManager imm =
(InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm == null) return;
View view = activity.getCurrentFocus();
if (view == null) view = new View(activity);
imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
}
}
/**
* 动态显示软键盘
*
* @param view 视图
*/
public static void showSoftInput(Context context, final View view) {
if(context != null && view != null){
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) return;
view.setFocusable(true);
view.setFocusableInTouchMode(true);
view.requestFocus();
imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
}
}
/**
* 动态隐藏软键盘
*
* @param activity activity
*/
public static void hideSoftInput(final Activity activity) {
if(activity != null){
InputMethodManager imm =
(InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm == null) return;
View view = activity.getCurrentFocus();
if (view == null) view = new View(activity);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
/**
* 动态隐藏软键盘
*
* @param view 视图
*/
public static void hideSoftInput(Context context, final View view) {
if(context != null && view != null){
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) return;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
/**
* 切换软键盘显示与否状态
*/
public static void toggleSoftInput(Context context) {
if(context != null){
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) return;
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
/**
* 判断软键盘是否可见
* <p>默认软键盘最小高度为 200</p>
*
* @param activity activity
* @return {@code true}: 可见<br>{@code false}: 不可见
*/
public static boolean isSoftInputVisible(final Activity activity) {
return getContentViewInvisibleHeight(activity) >= 200;
}
/**
* 判断软键盘是否可见
*
* @param activity activity
* @param minHeightOfSoftInput 软键盘最小高度
* @return {@code true}: 可见<br>{@code false}: 不可见
*/
public static boolean isSoftInputVisible(final Activity activity,
final int minHeightOfSoftInput) {
return getContentViewInvisibleHeight(activity) >= minHeightOfSoftInput;
}
private static int getContentViewInvisibleHeight(final Activity activity) {
if(activity != null){
final View contentView = activity.findViewById(android.R.id.content);
Rect r = new Rect();
contentView.getWindowVisibleDisplayFrame(r);
return contentView.getBottom() - r.bottom;
}
return 0;
}
/**
* 注册软键盘改变监听器
* @param activity activity
* @param listener listener
*/
private static int usableHeightPrevious;
public static void registerSoftInputChangedListener(final Activity activity, final OnSoftInputChangedListener listener) {
if (activity == null) return;
final View contentView = activity.findViewById(android.R.id.content);
contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
int usableHeightNow = computeUsableHeight(activity, contentView);
if (usableHeightNow != usableHeightPrevious) {
int usableHeightSansKeyboard = contentView.getRootView().getHeight();
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > (usableHeightSansKeyboard / 4)) {
// keyboard probably just became visible
if(listener != null)
listener.onSoftInputChangeState(KEYBOARD_OPEN);
} else {
// keyboard probably just became hidden
if(listener != null)
listener.onSoftInputChangeState(KEYBOARD_CLOSE);
}
contentView.requestLayout();
usableHeightPrevious = usableHeightNow;
}
}
});
}
private static int computeUsableHeight(Activity activity, View contentView) {
if(activity != null && contentView != null){
Rect r = new Rect();
contentView.getWindowVisibleDisplayFrame(r);
if (r.top == 0) {
r.top = getStateHeight(activity);//状态栏目的高度
}
return (r.bottom - r.top);
}
return 0;
}
private static int getStateHeight(Activity activity){
if(activity != null){
int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
return activity.getResources().getDimensionPixelSize(resourceId);
}
}
return 0;
}
/**
* 点击屏幕空白区域隐藏软键盘
* <p>根据 EditText 所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘</p>
* <p>需重写 dispatchTouchEvent</p>
* <p>参照以下注释代码</p>
*/
public static void clickBlankArea2HideSoftInput() {
Log.i("KeyboardUtils", "Please refer to the following code.");
/*
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideKeyboard(v, ev)) {
InputMethodManager imm =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS
);
}
}
return super.dispatchTouchEvent(ev);
}
// 根据 EditText 所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘
private boolean isShouldHideKeyboard(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] l = {0, 0};
v.getLocationInWindow(l);
int left = l[0],
top = l[1],
bottom = top + v.getHeight(),
right = left + v.getWidth();
return !(event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom);
}
return false;
}
*/
}
public interface OnSoftInputChangedListener {
void onSoftInputChangeState(int state);
}
}
|
package com.liuono.browser.servlet;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.liuono.browser.dao.RecordDao;
@WebServlet("/RecordServlet")
public class RecordServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html; charset=utf-8");
RecordDao recordDao = new RecordDao();
try {
List list = recordDao.getData("");
String result = JSON.toJSONString(list);
resp.getWriter().print(result);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
package cn.edu.ncu.collegesecondhand.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.math.BigDecimal;
import java.util.List;
import cn.edu.ncu.collegesecondhand.R;
import cn.edu.ncu.collegesecondhand.entity.Product;
import cn.edu.ncu.collegesecondhand.entity.ProductBean;
import cn.edu.ncu.collegesecondhand.ui.home.ProductActivity;
import de.hdodenhof.circleimageview.CircleImageView;
import kotlin.reflect.KVisibility;
/**
* Created by ren lingyun on 2020/4/15 19:28
*/
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
private List<ProductBean> productBeans;
private Context context;
public ProductAdapter(Context context,List<ProductBean> productBeans) {
this.context = context;
this.productBeans=productBeans;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.home_product_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final ProductBean productBean = productBeans.get(position);
Glide.with(context)
.load(productBean.getProductCover())
.centerCrop()
.into(holder.imageView_home_productCover);
holder.textView_home_productName.setText(productBean.getProductName());
holder.textView_home_productPrice.setText(String.format("%s", productBean.getProductPrice()));
Glide.with(context)
.load(productBean.getUserAvatar())
.centerCrop()
.into(holder.imageView_home_sellerAvatar);
holder.textView_home_sellerName.setText(productBean.getUserName());
if (productBean.getIsBadge() == 1) {
holder.layout_home_badge.setVisibility(View.VISIBLE);
if (productBean.getIsBadgeAdmin() == 1) {
holder.textView_home_badgeAdmin.setVisibility(View.VISIBLE);
}
if (productBean.getIsBadgeMember() == 1) {
holder.textView_home_badgeMember.setVisibility(View.VISIBLE);
}
if (productBean.getIsBadgeNcu() == 1) {
holder.textView_home_badgeNcu.setVisibility(View.VISIBLE);
}
}
holder.layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, ProductActivity.class);
intent.putExtra("id", productBean.getId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
public void setData(List<ProductBean> productBeans) {
this.productBeans = productBeans;
notifyDataSetChanged();
}
public void addData(List<ProductBean> productBeans) {
this.productBeans.addAll(productBeans);
notifyDataSetChanged();
}
@Override
public int getItemCount() {
return productBeans.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView_home_productCover;
TextView textView_home_productName;
TextView textView_home_productPrice;
CircleImageView imageView_home_sellerAvatar;
TextView textView_home_sellerName;
LinearLayout layout_home_badge;
TextView textView_home_badgeAdmin;
TextView textView_home_badgeMember;
TextView textView_home_badgeNcu;
LinearLayout layout;
public ViewHolder(View itemView) {
super(itemView);
imageView_home_productCover = itemView.findViewById(R.id.home_product_cover);
textView_home_productName = itemView.findViewById(R.id.home_product_name);
textView_home_productPrice = itemView.findViewById(R.id.home_product_price);
imageView_home_sellerAvatar = itemView.findViewById(R.id.home_seller_avatar);
textView_home_sellerName = itemView.findViewById(R.id.home_seller_name);
layout_home_badge = itemView.findViewById(R.id.home_badge);
textView_home_badgeAdmin = itemView.findViewById(R.id.home_badge_admin);
textView_home_badgeMember = itemView.findViewById(R.id.home_badge_member);
textView_home_badgeNcu = itemView.findViewById(R.id.home_badge_ncu);
layout = itemView.findViewById(R.id.home_product_whole);
}
}
}
|
package upenn.cis550.groupf.shared;
import com.google.gwt.user.client.rpc.IsSerializable;
public class Content implements IsSerializable {
int contentID;
// number of times this content is pinned
int frequency;
String contentKey;
String description;
boolean isCached;
public Content() {
}
public Content(int contentID, int frequency, String contentKey, String description, boolean iscached) {
setContentID(contentID);
setFrequency(frequency);
setContentKey(contentKey);
setDescription(description);
setCached(iscached);
}
public int getContentID() {
return contentID;
}
public void setContentID(int contentID) {
this.contentID = contentID;
}
public int getFrequency() {
return frequency;
}
public void setFrequency(int frequency) {
this.frequency = frequency;
}
public String getContentKey() {
return contentKey;
}
public void setContentKey(String contentKey) {
this.contentKey = contentKey;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isCached() {
return isCached;
}
public void setCached(boolean isCached) {
this.isCached = isCached;
}
}
|
/**
*
*/
/**
* @author Avip
*
*/
module KPLBO {
} |
package jpa;
import java.util.List;
import org.semanticweb.owlapi.model.OWLOntology;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.MemberValuePair;
import ORM.RelationshipType;
import OWL.ClassIRI;
import OWL.ObjectPropertyIRI;
import genericcode.GenericClass;
import genericcode.GenericVariable;
public class JavaVariable extends GenericVariable {
private List<AnnotationExpr> annotations = null;
private String codeType;
private AnnotationExpr relationshipAnnotation;
// private NodeList<Modifier> modifiers = null;
public JavaVariable(OWLOntology o, GenericClass c, FieldDeclaration node) {
super(o, "variable__" + c.getCodeName() + "." + getFieldNodeStringName(node));
VariableDeclarator variable = ((FieldDeclaration) node).getVariables().get(0);
this.setCodeName(variable.getNameAsString());
this.annotations = ((BodyDeclaration<FieldDeclaration>) node).getAnnotations();
this.setIsMapped();
this.setIsPk();
this.setIsFk();
this.classAssertion(ClassIRI.INSTANCE_VARIABLE);
if(this.isMapped()) {
this.classAssertion(ClassIRI.MAPPED_VARIABLE);
}
if(this.isPk()) {
this.classAssertion(ClassIRI.MAPPED_PRIMARY_KEY);
}
if(this.isFk()) {
this.classAssertion(ClassIRI.MAPPED_FOREIGN_KEY);
}
this.codeType = variable.getTypeAsString();
this.set_class(c);
this.setObjectProperty(ObjectPropertyIRI.BELONGS_TO, c);
}
static String getFieldNodeStringName(FieldDeclaration node) {
String ret = "";
VariableDeclarator variable = ((FieldDeclaration) node).getVariables().get(0);
ret += variable.getNameAsString();
return ret;
}
private void setIsMapped() {
this.setMapped(true);
for (AnnotationExpr ann : this.annotations) {
if (ann.getNameAsString().equals("Transient")) {
this.setMapped(false);
}
}
}
private void setIsPk() {
this.setPk(false);
for (AnnotationExpr ann : this.annotations) {
if (ann.getNameAsString().equals("Id")) {
this.setPk(true);
}
}
}
private void setIsFk() {
this.setFk(false);
for (AnnotationExpr ann : this.annotations) {
switch(ann.getNameAsString()) {
case "OneToOne":
this.setFk(true);
this.setRelationshipType(RelationshipType.ONE_TO_ONE);
this.relationshipAnnotation = ann;
break;
case "OneToMany":
this.setFk(true);
this.setRelationshipType(RelationshipType.ONE_TO_MANY);
this.relationshipAnnotation = ann;
break;
case "ManyToOne":
this.setFk(true);
this.setRelationshipType(RelationshipType.MANY_TO_ONE);
this.relationshipAnnotation = ann;
break;
case "ManyToMany":
this.setFk(true);
this.setRelationshipType(RelationshipType.MANY_TO_MANY);
this.relationshipAnnotation = ann;
break;
default:
break;
}
}
}
public String getMappedBy() {
// System.out.println(this.getCodeName() + " ---------");
List<MemberValuePair> members = this.relationshipAnnotation.findAll(MemberValuePair.class);
for(MemberValuePair m : members) {
if(m.getName().toString().equals("mappedBy")) {
return m.getValue().toString().replace("\"", "");
}
}
return null;
}
public String getCodeType() {
return this.codeType;
}
@Override
public String toCode() {
// TODO Auto-generated method stub
return null;
}
}
|
package com.openproject.controller;
import static com.google.common.base.Preconditions.checkArgument;
import static com.openproject.common.Validation.isValidCompanyID;
import static com.openproject.common.Validation.isValidSubscriptionID;
import static com.openproject.common.Validation.isValidUserID;
import javax.inject.Inject;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.springframework.stereotype.Service;
import com.google.common.base.Optional;
import com.openproject.exception.JAXRSUtil;
import com.openproject.services.AppDirectBillingHandler;
import com.openproject.vo.ChangeRequest;
import com.openproject.vo.OrderRequest;
@Service("subscriptionServiceImpl")
public class SubscriptionServiceImpl implements SubscriptionService {
private HttpHeaders httpHeaders;
@Inject
private AppDirectBillingHandler billingHandler;
@Override
public Response newSubscription(String companyId, String userId, OrderRequest order) {
checkArgument(isValidCompanyID(companyId), Status.BAD_REQUEST);
companyId = companyId.trim();
checkArgument(isValidUserID(userId), Status.BAD_REQUEST);
userId = userId.trim();
Optional<?> optional = billingHandler.doBilling(companyId, userId, order);
return JAXRSUtil.returnIffound(optional.get());
}
@Override
public Response updateSubscription(String companyId, String userId, String subscriptionId,
ChangeRequest changeRequest) {
checkArgument(isValidCompanyID(companyId), Status.BAD_REQUEST);
companyId = companyId.trim();
checkArgument(isValidUserID(userId), Status.BAD_REQUEST);
userId = userId.trim();
checkArgument(isValidSubscriptionID(subscriptionId), Status.BAD_REQUEST);
subscriptionId = subscriptionId.trim();
Optional<?> optional = billingHandler.changeBilling(companyId, userId, subscriptionId, changeRequest);
return JAXRSUtil.returnIffound(optional.get());
}
@Override
public Response cancelSubscription(String subscriptionId) {
checkArgument(isValidSubscriptionID(subscriptionId), Status.BAD_REQUEST);
subscriptionId = subscriptionId.trim();
Optional<?> optional = billingHandler.deactivate(subscriptionId);
return JAXRSUtil.returnIffound(optional.get());
}
/**
*
* @param httpHeaders
*/
@Context
public void setHttpHeaders(final HttpHeaders httpHeaders) {
this.httpHeaders = httpHeaders;
}
}
|
package cs3500.animator.model;
import cs3500.animator.animation.ChangeColor;
import cs3500.animator.animation.IAnimation;
import cs3500.animator.animation.MoveAnimation;
import cs3500.animator.animation.Rotate;
import cs3500.animator.animation.Scale;
import cs3500.animator.shape.Color;
import cs3500.animator.shape.IShape;
import cs3500.animator.shape.Position;
import cs3500.animator.shape.ReadableShape;
import cs3500.animator.shape.Oval;
import cs3500.animator.shape.Rectangle;
import cs3500.animator.util.TweenModelBuilder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Represents a model of the animator.
*/
public class Model implements IModel {
private List<IShape> originalShapes;
private List<IShape> listOfShapes;
private double maxFrame;
/**
* Constructs a model.
*/
public Model() {
this.listOfShapes = new ArrayList<IShape>();
}
@Override
public void addShapes(IShape shape) {
if (listOfShapes.size() == 0) {
this.listOfShapes.add(shape);
} else if (listOfShapes.size() > 0) {
for (int i = 0; i < listOfShapes.size(); i++) {
if (listOfShapes.get(i).getName() == shape.getName()
&& listOfShapes.get(i).getType() == shape.getType()) {
throw new IllegalArgumentException("Can't add same shapeDir type with same name.");
}
}
this.listOfShapes.add(shape);
if (shape.getEnd() > maxFrame) {
maxFrame = shape.getEnd();
}
}
set();
}
@Override
public double getMaxFrame() {
return this.maxFrame;
}
public void set(){
this.originalShapes = getListOfShapes();
}
public void reset(){
this.listOfShapes = this.originalShapes;
this.listOfShapes = getListOfShapes();
}
@Override
public ArrayList<ReadableShape> getShapesAtFrame(int frame) {
ArrayList<ReadableShape> temp = new ArrayList<>();
for (IShape s : this.listOfShapes) {
if (s.isSeen(frame)) {
temp.add(ReadableShape.generateTextReadableShape(tween(s, frame), null, 0));
}
}
Collections.sort(temp);
return temp;
}
@Override
public void addAnimation(String name, IAnimation a) {
for (IShape s : this.listOfShapes) {
if (s.getName() == name) {
s.addAnimation(a);
return;
}
}
throw new IllegalArgumentException("No shape with this name");
}
/**
* Tweens a shape at a certain time.
*
* @param shape The shape to be tweened.
* @param frame The frame it is going to be tweened to.
*/
public IShape tween(IShape shape, int frame) {
shape.shapeAtTime(frame);
return shape;
}
@Override
public String getShapeDescription() {
String shapeDesc = "Shapes:\n";
for (IShape shape : this.getListOfShapes()) {
shapeDesc += shape.toString();
}
return shapeDesc;
}
@Override
public ArrayList<ReadableShape> getAnimTextAtFrame(int frame, int fps) {
ArrayList<ReadableShape> temp = new ArrayList<>();
for (IShape s : this.listOfShapes) {
for (IAnimation a : s.getAnimations()) {
if (a.getStart() == frame) {
temp.add(ReadableShape.generateTextReadableShape(s, a, fps));
}
}
}
return temp;
}
@Override
public List<IShape> getListOfShapes() {
ArrayList<IShape> temp = new ArrayList<>();
for(IShape s : listOfShapes){
temp.add(s.copyShape(s));
}
return temp;
}
public List<IShape> getOriginal() {
ArrayList<IShape> temp = new ArrayList<>();
for(IShape s : originalShapes){
temp.add(s.copyShape(s));
}
return temp;
}
public static class Builder implements TweenModelBuilder<IModel> {
List<IAnimation> animationForBuilder = new ArrayList<>();
List<IShape> shapesForBuilder = new ArrayList<>();
/**
* Adds an oval to the list of shapes to be made.
*
* @param name the unique name given to this shapeDir
* @param cx the x-coordinate of the center of the oval
* @param cy the y-coordinate of the center of the oval
* @param xRadius the x-radius of the oval
* @param yRadius the y-radius of the oval
* @param red the red component of the color of the oval
* @param green the green component of the color of the oval
* @param blue the blue component of the color of the oval
* @param startOfLife the time tick at which this oval appears
* @param endOfLife the time tick at which this oval disappears
*/
@Override
public TweenModelBuilder<IModel> addOval(String name, float cx, float cy,
float xRadius, float yRadius,
float red, float green, float blue,
int startOfLife, int endOfLife, int layer) {
Oval temp = new Oval(name, new Position((double) cx, (double) cy),
(double) xRadius, (double) yRadius,
new Color((double) red, (double) green, (double) blue),
startOfLife, endOfLife, layer);
shapesForBuilder.add(temp);
return this;
}
/**
* Adds a rectangle to the list of shapes to be made.
*
* @param name the unique name given to this shapeDir
* @param lx the minimum x-coordinate of a corner of the
* rectangle
* @param ly the minimum y-coordinate of a corner of the
* rectangle
* @param width the width of the rectangle
* @param height the height of the rectangle
* @param red the red component of the color of the rectangle
* @param green the green component of the color of the rectangle
* @param blue the blue component of the color of the rectangle
* @param startOfLife the time tick at which this rectangle appears
* @param endOfLife the time tick at which this rectangle disappears
*/
@Override
public TweenModelBuilder<IModel> addRectangle(String name, float lx, float ly,
float width, float height,
float red, float green, float blue,
int startOfLife, int endOfLife, int layer) {
Rectangle temp = new Rectangle(name, new Position((double) lx, (double) ly),
(double) width, (double) height,
new Color((double) red, (double) green, (double) blue),
startOfLife, endOfLife, layer);
shapesForBuilder.add(temp);
return this;
}
/**
* Adds a move animation to the list of animations to run.
*
* @param name the unique name of the shapeDir to be moved
* @param moveFromX the x-coordinate of the initial position of this shapeDir.
* What this x-coordinate represents depends on the shapeDir.
* @param moveFromY the y-coordinate of the initial position of this shapeDir.
* what this y-coordinate represents depends on the shapeDir.
* @param moveToX the x-coordinate of the final position of this shapeDir. What
* this x-coordinate represents depends on the shapeDir.
* @param moveToY the y-coordinate of the final position of this shapeDir. what
* this y-coordinate represents depends on the shapeDir.
* @param startTime the time tick at which this movement should start
* @param endTime the time tick at which this movement should end
*/
@Override
public TweenModelBuilder<IModel> addMove(String name,
float moveFromX, float moveFromY,
float moveToX, float moveToY,
int startTime, int endTime) {
IShape tempShape = null;
for (IShape s : shapesForBuilder) {
if (s.getName().equals(name)) {
tempShape = s;
}
}
IAnimation tempAnim = new MoveAnimation(tempShape, startTime, endTime,
new Position((double) moveFromX, (double) moveFromY),
new Position((double) moveToX, (double) moveToY));
animationForBuilder.add(tempAnim);
return this;
}
/**
* Adds a color change animation to the list of animations to be made.
*
* @param name the unique name of the shapeDir whose color is to be changed
* @param oldR the r-component of the old color
* @param oldG the g-component of the old color
* @param oldB the b-component of the old color
* @param newR the r-component of the new color
* @param newG the g-component of the new color
* @param newB the b-component of the new color
* @param startTime the time tick at which this color change should start
* @param endTime the time tick at which this color change should end
*/
@Override
public TweenModelBuilder<IModel> addColorChange(String name,
float oldR, float oldG, float oldB,
float newR, float newG, float newB,
int startTime, int endTime) {
IShape tempShape = null;
for (IShape s : shapesForBuilder) {
if (s.getName().equals(name)) {
tempShape = s;
}
}
IAnimation tempAnim = new ChangeColor(tempShape, startTime, endTime,
new Color((double) oldR, (double) oldG, (double) oldB),
new Color((double) newR, (double) newG, (double) newB));
animationForBuilder.add(tempAnim);
return this;
}
/**
* Adds a scale change to the list of animations to be made.
*/
@Override
public TweenModelBuilder<IModel> addScaleToChange(String name,
float fromSx, float fromSy,
float toSx, float toSy,
int startTime, int endTime) {
IShape tempShape = null;
for (IShape s : shapesForBuilder) {
if (s.getName().equals(name)) {
tempShape = s;
}
}
IAnimation tempAnim = new Scale(tempShape, startTime, endTime,
(double) fromSx, (double) fromSy,
(double) toSx, (double) toSy);
animationForBuilder.add(tempAnim);
return this;
}
/**
* Adds a rotation change to the list of animations to be made.
*/
public TweenModelBuilder<IModel> addRotate(String name, float fromDegree,float toDegree,
int startTime, int endTime) {
IShape tempShape = null;
for (IShape s : shapesForBuilder) {
if (s.getName().equals(name)) {
tempShape = s;
}
}
IAnimation tempAnim = new Rotate(tempShape,
(double)fromDegree,(double)toDegree,startTime,endTime);
animationForBuilder.add(tempAnim);
return this;
}
/**
* Builds the model from the list of animations.
*
* @return the built model.
*/
@Override
public IModel build() {
IModel model = new Model();
for (IShape s : shapesForBuilder) {
model.addShapes(s);
}
for (IAnimation a : animationForBuilder) {
model.addAnimation(a.getShapeName(), a);
}
return model;
}
}
}
|
package model;
public interface LetterLezer {
public char leesLetter();
}
|
package projecteuler;
import java.io.IOException;
import java.math.BigInteger;
public class SelfPowers {
public static void main(String args[]) throws IOException {
BigInteger sum = new BigInteger("0");
for (long i = 1; i <= 1000l; i++) {
sum = sum.add(BigInteger.valueOf(i).pow((int)i));
}
System.out.println(sum);
BigInteger m = sum.mod(new BigInteger("10"));
System.out.println(m);
}
}
|
package com.shilong.jysgl.action.tea;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.shilong.jysgl.pojo.po.Dictinfo;
import com.shilong.jysgl.pojo.po.Paper;
import com.shilong.jysgl.pojo.po.Project;
import com.shilong.jysgl.pojo.po.Teacher;
import com.shilong.jysgl.pojo.vo.PaperCustom;
import com.shilong.jysgl.pojo.vo.PaperQueryVo;
import com.shilong.jysgl.pojo.vo.ProjectCustom;
import com.shilong.jysgl.pojo.vo.ProjectQueryVo;
import com.shilong.jysgl.pojo.vo.TeacherCustom;
import com.shilong.jysgl.process.context.Config;
import com.shilong.jysgl.process.result.CharData;
import com.shilong.jysgl.process.result.Chart;
import com.shilong.jysgl.process.result.ChartsDataSourceResult;
import com.shilong.jysgl.process.result.DataGridResultInfo;
import com.shilong.jysgl.process.result.ExceptionResultInfo;
import com.shilong.jysgl.process.result.PageQuery;
import com.shilong.jysgl.process.result.ResultInfo;
import com.shilong.jysgl.process.result.ResultUtil;
import com.shilong.jysgl.process.result.SubmitResultInfo;
import com.shilong.jysgl.service.DictInfoService;
import com.shilong.jysgl.service.PaperService;
import com.shilong.jysgl.service.TeacherService;
import com.shilong.jysgl.utils.UUIDBuild;
/**
* @Descriptrion :
* @author mr-li
* @Company www.shilong.com
* @CreateDate 2015年11月18日
*/
@Controller
@RequestMapping("/paper")
public class PaperAction {
@Resource
private PaperService paperService;
@Resource
private TeacherService teacherService;
@Resource
private DictInfoService dictInfoService;
@RequestMapping("/paperlist")
public String paperlist(Model model) throws Exception{
List<Dictinfo> shzt_info = dictInfoService.findDictInfoList("001");
List<Dictinfo> lwdc_info = dictInfoService.findDictInfoList("010");
List<Dictinfo> lwlb_info = dictInfoService.findDictInfoList("006");
List<Dictinfo> jszk_info = dictInfoService.findDictInfoList("011");
List<Dictinfo> smwc_info = dictInfoService.findDictInfoList("015");
model.addAttribute("shzt_info", shzt_info);
model.addAttribute("lwdc_info", lwdc_info);
model.addAttribute("lwlb_info", lwlb_info);
model.addAttribute("jszk_info", jszk_info);
model.addAttribute("smwc_info", smwc_info);
return "/paper/paperlist";
}
@RequestMapping("/paperlist_result")
public @ResponseBody DataGridResultInfo projectlist_result(PaperQueryVo paperQueryVo,int rows,int page) throws Exception{
int infoCount=paperService.findPaperCount(paperQueryVo);
PageQuery pageQuery=new PageQuery();
pageQuery.setPageParams(infoCount,rows, page);
paperQueryVo.setPageQuery(pageQuery);
List<PaperCustom> list = paperService.findPaperList(paperQueryVo);
DataGridResultInfo resultInfo = new DataGridResultInfo();
resultInfo.setRows(list);
resultInfo.setTotal(infoCount);
return resultInfo;
}
@RequestMapping("/addpaper")
public String addproject(Model model) throws Exception{
List<Dictinfo> shzt_info = dictInfoService.findDictInfoList("001");
List<Dictinfo> lwdc_info = dictInfoService.findDictInfoList("010");
List<Dictinfo> lwlb_info = dictInfoService.findDictInfoList("006");
List<Dictinfo> jszk_info = dictInfoService.findDictInfoList("011");
List<Dictinfo> smwc_info = dictInfoService.findDictInfoList("015");
model.addAttribute("shzt_info", shzt_info);
model.addAttribute("lwdc_info", lwdc_info);
model.addAttribute("lwlb_info", lwlb_info);
model.addAttribute("jszk_info", jszk_info);
model.addAttribute("smwc_info", smwc_info);
return "/paper/addpaper";
}
@RequestMapping("/addpaper_submit")
public @ResponseBody SubmitResultInfo addpaper_submit(PaperQueryVo paperQueryVo,MultipartFile fj_file,int[] indexs) throws Exception{
PaperCustom paperCustom = paperQueryVo.getPaperCustom();
if(fj_file!=null){
String originalFilename=fj_file.getOriginalFilename();
String new_filename=UUIDBuild.getUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
File file=new File("E:/upload/fj/paper/"+new_filename);
if(!file.exists()){
file.mkdirs();
}
fj_file.transferTo(file);
paperCustom.setFj("/upload/fj/paper/"+new_filename);
paperQueryVo.setPaperCustom(paperCustom);
}
paperService.insertPaper(paperQueryVo, indexs);
return new SubmitResultInfo(ResultUtil.createSuccess(Config.MESSAGE,906,null));
}
@RequestMapping("/editpaper")
public String editpaper(String paid,Model model) throws Exception{
Paper paper=paperService.getPaperById(paid);
List<TeacherCustom> teacherCustoms=paperService.getTeasBybId(paid);
List<Dictinfo> shzt_info = dictInfoService.findDictInfoList("001");
List<Dictinfo> lwdc_info = dictInfoService.findDictInfoList("010");
List<Dictinfo> lwlb_info = dictInfoService.findDictInfoList("006");
List<Dictinfo> jszk_info = dictInfoService.findDictInfoList("011");
List<Dictinfo> smwc_info = dictInfoService.findDictInfoList("015");
model.addAttribute("shzt_info", shzt_info);
model.addAttribute("lwdc_info", lwdc_info);
model.addAttribute("lwlb_info", lwlb_info);
model.addAttribute("jszk_info", jszk_info);
model.addAttribute("smwc_info", smwc_info);
model.addAttribute("paperCustom",paper);
model.addAttribute("teacherCustoms",teacherCustoms);
return "/paper/editpaper";
}
@RequestMapping("/editpaper_submit")
public @ResponseBody SubmitResultInfo editpaper_submit(PaperQueryVo paperQueryVo,MultipartFile fj_file,int[] indexs,String paid) throws Exception{
PaperCustom paperCustom = paperQueryVo.getPaperCustom();
if(fj_file!=null){
String originalFilename=fj_file.getOriginalFilename();
String new_filename=UUIDBuild.getUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
File file=new File("E:/upload/fj/paper/"+new_filename);
if(!file.exists()){
file.mkdirs();
}
fj_file.transferTo(file);
paperCustom.setFj("/upload/fj/paper/"+new_filename);
}else{
Paper paper=paperService.getPaperById(paid);
paperCustom.setFj(paper.getFj());
}
paperQueryVo.setPaperCustom(paperCustom);
paperService.updatePaper(paperQueryVo, indexs, paid);
return new SubmitResultInfo(ResultUtil.createSuccess(Config.MESSAGE,906,null));
}
@RequestMapping("/deletepaper_submit")
public @ResponseBody SubmitResultInfo deletepaper_submit(String paid) throws Exception{
paperService.deletePaperById(paid);
return new SubmitResultInfo(ResultUtil.createSuccess(Config.MESSAGE,906,null));
}
@RequestMapping("/paperdelete_submit")
public @ResponseBody SubmitResultInfo paperdelete_submit(PaperQueryVo paperQueryVo,int[] indexs) throws Exception{
int count=indexs.length;
//处理成功的数量
int count_success = 0;
//处理失败的数量
int count_error = 0;
//处理失败的原因
List<ResultInfo> msgs_error = new ArrayList<ResultInfo>();
for(int i=0;i<count;i++){
ResultInfo resultInfo=null;
String paid=paperQueryVo.getPaperCustoms().get(indexs[i]).getPaid();
try {
paperService.deletePaperById(paid);
} catch (Exception e) {
e.printStackTrace();
if(e instanceof ExceptionResultInfo){
resultInfo=((ExceptionResultInfo) e).getResultInfo();
}else{
resultInfo=ResultUtil.createFail(Config.MESSAGE,900,null);
}
}
if(resultInfo==null){
count_success++;
}else{
count_error++;
msgs_error.add(resultInfo);
}
}
return ResultUtil.createSubmitResult(ResultUtil.createSuccess(Config.MESSAGE,907, new Object[]{count_success,count_error}),msgs_error);
}
@RequestMapping("/analysispaperinfo")
public String analysisprojectinfo(Model model) throws Exception{
List<Dictinfo> shzt_info = dictInfoService.findDictInfoList("001");
List<Dictinfo> lwdc_info = dictInfoService.findDictInfoList("010");
List<Dictinfo> lwlb_info = dictInfoService.findDictInfoList("006");
List<Dictinfo> jszk_info = dictInfoService.findDictInfoList("011");
List<Dictinfo> smwc_info = dictInfoService.findDictInfoList("015");
model.addAttribute("shzt_info", shzt_info);
model.addAttribute("lwdc_info", lwdc_info);
model.addAttribute("lwlb_info", lwlb_info);
model.addAttribute("jszk_info", jszk_info);
model.addAttribute("smwc_info", smwc_info);
return "/paper/analysispaperinfo";
}
@RequestMapping("/analysispaperinfo_submit")
public @ResponseBody ChartsDataSourceResult analysispaperinfo_submit(PaperQueryVo paperQueryVo) throws Exception{
ChartsDataSourceResult cdsr=new ChartsDataSourceResult();
Chart chart=new Chart();
List<CharData> datas=new ArrayList<>();
List<Map> list=paperService.analysisPaperInfo(paperQueryVo);
CharData data1=null;
for(Map map:list){
String lable= map.get("lable")+"";
String data =map.get("data")+"";
data1=new CharData();
data1.setLabel(lable);
data1.setValue(data);
datas.add(data1);
}
chart.setCaption("教师论文信息统计图表");
chart.setyAxisName("人数");
cdsr.setChart(chart);
cdsr.setData(datas);
return cdsr;
}
@RequestMapping("/checkbh")
public @ResponseBody Teacher checkbh(String bh) throws Exception{
Teacher tea=teacherService.getTeacherBybh(bh);
if(tea==null){
return null;
}
return tea;
}
}
|
package prefixtopost;
import java.util.*;
public class PrefixToPost {
public static void main(String[] args) {
Scanner s1=new Scanner (System.in);
String str=s1.next();
Stack<String> st=new Stack<>();
for(int i=str.length()-1;i>=0;i--)
{
if(str.charAt(i)=='+' || str.charAt(i)=='-' || str.charAt(i)=='*' || str.charAt(i)=='/')
{
String str1=st.pop();
String str2=st.pop();
str2=str1 +str2+str.charAt(i);
st.push(str2);
}
else {
String a=String.valueOf(str.charAt(i));
st.push(a);
}
}
String newstr=st.pop();
System.out.println(newstr);
}
}
|
import java.util.Scanner;
public class Arien_scanner1 {
public static void main(String[] args) {
int N, bil1, bil2, i, nilaiMin = 1000, nilaiMax = 2000, jml = 1;
char pil;
Scanner input = new Scanner(System.in);
N = input.nextInt();
pil = input.next().charAt(0);
if (pil == 'A') {
for (i = 0; i < N; i++) {
bil1 = input.nextInt();
if (bil1 <= nilaiMin) {
if (bil1 == nilaiMin) {
jml++;
}
nilaiMin = bil1;
}
}
System.out.println(nilaiMin);
System.out.println(jml);
} else if (pil == 'B') {
for (i = 0; i < N; i++) {
bil2 = input.nextInt();
if (bil2 >= nilaiMax) {
if (bil2 == nilaiMax) {
jml++;
}
nilaiMax = bil2;
}
System.out.println(nilaiMax);
System.out.println(jml);
}
}
}
}
|
package com.youthlin.example.plugin;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.Getter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
/**
* @author youthlin.chen
* @date 2020-04-15 17:41
*/
public class PluginManager<T> {
@Getter
private final Set<PluginInstance<T>> instances = Sets.newHashSet();
public PluginInstance<T> install(File file) {
try {
PluginMeta meta = getMeta(file);
PluginClassLoader classLoader = new PluginClassLoader(fileToUrls(file));
@SuppressWarnings("unchecked")
Class<IPlugin<T>> pluginClass = (Class<IPlugin<T>>) classLoader.loadClass(meta.getEntrance());
IPlugin<T> plugin = pluginClass.getDeclaredConstructor().newInstance();
PluginInstance<T> instance = new PluginInstance<>(meta, classLoader, plugin);
instances.add(instance);
return instance;
} catch (Exception e) {
throw new IllegalStateException("Can not install plugin from file: " + file, e);
}
}
private PluginMeta getMeta(File file) throws IOException {
InputStream is;
if (file.isDirectory()) {
is = new FileInputStream(new File(file, "plugin.properties"));
} else {
JarFile jarFile = new JarFile(file);
ZipEntry metaEntry = jarFile.getEntry("plugin.properties");
is = jarFile.getInputStream(metaEntry);
}
final Properties properties = new Properties();
properties.load(is);
final ImmutableMap<String, String> map = Maps.fromProperties(properties);
return new PluginMeta(
map.get("namespace"),
map.get("entrance"),
map.get("name"),
map.get("author"),
map.get("version"),
map.get("describe")
);
}
private URL[] fileToUrls(File file) throws MalformedURLException {
return new URL[]{file.toURI().toURL()};
}
public void active(PluginInstance<T> instance, T context) {
instance.getPlugin().onActive(context);
instance.setState(State.ACTIVE);
}
public void disable(PluginInstance<T> instance, T context) {
instance.getPlugin().onDisabled(context);
instance.setState(State.DISABLED);
}
public void uninstall(PluginInstance<T> instance) {
Preconditions.checkArgument(Objects.equals(instance.getState(), State.DISABLED),
"Can not uninstall cause this plugin is not disabled");
instance.setState(State.UNINSTALLED);
instances.remove(instance);
}
}
|
package com.leyton.flow.transformer.inter;
import org.springframework.messaging.Message;
public interface CustomTransformer {
Integer transformer(Message<String> message);
}
|
package com.soa;
import com.soa.domain.Ownable;
import com.soa.domain.UserData;
import com.soa.service.DataAccessService;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import java.io.IOException;
import java.security.Principal;
import java.util.List;
import java.util.stream.Collectors;
@EqualsAndHashCode(callSuper = true)
@Data
@ManagedBean
@SessionScoped
@Stateless
@RolesAllowed({"ADMIN", "USER"})
public class AccessBean extends AbstractManagedBean {
@EJB
private DataAccessService dataService;
public boolean canCreate(String category) {
if (FacesContext.getCurrentInstance().getExternalContext().isUserInRole(UserData.UserRole.ADMIN.toString())) {
return true;
}
Integer userIndex = getCurrentUser().getIndex();
switch (category) {
case "Cave":
return userIndex % 3 == 0 && userIndex % 2 != 0;
case "Tower":
return userIndex % 2 == 0 && userIndex % 3 != 0;
case "Forest":
return (userIndex % 2 == 0 && userIndex % 3 == 0) || (userIndex % 2 != 0 && userIndex % 3 != 0);
}
return false;
}
public void checkCreate(String category) throws IllegalAccessException {
if (!canCreate(category)) {
throw new IllegalAccessException();
}
}
public boolean hasAccess(Ownable ownable) {
if (FacesContext.getCurrentInstance().getExternalContext().isUserInRole(UserData.UserRole.ADMIN.toString())) {
return true;
}
UserData userData = ownable.getOwner();
Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
if (userData == null || principal == null) {
return false;
}
return principal.getName().equals(userData.getLogin());
}
public void checkAccess(Ownable ownable) throws IllegalAccessException {
if (!hasAccess(ownable)) {
throw new IllegalAccessException();
}
}
public UserData getCurrentUser() {
String name = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName();
return dataService.findUserDataByLogin(name);
}
public boolean isIsAdmin() {
return getCurrentUser().getRole() == UserData.UserRole.ADMIN;
}
@RolesAllowed("ADMIN")
public List<String> getUsersNames() {
return dataService.findAllUsers().stream()
.map(UserData::getLogin)
.collect(Collectors.toList());
}
public void logout() throws IOException {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
reload();
}
}
|
package com.gmail.nossr50.datatypes;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockBreakEvent;
public class FakeBlockBreakEvent extends BlockBreakEvent {
private static final long serialVersionUID = 1L;
public FakeBlockBreakEvent(Block theBlock, Player player) {
super(theBlock, player);
}
} |
package com.itsoul.lab.generalledger.validation;
import com.itsoul.lab.generalledger.exception.BusinessException;
/**
* Business exception thrown if a transfer validation is illegal.
*
*
*/
public class TransferValidationException extends BusinessException {
private static final long serialVersionUID = -6114850538235916873L;
public TransferValidationException(String message) {
super(message);
}
}
|
package com.hopu.bigdata.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hopu.bigdata.model.Category;
public interface CategoryMapper extends BaseMapper<Category> {
}
|
package com.hwj.service;
import java.util.List;
import com.hwj.entity.Share;
public interface IShareService extends IBaseService<Share>{
List<Share> queryShareMind(Object value, Integer currentPage,
Integer pageSize);
Long searchShareMindPage(Object value);
}
|
package utn.sau.hp.com.modelo;
// Generated 04/12/2014 23:31:51 by Hibernate Tools 3.6.0
import java.util.HashSet;
import java.util.Set;
/**
* Competencias generated by hbm2java
*/
public class Competencias implements java.io.Serializable {
private Integer id;
private Areas areas;
private String competenciaNombre;
private Set requisitoscompetenciases = new HashSet(0);
public Competencias() {
}
public Competencias(Areas areas, String competenciaNombre) {
this.areas = areas;
this.competenciaNombre = competenciaNombre;
}
public Competencias(Areas areas, String competenciaNombre, Set requisitoscompetenciases) {
this.areas = areas;
this.competenciaNombre = competenciaNombre;
this.requisitoscompetenciases = requisitoscompetenciases;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Areas getAreas() {
return this.areas;
}
public void setAreas(Areas areas) {
this.areas = areas;
}
public String getCompetenciaNombre() {
return this.competenciaNombre;
}
public void setCompetenciaNombre(String competenciaNombre) {
this.competenciaNombre = competenciaNombre;
}
public Set getRequisitoscompetenciases() {
return this.requisitoscompetenciases;
}
public void setRequisitoscompetenciases(Set requisitoscompetenciases) {
this.requisitoscompetenciases = requisitoscompetenciases;
}
}
|
public class Question7
{
public static void main(String[] x)
{
int n,rev=0,rem;
int num=123;
n=num;
while(num!=0)
{
rem=num%10;
rev=rev*10+rem;
num /= 10;
}
System.out.println("reverse of number is " + rev);
}
} |
package Screens;
import java.awt.Canvas;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.io.IOException;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
public class MainScreen extends Canvas {
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
/**
* Launch the application.
*
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException,
InterruptedException {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainScreen window = new MainScreen();
window.frame.setVisible(true);
RoadBoard r = new RoadBoard(8);
Road main = new Road(r);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*
* @throws InterruptedException
* @throws IOException
*/
public MainScreen() throws IOException, InterruptedException {
initialize();
}
/**
* Initialize the contents of the frame.
*
* @throws InterruptedException
* @throws IOException
*/
private void initialize() throws IOException, InterruptedException {
frame = new JFrame();
frame.setBounds(500, 00, 300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(this);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
frame.getContentPane().setLayout(null);
}
}
|
//------------------------------------------------------------------------------
// Copyright (c) 2012 Microsoft Corporation. All rights reserved.
//
// Description: See the class level JavaDoc comments.
//------------------------------------------------------------------------------
package com.microsoft.live;
import android.os.AsyncTask;
/**
* TokenRequestAsync performs an async token request. It takes in a TokenRequest,
* executes it, checks the OAuthResponse, and then calls the given listener.
*/
class TokenRequestAsync extends AsyncTask<Void, Void, Void> implements ObservableOAuthRequest {
private final DefaultObservableOAuthRequest observerable;
/** Not null if there was an exception */
private LiveAuthException exception;
/** Not null if there was a response */
private OAuthResponse response;
private final TokenRequest request;
/**
* Constructs a new TokenRequestAsync and initializes its member variables
*
* @param request to perform
*/
public TokenRequestAsync(TokenRequest request) {
assert request != null;
this.observerable = new DefaultObservableOAuthRequest();
this.request = request;
}
@Override
public void addObserver(OAuthRequestObserver observer) {
this.observerable.addObserver(observer);
}
@Override
public boolean removeObserver(OAuthRequestObserver observer) {
return this.observerable.removeObserver(observer);
}
@Override
protected Void doInBackground(Void... params) {
try {
this.response = this.request.execute();
} catch (LiveAuthException e) {
this.exception = e;
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (this.response != null) {
this.observerable.notifyObservers(this.response);
} else if (this.exception != null) {
this.observerable.notifyObservers(this.exception);
} else {
final LiveAuthException exception = new LiveAuthException(ErrorMessages.CLIENT_ERROR);
this.observerable.notifyObservers(exception);
}
}
}
|
package br.com.jogos.olimpicos.resource;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import br.com.jogos.olimpicos.entity.Local;
import br.com.jogos.olimpicos.service.LocalService;
@RestController
@RequestMapping("/local")
public class LocalResource {
@Autowired
private LocalService localService;
/**
* Lista todos locais
* @return
*/
@GetMapping("/listAll")
public List<Local> listar() {
return localService.listAll();
}
/**
* Get Local por Id
* @param codigo
* @return
*/
@GetMapping("/{codigo}")
public ResponseEntity<Local> get(@PathVariable Integer codigo) {
Local local = localService.get(codigo);
return local != null ? ResponseEntity.ok(local) : ResponseEntity.noContent().build();
}
/**
* Delete Local por Id
* @param codigo
*/
@DeleteMapping("/{codigo}")
@ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable Integer codigo) {
localService.delete(codigo);
}
/**
* Salva novo Local
* @param local
* @param response
* @return
*/
@PostMapping("/save")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Local> save(@Valid @RequestBody Local local, HttpServletResponse response) {
Local localSave = localService.save(local);
return ResponseEntity.status(HttpStatus.CREATED).body(localSave);
}
/**
* Atualiza Local por Id
* @param codigo
* @param local
* @return
*/
@PutMapping("/{codigo}")
public ResponseEntity<Local> update(@PathVariable Integer codigo, @Valid @RequestBody Local local) {
Local localSave = localService.atualizar(codigo, local);
return ResponseEntity.ok(localSave);
}
}
|
package edu.mum.sonet.models.enums;
/**
* Created by Jonathan on 12/14/2019.
*/
public enum Location {
NONE, FAIRFIELD, SAN_FRANCISCO, CHICAGO, CAIRO, ADDIS_ABABA, HAVANA
}
|
package com.example.cubomagicoranking2.config;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.cubomagicoranking2.Domain.MelhorDeTres;
import com.example.cubomagicoranking2.R;
import java.util.List;
public class MelhorDeTresAdapter extends RecyclerView.Adapter<MelhorDeTresAdapter.MyViewHolder>{
private List<MelhorDeTres> listaMelhorDeTres;
private Context context;
public MelhorDeTresAdapter(List<MelhorDeTres> listaJogoSimples, Context context) {
this.listaMelhorDeTres = listaJogoSimples;
this.context = context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemLista = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_melhordetres , parent, false);
return new MyViewHolder(itemLista);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
MelhorDeTres mdt = listaMelhorDeTres.get(position);
holder.posicao.setText(String.valueOf(position+1));
holder.nome.setText(mdt.getJogador().getNome());
holder.tempo.setText(mdt.getTempoFinalStr());
}
@Override
public int getItemCount() {
return listaMelhorDeTres.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView posicao;
TextView nome;
TextView tempo;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
posicao = itemView.findViewById(R.id.textViewPosicaoMedia);
nome = itemView.findViewById(R.id.textViewNomeMedia);
tempo = itemView.findViewById(R.id.textViewTempoMedia);
}
}
}
|
package network.nerve.converter.constant;
import io.nuls.core.constant.CommonCodeConstanst;
import io.nuls.core.constant.ErrorCode;
import io.nuls.core.rpc.model.ModuleE;
/**
* @author: Loki
* @date: 2018/11/12
*/
public interface ConverterErrorCode extends CommonCodeConstanst {
ErrorCode CHAIN_NOT_EXIST = ErrorCode.init(ModuleE.CV.getPrefix() + "_0001");
ErrorCode AGENT_ADDRESS_NULL = ErrorCode.init(ModuleE.CV.getPrefix() + "_0002");
ErrorCode HETEROGENEOUS_ADDRESS_NULL = ErrorCode.init(ModuleE.CV.getPrefix() + "_0003");
ErrorCode HETEROGENEOUS_CHAINID_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0004");
ErrorCode PROPOSAL_TYPE_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0005");
ErrorCode PROPOSAL_TX_HASH_NULL = ErrorCode.init(ModuleE.CV.getPrefix() + "_0006");
ErrorCode REMOTE_RESPONSE_DATA_NOT_FOUND = ErrorCode.init(ModuleE.CV.getPrefix() + "_0007");
ErrorCode INSUFFICIENT_BALANCE = ErrorCode.init(ModuleE.CV.getPrefix() + "_0008");
ErrorCode IS_NOT_CURRENT_CHAIN_ADDRESS = ErrorCode.init(ModuleE.CV.getPrefix() + "_0009");
ErrorCode SIGNER_NOT_CONSENSUS_AGENT = ErrorCode.init(ModuleE.CV.getPrefix() + "_0010");
ErrorCode PROPOSAL_VOTE_INVALID = ErrorCode.init(ModuleE.CV.getPrefix() + "_0011");
ErrorCode SIGNER_NOT_VIRTUAL_BANK_AGENT = ErrorCode.init(ModuleE.CV.getPrefix() + "_0012");
ErrorCode RECHARGE_NOT_INCLUDE_COINFROM = ErrorCode.init(ModuleE.CV.getPrefix() + "_0013");
ErrorCode RECHARGE_HAVE_EXACTLY_ONE_COINTO = ErrorCode.init(ModuleE.CV.getPrefix() + "_0014");
ErrorCode HETEROGENEOUS_TX_NOT_EXIST = ErrorCode.init(ModuleE.CV.getPrefix() + "_0015");
ErrorCode RECHARGE_ASSETID_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0016");
ErrorCode RECHARGE_AMOUNT_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0017");
ErrorCode RECHARGE_ARRIVE_ADDRESS_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0018");
ErrorCode AGENT_IS_VIRTUAL_BANK = ErrorCode.init(ModuleE.CV.getPrefix() + "_0019");
ErrorCode AGENT_IS_NOT_VIRTUAL_BANK = ErrorCode.init(ModuleE.CV.getPrefix() + "_0020");
ErrorCode CAN_NOT_JOIN_VIRTUAL_BANK = ErrorCode.init(ModuleE.CV.getPrefix() + "_0021");
ErrorCode CAN_NOT_QUIT_VIRTUAL_BANK = ErrorCode.init(ModuleE.CV.getPrefix() + "_0022");
ErrorCode AGENT_INFO_NOT_FOUND = ErrorCode.init(ModuleE.CV.getPrefix() + "_0023");
ErrorCode WITHDRAWAL_COIN_SIZE_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0024");
ErrorCode WITHDRAWAL_FEE_NOT_EXIST = ErrorCode.init(ModuleE.CV.getPrefix() + "_0025");
ErrorCode WITHDRAWAL_FROM_TO_ASSET_AMOUNT_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0026");
ErrorCode WITHDRAWAL_ARRIVE_ADDRESS_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0027");
ErrorCode WITHDRAWAL_TX_NOT_EXIST = ErrorCode.init(ModuleE.CV.getPrefix() + "_0028");
ErrorCode CFM_WITHDRAWAL_ARRIVE_ADDRESS_MISMATCH = ErrorCode.init(ModuleE.CV.getPrefix() + "_0029");
ErrorCode CFM_WITHDRAWAL_HEIGHT_MISMATCH = ErrorCode.init(ModuleE.CV.getPrefix() + "_0030");
ErrorCode CFM_WITHDRAWAL_AMOUNT_MISMATCH = ErrorCode.init(ModuleE.CV.getPrefix() + "_0031");
ErrorCode VIRTUAL_BANK_OVER_MAXIMUM = ErrorCode.init(ModuleE.CV.getPrefix() + "_0032");
ErrorCode HETEROGENEOUS_COMPONENT_NOT_EXIST = ErrorCode.init(ModuleE.CV.getPrefix() + "_0033");
ErrorCode CHANGE_VIRTUAL_BANK_TX_NOT_EXIST = ErrorCode.init(ModuleE.CV.getPrefix() + "_0034");
ErrorCode VIRTUAL_BANK_MISMATCH = ErrorCode.init(ModuleE.CV.getPrefix() + "_0035");
ErrorCode HETEROGENEOUS_TX_TIME_MISMATCH = ErrorCode.init(ModuleE.CV.getPrefix() + "_0036");
ErrorCode VIRTUAL_BANK_MULTIADDRESS_MISMATCH = ErrorCode.init(ModuleE.CV.getPrefix() + "_0037");
ErrorCode TX_SUBSIDY_FEE_ADDRESS_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0038");
ErrorCode TX_INSUFFICIENT_SUBSIDY_FEE = ErrorCode.init(ModuleE.CV.getPrefix() + "_0039");
ErrorCode CFM_IS_DUPLICATION = ErrorCode.init(ModuleE.CV.getPrefix() + "_0040");
ErrorCode DISTRIBUTION_FEE_IS_DUPLICATION = ErrorCode.init(ModuleE.CV.getPrefix() + "_0041");
ErrorCode HETEROGENEOUS_SIGN_ADDRESS_LIST_EMPTY = ErrorCode.init(ModuleE.CV.getPrefix() + "_0042");
ErrorCode DISTRIBUTION_ADDRESS_MISMATCH = ErrorCode.init(ModuleE.CV.getPrefix() + "_0043");
ErrorCode DISTRIBUTION_FEE_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0044");
ErrorCode HETEROGENEOUS_SIGNER_LIST_MISMATCH = ErrorCode.init(ModuleE.CV.getPrefix() + "_0045");
ErrorCode HETEROGENEOUS_INIT_DUPLICATION = ErrorCode.init(ModuleE.CV.getPrefix() + "_0046");
ErrorCode HETEROGENEOUS_HAS_BEEN_INITIALIZED = ErrorCode.init(ModuleE.CV.getPrefix() + "_0047");
ErrorCode TX_DUPLICATION = ErrorCode.init(ModuleE.CV.getPrefix() + "_0048");
ErrorCode PASSWORD_IS_WRONG = ErrorCode.init(ModuleE.CV.getPrefix() + "_0049");
ErrorCode PASSWORD_FORMAT_WRONG = ErrorCode.init(ModuleE.CV.getPrefix() + "_0050");
ErrorCode ASSET_ID_EXIST = ErrorCode.init(ModuleE.CV.getPrefix() + "_0051");
ErrorCode ACCOUNT_NOT_EXIST = ErrorCode.init(ModuleE.CV.getPrefix() + "_0052");
ErrorCode HETEROGENEOUS_TRANSACTION_COMPLETED = ErrorCode.init(ModuleE.CV.getPrefix() + "_0053");
ErrorCode HETEROGENEOUS_TRANSACTION_DATA_INCONSISTENCY = ErrorCode.init(ModuleE.CV.getPrefix() + "_0054");
ErrorCode HETEROGENEOUS_TRANSACTION_CONTRACT_VALIDATION_FAILED = ErrorCode.init(ModuleE.CV.getPrefix() + "_0055");
ErrorCode HETEROGENEOUS_MANAGER_CHANGE_ERROR_1 = ErrorCode.init(ModuleE.CV.getPrefix() + "_0056");//待加入中存在地址-已经是管理员
ErrorCode HETEROGENEOUS_MANAGER_CHANGE_ERROR_2 = ErrorCode.init(ModuleE.CV.getPrefix() + "_0057");//重复的待加入地址列表
ErrorCode HETEROGENEOUS_MANAGER_CHANGE_ERROR_3 = ErrorCode.init(ModuleE.CV.getPrefix() + "_0058");//待退出中存在地址-不是管理员
ErrorCode HETEROGENEOUS_MANAGER_CHANGE_ERROR_4 = ErrorCode.init(ModuleE.CV.getPrefix() + "_0059");//重复的待退出地址列表
ErrorCode HETEROGENEOUS_MANAGER_CHANGE_ERROR_5 = ErrorCode.init(ModuleE.CV.getPrefix() + "_0060");//Maximum 15 managers
ErrorCode HETEROGENEOUS_MANAGER_CHANGE_ERROR_6 = ErrorCode.init(ModuleE.CV.getPrefix() + "_0061");//退出的管理员不能参与管理员变更交易
ErrorCode ASSET_EXIST = ErrorCode.init(ModuleE.CV.getPrefix() + "_0062");
ErrorCode REG_ASSET_INFO_INCONSISTENCY = ErrorCode.init(ModuleE.CV.getPrefix() + "_0063");
ErrorCode HETEROGENEOUS_CHAIN_NAME_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0064");
ErrorCode HETEROGENEOUS_INVOK_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0065");
ErrorCode SIGNATURE_BYZANTINE_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0066");
ErrorCode COINDATA_CANNOT_EXIST = ErrorCode.init(ModuleE.CV.getPrefix() + "_0067");
ErrorCode PROPOSAL_VOTE_RANGE_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0068");
ErrorCode PROPOSAL_HETEROGENEOUS_TX_MISMATCH = ErrorCode.init(ModuleE.CV.getPrefix() + "_0069");
ErrorCode PROPOSAL_HETEROGENEOUS_TX_AMOUNT_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0070");
ErrorCode ADDRESS_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0071");
ErrorCode PROPOSAL_CONTENT_EMPTY = ErrorCode.init(ModuleE.CV.getPrefix() + "_0072");
ErrorCode PROPOSAL_NOT_EXIST = ErrorCode.init(ModuleE.CV.getPrefix() + "_0073");
ErrorCode VOTE_CHOICE_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0074");
ErrorCode VOTING_STOPPED = ErrorCode.init(ModuleE.CV.getPrefix() + "_0075");
ErrorCode VOTER_SIGNER_MISMATCH = ErrorCode.init(ModuleE.CV.getPrefix() + "_0076");
ErrorCode DUPLICATE_VOTE = ErrorCode.init(ModuleE.CV.getPrefix() + "_0077");
ErrorCode NO_VOTING_RIGHTS = ErrorCode.init(ModuleE.CV.getPrefix() + "_0078");
ErrorCode PAUSE_NEWTX = ErrorCode.init(ModuleE.CV.getPrefix() + "_0080");
ErrorCode PROPOSAL_REJECTED= ErrorCode.init(ModuleE.CV.getPrefix() + "_0081");
ErrorCode ADDRESS_LOCKED= ErrorCode.init(ModuleE.CV.getPrefix() + "_0082");
ErrorCode ADDRESS_UNLOCKED= ErrorCode.init(ModuleE.CV.getPrefix() + "_0083");
ErrorCode DISQUALIFICATION_FAILED= ErrorCode.init(ModuleE.CV.getPrefix() + "_0084");
ErrorCode PROPOSAL_EXECUTIVE_FAILED = ErrorCode.init(ModuleE.CV.getPrefix() + "_0084");
ErrorCode SIGNER_NOT_SEED = ErrorCode.init(ModuleE.CV.getPrefix() + "_0085");
ErrorCode RESET_TX_NOT_EXIST = ErrorCode.init(ModuleE.CV.getPrefix() + "_0086");
ErrorCode HETEROGENEOUS_ASSET_NOT_FOUND = ErrorCode.init(ModuleE.CV.getPrefix() + "_0087");
ErrorCode WITHDRAWAL_CONFIRMED = ErrorCode.init(ModuleE.CV.getPrefix() + "_0088");
ErrorCode AGENT_IS_NOT_SEED_VIRTUAL_BANK = ErrorCode.init(ModuleE.CV.getPrefix() + "_0089");
ErrorCode NODE_NOT_IN_RUNNING = ErrorCode.init(ModuleE.CV.getPrefix() + "_0090");
ErrorCode NO_LONGER_SUPPORTED = ErrorCode.init(ModuleE.CV.getPrefix() + "_0091");
ErrorCode DUPLICATE_BIND = ErrorCode.init(ModuleE.CV.getPrefix() + "_0092");
ErrorCode ASSET_ID_NOT_EXIST = ErrorCode.init(ModuleE.CV.getPrefix() + "_0093");
ErrorCode HETEROGENEOUS_INFO_NOT_MATCH = ErrorCode.init(ModuleE.CV.getPrefix() + "_0094");
ErrorCode OVERRIDE_BIND_ASSET_NOT_FOUND = ErrorCode.init(ModuleE.CV.getPrefix() + "_0095");
ErrorCode HIGH_GAS_PRICE_OF_ETH = ErrorCode.init(ModuleE.CV.getPrefix() + "_0096");
ErrorCode NOT_BIND_ASSET = ErrorCode.init(ModuleE.CV.getPrefix() + "_0097");
ErrorCode INSUFFICIENT_FEE_OF_WITHDRAW = ErrorCode.init(ModuleE.CV.getPrefix() + "_0098");
ErrorCode WITHDRAWAL_ADDITIONAL_FEE_UNMATCHED = ErrorCode.init(ModuleE.CV.getPrefix() + "_0099");
ErrorCode DUPLICATE_REGISTER = ErrorCode.init(ModuleE.CV.getPrefix() + "_0100");
ErrorCode PROPOSAL_CONFIRMED = ErrorCode.init(ModuleE.CV.getPrefix() + "_0101");
ErrorCode HTG_RPC_UNAVAILABLE = ErrorCode.init(ModuleE.CV.getPrefix() + "_0102");
ErrorCode WITHDRAWAL_ADDITIONAL_FEE_COIN_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0103");
ErrorCode ONE_CLICK_CROSS_CHAIN_DES_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0104");
ErrorCode ONE_CLICK_CROSS_CHAIN_FEE_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0105");
ErrorCode ONE_CLICK_CROSS_CHAIN_TX_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0106");
ErrorCode ONE_CLICK_CROSS_CHAIN_TIPPING_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0107");
ErrorCode ADD_FEE_CROSS_CHAIN_FEE_ADDRESS_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0108");
ErrorCode ADD_FEE_CROSS_CHAIN_COIN_ERROR = ErrorCode.init(ModuleE.CV.getPrefix() + "_0109");
ErrorCode WITHDRAWAL_PAUSE = ErrorCode.init(ModuleE.CV.getPrefix() + "_0110");
}
|
package com.fb.kit;
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// . ' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
//
// .............................................
// 佛祖保佑 永无BUG
// 佛曰:
// 写字楼里写字间,写字间里程序员;
// 程序人员写程序,又拿程序换酒钱。
// 酒醒只在网上坐,酒醉还来网下眠;
// 酒醉酒醒日复日,网上网下年复年。
// 但愿老死电脑间,不愿鞠躬老板前;
// 奔驰宝马贵者趣,公交自行程序员。
// 别人笑我忒疯癫,我笑自己命太贱;
// 不见满街漂亮妹,哪个归得程序员?
import com.fb.pojos.MpSession;
import java.util.HashMap;
import java.util.Map;
/**
* 常量配置
* @author sun
* @date 2016年8月23日 上午10:33:42
*/
public class CommonUtils {
/** 网站后台的字典基本配置信息 **/
public static final int DICTIONARY_PLATFORM_SYSTEM = 1;
/** 网站前台的字典基本配置信息 **/
public static final int DICTIONARY_PLATFORM_WEBSITE = 2;
/** memcache key 用来保存在线管理员 **/
public static final Map<String, MpSession> sessionMap = new HashMap<String, MpSession>();
/**
* SettingGlobal 全局配置表
* @author sun
* @date 2016年8月23日 上午10:32:51
*/
public final static class SettingGlobal{
/** 系统操作日志开关 **/
public static final String SYSTEM_LOG_SWITCH = "system_log_switch";
/** 后台登录是否开启验证码的开关 **/
public static final String SYSTEM_LOGIN_VERIFYCODE_SWITCH = "system_login_verifycode_switch";
/** 登陆页面背景模版 **/
public static final String SYSTEM_LOGIN_BACKGROUND = "system_login_background";
/** 后台模版 **/
public static final String SYSTEM_SKIN_CLASS = "system_skin_class";
/** 后台边栏锁定 **/
public static final String SYSTEM_FIXED_SETTING = "system_fixed_setting";
/** 后台系统颜色设置 **/
public static final String SYSTEM_SETTING_COLOR = "system_setting_color";
/** setting_global 表的全局设置 **/
public static final String SG_WHITE_LIST_IPS = "white_list_ips";
/** 密码错误次数 **/
public static final String PASSWORD_ERROR_MAX_NUM = "password_error_max_num";
/** 密码错误锁定时长 **/
public static final String PASSWORD_ERROR_MAX_TIME = "password_error_max_time";
public static final String MESSAGE_DYNAMIC_FIELD = "message_dynamic_field";
public static final String DYNAMIC_SMS = "dynamic_sms";
public static final String KF_DYNAMIC_MESSAGE = "kf_dynamic_message";
}
/**
* 字典表Key值
* @author sun
* @date 2016年8月23日 上午10:33:01
*/
public final static class DictionaryKey{
/** 部门渠道 **/
public static final String DEPT_CHANNEL = "DEPT_CHANNEL";
/** 惠农聚宝标的产品类型 **/
public static final String HNJB_LOAN_PRODUCT_TYPE = "hnjb_loan_product_type";
/** 十月复投活动返现开关,只允许执行一次 **/
public static final String OCT_RECEIVE_ENABLE = "OCT_RECEIVE_ENABLE";
/** 平台 **/
public static final String SYSTEM_PLATFORM = "SYSTEM_PLATFORM";
}
/**
* gritter 弹窗提醒相关变量
* @date 2016年10月14日 上午8:58:29
*/
public final static class Gritter{
/** Girtter 通知窗口 */
public static final String GRITTER_TYPE = "gritter_type";//类型(不可为空), 包含 gritter-default、gritter-info、gritter-warning、gritter-error、gritter-success、gritter-center
public static final String GRITTER_CONTENT = "gritter_content";//通知内容(不可为空)
public static final String GRITTER_TITLE = "gritter_title";//通知窗口标题
public static final String GRITTER_IMAGE = "gritter_image";//头像
public static final String GRITTER_TIME = "gritter_time";//窗口关闭时间,毫秒
public static final String GRITTER_LIGHT = "gritter_light";//是否开灯照亮, 说的是背景颜色
/** Gritter 通知窗口类型 **/
public static final String GRITTER_TYPE_DEFAULT = "gritter-default";
public static final String GRITTER_TYPE_INFO = "gritter-info";
public static final String GRITTER_TYPE_WARNING = "gritter-warning";
public static final String GRITTER_TYPE_ERROR = "gritter-error";
public static final String GRITTER_TYPE_SUCCESS = "gritter-success";
public static final String GRITTER_TYPE_CENTER = "gritter-center";
}
/**
* Statistics包下 - 统计类的常量
* @date 2016年10月14日 上午9:02:54
*/
public final static class Statistics{
/** 统计名字 */
public static final String PF1 = "registerDD";
public static final String PF2 = "newuserInvest";
public static final String PF3 = "newuserRechange";
public static final String PF4 = "olduserInvest";
public static final String PF5 = "olduserRechange";
public static final String PF6 = "pvuv";
public static final String PF7 = "rechange_wc";
/** 平台统计 **/
public static final String TPF1 = "total_user";
public static final String TPF2 = "total_auth_user";
public static final String TPF3 = "total_recharge";
public static final String TPF4 = "total_invest";
public static final String TPF5 = "total_wc";
}
public static String switchHtml(String method){
String page = null;
if("all".equals(method)){
page = "allsearch.html";
}else if("hetang".equals(method)){
page = "hetangsearch.html";
}else if("natural".equals(method)){
page = "naturalsearch.html";
}else if("detail".equals(method)){
page = "detailsearch.html";
}else if("md".equals(method)){
page = "mdsearch.html";
}else if("offline".equals(method)){
page = "offlinesearch.html";
}else if("od".equals(method)){
page = "odsearch.html";
}else if("not_active".equals(method)){//未激活列表
page = "notActivesearch.html";
}else if("activated".equals(method)){//已激活列表
page = "activatedsearch.html";
}else if("data_count".equals(method)){//优惠卡数据统计
page = "dataCountsearch.html";
}
return page;
}
}
|
package com.example.attest.service;
import com.example.attest.dao.TransactionRepository;
import com.example.attest.model.api.TransactionStatusApiRequest;
import com.example.attest.model.api.TransactionStatusApiResponse;
import com.example.attest.model.domain.ChannelType;
import com.example.attest.model.domain.Transaction;
import com.example.attest.model.domain.TransactionStatus;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Optional;
import org.springframework.stereotype.Service;
@Service
public class TransactionStatusServiceImpl implements TransactionStatusService {
private TransactionRepository transactionRepository;
public TransactionStatusServiceImpl(TransactionRepository transactionRepository) {
this.transactionRepository = transactionRepository;
}
@Override
public TransactionStatusApiResponse getTransactionStatus(TransactionStatusApiRequest transactionStatusApiRequest) {
/**
* NOTE IMPORTANT:
* As the channel is not mandatory and the requirements do not say anything about the behaviour in this case,
* It has been considered that if we do not have the channel, it is interpreted as CLIENT
*/
if (transactionStatusApiRequest.getChannel() == null) {
transactionStatusApiRequest.setChannel(ChannelType.CLIENT);
}
Optional<Transaction> transactionOptional =
transactionRepository.findByReference(transactionStatusApiRequest.getReference());
if (!transactionOptional.isPresent()) {
return TransactionStatusApiResponse.builder()
.reference(transactionStatusApiRequest.getReference())
.status(TransactionStatus.INVALID)
.build();
} else {
Transaction transactionStored = transactionOptional.get();
// I suppose the date is stored always in UTC zone
LocalDate localDate = transactionStored.getDate()
.toLocalDate();
LocalDate today = LocalDate.now(ZoneId.of("UTC"));
if (localDate.isBefore(today)) {
return getStatusIfTransactionIsBeforeToday(transactionStatusApiRequest, transactionStored);
} else if (localDate.isEqual(today)) {
return getStatusIfTransactionIsToday(transactionStatusApiRequest, transactionStored);
} else {
return getStatusIfTransactionIsAfterToday(transactionStatusApiRequest, transactionStored);
}
}
}
private TransactionStatusApiResponse getStatusIfTransactionIsToday(TransactionStatusApiRequest transactionStatusApiRequest,
Transaction transactionStored) {
BigDecimal fee = transactionStored.getFee() == null ? BigDecimal.ZERO : transactionStored.getFee();
if (transactionStatusApiRequest.getChannel()
.equals(ChannelType.INTERNAL)) {
return TransactionStatusApiResponse.builder()
.reference(transactionStatusApiRequest.getReference())
.status(TransactionStatus.PENDING)
.amount(transactionStored.getAmount())
.fee(fee)
.build();
} else {
// Regardless of the channel, we return the PENDING status with the fee deducted
return TransactionStatusApiResponse.builder()
.reference(transactionStatusApiRequest.getReference())
.status(TransactionStatus.PENDING)
.amount(transactionStored.getAmount()
.subtract(fee))
.build();
}
}
private TransactionStatusApiResponse getStatusIfTransactionIsBeforeToday(
TransactionStatusApiRequest transactionStatusApiRequest,
Transaction transactionStored) {
BigDecimal fee = transactionStored.getFee() == null ? BigDecimal.ZERO : transactionStored.getFee();
if (transactionStatusApiRequest.getChannel()
.equals(ChannelType.INTERNAL)) {
return TransactionStatusApiResponse.builder()
.reference(transactionStatusApiRequest.getReference())
.status(TransactionStatus.SETTLED)
.amount(transactionStored.getAmount())
.fee(fee)
.build();
} else {
// Regardless of the channel, we return the SETTLED status with the fee deducted
return TransactionStatusApiResponse.builder()
.reference(transactionStatusApiRequest.getReference())
.status(TransactionStatus.SETTLED)
.amount(transactionStored.getAmount()
.subtract(fee))
.build();
}
}
private TransactionStatusApiResponse getStatusIfTransactionIsAfterToday(
TransactionStatusApiRequest transactionStatusApiRequest,
Transaction transactionStored) {
BigDecimal fee = transactionStored.getFee() == null ? BigDecimal.ZERO : transactionStored.getFee();
if (transactionStatusApiRequest.getChannel()
.equals(ChannelType.ATM)) {
return TransactionStatusApiResponse.builder()
.reference(transactionStatusApiRequest.getReference())
.status(TransactionStatus.PENDING)
.amount(transactionStored.getAmount()
.subtract(fee))
.build();
} else if (transactionStatusApiRequest.getChannel()
.equals(ChannelType.INTERNAL)) {
return TransactionStatusApiResponse.builder()
.reference(transactionStatusApiRequest.getReference())
.status(TransactionStatus.FUTURE)
.amount(transactionStored.getAmount())
.fee(fee)
.build();
} else {
return TransactionStatusApiResponse.builder()
.reference(transactionStatusApiRequest.getReference())
.status(TransactionStatus.FUTURE)
.amount(transactionStored.getAmount()
.subtract(fee))
.build();
}
}
}
|
/*
* Copyright 2002-2023 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.support;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.util.Arrays;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Representation of a
* <a href="https://www.manpagez.com/man/5/crontab/">crontab expression</a>
* that can calculate the next time it matches.
*
* <p>{@code CronExpression} instances are created through
* {@link #parse(String)}; the next match is determined with
* {@link #next(Temporal)}.
*
* @author Arjen Poutsma
* @since 5.3
* @see CronTrigger
*/
public final class CronExpression {
static final int MAX_ATTEMPTS = 366;
private static final String[] MACROS = new String[] {
"@yearly", "0 0 0 1 1 *",
"@annually", "0 0 0 1 1 *",
"@monthly", "0 0 0 1 * *",
"@weekly", "0 0 0 * * 0",
"@daily", "0 0 0 * * *",
"@midnight", "0 0 0 * * *",
"@hourly", "0 0 * * * *"
};
private final CronField[] fields;
private final String expression;
private CronExpression(CronField seconds, CronField minutes, CronField hours,
CronField daysOfMonth, CronField months, CronField daysOfWeek, String expression) {
// Reverse order, to make big changes first.
// To make sure we end up at 0 nanos, we add an extra field.
this.fields = new CronField[] {daysOfWeek, months, daysOfMonth, hours, minutes, seconds, CronField.zeroNanos()};
this.expression = expression;
}
/**
* Parse the given
* <a href="https://www.manpagez.com/man/5/crontab/">crontab expression</a>
* string into a {@code CronExpression}.
* The string has six single space-separated time and date fields:
* <pre>
* ┌───────────── second (0-59)
* │ ┌───────────── minute (0 - 59)
* │ │ ┌───────────── hour (0 - 23)
* │ │ │ ┌───────────── day of the month (1 - 31)
* │ │ │ │ ┌───────────── month (1 - 12) (or JAN-DEC)
* │ │ │ │ │ ┌───────────── day of the week (0 - 7)
* │ │ │ │ │ │ (0 or 7 is Sunday, or MON-SUN)
* │ │ │ │ │ │
* * * * * * *
* </pre>
*
* <p>The following rules apply:
* <ul>
* <li>
* A field may be an asterisk ({@code *}), which always stands for
* "first-last". For the "day of the month" or "day of the week" fields, a
* question mark ({@code ?}) may be used instead of an asterisk.
* </li>
* <li>
* Ranges of numbers are expressed by two numbers separated with a hyphen
* ({@code -}). The specified range is inclusive.
* </li>
* <li>Following a range (or {@code *}) with {@code /n} specifies
* the interval of the number's value through the range.
* </li>
* <li>
* English names can also be used for the "month" and "day of week" fields.
* Use the first three letters of the particular day or month (case does not
* matter).
* </li>
* <li>
* The "day of month" and "day of week" fields can contain a
* {@code L}-character, which stands for "last", and has a different meaning
* in each field:
* <ul>
* <li>
* In the "day of month" field, {@code L} stands for "the last day of the
* month". If followed by an negative offset (i.e. {@code L-n}), it means
* "{@code n}th-to-last day of the month". If followed by {@code W} (i.e.
* {@code LW}), it means "the last weekday of the month".
* </li>
* <li>
* In the "day of week" field, {@code dL} or {@code DDDL} stands for
* "the last day of week {@code d} (or {@code DDD}) in the month".
* </li>
* </ul>
* </li>
* <li>
* The "day of month" field can be {@code nW}, which stands for "the nearest
* weekday to day of the month {@code n}".
* If {@code n} falls on Saturday, this yields the Friday before it.
* If {@code n} falls on Sunday, this yields the Monday after,
* which also happens if {@code n} is {@code 1} and falls on a Saturday
* (i.e. {@code 1W} stands for "the first weekday of the month").
* </li>
* <li>
* The "day of week" field can be {@code d#n} (or {@code DDD#n}), which
* stands for "the {@code n}-th day of week {@code d} (or {@code DDD}) in
* the month".
* </li>
* </ul>
*
* <p>Example expressions:
* <ul>
* <li>{@code "0 0 * * * *"} = the top of every hour of every day.</li>
* <li><code>"*/10 * * * * *"</code> = every ten seconds.</li>
* <li>{@code "0 0 8-10 * * *"} = 8, 9 and 10 o'clock of every day.</li>
* <li>{@code "0 0 6,19 * * *"} = 6:00 AM and 7:00 PM every day.</li>
* <li>{@code "0 0/30 8-10 * * *"} = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day.</li>
* <li>{@code "0 0 9-17 * * MON-FRI"} = on the hour nine-to-five weekdays</li>
* <li>{@code "0 0 0 25 12 ?"} = every Christmas Day at midnight</li>
* <li>{@code "0 0 0 L * *"} = last day of the month at midnight</li>
* <li>{@code "0 0 0 L-3 * *"} = third-to-last day of the month at midnight</li>
* <li>{@code "0 0 0 1W * *"} = first weekday of the month at midnight</li>
* <li>{@code "0 0 0 LW * *"} = last weekday of the month at midnight</li>
* <li>{@code "0 0 0 * * 5L"} = last Friday of the month at midnight</li>
* <li>{@code "0 0 0 * * THUL"} = last Thursday of the month at midnight</li>
* <li>{@code "0 0 0 ? * 5#2"} = the second Friday in the month at midnight</li>
* <li>{@code "0 0 0 ? * MON#1"} = the first Monday in the month at midnight</li>
* </ul>
*
* <p>The following macros are also supported:
* <ul>
* <li>{@code "@yearly"} (or {@code "@annually"}) to run un once a year, i.e. {@code "0 0 0 1 1 *"},</li>
* <li>{@code "@monthly"} to run once a month, i.e. {@code "0 0 0 1 * *"},</li>
* <li>{@code "@weekly"} to run once a week, i.e. {@code "0 0 0 * * 0"},</li>
* <li>{@code "@daily"} (or {@code "@midnight"}) to run once a day, i.e. {@code "0 0 0 * * *"},</li>
* <li>{@code "@hourly"} to run once an hour, i.e. {@code "0 0 * * * *"}.</li>
* </ul>
* @param expression the expression string to parse
* @return the parsed {@code CronExpression} object
* @throws IllegalArgumentException in the expression does not conform to
* the cron format
*/
public static CronExpression parse(String expression) {
Assert.hasLength(expression, "Expression string must not be empty");
expression = resolveMacros(expression);
String[] fields = StringUtils.tokenizeToStringArray(expression, " ");
if (fields.length != 6) {
throw new IllegalArgumentException(String.format(
"Cron expression must consist of 6 fields (found %d in \"%s\")", fields.length, expression));
}
try {
CronField seconds = CronField.parseSeconds(fields[0]);
CronField minutes = CronField.parseMinutes(fields[1]);
CronField hours = CronField.parseHours(fields[2]);
CronField daysOfMonth = CronField.parseDaysOfMonth(fields[3]);
CronField months = CronField.parseMonth(fields[4]);
CronField daysOfWeek = CronField.parseDaysOfWeek(fields[5]);
return new CronExpression(seconds, minutes, hours, daysOfMonth, months, daysOfWeek, expression);
}
catch (IllegalArgumentException ex) {
String msg = ex.getMessage() + " in cron expression \"" + expression + "\"";
throw new IllegalArgumentException(msg, ex);
}
}
/**
* Determine whether the given string represents a valid cron expression.
* @param expression the expression to evaluate
* @return {@code true} if the given expression is a valid cron expression
* @since 5.3.8
*/
public static boolean isValidExpression(@Nullable String expression) {
if (expression == null) {
return false;
}
try {
parse(expression);
return true;
}
catch (IllegalArgumentException ex) {
return false;
}
}
private static String resolveMacros(String expression) {
expression = expression.trim();
for (int i = 0; i < MACROS.length; i = i + 2) {
if (MACROS[i].equalsIgnoreCase(expression)) {
return MACROS[i + 1];
}
}
return expression;
}
/**
* Calculate the next {@link Temporal} that matches this expression.
* @param temporal the seed value
* @param <T> the type of temporal
* @return the next temporal that matches this expression, or {@code null}
* if no such temporal can be found
*/
@Nullable
public <T extends Temporal & Comparable<? super T>> T next(T temporal) {
return nextOrSame(ChronoUnit.NANOS.addTo(temporal, 1));
}
@Nullable
private <T extends Temporal & Comparable<? super T>> T nextOrSame(T temporal) {
for (int i = 0; i < MAX_ATTEMPTS; i++) {
T result = nextOrSameInternal(temporal);
if (result == null || result.equals(temporal)) {
return result;
}
temporal = result;
}
return null;
}
@Nullable
private <T extends Temporal & Comparable<? super T>> T nextOrSameInternal(T temporal) {
for (CronField field : this.fields) {
temporal = field.nextOrSame(temporal);
if (temporal == null) {
return null;
}
}
return temporal;
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof CronExpression that &&
Arrays.equals(this.fields, that.fields)));
}
@Override
public int hashCode() {
return Arrays.hashCode(this.fields);
}
/**
* Return the expression string used to create this {@code CronExpression}.
*/
@Override
public String toString() {
return this.expression;
}
}
|
import java.io.*;
import java.util.*;
public class main {
public static void main(String[] args) throws IOException {
for (;;) {
Stack<String> elements = toONP();
try
{
double wynik = Wynik(elements);
if (!elements.empty())
throw new Exception();
System.out.println(wynik);
}
catch (Exception e) {System.out.println("error");}
}
}
private static Stack<String> toONP() throws IOException
{
BufferedReader wyrazenie = new BufferedReader(new InputStreamReader(System.in));
String s = wyrazenie.readLine();
char[] try1 = s.toCharArray();
s = "";
for (int i = try1.length-1; i>=0; i--)
s = s + try1[i];
Stack<String> stos = new Stack<String>();
Stack<String> wyjscie = new Stack<String>();
Stack<String> elements = new Stack<String>();
elements.addAll(Arrays.asList(s.trim().split("[ \t]+")));
for(int i = 0; i < elements.size(); i++)
{
String reverse = new String();
for (int j = elements.get(i).length() - 1 ; j >= 0 ; j--)
reverse = reverse + elements.get(i).charAt(j);
elements.setElementAt(reverse, i);
}
while(!elements.empty())
{
String pom = new String();
pom = elements.pop();
if(pom.equals("("))
{
stos.push("(");
}
else if(pom.equals(")"))
{
while(!stos.lastElement().equals("("))
{
if(!stos.lastElement().equals("("))
wyjscie.push(stos.pop());
else
stos.pop();
}
stos.pop();
}
else if(pom.equals("+") || pom.equals("-") || pom.equals("*") || pom.equals("/") || pom.equals("^"))
{
while(!stos.empty())
{
if(level(pom) == 3 || level(pom) > level(stos.lastElement()))
{
break;
}
wyjscie.push(stos.pop());
}
stos.push(pom);
}
else if(!pom.equals(" "))
wyjscie.push(pom);
}
while(!stos.empty())
{
String pom = new String();
pom = stos.pop();
wyjscie.push(pom);
}
String wynik = new String();
wynik = "";
for(int i = 0; i < wyjscie.size(); i++)
wynik = wynik + " " + wyjscie.get(i);
System.out.println(wynik);
return wyjscie;
}
private static double Wynik(Stack<String> elements) throws Exception {
String element = elements.pop();
double x,y;
try
{
x = Double.parseDouble(element);
}
catch (Exception e)
{
y = Wynik(elements);
x = Wynik(elements);
if(element.equals("+"))
x += y;
else if (element.equals("-"))
x -= y;
else if (element.equals("*"))
x *= y;
else if (element.equals("/"))
x /= y;
else if (element.equals("^"))
x = Math.pow(x, y);
else throw new Exception();
}
return x;
}
private static int level(String pom)
{
switch(pom)
{
case "+":;
case "-": return 1;
case "*":;
case "/": return 2;
case "^": return 3;
}
return 0;
}
} |
package com.github.dongchan.scheduler;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.jupiter.api.extension.Extension;
import javax.sql.DataSource;
/**
* @author Dongchan Year
*/
public class EmbeddedMySQLExtension implements Extension {
private final DataSource dataSource;
public EmbeddedMySQLExtension() {
synchronized (this){
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://192.168.43.251:33081/easesqlbot?useUnicode=true&characterEncoding=utf-8&useSSL=false&useTimezone=true&serverTimezone=GMT%2B8");
config.setUsername("super");
config.setPassword("super");
this.dataSource = new HikariDataSource(config);
}
}
public DataSource getDataSource() {
return dataSource;
}
}
|
package practice11;
import java.util.*;
import java.util.Observer;
import java.util.stream.Collectors;
public class Teacher extends Person {
private int id;
private String name;
private int age;
private HashSet<Klass> classes;
private HashSet<Klass> subjects;
public Teacher(int id, String name, int age) {
super(id, name, age);
this.id = id;
this.name = name;
this.age = age;
}
public Teacher(int id, String name, int age, HashSet<Klass> classes) {
super(id, name, age);
this.id = id;
this.name = name;
this.age = age;
this.classes = classes;
classes.forEach(x->{
x.attach(this);
});
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public HashSet<Klass> getClasses() {
return classes;
}
public boolean isTeaching(Student student) {
return classes.contains(student.getKlass());
}
public String introduceWith(Student student) {
return "My name is " + getName() + ". I am " + getAge() + " years old. I am a Teacher. " + (isTeaching(student) ? ("I teach ") : ("I don't teach ")) + student.getName() + ".";
}
public String introduce() {
if (classes == null) {
return "My name is " + getName() + ". I am " + getAge() + " years old. I am a Teacher. I teach No Class.";
}
StringBuilder c = new StringBuilder();
ArrayList<Integer> list = new ArrayList<>();
classes.forEach(x-> list.add(x.getNumber()));
Collections.sort(list);
list.forEach(integer -> c.append(" " + integer + ","));
return "My name is " + getName() + ". I am " + getAge() + " years old. I am a Teacher. I teach Class" + c.substring(0, c.length() - 1) + ".";
}
public void updateAppendMember(Student student) {
if (isTeaching(student)) {
String s = "I am "+ getName() +"."+" I know "+student.getName()+" has joined Class "+student.getKlass().getNumber()+".";
System.out.println(s);
}
}
public void updateAssignLeader(Student student) {
if (isTeaching(student)) {
String s1 = "I am Tom. I know Jerry become Leader of Class 2.\n";
String s = "I am "+ getName() +"."+" I know "+student.getName()+" become Leader of Class "+student.getKlass().getNumber()+".";
System.out.println(s);
}
}
} |
package com.test.base;
import com.test.SolutionA;
import com.test.SolutionB;
import junit.framework.TestCase;
public class Example extends TestCase
{
private Solution solution;
@Override
protected void setUp()
throws Exception
{
super.setUp();
}
public void testSolutionA()
{
solution = new SolutionA();
assertSolution();
}
public void testSolutionB()
{
solution = new SolutionB();
assertSolution();
}
private void assertSolution()
{
int[] numC = {-3, -4};
int resultC = solution.maxProduct(numC);
assertEquals(resultC, 12);
System.out.println("resultC = " + resultC);
int[] numA = {2, 3, -2, 4};
int resultA = solution.maxProduct(numA);
assertEquals(resultA, 6);
System.out.println("resultA = " + resultA);
int[] numB = {-2, 0, -1};
int resultB = solution.maxProduct(numB);
assertEquals(resultB, 0);
System.out.println("resultB = " + resultB);
}
@Override
protected void tearDown()
throws Exception
{
super.tearDown();
}
}
|
package com.uchain;
import org.junit.Test;
public class LevelDBBlockChainTest {
@Test
public void testReadSetting(){
}
}
|
package by.herzhot.managers;
import by.herzhot.constants.Configs;
import java.util.ResourceBundle;
/**
* @author Herzhot
* @version 1.0
* 08.05.2016
*/
public enum PathManager {
INSTANCE;
private final ResourceBundle bundle = ResourceBundle.getBundle(Configs.PATH_SOURCE);
public String getProperty(String key) {
return bundle.getString(key);
}
}
|
package yinq.Request;
import java.lang.reflect.InvocationTargetException;
/**
* Created by YinQ on 2018/11/29.
*/
public interface HttpRequestObservice {
public void onRequestSuccess(Object result);
public void onRequestFail(int errCode, String errMsg);
public void onRequestComplete(int errCode) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException;
}
|
package Instruments;
import Interfaces.IPlay;
import Interfaces.IStockChange;
import Inventory.InventoryType;
import java.util.Collections;
public abstract class Instrument implements IPlay, IStockChange {
private String manufacturer;
private int costPrice;
private int shopPrice;
private InstrumentType type;
public Instrument(InstrumentType type, String manufacturer, int costPrice) {
this.manufacturer = manufacturer;
this.costPrice = costPrice;
this.type = type;
}
public boolean isOfType(InstrumentType it){
return this.type == it;
}
public boolean isOfType(InventoryType it){
return false;
}
public String getManufacturer() {
return manufacturer;
}
public int getCostPrice() {
return costPrice;
}
public int getShopPrice() {
return shopPrice;
}
public InstrumentType getType() {
return type;
}
public int calculateMarkup() {
System.out.println("Instrument Abstract Class");
return getCostPrice() * 2 - getCostPrice();
}
//IStockChange promises
public void addStock(IStockChange Instrument) {
}
public void removeStock() {
}
}
|
package com.techboon.domain.enumeration;
/**
* The Country enumeration.
*/
public enum Country {
CHINA, SWEDEN, DUBAI, MALAYSIA, INDONESIA
}
|
/*
* 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 wifidiagtree;
/**
*
* @author Shanell Spann
* Course: IT-DEV 140 Programming with JAVA
* Assignment 3
* Date: 10/10/2020
* Description: Create a program that helps a person fix a bad WiFi connection.
* Purpose: Practice decision structures using if else statements.
*/
public class WifiDiagTree {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
wifiCheck w = new wifiCheck();
w.fixMyWifi();
}
}
|
package dwz.cache.memcache;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import dwz.cache.memcache.client.ErrorHandler;
import dwz.cache.memcache.client.MemcachedClient;
/**
* <strong>DefaultErrorHandlerImpl</strong><br>
* 默认Memecached ErrorHandler 实现<br>
* <strong>Create on : 2011-12-12<br></strong>
* <p>
* <strong>Copyright (C) Ecointel Software Co.,Ltd.<br></strong>
* <p>
*
* @author peng.shi peng.shi@ecointel.com.cn<br>
* @version <strong>Ecointel v1.0.0</strong><br>
*/
public class DefaultErrorHandlerImpl implements ErrorHandler {
private static final Log Logger = LogFactory.getLog(DefaultErrorHandlerImpl.class);
@Override
public void handleErrorOnInit(MemcachedClient client, Throwable error) {
Logger.error("ErrorOnInit", error);
}
@Override
public void handleErrorOnGet(MemcachedClient client, Throwable error, String cacheKey) {
Logger.error(new StringBuilder("ErrorOnGet, cacheKey: ").append(cacheKey).toString(), error);
}
@Override
public void handleErrorOnGet(MemcachedClient client, Throwable error, String[] cacheKeys) {
Logger.error(new StringBuilder("ErrorOnGet, cacheKey: ").append(cacheKeys).toString(), error);
}
@Override
public void handleErrorOnSet(MemcachedClient client, Throwable error, String cacheKey) {
Logger.error(new StringBuilder("ErrorOnSet, cacheKey: ").append(cacheKey).toString(), error);
}
@Override
public void handleErrorOnDelete(MemcachedClient client, Throwable error, String cacheKey) {
Logger.error(new StringBuilder("ErrorOnDelete, cacheKey: ").append(cacheKey).toString(), error);
}
@Override
public void handleErrorOnFlush(MemcachedClient client, Throwable error) {
Logger.error("ErrorOnFlush", error);
}
@Override
public void handleErrorOnStats(MemcachedClient client, Throwable error) {
Logger.error("ErrorOnStats", error);
}
}
|
package com.example.licio.moringaeats.ui;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.licio.moringaeats.Constants;
import com.example.licio.moringaeats.R;
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 com.miguelcatalan.materialsearchview.MaterialSearchView;
import butterknife.BindView;
import butterknife.ButterKnife;
public class Welcome extends AppCompatActivity implements View.OnClickListener {
@BindView(R.id.welcome) TextView mWelcome;
@BindView(R.id.desc) TextView mDescription;
@BindView(R.id.btnLearn) Button mBtnLearn;
//@BindView(R.id.btnView) Button mBtnView;
// @BindView(R.id.edtName) EditText mEdtName;
@BindView(R.id.btnEnter) Button mBtnEnter;
public static final String TAG = MainActivity.class.getSimpleName();
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference mSearchedIngredientReference;
private ValueEventListener mSearchedIngredientReferenceListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
ButterKnife.bind(this);
Typeface caviarFont = Typeface.createFromAsset(getAssets(), "fonts/CaviarDreams.ttf");
mWelcome.setTypeface(caviarFont);
mDescription.setTypeface(caviarFont);
mBtnLearn.setOnClickListener(this);
//mBtnView.setOnClickListener(this);
mBtnEnter.setOnClickListener(this);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
getSupportActionBar().setTitle("Welcome, " + user.getDisplayName() + "!");
} else {
}
}
};
mSearchedIngredientReference = FirebaseDatabase
.getInstance()
.getReference()
.child(Constants.FIREBASE_CHILD_RECIPES);
mSearchedIngredientReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ingredientsSnapshot : dataSnapshot.getChildren()) {
String ingredients = ingredientsSnapshot.getValue().toString();
Log.d("Ingredients updated", "ingredients: " + ingredients);
}
}
@Override
public void onCancelled(DatabaseError databaseError) { //update UI here if error occurred.
}
});
}
@Override
public void onClick(View v) {
// Intent intent = new Intent(Welcome.this,Home.class);
// startActivity(intent);
if(v == mBtnLearn) {
Intent intent2 = new Intent(Welcome.this, ViewRecipes.class);
startActivity(intent2);
}
if(v == mBtnEnter) {
Intent intent3 = new Intent(Welcome.this, Home.class);
// String ingredients = mEdtName.getText().toString();
// intent3.putExtra("ingredients", ingredients);
startActivity(intent3);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
logout();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
// @Override
// protected void onDestroy() {
// super.onDestroy();
// mSearchedIngredientReference.removeEventListener(mSearchedIngredientReferenceListener);
// }
}
|
package br.com.candleanalyser.simulation;
import java.text.NumberFormat;
import br.com.candleanalyser.advisors.BuyAdvisor;
import br.com.candleanalyser.advisors.SellAdvisor;
import br.com.candleanalyser.engine.Candle;
import br.com.candleanalyser.engine.StockPeriod;
public class Simulator {
/**
* Simulate operation using specific parameters
* @param fixedCostPerOperation Cost per buy/sell
* @param initialMoney
* @param stockPeriod
* @param buyAdvisor
* @param sellAdvisor
* @param buyThreshold Value between 0 and 1 for sensibility on buying (0-buy with minimum indication, 1-buy with maximum indication)
* @param sellThreshold Value between 0 and 1 for sensibility on buying (0-sell with minimum indication, 1-sell with maximum indication)
* @param listener
* @return
*/
public static PeriodResult operateUsingAdvisor(double fixedCostPerOperation, double initialMoney, StockPeriod stockPeriod, BuyAdvisor buyAdvisor, SellAdvisor sellAdvisor, float buyThreshold, float sellThreshold, SimulatorListener listener) {
double operationCost = fixedCostPerOperation * 2;
Operation currentOperation = null;
PeriodResult result = new PeriodResult(initialMoney);
result.setStockPeriod(stockPeriod);
boolean inside = false;
double currentMoney = initialMoney;
for (Candle candle : stockPeriod.getCandles()) {
buyAdvisor.nextCandle(candle);
if(buyAdvisor!=sellAdvisor) {
sellAdvisor.nextCandle(candle);
}
if (inside) {
if (sellAdvisor.getSellStrength()>=sellThreshold) {
currentOperation.registerSell(candle, fixedCostPerOperation, sellAdvisor.getCurrentInfo());
sellAdvisor.onSell((float)candle.getClose());
if(buyAdvisor!=sellAdvisor) {
buyAdvisor.onSell((float)candle.getClose());
}
if(listener!=null) {
listener.onSell(currentOperation);
}
currentMoney += currentOperation.getYieldMoney();
inside = false;
}
} else {
if (buyAdvisor.getBuyStrength()>=buyThreshold) {
if (currentMoney < (candle.getClose() + operationCost)) {
break;
}
long qtty = (long) Math.floor((currentMoney - operationCost) / candle.getClose());
currentOperation = new Operation(qtty, candle, fixedCostPerOperation, buyAdvisor.getCurrentInfo());
result.addOperation(currentOperation);
buyAdvisor.onBuy((float)candle.getClose());
if(buyAdvisor!=sellAdvisor) {
sellAdvisor.onBuy((float)candle.getClose());
}
if(listener!=null) {
listener.onBuy(currentOperation);
}
inside = true;
}
}
}
if (inside && currentOperation != null) {
result.setFinalMoney((currentMoney - currentOperation.getBuyDebit()) + (currentOperation.getQtty() * stockPeriod.getLastPrice()) - operationCost);
} else {
result.setFinalMoney(currentMoney);
}
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
return result;
}
} |
package machine_learning;
import java.util.List;
public class LogisticRegression extends LinearRegressionModel<Integer> {
/**
* @Description: This class assumes x0 = 1.0.
* @param data_set
* @param isBGD
*/
public LogisticRegression(List<DataEntry<double[], Double>> data_set, boolean isBGD) {
super(data_set, isBGD, new LinearSigmoid());
}
@Override
public Integer test(double[] data) {
double res = this.calculator.calc(data, theta);
return res<0.5?0:1;
}
@Override
public Integer[] batchTest(List<DataEntry<double[], Double>> data_set) {
int m = data_set.size();
Integer[] labels = new Integer[m];
for(int i=0;i<m;i++){
double res = this.calculator.calc(data_set.get(i).data_vec, theta);
labels[i] = res<0.5?0:1;
}
return labels;
}
@Override
protected void calcError(List<DataEntry<double[], Double>> data_set) {
int m = data_set.size();
int right = 0;
Integer[] pred_labels = batchTest(data_set);
double pred_var = 0.0;
for(int i=0;i<m;i++){
if(pred_labels[i].equals(data_set.get(i).label))
right ++;
pred_var += (double)Math.pow(pred_labels[i] - data_set.get(i).label, 2);
}
this.fitness = (double)right/(double)m;
this.error_sum = pred_var;
}
}
|
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class viewbooks extends HttpServlet
{
PreparedStatement ps,ps1;
Connection c;
public void init(ServletConfig config)
{
/*try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
c=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
}
catch(Exception e)
{
e.printStackTrace();
}*/
}
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
HttpSession session=req.getSession();
//String query="select rollno,sname,comm,DATETIME from ";
//query=query.concat(tabl);
try
{
//String category="DFMUSIC";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
c=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
//ps=c.prepareStatement(query);
//out.println(query);
ps=c.prepareStatement("select bid,bookname,author,edition,subject,available_till,rollno,sname from BOOKSAVAIL");
ps1=c.prepareStatement("select comm,rollno,sname from commentbpost where bid=?");
}
catch(Exception e)
{
e.printStackTrace();
}
//String date1,time1;
int id=0;
//out.println("<html><body>");
ps.executeUpdate();
ResultSet rs=ps.getResultSet();
out.println("<html> <head> <style> table { color:white; font-size:20px;} </style></head><body bgcolor=black>");
while(rs.next())
{
id=rs.getInt(1);
out.println(" <form action=\"/network/insertbcomm\"><table border=2 width=100%>");
out.println("<input type=hidden name=val value="+id+">");
out.println("<tr><td>Book:");
out.print(rs.getString(2));
out.println("</td><td>Author:");
out.println(rs.getString(3));
out.println("</td><td>Edition:");
out.println(rs.getInt(4));
out.println("</td><td>Subject:");
out.println(rs.getString(5));
out.println("</td><td>:Availability");
out.println(rs.getString(6));
out.println("</td><td>Rollno:");
out.println(rs.getString(7));
out.println("</td><td>Name:");
out.println(rs.getString(8));
out.println("</td></tr></table>");
ps1.setInt(1,id);
ps1.executeUpdate();
ResultSet rs1=ps1.getResultSet();
out.println("<table border=1><th>comment</th><th>name,roll</th>");
while(rs1.next())
{
out.println("<tr><td>");
out.println("<br> "+rs1.getString(1)+"<br></td><td>");
out.println(" "+rs1.getString(2)+","+rs1.getString(3));
out.println("</td></tr>");
}
out.println("</table>");
out.println("<br> <textarea name=comment rows=2 cols=10></textarea><br>");
out.println("<input type=submit value=Send></form>");
}
out.println("</body></html>");
c.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
|
package com.liyunkun.qiubaipage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by liyunkun on 2016/9/3 0003.
*/
public class HttpUtils {
public static byte[] getJSONArray(String urlPath){
HttpURLConnection conn=null;
InputStream is=null;
ByteArrayOutputStream baos=null;
try {
URL url=new URL(urlPath);
conn= (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5*1000);
conn.connect();
if(conn.getResponseCode()==200){
is=conn.getInputStream();
baos=new ByteArrayOutputStream();
int len;
byte[] bytes=new byte[1024];
while(true){
len=is.read(bytes);
if(len!=-1){
baos.write(bytes,0,len);
baos.flush();
}else{
break;
}
}
return baos.toByteArray();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(conn!=null){
conn.disconnect();
}
try {
if(baos!=null){
baos.close();
}
if(is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String getJSONString(String urlPath){
HttpURLConnection conn=null;
InputStream is=null;
StringBuilder stringBuilder=new StringBuilder();
try {
URL url=new URL(urlPath);
conn= (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5*1000);
conn.connect();
if(conn.getResponseCode()==200){
is=conn.getInputStream();
int len;
byte[] bytes=new byte[1024];
while(true){
len=is.read(bytes);
if(len!=-1){
stringBuilder.append(new String(bytes,0,len));
}else{
break;
}
}
return stringBuilder.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(conn!=null){
conn.disconnect();
}
try {
if(is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
|
package collections.text;
import collections.text.api.ITextSpliterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegTextSpliterator implements ITextSpliterator {
@Override
public String[] split(String text) {
Pattern p = Pattern.compile("[А-аЯ-я0-9]+");
Matcher m = p.matcher(text);
int i = 0;
String[] strings = new String[text.length()];
if (m.find()){
String s = text.substring(m.start(), m.end());
i++;
strings[i] = s;
}
return strings;
}
}
|
package com.dq.police.controller.actions.Related;
import com.dq.police.controller.Action;
import com.dq.police.helpers.ConstraintsUtil;
import com.dq.police.model.PersistenceManager;
import com.dq.police.model.entities.CrimePast;
import com.dq.police.model.entities.Related;
import com.dq.police.view.View;
import lombok.AllArgsConstructor;
import java.util.List;
@AllArgsConstructor
public class FindAllRelatedsAction extends Action {
private PersistenceManager persistence;
private View view;
@Override
public String execute() {
List<String> results = persistence.findAllAsJson(Related.class);
view.showGroup("Relateds", results);
return ConstraintsUtil.OPERATION_SUCCESS_MESSAGE;
}
@Override
public String getName() {
return "All Relateds";
}
}
|
package com.hyper.components.cr;
import org.jzy3d.colors.Color;
import org.jzy3d.colors.ColorMapper;
import org.jzy3d.maths.Coord3d;
public class GraphFunctionColor {
private Color plainColor;
private ColorMode colorMode;
public GraphFunctionColor(Color color) {
if(color.a == 0) colorMode = ColorMode.RAINBOW;
else colorMode = ColorMode.PLAIN;
this.plainColor = color;
}
public ColorMode getColorMode() {
return this.colorMode;
}
public Color getPlainColor() {
return this.plainColor;
}
public ColorMapper generateColorMapper() {
switch(colorMode) {
case PLAIN:
return new PlainMapper(plainColor);
case RAINBOW:
return new RainbowMapper();
default:
return null;
}
}
public static class PlainMapper extends ColorMapper {
private Color color;
public PlainMapper(Color c) {
this.color = c;
}
@Override
public Color getColor(Coord3d coord) {
return color;
}
}
public static class RainbowMapper extends ColorMapper {
@Override
public Color getColor(Coord3d coord) {
java.awt.Color color = new java.awt.Color(java.awt.Color.HSBtoRGB((float) (Math.atan2(coord.y, coord.x)*0.5/Math.PI), 1, 1));
return new Color(color.getRed(), color.getGreen(), color.getBlue());
}
}
public static enum ColorMode {
PLAIN,
RAINBOW;
}
}
|
package com.junzhao.base.widget;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import com.junzhao.base.base.MLApplication;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import java.util.ArrayList;
import java.util.List;
public class ReferralGalleryAdapter extends BaseAdapter {
private Context context;
private ArrayList<MyImageView> imageViews = new ArrayList<MyImageView>();
private ImageCacheManager imageCache;
private List<String> mItems;
private int _position;
//private MLLoadingDialog _dialog;
public void setData(List<String> data, int position) {
_position = position;
this.mItems = data;
notifyDataSetChanged();
}
protected BitmapUtils bitmapUtils;
protected BitmapDisplayConfig bigPicDisplayConfig;
public ReferralGalleryAdapter(Context context) {
this.context = context;
imageCache = ImageCacheManager.getInstance(context);
/* _dialog = new MLLoadingDialog(context);
_dialog.setCanceledOnTouchOutside(false);*/
}
@Override
public int getCount() {
return mItems != null ? mItems.size() : 0;
}
@Override
public Object getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MyImageView view = new MyImageView(context);
view.setLayoutParams(new Gallery.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
String item = mItems.get(position);
view.setTag(item);
if (!MLApplication.IMAGE_CACHE.get(item, view)) {
//view.setImageResource(R.drawable.default_message_header);
}
if (!this.imageViews.contains(view)) {
imageViews.add(view);
}
return view;
}
}
|
package com.example.animaciones.automaticas;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.animaciones.R;
public class Automaticas extends AppCompatActivity {
Button btnSet;
TextView txtSet;
Boolean isVisitble= true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_automaticas);
btnSet = findViewById(R.id.button);
txtSet = findViewById(R.id.textView);
btnSet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isVisitble){
txtSet.setVisibility(View.GONE);
}else{
txtSet.setVisibility(View.VISIBLE);
}
isVisitble =!isVisitble;
}
});
}
} |
package ru.spbau.bocharov.Trie;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Created by fyodor on 2/17/16.
*/
public class TrieImplTest {
@Test
public void testAdd() throws Exception {
Trie trie = new TrieImpl();
assertTrue(trie.add("Hello"));
assertTrue(trie.add("World"));
assertEquals(2, trie.size());
assertTrue(trie.contains("Hello"));
assertTrue(trie.contains("World"));
assertFalse(trie.contains("H"));
assertFalse(trie.contains("Wor"));
assertFalse(trie.contains(""));
assertFalse(trie.contains("HelloWorld"));
trie.add("Hi");
assertEquals(3, trie.size());
assertEquals(2, trie.howManyStartsWithPrefix("H"));
assertEquals(1, trie.howManyStartsWithPrefix("W"));
assertFalse(trie.contains("H"));
assertFalse(trie.contains("He"));
assertTrue(trie.add(""));
assertFalse(trie.add(""));
assertEquals(4, trie.size());
assertEquals(4, trie.howManyStartsWithPrefix(""));
assertTrue(trie.contains(""));
Trie trie2 = new TrieImpl();
trie2.add("AAB");
trie2.add("AAB");
trie2.add("AAB");
assertEquals(1, trie2.size());
trie2.add("AAC");
assertEquals(2, trie2.size());
trie2.add("AAD");
assertEquals(3, trie2.size());
trie2.add("AA");
assertEquals(4, trie2.size());
trie2.add("A");
assertEquals(5, trie2.size());
trie2.add("BBC");
assertEquals(6, trie2.size());
trie2.add("BBD");
assertEquals(7, trie2.size());
trie2.add("BBE");
assertEquals(8, trie2.size());
trie2.add("B");
assertEquals(9, trie2.size());
assertTrue(trie2.contains("AAD"));
assertTrue(trie2.contains("BBC"));
assertTrue(trie2.contains("BBD"));
assertTrue(trie2.contains("BBE"));
assertEquals(3, trie2.howManyStartsWithPrefix("BB"));
String str1 = "cat";
String str2 = "dog";
assertTrue(trie.add(str1));
assertTrue(trie.add(str2));
assertFalse(trie.add(str1));
assertFalse(trie.add(str2));
assertTrue(trie.add("ca"));
assertTrue(trie.add("c"));
}
@Test
public void testContains() throws Exception {
Trie trie = new TrieImpl();
trie.add("Hello");
trie.add("World");
trie.add("Hello world!");
trie.add("Fizz");
trie.add("Buzz");
trie.add("FizzBuzz");
trie.add("C++ > Java");
assertTrue(trie.contains("Buzz"));
assertTrue(trie.contains("Fizz"));
assertTrue(trie.contains("Hello"));
assertTrue(trie.contains("World"));
assertTrue(trie.contains("FizzBuzz"));
trie.remove("Hello world!");
assertFalse(trie.contains("Hello world!"));
assertTrue(trie.contains("Hello"));
trie.remove("Fizz");
assertTrue(trie.contains("FizzBuzz"));
assertFalse(trie.contains("Fizz"));
trie.add("Very");
trie.add("VeryVery");
trie.add("VeryVeryLong");
trie.add("VeryVeryLongWord");
assertTrue(trie.contains("Very"));
assertTrue(trie.contains("VeryVery"));
assertTrue(trie.contains("VeryVeryLong"));
assertTrue(trie.contains("VeryVeryLongWord"));
assertFalse(trie.contains("AnyWord"));
assertFalse(trie.contains("Word"));
assertFalse(trie.contains("Ve"));
assertFalse(trie.contains("VeryV"));
assertFalse(trie.contains("VeryVeryLongWord1"));
assertFalse(trie.contains("VeryVeryLongWor"));
trie.remove("Very");
assertFalse(trie.contains("Very"));
assertTrue(trie.contains("VeryVery"));
trie.remove("VeryVery");
assertFalse(trie.contains("VeryVery"));
assertTrue(trie.contains("VeryVeryLong"));
trie.add("VeryVeryLongWord1");
trie.remove("VeryVeryLongWord");
assertTrue(trie.contains("VeryVeryLongWord1"));
trie.add("test");
assertTrue(trie.contains("test"));
trie.add("testt");
assertTrue(trie.contains("test"));
assertTrue(trie.contains("testt"));
assertTrue(trie.add(""));
assertTrue(trie.contains(""));
trie.add("element");
assertTrue(trie.contains("element"));
assertFalse(trie.contains("elem"));
assertFalse(trie.contains("ent"));
assertFalse(trie.contains("tes"));
}
@Test
public void testRemove() throws Exception {
Trie trie = new TrieImpl();
trie.add("Hello");
trie.add("World");
assertTrue(trie.remove("Hello"));
assertEquals(1, trie.size());
trie.add("");
trie.add("HI");
trie.add("Hi");
assertEquals(4, trie.howManyStartsWithPrefix(""));
assertEquals(4, trie.size());
assertEquals(2, trie.howManyStartsWithPrefix("H"));
assertTrue(trie.remove(""));
assertFalse(trie.remove(""));
assertFalse(trie.remove("Hello"));
assertTrue(trie.remove("HI"));
assertEquals(1, trie.howManyStartsWithPrefix("H"));
trie.add("String");
trie.add("Word");
assertFalse(trie.remove("YetWord"));
assertTrue(trie.remove("Word"));
trie.add("Word");
trie.add("word");
assertTrue(trie.remove("word"));
Trie set = new TrieImpl();
String s = "s";
String ss = "ss";
String sa = "sa";
assertTrue(set.add(s));
assertTrue(set.add(ss));
assertTrue(set.add(sa));
assertEquals(3, set.size());
assertTrue(set.remove(s));
assertFalse(set.remove(s));
assertEquals(2, set.howManyStartsWithPrefix("s"));
Trie set2 = new TrieImpl();
assertFalse(set2.remove(""));
assertEquals(0, set2.size());
set2.add("test");
set2.add("element");
set2.add("AU");
assertEquals(3, set2.size());
assertTrue(set2.remove("element"));
assertEquals(2, set2.size());
assertTrue(set2.remove("test"));
assertEquals(1, set2.size());
assertFalse(set2.remove("te"));
assertFalse(set2.remove("A"));
assertTrue(set2.remove("AU"));
assertEquals(0, set2.size());
set2.add("a");
set2.add("aa");
set2.add("aaa");
assertEquals(3, set2.size());
assertTrue(set2.remove("aa"));
assertTrue(set2.contains("a"));
assertTrue(set2.contains("aaa"));
assertEquals(2, set2.size());
set2.add("");
assertEquals(3, set2.size());
assertTrue(set2.remove(""));
assertEquals(2, set2.size());
assertTrue(set2.remove("a"));
assertTrue(set2.remove("aaa"));
assertEquals(0, set2.size());
}
@Test
public void testSize() throws Exception {
Trie trie = new TrieImpl();
assertEquals(trie.size(), 0);
trie.add("String");
assertEquals(trie.size(), 1);
trie.add("String2");
assertEquals(trie.size(), 2);
trie.add("Word");
assertEquals(trie.size(), 3);
trie.remove("str");
assertEquals(trie.size(), 3);
trie.remove("String");
assertEquals(trie.size(), 2);
trie.remove("String2");
assertEquals(trie.size(), 1);
trie.remove("Word");
assertEquals(trie.size(), 0);
trie.remove("Word");
assertEquals(trie.size(), 0);
trie.remove("Word");
assertEquals(trie.size(), 0);
assertEquals(0, trie.size());
trie.add("a");
trie.add("aa");
trie.add("aaa");
assertEquals(3, trie.size());
trie.remove("a");
assertEquals(2, trie.size());
trie.remove("aa");
assertEquals(1, trie.size());
trie.remove("aaa");
assertEquals(0, trie.size());
}
@Test
public void testHowManyStartsWithPrefix() throws Exception {
Trie trie = new TrieImpl();
trie.add("Very");
trie.add("VeryVery");
trie.add("VeryVeryLong");
trie.add("VeryVeryLongWord");
assertEquals(trie.howManyStartsWithPrefix("V"), 4);
assertEquals(trie.howManyStartsWithPrefix("Very"), 4);
assertEquals(trie.howManyStartsWithPrefix("VE"), 0);
assertEquals(trie.howManyStartsWithPrefix("VeryV"), 3);
assertEquals(trie.howManyStartsWithPrefix("VeryVery"), 3);
assertEquals(trie.howManyStartsWithPrefix("VeryVeryV"), 0);
assertEquals(trie.howManyStartsWithPrefix("VeryVeryL"), 2);
assertEquals(trie.howManyStartsWithPrefix("VeryVeryLongWord"), 1);
Trie set = new TrieImpl();
set.add("a");
set.add("aa");
set.add("aaa");
assertEquals(3, set.howManyStartsWithPrefix("a"));
assertEquals(2, set.howManyStartsWithPrefix("aa"));
assertEquals(1, set.howManyStartsWithPrefix("aaa"));
set.add("");
assertEquals(4, set.howManyStartsWithPrefix(""));
set.remove("aa");
assertEquals(3, set.howManyStartsWithPrefix(""));
set.add("ab");
assertEquals(3, set.howManyStartsWithPrefix("a"));
set.remove("ab");
set.remove("aaa");
set.remove("a");
assertEquals(0, set.howManyStartsWithPrefix("a"));
assertEquals(1, set.howManyStartsWithPrefix(""));
set.remove("");
assertEquals(0, set.howManyStartsWithPrefix(""));
}
@Test
public void testSimpleSerialization() throws IOException {
Trie trie = instance();
assertTrue(trie.add("abc"));
assertTrue(trie.add("cde"));
assertEquals(2, trie.size());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
((StreamSerializable) trie).serialize(outputStream);
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
Trie newTrie = instance();
((StreamSerializable) newTrie).deserialize(inputStream);
assertTrue(newTrie.contains("abc"));
assertTrue(newTrie.contains("cde"));
assertEquals(2, trie.size());
}
@Test(expected=IOException.class)
public void testSimpleSerializationFails() throws IOException {
Trie trie = instance();
assertTrue(trie.add("abc"));
assertTrue(trie.add("cde"));
OutputStream outputStream = new OutputStream() {
@Override
public void write(int b) throws IOException {
throw new IOException("Fail");
}
};
((StreamSerializable) trie).serialize(outputStream);
}
public static Trie instance() {
return new TrieImpl();
}
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kafka2jdbc;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.transformations.ShuffleMode;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.config.ExecutionConfigOptions;
import org.apache.flink.table.api.config.OptimizerConfigOptions;
import org.apache.flink.table.api.java.StreamTableEnvironment;
public class testNonExistedTable {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(4);
EnvironmentSettings envSettings = EnvironmentSettings.newInstance()
.useBlinkPlanner()
.inStreamingMode()
.build();
StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env, envSettings);
String csvSourceDDL = "create table csv(" +
" id INT," +
" note VARCHAR," +
" country VARCHAR," +
" record_time TIMESTAMP(3)," +
" doub_val DECIMAL(6, 2)," +
" date_val DATE," +
" time_val TIME" +
") with (" +
" 'connector.type' = 'filesystem',\n" +
" 'connector.path' = '/Users/bang/sourcecode/project/flink-sql-etl/data-generator/src/main/resources/test_nonexistedTable.csv',\n" +
" 'format.type' = 'csv'" +
")";
String mysqlSinkDDL = "CREATE TABLE nonExisted (\n" +
" c0 BOOLEAN," +
" c1 INTEGER," +
" c2 BIGINT," +
" c3 FLOAT," +
" c4 DOUBLE," +
" c5 DECIMAL(38, 18)," +
" c6 VARCHAR," +
" c7 DATE," +
" c8 TIME," +
" c9 TIMESTAMP(3)" +
") WITH (\n" +
" 'connector.type' = 'jdbc',\n" +
" 'connector.url' = 'jdbc:mysql://localhost:3306/test',\n" +
" 'connector.username' = 'root'," +
" 'connector.table' = 'nonExisted3',\n" +
" 'connector.driver' = 'com.mysql.jdbc.Driver',\n" +
" 'connector.write.auto-create-table' = 'true' " +
")";
String query = "insert into nonExisted " +
"select max(c0),c1,c2,c3,c4,max(c5),max(c6),max(c7),max(c8),max(c9) from " +
" (select true as c0, id as c1, cast(id as bigint) as c2,cast(doub_val as float)as c3,cast(doub_val as double) as c4," +
" doub_val as c5, country as c6, date_val as c7, time_val as c8, record_time as c9 from csv)" +
" a group by c1, c2, c3, c4";
// String query = "insert into nonExisted select true as c0, id as c1, cast(id as bigint) as c2,cast(doub_val as float)as c3,cast(doub_val as double) as c4," +
// " doub_val as c5, country as c6, date_val as c7, time_val as c8, record_time as c9 from csv";
tableEnvironment.sqlUpdate(csvSourceDDL);
tableEnvironment.sqlUpdate(mysqlSinkDDL);
tableEnvironment.sqlUpdate(query);
tableEnvironment.execute("csvTest");
}
}
|
package edu.mum.sonet.aop;
import edu.mum.sonet.models.Comment;
import edu.mum.sonet.models.Post;
import edu.mum.sonet.models.User;
import edu.mum.sonet.models.AdminNotification;
import edu.mum.sonet.services.*;
import edu.mum.sonet.models.enums.UserStatus;
import edu.mum.sonet.services.CommentService;
import edu.mum.sonet.services.PostService;
import edu.mum.sonet.services.UnhealthyContentFilterService;
import edu.mum.sonet.services.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
/**
* Created by Jonathan on 12/12/2019.
*/
@Aspect
@Component
public class UnhealthyContentFilterAspect {
private final UnhealthyContentFilterService unhealthyContentFilterService;
private final UserService userService;
private final EmailService emailService;
private AdminNotificationService adminNotificationService;
public UnhealthyContentFilterAspect(UnhealthyContentFilterService unhealthyContentFilterService, UserService userService
, EmailService emailService, AdminNotificationService adminNotificationService) {
this.unhealthyContentFilterService = unhealthyContentFilterService;
this.userService = userService;
this.emailService = emailService;
this.adminNotificationService = adminNotificationService;
}
@Around(value = "execution(* edu.mum.sonet.services.PostService.save(..)) || " +
"execution(* edu.mum.sonet.services.CommentService.save(..))")
public Object filter(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("===== start filter for unhealthy posts");
boolean isUnhealthy = false;
AdminNotification adminNotification = null;
String email = SecurityContextHolder.getContext().getAuthentication().getName();
User user = userService.findByEmail(email);
Object[] args = proceedingJoinPoint.getArgs();
if ( proceedingJoinPoint.getTarget() instanceof CommentService) {
Comment comment = (Comment) args[0];
if (unhealthyContentFilterService.hasUnhealthyContent(comment.getText())) {
comment.setIsHealthy(false);
isUnhealthy = true;
///> Change the argument
args[0] = comment;
adminNotification = new AdminNotification("Comment",comment.getText(),user);
adminNotificationService.notifyAdmin(adminNotification);
}
} else if (proceedingJoinPoint.getTarget() instanceof PostService) {
Post post = (Post) args[0];
System.out.println(">>> filter post text: "+post);
if (unhealthyContentFilterService.hasUnhealthyContent(post.getText())) {
post.setIsHealthy(false);
isUnhealthy = true;
///> Change the argument
args[0] = post;
adminNotification = new AdminNotification("Post",post.getText(),user);
System.out.println(">>> filter send to admin: "+post);
adminNotificationService.notifyAdmin(adminNotification);
}
}
///> Get Current User
if ( user == null ) {
throw new UsernameNotFoundException("Unable to find User in Principal");
}
///> Increment the number of unhealthy content the user has
user.setUnhealthyContentCount(user.getUnhealthyContentCount() + 1);
// TODO: Send Notification to admin
if (user.getUnhealthyContentCount() >= 20 ) {
// Disable user's account
user.setUserStatus(UserStatus.BLOCKED);
// TODO: Send email to user ***** DON'T FORGET TO RESET THE COUNT IF ADMIN ACCEPT'S USER'S CLAIM
emailService.sendEmail(user.getEmail(), "SoNet Account Blocked", "Your account was blocked for posting too many unhealthy content on our systems. Go to the website and file a claim.");
}
Object ret = proceedingJoinPoint.proceed(args);
// if (isUnhealthy) throw new UnhealthyContentDetectedException("Unhealthy Post Detected");
return ret;
}
}
|
package Vistas;
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.text.html.HTMLDocument.Iterator;
import Controlador.AreaAdministracion;
import Vistas.ListadoEmpleado;
public class PanelDeControl extends JFrame {
private JPanel pnlContenedor;
private JPanel pnlCentro;
private JLabel lblTitle;
public static void main(String[] args) {
new PanelDeControl();
}
public PanelDeControl() {
// Establecer el titulo de la ventana
this.setTitle("Panel de Control");
// Establecer la dimension de la ventana (ancho, alto)
this.setSize(640, 480);
// Establecer NO dimensionable la ventana
this.setResizable(false);
// Ubicar la ventana en el centro de la pantalla
this.setLocationRelativeTo(null);
// Cerrar la ventana al hacer click en boton de X (cerrar)
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
// Agregar el panel al JFrame
this.getContentPane().add(this.getPanelContenedor());
// Mostrar la ventana
this.setVisible(true);
}
private JPanel getPanelContenedor() {
// crear panel contenedor
pnlContenedor = new JPanel();
// crear panel del centro
pnlCentro = new JPanel();
// setear el layout manager del panel contenedor
pnlContenedor.setLayout(new BorderLayout());
// A�adir el menu al panel contenedor
pnlContenedor.add(getMenu(), BorderLayout.PAGE_START);
// A�adir el panel del centro al panel contenedor
pnlContenedor.add(getPanelCentro(), BorderLayout.CENTER);
return pnlContenedor;
}
private JPanel getPanelCentro() {
// setear el layout manager del panel del centro
pnlCentro.setLayout(new BorderLayout());
lblTitle = new JLabel("Administracion de Gimnasio");
lblTitle.setFont(new Font("Serif", Font.BOLD, 30));
lblTitle.setHorizontalAlignment(JLabel.CENTER);
pnlCentro.add(lblTitle, BorderLayout.PAGE_START);
pnlCentro.add(getImg(), BorderLayout.CENTER);
return pnlCentro;
}
private JMenuBar getMenu() {
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("Archivo");
JMenu abmMenu = new JMenu("ABM");
JMenu IngresoMenu = new JMenu("Ingreso");
JMenu notificacionesMenu = new JMenu("Notificaciones");
JMenu cronogramaMenu = new JMenu("Cronograma");
JMenu liquidacionMenu = new JMenu("Liquidacion");
menuBar.add(fileMenu);
menuBar.add(abmMenu);
menuBar.add(notificacionesMenu);
menuBar.add(cronogramaMenu);
menuBar.add(IngresoMenu);
menuBar.add(liquidacionMenu);
JMenuItem close = new JMenuItem("Cerrar");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}
});
JMenuItem listadoSocios = new JMenuItem("Socios");
listadoSocios.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new ListadoSocio();
}
});
JMenuItem listadoEmpleados = new JMenuItem("Empleados");
listadoEmpleados.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new ListadoEmpleado();
}
});
JMenuItem listadoDeportes = new JMenuItem("Deportes");
listadoDeportes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new ListadoDeporte();
}
});
JMenuItem listadoClases = new JMenuItem("Clases");
listadoClases.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new ListadoClase();
}
});
JMenuItem listadoAbono = new JMenuItem("Abono");
listadoAbono.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new ListadoAbono();
}
});
JMenuItem listadoFacturas = new JMenuItem("Facturas");
listadoFacturas.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Listado Facturas");
}
});
JMenuItem liquidacionDeSueldo = new JMenuItem("liquidacionDeSueldo");
liquidacionDeSueldo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Liquidador();
}
});
JMenuItem validarIngreso = new JMenuItem("Validar Ingreso");
validarIngreso.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Listado Validar Ingreso");
}
});
JMenuItem mailMasivoNovedades = new JMenuItem("Mail Masivo de Novedades");
mailMasivoNovedades.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
List<String> emails = AreaAdministracion.getInstancia().obtenerEmailSocios();
String URI = "mailto:";
String mailto = "";
List<String> to = new LinkedList<>();
for (String object : emails) {
to = emails;
mailto = String.join(";", to);
}
try {
Desktop.getDesktop().mail(new URI(URI + mailto));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
});
JMenuItem mailFiltro = new JMenuItem("Mail por Filtro");
mailFiltro.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Listado Mail por Filtro");
}
});
JMenuItem cronograma = new JMenuItem("Cronograma");
cronograma.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Cronograma();
}
});
fileMenu.add(close);
abmMenu.add(listadoSocios);
abmMenu.add(listadoEmpleados);
abmMenu.add(listadoDeportes);
abmMenu.add(listadoClases);
abmMenu.add(listadoAbono);
abmMenu.add(validarIngreso);
notificacionesMenu.add(mailMasivoNovedades);
notificacionesMenu.add(mailFiltro);
cronogramaMenu.add(cronograma);
IngresoMenu.add(validarIngreso);
liquidacionMenu.add(liquidacionDeSueldo);
return menuBar;
}
private JLabel getImg() {
JLabel picLabel = null;
try {
String pathImg = "img/gym.jpg";
BufferedImage img = ImageIO.read(new java.io.File(pathImg));
picLabel = new JLabel(new ImageIcon(img));
} catch (IOException e) {
e.printStackTrace();
}
return picLabel;
}
}
|
package cn.euphonium.codereviewsystemserver.utils;
import cn.euphonium.codereviewsystemserver.entity.*;
import com.alibaba.fastjson.JSON;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
public class SandboxUtils {
public static final String sandboxBaseUrl = "http://118.178.194.230:5050";
public static SandboxResponse runAndParse(String reqJSON) {
//post restful
String url = sandboxBaseUrl + "/run";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(reqJSON, headers);
String responseJSONStr = restTemplate.postForObject(url, request, String.class);
// System.out.println(responseJSONStr);
responseJSONStr = responseJSONStr.substring(1, responseJSONStr.length() - 1);
// System.out.println(responseJSONStr);
SandboxResponse sandboxResponse = JSON.parseObject(responseJSONStr, SandboxResponse.class);
return sandboxResponse;
}
public static String compileCodeInSandbox(String content) throws Exception {
Cmd cmd = new Cmd();
String[] args = {"/usr/bin/gcc", "a.c", "-o", "a", "-std=c99"};
cmd.setArgs(args);
Map<String, Map<String, String>> copyIn = cmd.getCopyIn();
Map<String, String> codeMap = new HashMap<>();
codeMap.put("content", content);
copyIn.put("a.c", codeMap);
String[] copyOutCached = new String[]{"a"};
cmd.setCopyOutCached(copyOutCached);
SandboxRequest req = new SandboxRequest();
Cmd[] cmds = new Cmd[1];
cmds[0] = cmd;
req.setCmd(cmds);
String reqJSON = JSON.toJSONString(req);
SandboxResponse sandboxResponse = runAndParse(reqJSON);
if (!sandboxResponse.getStatus().equals("Accepted")) {
throw new Exception("compile error");
}
return sandboxResponse.getFileIds().get("a");
}
public static void deleteFileByIdInSandbox(String fileId) {
String url = sandboxBaseUrl + "/file/" + fileId;
RestTemplate restTemplate = new RestTemplate();
restTemplate.delete(url);
// ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.DELETE,null,String.class);
// System.out.println(result);
}
public static OJResponse onlineJudgeOneSample(Sample sample, String fileId, OJResponse ojResponse) throws Exception {
Cmd cmd = new Cmd();
String[] args = {"a"};
cmd.setArgs(args);
Map<String, Object>[] files = cmd.getFiles();
files[0].put("content", sample.getInput());
Map<String, Map<String, String>> copyIn = cmd.getCopyIn();
Map<String, String> codeMap = new HashMap<>();
codeMap.put("fileId", fileId);
copyIn.put("a", codeMap);
SandboxRequest req = new SandboxRequest();
Cmd[] cmds = new Cmd[1];
cmds[0] = cmd;
req.setCmd(cmds);
String reqJSON = JSON.toJSONString(req);
SandboxResponse sandboxResponse = runAndParse(reqJSON);
String stderr = sandboxResponse.getFiles().get("stderr");
String stdout = sandboxResponse.getFiles().get("stdout");
if (!sandboxResponse.getStatus().equals("Accepted")) {
if (sandboxResponse.getStatus().equals("Non Zero Exit Status")) {
ojResponse.setStatus(stderr);
} else {
ojResponse.setStatus(sandboxResponse.getStatus());
}
} else if (!stderr.equals("")) {
ojResponse.setStatus("stderr[" + stderr + "]");
} else if (!stdout.equals(sample.getOutput())) {
ojResponse.setStatus("wrong output");
ojResponse.setInput(sample.getInput());
ojResponse.setRealOutput(stdout);
ojResponse.setExpectedOutput(sample.getOutput());
} else {
ojResponse.setMemory(ojResponse.getMemory() + sandboxResponse.getMemory());
ojResponse.setRunTime(ojResponse.getRunTime() + sandboxResponse.getRunTime());
}
return ojResponse;
}
}
|
package com.yusys.warrantManager;
import java.util.List;
import java.util.Map;
public interface WarrantOutDao {
//查询待出库信息
List<Map<String, String>> queryListWarrantOut(Map<String, String> pmap);
//更新库存表
public void updateWarrantOut(Map<String, String> pmap);
//新增一条记录
public void saveWarrantOutRecord(Map<String, String> pmap);
//更新中间表标识
public void updateWarrantFlag(Map<String, String> pmap);
//查询流水号
List<Map<String, String>> queryListSerno(Map<String, String> pmap);
//打回
public void beatWarrantOut(Map<String, String> pmap);
}
|
package com.zheng.highconcurrent.atomic;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/**
* @Author zhenglian
* @Date 2019/1/18
*/
public class AtomicIntegerFieldUpdaterApp {
private static class Animal {
protected String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
private static class Human extends Animal {
private volatile int studyLevel;
private AtomicIntegerFieldUpdater<Human> updater = AtomicIntegerFieldUpdater.newUpdater(Human.class, "studyLevel");
public int getStudyLevel() {
return studyLevel;
}
public void setStudyLevel(int studyLevel) {
this.studyLevel = studyLevel;
}
public AtomicIntegerFieldUpdater<Human> getUpdater() {
return updater;
}
public void setUpdater(AtomicIntegerFieldUpdater<Human> updater) {
this.updater = updater;
}
public void printField(String name) {
try {
System.out.println(this.getClass().getField(name));
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
@Test
public void instance() {
Human human = new Human();
// 判断human对象是否是Animal类的实例
System.out.println(Animal.class.isInstance(human));
// Animal是否是Human的父类或者父接口
System.out.println(Animal.class.isAssignableFrom(Human.class));
}
@Test
public void declareField() throws Exception {
Human human = new Human();
human.printField("name"); // 父级字段必须是public
System.out.println(human.getClass().getDeclaredField("studyLevel"));
System.out.println(human.getClass().getField("name"));
System.out.println(human.getClass().getDeclaredField("name"));
}
@Test
public void get() {
Human human = new Human();
int studyLevel = human.getUpdater().get(human);
System.out.println(studyLevel);
}
}
|
package Problem_15353;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
// 언어 제한 : C / C++
// Java로 문제만 풀었음, 채점하지 않음.
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String buf = br.readLine();
StringBuilder a = new StringBuilder(buf.split(" ")[0]);
StringBuilder b = new StringBuilder(buf.split(" ")[1]);
a.reverse();
b.reverse();
String a_ = a.toString();
String b_ = b.toString();
StringBuilder c = new StringBuilder();
boolean isTen = false;
int length = a_.length() > b_.length() ? a_.length() : b_.length();
for(int i = 0; i<length; i++) {
int a__ = 0;
int b__ = 0;
if(i < a_.length()) a__ = a_.charAt(i) - '0';
if(i < b_.length()) b__ = b_.charAt(i) - '0';
int c__ = a__ + b__;
if(isTen) {
c__ += 1;
isTen = false;
}
if(c__/10 == 1) isTen = true;
c__%=10;
c.append(c__);
}
if(isTen) c.append(1);
System.out.println(c.reverse());
}
}
|
package com.test.automation.PageObjectModel;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.MalformedURLException;
import java.util.Properties;
import java.net.URL;
import java.util.concurrent.TimeUnit;
public class DriverInitializer {
private static Properties properties = null;
private WebDriver driver = null;
private String browser = null;
private String baseUrl = null;
private String os = null;
private String node = null;
static {
try {
properties = new Properties();
properties.load(DriverInitializer.class.getClassLoader()
.getResourceAsStream("application.properties"));
System.setProperty("webdriver.chrome.driver", properties.getProperty("chrome.path"));
System.setProperty("webdriver.gecko.driver", properties.getProperty("gecko.path"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static WebDriver getDriver(String browser) {
WebDriver driver = null;
switch (getProperty("browser")) {
case "chrome":
driver = new ChromeDriver();
break;
case "firefox":
driver = new FirefoxDriver();
break;
default:
driver = new ChromeDriver();
}
return driver;
}
public DriverInitializer(String os, String browser, String baseUrl, String node) throws MalformedURLException {
this.browser = browser;
this.os = os;
this.baseUrl = baseUrl;
this.node = node;
Platform platform = Platform.fromString(os.toUpperCase());
if(browser.equalsIgnoreCase("chrome")) {
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setCapability("platform", platform);
this.driver = new RemoteWebDriver(new URL(node + "/wd/hub"), chromeOptions);
} else if (browser.equalsIgnoreCase("firefox")) {
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setCapability("platform", platform);
this.driver = new RemoteWebDriver(new URL(node + "/wd/hub"), firefoxOptions);
} else {
InternetExplorerOptions ieOption = new InternetExplorerOptions();
ieOption.setCapability("platform", platform);
this.driver = new RemoteWebDriver(new URL(node + "/wd/hub"), ieOption);
}
this.driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
this.driver.manage().window().maximize();
this.driver.get(baseUrl);
}
public static String getProperty(String key) {
return properties == null ? null : properties.getProperty(key, "");
}
public String getOs() {
return this.os;
}
public String getBrowser() {
return this.browser;
}
public String getBaseUrl() {
return this.baseUrl;
}
public String getNode() {
return this.node;
}
public WebDriver getDriver() {
return this.driver;
}
}
|
package Exam_2019_07_27_28_Kiko;
import java.util.Scanner;
public class Pro_02_Summer_Shoping {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Въведете сума на бюджета: ");
double budget = Double.parseDouble(scanner.nextLine());
System.out.print("Въведете цена на плажната кърпа: ");
double towelPrice = Double.parseDouble(scanner.nextLine());
System.out.print("Въведете цяло число за процента отстъпка: ");
int percentDiscount = Integer.parseInt(scanner.nextLine());
double umbrellaPrice = towelPrice * 2 / 3;
double sandalsPrice = umbrellaPrice * 0.75;
double bagPrice = (towelPrice + sandalsPrice) / 3;
double sumPurchases = towelPrice + umbrellaPrice +
sandalsPrice + bagPrice;
double discountSum = sumPurchases * (100 - percentDiscount) /100;
double diff = Math.abs(budget - discountSum);
if (budget >= discountSum) {
System.out.printf("Annie's sum is %.2f lv. She has %.2f lv. left.", discountSum, diff);
} else {
System.out.printf("Annie's sum is %.2f lv. She needs %.2f lv. more.", discountSum, diff);
}
}
}
|
package com.shanshu.ai;
/*
* Copyright (c) 2018, Cardinal Operations and/or its affiliates. All rights reserved.
* CARDINAL OPERATIONS PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author Frank Huang (runping@shanshu.ai)
* @date 2018/06/14
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
} |
package com.taotao.testActiveMq;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import javax.jms.*;
import javax.print.attribute.standard.Destination;
public class TestActiveMq2 {
@Test
public void testQueueProducer() {
//1.读取配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-activemq.xml");
//2.从容器中获得JMSTemplate对象
JmsTemplate jmsTemplate = applicationContext.getBean(JmsTemplate.class);
//3.从容器中获得一个Destination对象
Queue queue = (Queue)applicationContext.getBean("queueDestination");
//4.使用JMSTemplate对象发送消息,需要知道Destination
jmsTemplate.send(queue,new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
TextMessage textMessage = session.createTextMessage("spring activemq test");
return textMessage;
}
});
}
}
|
package de.codecentric.cvgenerator;
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeLanguageRepository extends JpaRepository<EmployeeLanguage, Integer>{
}
|
package com.example;
import java.util.StringJoiner;
/**
* Fizz buzz programming exercise.
*/
public class App {
/**
* Application entry point.
*
* @param args the command line arguments, two integers expected
*/
public static void main(String[] args) {
int start = Integer.parseInt(args[0]);
int end = Integer.parseInt(args[1]);
App app = new App();
String string = app.getStringForRange(start, end);
System.out.println(string);
}
/**
* Get fizzbuzz words for range of integers.
*
* @param start the integer to start the range (inclusive)
* @param end the integer to end the range (inclusive)
* @return the string of fizzbuzz words for the range
*/
public String getStringForRange(int start, int end) {
StringJoiner sj = new StringJoiner(" ");
for (int i = start; i <= end; ++i) {
sj.add(getStringForNumber(i));
}
return sj.toString();
}
/**
* Get fizzbuzz word for single integer.
*
* @param number the integer to convert
* @return the fizzbuzz word for the integer
*/
public String getStringForNumber(int number) {
if (number == 0) {
return "0";
} else if (number % 15 == 0) {
return "fizzbuzz";
} else if (number % 5 == 0) {
return "buzz";
} else if (number % 3 == 0) {
return "fizz";
}
return Integer.toString(number);
}
}
|
package com.cheese.radio.inject.module;
import android.app.Activity;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import com.cheese.radio.inject.qualifier.context.ActivityContext;
import com.cheese.radio.inject.qualifier.manager.ActivityFragmentManager;
import com.cheese.radio.inject.scope.ActivityScope;
import dagger.Module;
import dagger.Provides;
/**
* project:cutv_ningbo
* description:
* create developer: admin
* create time:15:17
* modify developer: admin
* modify time:15:17
* modify remark:
*
* @version 2.0
*/
@Module
public class ActivityModule {
private final Activity activity;
public ActivityModule(Activity activity) {
this.activity = activity;
}
@ActivityContext
@Provides
@ActivityScope
Context provideActivityContext() {
return activity;
}
@Provides
@ActivityScope
@ActivityFragmentManager
FragmentManager provideFragmentManager() {
if (activity instanceof FragmentActivity)
return ((FragmentActivity) activity).getSupportFragmentManager();
return null;
}
@Provides
@ActivityScope
DisplayMetrics provideDisplayMetrics() {
return activity.getResources().getDisplayMetrics();
}
@Provides
@ActivityScope
LayoutInflater provideLayoutInflater() {
return LayoutInflater.from(activity);
}
}
|
package projecteulerproblems;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import projecteulerproblems.PrimeNumberGenerator;
public class PrimeNumberGeneratorTest {
private static final int UPPER_LIMIT = 100000;
private static final int MILLIS_PER_PRIME = 78;
@Before
public void setUp() throws Exception {
}
@Test (timeout = UPPER_LIMIT * MILLIS_PER_PRIME)
public void testCalculatePrimesUpTo() {
PrimeNumberGenerator.getFirstNPrimes(UPPER_LIMIT);
}
}
|
package com.myou.appback.modules.foundation.oid.util;
import java.io.Serializable;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;
/**
* Description: 20位OID的 Hibernate生成器<br>
* @version 1.0
*/
public class HibernateOIDGenerator implements IdentifierGenerator {
public HibernateOIDGenerator() {
}
public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
return OIDGenerator.getOID(session.connection());
}
}
|
package th.co.gosoft;
public class Operand {
protected final int value;
public Operand(int value) {
this.value = value;
}
}
|
package com._520it.dao;
import java.io.Serializable;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
//必须实现Serializable接口,不实现该接口的话钝化时不能真正将user写到硬盘上
public class User implements HttpSessionActivationListener,Serializable {
private int uid;
private String uname;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
//钝化
public void sessionWillPassivate(HttpSessionEvent se) {
System.out.println("user被钝化了");
}
//活化
public void sessionDidActivate(HttpSessionEvent se) {
System.out.println("user被活化了");
}
}
|
package negocio.basica;
// Generated 24/09/2012 21:42:02 by Hibernate Tools 3.2.0.CR1
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* Funcionario generated by hbm2java
*/
public class Funcionario implements java.io.Serializable {
private int id;
private Departamento departamento;
private Privilegio privilegio;
private String nome;
private String email;
private String cpf;
private String rg;
private Date dtnascimento;
private String endereco;
private String bairro;
private String cidade;
private String cep;
private String telefone;
private String login;
private String senha;
private String cargo;
private String estado;
private Set chamados = new HashSet(0);
public Funcionario() {
}
public Funcionario(int id, Departamento departamento, Privilegio privilegio) {
this.id = id;
this.departamento = departamento;
this.privilegio = privilegio;
}
public Funcionario(int id, Departamento departamento,
Privilegio privilegio, String nome, String email, String cpf,
String rg, Date dtnascimento, String endereco, String bairro,
String cidade, String cep, String telefone, String login,
String senha, String cargo, String estado, Set chamados) {
this.id = id;
this.departamento = departamento;
this.privilegio = privilegio;
this.nome = nome;
this.email = email;
this.cpf = cpf;
this.rg = rg;
this.dtnascimento = dtnascimento;
this.endereco = endereco;
this.bairro = bairro;
this.cidade = cidade;
this.cep = cep;
this.telefone = telefone;
this.login = login;
this.senha = senha;
this.cargo = cargo;
this.estado = estado;
this.chamados = chamados;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public Departamento getDepartamento() {
return this.departamento;
}
public void setDepartamento(Departamento departamento) {
this.departamento = departamento;
}
public Privilegio getPrivilegio() {
return this.privilegio;
}
public void setPrivilegio(Privilegio privilegio) {
this.privilegio = privilegio;
}
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCpf() {
return this.cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getRg() {
return this.rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public Date getDtnascimento() {
return this.dtnascimento;
}
public void setDtnascimento(Date dtnascimento) {
this.dtnascimento = dtnascimento;
}
public String getEndereco() {
return this.endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getBairro() {
return this.bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getCidade() {
return this.cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public String getCep() {
return this.cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getTelefone() {
return this.telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getLogin() {
return this.login;
}
public void setLogin(String login) {
this.login = login;
}
public String getSenha() {
return this.senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getCargo() {
return this.cargo;
}
public void setCargo(String cargo) {
this.cargo = cargo;
}
public String getEstado() {
return this.estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public Set getChamados() {
return this.chamados;
}
public void setChamados(Set chamados) {
this.chamados = chamados;
}
}
|
package com.karya.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* A simple POJO to represent our user domain
*
*/
@Entity
@Table(name="testcase001mb")
public class TestCase001MB {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="ID", nullable = false)
private Long id;
@Column(name="FOLDERNAME", nullable = false)
private String folderName;
@Column(name="TITLE", nullable = false)
private String title;
@Column(name="STATUS", nullable = false)
private String status;
@Column(name="PRIORITY", nullable = true)
private String priority;
@Column(name="LSTRNRELEASE", nullable = false)
private String lstrnRelease;//Last Run Release
@Column(name="ASSIGNTO", nullable = false)
private String assignTo;
@Column(name="LSTRNDATE", nullable = false)
private Date lstrnDate ;
@Column(name="LSTRNSTATUS", nullable = false)
private String lstrnStatus;
@Column(name="LSTRNTESTSET", nullable = false)
private String lstrnTestSet;
@Column(name="DATEUPDATED", nullable = false)
private Date dateUpdated;
@Column(name="EXECTYPE", nullable = false)
private String execType;
@Column(name="ORIGINALID", nullable = false)
private String originalId;
@Column(name="TESTTYPE", nullable = false)
private String testType;
@Column(name="VERSION", nullable = false)
private String version;
@Column(name="LSTRNBY", nullable = false)
private String lstrnBy;
@Column(name="OWNER", nullable = false)
private String owner;
@Column(name="RUNTIME", nullable = false)
private String runTime;
@Column(name="REVIEWED", nullable = false)
private String reviewed;
@Column(name="RNBYHOST", nullable = false)
private String rnbyHost;
@Column(name="AUTOMATED", nullable = false)
private String automated;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getLstrnBy() {
return lstrnBy;
}
public void setLstrnBy(String lstrnBy) {
this.lstrnBy = lstrnBy;
}
public Date getLstrnDate() {
return lstrnDate;
}
public void setLstrnDate(Date lstrnDate) {
this.lstrnDate = lstrnDate;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getRunTime() {
return runTime;
}
public void setRunTime(String runTime) {
this.runTime = runTime;
}
public String getReviewed() {
return reviewed;
}
public void setReviewed(String reviewed) {
this.reviewed = reviewed;
}
public String getRnbyHost() {
return rnbyHost;
}
public void setRnbyHost(String rnbyHost) {
this.rnbyHost = rnbyHost;
}
public String getAutomated() {
return automated;
}
public void setAutomated(String automated) {
this.automated = automated;
}
public String getLstrnStatus() {
return lstrnStatus;
}
public void setLstrnStatus(String lstrnStatus) {
this.lstrnStatus = lstrnStatus;
}
public String getLstrnTestSet() {
return lstrnTestSet;
}
public void setLstrnTestSet(String lstrnTestSet) {
this.lstrnTestSet = lstrnTestSet;
}
public Date getDateUpdated() {
return dateUpdated;
}
public void setDateUpdated(Date dateUpdated) {
this.dateUpdated = dateUpdated;
}
public String getExecType() {
return execType;
}
public void setExecType(String execType) {
this.execType = execType;
}
public String getOriginalId() {
return originalId;
}
public void setOriginalId(String originalId) {
this.originalId = originalId;
}
public String getTestType() {
return testType;
}
public void setTestType(String testType) {
this.testType = testType;
}
public String getAssignTo() {
return assignTo;
}
public void setAssignTo(String assignTo) {
this.assignTo = assignTo;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/*public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}*/
public String getFolderName() {
return folderName;
}
public void setFolderName(String folderName) {
this.folderName = folderName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLstrnRelease() {
return lstrnRelease;
}
public void setLstrnRelease(String lstrnRelease) {
this.lstrnRelease = lstrnRelease;
}
}
|
/**
*
*/
package se.vgregion.alfrescoclient.domain;
import java.util.List;
/**
* Domain class representing Alfresco events.
*
* @author simongoransson
*/
public class Events {
private List<Event> events;
public List<Event> getEvents() {
return events;
}
public void setEvents(List<Event> events) {
this.events = events;
}
public static class Event {
private String name;
private String title;
private String where;
private String when;
private String url;
private String start;
private String end;
private String endDate;
private String site;
private String siteTitle;
private boolean allday;
private String tags;
private String duration;
private boolean isoutlook;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getWhere() {
return where;
}
public void setWhere(String where) {
this.where = where;
}
public String getWhen() {
return when;
}
public void setWhen(String when) {
this.when = when;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getSite() {
return site;
}
public void setSite(String site) {
this.site = site;
}
public String getSiteTitle() {
return siteTitle;
}
public void setSiteTitle(String siteTitle) {
this.siteTitle = siteTitle;
}
public boolean isAllday() {
return allday;
}
public void setAllday(boolean allday) {
this.allday = allday;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public boolean isIsoutlook() {
return isoutlook;
}
public void setIsoutlook(boolean isoutlook) {
this.isoutlook = isoutlook;
}
}
}
|
package ChainOfResponsibility;
/**
* 定义:将能够处理同一类请求的对象连成一条链,所提交的请求沿着链传播
* 链上的对象逐个判断是否有能力处理该请求,如果能处理则处理,如果不能则传递给链上的下一个对象
*
*
*
* @author Johnsonk
* @date Aug 8, 2018
*/
public class ChainOfResponsibility {
public static void main(String[] args) {
Leader aLeader=new Director("张三");
Leader aLeader2=new Manager("李四");
Leader aLeader3=new GeneralManager("王五");
//组织责任链
aLeader.setNextLeader(aLeader2);
aLeader2.setNextLeader(aLeader3);
//开始请假操作
LeaveRequest request=new LeaveRequest("tom", 11, "回老家");
//交给主任操作
aLeader.handleRequest(request);
}
}
|
package org.tum.project.constant;
public class ConstantValue {
// module table variable
public static final String TIMESTAMP="timestamp";
public static final String PACKETID="packetId";
public static final String FLOWID="flowId";
public static final String FLITID="flitId";
public static final String ISTAIL="isTail";
//fifo table variable
public static final String FIFONAME="fifoName";
public static final String CURRENTFIFOSIZE="currentFIFOSize";
}
|
package org.andrill.conop.core;
import java.math.BigDecimal;
public interface Observation {
/**
* Gets the event.
*
* @return the event.
*/
public abstract Event getEvent();
/**
* Gets the level.
*
* @return the level.
*/
public abstract BigDecimal getLevel();
/**
* Gets the down-weight.
*
* @return the down-weight.
*/
public abstract double getWeightDown();
/**
* Gets the up-weight.
*
* @return the up-weight.
*/
public abstract double getWeightUp();
} |
package norswap.autumn;
import norswap.autumn.parsers.*;
import norswap.autumn.visitors.VisitorFirstParsers;
import norswap.autumn.visitors.WellFormednessChecker;
/**
* A visitor interface for the built-in implementations of {@link Parser}.
*
* <p>To write a visitor for the built-in parser implementations, it suffices to implement this
* interface. The built-in parsers already override {@link Parser#accept(ParserVisitor)} to call
* {@code visitor.visit(this);} — which will select the right overload for the specific parser.
*
* <p>To handle custom parsers (say {@code MyParser}), things are slightly more complex. You must
* first create a sub-interface extending {@code ParserVisitor} (say {@code MyParserVisitor}),
* adding a method {@code void visit(MyParser parser);}. Next, {@code MyParser} must override {@link
* Parser#accept(ParserVisitor)} to call {@code ((MyParserVisitor)visitor).visit(this);}. Now all
* visitors that implement {@code MyParserVisitor} will work with all built-in parsers as well as
* {@code MyParser}.
*
* <p>This is not the end of the story, as you may want to compose visitors for multiple parsers.
* The trick is to actually implement {@code ParserVisitor} and its sub-interfaces as interfaces,
* then to compose these implementations with a single class.
*
* <p>As an example, consider this hierarchy:
* <pre>
* {@code
* interface ParserVisitor
* + interface MyParserVisitor (extends ParserVisitor)
* + interface _VisitorA (extends ParserVisitor)
* + class VisitorA (extends _VisitorA)
* + interface _VisitorB (extends ParserVisitor)
* + class VisitorB (extends _VisitorB)
*
* interface _VisitorMyParserA extends _VisitorA, MyParserVisitor
* + final class VisitorMyParserA (extends VisitorA implements _VisitorMyParserA)
*
* interface _VisitorMyParserB extends _VisitorB, MyParserVisitor
* + final class VisitorMyParserB (extends VisitorA implements _VisitorMyParserB)
* }
* </pre>
*
* <p>Within it, we have an interface to handle our custom parser {@code MyParser}: {@code
* MyParserVisitor}. We also have two visitor implementations that do not support {@code MyParser}:
* {@code _VisitorA} and {@code _VisitorB}, which might be coming from some library. Note that those
* are interfaces, precisely so that they can be composed.
*
* <p>{@code VisitorA} and {@code VisitorB} are instantiable versions of these implementations.
* Typically, these classes will be almost empty: the only thing you must do is to supply storage for
* the state of the visitors. (e.g. storage for {@link VisitorFirstParsers#firsts()}).
*
* <p>Note that it's a convention to use an underscore (_) in front of the name of the
* "implementation interfaces" and to use the same name without the underscore for the corresponding
* instantiable version. Another convention we use is to have visitors' names (both interfaces and
* classes) start with "Visitor".
*
* <p>Now, if you want to use {@code _VisitorA} with {@code MyParserVisitor}, you need to compose
* them and supply an {@code void accept(MyParser)} overload. This is what {@code _VisitorMyParserA}
* does, and similarly with {@code _VisitorMyParserB} for {@code _VisitorB}. We also supply
* the corresponding instantiable classes. Note that if you're not going to expose your code as a
* library, you can skip the interface step ({@code _VisitorMyParserA}) and immediately implement
* {@code _VisitorA} and {@code MyParserVisitor} in a class!
*
* <p>Note that we make {@code _VisitorMyParserA} extends {@code VisitorA}: this simply avoids
* duplicating the storage definitions already made in {@code VisitorA}.
*
* <p>These composition hierarchies can even get hairier, but everything will keep working as long
* as each method is only overriden in a single interface of the hiearchy.
*
* <p>Finally, note that the visitor interface <b>only</b> allows specialization of behaviour based
* on the parser type. It does not perform any kind of grammar traversal on your behalf. Of course,
* for some visitors, such a traversal might be a part of the specialized functionality, but {@code
* ParseVisitor} offers no support for this. However, {@link ParserWalker} has the logic to traverse
* the grammar (which is essentially a directed parser graph whose edges are given by {@link
* Parser#children()}. As an example of how visitors and walkers can work in tandem, see {@link
* WellFormednessChecker} and its implementation.
*/
public interface ParserVisitor
{
// ---------------------------------------------------------------------------------------------
/**
* Catch-all overload, in case someone doesn't want to implement a visitor interface for a
* custom parser. If no catch-all is conceivable for your visitor, this should throw a runtime
* exception.
*/
void visit (Parser parser);
// ---------------------------------------------------------------------------------------------
void visit (AbstractChoice parser);
void visit (AbstractForwarding parser);
void visit (AbstractPrimitive parser);
void visit (Around parser);
void visit (CharPredicate parser);
void visit (Choice parser);
void visit (Collect parser);
void visit (Empty parser);
void visit (Fail parser);
void visit (GuardedRecursion parser);
void visit (LazyParser parser);
void visit (LeftAssoc parser);
void visit (LeftRecursive parser);
void visit (Longest parser);
void visit (Lookahead parser);
void visit (Memo parser);
void visit (Not parser);
void visit (ObjectPredicate parser);
void visit (Optional parser);
void visit (Repeat parser);
void visit (RightAssoc parser);
void visit (Sequence parser);
void visit (StringMatch parser);
void visit (TokenChoice parser);
void visit (TokenParser parser);
// ---------------------------------------------------------------------------------------------
} |
package com.hillel.javaElementary.classes.Lesson_8.Task_5;
import java.util.Date;
public class LoggingHumanLifecycleObserver implements IHumanLifecycleObserver{
@Override
public void onHumanWasBorn(BornParams params) {
System.out.printf("%s was born with name %s and %s",
params.getGender() ? "Male":"Female",
params.getName(),
params.getBirthday().toString()+"\n");
}
@Override
public void onWentToKindergarten(EducationParams params) {
System.out.printf("Went to the %s kindergarten in %s age\n",
params.getEducationalEstablishment(),
params.getAge());
}
@Override
public void onWentToSchool(EducationParams params) {
System.out.printf("Went to the %s school in %s age\n",
params.getEducationalEstablishment(),
params.getAge());
}
@Override
public void onWentToUniversity(EducationParams params) {
System.out.printf("Went to the %s university in %s age\n",
params.getEducationalEstablishment(),
params.getAge());
}
@Override
public void onGotWork(WorkParams params) {
System.out.printf("Got work on %s position with salary = %s\n",
params.getPosition(),
params.getSalary());
}
@Override
public void onBoughtCar(BoughtCarParams params) {
System.out.printf("Bought car %s year for %s price with %s mileage\n",
params.getBrand(),
params.getCost(),
params.getMileage());
}
@Override
public void onCreatingFamily(CreatingFamilyParams params) {
System.out.printf("Got married on %s in %s age\n",
params.getWifeName(),
params.getAge());
}
@Override
public void onGaveBirth(GaveBirthParams params) {
System.out.printf("Gave birth the %s with %s name %s\n",
params.getGender() ? "Male":"Female",
params.getChildName(),
params.getBirthday().toString());
}
@Override
public void onDeath(Date date) {
System.out.printf("Died %s\n",
date.getTime());
}
}
|
package com.flavio.android.petlegal.model;
/**
* Created by Flávio on 24/05/2018.
*/
public class Atendimento {
}
|
package cn.jacfrak;
public class ServerConstant {
public static final Integer SERVER_STATUS_USED = 1;
public static final Integer SERVER_STATUS_UNUSE = 0;
//重启ss
public static final String RESTARTSHADOWSOCKS = "/etc/init.d/shadowsocks restart";
//开启防火墙端口
public static final String OPENPORTPERMANENT = "firewall-cmd --zone=public --add-port=remote_port/tcp --permanent";
//更新防火墙规则
public static final String UPDATEFIREWALLRULE = "firewall-cmd --reload";
//关闭防火墙端口
public static final String REMOVEPORTPERMANENT = "firewall-cmd --zone=public --remove-port=remote_port/tcp --permanent";
//重启防火墙
public static final String RESTARTFIREWALL = "systemctl restart firewalld.service";
//端口统计
public static final String PORTSTATISTIC = "iptables -A OUTPUT -p tcp --sport remote_port";
//关闭某个端口统计
public static final String REMOVEPORTSTATISTIC = "iptables -D OUTPUT -p tcp --sport port";
//端口统计保存
public static final String SAVEIPTABLES = "iptables-save";
//重启系统
public static final String RESTARTSYSTEM = "reboot";
}
|
/* $Id$ */
package djudge.judge.dchecker;
public class ValidatorTask
{
public String contestId;
public String problemId;
public int groupNumber;
public int testNumber;
public RemoteFile programOutput;
public RemoteFile testInput;
public RemoteFile testOutput;
public ValidatorTask()
{
programOutput = new RemoteFile();
testInput = new RemoteFile();
testOutput = new RemoteFile();
}
}
|
package services;
import java.util.Calendar;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import repositories.LikeRepository;
import domain.Chorbi;
import domain.Like;
@Service
@Transactional
public class LikeService {
// Managed repository -----------------------------------------------------
@Autowired
private LikeRepository likeRepository;
// Supporting services ----------------------------------------------------
@Autowired
private ChorbiService chorbiService;
// Constructors -----------------------------------------------------------
public LikeService() {
super();
}
// Simple CRUD methods ----------------------------------------------------
public Like findOne(final int likeId) {
Assert.isTrue(likeId != 0);
Like result;
result = this.likeRepository.findOne(likeId);
return result;
}
public Collection<Like> findAll() {
Collection<Like> result;
result = this.likeRepository.findAll();
return result;
}
public Like create(final Chorbi givenTo) {
Assert.notNull(givenTo);
Like like;
Chorbi principal;
Calendar calendar;
Like likeBefore;
principal = this.chorbiService.findByPrincipal();
// comprobar que haya un chorbi logueado, que no este baneado y que no se vaya a dar like a sí mismo
Assert.notNull(principal);
Assert.isTrue(!principal.getBanned());
Assert.isTrue(!principal.equals(givenTo));
// comprobar que no se habian dado like antes
likeBefore = this.findByGivenToIdAndGivenById(givenTo.getId(), principal.getId());
Assert.isNull(likeBefore);
calendar = Calendar.getInstance();
calendar.set(Calendar.MILLISECOND, -10);
like = new Like();
like.setGivenBy(principal);
like.setGivenTo(givenTo);
like.setLikeMoment(calendar.getTime());
return like;
}
public Like save(Like like) {
Assert.notNull(like);
Chorbi principal;
principal = this.chorbiService.findByPrincipal();
Assert.isTrue(!principal.getBanned());
Assert.isTrue(principal.equals(like.getGivenBy()));
like = this.likeRepository.save(like);
return like;
}
public void delete(final Like like) {
Assert.notNull(like);
Chorbi principal;
principal = this.chorbiService.findByPrincipal();
Assert.isTrue(!principal.getBanned());
Assert.isTrue(principal.equals(like.getGivenBy()));
this.likeRepository.delete(like);
}
// Other business methods -------------------------------------------------
public Like findByGivenToIdAndGivenById(final int chorbiToId, final int chorbiById) {
Like result;
result = this.likeRepository.findByGivenToIdAndGivenById(chorbiToId, chorbiById);
return result;
}
public Collection<Like> findByGivenToId(final int chorbiToId) {
Collection<Like> result;
result = this.likeRepository.findByGivenToId(chorbiToId);
return result;
}
public Collection<Like> findByGivenById(final int chorbiToId) {
Collection<Like> result;
result = this.likeRepository.findByGivenById(chorbiToId);
return result;
}
public Object[] findMinMaxAvgReceivedPerChorbi() {
Object[] result;
result = this.likeRepository.findMinMaxAvgReceivedPerChorbi();
return result;
}
public Object[] findMinMaxAvgStarsPerChorbi() {
Object[] result;
result = this.likeRepository.findMinMaxAvgStatsPerChorbi();
return result;
}
}
|
import java.util.Scanner;
public class TextMenu
{
private void printMenu()
{
System.out.println("==============================================");
System.out.println("Menu tekstowe dla listy 4");
System.out.println("==============================================");
System.out.println(" Aby wybrać zadanie wpisz odpowiednią liczbę");
System.out.println(" 0 -Wyświetl menu");
System.out.println(" 1 -Stwórz tablice o wybranym rozmiarze");
System.out.println(" 2 -Manualna generaja tablicy");
System.out.println(" 3 -Automatyczna generacja tablicy");
System.out.println(" 4 -Wyświetlenie sumy wartości elementów tablicy");
System.out.println(" 5 -Wyświetlenie wartości maksymalnej tablicy");
System.out.println(" 6 -Wyświetlnie indeksu elementu maksymalnego tablicy");
System.out.println(" 7 -Czy podana wartość występuje na którejś z początkowych pozycji tablicy");
System.out.println(" 8 -Czy tablica jest różnowartościowa"); // FIXME: bad result !!!!!!!!!!!!!!!!
System.out.println(" 9 -Czy tablica jest różnowartościowa - 2 sposób");
System.out.println(" 10 -Czy tablica jest różnowartościowa - 3 sposób");
System.out.println(" 11 -Usunięcie wszystkich wystąpień podanej liczby");
System.out.println(" 12 -Usunięcie wszystkich powtórzeń elementów tablicy");
System.out.println(" 13 -Wyświetlenie tablicy");
System.out.println(" 14 -Usunięcie tablicy");
System.out.println(" 15 -Wyjście");
System.out.println("==============================================");
}
public void textMenu()
{
cTable tab = null;
Scanner menu = new Scanner(System.in);
printMenu();
while(true)
{
int choice = menu.nextInt();
switch (choice)
{
case 0:
printMenu();
break;
case 1:
System.out.println("Wpisz rozmiar tablicy");
tab = new cTable(menu.nextInt());
break;
case 2:
System.out.println("Manualna generacja tablicy");
System.out.println("Wpisz elementy tablicy");
tab.manuallyGenerate();
break;
case 3:
System.out.println("Automatyczna generacja tablicy");
tab.generate();
break;
case 4:
System.out.println("Suma wartości elementów tablicy");
int result = tab.sum();
System.out.println("Suma = " + result);
break;
case 5:
System.out.println("Wartosć maksymalna tablicy");
try
{
result = tab.maxValue();
System.out.println("Maksymalna wartość = " + result);
}
catch(NullPointerException e)
{
System.out.println("Najpierw utwórz tablicę");
}
break;
case 6:
System.out.println("Indeks elementu maksymalnego tablicy");
try
{
int index = tab.indexOfmaxValue();
System.out.println("Index wartości max = " + index);
}
catch(NullPointerException e)
{
System.out.println("Najpierw utwórz tablicę");
}
break;
case 7:
System.out.println("Czy podana wartość występuje na którejś z początkowych pozycji tablicy");
System.out.println("Wpisz wartość oraz zakres");
try
{
boolean ret = tab.isInTable(menu.nextInt(), menu.nextInt());
System.out.println(" Czy jest w tablicy = " + ret);
}
catch(NullPointerException e)
{
System.out.println("Najpierw utwórz tablicę");
}
break;
case 8:
System.out.println("Czy tablica jest różnowartościowa");
try
{
System.out.println(" Czy jest różnowartościowa = " + tab.isMultiValued());
}
catch(NullPointerException e)
{
System.out.println("Najpierw utwórz tablicę");
}
break;
case 9:
System.out.println("Czy tablica jest różnowartościowa- 2 sposób");
try
{
System.out.println(" Czy jest różnowartościowa2 = " + tab.isMultiValued2());
}
catch(NullPointerException e)
{
System.out.println("Najpierw utwórz tablicę");
}
break;
case 10:
System.out.println("Czy tablica jest różnowartościowa- 3 sposób");
try
{
System.out.println(" Czy jest różnowartościowa3 = " + tab.isMultiValued3());
}
catch(NullPointerException e)
{
System.out.println("Najpierw utwórz tablicę");
}
break;
case 11:
System.out.println("Usunięcie wszystkich wystapień podanej liczby");
try
{
System.out.println("Wpisz liczbę do usunięcia");
tab.removeNumber(menu.nextInt());
}
catch(NullPointerException e)
{
System.out.println("Najpierw utwórz tablicę");
}
break;
case 12:
System.out.println("Usunięcie wszystkich powtórzeń elementów tablicy");
try
{
tab.removeRepeating();
tab.display();
}
catch(NullPointerException e)
{
System.out.println("Najpierw utwórz tablicę");
}
break;
case 13:
System.out.println("Wyświetlenie tablicy");
try
{
tab.display();
}
catch(NullPointerException e)
{
System.out.println("Najpierw utwórz tablicę");
}
break;
case 14:
System.out.println("Usunięcie tablicy");
tab = null;
break;
case 15:
menu.close();
System.exit(0);
break;
default:
System.out.println("Nie ma tkiej opcji");
break;
}
}
}
}
|
package Algorithms;
public class Main {
public static void main(String[] args) {
Algorithms alg = new Algorithms(10);
alg.RunSort();
}
}
|
package ru.mcfr.oxygen.framework.operations.table;
import ro.sync.ecss.extensions.api.*;
import ro.sync.ecss.extensions.api.access.AuthorTableAccess;
import ro.sync.ecss.extensions.api.node.AttrValue;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;
import ro.sync.ecss.extensions.api.node.AuthorElement;
import ro.sync.ecss.extensions.api.node.AuthorNode;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: ws
* Date: 09.03.11
* Time: 14:26
* To change this template use File | Settings | File Templates.
*/
public class DeleteInsertRowOperation implements AuthorOperation {
public void doOperation(AuthorAccess authorAccess, ArgumentsMap argumentsMap) throws IllegalArgumentException, AuthorOperationException {
AuthorDocumentController controller = authorAccess.getDocumentController();
AuthorSchemaManager manager = authorAccess.getDocumentController().getAuthorSchemaManager();
AuthorTableAccess tableContainer = authorAccess.getTableAccess();
String selectedText = "";
try {
selectedText = authorAccess.getEditorAccess().getSelectedText();
} catch (Exception e) {
}
try{
int currentPosition = authorAccess.getEditorAccess().getCaretOffset();
if (!selectedText.isEmpty())
currentPosition = authorAccess.getEditorAccess().getSelectionStart();
AuthorNode cell = controller.getNodeAtOffset(currentPosition);
while (!cell.getName().equalsIgnoreCase("ячейка"))
cell = cell.getParent();
AuthorNode table = cell;
while (!table.getName().equalsIgnoreCase("таблица"))
table = table.getParent();
int[] cellCoord = authorAccess.getTableAccess().getTableCellIndex((AuthorElement) cell);
int selectedRowNumber = cellCoord[0];
AuthorElement row = authorAccess.getTableAccess().getTableRow(selectedRowNumber, (AuthorElement) table);
int columnsCount = authorAccess.getTableAccess().getTableNumberOfColumns((AuthorElement) table);
if (argumentsMap.getArgumentValue("вид операции").equals("удалить")){
for (int i = 0; i < columnsCount; i++) {
AuthorElement iCell = authorAccess.getTableAccess().getTableCellAt(selectedRowNumber, i, (AuthorElement) table);
try {
int rowspanValue = Integer.valueOf(iCell.getAttribute("rowspan").getValue());
controller.setAttribute("rowspan", new AttrValue("" + (--rowspanValue)), iCell);
} catch (Exception e) {
}
}
controller.deleteNode(row);
authorAccess.getEditorAccess().setCaretPosition(currentPosition);
return;
}
int pointToInsert = row.getEndOffset() + 1;
String xmlText = "<строка>";
//border and colspan copy
List<AuthorNode> cells = row.getContentNodes();
for (AuthorNode cel : cells){
String cellText = "<ячейка";
AuthorElement aeCell = (AuthorElement) cel;
int attrsCount = aeCell.getAttributesCount();
for (int i = 0; i < attrsCount; i++){
if (aeCell.getAttributeAtIndex(i).equalsIgnoreCase("colspan") | aeCell.getAttributeAtIndex(i).contains("border")){
String attrName = aeCell.getAttributeAtIndex(i);
String attrValue = aeCell.getAttribute(attrName).getValue();
cellText += " " + attrName + "=\"" + attrValue + "\"";
}
}
cellText += "/>";
xmlText += cellText;
}
xmlText += "</строка>";
//rowspan in table
for (int i = 0; i < columnsCount; i++){
AuthorElement iCell = authorAccess.getTableAccess().getTableCellAt(selectedRowNumber, i, (AuthorElement) table);
try {
int rowspanValue = Integer.valueOf(iCell.getAttribute("rowspan").getValue());
controller.setAttribute("rowspan", new AttrValue("" + (++rowspanValue)), iCell);
} catch (Exception e){ }
}
AuthorDocumentFragment fragment = controller.createNewDocumentFragmentInContext(xmlText, pointToInsert);
controller.insertFragment(pointToInsert,fragment);
authorAccess.getEditorAccess().setCaretPosition(currentPosition);
//controller.insertXMLFragment(xmlText ,pointToInsert);
} catch (Exception e) {}
}
public ArgumentDescriptor[] getArguments() {
return new ArgumentDescriptor[]{
new ArgumentDescriptor("вид операции",ArgumentDescriptor.TYPE_STRING,"удалить/вставить"),
new ArgumentDescriptor("направление",ArgumentDescriptor.TYPE_STRING,"перед/после"),
};
}
public String getDescription() {
return "Вставить строку после";
}
}
|
package com.clearminds.rgv.tests;
import com.clearminds.rgv.dtos.Estudiante;
import com.clearminds.rgv.excepciones.BDDException;
import com.clearminds.rgv.servicios.ServicioEstudiante;
public class TestServicio {
public static void main(String[] args) {
ServicioEstudiante srvEstudiante = new ServicioEstudiante();
try {
srvEstudiante.insertarEstudiante(new Estudiante("José", "Intriago"));
} catch (BDDException e) {
e.printStackTrace();
e.getMessage();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.