text
stringlengths 10
2.72M
|
|---|
package ru.vlad805.mapssharedpoints;
import java.util.HashMap;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import mjson.Json;
public class MainActivity extends ExtendedActivity {
private EditText loginView;
private EditText passwordView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Utils.isAuthorized(this)) {
if (!Utils.has(this, Const.SHARED_USER)) {
setProgressDialog("");
resolveUser(Utils.getInt(this, Const.USER_ID));
}
startActivity(new Intent(this, MapActivity.class));
finish();
return;
}
loginView = (EditText) findViewById(R.id.login_login_value);
passwordView = (EditText) findViewById(R.id.login_password_value);
}
public void authorize (View v) {
String login = loginView.getText().toString().trim();
String password = passwordView.getText().toString().trim();
if (login.length() <= 3 || password.length() < 6) {
Utils.toast(this, "Неверно введены данные!");
return;
}
setProgressDialog(R.string.login_process);
auth(login, password);
}
public void registerVK (View v) {
Intent i = new Intent(this, RegisterActivity.class);
i.putExtra(Const.IS_VK, true);
startActivity(i);
}
private void auth (String login, String password) {
HashMap<String, String> params = new HashMap<>();
params.put(Const.LOGIN, login);
params.put(Const.PASSWORD, password);
try {
new API(getActivity(), Const.API.login, params, new APICallback() {
@Override
public void onResult (Json result) {
String userAccessToken = result.at(Const.USER_ACCESS_TOKEN).asString();
int userId = result.at(Const.USER_ID).asInteger();
Utils.setInt(getActivity(), Const.USER_ID, userId);
Utils.setString(getActivity(), Const.USER_ACCESS_TOKEN, userAccessToken);
resolveUser(userId);
}
@Override
public void onError (APIError e) {
closeProgressDialog();
showAPIError(e);
}
}).send();
} catch (NotAvailableInternetException e) {
runOnUiThread(noInternet);
}
}
public void register (View v) {
startActivity(new Intent(this, RegisterActivity.class));
}
private void resolveUser (int userId) {
HashMap<String, String> params = new HashMap<>();
params.put(Const.USER_IDS, String.valueOf(userId));
try {
new API(getActivity(), Const.API.getUsers, params, new APICallback() {
@Override
public void onResult (Json users) {
closeProgressDialog();
if (users.asJsonList().size() == 0) {
finish();
return;
}
Json user = users.asJsonList().get(0);
String name = user.at(Const.FIRST_NAME).asString();
Utils.setString(getActivity(), Const.SHARED_USER, user.toString());
Utils.toast(getActivity(), String.format(getString(R.string.login_welcome), name));
startActivity(new Intent(getActivity(), MapActivity.class));
finish();
}
@Override
public void onError (APIError e) {
showAPIError(e);
}
}).send();
} catch (NotAvailableInternetException e) {
noInternet.run();
}
}
}
|
package basics;
/**
* Simple BMI calculator (command-line-interface).
*
* @author Aga
*
*/
public class BmiCalculator {
static double computeBMI(int heightInCm, int weightInKg) {
double heightInM = heightInCm / 100;
return (double) weightInKg / (heightInM * heightInM);
}
public static void main(String[] args) {
int height = Integer.parseInt(args[0]);
int weight = Integer.parseInt(args[1]);
double bmiScore = computeBMI(height, weight);
System.out.println("Twój BMI wynosi: " + bmiScore);
if (bmiScore < 18.5) {
System.out.println("Masz niedowagę!");
} else if (bmiScore < 25) {
System.out.println("Twoja waga jest optymalna :)");
} else {
System.out.println("Masz nadwagę!");
}
}
}
|
package com.example.xinruigao.musicinbackground;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import static com.example.xinruigao.musicinbackground.MyService.NOTIFY_PAUSE;
import static com.example.xinruigao.musicinbackground.MyService.NOTIFY_TOAST;
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String toastMessage = intent.getStringExtra(NOTIFY_TOAST);
if (intent.getAction().equals(MyService.NOTIFY_PLAY)){
Toast.makeText(context, "NOTIFY_PLAY", Toast.LENGTH_LONG).show();
} else if (intent.getAction().equals(MyService.NOTIFY_PAUSE)){
Toast.makeText(context, "NOTIFY_PAUSE", Toast.LENGTH_LONG).show();
Intent serviceIntent = new Intent(context, MyService.class);
context.stopService(serviceIntent);
}else if (intent.getAction().equals(MyService.NOTIFY_NEXT)){
Toast.makeText(context, "NOTIFY_NEXT", Toast.LENGTH_LONG).show();
}else if (intent.getAction().equals(MyService.NOTIFY_PREVIOUS)){
Toast.makeText(context, "NOTIFY_PREVIOUS", Toast.LENGTH_LONG).show();
}else if(intent.getAction().equals(MyService.NOTIFY_TOAST)){
Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show();
}
}
}
|
package com.androidapp.yemyokyaw.movieapp.viewholders;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.androidapp.yemyokyaw.movieapp.MovieApp;
import com.androidapp.yemyokyaw.movieapp.R;
import com.androidapp.yemyokyaw.movieapp.data.vo.MovieVO;
import com.androidapp.yemyokyaw.movieapp.delegates.MovieListDelegate;
import com.androidapp.yemyokyaw.movieapp.utils.AppConstants;
import com.bumptech.glide.Glide;
/**
* Created by yemyokyaw on 12/5/17.
*/
public class MovieListViewHolder extends BaseViewHolder<MovieVO> {
ImageView ivMovieImg;
TextView tvMovieTitle;
TextView tvMovieType;
TextView tvMovieRating;
RatingBar rbMoviePopular;
TextView tvOverview;
private MovieListDelegate mDelegate;
public MovieListViewHolder(View view, MovieListDelegate mlDelegate) {
super(view);
tvMovieType = (TextView) view.findViewById(R.id.tv_moive_type_id);
tvMovieTitle = (TextView) view.findViewById(R.id.tv_movie_title_id);
tvMovieRating = (TextView) view.findViewById(R.id.tv_movie_rating_id);
rbMoviePopular = (RatingBar) view.findViewById(R.id.rb_movie_popular_id);
ivMovieImg = (ImageView) view.findViewById(R.id.cv_movie_img_id);
tvOverview = (TextView) view.findViewById(R.id.btn_movie_overview_id);
this.mDelegate = mlDelegate;
}
@Override
public void setData(MovieVO data) {
final MovieVO movie = data;
tvMovieTitle.setText(data.getTitle());
tvMovieType.setText(data.getRelease_date());
tvMovieRating.setText(String.valueOf(data.getVote_average()));
rbMoviePopular.setRating(data.getPopularity() / 250.0f);
String imgUrl = AppConstants.IMAGE_URL + data.getPoster_path();
Glide.with(ivMovieImg.getContext())
.load(imgUrl)
.centerCrop()
.placeholder(R.drawable.movie_photo_placeholder)
.error(R.drawable.movie_photo_placeholder)
.into(ivMovieImg);
tvOverview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDelegate.onTapped(movie);
}
});
}
@Override
public void onClick(View v) {
}
}
|
package com.kh.efp.Search.model.vo;
public class Ban implements java.io.Serializable{
private int banId;
private int bid;
private int mid;
private String banReason;
public Ban() {
super();
// TODO Auto-generated constructor stub
}
public Ban(int badId, int bid, int mid, String reason) {
super();
this.banId = badId;
this.bid = bid;
this.mid = mid;
this.banReason = reason;
}
public int getBadId() {
return banId;
}
public void setBadId(int badId) {
this.banId = badId;
}
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public int getMid() {
return mid;
}
public void setMid(int mid) {
this.mid = mid;
}
public String getReason() {
return banReason;
}
public void setReason(String reason) {
this.banReason = reason;
}
@Override
public String toString() {
return "Ban [badId=" + banId + ", bid=" + bid + ", mid=" + mid + ", reason=" + banReason + "]";
}
}
|
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.api.app.command;
import javax.validation.constraints.NotNull;
import monasca.common.model.alarm.AlarmState;
public class UpdateAlarmCommand {
@NotNull
public AlarmState state;
@NotNull
public String lifecycleState;
@NotNull
public String link;
public UpdateAlarmCommand() {}
public UpdateAlarmCommand(AlarmState state, String lifecycleState, String link) {
this.state = state;
this.lifecycleState = lifecycleState;
this.link = link;
}
}
|
package com.tencent.mm.ui.base;
import android.text.InputFilter;
import android.text.Spanned;
import com.tencent.map.lib.gl.model.GLIcon;
import com.tencent.mm.ui.tools.g;
public class MMTagPanel$c implements InputFilter {
final /* synthetic */ MMTagPanel txS;
int txZ = 36;
private int tya = GLIcon.TOP;
private int tyb;
public MMTagPanel$c(MMTagPanel mMTagPanel) {
this.txS = mMTagPanel;
}
public final CharSequence filter(CharSequence charSequence, int i, int i2, Spanned spanned, int i3, int i4) {
int abd = g.abd(spanned.toString()) + g.abd(charSequence.toString());
if (i4 > i3) {
if (abd - (i4 - i3) > this.txZ) {
MMTagPanel.a(this.txS, true);
this.tyb = (abd - (i4 - i3)) - this.txZ;
} else {
MMTagPanel.a(this.txS, false);
}
} else if (abd > this.txZ) {
MMTagPanel.a(this.txS, true);
this.tyb = abd - this.txZ;
} else {
MMTagPanel.a(this.txS, false);
}
if (MMTagPanel.h(this.txS) && 1 == this.tyb && charSequence.equals("\n")) {
this.tyb = 0;
}
if (MMTagPanel.e(this.txS) != null) {
this.txS.post(new 1(this));
}
if (abd > this.tya) {
return "";
}
return charSequence;
}
}
|
package exer;
import java.io.*;
public class exTest1 {
public static void main(String[] args) {
method(0,1);
}
//throw 抛出一个异常对象
//throws 异常声明
public static void method(int num1, int num2){
if(num1 == 0)
try {
throw new FileNotFoundException("文件没找到");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
// System.out.println("文件没找到");
}
if(num2 == 1)
try {
throw new IOException("IO异常");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
|
package com.company.blog.repo;
import com.company.blog.models.Request;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Collection;
import java.util.List;
public interface RequestRepository extends CrudRepository<Request, Long> {
// List<Request> findAllByOrderByIdDesc();
List<Request> findAllByOrderByIdDesc();
List<Request> findAllByStatusOrderByIdDesc(String status);
List<Request> findAllByRoomOrderByIdDesc(String room);
// default Collection<Request> findElectro() {
// return findByToWhomOrderByIdDesc("Электромонтер");
// }
//Collection<Request> findByToWhomOrderByIdDesc(String электромонтер);
@Query("SELECT u FROM Request u WHERE u.toWhom = 'Электромонтер' AND u.status = 'Не выполнено' OR u.toWhom = 'Электромонтер' AND u.status = 'На выполнении' ORDER BY u.id DESC")
Collection<Request> findElectroByOrderByIdDesc();
@Query("SELECT u FROM Request u WHERE u.toWhom = 'Сантехник' AND u.status = 'Не выполнено' OR u.toWhom = 'Сантехник' AND u.status = 'На выполнении' ORDER BY u.id DESC")
Collection<Request> findSantechnikByOrderByIdDesc();
@Query("SELECT u FROM Request u WHERE u.toWhom = 'Комплексный_рабочий' AND u.status = 'Не выполнено' OR u.toWhom = 'Комплексный_рабочий' AND u.status = 'На выполнении' ORDER BY u.id DESC")
Collection<Request> findKomplByOrderByIdDesc();
@Query("SELECT u FROM Request u WHERE u.toWhom = 'Горничная' AND u.status = 'Не выполнено' OR u.toWhom = 'Горничная' AND u.status = 'На выполнении' ORDER BY u.id DESC")
Collection<Request> findGornichnayaByOrderByIdDesc();
// Iterable<Request> findByStatusAndToWhom(String filter, String электромонтер);
// Iterable<Request> findByStatusAndToWhom(String filter, String toWhom);
List<Request> findByStatusAndToWhom(String filter, String toWhom);
}
|
package controllers;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.io.IOException;
public class IntroductionController {
public void toMenu(MouseEvent mouseEvent) throws Exception {
Stage stage = (Stage) ((Node)mouseEvent.getSource()).getScene().getWindow();
Parent root = FXMLLoader.load(getClass().getResource("/resources/menu.fxml"));
stage.setScene(new Scene(root));
}
public void toDomain(MouseEvent mouseEvent) throws Exception {
Stage stage = (Stage) ((Node)mouseEvent.getSource()).getScene().getWindow();
Parent root = FXMLLoader.load(getClass().getResource("/resources/model.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
}
}
|
package edu.nju.web.controller;
import edu.nju.RuanHuApplication;
import edu.nju.data.dao.UserDAO;
import edu.nju.data.entity.Answer;
import edu.nju.data.entity.User;
import edu.nju.web.controller.json.AnswerJsonController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import java.util.HashMap;
import java.util.Map;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Created by cuihao on 2016/7/12.
*/
@RunWith(SpringJUnit4ClassRunner.class) //表示继承了SpringJUnit4ClassRunner类
@SpringApplicationConfiguration(classes = RuanHuApplication.class) // 指定我们SpringBoot工程的Application启动类
@WebAppConfiguration
@Rollback
@Transactional
public class AnswerControllerTest {
@Autowired
private AnswerJsonController answerJsonController;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private UserDAO userDAO;
private MockMvc mockMvc;
private Map<String, Object> sessionMap = new HashMap<>();
@Before
public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
User user = userDAO.getUserByName("ch");
sessionMap.put("user",user);
}
@Test
public void tempSave() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/answer/tempSave").sessionAttrs(sessionMap)
.param("questionId","1").param("markedText","###head"))
.andExpect(status().isOk());
HashMap<String,Answer> map = new HashMap<>();
sessionMap.put("tempAnswer",map);
mockMvc.perform(MockMvcRequestBuilders.get("/answer/tempSave").sessionAttrs(sessionMap)
.param("questionId","1").param("markedText","###head2"))
.andExpect(status().isOk());
map.put("1",new Answer());
sessionMap.put("tempAnswer",map);
mockMvc.perform(MockMvcRequestBuilders.get("/answer/tempSave").sessionAttrs(sessionMap)
.param("questionId","1").param("markedText","###head3"))
.andExpect(status().isOk());
}
@Test
public void getTempAnswer() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/answer/getTempAnswer").sessionAttrs(sessionMap).param("questionId","1"))
.andExpect(status().isOk());
HashMap<String,Answer> map = new HashMap<>();
sessionMap.put("tempAnswer",map);
mockMvc.perform(MockMvcRequestBuilders.get("/answer/getTempAnswer").sessionAttrs(sessionMap).param("questionId","1"))
.andExpect(status().isOk());
map.put("1",new Answer());
sessionMap.put("tempAnswer",map);
mockMvc.perform(MockMvcRequestBuilders.get("/answer/getTempAnswer").sessionAttrs(sessionMap).param("questionId","1"))
.andExpect(status().isOk());
}
@Test
public void newAnswer() throws Exception {
}
@Test
public void saveAnswer() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/answer/saveAnswer").sessionAttrs(sessionMap)
.param("questionId","1").param("markedText","###head\nhah")).andExpect(status().isOk());
}
@Test
public void markAsSolution() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/answer/markAsSolution").sessionAttrs(sessionMap)
.param("answerId","1").param("questionId","1")).andExpect(status().isOk());
}
}
|
package com.simple.base.components.nio.service;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HandlerMapping {
String path() default "";
String id() default "0";
}
|
package com.supconit.kqfx.web.fxzf.warn.entities;
import hc.base.domains.PK;
import com.supconit.kqfx.web.fxzf.qbb.entities.QbbMbxx;
public class WarnInfo implements PK<String> {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* id
*/
private String id;
/**
* 告警模板类型
*/
private String warnType;
// private String templetType;
/**
* 对应的治超站
*/
private String detectStation;
/**
* 情报板模板ID
*/
private String qbbTempletId;
/**
* 情报板内容
*/
private String templetInfo;
/**
* 删除标志位
*/
private Integer deleted;
/**
* 情报板模板信息
*/
private QbbMbxx qbbmbxx;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
// public String getTempletType() {
// return templetType;
// }
//
// public void setTempletType(String templetType) {
// this.templetType = templetType;
// }
public String getQbbTempletId() {
return qbbTempletId;
}
public void setQbbTempletId(String qbbTempletId) {
this.qbbTempletId = qbbTempletId;
}
public String getTempletInfo() {
return templetInfo;
}
public void setTempletInfo(String templetInfo) {
this.templetInfo = templetInfo;
}
public Integer getDeleted() {
return deleted;
}
public void setDeleted(Integer deleted) {
this.deleted = deleted;
}
public QbbMbxx getQbbmbxx() {
return qbbmbxx;
}
public void setQbbmbxx(QbbMbxx qbbmbxx) {
this.qbbmbxx = qbbmbxx;
}
public String getDetectStation() {
return detectStation;
}
public void setDetectStation(String detectStation) {
this.detectStation = detectStation;
}
public String getWarnType() {
return warnType;
}
public void setWarnType(String warnType) {
this.warnType = warnType;
}
}
|
package com.ibeiliao.pay.impl.dao;
import com.ibeiliao.pay.datasource.MyBatisDao;
import com.ibeiliao.pay.impl.entity.JhjUserPO;
import org.apache.ibatis.annotations.Param;
/**
* t_jhj_user 表的操作接口
*
* @author linyi 2016-08-18
*/
@MyBatisDao
public interface JhjUserDao {
/**
* 保存数据
*
* @param po 要保存的对象
*/
void insert(JhjUserPO po);
/**
* 修改数据,以主键更新
*
* @param po - 要更新的数据
* @return 更新的行数
*/
int update(JhjUserPO po);
/**
* 根据主键读取记录
*/
JhjUserPO get(@Param("jid") long jid);
/**
* 根据用户类型和用户ID读取记录.
*
* @param userType 用户类型,见 {@link com.ibeiliao.pay.api.enums.UserType}
* @param userId 用户ID
* @return
*/
JhjUserPO getByTypeAndUserId(@Param("userType") short userType, @Param("userId") long userId);
}
|
/*
* 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 BasesNumericas;
/**
*
* @author janeth
*/
public class Binario extends OperacionesLogicas {
private int vectorA[];
private int vectorB[];
public void SetVectorA(int[] _vectorA) {
vectorA = _vectorA;
}
public int[] GetetVectorA(int numBinario) {
return vectorA;
}
public void SetVectorB(int[] _vectorB) {
vectorB = _vectorB;
}
public int[] GetetVectorB(int numBinario) {
return vectorB;
}
public int NotBinario(int numBinario) {
vectorA = SepararNum(numBinario);
for (int i = 0; i < vectorA.length; i++) {
vectorA[i] = Not(vectorA[i]);
}
return ConcatenarVector(vectorA);
}
public int AndBinario(int numBinario1, int numBinario2) {
vectorA = SepararNum(numBinario1);
vectorB = SepararNum(numBinario2);
int vector[];
int cond;
if(vectorA.length>vectorB.length){
cond=vectorA.length;
}
else{
cond=vectorB.length;
}
for (int i = 0; i < cond;i++) {
vectorA[i] = And(vectorA[i], vectorB[i]);
}
return ConcatenarVector(vectorA);
}
public int OrBinario(int numBinario1, int numBinario2) {
vectorA = SepararNum(numBinario1);
vectorB = SepararNum(numBinario2);
for (int i = 0; i < vectorA.length; i++) {
vectorA[i] = Or(vectorA[i], vectorB[i]);
}
return ConcatenarVector(vectorA);
}
public int XorBinario(int numBinario1, int numBinario2) {
vectorA = SepararNum(numBinario1);
vectorB = SepararNum(numBinario2);
for (int i = 0; i < vectorA.length; i++) {
vectorA[i] = Xor(vectorA[i], vectorB[i]);
}
return ConcatenarVector(vectorA);
}
public int[] SepararNum(int num) {
String vectorNumString[];
vectorNumString = ("" + num).split("");
int vectorNumInt[] = new int[vectorNumString.length];
for (int i = (vectorNumString.length - 1); i >= 0; i--) {
vectorNumInt[i] = Integer.parseInt(vectorNumString[i]);
}
return vectorNumInt;
}
public int ConcatenarVector(int[] _vector) {
String numConcatenado = "";
for (int i = 0; i < _vector.length; i++) {
numConcatenado += _vector[i];
}
return Integer.parseInt(numConcatenado);
}
public boolean VerificarRestriccionBinario(int numBinario) {
return numBinario <= 11111111;
}
}
|
package Chapter3;
//변수 num의 값보다 크면서도 가장 가까운 10의 배수에서 변수 num의 값을 뺀 나머지를 구하는 코드
//24의 크면서도 가장 가까운 10의 배수는 30
//19의 경우 20, 81의 경우 90
//30에서 24를 뺀 나머지는 6이기 때문에 변수 num의 값이 24라면 6을 결과로 얻어야 한다 ..?
public class Exercise3_6 {
public static void main(String[] args) {
int num = 24;
System.out.println(((num/10)+1)*10 - num);
System.out.println(10 - num%10); //답
}
}
|
package br.com.galgo.testes.suite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import br.com.galgo.testes.recursos_comuns.suite.StopOnFirstFailureSuite;
import br.com.galgo.testes.recursos_comuns.teste.TesteLogin;
@RunWith(StopOnFirstFailureSuite.class)
@Suite.SuiteClasses({ TesteLogin.class })
public class SuiteLogin {
}
|
/**
* Axway Appcelerator Titanium - ti.identity
* Copyright (c) 2017 by Axway. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package ti.identity;
import android.app.KeyguardManager;
import android.content.Context;
import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
import androidx.biometric.BiometricPrompt.AuthenticationCallback;
import androidx.fragment.app.FragmentActivity;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollFunction;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
@Kroll.proxy(creatableInModule = TitaniumIdentityModule.class)
public class KeychainItemProxy extends KrollProxy
{
private static final String TAG = "KeychainItem";
public static final String PROPERTY_IDENTIFIER = "identifier";
public static final String PROPERTY_CIPHER = "cipher";
public static final String PROPERTY_ACCESSIBILITY_MODE = "accessibilityMode";
public static final String PROPERTY_ACCESS_CONTROL_MODE = "accessControlMode";
public static final String EVENT_SAVE = "save";
public static final String EVENT_READ = "read";
public static final String EVENT_UPDATE = "update";
public static final String EVENT_RESET = "reset";
public static final int ACCESSIBLE_ALWAYS = 0;
public static final int ACCESSIBLE_ALWAYS_THIS_DEVICE_ONLY = 1;
public static final int ACCESSIBLE_WHEN_PASSCODE_SET_THIS_DEVICE_ONLY = 2;
public static final int ACCESS_CONTROL_USER_PRESENCE = 1;
public static final int ACCESS_CONTROL_DEVICE_PASSCODE = 2;
public static final int ACCESS_CONTROL_TOUCH_ID_ANY = 4;
public static final int ACCESS_CONTROL_TOUCH_ID_CURRENT_SET = 8;
private KeyStore keyStore;
private SecretKey key;
private Cipher cipher;
private int ivSize = 16;
private BiometricPrompt.CryptoObject cryptoObject;
private String algorithm = KeyProperties.KEY_ALGORITHM_AES;
private String blockMode = KeyProperties.BLOCK_MODE_CBC;
private String padding = KeyProperties.ENCRYPTION_PADDING_PKCS7;
protected BiometricManager biometricManager;
protected BiometricPrompt.PromptInfo biometricPromptInfo;
private BiometricPrompt.AuthenticationCallback authenticationCallback;
private String identifier = "";
private int accessibilityMode = 0;
private int accessControlMode = 0;
private KeyguardManager keyguardManager;
private String suffix = "_kc.dat";
private Context context;
private class EVENT
{
public final String event;
public final String value;
public EVENT(String event, String value)
{
this.event = event;
this.value = value;
}
public EVENT(String event)
{
this.event = event;
this.value = null;
}
}
private List<EVENT> eventQueue = new ArrayList<EVENT>();
private boolean eventBusy = false;
@SuppressWarnings("NewApi")
public KeychainItemProxy()
{
super();
defaultValues.put(PROPERTY_ACCESSIBILITY_MODE, 0);
defaultValues.put(PROPERTY_ACCESS_CONTROL_MODE, 0);
defaultValues.put(PROPERTY_CIPHER, getCipher());
try {
context = TiApplication.getAppRootOrCurrentActivity();
// fingerprint authentication
if (Build.VERSION.SDK_INT >= 23) {
keyguardManager = context.getSystemService(KeyguardManager.class);
biometricManager = BiometricManager.from(context);
authenticationCallback = new AuthenticationCallback() {
@Override
public void onAuthenticationError(int errorCode, CharSequence errString)
{
switch (errorCode) {
case BiometricPrompt.ERROR_USER_CANCELED:
case BiometricPrompt.ERROR_CANCELED:
case BiometricPrompt.ERROR_NEGATIVE_BUTTON:
doEvents(TitaniumIdentityModule.ERROR_AUTHENTICATION_FAILED, errString.toString());
break;
default:
doEvents(errorCode, errString.toString());
}
}
@Override
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result)
{
doEvents(0, null);
}
@Override
public void onAuthenticationFailed()
{
doEvents(TitaniumIdentityModule.ERROR_AUTHENTICATION_FAILED,
"failed to authenticate fingerprint!");
}
};
final BiometricPrompt.PromptInfo.Builder promptInfo = new BiometricPrompt.PromptInfo.Builder();
promptInfo.setTitle(TitaniumIdentityModule.reason);
promptInfo.setSubtitle(TitaniumIdentityModule.reasonSubtitle);
promptInfo.setDescription(TitaniumIdentityModule.reasonText);
promptInfo.setNegativeButtonText(TitaniumIdentityModule.negativeButtonText);
biometricPromptInfo = promptInfo.build();
}
// load Android key store
keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
} catch (Exception e) {
Log.e(TAG, "could not load Android key store: " + e.getMessage());
}
}
@Kroll.getProperty
@Kroll.method
public int getAccessibilityMode()
{
return accessibilityMode;
}
@Kroll.getProperty
@Kroll.method
public int getAccessControlMode()
{
return accessControlMode;
}
@Kroll.getProperty
@Kroll.method
private String getCipher()
{
return algorithm + "/" + blockMode + "/" + padding;
}
@Kroll.getProperty
@Kroll.method
private String getIdentifier()
{
return identifier;
}
private boolean useFingerprintAuthentication()
{
if ((accessControlMode & (ACCESS_CONTROL_TOUCH_ID_ANY | ACCESS_CONTROL_TOUCH_ID_CURRENT_SET)) != 0) {
return true;
}
return false;
}
private void processEvents()
{
if (!eventBusy && !eventQueue.isEmpty()) {
eventBusy = true;
EVENT e = eventQueue.get(0);
KrollDict result = null;
switch (e.event) {
case EVENT_UPDATE:
case EVENT_SAVE:
result = initEncrypt();
break;
case EVENT_READ:
result = initDecrypt();
break;
case EVENT_RESET:
result = doReset();
break;
}
if (result != null) {
fireEvent(e.event, result);
eventQueue.remove(e);
eventBusy = false;
processEvents();
} else if (!useFingerprintAuthentication()) {
doEvents(0, null);
}
}
}
private void doEvents(int errorCode, String message)
{
KrollDict result = null;
if (!eventQueue.isEmpty()) {
EVENT e = eventQueue.get(0);
if (errorCode != 0) {
result = new KrollDict();
result.put("success", false);
result.put("code", errorCode);
result.put("error", message);
} else {
switch (e.event) {
case EVENT_UPDATE:
if (!exists()) {
result = new KrollDict();
result.put("success", false);
result.put("code", -1);
result.put("error", "could not update, item does not exist.");
break;
}
case EVENT_SAVE:
result = doEncrypt(e.value);
break;
case EVENT_READ:
result = doDecrypt();
break;
}
}
if (result != null) {
fireEvent(e.event, result);
}
eventQueue.remove(e);
}
eventBusy = false;
processEvents();
}
@SuppressWarnings("NewApi")
private KrollDict initEncrypt()
{
try {
// initialize encryption cipher
cipher.init(Cipher.ENCRYPT_MODE, key);
// fingerprint authentication
if (biometricManager != null && useFingerprintAuthentication()) {
final Executor executor = Executors.newSingleThreadExecutor();
final BiometricPrompt prompt = new BiometricPrompt(
(FragmentActivity) TiApplication.getAppCurrentActivity(), executor, authenticationCallback);
prompt.authenticate(biometricPromptInfo, cryptoObject);
}
} catch (Exception e) {
KrollDict result = new KrollDict();
result.put("identifier", identifier);
result.put("success", false);
if (e instanceof InvalidKeyException && key == null) {
result.put("code", TitaniumIdentityModule.ERROR_PASSCODE_NOT_SET);
result.put("error", "device is not secure, could not generate key!");
} else if (e instanceof KeyPermanentlyInvalidatedException) {
result.put("code", TitaniumIdentityModule.ERROR_KEY_PERMANENTLY_INVALIDATED);
result.put("error", "key permantently invalidated!");
try {
if (keyStore != null) {
keyStore.deleteEntry(identifier);
}
} catch (Exception ex) {
// do nothing...
}
} else {
result.put("code", -1);
result.put("error", e.getMessage());
}
return result;
}
return null;
}
private KrollDict doEncrypt(String value)
{
KrollDict result = new KrollDict();
result.put("identifier", identifier);
try {
// save encrypted data to private storage
FileOutputStream fos = context.openFileOutput(identifier + suffix, Context.MODE_PRIVATE);
// write IV
fos.write(cipher.getIV());
// write encrypted data
byte[] data = value.getBytes(StandardCharsets.UTF_8);
byte[] encryptedData = cipher.doFinal(data);
fos.write(encryptedData);
// close stream
if (fos != null) {
fos.close();
}
result.put("success", true);
result.put("code", 0);
} catch (Exception e) {
result.put("success", false);
result.put("code", -1);
result.put("error", e.getMessage());
}
return result;
}
@SuppressWarnings("NewApi")
private KrollDict initDecrypt()
{
try {
// load file from private storage
FileInputStream fin = context.openFileInput(identifier + suffix);
// read IV
byte[] iv = new byte[ivSize];
fin.read(iv, 0, iv.length);
// close stream
if (fin != null) {
fin.close();
}
// initialize decryption cipher
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
// fingerprint authentication
if (biometricManager != null && useFingerprintAuthentication()) {
final Executor executor = Executors.newSingleThreadExecutor();
final BiometricPrompt prompt = new BiometricPrompt(
(FragmentActivity) TiApplication.getAppCurrentActivity(), executor, authenticationCallback);
prompt.authenticate(biometricPromptInfo, cryptoObject);
}
} catch (Exception e) {
KrollDict result = new KrollDict();
result.put("identifier", identifier);
result.put("success", false);
result.put("code", -1);
if (e instanceof FileNotFoundException) {
result.put("error", "keychain data does not exist!");
} else if (e instanceof InvalidKeyException && key == null) {
result.put("code", TitaniumIdentityModule.ERROR_PASSCODE_NOT_SET);
result.put("error", "device is not secure, could not generate key!");
} else if (e instanceof KeyPermanentlyInvalidatedException) {
result.put("code", TitaniumIdentityModule.ERROR_KEY_PERMANENTLY_INVALIDATED);
result.put("error", "key permantently invalidated!");
try {
if (keyStore != null) {
keyStore.deleteEntry(identifier);
}
} catch (Exception ex) {
// do nothing...
}
} else {
result.put("error", e.getMessage());
}
return result;
}
return null;
}
private KrollDict doDecrypt()
{
KrollDict result = new KrollDict();
result.put("identifier", identifier);
try {
// load file from private storage
FileInputStream fin = context.openFileInput(identifier + suffix);
fin.skip(ivSize);
// read decrypted data
BufferedInputStream bis = new BufferedInputStream(fin);
CipherInputStream cis = new CipherInputStream(bis, cipher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
String decrypted = "";
// since we only encrypt strings, this is acceptable
while ((length = cis.read(buffer)) != -1) {
// obtain decrypted string from buffer
baos.write(buffer, 0, length);
}
decrypted = new String(baos.toByteArray(), StandardCharsets.UTF_8).replace("\u0000+$", "");
// close stream
if (baos != null) {
baos.close();
}
if (cis != null) {
cis.close();
}
if (bis != null) {
bis.close();
}
if (fin != null) {
fin.close();
}
result.put("success", true);
result.put("code", 0);
result.put("value", decrypted);
} catch (Exception e) {
result.put("success", false);
result.put("code", -1);
if (e instanceof FileNotFoundException) {
result.put("error", "keychain data does not exist!");
} else {
result.put("error", e.getMessage());
}
}
return result;
}
private KrollDict doReset()
{
KrollDict result = new KrollDict();
boolean deleted = false;
// delete file from private storage
File file = context.getFileStreamPath(identifier + suffix);
if (file != null && file.exists()) {
deleted = context.deleteFile(identifier + suffix);
// remove key from Android key store
/*if (deleted) {
try {
keyStore.deleteEntry(identifier);
} catch (Exception e) {
deleted = false;
result.put("error", "could not remove key");
}
} else {*/
if (!deleted) {
result.put("error", "could not delete data");
}
}
result.put("success", deleted);
result.put("code", deleted ? 0 : -1);
return result;
}
private boolean exists()
{
File file = context.getFileStreamPath(identifier + suffix);
return file != null && file.exists();
}
public void resetEvents()
{
eventQueue.clear();
eventBusy = false;
}
@Kroll.method
public void save(String value)
{
eventQueue.add(new EVENT(EVENT_SAVE, value));
processEvents();
}
@Kroll.method
public void read()
{
eventQueue.add(new EVENT(EVENT_READ));
processEvents();
}
@Kroll.method
public void update(String value)
{
eventQueue.add(new EVENT(EVENT_UPDATE, value));
processEvents();
}
@Kroll.method
public void reset()
{
eventQueue.add(new EVENT(EVENT_RESET));
processEvents();
}
@Kroll.method
public void fetchExistence(Object callback)
{
if (callback instanceof KrollFunction) {
KrollDict result = new KrollDict();
result.put("exists", exists());
((KrollFunction) callback).callAsync(krollObject, new Object[] { result });
}
}
@Override
@SuppressWarnings("NewApi")
public void handleCreationDict(KrollDict dict)
{
super.handleCreationDict(dict);
if (dict.containsKey(PROPERTY_CIPHER)) {
String[] cipher = dict.getString(PROPERTY_CIPHER).split("/");
if (cipher.length == 3) {
algorithm = cipher[0];
blockMode = cipher[1];
padding = cipher[2];
// set IV size
ivSize = blockMode == KeyProperties.BLOCK_MODE_GCM ? 12 : 16;
}
}
if (dict.containsKey(PROPERTY_ACCESSIBILITY_MODE)) {
accessibilityMode = dict.getInt(PROPERTY_ACCESSIBILITY_MODE);
}
if (dict.containsKey(PROPERTY_ACCESS_CONTROL_MODE)) {
accessControlMode = dict.getInt(PROPERTY_ACCESS_CONTROL_MODE);
}
if (dict.containsKey(PROPERTY_IDENTIFIER)) {
identifier = dict.getString(PROPERTY_IDENTIFIER);
if (!identifier.isEmpty()) {
try {
if (!keyStore.containsAlias(identifier)) {
KeyGenerator generator = KeyGenerator.getInstance(algorithm, "AndroidKeyStore");
KeyGenParameterSpec.Builder spec =
new KeyGenParameterSpec
.Builder(identifier, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(blockMode)
.setEncryptionPaddings(padding);
if ((accessControlMode & (ACCESS_CONTROL_TOUCH_ID_ANY | ACCESS_CONTROL_TOUCH_ID_CURRENT_SET))
!= 0) {
spec.setUserAuthenticationRequired(true);
}
if ((accessControlMode & ACCESS_CONTROL_TOUCH_ID_CURRENT_SET) != 0
&& Build.VERSION.SDK_INT >= 24) {
spec.setInvalidatedByBiometricEnrollment(true);
}
generator.init(spec.build());
key = generator.generateKey();
} else {
key = (SecretKey) keyStore.getKey(identifier, null);
}
if ((accessControlMode & (ACCESS_CONTROL_USER_PRESENCE | ACCESS_CONTROL_DEVICE_PASSCODE)) != 0
&& !keyguardManager.isDeviceSecure()) {
key = null;
Log.e(TAG, "device is not secure, could not generate key!");
}
cipher = Cipher.getInstance(getCipher());
if (biometricManager != null) {
cryptoObject = new BiometricPrompt.CryptoObject(cipher);
}
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
}
}
@Override
public String getApiName()
{
return "Ti.Identity.KeychainItem";
}
}
|
/**
*/
package com.rockwellcollins.atc.limp;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Boolean Literal Expr</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link com.rockwellcollins.atc.limp.BooleanLiteralExpr#getBoolVal <em>Bool Val</em>}</li>
* </ul>
*
* @see com.rockwellcollins.atc.limp.LimpPackage#getBooleanLiteralExpr()
* @model
* @generated
*/
public interface BooleanLiteralExpr extends Expr
{
/**
* Returns the value of the '<em><b>Bool Val</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Bool Val</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Bool Val</em>' attribute.
* @see #setBoolVal(String)
* @see com.rockwellcollins.atc.limp.LimpPackage#getBooleanLiteralExpr_BoolVal()
* @model
* @generated
*/
String getBoolVal();
/**
* Sets the value of the '{@link com.rockwellcollins.atc.limp.BooleanLiteralExpr#getBoolVal <em>Bool Val</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Bool Val</em>' attribute.
* @see #getBoolVal()
* @generated
*/
void setBoolVal(String value);
} // BooleanLiteralExpr
|
package dev.restservices.controllers;
import java.net.URI;
import java.util.List;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import dev.restservices.exceptions.MoviesServiceException;
import dev.restservices.models.Movie;
import dev.restservices.services.MoviesDataService;
@RestController
public class MoviesController {
private static Logger logger = LoggerFactory.getLogger(MoviesController.class);
@Autowired //Simulating DAO
MoviesDataService moviesService;
@GetMapping(path="/movies")
public ResponseEntity<List<Movie>> getMovies(){
List<Movie> movies = moviesService.getMoviesList();
if(movies == null ){
throw new MoviesServiceException("Couldn't find the list of movies");
}
else if(movies.isEmpty()){
throw new MoviesServiceException("List of movies exist but it's empty!");
}
return new ResponseEntity<List<Movie>>(movies, HttpStatus.OK);
}
@PostMapping(path="/movies")
public ResponseEntity<Void> addMovie(@Valid @RequestBody Movie movie){
Long movieId = movie.getId();
URI newLocation = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(movieId).toUri();
logger.info("Adding new resource at : ", newLocation.toString());
return ResponseEntity.created(newLocation).contentType(MediaType.APPLICATION_JSON).build();
// No communication with the service...
//moviesService.addMovie(newMovie);
}
}
|
public class bola {
private double jari;
private double pi=3.141592;
public bola() {
}
public void setJari(double jari) {
this.jari=jari;
}
public void setPi(double pi){
this.pi=pi;
}
public double getJari(){
return jari;
}
public double getPi(){
return pi;
}
public double getLuas(){
return 4*pi*(Math.pow(jari, 2));
}
public double getVolume(){
return 1.333333333*pi*(Math.pow(jari, 3));
}
}
|
package SelfCheck5;
import java.util.Scanner;
public class FuelControl {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Specify the size of the fuel tank: ");
double fuelCapacity = in.nextDouble();
System.out.print("The following amount of fuel is in the "
+ "fuel tank: ");
double fuelAmount = in.nextDouble();
double fuelLeft = (fuelAmount * 100.0) / fuelCapacity;
final double FUEL_WARNING = 10;
String statusLight = "";
if (fuelLeft < FUEL_WARNING) {
statusLight = "red";
} else {
statusLight = "green";
}
System.out.println("The statusLight for " + fuelAmount + " litres"
+ " of fuel or " + fuelLeft + "% is: " + statusLight);
}
}
|
/**
* ファイル名 : TitleDTO.java
* 作成者 : hung.pd
* 作成日時 : 2018/05/31
* Copyright © 2017-2018 TAU Corporation. All Rights Reserved.
*/
package jp.co.tau.web7.admin.supplier.dto;
import lombok.Getter;
import lombok.Setter;
/**
* <p>ファイル名 : TitleDTO</p>
* <p>説明 : Title DTO</p>
* @author hung.pd
* @since : 2018/05/31
*/
@Getter
@Setter
public class TitleDTO extends BaseDTO {
/** ストックNO */
private String stkNo;
/** 仕入先管理番号 */
private String supplierMngNo;
/** オークション番号 */
private Long tauAucId;
/** 仕入先備考 */
private String supplierRemarks;
}
|
interface Sound{
public void SoundUp(int level);
public void SoundDown(int level);
}
class Tv implements Sound{
private int SndLevel;
Tv{
this
//추상메서드 몸통 구현(level만큼 올라가고 내려가고)
//볼륨이 0보다 작으면 0으로 세팅
}
class Radio implements Sound{
private int SndLevel;
//생성자
//추상메서드 몸통 구현(level만큼 올라가고 내려가고)
//볼륨이 0보다 작으면 0으로 세팅
}
class SoudExam{
public static void main(String ar[]){
Sound radio = new Radio();
Sound tv = new Tv();
radio.SoundUp(5);
tv.SoundUp(5);
}
}
|
package TestingExercises;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class WomenPage extends NavBarPage {
@FindBy(css = "#layered_id_attribute_group_16")
private WebElement yellow;
@FindBy(css = "#list > a > i")
private WebElement listView;
@FindBy(css = "#enabled_filters > ul > li > a > i")
private WebElement removeYellowFilter;
@FindBy(css = "#center_column > ul > li.ajax_block_product.last-line.last-item-of-tablet-line.last-mobile-line.col-xs-12 > div > div > div.right-block.col-xs-4.col-xs-12.col-md-4 > div > div.button-container.col-xs-7.col-md-12 > a.button.ajax_add_to_cart_button.btn.btn-default > span")
private WebElement addToCart;
public void clickYellow(){
yellow.click();
}
public void clickRemoveYellow(){
removeYellowFilter.click();
}
public void clickAddDress2ToCart(){
addToCart.click();
}
public void clickList(){
listView.click();
}
}
|
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class InfoSearchReducer
extends Reducer<Text, IntWritable, Text, IntWritable> { // <k2, v2, k3, v3>
// k2 = reducer key input
// v2 = reducer list of value input for the key
// k3 = reducer key output
// v3 = reducer value output
@Override
public void reduce(Text key, Iterable<IntWritable> values,
Context context)
throws IOException, InterruptedException {
int sum = 0; // Declare and initialize sum integer with value 0
// For the given key iterate through all the values and add up to sum variable
for (IntWritable value : values) {
sum += value.get();
}
context.write(key, new IntWritable(sum));
}
}
|
package com.github.marco9999.directtalk;
import android.widget.TextView;
public class DirectTalkGlobalRefs
{
// App already setup?
private static boolean isSetup = false;
// TextViews
private static TextView lastmessage = null;
private static TextView status = null;
private static TextView host = null;
private static TextView port = null;
// Handler
private static DirectTalkHandlerSub handler = null;
synchronized static void set_lastmessage(TextView _lastmessage)
{
lastmessage = _lastmessage;
}
synchronized static void set_status(TextView _status)
{
status = _status;
}
synchronized static void set_host(TextView _host)
{
host = _host;
}
synchronized static void set_port(TextView _port)
{
port = _port;
}
synchronized static void set_isSetup(boolean _isSetup)
{
isSetup = _isSetup;
}
synchronized static void set_handler(DirectTalkHandlerSub _handler)
{
handler = _handler;
}
synchronized static TextView get_lastmessage()
{
return lastmessage;
}
synchronized static TextView get_status()
{
return status;
}
synchronized static TextView get_host()
{
return host;
}
synchronized static TextView get_port()
{
return port;
}
synchronized static boolean get_isSetup()
{
return isSetup;
}
synchronized static DirectTalkHandlerSub get_handler()
{
return handler;
}
}
|
package io.naztech.Services;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import io.naztech.Dao.StudentDao;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
@AllArgsConstructor
@ToString
@Slf4j
public class Student implements StudentDao {
private static Connection connection = null;
static {
connection = DBCon.getConnection();
}
@Getter
@Setter
private Integer id = null;
@Getter
@Setter
String name = null;
@Getter
@Setter
String created_at = null;
@Getter
@Setter
String updated_at = null;
public Student(String name) {
this.name = name;
}
private Student() {
}
public static Student Search(Integer id) {
Student s044 = new Student();
try {
String insertionQuery = "Select * from student_m044 where id=" + id;
// Connection con=DBCon.getConnection();
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(insertionQuery);
while (result.next()) {
s044.id = Integer.parseInt(result.getString("id"));
s044.name = result.getString("name");
s044.created_at = result.getString("created_at");
s044.updated_at = result.getString("updated_at");
}
return s044;
} catch (Exception e) {
log.error("Search Failed:" + e);
return null;
}
}
public Student Search() {
if (this.id == null) {
log.error("Invalid Sudent Id:Please Insert a Student Id Before Search \n OR Use Static Search Method");
return null;
}
try {
String insertionQuery = "Select * from student_m044 where id=" + this.id;
// Connection con=DBCon.getConnection();
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(insertionQuery);
while (result.next()) {
this.id = Integer.parseInt(result.getString("id"));
this.name = result.getString("name");
this.created_at = result.getString("created_at");
this.updated_at = result.getString("updated_at");
}
} catch (Exception e) {
log.error("Search Failed:" + e);
return null;
}
return this;
}
@Override
public Student insert() {
try {
String insertionQuery = "insert into student_m044(name,created_at,updated_at) output inserted.id,inserted.name,inserted.created_at,inserted.updated_at values ('"
+ this.name + "',GETDATE()," + this.updated_at + ")";
// Connection con=DBCon.getConnection();
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(insertionQuery);
while (result.next()) {
this.id = Integer.parseInt(result.getString("id"));
this.name = result.getString("name");
this.created_at = result.getString("created_at");
this.updated_at = result.getString("updated_at");
}
} catch (Exception e) {
log.error("Insertion Failed:" + e);
return null;
}
return this;
}
@Override
public Student update() {
try {
String insertionQuery = "update student_m044 Set name='" + this.name
+ "',updated_at=GETDATE() output inserted.id,inserted.name,inserted.created_at,inserted.updated_at where id="
+ this.id + "";
// Connection con=DBCon.getConnection();
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(insertionQuery);
while (result.next()) {
this.id = Integer.parseInt(result.getString("id"));
this.name = result.getString("name");
this.created_at = result.getString("created_at");
this.updated_at = result.getString("updated_at");
}
} catch (Exception e) {
log.error("update Failed:" + e);
return null;
}
return this;
}
@Override
public Boolean delete() {
try {
String insertionQuery = "DELETE FROM student_m044 WHERE id=" + this.id + "";
// Connection con=DBCon.getConnection();
Statement statement = connection.createStatement();
int result = statement.executeUpdate(insertionQuery);
if (result == 1) {
this.id = null;
this.name = null;
this.updated_at = null;
this.created_at = null;
return true;
} else
return false;
} catch (Exception e) {
log.error("delete Failed:" + e);
return false;
}
}
public boolean equals(Student obj) {
return (this.created_at.equals(obj.created_at) && this.id.equals(obj.id) && this.name.equals(obj.name)
&& this.updated_at.equals(obj.updated_at) );
}
/*
private Boolean strcom(String x, String y) {
Integer l1 = x.length();
Integer l2 = x.length();
if (l1 != l2) {
return false;
} else {
for (int i = 0; i < l1 / 2; i++) {
if (x.charAt(i) != y.charAt(i) && x.charAt(l1 - 1 - i) == y.charAt(l1 - 1 - i)) {
return false;
}
}
return true;
}
}
*/
}
|
package com.hawk.application.web;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.hawk.application.model.Application;
import com.hawk.application.model.Report;
import com.hawk.application.model.SearchReportVo;
import com.hawk.application.service.ApplicationService;
import com.hawk.application.service.RedisService;
@Controller
public class ReportController extends BaseController {
@Autowired
private RedisService redisService;
@Autowired
private ApplicationService applicationService;
@ModelAttribute("allApplications")
public List<Application> populateAllApplicationTypes() {
List<Application> result = new ArrayList<Application>();
Application all = new Application();
all.setApplicationName("全部");
result.add(all);
result.addAll(applicationService.findAllApplications(getLoginEmail()));
return result;
}
@RequestMapping(value = "/reportNow", method = RequestMethod.GET)
public String initFindNowReport(Map<String, Object> model) {
SearchReportVo searchReportVo = new SearchReportVo.Builder().build();
Date today = new Date();
searchReportVo.setDateFrom(new Date(today.getTime() - 24 * 60 * 60
* 1000));
searchReportVo.setDateTo(today);
List<Report> results = this.redisService.retriveFinancialReport(
getLoginEmail(), searchReportVo);
model.put("searchReportVo", searchReportVo);
model.put("selections", results);
return "report/reportToday";
}
@RequestMapping(value = "/reportNow", method = RequestMethod.POST)
public String processFindNowReport(SearchReportVo searchReportVo,
Map<String, Object> model) {
Date today = new Date();
searchReportVo.setDateFrom(new Date(today.getTime() - 24 * 60 * 60
* 1000));
searchReportVo.setDateTo(today);
List<Report> results = this.redisService.retriveFinancialReport(
getLoginEmail(), searchReportVo);
model.put("selections", results);
return "report/reportToday";
}
@RequestMapping(value = "/reportPast", method = RequestMethod.GET)
public String initFindPastReport(Map<String, Object> model) {
SearchReportVo searchReportVo = new SearchReportVo.Builder().build();
Date today = new Date();
searchReportVo.setDateFrom(new Date(today.getTime() - 7 * 24 * 60 * 60
* 1000));
searchReportVo.setDateTo(today);
List<Report> results = this.redisService.retriveFinancialReport(
getLoginEmail(), searchReportVo);
model.put("searchReportVo", searchReportVo);
model.put("selections", results);
return "report/reportHistory";
}
@RequestMapping(value = "/reportPast", method = RequestMethod.POST)
public String processFindPastReport(SearchReportVo searchReportVo,
Map<String, Object> model) {
List<Report> results = this.redisService.retriveFinancialReport(
getLoginEmail(), searchReportVo);
model.put("selections", results);
return "report/reportHistory";
}
}
|
package ibd.service;
import ibd.persistence.entity.Subcategory;
import ibd.persistence.repository.SubcategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SubcategoryService {
@Autowired
private SubcategoryRepository subcategoryRepository;
public List<Subcategory> findAll(){
return subcategoryRepository.findAll();
}
public void save(Subcategory subcategory) {
subcategoryRepository.save(subcategory);
}
public void remove(Long id) {
subcategoryRepository.delete(id);
}
public Subcategory findOne(Long id) {
return subcategoryRepository.findOne(id);
}
}
|
package com.cg.ibs.im.ui;
import java.util.Scanner;
import com.cg.ibs.im.service.ClientService;
public class InvestmentUI {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println(" Press 1 for customer and 2 for bank representative");
System.out.println("--------------------");
int num= sc.nextInt();
Menu choice = null;
BankMenu option=null;
System.out.println("Enter the userId");
String userId= sc.next();
System.out.println("Enter the password");
String password= sc.next();
ClientService service= new ClientService();
if(num==1){
if(service.isValid(userId, password)){
while (choice != Menu.Quit) {
System.out.println("Choice");
System.out.println("--------------------");
for (Menu menu : Menu.values()) {
System.out.println(menu.ordinal() + "\t" + menu);
}
System.out.println("Choice");
int ordinal = sc.nextInt();
if (ordinal >= 0 && ordinal < Menu.values().length) {
choice = Menu.values()[ordinal];
switch (choice) {
case viewMyInvestment:
service.isValid(userId, password);
break;
case viewGoldPrice:
break;
case viewSilverPrice:
break;
case viewMFplans:
break;
case buyGold:
break;
case sellGold:
break;
case buySilver:
break;
case sellSilver:
break;
case depositMFplan:
break;
case WithdrawMFplan:
break;
case Quit:
System.out.println("thank you for coming");
break;
}
} else {
System.out.println("Invalid Option!!");
choice = null;
}
}}
}
else if(num==2){
while(option!=BankMenu.Quit){
System.out.println("Choice");
System.out.println("--------------------");
for (BankMenu menu : BankMenu.values()) {
System.out.println(menu.ordinal() + "\t" + menu);
}
System.out.println("Choice");
int ordinal = sc.nextInt();
if (ordinal >= 0 && ordinal < BankMenu.values().length) {
option = BankMenu.values()[ordinal];
switch (option) {
case updateGoldPrice:
service.isValid(userId, password);
break;
case updateSilverPrice:
break;
case updateMFplans :
break;
case Quit:
break;
}
sc.close();
}}}}}
|
package Tree;
/**
* @author admin
* @version 1.0.0
* @ClassName IsFullTree.java
* @Description 满二叉树
* 最大深度为l 总结点数 m m = 2^l - 1
* 更好的办法是用左神的树的动态规划 分解为对每棵树都要统计高度和子节点个数(先向左数要,再向右树要)
* @createTime 2021年03月06日 14:31:00
*/
public class IsFullTree {
public static void main(String[] args) {
TreeNode head1 = new TreeNode(1);
head1.left = new TreeNode(2);
head1.right = new TreeNode(3);
head1.left.left = new TreeNode(4);
head1.left.right = new TreeNode(5);
head1.right.left = new TreeNode(6);
head1.right.right = new TreeNode(7);
util.PrintTree.printTree(head1);
System.out.println("该树是满二叉树吗: "+IsFulltree(head1));
TreeNode head2 = new TreeNode(5);
head2.left = new TreeNode(3);
head2.left.left = new TreeNode(2);
head2.left.right = new TreeNode(4);
head2.left.left.left = new TreeNode(1);
head2.right = new TreeNode(7);
head2.right.left = new TreeNode(6);
head2.right.right = new TreeNode(8);
util.PrintTree.printTree(head2);
System.out.println("该树是满二叉树吗: "+IsFulltree(head2));
}
public static boolean IsFulltree(TreeNode root){
if(root == null){
return true;
}
FullReturndata data = process(root); //收集两个树的公共信息,这里是数高度和节点数
//结合题意去判断
return data.nodesNum == (Math.pow(2,data.height ) - 1);
}
//提出递归中所需的公共部分
public static class FullReturndata{
public int height;
public int nodesNum;
//设定一个构造函数
public FullReturndata(int h,int n){
this.height = h;
this.nodesNum = n;
}
}
//递归
public static FullReturndata process(TreeNode root){
if (root == null){
return new FullReturndata(0, 0);
}
FullReturndata leftData = process(root.left);
FullReturndata rightData = process(root.right);
//加工这个递归里的信息
int height = Math.max(leftData.height, rightData.height)+1; //加1是别忘了最头上的root
int nodesNum = leftData.nodesNum + rightData.nodesNum + 1;
return new FullReturndata(height, nodesNum);
}
}
|
package com.fundwit.sys.shikra.user.controller;
import com.fundwit.sys.shikra.email.RawEmailMessage;
import com.fundwit.sys.shikra.email.SmtpServerRule;
import com.fundwit.sys.shikra.user.persistence.repository.IdentityRepository;
import com.fundwit.sys.shikra.user.persistence.repository.UserRepository;
import com.fundwit.sys.shikra.user.pojo.VerifyCodeRequest;
import com.fundwit.sys.shikra.user.service.CaptchaService;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.MediaType;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import javax.mail.MessagingException;
import java.io.IOException;
import java.time.Duration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = {
"spring.mail.host=localhost",
"spring.mail.sender=testSender@qq.com",
"spring.mail.properties.mail.smtp.auth=false",
"spring.mail.properties.mail.smtp.starttls.enable=false",
"spring.mail.properties.mail.smtp.starttls.required=false"
})
public class VerifierControllerTest {
@Rule
public SmtpServerRule smtpServerRule = new SmtpServerRule();
protected WebTestClient client;
@LocalServerPort
private int port;
@Autowired
UserRepository userRepository;
@Autowired
IdentityRepository identityRepository;
@Autowired
private CaptchaService captchaService;
@Autowired
private JavaMailSenderImpl javaMailSender;
@Before
public void setUp() {
this.javaMailSender.setPort(smtpServerRule.getPort());
this.client = WebTestClient.bindToServer().baseUrl("http://localhost:" + this.port)
.responseTimeout(Duration.ofMinutes(5))
//.defaultHeader("")
.build();
}
@Test
public void testVerifier() throws IOException, MessagingException {
VerifyCodeRequest request = new VerifyCodeRequest();
request.setEmail("xxx@test.com");
client.post().uri("/verifier/email")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.syncBody(request).exchange()
.expectStatus().isNoContent();
assertEquals(1, smtpServerRule.getReceivedMails().size());
RawEmailMessage message = smtpServerRule.getReceivedMails().get(0);
assertEquals("xxx@test.com", message.getRecipient());
assertEquals("testSender@qq.com", message.getFrom());
assertEquals("[Shikra] 验证码", message.getSubject());
assertTrue(message.getTextContent().contains("您的验证码为:"));
}
}
|
package com.tencent.recovery;
import android.content.Context;
import com.tencent.recovery.option.CommonOptions;
import com.tencent.recovery.option.CommonOptions.Builder;
import com.tencent.recovery.option.IOptionsCreator;
import com.tencent.recovery.option.ProcessOptions;
import com.tencent.recovery.util.Util;
import com.tencent.recovery.wx.WXConstantsRecovery;
import com.tencent.recovery.wx.service.WXRecoveryHandleService;
import com.tencent.recovery.wx.service.WXRecoveryUploadService;
import com.tencent.recovery.wx.util.FileUtil;
import com.tencent.recovery.wx.util.WXUtil;
import java.io.File;
public class DefaultOptionsCreator implements IOptionsCreator {
private String clientVersion;
public ProcessOptions createProcessOptions(String str, int i) {
return null;
}
public CommonOptions createCommonOptions(Context context) {
Builder builder = new Builder();
builder.vhz = WXRecoveryHandleService.class.getName();
builder.vhA = WXRecoveryUploadService.class.getName();
builder.clientVersion = getClientVersion();
builder.vhv = String.format("http://dldir1.qq.com/weixin/android/recovery-%s.conf", new Object[]{getClientVersion()});
builder.fMk = WXUtil.hp(context);
builder.vhB = true;
builder.vhC = 600000;
builder.vhD = 600000;
return builder.cEZ();
}
private String getClientVersion() {
if (Util.oW(this.clientVersion)) {
File file = new File(WXConstantsRecovery.vhL, "version.info");
if (file.exists()) {
this.clientVersion = FileUtil.W(file);
}
}
if (Util.oW(this.clientVersion)) {
this.clientVersion = "0x26060736";
}
return this.clientVersion;
}
public String toString() {
return String.format("Creator: [ClientVersion=%s]", new Object[]{getClientVersion()});
}
}
|
package com.lubarov.daniel.web.http.parsing;
import com.lubarov.daniel.parsing.ParseResult;
import com.lubarov.daniel.web.http.HttpVersion;
import com.lubarov.daniel.web.http.RequestLine;
import com.lubarov.daniel.web.http.RequestMethod;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.assertEquals;
public class RequestLineParserTest {
private static final RequestLine example1 = new RequestLine.Builder()
.setMethod(RequestMethod.GET)
.setResource("/path/to/resource")
.setHttpVersion(HttpVersion._1_0)
.build();
@Test
public void testTryParse() {
ParseResult<RequestLine> result = RequestLineParser.singleton
.tryParse(example1.toString().getBytes(StandardCharsets.US_ASCII), 0)
.getOrThrow("Could not parse.");
assertEquals(example1.toString().length(), result.getRem());
assertEquals(example1, result.getValue());
}
}
|
package io.github.jorelali.commandapi.api;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
public class CommandAPIMain extends JavaPlugin {
private static Logger logger;
public static Logger getLog() {
return logger;
}
/**
* Configuration wrapper class.
* The config.yml file used by the CommandAPI is only ever read from,
* nothing is ever written to it. That's why there's only getter methods.
*/
public class Config {
//Output registering and unregistering of commands
private final boolean verboseOutput;
//Create a command_registration.json file
private final boolean createDispatcherFile;
public Config(FileConfiguration fileConfig) {
verboseOutput = fileConfig.getBoolean("verbose-outputs");
createDispatcherFile = fileConfig.getBoolean("create-dispatcher-json");
}
public boolean hasVerboseOutput() {
return verboseOutput;
}
public boolean willCreateDispatcherFile() {
return createDispatcherFile;
}
}
private static Config config;
//Gets the instance of Config
public static Config getConfiguration() {
return config;
}
@Override
public void onLoad() {
saveDefaultConfig();
CommandAPIMain.config = new Config(getConfig());
logger = getLogger();
//Instantiate CommandAPI
CommandAPI.getInstance();
}
@Override
public void onEnable() {
//Prevent command registration after server has loaded
Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> {
CommandAPI.canRegister = false;
//Sort out permissions after the server has finished registering them all
CommandAPI.fixPermissions();
}, 0L);
}
}
|
package lab6;
import java.io.File;
import java.io.*;
import java.util.ArrayList;
//Name:Rizwan Ahmad
//Class:BSCS-2B
//Registration:00073
public class File_Crawl {
private WorkQueue Working_que;
static int i = 0;
private class Worker implements Runnable {
private WorkQueue que;
public Worker(WorkQueue q) {
que = q;
}
public void run() {
String Namee;
while ((Namee = que.remove()) != null) {
File File_pointer = new File(Namee);
String entries[] = File_pointer.list();
if (entries == null)
continue;
for (String entry : entries) {
if (entry.compareTo(".") == 0)
continue;
if (entry.compareTo("..") == 0)
continue;
String fn = Namee + "\\" + entry;
System.out.println(fn);
}
}
}
}
public File_Crawl() {
Working_que = new WorkQueue();
}
public Worker createWorker() {
return new Worker(Working_que);
}
// need try ... catch below in case the directory is not legal
public void processDirectory(String dir) {
try{
File File_pointer = new File(dir);
if (File_pointer.isDirectory()) {
String entries[] = File_pointer.list();
if (entries != null)
Working_que.add(dir);
for (String entry : entries) {
String subdir;
if (entry.compareTo(".") == 0)
continue;
if (entry.compareTo("..") == 0)
continue;
if (dir.endsWith("\\"))
subdir = dir+entry;
else
subdir = dir+"\\"+entry;
processDirectory(subdir);
}
}}catch(Exception e){}
}
public static void main(String Args[]) {
File_Crawl fc = new File_Crawl();
// Here are all the threads
int N = 5;
ArrayList<Thread> thread = new ArrayList<Thread>(N);
for (int ai = 0; ai < N; ai++) {
Thread tt = new Thread(fc.createWorker());
thread.add(tt);
tt.start();
}
fc.processDirectory(Args[0]);
// indicating ther are 0 directoriez to ad
fc.Working_que.finish();
for (int ii = 0; ii < N; ii++){
try {
thread.get(ii).join();
} catch (Exception e) {};
}
}
}
|
package problemDomain;
import java.math.BigDecimal;
/**
* A check to pay with
*/
public class Check extends AuthorizedPayment
{
/**
* The routing number of the account of the check
*/
private String routingNumber;
/**
* The account number of the account of the check
*/
private String accountNumber;
/**
* The check number of the check
*/
private String checkNumber;
/**
* The default constructor
*/
public Check()
{
}
/**
* The constructor that initializes the amount, account number, routing number, and check number of the check
* @param amount The amount of the check
* @param accountNumber The account number of the account that the money is coming from
* @param routingNumber The routing number of the account that the money is coming from
* @param checkNumber The check number of the check
*/
public Check(String amount, String accountNumber, String routingNumber, String checkNumber)
{
this.amount = new BigDecimal(amount);
this.accountNumber = accountNumber;
this.routingNumber = routingNumber;
this.checkNumber = checkNumber;
}
/**
* Tell whether the check is authorized
* @return Is the check authorized?
*/
public Boolean isAuthorized()
{
return true;
}
/**
* Calculate the amount of change to give back
* @return the amount of change to give back
*/
public BigDecimal calcChange()
{
return amtTendered.subtract(amount);
}
/**
* Convert the class to a string
* @return The string representation of the class
*/
public String toString()
{
// TODO - implement Check.toString
throw new UnsupportedOperationException();
}
}
|
package com.tencent.mm.plugin.wallet_core.ui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import com.tencent.mm.wallet_core.c.p;
class WalletConfirmCardIDUI$1 implements OnMenuItemClickListener {
final /* synthetic */ WalletConfirmCardIDUI pvp;
WalletConfirmCardIDUI$1(WalletConfirmCardIDUI walletConfirmCardIDUI) {
this.pvp = walletConfirmCardIDUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
p.cDe();
this.pvp.finish();
return false;
}
}
|
package com.countout.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.countout.entity.MessageEntity;
import com.countout.entity.MessageReadLogEntity;
import com.countout.service.MessageReadLogService;
import com.tang.util.page.Page;
/**
* 日志读取记录
* @author Mr.tang
*/
@Controller
@RequestMapping(value = "/messageReadLog")
public class MessageReadLogController {
private final Logger logger = Logger.getLogger(MessageReadLogController.class);
// private Map<String, Object> result = new HashMap<String, Object>();
@Autowired
private MessageReadLogService messageReadLogService;
/**
* 分页查询
* @param request
* @param requestMap
* @return
*/
@ResponseBody
@RequestMapping(value = "/page.do")
public Object pageQuery(HttpServletRequest request, @RequestBody Map<String, Object> requestMap){
Map<String, Object> result = new HashMap<String, Object>();
try {
Page<MessageReadLogEntity> logList = this.messageReadLogService.pageQuery(requestMap);
result.put("logList", logList);
result.put("flg", Boolean.TRUE);
result.put("msg", "日志读取记录分页查询成功");
} catch (Exception e) {
result.put("msg", "查询出现异常!");
result.put("flg", Boolean.FALSE);
logger.error("日志读取记录分页查询异常!"+e);
e.printStackTrace();
}
return result;
}
/**
* 读取消息
* @param request
* @param requestMap
* @return
*/
@ResponseBody
@RequestMapping(value = "/viewMessage")
public Object viewMessage(HttpServletRequest request, @RequestBody Map<String, Object> requestMap){
Map<String, Object> result = new HashMap<String, Object>();
try {
MessageEntity userList = this.messageReadLogService.queryMessage(requestMap);
result.put("userList", userList);
result.put("msg", "消息信息查询成功");
result.put("flg", Boolean.TRUE);
} catch (Exception e) {
result.put("msg", "消息信息查询出现异常!");
result.put("flg", Boolean.FALSE);
logger.error("读取消息出现异常!"+e);
e.printStackTrace();
}
return result;
}
}
|
package com.demo.test.filter;
import com.alibaba.fastjson.JSON;
import com.demo.test.constant.Constant;
import com.demo.test.domain.Student;
import com.demo.test.exception.ApiErrorResponse;
import com.demo.test.exception.GlobalExceptionHandler;
import com.demo.test.utils.TokenUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* 已废弃
* token验证拦截类————在2019/10/07之后该类已废弃
*
* @author Jack
* @version 2.0, use now
* @date 2019/06/02
* @date 2019/10/07 no longer used
*/
@WebFilter(filterName = "tokenAuthorFilter", urlPatterns = "/*")
public class TokenAuthorFilter implements Filter {
static Logger logger = LogManager.getLogger(TokenAuthorFilter.class);
//在这里面填不需要被拦截的地址
private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(
new HashSet<String>(Arrays.asList("/v1/api/students/login", "/v1/api/students/isLogin"
, "/api", "/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs"
, "/webjars/*", "/addStudent", "/loginForMap", "/loginForParams"
, "/test", "/myException", "/byzero", "/druid/login.html", "/druid/*"
, "/swagger-resources/configuration/ui", "/swagger-resources"
, "/swagger-resources/configuration/security"))
);
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rep = (HttpServletResponse) response;
// 设置允许跨域的配置
// 这里填写你允许进行跨域的主机ip(正式上线时可以动态配置具体允许的域名和IP)
rep.setHeader("Access-Control-Allow-Origin", "*");
//允许的访问方法
rep.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
//Access-Control-Max-Age 用于 CORS 相关配置的缓存
rep.setHeader("Access-Control-Max-Age", "3600");
rep.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, " +
"X-App-Id, Token, Content-Length, Authorization");
rep.setHeader("Access-Control-Allow-Credentials", "true");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
// header方式传递token, 实际是signature
String token = req.getHeader("token");
String path = req.getRequestURI().substring(req.getContextPath().length())
.replaceAll("[/]+$", "");
boolean allowedPath = ALLOWED_PATHS.contains(path);
boolean isFilter = false;
ApiErrorResponse apiErrorResponse;
String method = ((HttpServletRequest) request).getMethod();
if (Constant.OPTIONS.equals(method)) {
rep.setStatus(HttpServletResponse.SC_OK);
} else {
if (!allowedPath) {
String msg, code;
if (null != token && token.length() > 0) {
Student student = (Student) req.getSession().getAttribute("currentUser");
if (student != null) {
if (TokenUtils.volidateToken(token, student.getId())) {
msg = "用户授权认证通过!";
code = Constant.SUCCESS;
isFilter = true;
} else {
code = Constant.TOKEN_INVALID;
msg = "客户端请求参数Token验证失败!请重新申请 token!";
logger.error(msg + " {token} : " + token);
}
} else {
code = Constant.NO_LOGIN_USER;
msg = "当前没有用户登录,请重新登录!";
logger.error(msg + " {token} : " + token);
}
} else {
code = Constant.NO_TOKEN;
//msg = "客户端请求无参数token信息, 没有访问权限!";
msg = "用户没有登录, 没有访问权限!";
logger.error(msg + " {token} : " + token);
}
apiErrorResponse = ApiErrorResponse.builder().code(code).message(msg).build();
// 验证失败
String resultCode = apiErrorResponse.getCode();
if (Constant.NO_TOKEN.equals(resultCode)
|| Constant.TOKEN_INVALID.equals(resultCode)
|| Constant.NO_LOGIN_USER.equals(resultCode)) {
try (OutputStreamWriter osw =
new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8);
PrintWriter writer = new PrintWriter(osw, true)) {
String jsonStr = JSON.toJSONString(apiErrorResponse);
writer.write(jsonStr);
writer.flush();
} catch (IOException e) {
logger.error("过滤器返回信息失败,错误:" + GlobalExceptionHandler.buildErrorMessage(e));
}
return;
}
if (isFilter) {
logger.info("token filter OK!");
chain.doFilter(request, response);
}
} else {
//不需要被拦截的方法,直接放行
chain.doFilter(request, response);
}
}
}
@Override
public void init(FilterConfig arg0) {
}
@Override
public void destroy() {
}
}
|
/*
* 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 co.tweetbuy.servlet;
import co.tweetbuy.util.Constants;
import static co.tweetbuy.util.LogIt.logger;
import java.io.IOException;
import java.io.PrintWriter;
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 org.apache.log4j.Level;
import org.apache.log4j.Logger;
/**
*
* @author emrah
*/
@WebServlet(name = "DownloadServlet", urlPatterns = {"/Download"})
public class DownloadServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String lang = request.getParameter("l");
String mail = request.getParameter("m");
Logger logger = Logger.getLogger((new Object()).getClass());
org.apache.log4j.PatternLayout layout = new org.apache.log4j.PatternLayout("%d %-5p %m%n");
org.apache.log4j.RollingFileAppender appender
= new org.apache.log4j.RollingFileAppender(
layout,
Constants.MAIL_TRACKING_LOG_FILE);
appender.setMaxFileSize("10MB");
appender.setMaxBackupIndex(10);
appender.setAppend(true);
logger.addAppender(appender);
logger.setAdditivity(false);
if (Constants.LOG4J_LEVEL == 6) {
logger.setLevel(Level.TRACE);
} else if (Constants.LOG4J_LEVEL == 5) {
logger.setLevel(Level.DEBUG);
} else if (Constants.LOG4J_LEVEL == 4) {
logger.setLevel(Level.INFO);
} else {
logger.setLevel(Level.WARN);
}
logger.info("lang:"+lang+" email:"+mail);
if("tr".equals(lang)){
response.sendRedirect(Constants.CONTEXT_ROOT+"downloads/TweetBuy_Fundraising_Platform_TR.pdf");
} else {
response.sendRedirect(Constants.CONTEXT_ROOT+"downloads/TweetBuy_Fundraising_Platform_EN.pdf");
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.tencent.mm.plugin.traceroute.ui;
import com.tencent.mm.plugin.traceroute.ui.NetworkDiagnoseAllInOneUI.1;
class NetworkDiagnoseAllInOneUI$1$2 implements Runnable {
final /* synthetic */ 1 oDL;
final /* synthetic */ int oDM;
NetworkDiagnoseAllInOneUI$1$2(1 1, int i) {
this.oDL = 1;
this.oDM = i;
}
public final void run() {
this.oDL.oDK.oDy = this.oDM;
this.oDL.oDK.YI();
}
}
|
import javafx.application.Platform;
import javafx.beans.property.FloatProperty;
import javafx.beans.property.SimpleFloatProperty;
import javafx.geometry.Rectangle2D;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import javafx.stage.Screen;
import uk.co.caprica.vlcj.component.DirectMediaPlayerComponent;
import java.nio.ByteBuffer;
/**
* Created by thomasfouan on 16/03/2016.
*/
public class ResizablePlayer {
private ImageView imageView;
private DirectMediaPlayerComponent mediaPlayerComponent;
private WritableImage writableImage;
private Pane playerHolder;
private WritablePixelFormat<ByteBuffer> pixelFormat;
private FloatProperty videoSourceRatioProperty;
public ResizablePlayer(AnchorPane playerContainer) {
// Initialisation of the components
playerHolder = new Pane();
pixelFormat = PixelFormat.getByteBgraPreInstance();
videoSourceRatioProperty = new SimpleFloatProperty(0.4f);
initializeImageView();
mediaPlayerComponent = new CanvasPlayerComponent(writableImage, pixelFormat, videoSourceRatioProperty);
// Add the player pane in the playerContainer
VBox vBox = (VBox) playerContainer.lookup("#playerContainer");
BorderPane playerPane = new BorderPane(playerHolder);
playerPane.setStyle("-fx-background-color: black");
vBox.getChildren().add(0, playerPane);
VBox.setVgrow(playerPane, Priority.ALWAYS);
}
public DirectMediaPlayerComponent getMediaPlayerComponent() {
return mediaPlayerComponent;
}
public Pane getPlayerHolder() {
return playerHolder;
}
/**
* initialize the type of image (size, ratio) to write in the player, accordingly with :
* - the dimensions of the screen
* - and the ratio of the video source
*
* Add listeners on the screen and on the ratio fo the current media.
*/
private void initializeImageView() {
Rectangle2D visualBounds = Screen.getPrimary().getVisualBounds();
writableImage = new WritableImage((int) visualBounds.getWidth(), (int) visualBounds.getHeight());
// Add an imageView in the playerHolder to display each frame of the media
imageView = new ImageView(writableImage);
playerHolder.getChildren().add(imageView);
playerHolder.widthProperty().addListener((observable, oldValue, newValue) -> {
fitImageViewSize(newValue.floatValue(), (float) playerHolder.getHeight());
});
playerHolder.heightProperty().addListener((observable, oldValue, newValue) -> {
fitImageViewSize((float) playerHolder.getWidth(), newValue.floatValue());
});
videoSourceRatioProperty.addListener((observable, oldValue, newValue) -> {
fitImageViewSize((float) playerHolder.getWidth(), (float) playerHolder.getHeight());
});
}
/**
* Set image dimensions to write in the player with the new values width and height.
* @param width
* @param height
*/
private void fitImageViewSize(float width, float height) {
Platform.runLater(() -> {
float fitHeight = videoSourceRatioProperty.get() * width;
if (fitHeight > height) {
imageView.setFitHeight(height);
double fitWidth = height / videoSourceRatioProperty.get();
imageView.setFitWidth(fitWidth);
imageView.setX((width - fitWidth) / 2);
imageView.setY(0);
}
else {
imageView.setFitWidth(width);
imageView.setFitHeight(fitHeight);
imageView.setY((height - fitHeight) / 2);
imageView.setX(0);
}
});
}
}
|
package core;
import java.util.Random;
import ui.Connect4TextConsole;
/**
* Plays a token in a random column from 1 to 7 to simulate an AI.
* This class also will display if the computer won or not.
*
* @author Brendan Brunelle
* @version (version) 3/4/2020
*/
public class Connect4ComputerPlayer {
public static int computerChoice = 0;
static Random rand = new Random();
/**
* Generates a random number from 1 to 7
*/
public static void generateRandom() {
computerChoice = rand.nextInt(7)+1;
}
/**
* Attempts to play a computer move and will use recursion to
* play another column if one can't be played.
*/
public static void playComputerMove() {
generateRandom();
if(!Connect4.dropPiece(Connect4TextConsole.board, computerChoice-1, 'O')) {
playComputerMove();
}else {
if(Connect4.checkWin(Connect4TextConsole.board)) {
System.out.println("The computer has won.");
Connect4TextConsole.printBoard(Connect4TextConsole.board);
Connect4TextConsole.win = true;
}else {
Connect4TextConsole.player = 'X';
}
}
}
}
|
package com.nith.appteam.nimbus2020.Models;
public class Id_Value {
private String value;
private String id;
public Id_Value(String value, String id) {
this.value = value;
this.id = id;
}
public String getValue() {
return value;
}
public String getId() {
return id;
}
}
|
package com.nic.usermanagement.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.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name="bhudhar")
public class BhudharRegistration {
@Id
@Column(name="bhudharid")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="bhudhar_bhudharid_seq")
@SequenceGenerator(name="bhudhar_bhudharid_seq", sequenceName="bhudhar_bhudharid_seq", allocationSize=1)
private Integer bhudharId;
private String propertytaxid;
private String state;
private String village;
private String locality;
private String surveyno;
private String plotno;
private String electricityserviceid;
private String propertyextent;
private String address;
private String district;
private String hamlet;
private String pincode;
private String houseno;
private String flatno;
private String waterid;
private String unitsid;
public Integer getBhudharId() {
return bhudharId;
}
public void setBhudharId(Integer bhudharId) {
this.bhudharId = bhudharId;
}
public String getPropertytaxid() {
return propertytaxid;
}
public void setPropertytaxid(String propertytaxid) {
this.propertytaxid = propertytaxid;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getVillage() {
return village;
}
public void setVillage(String village) {
this.village = village;
}
public String getLocality() {
return locality;
}
public void setLocality(String locality) {
this.locality = locality;
}
public String getSurveyno() {
return surveyno;
}
public void setSurveyno(String surveyno) {
this.surveyno = surveyno;
}
public String getPlotno() {
return plotno;
}
public void setPlotno(String plotno) {
this.plotno = plotno;
}
public String getElectricityserviceid() {
return electricityserviceid;
}
public void setElectricityserviceid(String electricityserviceid) {
this.electricityserviceid = electricityserviceid;
}
public String getPropertyextent() {
return propertyextent;
}
public void setPropertyextent(String propertyextent) {
this.propertyextent = propertyextent;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getHamlet() {
return hamlet;
}
public void setHamlet(String hamlet) {
this.hamlet = hamlet;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getHouseno() {
return houseno;
}
public void setHouseno(String houseno) {
this.houseno = houseno;
}
public String getFlatno() {
return flatno;
}
public void setFlatno(String flatno) {
this.flatno = flatno;
}
public String getWaterid() {
return waterid;
}
public void setWaterid(String waterid) {
this.waterid = waterid;
}
public String getUnitsid() {
return unitsid;
}
public void setUnitsid(String unitsid) {
this.unitsid = unitsid;
}
}
|
package com.arkaces.aces_marketplace_api.reset_password;
import com.arkaces.aces_marketplace_api.error.FieldErrorCodes;
import com.arkaces.aces_marketplace_api.error.ValidatorException;
import com.arkaces.aces_marketplace_api.recaptcha.RecaptchaService;
import com.arkaces.aces_marketplace_api.user.UserEntity;
import com.arkaces.aces_marketplace_api.user.UserRepository;
import lombok.RequiredArgsConstructor;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CreateResetPasswordRequestValidator {
private final EmailValidator emailValidator;
private final RecaptchaService recaptchaService;
private final UserRepository userRepository;
public void validate(CreateResetPasswordRequest createResetPasswordRequest, String clientIp) {
BindingResult bindingResult = new BeanPropertyBindingResult(createResetPasswordRequest, "createResetPasswordRequest");
String emailAddress = createResetPasswordRequest.getEmailAddress();
if (StringUtils.isEmpty(emailAddress)) {
bindingResult.rejectValue("emailAddress", FieldErrorCodes.REQUIRED, "Email address required.");
} else if (! emailValidator.isValid(emailAddress)) {
bindingResult.rejectValue("emailAddress", FieldErrorCodes.INVALID_EMAIL_ADDRESS, "Invalid email address");
} else {
UserEntity userEntity = userRepository.findOneByEmailAddress(emailAddress);
if (userEntity == null) {
bindingResult.rejectValue("emailAddress", FieldErrorCodes.USER_NOT_FOUND_WITH_EMAIL_ADDRESS,
"User not found with the given email address");
}
}
if (StringUtils.isEmpty(createResetPasswordRequest.getRecaptchaCode())) {
bindingResult.rejectValue("recaptchaCode", FieldErrorCodes.REQUIRED, "Recaptcha code required.");
} else {
// validate captcha code
String recaptchaCode = createResetPasswordRequest.getRecaptchaCode();
if (! recaptchaService.isValid(recaptchaCode, clientIp)) {
bindingResult.rejectValue("recaptchaCode", FieldErrorCodes.INVALID_RECAPTCHA_CODE, "Recaptcha code invalid.");
}
}
if (bindingResult.hasErrors()) {
throw new ValidatorException(bindingResult);
}
}
}
|
package com.baizhi.cmfz_mzw.controller;
import com.baizhi.cmfz_mzw.enetity.Menu;
import com.baizhi.cmfz_mzw.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.List;
@RequestMapping("menu")
@RestController
public class MenuController {
@Autowired
private MenuService menuService;
@RequestMapping("selectAll")
public List<Menu> selectAll(HttpSession session){
return menuService.selectAll();
}
}
|
package com.fileUploader;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class getFileFromReact
*/
public class getFileFromReact extends HttpServlet {
private static final long serialVersionUID = 1L;
//private static final String UPLOAD_DIRECTORY = "/usr/local/apache2/htdocs/firmware";
private static final String UPLOAD_DIRECTORY = "D:/temp/WEB_UPLOADS";
private String filePath = "";
private String failedResult = "";
/**
* @see HttpServlet#HttpServlet()
*/
public getFileFromReact() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try
{
System.out.println("In Post Method.");
if (!ServletFileUpload.isMultipartContent(request))
{
PrintWriter writer = response.getWriter();
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
writer.println("{\"msg\": \"Request does not contain upload data\"}");
System.out.println("Request does not contain upload data.");
writer.flush();
return;
}
System.out.println("MultipartContent detected.");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(3145728);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(41943040L);
upload.setSizeMax(52428800L);
File uploadDir = new File(UPLOAD_DIRECTORY);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try
{
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
while (iter.hasNext())
{
FileItem item = (FileItem)iter.next();
if (!item.isFormField())
{
String fileName = new File(item.getName()).getName();
System.out.println("File Name: " + fileName);
this.filePath = (UPLOAD_DIRECTORY + File.separator + fileName + new Date().getTime());
File storeFile = new File(this.filePath);
item.write(storeFile);
}
}
if ("".equals(this.failedResult)) {
response.setStatus(HttpServletResponse.SC_CREATED);
PrintWriter writer = response.getWriter();
writer.println("{\"msg\": \"Upload has been done successfully!\"}");
System.out.println("Upload has been done successfully!");
writer.flush();
return;
} else {
request.setAttribute("message", "<h2>The below records failed to insert:</h2> <br/><table border=0><tr><td> MAKE </td> <td> MODEL</td><td> GT </td><td> LT</td> <td>RESOURCE_PATH</td></tr>" + this.failedResult + "</table>");
}
}
catch (Exception ex)
{
request.setAttribute("message", "There was an error: " + ex.getMessage());
}
}
catch (Exception e)
{
System.out.println("error " + e);
}
PrintWriter writer = response.getWriter();
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
writer.println("{\"msg\": \"Failed to parse the file!\"}");
System.out.println("Failed to parse the file!");
writer.flush();
return;
}
}
|
package com.tencent.mm.plugin.ipcall.a;
import com.tencent.mm.sdk.platformtools.x;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public final class f {
private static Map<Integer, List<Integer>> kor = new HashMap();
public int mCurrentState = -1;
public final boolean rv(int i) {
int i2 = this.mCurrentState == -1 ? 1 : (kor.containsKey(Integer.valueOf(this.mCurrentState)) && ((List) kor.get(Integer.valueOf(this.mCurrentState))).contains(Integer.valueOf(i))) ? 1 : 0;
if (i2 != 0) {
x.i("MicroMsg.IPCallStateIndicator", "updateState, origin: %s, new: %s", new Object[]{stateToString(this.mCurrentState), stateToString(i)});
this.mCurrentState = i;
return true;
}
x.i("MicroMsg.IPCallStateIndicator", "transform state error, origin state: %s, new state: %s", new Object[]{stateToString(i.aXt().mCurrentState), stateToString(i)});
return false;
}
public final boolean aXj() {
return this.mCurrentState == 1 || this.mCurrentState == 3 || this.mCurrentState == 4 || this.mCurrentState == 5;
}
public final boolean aXk() {
return this.mCurrentState == 4 || this.mCurrentState == 5;
}
public final boolean aXl() {
return this.mCurrentState == 5;
}
public final boolean aXm() {
return this.mCurrentState == 5;
}
public static String stateToString(int i) {
switch (i) {
case -1:
return "RESET_STATE";
case 1:
return "START_INVITE";
case 2:
return "INVITE_FAILED";
case 3:
return "INVITE_SUCCESS";
case 4:
return "RING_ING";
case 5:
return "USER_ACCEPT";
case 8:
return "USER_CANCEL";
case 9:
return "USER_SELF_SHUTDOWN";
case 10:
return "OTHER_SIDE_USER_SHUTDOWN";
case 11:
return "USER_SELF_SHUTDOWN_BY_ERR";
case 12:
return "CANCEL_BY_ERR";
default:
return String.valueOf(i);
}
}
static {
List arrayList = new ArrayList();
arrayList.add(Integer.valueOf(3));
arrayList.add(Integer.valueOf(2));
arrayList.add(Integer.valueOf(8));
arrayList.add(Integer.valueOf(12));
kor.put(Integer.valueOf(1), arrayList);
arrayList = new ArrayList();
arrayList.add(Integer.valueOf(12));
arrayList.add(Integer.valueOf(8));
kor.put(Integer.valueOf(2), arrayList);
arrayList = new ArrayList();
arrayList.add(Integer.valueOf(4));
arrayList.add(Integer.valueOf(5));
arrayList.add(Integer.valueOf(8));
arrayList.add(Integer.valueOf(12));
kor.put(Integer.valueOf(3), arrayList);
arrayList = new ArrayList();
arrayList.add(Integer.valueOf(5));
arrayList.add(Integer.valueOf(8));
arrayList.add(Integer.valueOf(12));
kor.put(Integer.valueOf(4), arrayList);
arrayList = new ArrayList();
arrayList.add(Integer.valueOf(9));
arrayList.add(Integer.valueOf(10));
arrayList.add(Integer.valueOf(11));
kor.put(Integer.valueOf(5), arrayList);
}
}
|
package web;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class MyListener implements ServletRequestListener,
ServletRequestAttributeListener{
//tomcat销毁request前自动调用此方法
public void requestDestroyed(ServletRequestEvent e) {
System.out.println("销毁request");
}
//tomcat创建request后自动调用此方法
public void requestInitialized(ServletRequestEvent e) {
System.out.println("创建request");
System.out.println(e.getServletRequest());
}
public void attributeAdded(ServletRequestAttributeEvent srae) {
System.out.println("向request内添加一个值");
}
public void attributeRemoved(ServletRequestAttributeEvent srae) {
}
public void attributeReplaced(ServletRequestAttributeEvent srae) {
}
}
|
package collage.controller.check;
public class Status {
private String message;
private double persent;
}
|
package com.example.myapplication;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.Key;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.crypto.spec.SecretKeySpec;
public class SysData {
//仪器的参数
static int shuiyangStep = 65; //水样泵旋转圈数
static double shuiyangVolume = 100.0; //水样的液体体积
static int liusuanStep = 3200; //加硫酸的步数
static double liusuanVolume = 5.0; //加硫酸的体积
static int caosuannaStep = 5200; //加草酸钠的步数
static double caosuannaVolume = 10.0; //加草酸钠的体积
static int gaomengsuanjiaStep = 5200; //加高锰酸钾的步数
static double gaomengsuanjiaVolume = 10.0; //加高锰酸钾的体积
static double xiaojieTemp = 92; //消解温度
static int xiaojieTime = 1500; //消解时长
static int didingStep = 50; //每滴滴定步数
static double didingVolume = 0.1; //每滴滴定体积
static int didingNum = 0; //滴定的滴数
static int didingMax = 400; //最大滴数,计量标定-100,默认值-400
static int didingDifference = 20; //滴定时模拟量下降的值大于这个差值判定为滴定终点
static double didingSumVolume = 0; //滴定的总体积
static double kongbaiValue = 0.25; //空白实验滴定高锰酸钾的量
static double biaodingValue = 10.0; //标定实验滴定高锰酸钾的量
static double caosuannaCon = 0.01; //草酸钠的浓度
static double codValue = 0; //测定的cod值
static int didingDeviation = 720; //开始滴定到出液体需要的步数
static double originalValue = 0; //校准前的cod值
static double newValue = 0; //校准后的cod值
static double coefficient = 1.0; //标定系数K值
static double calibrationMin= 9.5; //标定最小滴定值
static double calibrationMax= 11.0; //标定最大滴定值
static boolean calibrationResult = true; //校准结果
static double ccf = 1.0; //浓度修正因子,0.01浓度值为1.0,0.025浓度值为0.97
static double slopeA = 1.0; //斜率
static double interceptB = 0; //截距
static double trueValue = 0; //真实值
static boolean isCorrection = true; //计算结果是否修正
//仪器运行状态
static boolean isGetNetTime = false; //是否已经获取到网络时间
static boolean isRun = false; //仪器是否运行
static int progressRate = 0; //分析进度
static String statusMsg = ""; //仪器当前执行动作
static double tempIn, tempOut; //温度值,in反应器内温度,out加热器温度
static int adLight, adBack; //adLight光电值,adBack备用模拟量
static double smaAdLight; //adLight光电值的滑动平均值
static byte[] Pump = new byte[10]; //记录各泵的状态,十六进制数据,0x00-状态正常,0x01-帧错误,0x02-参数错误,0x03-光耦错误,0x04-电机忙,0xfe-任务挂起,0xff-未知错误
static int startAdLight; //存储滴定前的光电值
static String errorMsg = ""; //记录仪器出错信息
static String[] errorMsgList = {"无报警", "加水样出错", "加硫酸出错", "加高锰酸钾出错", "加草酸钠出错", "滴定超量", "测定超时", "反应器温度过高", "注射泵故障", "试剂量低", "主板温度过高", "主板无法访问"};
static int errorId = 0; //仪表出错代码 1-加水样出错,2-加硫酸出错,3-加高锰酸钾出错,4-加草酸钠出错,5-滴定超量,6-测定超时,7-反应器温度过高,8-注射泵故障, 9-试剂量低, 10-主板温度过高, 11-访问系统时间出错
static long startXiaojie; //消解开始时间
static long endXiaoJie; //消解结束时间
static int jiaoBanType = 0; //搅拌方式 0-停止搅拌,1-间歇搅拌,2-持续搅拌
static long startTime; //测定开始时间
static long endTime; //测定结束时间
static String workType = "水样分析"; //仪表工作类型 水样分析、标样测定、仪表校准、仪表复位
static String workFrom = "未知"; //启动分析命令来自于 触摸屏、串口、Web、定时启动
static double tempBox; //主板温度 DS3231芯片温度
static int ds3231Error = 0; //访问芯片DS3231出错的次数
static boolean isSaveLog = false; //是否保存运行日志
static boolean resetP2 = false; //是否复位P2注射泵
static boolean resetP3 = false; //是否复位P3注射泵
//系统参数
static String httpAddr = ""; //http访问地址
static String wifiIpAddr = ""; //无线网络ip地址
static String[] localIpAddr; //可用网络ip地址
static String webIPAddr = "0.0.0.0"; //web服务ip地址
static int webPort = 8080; //web服务端口
static String wifiSsid = ""; //无线网络ssid
static String wifiPass = ""; //无线网络密码
static boolean restartWebFlag = false; //是否需要重启web服务
static boolean webServiceFlag = false; //web服务是否启动
static boolean stopFlag = false; //紧急停止
static boolean isLoop = false; //是否循环运行
static long nextStartTime = 0; //下次启动时间
static int startCycle = 1; //启动周期
static int numberTimes = 0; //启动次数
static int startType = 0; //定时启动的类型:0-空; 1-水质测定; 2-标样测定; 3-仪表校准
static boolean isUpdateAutoRun = false; //是否需要更新自动启动信息
static boolean isUpdatnetwork = false; //是否需要更新网络信息
static String adminUsername = "admin"; //管理员用户名
static String adminPassword = "nsy218"; //管理员密码
static List<String> deviceList; //串口通讯名称列表
static int BAUD_RATE = 9600; //外部串口通讯波特率
static int DATA_BITS = 8; //外部串口通讯数据位
static int STOP_BITS = 1; //外部串口通讯停止位
static int MODBUS_ADDR = 3; //MODBUS地址位
static boolean isUpdateCom1 = false; //是否需要更新串口参数
static int updateNum = 3; //界面更新次数
static String version = "1.0"; //软件版本
//数据查询结果
static List<Result> results = null; //仪表测定结果数据
static List<Result> resultChart = null; //仪表趋势线图测定结果数据
static List<AlertLog> alertLogs = null; //仪表报警记录数据
static List<Calibration> calibrations = null; //仪表校准记录数据
static String listDataType = "codmn"; //查询的数据类型,codmn,alert,calibration
//数据查询结果分页
static int currentPage = 1; //当前浏览的页码
static int countData = 0; //数据的总条数
static int numPerpage = 7; //每页的数据条数
static int maxPage = 1; //最大页数
static long startDataTime = 0; //查询起始时间
static long endDataTime = 0; //查询结束时间
//仪器控制页面状态
static boolean statusD1 = false; //D1状态
static boolean statusD2 = false; //D2状态
static boolean statusD3 = false; //D3状态
static boolean statusD4 = false; //D4状态
static boolean statusD5 = false; //D5状态
static boolean statusD6 = false; //D6状态
static boolean statusD7 = false; //D7状态
static boolean statusD8 = false; //D8状态
static boolean statusD9 = false; //D9状态
static boolean statusD10 = false; //D10状态
static boolean statusD11 = false; //D11状态
static boolean statusD12 = false; //D12状态
static boolean statusD35 = false; //D35状态
static boolean statusD24EN = false; //D24EN状态
//仪器的试剂状态
static boolean isEmptyPipeline = false; //测定前是否清空取样管内的液体
static boolean isNotice = false; //试剂量低是否报警
static boolean liusuanStatus; //硫酸试剂量,true-有试剂,false-无试剂
static boolean gaomengsuanjiaStatus; //高锰酸钾试剂量,true-有试剂,false-无试剂
static boolean caosuannaStatus; //草酸钠试剂量,true-有试剂,false-无试剂
static boolean zhengliushuiStatus; //蒸馏水试剂量,true-有试剂,false-无试剂
//计算COD的值
public static double calculationValue() {
//不同试剂浓度影响因子
if(caosuannaCon == 0.025) {
ccf = 0.975; //0.025浓度的试剂修正值
} else {
ccf = 1.00; //0.01浓度的试剂修正值
}
//计算CODMn的值
double k = caosuannaVolume / biaodingValue;
didingSumVolume = didingNum * didingVolume;
didingSumVolume = (double)Math.round(didingSumVolume*1000)/1000; //取小数点后三位
codValue = ((gaomengsuanjiaVolume + didingSumVolume) * k * ccf - caosuannaVolume) * caosuannaCon * 8 * 1000 / shuiyangVolume;
codValue = (double)Math.round(codValue*100)/100;
//用斜率截距计算修正值
if(isCorrection) {
trueValue = codValue;
slopeA = (double)Math.round(slopeA*1000)/1000;
interceptB = (double)Math.round(interceptB*1000)/1000;
codValue = (slopeA * codValue) + interceptB;
}
//取小数点后两位
codValue = (double)Math.round(codValue*100)/100;
//数据检查,异常数据修正
if(codValue < 0) {
codValue = 0; //当测定值小于0时,返回0
} else if (codValue > 25) {
codValue = 25; //当测定值大于25时,返回25
}
//返回COD值
return codValue;
}
//计算校准后的新值
public static double calibrationValue() {
double orgDidingVolume = didingSumVolume;
didingSumVolume = didingNum * didingVolume;
didingSumVolume = (double)Math.round(didingSumVolume*100)/100; //取小数点后两位
originalValue = ((gaomengsuanjiaVolume + orgDidingVolume) * 1 - caosuannaVolume) * caosuannaCon * 8 * 1000 / shuiyangVolume;
originalValue = (double) Math.round(originalValue * 100) / 100; //取小数点后两位
if(didingSumVolume >= calibrationMin && didingSumVolume <= calibrationMax) {
biaodingValue = didingSumVolume;
coefficient = caosuannaVolume / didingSumVolume;
// originalValue = ((gaomengsuanjiaVolume + orgDidingVolume) * 1 - caosuannaVolume) * caosuannaCon * 8 * 1000 / shuiyangVolume;
// originalValue = (double) Math.round(originalValue * 100) / 100; //取小数点后两位
newValue = ((gaomengsuanjiaVolume + orgDidingVolume) * coefficient - caosuannaVolume) * caosuannaCon * 8 * 1000 / shuiyangVolume;
newValue = (double) Math.round(newValue * 100) / 100; //取小数点后两位
calibrationResult = true;
}else {
// originalValue = ((gaomengsuanjiaVolume + orgDidingVolume) * 1 - caosuannaVolume) * caosuannaCon * 8 * 1000 / shuiyangVolume;
// originalValue = (double) Math.round(originalValue * 100) / 100; //取小数点后两位
newValue = codValue;
calibrationResult = false;
}
return newValue;
}
//保存测定值数据至数据库
public static void saveDataToDB() {
Log.i("数据库", "添加测定结果数据");
new Thread(new Runnable() {
@Override
public void run() {
Result result = new Result();
result.dateTime = startTime;
result.dataType = "COD";
result.dataValue = codValue;
MainActivity.db.resultDao().insert(result);
MainActivity.db.calibrationDao().deleteById(16); //删除16号校准数据
}
}).start();
}
//保存校准数据至数据库
public static void saveCalibrationDataToDB() {
Log.i("数据库", "添加校准数据");
new Thread(new Runnable() {
@Override
public void run() {
Calibration calibration = new Calibration();
calibration.dateTime = startTime;
calibration.byValue = originalValue;
calibration.csnValue = caosuannaVolume;
calibration.gmsjValue = didingSumVolume;
if(didingSumVolume != 0) {
coefficient = (double) Math.round(caosuannaVolume / didingSumVolume * 100) / 100; //取小数点后两位
calibration.coefficient = coefficient;
} else {
calibration.coefficient = 1.0;
}
calibration.newValue = newValue;
MainActivity.db.calibrationDao().insert(calibration);
}
}).start();
}
//保存报警记录数据至数据库
public static void saveAlertToDB() {
Log.i("数据库", "添加报警信息数据");
new Thread(new Runnable() {
@Override
public void run() {
AlertLog alertLog = new AlertLog();
alertLog.alertTime = System.currentTimeMillis();
alertLog.errorId = errorId;
alertLog.errorMsg = errorMsg;
alertLog.resetFlag = 0;
alertLog.resetTime = null;
MainActivity.db.alertLogDao().insert(alertLog);
}
}).start();
}
//从数据库读取曲线数据
public static void readChartData(final int num, final int start) {
Log.i("数据库", "读取趋势线数据");
new Thread(new Runnable() {
@Override
public void run() {
SysData.resultChart = MainActivity.db.resultDao().getNum(num, start); //从数据库中读取30条数据
}
}).start();
}
//从数据库读取数据
public static void readData(final int num, final int start) {
Log.i("数据库", "读取数据");
new Thread(new Runnable() {
@Override
public void run() {
if(listDataType.equals("codmn")) {
List<Result> rss;
countData = MainActivity.db.resultDao().findResultCount();
maxPage = countData / numPerpage + 1;
rss = MainActivity.db.resultDao().getNum(num, start);
results = rss;
}
if(listDataType.equals("alert")) {
List<AlertLog> rss;
countData = MainActivity.db.alertLogDao().findAlertLogCount();
maxPage = countData / numPerpage + 1;
rss = MainActivity.db.alertLogDao().getNum(num, start);
alertLogs = rss;
}
if(listDataType.equals("calibration")) {
List<Calibration> rss;
countData = MainActivity.db.calibrationDao().findCalibrationCount();
maxPage = countData / numPerpage + 1;
rss = MainActivity.db.calibrationDao().getNum(num, start);
calibrations = rss;
}
}
}).start();
}
//复位报警记录
public static void resetAlert() {
Log.i("数据库", "更新报警信息数据");
new Thread(new Runnable() {
@Override
public void run() {
MainActivity.db.alertLogDao().updateByFlag(System.currentTimeMillis());
Log.i("更新数据库", "resetTime:" + System.currentTimeMillis());
}
}).start();
}
//删除一条校准记录
public static void delDataFromCalibration(final int id) {
Log.i("数据库", "删除一条校准记录");
new Thread(new Runnable() {
@Override
public void run() {
MainActivity.db.calibrationDao().deleteById(id); //删除16号校准数据
}
}).start();
}
}
|
package com.mysql.cj.protocol.x;
import com.mysql.cj.protocol.Message;
import com.mysql.cj.protocol.ProtocolEntityFactory;
public class NoticeFactory implements ProtocolEntityFactory<Notice, XMessage> {
public Notice createFromMessage(XMessage message) {
return Notice.getInstance(message);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\protocol\x\NoticeFactory.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.tencent.mm.plugin.order.ui;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.style.StrikethroughSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.tencent.mm.plugin.order.model.i;
import com.tencent.mm.plugin.order.ui.MallOrderRecordListUI.b;
import com.tencent.mm.plugin.wxpay.a;
import com.tencent.mm.plugin.wxpay.a.c;
import com.tencent.mm.plugin.wxpay.a.f;
import com.tencent.mm.plugin.wxpay.a.g;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.wallet_core.ui.e;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
protected class MallOrderRecordListUI$a extends BaseAdapter {
final /* synthetic */ MallOrderRecordListUI lPQ;
protected MallOrderRecordListUI$a(MallOrderRecordListUI mallOrderRecordListUI) {
this.lPQ = mallOrderRecordListUI;
}
public final int getCount() {
return this.lPQ.lPM.size();
}
private i uv(int i) {
return (i) this.lPQ.lPM.get(i);
}
public final long getItemId(int i) {
return (long) i;
}
public final View getView(int i, View view, ViewGroup viewGroup) {
b bVar;
String dj;
if (view == null) {
view = View.inflate(this.lPQ, g.mall_order_list_item, null);
bVar = new b(this.lPQ, (byte) 0);
bVar.lPS = (TextView) view.findViewById(f.order_list_item_title_tv);
bVar.lPU = (TextView) view.findViewById(f.order_list_item_time_tv);
bVar.lPT = (TextView) view.findViewById(f.order_list_item_status_tv);
bVar.lPV = (TextView) view.findViewById(f.order_list_item_product_price_tv);
bVar.lPX = view.findViewById(f.order_list_item_month_view);
bVar.lPY = (TextView) view.findViewById(f.order_list_item_month_view_date);
bVar.lPZ = (TextView) view.findViewById(f.order_list_item_month_view_amount);
bVar.lPW = (TextView) view.findViewById(f.order_list_item_product_real_pay_tv);
view.setTag(bVar);
} else {
bVar = (b) view.getTag();
}
i uv = uv(i);
Object obj = null;
if (i == 0) {
obj = 1;
i uv2 = uv(0);
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTimeInMillis(((long) uv2.lOH) * 1000);
dj = MallOrderRecordListUI.dj(gregorianCalendar.get(1), gregorianCalendar.get(2) + 1);
} else {
i uv3 = uv(i);
i uv4 = uv(i - 1);
if (uv3.lOH > 0 && uv4.lOH > 0) {
GregorianCalendar gregorianCalendar2 = new GregorianCalendar();
gregorianCalendar2.setTimeInMillis(((long) uv4.lOH) * 1000);
GregorianCalendar gregorianCalendar3 = new GregorianCalendar();
gregorianCalendar3.setTimeInMillis(((long) uv3.lOH) * 1000);
if (!(gregorianCalendar2.get(1) == gregorianCalendar3.get(1) && gregorianCalendar2.get(2) == gregorianCalendar3.get(2))) {
obj = 1;
dj = MallOrderRecordListUI.dj(gregorianCalendar3.get(1), gregorianCalendar3.get(2) + 1);
}
}
dj = null;
}
if (obj != null) {
bVar.lPY.setText(new SimpleDateFormat(this.lPQ.getString(a.i.fmt_year_month, new Object[]{""})).format(new Date(((long) uv(i).lOH) * 1000)));
if (!(bi.oW(dj) || bi.oW((String) this.lPQ.lPP.get(dj)))) {
bVar.lPZ.setText((CharSequence) this.lPQ.lPP.get(dj));
}
bVar.lPX.setVisibility(0);
} else {
bVar.lPX.setVisibility(8);
}
bVar.lPS.setText(uv.lOG);
bVar.lPT.setText(uv.lOI);
int color = this.lPQ.mController.tml.getResources().getColor(c.mall_order_detail_item_subtitle_color);
if (!bi.oW(uv.lOU)) {
try {
color = Color.parseColor(uv.lOU);
} catch (Exception e) {
x.w("MicroMsg.WalletOrderListUI", "Parse color exp. colortext=" + bi.oV(uv.lOU));
}
}
bVar.lPT.setTextColor(color);
bVar.lPU.setText(this.lPQ.uu(uv.lOH));
color = this.lPQ.mController.tml.getResources().getColor(c.mall_order_detail_item_title_color);
if (!bi.oW(uv.lOV)) {
try {
color = Color.parseColor(uv.lOV);
} catch (Exception e2) {
x.w("MicroMsg.WalletOrderListUI", "Parse color exp. colortext=" + bi.oV(uv.lOV));
}
}
if (uv.lOF != uv.lOW) {
Object e3 = e.e(uv.lOF / 100.0d, uv.lOK);
CharSequence spannableString = new SpannableString(e3);
spannableString.setSpan(new StrikethroughSpan(), 0, e3.length(), 33);
bVar.lPV.setText(spannableString);
} else {
bVar.lPV.setText("");
}
bVar.lPW.setTextColor(color);
bVar.lPW.setText(e.e(uv.lOW / 100.0d, uv.lOK));
return view;
}
}
|
package com.tencent.d.b.f;
class f$1 implements Runnable {
final /* synthetic */ d vmy;
final /* synthetic */ f vmz;
f$1(f fVar, d dVar) {
this.vmz = fVar;
this.vmy = dVar;
}
public final void run() {
this.vmy.execute();
}
}
|
package ui;
import korisnici.Osoba;
import java.awt.*;
import javax.swing.*;
import javax.xml.stream.Location;
public class KorisnickiEkran extends JPanel {
private JPanel panel1;
private JButton naruciVoznjuTelefonomButton;
private JButton istorijaVoznjiButton;
private JButton naruciVoznjuAplikacijomButton;
private JLabel ime;
private JPanel panelSlike;
public KorisnickiEkran(Osoba prijavljeniKorisnik) {
panel1.setSize(100, 200);
panel1.setLocation(400, 400);
add(panel1);
ime.setText("Dobrodosli: " + prijavljeniKorisnik.getIme());
}
}
|
package collection.sets.task2;
import java.util.Arrays;
import java.util.List;
public class Application {
private final static List<Order> initOrder() {
return Arrays.asList(
new Order("xxz", 1),
new Order("xxz", 1),
new Order("xsz", 3),
new Order("xaz", 4),
new Order("xoz", 5),
new Order("xoz", 5),
new Order("xxz", 7),
new Order("xxz", 7)
);
}
public static void main (String[] args) {
new OrdersGenerator(initOrder()).hashSetCreator();
}
}
|
package no.fint.provider.fiks.utils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.text.lookup.StringLookup;
import java.lang.reflect.InvocationTargetException;
public class BeanPropertyLookup<T> implements StringLookup {
private final T bean;
public BeanPropertyLookup(T bean) {
this.bean = bean;
}
@Override
public String lookup(String key) {
try {
return String.valueOf(PropertyUtils.getProperty(bean, key));
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
|
package it.geek.annunci.util;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.struts.util.LabelValueBean;
import org.springframework.jdbc.core.RowMapper;
public class CollezioniRowMapper implements RowMapper<LabelValueBean>{
public LabelValueBean mapRow(ResultSet rs, int rowNum) throws SQLException {
String value = rs.getString(1);
String label = rs.getString(2);
LabelValueBean l = new LabelValueBean(label,value);
return l;
}
}
|
/**
*
*/
package etc;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import site.com.google.anywaywrite.util.file.BgFileUtil;
/**
* @author y-kitajima
*
*/
public class SqlViewer extends JFrame {
List<String> texts = new ArrayList<String>();
private String sqlFilePath = "C:\\Users\\y-kitajima.DSOL.000\\Desktop\\BOM2.txt";
public SqlViewer() {
List<String> txts = BgFileUtil
.readTextList(new File(sqlFilePath), "sjis");
List<SqlStmt> stmts = getSqlStmts(txts);
CardLayout cl = new CardLayout();
JPanel cardPanel = new JPanel();
cardPanel.setLayout(cl);
int no = 0;
for (SqlStmt stmt : stmts) {
no++;
JPanel panel = new JPanel();
JScrollPane scp = new JScrollPane();
JTextArea area = new JTextArea();
for (String line : stmt.getLines()) {
area.append(line);
area.append("\n");
}
scp.setViewportView(area);
panel.add(scp);
cardPanel.add(panel, "sql" + no);
}
getContentPane().add(cardPanel, BorderLayout.CENTER);
// if (stmts.size() > 0) {
// cl.show(this, "sql1");
// }
}
private static class SqlStmt {
private List<String> lines;
private List<Integer> indexes;
private List<String> getLines() {
if (lines == null) {
lines = new ArrayList<String>();
}
return lines;
}
private List<Integer> getIndexes() {
if (indexes == null) {
indexes = new ArrayList<Integer>();
}
return indexes;
}
private void addLine(int idx, String line) {
getIndexes().add(idx);
getLines().add(line);
}
}
private List<SqlStmt> getSqlStmts(List<String> txts) {
List<SqlStmt> ret = new ArrayList<SqlStmt>();
boolean isStmt = false;
SqlStmt stmt = null;
for (int idx = 0, size = txts.size(); idx < size; idx++) {
String line = txts.get(idx);
if (line == null) {
continue;
}
line = line.trim();
if (line.startsWith("sql_stmt :=")) {
if (!isStmt) {
stmt = new SqlStmt();
stmt.addLine(idx, line);
isStmt = true;
} else {
stmt.addLine(idx, line);
}
} else {
if (isStmt) {
ret.add(stmt);
stmt = null;
isStmt = false;
}
}
}
return ret;
}
public static void main(String[] args) {
final SqlViewer sv = new SqlViewer();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
sv.setSize(200, 200);
sv.setVisible(true);
}
});
}
}
|
/****
Copyright (c) 2015, Skyley Networks, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Skyley Networks, Inc. nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Skyley Networks, Inc. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
****/
package com.skyley.skstack_ip.api.skenums;
/**
* スキャンモードを列挙
* @author Skyley Networks, Inc.
* @version 0.1
*/
public enum SKScanMode {
/** EDスキャン */
ED_SCAN("0"),
/** アクティブスキャン、IEあり */
ACTIVE_SCAN_WITH_IE("2"),
/** アクティブスキャン、IEなし */
ACTIVE_SCAN_WITHOUT_IE("3");
/** スキャンモードのraw value */
private String mode;
/**
* コンストラクタ
* @param mode スキャンモードのraw value
*/
private SKScanMode(String mode) {
this.mode = mode;
}
/**
* スキャンモードのraw valueを取得
*/
public String toString() {
return mode;
}
}
|
package com.library.bexam.dao;
import com.library.bexam.entity.QuestionTypeEntity;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 题型数据访问对象
*
* @author JayChen
*/
public interface QuestionTypeDao {
/**
* 获取题型列表
*
* @return List
* @author JayChen
*/
List list(@Param("subjectId")int subjectId);
/**
* 添加题型
*
* @return boolean
* @author JayChen
*/
boolean add(QuestionTypeEntity questionTypeEntity);
/**
* 根据ID获取题型信息
*
* @return Result
* @author JayChen
*/
QuestionTypeEntity getQuestionTypeById(String typeId);
/**
* 批量添加题型
*
* @return boolean
* @author JayChen
*/
boolean batchAdd(List<QuestionTypeEntity> questionTypeEntities);
/**
* 从学科网拉取试题类型,存类型id
* @param questionTypeEntities
* @return
*/
boolean batchAddForXK(List<QuestionTypeEntity> questionTypeEntities);
/**
* 添加学科与题型关联关系
*
* @return boolean
* @author JayChen
*/
boolean addSubject2QuestionType(@Param("subjectId") String subjectId, @Param("questionTypeId") String questionTypeId);
/**
* 批量添加学科与题型关联关系
*
* @return boolean
* @author JayChen
*/
boolean batchAddSubject2QuestionType(List<QuestionTypeEntity> questionTypeEntities);
/**
* 删除题型
*
* @return boolean
* @author JayChen
*/
boolean delete(String[] typeIdArray);
/**
* 删除学科与题型关联关系
*
* @return boolean
* @author JayChen
*/
boolean deleteSubject2QuestionType(String[] typeIdArray);
/**
* 更新题型信息
*
* @return boolean
* @author JayChen
*/
boolean update(QuestionTypeEntity questionTypeEntity);
}
|
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class InputStreamExample2 {
public static void main(String[] args) {
// String path = "E:\\kosta178\\설치프로그램\\jdk-9.0.4_windows-x64_bin.exe";
String path = "src/OutputStreamExample.java";
InputStream in = null;
try {
in = new FileInputStream(path);
byte[] buffer = new byte[1024*4];
/*in.read(buffer);
for (byte b : buffer) {
System.out.println(b);
}*/
int count = 0;
while((count=in.read(buffer)) != -1) {
for (int i = 0; i < count; i++) {
System.out.println(buffer[i]);
}
}
System.out.println("데이터 입력 완료");
} catch (FileNotFoundException e) {
System.out.println("읽고자 하는 파일이 존재하지 않습니다.");
} catch (IOException e) {
System.out.println("파일을 읽는데 문제가 발생하였습니다.");
} finally {
try {
if (in != null) in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
package com.research.hadoop.outputformat.custom;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import java.io.IOException;
/**
* @fileName: FilterRecordWriter.java
* @description: FilterRecordWriter.java类说明
* @author: by echo huang
* @date: 2020-07-25 11:18
*/
public class FilterRecordWriter extends RecordWriter<Text, NullWritable> {
private FSDataOutputStream fsMy;
private FSDataOutputStream fsOther;
public FilterRecordWriter(TaskAttemptContext context) throws IOException {
// 获取文件系统
FileSystem fs = FileSystem.get(context.getConfiguration());
fsMy = fs.create(new Path("/Users/babywang/Desktop/output/my.log"));
fsOther = fs.create(new Path("/Users/babywang/Desktop/output/other.log"));
}
@Override
public void write(Text text, NullWritable nullWritable) throws IOException, InterruptedException {
boolean isExist = text.toString().contains("wy") || text.toString().contains("hsm");
if (isExist) {
fsMy.write(text.getBytes());
return;
}
fsOther.write(text.getBytes());
}
@Override
public void close(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
IOUtils.closeStream(fsMy);
IOUtils.closeStream(fsOther);
}
}
|
package com.mantouland.fakeelf.component.activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.mantouland.atool.callback.impl.JsonCallBack;
import com.mantouland.fakeelf.R;
import com.mantouland.fakeelf.bean.ListBean;
import com.mantouland.fakeelf.bean.ListDetailBean;
import com.mantouland.fakeelf.component.service.MusicService;
import com.mantouland.fakeelf.constant.APPConstant;
import com.mantouland.fakeelf.controller.MusicController;
import com.mantouland.fakeelf.controller.MusicLoader;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "testmain";
/**
*
*/
private ImageButton musicDetail;
private TextView musicName;
private TextView author;
private ImageView moodPic;
private ImageView moo2;
private ImageView moo3;
private ImageView moo4;
private ImageView mooFrame;
private ConstraintLayout mainLayout;
private MusicService.MyBinder musicBinder;
private ServiceConnection connection;
private int time;
private Handler handler=null;
private String nowMood="HAPPY";
private String[] moodList={"HAPPY","UNHAPPY","CLAM","EXCITING"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
askPermission();
MusicController.getInstance().stop();
setContentView(R.layout.activity_main);
bindViews();
handler=new Handler();
Intent musicIntent =new Intent(this,MusicService.class);
Log.d(TAG, "onCreate: ");
connection= new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
musicBinder= (MusicService.MyBinder) service;
MusicController.getInstance().setBinder(musicBinder);
handler.postDelayed(progressChecker,3000);
//refreshUI();
Log.d(TAG, "onServiceConnected: "+musicBinder);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
bindService(musicIntent,connection,BIND_AUTO_CREATE);
initMusicController();
}
void bindViews(){
musicName=findViewById(R.id.t_musicname);
author=findViewById(R.id.t_author);
moodPic=findViewById(R.id.b_mood);
moo2=findViewById(R.id.i_m1);
moo3=findViewById(R.id.i_m2);
moo4=findViewById(R.id.i_m3);
mooFrame=findViewById(R.id.i_mood);
moodPic.setOnClickListener(this);
moo2.setOnClickListener(this);
moo3.setOnClickListener(this);
moo4.setOnClickListener(this);
mainLayout=findViewById(R.id.mainl);
mainLayout.setOnClickListener(this);
moo2.setVisibility(View.INVISIBLE);
moo3.setVisibility(View.INVISIBLE);
moo4.setVisibility(View.INVISIBLE);
musicDetail=findViewById(R.id.b_detail);
musicDetail.setOnClickListener(this);
mooFrame.setVisibility(View.INVISIBLE);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.b_mood:
int cur=0;
for (int i=0;i<moodList.length;i++){
if (nowMood.equals(moodList[i])){
cur=i;
break;
}
}
String temp=moodList[0];
moodList[0]=moodList[cur];
moodList[cur]=temp;
//123 is remaining
moo2.setImageResource(mood2Mip(moodList[1]));
moo3.setImageResource(mood2Mip(moodList[2]));
moo4.setImageResource(mood2Mip(moodList[3]));
hideMood();
break;
case R.id.i_m2:
if (moo3.getVisibility()==View.VISIBLE){
nowMood=moodList[2];
hideMood();
MusicController.getInstance().stop();
moodPic.setImageResource(mood2Mip(moodList[2]));
initMusicController();
}
break;
case R.id.i_m3:
if (moo4.getVisibility()==View.VISIBLE){
nowMood=moodList[3];
hideMood();
MusicController.getInstance().stop();
moodPic.setImageResource(mood2Mip(moodList[3]));
initMusicController();
}
break;
case R.id.i_m1:
if (moo2.getVisibility()==View.VISIBLE){
nowMood=moodList[1];
hideMood();
MusicController.getInstance().stop();
moodPic.setImageResource(mood2Mip(moodList[1]));
initMusicController();
}
break;
case R.id.b_detail:
Log.d(TAG, "onClick: "+"gotodetail");
Bundle bundle = new Bundle();
Intent intent=new Intent(v.getContext(),Detail.class);
intent.putExtras(bundle);
v.getContext().startActivity(intent);
break;
case R.id.mainl:
Log.d(TAG, "onClick: "+"DEFAULTCLi");
mooFrame.setVisibility(View.INVISIBLE);
moo2.setVisibility(View.INVISIBLE);
moo3.setVisibility(View.INVISIBLE);
moo4.setVisibility(View.INVISIBLE);
break;
}
}
void hideMood(){
if (mooFrame.getVisibility()==View.VISIBLE){
mooFrame.setVisibility(View.INVISIBLE);
moo2.setVisibility(View.INVISIBLE);
moo3.setVisibility(View.INVISIBLE);
moo4.setVisibility(View.INVISIBLE);
}else {
moodPic.setVisibility(View.INVISIBLE);
mooFrame.setVisibility(View.VISIBLE);
moodPic.setVisibility(View.VISIBLE);
moo2.setVisibility(View.VISIBLE);
moo3.setVisibility(View.VISIBLE);
moo4.setVisibility(View.VISIBLE);
}
}
int mood2Mip(String string){
switch (string) {
case "HAPPY":
return R.mipmap.ic_mood_happy;
case "UNHAPPY":
return R.mipmap.ic_mood_unhappy;
case "CLAM":
return R.mipmap.ic_mood_clam;
case "EXCITING":
return R.mipmap.ic_mood_exciting;
}
return 0;
}
private boolean checkPermission() {
boolean hasPermission = true;
for (String permission:APPConstant.APP_PERMISSION){
Log.d(TAG, "checkPermission: "+permission);
hasPermission=ContextCompat.checkSelfPermission(this,permission)==PackageManager.PERMISSION_GRANTED;
if (!hasPermission)
break;
}
return hasPermission;
}
private void requestPermission() {
ActivityCompat.requestPermissions
(this, APPConstant.APP_PERMISSION, 1);
}
private void askPermission(){
if (!checkPermission())
requestPermission();
}
private void initMusicController(){
//set first data
updateMood(nowMood);
}
private void updateMood(String mood){
//
MusicLoader.getInstance().loadMood(mood, new JsonCallBack() {
@Override
public void onSuccess(Object jsonBean) {
ListBean listBean=(ListBean)jsonBean;
Log.d(TAG, "onSuccess: "+listBean.getData().getId());
MusicLoader.getInstance().loadDetail(listBean.getData().getId(), new JsonCallBack() {
@Override
public void onSuccess(Object jsonBean) {
ListDetailBean listDetailBean = (ListDetailBean) jsonBean;
MusicController.getInstance().setMusicList(listDetailBean);
MusicController.getInstance().playThis();
Log.d(TAG, "onSuccess: ");
handler.post(UiRunnable);
}
});
//set over
}
});
}
private void refreshUI(){
}
Runnable UiRunnable =new Runnable(){
@Override
public void run() {
String musicStringName = MusicController.getInstance().getNowPlaying().getName();
String authorName= MusicController.getInstance().getNowPlaying().getAr().get(0).getName();
musicStringName=musicStringName.trim();
authorName=authorName.trim();
musicName.setText(musicStringName);
author.setText(authorName);
}
};
Runnable progressChecker = new Runnable() {
@Override
public void run() {
time=MusicController.getInstance().checkProgress();
handler.post(UiRunnable);
handler.postDelayed(this,300);
}
};
}
|
/**
* Created by jiajia on 2017/5/22.
*/
public class MySqrt {
public void sqrt(double n) {
double min = 0;
double max = n;
double mid = ((min + max) / 2.0);
double qow = mid * mid;
while (min < max) {
if (qow > max) {
max = mid;
mid = (min + max) / 2.0;
qow = mid * mid;
} else {
min = mid;
mid = (min + max) / 2.0;
qow = mid * mid;
}
}
}
}
|
/*
Write the program "Heads or Tails" ,
"You input the number of repeats, for example, 1000 times and programm
reportes the number of heads and tails.
*/
package Lab06A;
/**
*
* @author Aliaksiej Protas
*/
public class Lab06A {
public static void main(String[] args) {
View.print("\n Lets play Heads or Tails!!!! \n The program will show your the number of repeats");
while (true){
int number = UserInput.input("\n Input number of repeats:");
int heads = CoinCount.Heads(number);
View.print("\n The number of the Heads is: " + heads +
"\n The number of the Tails is: " + (number - heads));
if (!Complete.complete("Do you want to continue?")){
break;
}
}
}
}
|
package JavaSem1.BattleShipRuzan;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Scanner;
/**
* Created by Ruzan on 11/6/2016.
*/
public class Controller implements ControllerI
{
private static final String HOSTNAME = "129.21.102.253";
private Fleet f;
private Ocean o;
Ship[] s;
private int maxRow;
private int maxColumn;
static String fromServer;
RMIClient rmic;
RMIServer rmis;
boolean done;
String host;
String oc;
String pc;
public Controller(String host, Ocean o, String pc, String oc)
{
maxColumn = o.getColumn() - 2;
maxRow = o.getRow() - 2;
f = new Fleet(maxRow,maxColumn);
this.o = o;
s = new Ship[4];
System.out.println("You are trying to connect to: " + host);
this.host = host;
this.oc = oc;
this.pc = pc;
}
public boolean connect(JProgressBar jp)
{
rmis = new RMIServer(this, pc);
int i = 1;
while(i < 100000)
{
jp.setValue(i % 1000);
try
{
rmic = new RMIClient(host, oc);
}
catch (Exception e)
{
continue;
}
finally
{
i++;
}
break;
}
if(i == 100000)
{
JOptionPane.showMessageDialog(null, "Sorry! We could not connect.");
System.exit(1);
}
return true;
}
public void readytoPlay() throws RemoteException
{
TurnAndVictory.myTurn = true;
}
public void doneWithPlaying() throws RemoteException
{
TurnAndVictory.myTurn = false;
rmic.callReady();
}
public boolean fillFunc (int xCoord, int yCoord, int len, char orien)
{
char[][] board = f.getBoard();
boolean ok = true;
int maxrow = board.length - 2;
int maxcolumn = board[0].length - 2;
//First, we check validity for horizontal position!
if (xCoord < 1 || xCoord > maxrow || yCoord < 1 || yCoord > maxcolumn)
{
ok = false;
}
if ((orien != 'H' && orien != 'V'))
{
ok = false;
}
if (orien == 'H' && yCoord + len - 1 > maxcolumn)
{
ok = false;
}
if (orien == 'V' && xCoord + len - 1 > maxrow)
{
ok = false;
}
if (orien == 'H' && ok)
{
for (int i = xCoord - 1; i < xCoord + 2; i++)
{
for (int j = yCoord - 1; j < yCoord + len + 1; j++)
{
if (i == xCoord - 1 || i == xCoord + 1 || j == yCoord - 1 || j == yCoord + len)
{
if (board[i][j] == 'S')
{
ok = false;
}
} else if (board[xCoord][j] != '~')
{
ok = false;
}
}
}
}
//Now, we check validity for vertical positions
if (orien == 'V' && ok)
{
for (int j = yCoord - 1; j < yCoord + 2; j++)
{
for (int i = xCoord - 1; i < xCoord + len + 1; i++)
{
if (j == yCoord - 1 || j == yCoord + 1 || i == xCoord - 1 || i == xCoord + len)
{
if (board[i][yCoord] == 'S')
{
ok = false;
}
} else if (board[i][yCoord] != '~')
{
ok = false;
}
}
}
}
return ok;
}
public void fillIt(Ship s1)
{
int xCoord = s1.getxCoord();
int yCoord = s1.getyCoord();
int len = s1.getLen();
s[len - 2] = s1;
char orien = s1.getOrien();
char[][] board = f.getBoard();
//Now, if position is a valid horizontal position, we start filling that position:
if (orien=='H')
{
for (int i=xCoord; i<xCoord+1;i++)
{
for (int j = yCoord; j < yCoord + len; j++)
{
if (i==xCoord-1 || i==xCoord+1 || j==yCoord-1 || j==yCoord + len)
{
board[i][j] = 'B';
}
else
{
board[xCoord][j] = 'S';
}
}
}
}
//Now, if position is a valid vertical position, we start filling that position:
if (orien == 'V')
{
for (int j=yCoord; j<yCoord+1; j++)
{
for (int i = xCoord; i < xCoord + len; i++)
{
if (j==yCoord-1 || j==yCoord+1 || i==xCoord-1 || i==xCoord+len)
{
board[i][j] = 'B';
}
else
{
board[i][yCoord] = 'S';
}
}
}
}
}
public char fhit(int x, int y) throws RemoteException
{
if(x > o.getRow() && y > o.getColumn())
{
return 'N';
}
return rmic.hitFleet(x,y);
}
public char fcheck(int x, int y) throws RemoteException
{
char out = 'N';
char board[][] = f.getBoard();
int maxrow=board.length-2;
int maxcolumn=board[0].length-2;
if (1<=x && x<=maxrow && 1<=y && y<=maxcolumn)
{
if (board[x][y] == 'S')
{
board[x][y] = 'H';
out = 'H';
}
else if(board[x][y] == '~' || board[x][y] == 'B')
{
board[x][y] = 'M';
out = 'M';
}
}
return out;
}
public String shit(int x, int y) throws RemoteException
{
return rmic.callSHit(x,y);
}
public String checkSHit(int x, int y) throws RemoteException
{
boolean des = false;
String name = "";
for(int iter = 0; iter < s.length; iter ++)
{
char orien = s[iter].getOrien();
int xCoord = s[iter].getxCoord();
int yCoord = s[iter].getyCoord();
int len = s[iter].getLen();
int left = s[iter].getLeft();
name = s[iter].getName();
if (orien == 'H' && x == xCoord && y >= yCoord && y < yCoord + len)
{
s[iter].decrLeft();
left --;
if (left == 0)
{
des = true;
}
break;
}
else if (orien == 'V' && y == yCoord && x >= xCoord && x < xCoord + len)
{
s[iter].decrLeft();
left --;
if (left == 0)
{
des = true;
}
break;
}
}
if(des)
{
return name;
}
else
{
return "Nothing";
}
}
public char ohit(int x, int y,char out)
{
char [][] board = o.getBoard();
board[x][y] = out;
return out;
}
public void loss() throws RemoteException
{
rmic.lose();
}
public int getMaxRow()
{
return maxRow;
}
public int getMaxColumn()
{
return maxColumn;
}
public boolean alreadyHit(int x, int y)
{
char [][]board = o.getBoard();
if(board[x][y] != '~')
{
return true;
}
else
{
return false;
}
}
public char[][] getFBoard()
{
return f.getBoard();
}
public char[][] getOBoard()
{
return o.getBoard();
}
public boolean vic() throws RemoteException
{
return rmic.vicCond();
}
public boolean checkVic() throws RemoteException
{
boolean vic = true;
for(int i = 0; i < s.length; i++)
{
if(s[i].getLeft() > 0)
{
vic = false;
}
}
return vic;
}
public void forceVic() throws RemoteException
{
rmic.forceVic();
}
public void forcedVic() throws RemoteException
{
TurnAndVictory.vic = 'S';
}
public void youLose() throws RemoteException
{
TurnAndVictory.vic = 'L';
}
public void createShip(int x, int y, int i, char orien, String name)
{
s[i - 2] = new Ship(x,y,i,orien,name);
}
public int noOfShips()
{
return s.length;
}
public static void main(String a[]) throws IOException
{
Game g = new Game();
JFrame f = new JFrame("BATTLESHIP");
int maxRow = 10;
int maxColumn = 10;
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setMinimumSize(new Dimension(800, 500));
g.createUI(f.getContentPane());
f.pack();
f.setVisible(true);
}
}
|
/*
* 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 testejava;
import java.awt.Color;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
/**
*
* @author Rafael Assis
*/
public class Frm_Calc_Financ extends javax.swing.JFrame {
DecimalFormat decimal = new DecimalFormat("#0.00");
public void calctotal() {
double quantiaRegata = Double.parseDouble(Regata_Quant.getText()) * 19.90;
double quantiaSocial = Double.parseDouble(Social_Quant.getText()) * 59.90;
double quantiaBlusa = Double.parseDouble(Blusa_Quant.getText()) * 119.90;
double quantiaPullover = Double.parseDouble(Pullover_Quant.getText()) * 39.90;
double quantiaSapato = Double.parseDouble(Sapato_Quant.getText()) * 99.90;
double quantiaCalca = Double.parseDouble(Calca_Quant.getText()) * 38.90;
double quantiaMeia = Double.parseDouble(Meia_Quant.getText()) * 9.90;
double quantiaLuva = Double.parseDouble(Luva_Quant.getText()) * 24.90;
double quantiaJaq = Double.parseDouble(Jaq_Quant.getText()) * 329.90;
double quantiaBerm = Double.parseDouble(Berm_Quant.getText()) * 69.90;
double quantiaChinelo = Double.parseDouble(Chinelo_Quant.getText()) * 14.90;
double quantiaBone = Double.parseDouble(Bone_Quant.getText()) * 6.90;
Tot_Regata.setText(decimal.format(quantiaRegata));
Tot_Social.setText(decimal.format(quantiaSocial));
Tot_Blusa.setText(decimal.format(quantiaBlusa));
Tot_Pullover.setText(decimal.format(quantiaPullover));
Tot_Sapato.setText(decimal.format(quantiaSapato));
Tot_Calca.setText(decimal.format(quantiaCalca));
Tot_Meia.setText(decimal.format(quantiaMeia));
Tot_Luva.setText(decimal.format(quantiaLuva));
Tot_Jaq.setText(decimal.format(quantiaJaq));
Tot_Berm.setText(decimal.format(quantiaBerm));
Tot_Chinelo.setText(decimal.format(quantiaChinelo));
Tot_Bone.setText(decimal.format(quantiaBone));
SubTotal = quantiaRegata + quantiaSocial + quantiaBlusa + quantiaPullover + quantiaSapato + quantiaCalca + quantiaMeia + quantiaLuva + quantiaJaq + quantiaBerm + quantiaChinelo + quantiaBone;
Sub_Total.setText(decimal.format(SubTotal));
}
double SubTotal;
public void formaPag(){
if(RB_Praz.isSelected() == true){
Parc_Quant.setEnabled(true);
}
else{
Parc_Quant.setEnabled(false);
}
}
/**
* Creates new form Frm_Calc_Financ
*/
public Frm_Calc_Financ() {
initComponents();
RB_Vis.setSelected(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
RB_Formas = new javax.swing.ButtonGroup();
Financ_Painel = new javax.swing.JPanel();
Product_Label = new javax.swing.JLabel();
Preco_Label = new javax.swing.JLabel();
Blusa_Preco = new javax.swing.JLabel();
Pullover_Preço = new javax.swing.JLabel();
Regata_Preco = new javax.swing.JLabel();
Social_Preco = new javax.swing.JLabel();
Sapato_Preco = new javax.swing.JLabel();
Calca_Preco = new javax.swing.JLabel();
Luva_Preco = new javax.swing.JLabel();
Meia_Preco = new javax.swing.JLabel();
Jaq_Preco = new javax.swing.JLabel();
Berm_Preco = new javax.swing.JLabel();
Chinelo_Preco = new javax.swing.JLabel();
Bone_Preco = new javax.swing.JLabel();
Quant_Label = new javax.swing.JLabel();
Blusa_Quant = new javax.swing.JTextField();
Pullover_Quant = new javax.swing.JTextField();
Regata_Quant = new javax.swing.JTextField();
Social_Quant = new javax.swing.JTextField();
Sapato_Quant = new javax.swing.JTextField();
Calca_Quant = new javax.swing.JTextField();
Meia_Quant = new javax.swing.JTextField();
Luva_Quant = new javax.swing.JTextField();
Jaq_Quant = new javax.swing.JTextField();
Berm_Quant = new javax.swing.JTextField();
Chinelo_Quant = new javax.swing.JTextField();
Total_Label = new javax.swing.JLabel();
Tot_Regata = new javax.swing.JLabel();
Tot_Social = new javax.swing.JLabel();
Tot_Blusa = new javax.swing.JLabel();
Tot_Pullover = new javax.swing.JLabel();
Tot_Sapato = new javax.swing.JLabel();
Tot_Calca = new javax.swing.JLabel();
Tot_Meia = new javax.swing.JLabel();
Tot_Luva = new javax.swing.JLabel();
Tot_Jaq = new javax.swing.JLabel();
Tot_Berm = new javax.swing.JLabel();
Tot_Chinelo = new javax.swing.JLabel();
Bone_Quant = new javax.swing.JTextField();
Tot_Bone = new javax.swing.JLabel();
Regata_Check = new javax.swing.JCheckBox();
Social_Check = new javax.swing.JCheckBox();
Blusa_Check = new javax.swing.JCheckBox();
Pullover_Check = new javax.swing.JCheckBox();
Berm_Check = new javax.swing.JCheckBox();
Jaq_Check = new javax.swing.JCheckBox();
Chinelo_Check = new javax.swing.JCheckBox();
Bone_Check = new javax.swing.JCheckBox();
Sapato_Check = new javax.swing.JCheckBox();
Calca_Check = new javax.swing.JCheckBox();
Meia_Check = new javax.swing.JCheckBox();
Luva_Check = new javax.swing.JCheckBox();
Sub_Label = new javax.swing.JLabel();
Sub_Total = new javax.swing.JLabel();
Sub_Button = new javax.swing.JButton();
For_Pag = new javax.swing.JPanel();
RB_Vis = new javax.swing.JRadioButton();
RB_Praz = new javax.swing.JRadioButton();
Qt_Parc_Label = new javax.swing.JLabel();
Parc_Quant = new javax.swing.JComboBox();
Tot_Parc_label = new javax.swing.JLabel();
Tot_Parc = new javax.swing.JLabel();
Desc_Label = new javax.swing.JLabel();
Desc = new javax.swing.JLabel();
Total_Financ_Lable = new javax.swing.JLabel();
Total_Pag = new javax.swing.JLabel();
Calc_Total = new javax.swing.JButton();
Clear_All = new javax.swing.JButton();
Quit_Button = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Financ_Painel.setBorder(javax.swing.BorderFactory.createTitledBorder("Controle de vendas:"));
Product_Label.setText("Produtos:");
Preco_Label.setText("Preço (em R$):");
Blusa_Preco.setText("119,90");
Pullover_Preço.setText("39,90");
Regata_Preco.setText("19,90");
Social_Preco.setText("59,90");
Sapato_Preco.setText("99.90");
Calca_Preco.setText("38.90");
Luva_Preco.setText("24,90");
Meia_Preco.setText("9,90");
Jaq_Preco.setText("329.90");
Berm_Preco.setText("69.90");
Chinelo_Preco.setText("14.90");
Bone_Preco.setText("6.90");
Quant_Label.setText("Quantidade:");
Blusa_Quant.setEditable(false);
Blusa_Quant.setText("0");
Blusa_Quant.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
caracteres(evt);
}
});
Pullover_Quant.setEditable(false);
Pullover_Quant.setText("0");
Pullover_Quant.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
caracteres(evt);
}
});
Regata_Quant.setEditable(false);
Regata_Quant.setText("0");
Regata_Quant.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Regata_QuantActionPerformed(evt);
}
});
Regata_Quant.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
caracteres(evt);
}
});
Social_Quant.setEditable(false);
Social_Quant.setText("0");
Social_Quant.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
caracteres(evt);
}
});
Sapato_Quant.setEditable(false);
Sapato_Quant.setText("0");
Sapato_Quant.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
caracteres(evt);
}
});
Calca_Quant.setEditable(false);
Calca_Quant.setText("0");
Calca_Quant.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
caracteres(evt);
}
});
Meia_Quant.setEditable(false);
Meia_Quant.setText("0");
Meia_Quant.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Meia_QuantActionPerformed(evt);
}
});
Meia_Quant.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
caracteres(evt);
}
});
Luva_Quant.setEditable(false);
Luva_Quant.setText("0");
Luva_Quant.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
caracteres(evt);
}
});
Jaq_Quant.setEditable(false);
Jaq_Quant.setText("0");
Jaq_Quant.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
caracteres(evt);
}
});
Berm_Quant.setEditable(false);
Berm_Quant.setText("0");
Berm_Quant.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
caracteres(evt);
}
});
Chinelo_Quant.setEditable(false);
Chinelo_Quant.setText("0");
Chinelo_Quant.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
caracteres(evt);
}
});
Total_Label.setText("Total R$:");
Tot_Regata.setText("0.00");
Tot_Social.setText("0.00");
Tot_Blusa.setText("0.00");
Tot_Pullover.setText("0.00");
Tot_Sapato.setText("0.00");
Tot_Calca.setText("0.00");
Tot_Meia.setText("0.00");
Tot_Luva.setText("0.00");
Tot_Jaq.setText("0.00");
Tot_Berm.setText("0.00");
Tot_Chinelo.setText("0.00");
Bone_Quant.setEditable(false);
Bone_Quant.setText("0");
Bone_Quant.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Bone_QuantActionPerformed(evt);
}
});
Bone_Quant.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
caracteres(evt);
}
});
Tot_Bone.setText("0.00");
Regata_Check.setText("Camiseta Regata");
Regata_Check.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Regata_CheckActionPerformed(evt);
}
});
Social_Check.setText("Camisa Social");
Social_Check.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Social_CheckActionPerformed(evt);
}
});
Blusa_Check.setText("Blusa");
Blusa_Check.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Blusa_CheckActionPerformed(evt);
}
});
Pullover_Check.setText("Pullover");
Pullover_Check.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Pullover_CheckActionPerformed(evt);
}
});
Berm_Check.setText("Bermuda");
Berm_Check.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Berm_CheckActionPerformed(evt);
}
});
Jaq_Check.setText("Jaqueta");
Jaq_Check.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Jaq_CheckActionPerformed(evt);
}
});
Chinelo_Check.setText("Chinelo");
Chinelo_Check.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Chinelo_CheckActionPerformed(evt);
}
});
Bone_Check.setText("Boné");
Bone_Check.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Bone_CheckActionPerformed(evt);
}
});
Sapato_Check.setText("Sapato");
Sapato_Check.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Sapato_CheckActionPerformed(evt);
}
});
Calca_Check.setText("Calça");
Calca_Check.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Calca_CheckActionPerformed(evt);
}
});
Meia_Check.setText("Meias");
Meia_Check.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Meia_CheckActionPerformed(evt);
}
});
Luva_Check.setText("Luva");
Luva_Check.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Luva_CheckActionPerformed(evt);
}
});
javax.swing.GroupLayout Financ_PainelLayout = new javax.swing.GroupLayout(Financ_Painel);
Financ_Painel.setLayout(Financ_PainelLayout);
Financ_PainelLayout.setHorizontalGroup(
Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(Financ_PainelLayout.createSequentialGroup()
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Product_Label)
.addGroup(Financ_PainelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Regata_Check)
.addComponent(Social_Check)
.addComponent(Blusa_Check)
.addComponent(Pullover_Check)
.addComponent(Jaq_Check)
.addComponent(Berm_Check)
.addComponent(Chinelo_Check)
.addComponent(Bone_Check)
.addComponent(Sapato_Check)
.addComponent(Calca_Check)
.addComponent(Meia_Check)
.addComponent(Luva_Check))))
.addGap(104, 104, 104)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(Financ_PainelLayout.createSequentialGroup()
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Blusa_Preco)
.addComponent(Calca_Preco)
.addComponent(Meia_Preco)
.addComponent(Luva_Preco)
.addComponent(Jaq_Preco)
.addComponent(Berm_Preco)
.addComponent(Chinelo_Preco)
.addComponent(Bone_Preco)
.addComponent(Sapato_Preco))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(Financ_PainelLayout.createSequentialGroup()
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Preco_Label)
.addComponent(Social_Preco)
.addComponent(Pullover_Preço)
.addComponent(Regata_Preco)
.addGroup(Financ_PainelLayout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(Financ_PainelLayout.createSequentialGroup()
.addGap(250, 250, 250)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(Jaq_Quant)
.addComponent(Quant_Label, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Regata_Quant)
.addComponent(Social_Quant)
.addComponent(Sapato_Quant, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(Blusa_Quant, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(Pullover_Quant)
.addComponent(Calca_Quant, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(Meia_Quant, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(Luva_Quant)
.addComponent(Berm_Quant)))
.addComponent(Chinelo_Quant, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Bone_Quant, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(99, 99, 99)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(Total_Label)
.addComponent(Tot_Bone, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)
.addComponent(Tot_Chinelo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Tot_Berm, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Tot_Jaq, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Tot_Luva, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Tot_Meia, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Tot_Calca, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Tot_Sapato, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Tot_Pullover, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Tot_Blusa, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Tot_Social, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Tot_Regata, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
Financ_PainelLayout.setVerticalGroup(
Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(Financ_PainelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Preco_Label)
.addComponent(Product_Label))
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Quant_Label)
.addComponent(Total_Label)))
.addGap(18, 18, 18)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Regata_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Tot_Regata))
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Regata_Preco)
.addComponent(Regata_Check)))
.addGap(18, 18, 18)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Social_Preco)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Social_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Tot_Social))
.addComponent(Social_Check))
.addGap(18, 18, 18)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Blusa_Preco)
.addComponent(Blusa_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Tot_Blusa)
.addComponent(Blusa_Check))
.addGap(18, 18, 18)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Pullover_Preço)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Pullover_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Tot_Pullover)))
.addComponent(Pullover_Check))
.addGap(18, 18, 18)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Tot_Sapato)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Sapato_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Sapato_Preco)
.addComponent(Sapato_Check)))
.addGap(18, 18, 18)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Calca_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Calca_Preco)
.addComponent(Tot_Calca)
.addComponent(Calca_Check))
.addGap(18, 18, 18)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Tot_Meia)
.addComponent(Meia_Preco)
.addComponent(Meia_Check))
.addComponent(Meia_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Luva_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Tot_Luva))
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Luva_Preco)
.addComponent(Luva_Check)))
.addGap(18, 18, 18)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Jaq_Preco)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Tot_Jaq)
.addComponent(Jaq_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(Jaq_Check))
.addGap(18, 18, 18)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Berm_Preco)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Tot_Berm)
.addComponent(Berm_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(Berm_Check))
.addGap(18, 18, 18)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Chinelo_Preco)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Chinelo_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Tot_Chinelo))
.addComponent(Chinelo_Check))
.addGap(18, 18, 18)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(Financ_PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Bone_Preco)
.addComponent(Bone_Check))
.addComponent(Bone_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Tot_Bone))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
Sub_Label.setText("Sub-Total: R$");
Sub_Total.setText("0,00");
Sub_Button.setText("Sub-Total");
Sub_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Sub_ButtonActionPerformed(evt);
}
});
For_Pag.setBorder(javax.swing.BorderFactory.createTitledBorder("Forma de Pagamento:"));
RB_Formas.add(RB_Vis);
RB_Vis.setText("À Vista");
RB_Vis.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RB_VisActionPerformed(evt);
}
});
RB_Formas.add(RB_Praz);
RB_Praz.setText("À Prazo");
RB_Praz.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RB_PrazActionPerformed(evt);
}
});
Qt_Parc_Label.setText("Quantidade de Parcelas: ");
Parc_Quant.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "2", "3", "4", "5", "6" }));
Parc_Quant.setEnabled(false);
Parc_Quant.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Parc_QuantActionPerformed(evt);
}
});
Tot_Parc_label.setText("Total parcelado: R$");
Tot_Parc.setText("0.00");
javax.swing.GroupLayout For_PagLayout = new javax.swing.GroupLayout(For_Pag);
For_Pag.setLayout(For_PagLayout);
For_PagLayout.setHorizontalGroup(
For_PagLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(For_PagLayout.createSequentialGroup()
.addContainerGap()
.addGroup(For_PagLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(For_PagLayout.createSequentialGroup()
.addComponent(Tot_Parc_label, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Tot_Parc, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(For_PagLayout.createSequentialGroup()
.addGroup(For_PagLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(RB_Vis)
.addComponent(RB_Praz)
.addGroup(For_PagLayout.createSequentialGroup()
.addComponent(Qt_Parc_Label)
.addGap(88, 88, 88)
.addComponent(Parc_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addGap(99, 99, 99))
);
For_PagLayout.setVerticalGroup(
For_PagLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(For_PagLayout.createSequentialGroup()
.addContainerGap()
.addComponent(RB_Vis)
.addGap(18, 18, 18)
.addComponent(RB_Praz)
.addGap(18, 18, 18)
.addGroup(For_PagLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Qt_Parc_Label)
.addComponent(Parc_Quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(For_PagLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Tot_Parc_label)
.addComponent(Tot_Parc))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
Desc_Label.setText("Total de Desconto: R$");
Desc.setText("0.00");
Total_Financ_Lable.setText("Total a Pagar: R$");
Total_Pag.setText("0.00");
Calc_Total.setText("Calcular Total");
Calc_Total.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Calc_TotalActionPerformed(evt);
}
});
Clear_All.setText("Limpar Tudo");
Clear_All.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Clear_AllActionPerformed(evt);
}
});
Quit_Button.setText("Fechar Formulário");
Quit_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Quit_ButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(203, 203, 203)
.addComponent(Sub_Button)
.addGap(87, 87, 87)
.addComponent(Sub_Label)
.addGap(29, 29, 29)
.addComponent(Sub_Total)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(Financ_Painel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(For_Pag, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(Desc_Label)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Desc, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(Total_Financ_Lable)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Total_Pag, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(49, 49, 49)
.addComponent(Calc_Total)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Clear_All)
.addGap(49, 49, 49))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Quit_Button)
.addGap(159, 159, 159))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Financ_Painel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(For_Pag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Desc_Label)
.addComponent(Desc))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Total_Financ_Lable)
.addComponent(Total_Pag))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Calc_Total)
.addComponent(Clear_All))
.addGap(18, 18, 18)
.addComponent(Quit_Button)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Sub_Button)
.addComponent(Sub_Label)
.addComponent(Sub_Total))
.addContainerGap(33, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void Regata_QuantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Regata_QuantActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_Regata_QuantActionPerformed
private void Bone_QuantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Bone_QuantActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_Bone_QuantActionPerformed
private void Parc_QuantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Parc_QuantActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_Parc_QuantActionPerformed
private void Quit_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Quit_ButtonActionPerformed
dispose();
}//GEN-LAST:event_Quit_ButtonActionPerformed
private void caracteres(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_caracteres
String caracter = "0987654321";
if(!caracter.contains(evt.getKeyChar()+"")){
evt.consume();
}
}//GEN-LAST:event_caracteres
private void Sub_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Sub_ButtonActionPerformed
calctotal();
if(SubTotal == 0){
JOptionPane.showMessageDialog(this,"O valor do Sub-total não pode ser de R$0.00");
}
}//GEN-LAST:event_Sub_ButtonActionPerformed
private void Regata_CheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Regata_CheckActionPerformed
if(Regata_Check.isSelected() == true){
//Regata_Quant.setText("");
Regata_Quant.setEditable(true);
Regata_Quant.requestFocus(true);
}
else{
Regata_Quant.setText("0");
Regata_Quant.setEditable(false);
}
}//GEN-LAST:event_Regata_CheckActionPerformed
private void Social_CheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Social_CheckActionPerformed
if(Social_Check.isSelected() == true){
//Social_Quant.setText("");
Social_Quant.setEditable(true);
Social_Quant.requestFocus(true);
}
else{
Social_Quant.setEditable(false);
Social_Quant.setText("0");
}
}//GEN-LAST:event_Social_CheckActionPerformed
private void Blusa_CheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Blusa_CheckActionPerformed
if(Blusa_Check.isSelected() == true){
//Blusa_Quant.setText("");
Blusa_Quant.setEditable(true);
Blusa_Quant.requestFocus(true);
}
else{
Blusa_Quant.setEditable(false);
Blusa_Quant.setText("0");
}
}//GEN-LAST:event_Blusa_CheckActionPerformed
private void Pullover_CheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Pullover_CheckActionPerformed
if(Pullover_Check.isSelected() == true){
//Pullover_Quant.setText("");
Pullover_Quant.setEditable(true);
Pullover_Quant.requestFocus(true);
}
else{
Pullover_Quant.setEditable(false);
Pullover_Quant.setText("0");
}
}//GEN-LAST:event_Pullover_CheckActionPerformed
private void Sapato_CheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Sapato_CheckActionPerformed
if(Sapato_Check.isSelected() == true){
//Sapato_Quant.setText("");
Sapato_Quant.setEditable(true);
Sapato_Quant.requestFocus(true);
}
else{
Sapato_Quant.setEditable(false);
Sapato_Quant.setText("0");
}
}//GEN-LAST:event_Sapato_CheckActionPerformed
private void Calca_CheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Calca_CheckActionPerformed
if(Calca_Check.isSelected() == true){
//Calca_Quant.setText("");
Calca_Quant.setEditable(true);
Calca_Quant.requestFocus(true);
}
else{
Calca_Quant.setEditable(false);
Calca_Quant.setText("0");
}
}//GEN-LAST:event_Calca_CheckActionPerformed
private void Meia_CheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Meia_CheckActionPerformed
if(Meia_Check.isSelected() == true){
//Meia_Quant.setText("");
Meia_Quant.setEditable(true);
Meia_Quant.requestFocus(true);
}
else{
Meia_Quant.setEditable(false);
Meia_Quant.setText("0");
}
}//GEN-LAST:event_Meia_CheckActionPerformed
private void Luva_CheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Luva_CheckActionPerformed
if(Luva_Check.isSelected() == true){
//Luva_Quant.setText("");
Luva_Quant.setEditable(true);
Luva_Quant.requestFocus(true);
}
else{
Luva_Quant.setEditable(false);
Luva_Quant.setText("0");
}
}//GEN-LAST:event_Luva_CheckActionPerformed
private void Jaq_CheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Jaq_CheckActionPerformed
if(Jaq_Check.isSelected() == true){
//Jaq_Quant.setText("");
Jaq_Quant.setEditable(true);
Jaq_Quant.requestFocus(true);
}
else{
Jaq_Quant.setEditable(false);
Jaq_Quant.setText("0");
}
}//GEN-LAST:event_Jaq_CheckActionPerformed
private void Berm_CheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Berm_CheckActionPerformed
if(Berm_Check.isSelected() == true){
//Berm_Quant.setText("");
Berm_Quant.setEditable(true);
Berm_Quant.requestFocus(true);
}
else{
Berm_Quant.setEditable(false);
Berm_Quant.setText("0");
}
}//GEN-LAST:event_Berm_CheckActionPerformed
private void Chinelo_CheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Chinelo_CheckActionPerformed
if(Chinelo_Check.isSelected() == true){
//Chinelo_Quant.setText("");
Chinelo_Quant.setEditable(true);
Chinelo_Quant.requestFocus(true);
}
else{
Chinelo_Quant.setEditable(false);
Chinelo_Quant.setText("0");
}
}//GEN-LAST:event_Chinelo_CheckActionPerformed
private void Bone_CheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Bone_CheckActionPerformed
if(Bone_Check.isSelected() == true){
//Bone_Quant.setText("");
Bone_Quant.setEditable(true);
Bone_Quant.requestFocus(true);
}
else{
Bone_Quant.setEditable(false);
Bone_Quant.setText("0");
}
}//GEN-LAST:event_Bone_CheckActionPerformed
private void Calc_TotalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Calc_TotalActionPerformed
calctotal();
if (RB_Vis.isSelected() == true){
double totalDesc = SubTotal * 0.115;
double total = SubTotal - totalDesc;
Desc.setText(decimal.format(totalDesc));
Total_Pag.setText(decimal.format(total));
Tot_Parc.setText("0,00");
}
if(RB_Praz.isSelected() == true){
if(SubTotal > 10){
String parcelas = (String) Parc_Quant.getSelectedItem();
double jurParc = Integer.parseInt(parcelas) * 6.90;
double Porcentagem = SubTotal * 0.01;
Desc.setText("0.00");
double total_parcelado = SubTotal + Porcentagem + jurParc;
Tot_Parc.setText(decimal.format(total_parcelado));
Total_Pag.setText(decimal.format(total_parcelado));
}
if(SubTotal == 0){
JOptionPane.showMessageDialog(this, "O Sub-total da compra não pode ser de R$0.00");
}
if(SubTotal < 10.00){
JOptionPane.showMessageDialog(this,"O valor para opção de pagamento deve ser maior que R$10.00");
}
}
}//GEN-LAST:event_Calc_TotalActionPerformed
private void RB_PrazActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RB_PrazActionPerformed
formaPag();
}//GEN-LAST:event_RB_PrazActionPerformed
private void RB_VisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RB_VisActionPerformed
formaPag();
}//GEN-LAST:event_RB_VisActionPerformed
private void Meia_QuantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Meia_QuantActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_Meia_QuantActionPerformed
private void Clear_AllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Clear_AllActionPerformed
Regata_Check.setSelected(false);
Social_Check.setSelected(false);
Blusa_Check.setSelected(false);
Pullover_Check.setSelected(false);
Sapato_Check.setSelected(false);
Calca_Check.setSelected(false);
Meia_Check.setSelected(false);
Luva_Check.setSelected(false);
Jaq_Check.setSelected(false);
Berm_Check.setSelected(false);
Chinelo_Check.setSelected(false);
Bone_Check.setSelected(false);
Regata_Quant.setEditable(false);
Social_Quant.setEditable(false);
Blusa_Quant.setEditable(false);
Pullover_Quant.setEditable(false);
Sapato_Quant.setEditable(false);
Calca_Quant.setEditable(false);
Meia_Quant.setEditable(false);
Luva_Quant.setEditable(false);
Jaq_Quant.setEditable(false);
Berm_Quant.setEditable(false);
Chinelo_Quant.setEditable(false);
Bone_Quant.setEditable(false);
Regata_Quant.setText("0");
Social_Quant.setText("0");
Blusa_Quant.setText("0");
Pullover_Quant.setText("0");
Sapato_Quant.setText("0");
Calca_Quant.setText("0");
Meia_Quant.setText("0");
Luva_Quant.setText("0");
Jaq_Quant.setText("0");
Berm_Quant.setText("0");
Chinelo_Quant.setText("0");
Bone_Quant.setText("0");
Tot_Regata.setText("0.00");
Tot_Social.setText("0.00");
Tot_Blusa.setText("0.00");
Tot_Pullover.setText("0.00");
Tot_Sapato.setText("0.00");
Tot_Calca.setText("0.00");
Tot_Meia.setText("0.00");
Tot_Luva.setText("0.00");
Tot_Jaq.setText("0.00");
Tot_Berm.setText("0.00");
Tot_Chinelo.setText("0.00");
Tot_Bone.setText("0.00");
Sub_Total.setText("0.00");
Tot_Parc.setText("0.00");
Desc.setText("0.00");
Total_Pag.setText("0.00");
}//GEN-LAST:event_Clear_AllActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Frm_Calc_Financ.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frm_Calc_Financ.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frm_Calc_Financ.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frm_Calc_Financ.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new Frm_Calc_Financ().setVisible(true);
//if(Regata_Check.isSelected()){
//}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox Berm_Check;
private javax.swing.JLabel Berm_Preco;
private javax.swing.JTextField Berm_Quant;
private javax.swing.JCheckBox Blusa_Check;
private javax.swing.JLabel Blusa_Preco;
private javax.swing.JTextField Blusa_Quant;
private javax.swing.JCheckBox Bone_Check;
private javax.swing.JLabel Bone_Preco;
private javax.swing.JTextField Bone_Quant;
private javax.swing.JButton Calc_Total;
private javax.swing.JCheckBox Calca_Check;
private javax.swing.JLabel Calca_Preco;
private javax.swing.JTextField Calca_Quant;
private javax.swing.JCheckBox Chinelo_Check;
private javax.swing.JLabel Chinelo_Preco;
private javax.swing.JTextField Chinelo_Quant;
private javax.swing.JButton Clear_All;
private javax.swing.JLabel Desc;
private javax.swing.JLabel Desc_Label;
private javax.swing.JPanel Financ_Painel;
private javax.swing.JPanel For_Pag;
private javax.swing.JCheckBox Jaq_Check;
private javax.swing.JLabel Jaq_Preco;
private javax.swing.JTextField Jaq_Quant;
private javax.swing.JCheckBox Luva_Check;
private javax.swing.JLabel Luva_Preco;
private javax.swing.JTextField Luva_Quant;
private javax.swing.JCheckBox Meia_Check;
private javax.swing.JLabel Meia_Preco;
private javax.swing.JTextField Meia_Quant;
private javax.swing.JComboBox Parc_Quant;
private javax.swing.JLabel Preco_Label;
private javax.swing.JLabel Product_Label;
private javax.swing.JCheckBox Pullover_Check;
private javax.swing.JLabel Pullover_Preço;
private javax.swing.JTextField Pullover_Quant;
private javax.swing.JLabel Qt_Parc_Label;
private javax.swing.JLabel Quant_Label;
private javax.swing.JButton Quit_Button;
private javax.swing.ButtonGroup RB_Formas;
private javax.swing.JRadioButton RB_Praz;
private javax.swing.JRadioButton RB_Vis;
private javax.swing.JCheckBox Regata_Check;
private javax.swing.JLabel Regata_Preco;
private javax.swing.JTextField Regata_Quant;
private javax.swing.JCheckBox Sapato_Check;
private javax.swing.JLabel Sapato_Preco;
private javax.swing.JTextField Sapato_Quant;
private javax.swing.JCheckBox Social_Check;
private javax.swing.JLabel Social_Preco;
private javax.swing.JTextField Social_Quant;
private javax.swing.JButton Sub_Button;
private javax.swing.JLabel Sub_Label;
private javax.swing.JLabel Sub_Total;
private javax.swing.JLabel Tot_Berm;
private javax.swing.JLabel Tot_Blusa;
private javax.swing.JLabel Tot_Bone;
private javax.swing.JLabel Tot_Calca;
private javax.swing.JLabel Tot_Chinelo;
private javax.swing.JLabel Tot_Jaq;
private javax.swing.JLabel Tot_Luva;
private javax.swing.JLabel Tot_Meia;
private javax.swing.JLabel Tot_Parc;
private javax.swing.JLabel Tot_Parc_label;
private javax.swing.JLabel Tot_Pullover;
private javax.swing.JLabel Tot_Regata;
private javax.swing.JLabel Tot_Sapato;
private javax.swing.JLabel Tot_Social;
private javax.swing.JLabel Total_Financ_Lable;
private javax.swing.JLabel Total_Label;
private javax.swing.JLabel Total_Pag;
// End of variables declaration//GEN-END:variables
}
|
package com.thoughmechanix.organization.source;
import com.thoughmechanix.organization.channel.CustomChannels;
import com.thoughmechanix.organization.domain.Organization;
import com.thoughmechanix.organization.model.OrganizationChangeModel;
import com.thoughmechanix.organization.util.UserContext;
import com.thoughmechanix.organization.util.UserContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
@Component
@Slf4j
@RequiredArgsConstructor
public class SimpleSourceBean {
private final CustomChannels custom;
public void publishOrgChange(String action, String orgId){
log.info("Sending Kafka message {} for Organization Id : {}",action,orgId);
OrganizationChangeModel organizationChangeModel = new OrganizationChangeModel(
Organization.class.getTypeName(), action, orgId, UserContextHolder.getContext().getCorrelationId()
);
custom.output().send(MessageBuilder.withPayload(organizationChangeModel).build());
}
}
|
package com.OovEver.easyCrawle.event;
import com.OovEver.easyCrawle.Config.Config;
import java.util.*;
import java.util.function.Consumer;
/**
* 基于观察者模式
* 事件管理器
* @author OovEver
* 2018/5/17 23:36
*/
public class EventManager {
// 事件模式
private static final Map<ElvesEvent, List<Consumer<Config>>> elvesEventConsumerMap = new HashMap<>();
/**
* 注册事件
* @param elvesEvent 要注册的事件
* @param consumer 即接口表示一个接受单个输入参数并且没有返回值的操作。不像其它函数式接口,Consumer接口期望执行带有副作用的操作(Consumer的操作可能会更改输入参数的内部状态)。
*/
public static void registerEvent(ElvesEvent elvesEvent, Consumer<Config> consumer) {
List<Consumer<Config>> consumers = elvesEventConsumerMap.get(elvesEvent);
if (null == consumers) {
consumers = new ArrayList<>();
}
consumers.add(consumer);
elvesEventConsumerMap.put(elvesEvent, consumers);
}
/**
* 执行事件
* @param elvesEvent 要执行的事件
* @param config 配置名称
*/
public static void fireEvent(ElvesEvent elvesEvent, Config config) {
Optional.ofNullable(elvesEventConsumerMap.get(elvesEvent)).ifPresent(consumers -> consumers.forEach(consumer -> consumer.accept(config)));
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author user
*/
import javax.swing.*;
public class Main {
public static void main(String[] args) {
try {
Class.forName("java.sql.DriverManager");
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
String url,db,pas;
url="jdbc:mysql://localhost/psdb";
db="root";
pas="";
new LoginGUI(url,db).setVisible(true);
}
}
|
package com.ross.spark.api.transform;
import com.google.gson.Gson;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import java.util.Arrays;
import java.util.List;
/**
* map算子
* map和foreach算子:
* 1. 循环map调用元的每一个元素;
* 2. 执行call函数, 并返回.
*/
class User{
public String id;
public String name;
public String pwd;
public String sex;
public User(String id, String name, String pwd, String sex){
this.id = id;
this.name = name;
this.pwd = pwd;
this.sex = sex;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
", sex='" + sex + '\'' +
'}';
}
}
public class MapDemo {
public static void main(String[] args){
SparkConf conf = new SparkConf().setAppName("MapDemo").setMaster("local");
JavaSparkContext sc = new JavaSparkContext(conf);
List<String> list = Arrays.asList(
"{'id':1,'name':'xl1','pwd':'xl123','sex':2}",
"{'id':2,'name':'xl2','pwd':'xl123','sex':1}",
"{'id':3,'name':'xl3','pwd':'xl123','sex':2}",
"{'id':4,'name':'xl4','pwd':'xl123','sex':1}");
JavaRDD<String> rdd = sc.parallelize(list);
// JavaRDD<User> rddUser = rdd.map(new Function<String, User>() {
// @Override
// public User call(String v1) throws Exception {
// Gson gson = new Gson();
// return gson.fromJson(v1, User.class);
// }
// });
//lambda函数式
JavaRDD<User> rddUser = rdd.map(v1 -> (new Gson().fromJson(v1, User.class)));
// rddUser.foreach(new VoidFunction<User>() {
// @Override
// public void call(User user) throws Exception {
// System.out.println(user.toString());
// }
// });
//lambda表达式
rddUser.foreach(user -> System.out.println(user.toString()));
}
}
|
package com.spring.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.mail.MessagingException;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.spring.domain.SMEBuyerCardGridValue;
import com.spring.domain.SMELoanMailRecipient;
import com.spring.domain.User;
import com.spring.service.UserService;
public class CreateExcelFileForCardPrinting {
private static Logger logger = Logger.getLogger(CreateExcelFileForCardPrinting.class);
public String create(String currentDate, String outputFileLocation,List<SMEBuyerCardGridValue> buyerCardDetails,UserService userService)
{
//Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
String filename="";
//Create a blank sheet for order delivered
XSSFSheet sheet = workbook.createSheet("SME_Card_Details");//
XSSFCellStyle style = workbook.createCellStyle();
XSSFFont font = workbook.createFont();
font.setBoldweight((short) 10000);
font.setColor((short) 16);
style.setFont(font);
style.setWrapText(true);
//XSSFCellStyle plainData = workbook.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
XSSFCellStyle styledata = workbook.createCellStyle();
//XSSFCellStyle plainData = workbook.createCellStyle();
styledata.setAlignment(CellStyle.ALIGN_RIGHT);
//This data needs to be written (Object[])
XSSFRow row1 = sheet.createRow(0);
row1.setHeight((short) 400);
CellRangeAddress heading = new CellRangeAddress(0, 0, 0, 14);
sheet.addMergedRegion(heading);
XSSFCell infoCell150 = row1.createCell(0);
infoCell150.setCellStyle(style);
infoCell150.setCellValue("smelending.com Card Details");
Map<Integer, Object[]> data = new HashMap<Integer, Object[]>();
// Buyer Id Card Number Part1 Part2 Part3 Part4 Valid From Valid Through Valid Through CVV First Name Middle Name Last Name Company Name Track1 Track2
// data.put(1, new Object[] {"SL. NO", "BUYER ID", "TRANSACTION DATE","TRANSACTION AMOUNT"});
data.put(1, new Object[] {"Buyer ID", "Card Number", "Part1","Part2","Part3","Part4","Valid From","Valid Through","CVV","First Name","Middle Name","Last Name","Company Name","Track1","Track2"});
Integer rn=2;
try {
if (buyerCardDetails!=null) {
for(SMEBuyerCardGridValue val:buyerCardDetails)
{
String cnum=val.getCard_number();
//${fn:substring(trans.expyr, 2, 4)}${trans.expmon}
String ValidFrom="Aug-16";
String[] Month = {"JAN", "FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"};
String expmon=val.getExpmon();
String expyr=val.getExpyr();
String ValidThrough=Month[Integer.parseInt(expmon)-1]+"-"+expyr.substring(2, 4);
User buyer=userService.getBuyerDetails(val.getBuyer_id());
String track1="%B"+cnum+"^"+buyer.getFirstName()+" "+buyer.getLastName()+"^"+expyr.substring(2, 4)+""+expmon+"001"+val.getCvv()+"?";
String track2=";"+cnum+"="+expyr.substring(2, 4)+""+expmon+"001"+val.getCvv()+"?";
data.put(rn, new Object[] {val.getBuyer_id(),"'"+cnum, cnum.substring(0, 4),cnum.substring(4, 8),cnum.substring(8, 12),cnum.substring(12, 16),ValidFrom,ValidThrough,val.getCvv(),buyer.getFirstName(),"",buyer.getLastName(),buyer.getCompanyname(),track1,track2 });
//Above single quotes with cnum make string in excel other wise it will become last digit as zero
rn++;
}
}
else {
logger.info("No data available for CreateExcelFileForCardPrinting");
}
} catch (Exception e) {
logger.info("I m in CreateExcelFileForCardPrinting.java !!! error while getting values from database");
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
}
//Iterate over data and write to sheet
Set<Integer> keyset = data.keySet();
int rownum = 1;
sheet.setColumnWidth(0, (10 * 256));
sheet.setColumnWidth(1, (20 * 256));
sheet.setColumnWidth(2, (10 * 256));
sheet.setColumnWidth(3, (10 * 256));
sheet.setColumnWidth(4, (10 * 256));
sheet.setColumnWidth(5, (10 * 256));
sheet.setColumnWidth(6, (15 * 256));
sheet.setColumnWidth(7, (15 * 256));
sheet.setColumnWidth(8, (5 * 256));
sheet.setColumnWidth(9, (25 * 256));
sheet.setColumnWidth(10, (15 * 256));
sheet.setColumnWidth(11, (25 * 256));
sheet.setColumnWidth(12, (30 * 256));
sheet.setColumnWidth(13, (45 * 256));
sheet.setColumnWidth(14, (30 * 256));
XSSFCellStyle headerCenterData = workbook.createCellStyle();
headerCenterData.setAlignment(CellStyle.ALIGN_CENTER);
font.setColor((short) 16);
headerCenterData.setFont(font);
headerCenterData.setWrapText(true);
XSSFCellStyle headerLogoStyle = workbook.createCellStyle();
headerLogoStyle.setAlignment(CellStyle.ALIGN_LEFT);
headerCenterData.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
headerCenterData.setFillPattern(CellStyle.SOLID_FOREGROUND);
headerCenterData.setBorderRight(HSSFCellStyle.BORDER_THIN);
for (Integer key : keyset)
{
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
if(rownum==2){
Cell cell = row.createCell(cellnum++);
cell.setCellStyle(headerCenterData);
if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Integer)
cell.setCellValue((Integer)obj);
}
else
{
Cell cell = row.createCell(cellnum++);
cell.setCellStyle(styledata);
if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Integer)
cell.setCellValue((Integer)obj);
}
}
}
//creating file
try
{
//Write the workbook in file system
filename="smelending_card_details_"+getCurrentDateInDDMMYYYY()+".xlsx";
File fout=new File(outputFileLocation,filename);
FileOutputStream out = new FileOutputStream(fout);
workbook.write(out);
out.close();
logger.info(filename+" written successfully on disk.");
}
catch (Exception e)
{
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
}
return filename;
}
//for sending file as attachment
public void sendOutputFile(String card_output_files_location_only, SMELoanMailRecipient smeLoanMailRecipients,CardPrintingServiceEmailer cardPrintingServiceEmailer,String bodyAdditionalInfo) throws MessagingException, IOException {
String Send_File_Path_only = card_output_files_location_only;
String fromAddress="";
String fromPassword="";
String Recipient = smeLoanMailRecipients.getSeller_email_to_address(); //to_address
String senderName = smeLoanMailRecipients.getSender_name(); //sendername
String ccAddress = smeLoanMailRecipients.getCc_address(); //ccaddress
String subject = smeLoanMailRecipients.getSubject(); //subject
String bodyMessage = smeLoanMailRecipients.getBody(); //body
fromAddress=smeLoanMailRecipients.getUsername(); //username
fromPassword=smeLoanMailRecipients.getPassword(); //password
try {
logger.info("location of file attachment :: "+card_output_files_location_only);
String filename="smelending_card_details_"+getCurrentDateInDDMMYYYY()+".xlsx";
File file =new File(card_output_files_location_only,filename);
logger.info("filename for attachment :: "+filename);
if (file!=null) {
logger.info("Entering the condition without ERROR");
String body = "Hi Team,\n\n\t "+bodyMessage+bodyAdditionalInfo+"\n\nBest Regards,\nsmelending.com";// rs.getString(6);
logger.info("\n Recipient: " + Recipient + "\n senderName: " + senderName + "\n ccAddress: " + ccAddress + "\n subject: " + subject + "\n body: " + body);
cardPrintingServiceEmailer.sendMailWithAttachment(file,file, fromAddress, Recipient.split(","),ccAddress.split(","), subject, body);
}
} catch (Exception e) {
logger.info("Exception got while sending message in FormatChanger.java");
logger.info("Entering the condition with ERROR");
String body = "Hi Team,\n\t Please find the attachment for the dzCard error file.\n\nBest Regards,\nsmelending.com";
logger.info("\n Recipient: " + Recipient + "\n senderName: " + senderName + "\n ccAddress: " + ccAddress + "\n subject: " + subject + "\n body: " + body);
cardPrintingServiceEmailer.sendMailWithAttachment(null,null, fromAddress, Recipient.split(","),ccAddress.split(","), subject, body);
}
}
public static String getCurrentDateInDDMMYYYY(){
String pattern = "dd-MM-yyyy";
String dateInString =new SimpleDateFormat(pattern).format(new Date());
return dateInString;
}
public static String getAmountWithDecimal(String amount) {
if(amount!=null)
{
String decimalVal=amount.substring(amount.length()-2, amount.length());
String beforedecimal=amount.substring(0, amount.length()-2);
return beforedecimal.replaceFirst("^0+(?!$)", "")+"."+decimalVal;
}
else
{
return null;
}
}
public static String getDateInDDMMYYYY(String givenDate){
DateFormat df2 = new SimpleDateFormat("yyyyMMdd");
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date date=null;
Calendar c = null;
try {
c = Calendar.getInstance();
c.setTime( df2.parse(givenDate));
//c.add(Calendar.DATE, (13)); //14days period for order lapsed
date = df2.parse(givenDate);
} catch (ParseException e) {
//logger.info("Exception while creating date");
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
}
logger.info("date info :"+dateFormat.format(c.getTime()));
return dateFormat.format(c.getTime());
}
public static String getCurrentDateInddMMYYYY(){
String todayAsString = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
//String pattern = "dd-MM-yyyy";
// String dateInString =new SimpleDateFormat(pattern).format(new Date());
logger.info("settlement date: "+todayAsString);
return todayAsString;
}
}
|
package solutions.lab2;
import java.util.Vector;
import java.util.logging.Level;
import org.metacsp.framework.ConstraintNetwork;
import org.metacsp.framework.ValueOrderingH;
import org.metacsp.framework.VariableOrderingH;
import org.metacsp.meta.TCSP.MostConstrainedFirstVarOH;
import org.metacsp.meta.TCSP.TCSPLabeling;
import org.metacsp.meta.TCSP.TCSPSolver;
import org.metacsp.meta.TCSP.WidestIntervalFirstValOH;
import org.metacsp.multi.TCSP.DistanceConstraint;
import org.metacsp.multi.TCSP.DistanceConstraintSolver;
import org.metacsp.multi.TCSP.MultiTimePoint;
import org.metacsp.time.APSPSolver;
import org.metacsp.time.Bounds;
import org.metacsp.time.TimePoint;
import org.metacsp.utility.logging.MetaCSPLogging;
public class ExTCSPComplete {
public static void main(String args[]) {
TCSPSolver metaSolver = new TCSPSolver(0, 100, 0);
DistanceConstraintSolver groundSolver = (DistanceConstraintSolver)metaSolver.getConstraintSolvers()[0];
APSPSolver groundGroundSolver = (APSPSolver)groundSolver.getConstraintSolvers()[0];
MetaCSPLogging.setLevel(metaSolver.getClass(), Level.FINEST);
/*
* In a restaurant, we have both a human waiter and a robot waiter. A guest Enters a restaurant and orders a coffee.
* . A human waiter takes (5-7) min to make a coffee ready and A robot waiter takes (8-10) min to make a coffee ready. Then,
* the robot travel to serve a coffee. It either takes (5-10) min if it travel among the guest and tables or takes 7 min if it travels in a
* fixed path designed only for a robot. Then, the robot has to serve a sugorpot which it takes either [5,10] or 6 min. In order to avoid
* coffee getting cold, guest must have 15 min after the coffee prepared. The whole serving time should not exceed than 25 min.
*/
MultiTimePoint guestOrder = (MultiTimePoint)groundSolver.createVariable();
MultiTimePoint coffeeReady = (MultiTimePoint)groundSolver.createVariable();
MultiTimePoint servingCoffee = (MultiTimePoint)groundSolver.createVariable();
MultiTimePoint servingSugarPot = (MultiTimePoint)groundSolver.createVariable();
ConstraintNetwork.draw(groundSolver.getConstraintNetwork(), "TCSP");
ConstraintNetwork.draw(groundGroundSolver.getConstraintNetwork(), "STP");
Vector<DistanceConstraint> cons = new Vector<DistanceConstraint>();
DistanceConstraint guestOrderTime = new DistanceConstraint(new Bounds(3, 3));
guestOrderTime.setFrom(groundSolver.getSource());
guestOrderTime.setTo(guestOrder);
cons.add(guestOrderTime);
DistanceConstraint preparingCoffee = new DistanceConstraint(new Bounds(5, 7), new Bounds(8, 10));
preparingCoffee.setFrom(guestOrder);
preparingCoffee.setTo(coffeeReady);
cons.add(preparingCoffee);
// DistanceConstraint coffeePreparing = new DistanceConstraint(new Bounds(6, 6));
// coffeePreparing.setFrom(groundSolver.getSource());
// coffeePreparing.setTo(coffeeReady);
// cons.add(coffeePreparing);
DistanceConstraint travelToServCoffee = new DistanceConstraint(new Bounds(5, 10), new Bounds(7, 7) );
travelToServCoffee.setFrom(coffeeReady);
travelToServCoffee.setTo(servingCoffee);
cons.add(travelToServCoffee);
DistanceConstraint travelToServSugorPot = new DistanceConstraint(new Bounds(4, 10), new Bounds(6, 8));
travelToServSugorPot.setFrom(servingCoffee);
travelToServSugorPot.setTo(servingSugarPot);
cons.add(travelToServSugorPot);
DistanceConstraint validDurationForHotCoffee = new DistanceConstraint(new Bounds(0, 12));
validDurationForHotCoffee.setFrom(coffeeReady);
validDurationForHotCoffee.setTo(servingSugarPot);
cons.add(validDurationForHotCoffee);
DistanceConstraint servingTime = new DistanceConstraint(new Bounds(0, 20));
servingTime.setFrom(guestOrder);
servingTime.setTo(servingSugarPot);
cons.add(servingTime);
groundSolver.addConstraints(cons.toArray(new DistanceConstraint[cons.size()]));
//groundSolver.addConstraints(new DistanceConstraint[] {preparingCoffee,travelToServCoffee,travelToServSugorPot,validDurationForHotCoffee, servingTime});
VariableOrderingH varOH = new MostConstrainedFirstVarOH();
ValueOrderingH valOH = new WidestIntervalFirstValOH();
TCSPLabeling metaCons = new TCSPLabeling(varOH, valOH);
metaSolver.addMetaConstraint(metaCons);
System.out.println("Solved? " + metaSolver.backtrack());
System.out.println(groundSolver.getSource());
System.out.println(coffeeReady);
System.out.println(servingCoffee);
System.out.println(((TimePoint)servingSugarPot.getInternalVariables()[0]).getLowerBound());
System.out.println(((TimePoint)servingSugarPot.getInternalVariables()[0]).getUpperBound());
metaSolver.draw();
// System.out.println(metaSolver.getDescription());
// System.out.println(metaCons.getDescription());
}
}
|
/**
* This class handles joining an existing campaign.
* User can search for a campaign by entering campaign code
* and join with a specific character.
*
* @author: Meng Yang
*/
package edu.tacoma.uw.myang12.pocketdungeon.campaign;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import edu.tacoma.uw.myang12.pocketdungeon.model.Character;
import edu.tacoma.uw.myang12.pocketdungeon.character.CharacterListActivity;
import edu.tacoma.uw.myang12.pocketdungeon.model.Campaign;
import edu.tacoma.uw.myang12.pocketdungeon.R;
public class CampaignJoinActivity extends AppCompatActivity {
private List<Character> mCharacterList;
private RecyclerView mRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_campaign_join);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
Campaign campaign = (Campaign) bundle.getSerializable("CAMPAIGN");
SharedPreferences mSharedPreferences = getSharedPreferences(getString(R.string.LOGIN_PREFS),
Context.MODE_PRIVATE);
mSharedPreferences.edit()
.putInt(getString(R.string.CAMPAIGNID), campaign.getCampaignID())
.commit();
String campaignId = "Code: " + campaign.getCampaignID();
String campaignName = "Name: " + campaign.getCampaignName();
String campaignDesc = "Description: " + campaign.getGetCampaignNotes();
TextView mIdView = findViewById(R.id.campaignId_txt);
TextView mNameView = findViewById(R.id.campaignName_txt);
TextView mDescView = findViewById(R.id.campaignDesc_txt);
mIdView.setText(campaignId);
mNameView.setText(campaignName);
mDescView.setText(campaignDesc);
Button charButton = findViewById(R.id.select_char_btn);
charButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(CampaignJoinActivity.this, CharacterListActivity.class);
startActivity(i);
}
});
StringBuilder url = new StringBuilder(getString(R.string.search_characters));
url.append(campaign.getCampaignID());
new CampaignJoinActivity.CharacterTask().execute(url.toString());
mRecyclerView = findViewById(R.id.player_list);
assert mRecyclerView != null;
setupRecyclerView(mRecyclerView);
}
private void setupRecyclerView(@NonNull RecyclerView recyclerView) {
if (mCharacterList != null) {
recyclerView.setAdapter(new CampaignJoinActivity.SimpleItemRecyclerViewAdapter(this, mCharacterList));
}
recyclerView.setLayoutManager(new LinearLayoutManager(CampaignJoinActivity.this));
}
public static class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<CampaignJoinActivity.SimpleItemRecyclerViewAdapter.ViewHolder> {
private final CampaignJoinActivity mParentActivity;
private final List<Character> mValues;
SimpleItemRecyclerViewAdapter(CampaignJoinActivity parent,
List<Character> items) {
mValues = items;
mParentActivity = parent;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.campaign_character_list, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final CampaignJoinActivity.SimpleItemRecyclerViewAdapter.ViewHolder holder, int position) {
holder.mNameView.setText(mValues.get(position).getCharacterName());
}
@Override
public int getItemCount() {
return mValues.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
final TextView mNameView;
ViewHolder(View view) {
super(view);
mNameView = view.findViewById(R.id.character_name);
}
}
}
private class CharacterTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
HttpURLConnection urlConnection = null;
for (String url : urls) {
try {
URL urlObject = new URL(url);
urlConnection = (HttpURLConnection) urlObject.openConnection();
/** Get response from server. */
InputStream content = urlConnection.getInputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
response = "Unable to download the list of characters, Reason: "
+ e.getMessage();
}
finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
return response;
}
/** If character is retrieved successfully, inform user.
* Otherwise, send error message.
* @param s response message
*/
@Override
protected void onPostExecute(String s) {
if (s.startsWith("Unable to")) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
return;
}
try {
JSONObject jsonObject = new JSONObject(s);
if (jsonObject.getBoolean("success")) {
mCharacterList = Character.parseCharacterJSON(
jsonObject.getString("names"));
if (!mCharacterList.isEmpty()) {
setupRecyclerView(mRecyclerView);
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "JSON Error: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
}
|
package models.excel;
import lombok.Data;
/**
* Created by shanmao on 17/9/9.
*
* 商家汇总信息
*/
@Data
public class ShopCollectionExcel {
/** 店铺名 */
private String shopName;
/** 总单数 */
private int orderNum;
/** 总金额 */
private int totalAmount;
}
|
package com.baomidou.mybatisplus.samples.quickstart.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.samples.quickstart.domain.LoanProduct;
import com.baomidou.mybatisplus.samples.quickstart.mapper.LoanProductMapper;
import com.baomidou.mybatisplus.samples.quickstart.service.LoanProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class LoanProductServiceImpl extends ServiceImpl<LoanProductMapper, LoanProduct> implements LoanProductService {
}
|
package com.harrymt.productivitymapping.database;
import com.harrymt.productivitymapping.PROJECT_GLOBALS;
/**
* Defines the database layout.
*/
public class DatabaseSchema {
private static final String TAG = PROJECT_GLOBALS.LOG_NAME + "DatabaseSchema";
static class ZONE {
static final String TABLE = "zoneTbl";
static class KEY {
static final String ID = "id";
static final String LAT = "lat";
static final String LNG = "lng";
static final String RADIUS = "radius";
static final String NAME = "name";
static final String HAS_SYNCED = "hasSynced"; // 1 it has, 0 is hasn't
static final String BLOCKING_APPS = "blockingApps";
static final String KEYWORDS = "keywords";
}
static final String SQL_CREATE_TABLE =
"CREATE TABLE if not exists " + TABLE + " (" +
KEY.ID + " INTEGER PRIMARY KEY autoincrement, " +
KEY.LAT + " REAL, " +
KEY.LNG + " REAL, " +
KEY.RADIUS + " REAL, " +
KEY.NAME + " TEXT, " +
KEY.HAS_SYNCED + " INTEGER, " +
KEY.BLOCKING_APPS + " TEXT, " +
KEY.KEYWORDS + " TEXT " +
");";
}
static class SESSION {
static final String TABLE = "sessionTbl";
static class KEY {
static final String ID = "id";
static final String ZONE_ID = "zoneId";
static final String START_TIME = "startTime";
static final String STOP_TIME = "stopTime";
}
static final String SQL_CREATE_TABLE =
"CREATE TABLE if not exists " + TABLE + " (" +
KEY.ID + " INTEGER PRIMARY KEY autoincrement, " +
KEY.ZONE_ID + " INTEGER, " +
KEY.START_TIME + " INTEGER, " +
KEY.STOP_TIME + " INTEGER " +
");";
}
static class NOTIFICATION {
static final String TABLE = "notificationTbl";
static class KEY {
static final String ID = "id";
static final String SENT_TO_USER = "sentToUser";
static final String SESSION_ID = "sessionId";
static final String PACKAGE = "package";
static final String TITLE = "title";
static final String TEXT = "nText";
static final String SUB_TEXT = "subText";
static final String CONTENT_INFO = "contentInfo";
static final String ICON = "icon";
static final String LARGE_ICON = "lIcon";
}
static final String SQL_CREATE_TABLE =
"CREATE TABLE if not exists " + TABLE + " (" +
KEY.ID + " INTEGER PRIMARY KEY autoincrement, " +
KEY.SESSION_ID + " INTEGER, " +
KEY.SENT_TO_USER + " INTEGER, " +
KEY.PACKAGE + " TEXT, " +
KEY.TITLE + " TEXT, " +
KEY.TEXT + " TEXT, " +
KEY.SUB_TEXT + " TEXT, " +
KEY.CONTENT_INFO + " TEXT, " +
KEY.ICON + " INTEGER, " +
KEY.LARGE_ICON + " BLOB" +
");";
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.coverview;
import android.view.View;
import com.tencent.mm.plugin.appbrand.jsapi.base.a;
import com.tencent.mm.plugin.appbrand.page.p;
import com.tencent.mm.plugin.appbrand.q.f;
import com.tencent.mm.sdk.platformtools.x;
import org.json.JSONObject;
public final class d extends a {
private static final int CTRL_INDEX = 446;
public static final String NAME = "insertScrollView";
protected final View a(p pVar, JSONObject jSONObject) {
return new WxaScrollView(pVar.mContext);
}
protected final int k(JSONObject jSONObject) {
return jSONObject.getInt("viewId");
}
protected final void a(p pVar, int i, View view, JSONObject jSONObject) {
x.d("MicroMsg.JsApiInsertScrollView", "onInsertView(viewId : %s, %s)", Integer.valueOf(i), jSONObject);
WxaScrollView wxaScrollView = (WxaScrollView) view;
boolean optBoolean = jSONObject.optBoolean("needScrollEvent");
String optString = jSONObject.optString("data", "");
com.tencent.mm.plugin.appbrand.jsapi.o.d.a(view, jSONObject.optJSONObject("style"));
pVar.agU().E(i, true).p("data", optString);
if (optBoolean) {
wxaScrollView.setOnScrollChangedListener(new 1(this, pVar, i));
}
jSONObject.optInt("scrollLeft", 0);
if (jSONObject.has("scrollX")) {
x.i("MicroMsg.JsApiInsertScrollView", "scrollHorizontal:%b", Boolean.valueOf(jSONObject.optBoolean("scrollX", true)));
wxaScrollView.setScrollHorizontal(optBoolean);
}
if (jSONObject.has("scrollY")) {
x.i("MicroMsg.JsApiInsertScrollView", "scrollVertical:%b", Boolean.valueOf(jSONObject.optBoolean("scrollY", true)));
wxaScrollView.setScrollVertical(optBoolean);
}
if (jSONObject.has("scrollTop")) {
x.i("MicroMsg.JsApiInsertScrollView", "scrollTop:%d", Integer.valueOf(f.a(jSONObject, "scrollTop", wxaScrollView.getScrollY())));
wxaScrollView.postDelayed(new 2(this, wxaScrollView, r1), 100);
}
}
}
|
package com.tencent.mm.plugin.messenger.foundation.a;
import com.tencent.mm.by.a.a;
class t$a$2 implements a<r<T>> {
final /* synthetic */ com.tencent.mm.bk.a lcr;
final /* synthetic */ t.a lcs;
t$a$2(t.a aVar, com.tencent.mm.bk.a aVar2) {
this.lcs = aVar;
this.lcr = aVar2;
}
public final /* synthetic */ void aD(Object obj) {
((r) obj).e(this.lcr);
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.servlet.admin;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.openkm.bean.HttpSessionInfo;
import com.openkm.core.HttpSessionManager;
import com.openkm.frontend.client.bean.GWTUINotification;
import com.openkm.servlet.frontend.UINotificationServlet;
import com.openkm.util.UserActivity;
import com.openkm.util.WebUtils;
/**
* Logged users servlet
*/
public class LoggedUsersServlet extends BaseServlet {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(LoggedUsersServlet.class);
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException {
log.debug("doGet({}, {})", request, response);
request.setCharacterEncoding("UTF-8");
updateSessionManager(request);
String action = WebUtils.getString(request, "action");
String userId = request.getRemoteUser();
if (action.equals("messageCreate")) {
create(userId, request, response);
} else if (action.equals("messageList")) {
messageList(userId, request, response);
} else if (action.equals("messageEdit")) {
edit(userId, request, response);
} else if (action.equals("messageDelete")) {
delete(userId, request, response);
}
if (action.equals("")) {
list(userId, request, response);
} else if (WebUtils.getBoolean(request, "persist")) {
messageList(userId, request, response);
}
}
public void list(String userId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = getServletContext();
List<HttpSessionInfo> sessions = HttpSessionManager.getInstance().getSessions();
sc.setAttribute("sessions", sessions);
sc.getRequestDispatcher("/admin/logged_users.jsp").forward(request, response);
// Activity log
UserActivity.log(userId, "ADMIN_LOGGED_USERS", null, null, null);
}
public void messageList(String userId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = getServletContext();
sc.setAttribute("messages", UINotificationServlet.getAll());
sc.getRequestDispatcher("/admin/message_list.jsp").forward(request, response);
// Activity log
UserActivity.log(userId, "ADMIN_GET_MESSAGES", null, null, null);
}
public void create(String userId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (WebUtils.getBoolean(request, "persist")) {
int action = WebUtils.getInt(request, "me_action");
String message = WebUtils.getString(request, "me_message");
int type = WebUtils.getInt(request, "me_type");
boolean show = WebUtils.getBoolean(request, "me_show");
UINotificationServlet.add(action, message, type, show);
// Activity log
UserActivity.log(userId, "ADMIN_ADD_MESSAGE", String.valueOf(action), null, message);
} else {
ServletContext sc = getServletContext();
sc.setAttribute("action", WebUtils.getString(request, "action"));
sc.setAttribute("persist", true);
sc.setAttribute("me", new GWTUINotification());
sc.getRequestDispatcher("/admin/message_edit.jsp").forward(request, response);
}
}
public void edit(String userId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (WebUtils.getBoolean(request, "persist")) {
int id = WebUtils.getInt(request, "me_id");
int action = WebUtils.getInt(request, "me_action");
String message = WebUtils.getString(request, "me_message");
int type = WebUtils.getInt(request, "me_type");
boolean show = WebUtils.getBoolean(request, "me_show");
GWTUINotification uin = UINotificationServlet.findById(id);
uin.setAction(action);
uin.setMessage(message);
uin.setShow(show);
uin.setType(type);
// Activity log
UserActivity.log(userId, "ADMIN_EDIT_MESSAGE", String.valueOf(action), null, message);
} else {
int id = WebUtils.getInt(request, "me_id");
ServletContext sc = getServletContext();
sc.setAttribute("action", WebUtils.getString(request, "action"));
sc.setAttribute("persist", true);
sc.setAttribute("me", UINotificationServlet.findById(id));
sc.getRequestDispatcher("/admin/message_edit.jsp").forward(request, response);
}
}
public void delete(String userId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (WebUtils.getBoolean(request, "persist")) {
int id = WebUtils.getInt(request, "me_id");
UINotificationServlet.delete(id);
// Activity log
UserActivity.log(userId, "ADMIN_DELETE_MESSAGE", String.valueOf(id), null, null);
} else {
int id = WebUtils.getInt(request, "me_id");
ServletContext sc = getServletContext();
sc.setAttribute("action", WebUtils.getString(request, "action"));
sc.setAttribute("persist", true);
sc.setAttribute("me", UINotificationServlet.findById(id));
sc.getRequestDispatcher("/admin/message_edit.jsp").forward(request, response);
}
}
}
|
package communication;
import communication.CommunicationTypes;
public class CommunicationAnswer {
private final CommunicationTypes type;
private final Object value;
public CommunicationAnswer(CommunicationTypes type, Object value) {
this.type = type;
this.value = value;
}
public CommunicationTypes getType() {
return type;
}
public Object getValue() {
return value;
}
}
|
package com.smxknife.java.ex27;
import java.util.function.Function;
import java.util.stream.Stream;
/**
* @author smxknife
* 2019-05-31
*/
public class Demo6 {
public static void main(String[] args) {
Stream<String> first = Stream.of("a", "b", "c");
Stream<String> two = Stream.of("1", "2", "3");
Stream<String> three = Stream.of("yi", "er", "san").parallel();
Stream<String> four = Stream.of("一", "二", "三").parallel();
Stream<String> first1 = Stream.of("a", "b", "c");
Stream<String> two1 = Stream.of("1", "2", "3");
Stream<String> three1 = Stream.of("yi", "er", "san").parallel();
Stream<String> four1 = Stream.of("一", "二", "三").parallel();
Stream<String> concat = Stream.concat(first, two);
System.out.println(concat.isParallel());
Stream<String> stringStream = Stream.of(first, two).flatMap(Function.identity());
System.out.println(stringStream.isParallel());
Stream<String> concat1 = Stream.concat(four, three);
System.out.println(concat1.isParallel());
Stream<String> stringStream1 = Stream.of(four, three).flatMap(Function.identity());
System.out.println(stringStream1.isParallel());
Stream<String> reduce = Stream.of(first1, two1, three1)
.reduce(Stream.empty(), Stream::concat);
System.out.println(reduce.isParallel());
}
}
|
package com.duanxr.yith.easy;
import java.util.Stack;
/**
* @author 段然 2021/3/8
*/
public class YongLiangGeZhanShiXianDuiLieLcof {
/**
* English description is not available for the problem.
*
* 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
*
*
*
* 示例 1:
*
* 输入:
* ["CQueue","appendTail","deleteHead","deleteHead"]
* [[],[3],[],[]]
* 输出:[null,null,3,-1]
* 示例 2:
*
* 输入:
* ["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
* [[],[],[5],[2],[],[]]
* 输出:[null,-1,null,null,5,2]
* 提示:
*
* 1 <= values <= 10000
* 最多会对 appendTail、deleteHead 进行 10000 次调用
*
*/
class CQueue {
private Stack<Integer> ls;
private Stack<Integer> rs;
//private boolean onRight = false;
public CQueue() {
ls = new Stack<>();
rs = new Stack<>();
}
public void appendTail(int value) {
ls.push(value);
}
public int deleteHead() {
if (rs.isEmpty()) {
stackMove(ls, rs);
}
return rs.isEmpty() ? -1 : rs.pop();
}
/* public void appendTail(int value) {
if (onRight) {
stackMove(rs, ls);
onRight = false;
}
ls.push(value);
}
public int deleteHead() {
if (!onRight) {
stackMove(ls, rs);
onRight = true;
}
return rs.isEmpty() ? -1 : rs.pop();
}*/
private void stackMove(Stack<Integer> origin, Stack<Integer> target) {
while (!origin.isEmpty()) {
target.push(origin.pop());
}
}
}
}
|
package com.logstash.configchecker.service;
public interface CheckConfigurationService {
boolean checkConfiguration(String configuration);
}
|
import java.util.Scanner;
import java.util.Vector;
class S3 {
public int instanceV = 1;
public void set(int value) {
instanceV = value;
}
public String toString() {
return "S3: " + instanceV;
}
public static void main(String args[]) {
System.out.println(new S3());
}
}
public class X_4 extends S3 {
public int instanceV = 4;
public void onlyInS4() {
System.out.println("S4: onlyInS4");
}
public void set(int value) {
instanceV = value;
}
public String toString() {
return "S4: " + instanceV;
}
public static void main(String args[]) {
X_4 aS4 = new X_4();
S3 aS3 = (S3)aS4;
System.out.println("aS4 =" + aS4 );
System.out.println("aS4.instanceV = " + aS4.instanceV );
System.out.println("aS3 =" + aS3 );
System.out.println("aS3.instanceV = " + aS3.instanceV );
System.out.println("S4.set(44);");
System.out.println("S3.set(33);");
aS4.set(44);
aS3.set(33);
System.out.println("aS4 =" + aS4 );
System.out.println("aS4.instanceV =" + aS4.instanceV );
System.out.println("aS3 =" + aS3 );
System.out.println("aS3.instanceV =" + aS3.instanceV );
}
}
|
import jUnitTestSuits.compileTests.*;
import jUnitTestSuits.correctnessTests.barrier.Barrier_corrTest;
import jUnitTestSuits.correctnessTests.critical.Critical_corrTest;
import jUnitTestSuits.correctnessTests.firstPrivate.*;
import jUnitTestSuits.correctnessTests.flush.Flush_corrTest;
import jUnitTestSuits.correctnessTests.libraries.Omp_get_max_threadsTest;
import jUnitTestSuits.correctnessTests.libraries.Omp_get_num_procsTest;
import jUnitTestSuits.correctnessTests.libraries.Omp_get_num_threadsTest;
import jUnitTestSuits.correctnessTests.libraries.Omp_get_thread_numTest;
import jUnitTestSuits.correctnessTests.libraries.Omp_set_num_threadsTest;
import jUnitTestSuits.correctnessTests.loopFor.*;
import jUnitTestSuits.correctnessTests.master.Master_corrTest;
import jUnitTestSuits.correctnessTests.ordered.Ordered_corrTest;
import jUnitTestSuits.correctnessTests.parallel.*;
import jUnitTestSuits.correctnessTests.reduction.group1.*;
import jUnitTestSuits.correctnessTests.reduction.group2.*;
import jUnitTestSuits.correctnessTests.reduction.group3.*;
import jUnitTestSuits.correctnessTests.reduction.group4.*;
import jUnitTestSuits.correctnessTests.reduction.group5.*;
import jUnitTestSuits.correctnessTests.reduction.group6.*;
import jUnitTestSuits.correctnessTests.reduction.group7.*;
import jUnitTestSuits.correctnessTests.reduction.group8.*;
import jUnitTestSuits.correctnessTests.schedule.*;
import jUnitTestSuits.correctnessTests.sections.Sections_corrTest;
import jUnitTestSuits.correctnessTests.shared.*;
import jUnitTestSuits.correctnessTests.single.Single_corrTest;
import jUnitTestSuits.memoryAndCPUTest.loopFor.*;
import jUnitTestSuits.memoryAndCPUTest.parallel.Parallel_MacTest;
import jUnitTestSuits.memoryAndCPUTest.schedule.Schedule_Group1_MacTest;
import jUnitTestSuits.memoryAndCPUTest.schedule.Schedule_Group2_MacTest;
import jUnitTestSuits.memoryAndCPUTest.schedule.Schedule_Group3_MacTest;
import jUnitTestSuits.memoryAndCPUTest.schedule.Schedule_Group4_MacTest;
import jUnitTestSuits.memoryAndCPUTest.schedule.Schedule_Group5_MacTest;
import jUnitTestSuits.memoryAndCPUTest.schedule.Schedule_Group6_MacTest;
import jUnitTestSuits.runningTimeAndStabilityTest.loopFor.*;
import jUnitTestSuits.runningTimeAndStabilityTest.parallel.*;
import jUnitTestSuits.runningTimeAndStabilityTest.schedule.*;
import org.junit.runner.JUnitCore;
import Utility.ResultReportHelper.GenerateReport;
public class JunitTestRunner {
//
private static int CompileRunCount = 0;
private static long CompileRunTime = 0;
private static int CompileFailureCount = 0;
private static int MaCRunCount = 0;
private static long MaCRunTime = 0;
private static int MaCFailureCount = 0;
private static int RTRunCount = 0;
private static long RTRunTime = 0;
private static int RTFailureCount = 0;
private static int CorrectnessRunCount = 0;
private static long CorrectnessRunTime = 0;
private static int CorrectnessFailureCount = 0;
/**
* @param args
*/
public static void main(String[] args) {
Class<?>[] directiveClasses = { BarrierTest.class,
CriticalTest.class, FlushTest.class, MasterTest.class,
OrderedTest.class, SectionsTest.class, SingleTest.class,
LoopForTest.class, ParallelTest.class };
Class<?>[] ClausesClasses = { PrivateTest.class,
FirstPrivateTest.class, LastPrivateTest.class,
CopyPrivateTest.class, SharedTest.class, ReductionTest.class,
ScheduleTest.class };
org.junit.runner.Result DirectiveResult = JUnitCore
.runClasses(directiveClasses);
org.junit.runner.Result ClausesResult = JUnitCore
.runClasses(ClausesClasses);
org.junit.runner.Result LibraryResult = JUnitCore
.runClasses(LibrariesTest.class);
CompileRunCount = DirectiveResult.getRunCount()
+ ClausesResult.getRunCount() + LibraryResult.getRunCount();
CompileRunTime = DirectiveResult.getRunTime()
+ ClausesResult.getRunTime() + LibraryResult.getRunTime();
CompileFailureCount = DirectiveResult.getFailureCount()
+ ClausesResult.getFailureCount()
+ LibraryResult.getFailureCount();
// /////////////////////////////////////////////////////////////////////////////////////////
Class<?>[] directiveClasses_CPUandMemory = {
// LoopFor_Group1_MacTest.class, LoopFor_Group2_MacTest.class,
// LoopFor_Group3_MacTest.class, LoopFor_Group4_MacTest.class,
// Parallel_MacTest.class, Schedule_Group3_MacTest.class,
// Schedule_Group5_MacTest.class, Schedule_Group1_MacTest.class,
// Schedule_Group2_MacTest.class, Schedule_Group4_MacTest.class,
// Schedule_Group6_MacTest.class
};
org.junit.runner.Result DirectiveResult_MaC = JUnitCore
.runClasses(directiveClasses_CPUandMemory);
MaCRunCount = DirectiveResult_MaC.getRunCount();
MaCRunTime = DirectiveResult_MaC.getRunTime();
MaCFailureCount = DirectiveResult_MaC.getFailureCount();
Class<?>[] directiveClasses_RunningTime = {
// LoopFor_Group1_RtTest.class, LoopFor_Group2_RtTest.class,
// LoopFor_Group3_RtTest.class, LoopFor_Group4_RtTest.class,
// LoopFor_Group5_RtTest.class, LoopFor_Group6_RtTest.class,
// Parallel_Group1_RtTest.class, Parallel_Group2_RtTest.class,
// Parallel_Group3_RtTest.class, Schedule_Group1_RtTest.class,
// Schedule_Group2_RtTest.class, Schedule_Group3_RtTest.class,
// Schedule_Group4_RtTest.class, Schedule_Group5_RtTest.class,
// Schedule_Group6_RtTest.class
};
org.junit.runner.Result DirectiveResult_RT = JUnitCore
.runClasses(directiveClasses_RunningTime);
RTRunCount = DirectiveResult_RT.getRunCount();
RTRunTime = DirectiveResult_RT.getRunTime();
RTFailureCount = DirectiveResult_RT.getFailureCount();
// ///////////////////////////////////////////////////////////////////////////////////////////
/***************************************
* Do not include correctness tests
* *************************************/
Class<?>[] libraryClasses_corr = {
Omp_get_max_threadsTest.class,
Omp_get_num_procsTest.class,
Omp_get_num_threadsTest.class,
Omp_get_thread_numTest.class,
Omp_set_num_threadsTest.class
};
org.junit.runner.Result LibraryResult_corr = JUnitCore
.runClasses(libraryClasses_corr);
Class<?>[] directiveClasses_corr = {
Single_corrTest.class,
Ordered_corrTest.class,
Master_corrTest.class,
Sections_corrTest.class,
Barrier_corrTest.class,
Critical_corrTest.class,
Flush_corrTest.class,
LoopFor_Group1_corrTest.class, LoopFor_Group2_corrTest.class,
LoopFor_Group3_corrTest.class, LoopFor_Group4_corrTest.class,
LoopFor_Group5_corrTest.class, LoopFor_Group6_corrTest.class,
Parallel_Group1_corrTest.class, Parallel_Group2_corrTest.class,
Parallel_Group3_corrTest.class
};
org.junit.runner.Result DirectiveResult_corr = JUnitCore
.runClasses(directiveClasses_corr);
Class<?>[] clausesClasses_corr = {
FirstPrivate_Group1_corrTest.class,
FirstPrivate_Group2_corrTest.class,
Shared_Group1Test.class,
Shared_Group2Test.class,
Shared_Group3Test.class,
Schedule_Group1Test.class, Schedule_Group2Test.class,
Schedule_Group3Test.class, Schedule_Group4Test.class,
Schedule_Group5Test.class, Schedule_Group6Test.class,
Reduction_Group1_1Test.class,
Reduction_Group1_2Test.class,
Reduction_Group1_3Test.class,
Reduction_Group2_1Test.class,
Reduction_Group2_2Test.class,
Reduction_Group2_3Test.class,
Reduction_Group3_1Test.class,
Reduction_Group3_2Test.class,
Reduction_Group3_3Test.class,
Reduction_Group4_1Test.class,
Reduction_Group4_2Test.class,
Reduction_Group4_3Test.class,
Reduction_Group7_1Test.class,
Reduction_Group7_2Test.class,
Reduction_Group7_3Test.class,
Reduction_Group8_1Test.class,
Reduction_Group8_2Test.class,
Reduction_Group8_3Test.class,
};
org.junit.runner.Result ClausesResult_corr = JUnitCore
.runClasses(clausesClasses_corr);
CorrectnessRunCount = DirectiveResult_corr.getRunCount()
+ ClausesResult_corr.getRunCount()
+ LibraryResult_corr.getRunCount();
CorrectnessRunTime = DirectiveResult_corr.getRunTime()
+ ClausesResult_corr.getRunTime()
+ LibraryResult_corr.getRunTime();
CorrectnessFailureCount = DirectiveResult_corr.getFailureCount()
+ ClausesResult_corr.getFailureCount()
+ LibraryResult_corr.getFailureCount();
// Gennerate Report Parameters
int[] RunCount = { CompileRunCount, CorrectnessRunCount, RTRunCount,
MaCRunCount };
long[] RunTime = { CompileRunTime, CorrectnessRunTime, RTRunTime,
MaCRunTime };
int[] FailrueCount = { CompileFailureCount, CorrectnessFailureCount,
RTFailureCount, MaCFailureCount };
// Generate Report
GenerateReport report = new GenerateReport();
report.generate(RunCount, RunTime, FailrueCount);
System.out.println("Finished!");
}
}
|
package org.qizuo.cm;
import ch.qos.logback.ext.spring.web.LogbackConfigListener;
import org.qizuo.cm.frame.filter_interceptor.springmvc.SpringmvcDispatcherServlet;
import org.qizuo.cm.frame.listener.session.SessionListener;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import javax.servlet.*;
import java.util.EnumSet;
/**
* @Author: fangl
* @Description: 初始化(无需改动)
* @Date: 17:24 2018/10/25
*/
public class Start implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//spring启动项(Listener配置)
servletContext.setInitParameter("contextConfigLocation", "classpath:config/spring/applicationContext.xml");
servletContext.addListener(ContextLoaderListener.class);
//日志打印(Listener配置)
servletContext.setInitParameter("logbackConfigLocation", "classpath:config/log/logback.xml");
servletContext.addListener(LogbackConfigListener.class);
//单个用户登录监听
servletContext.addListener(SessionListener.class);
//request获取
servletContext.addListener(RequestContextListener.class);
//字符集过滤(filter方式加载)
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("utf-8");
FilterRegistration.Dynamic encoding = servletContext.addFilter("characterEncodingFilter", characterEncodingFilter);
EnumSet<DispatcherType> dispatcherTypes = EnumSet.allOf(DispatcherType.class);
dispatcherTypes.add(DispatcherType.REQUEST);
dispatcherTypes.add(DispatcherType.FORWARD);
encoding.addMappingForUrlPatterns(dispatcherTypes, true, "/");
//springMvc启动项(servlet方式加载)
XmlWebApplicationContext appContext = new XmlWebApplicationContext();
appContext.setConfigLocation("classpath:config/spring/spring-mvc.xml");
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new SpringmvcDispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
//listener加载(Listener可以用上述的加载方式,也可以用这个方式)
/*ContextLoaderListener logbackConfigLocation=new ContextLoaderListener();
logbackConfigLocation.initWebApplicationContext(servletContext);*/
}
}
|
package swm11.jdk.jobtreaming.back.app.notice.model;
import lombok.Getter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import swm11.jdk.jobtreaming.back.app.common.model.AbstractBoard;
import swm11.jdk.jobtreaming.back.app.expert.model.Expert;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.io.Serializable;
@Entity
@Table(name = "notice")
@Getter
@DynamicInsert
@DynamicUpdate
public class Notice extends AbstractBoard implements Serializable {
@ManyToOne
@JoinColumn(nullable = false, referencedColumnName = "id")
private Expert writer; // 작성자
}
|
package net.liuzd.spring.boot.v2.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class HelloController {
@GetMapping(value= {"","hello"})
public String Hello() {
return "Hello this is SpringWebFlux";
}
@GetMapping("hellos")
public Mono<String> sayHelloWorld() {
return Mono.just("Hello World");
}
}
|
package registration.booking.service.service;
import registration.booking.service.model.Cart;
public interface CartService {
Cart createOrUpdate(Cart cart);
Cart find(Long id);
}
|
/**
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of the Liferay Enterprise
* Subscription License ("License"). You may not use this file except in
* compliance with the License. You can obtain a copy of the License by
* contacting Liferay, Inc. See the License for the specific language governing
* permissions and limitations under the License, including but not limited to
* distribution rights of the Software.
*
*
*
*/
package com.everis.formacion.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* This class is used by SOAP remote services.
*
* @author dmartici
* @generated
*/
public class FabricanteSoap implements Serializable {
public static FabricanteSoap toSoapModel(Fabricante model) {
FabricanteSoap soapModel = new FabricanteSoap();
soapModel.setFabricanteId(model.getFabricanteId());
soapModel.setCompanyId(model.getCompanyId());
soapModel.setGroupId(model.getGroupId());
soapModel.setUserId(model.getUserId());
soapModel.setNombre(model.getNombre());
soapModel.setEmail(model.getEmail());
soapModel.setWeb(model.getWeb());
soapModel.setTelefono(model.getTelefono());
soapModel.setFechaAlta(model.getFechaAlta());
soapModel.setMailPersonaContacto(model.getMailPersonaContacto());
soapModel.setNumeroEmpleados(model.getNumeroEmpleados());
return soapModel;
}
public static FabricanteSoap[] toSoapModels(Fabricante[] models) {
FabricanteSoap[] soapModels = new FabricanteSoap[models.length];
for (int i = 0; i < models.length; i++) {
soapModels[i] = toSoapModel(models[i]);
}
return soapModels;
}
public static FabricanteSoap[][] toSoapModels(Fabricante[][] models) {
FabricanteSoap[][] soapModels = null;
if (models.length > 0) {
soapModels = new FabricanteSoap[models.length][models[0].length];
}
else {
soapModels = new FabricanteSoap[0][0];
}
for (int i = 0; i < models.length; i++) {
soapModels[i] = toSoapModels(models[i]);
}
return soapModels;
}
public static FabricanteSoap[] toSoapModels(List<Fabricante> models) {
List<FabricanteSoap> soapModels = new ArrayList<FabricanteSoap>(models.size());
for (Fabricante model : models) {
soapModels.add(toSoapModel(model));
}
return soapModels.toArray(new FabricanteSoap[soapModels.size()]);
}
public FabricanteSoap() {
}
public long getPrimaryKey() {
return _fabricanteId;
}
public void setPrimaryKey(long pk) {
setFabricanteId(pk);
}
public long getFabricanteId() {
return _fabricanteId;
}
public void setFabricanteId(long fabricanteId) {
_fabricanteId = fabricanteId;
}
public long getCompanyId() {
return _companyId;
}
public void setCompanyId(long companyId) {
_companyId = companyId;
}
public long getGroupId() {
return _groupId;
}
public void setGroupId(long groupId) {
_groupId = groupId;
}
public long getUserId() {
return _userId;
}
public void setUserId(long userId) {
_userId = userId;
}
public String getNombre() {
return _nombre;
}
public void setNombre(String nombre) {
_nombre = nombre;
}
public String getEmail() {
return _email;
}
public void setEmail(String email) {
_email = email;
}
public String getWeb() {
return _web;
}
public void setWeb(String web) {
_web = web;
}
public String getTelefono() {
return _telefono;
}
public void setTelefono(String telefono) {
_telefono = telefono;
}
public Date getFechaAlta() {
return _fechaAlta;
}
public void setFechaAlta(Date fechaAlta) {
_fechaAlta = fechaAlta;
}
public String getMailPersonaContacto() {
return _mailPersonaContacto;
}
public void setMailPersonaContacto(String mailPersonaContacto) {
_mailPersonaContacto = mailPersonaContacto;
}
public long getNumeroEmpleados() {
return _numeroEmpleados;
}
public void setNumeroEmpleados(long numeroEmpleados) {
_numeroEmpleados = numeroEmpleados;
}
private long _fabricanteId;
private long _companyId;
private long _groupId;
private long _userId;
private String _nombre;
private String _email;
private String _web;
private String _telefono;
private Date _fechaAlta;
private String _mailPersonaContacto;
private long _numeroEmpleados;
}
|
/*
* Name: Bahari Hasjim A12110331
* Login: cs8bach
* Date: January 21, 2015
* File: WordCloud.java
* Sources of Help: Derrick Lieu (roommate), piazza
*
* This program creates methods for WordCloud that can read in a text input
* and then adds the words to the list if it is unique, or increment the
* frequency if the word already exists. It also has a method that removes
* common words so that they will not be included in the list.
* Additionally, this class has a method that will print out the n most frequent
* words in the list
*/
// Don't remove these lines. They tell java where to find various classes
// you will use.
import java.util.*;
import java.io.*;
/** Don't forget your comments */
public class WordCloud {
// The ArrayList to store the words and their associated counts
ArrayList<WordPair> list;
// construct the list
public WordCloud() {
list = new ArrayList<WordPair>();
}
// This method will read all the words from the source file and properly
// update the list
public boolean getWordsFromFile(String filename ) throws IOException {
Scanner input = new Scanner (new File(filename));
//initializes the list so that size > 0
list.add(new WordPair(input.next()));
// go through all the words from the input
while(input.hasNext())
{
String fileWord = input.next();
String caseInsensFileWord = fileWord;
caseInsensFileWord = caseInsensFileWord.toLowerCase();
boolean wordsMatch=false;
int savedIndex=0;
// goes through the list and sees if there is a match or not
for(int index = 0; index < list.size(); index++)
{
WordPair word = list.get(index);
String caseInsensWord = word.getWord();
caseInsensWord = caseInsensWord.toLowerCase();
if(caseInsensFileWord.equals(caseInsensWord))
{
wordsMatch=true;
savedIndex=index;
}
}
// if it matches, increase the count
// if it does not match, add that word as a new wordPair to the list
if(wordsMatch)
{
list.get(savedIndex).increment();
}
else
{
list.add(new WordPair(fileWord));
}
}
return true;
}
// This method will remove any commonly used words from
// the list. You may either remove the element or just
// set the number of occurences to a small value
public void removeCommon( String omitFilename ) throws IOException {
Scanner input = new Scanner(new File(omitFilename));
while(input.hasNext())
{
String omitWord = input.next();
String caseInsensOmitWord = omitWord;
caseInsensOmitWord = caseInsensOmitWord.toLowerCase();
for(int index=0; index < list.size(); index++)
{
WordPair doesThisMatch = list.get(index);
String caseInsensMatch = doesThisMatch.getWord();
caseInsensMatch = caseInsensMatch.toLowerCase();
if(caseInsensOmitWord.equals(caseInsensMatch))
{
doesThisMatch.setCount(-1);
}
}
}
}
// This method sorts the list through selection sort
// it finds the word with the smallest "count"
// Then it moves that word to the left,sorted side of the array
// Then, we find the word with the next smallest "count"
// Then move that word to the index after the word with the smallest "count"
public void selectionSort(){
// this will be the index of the sorted side of the array
for(int i=0; i<list.size()-1; i++) {
minIndex = i;
//find the word with the smallest count in the unsorted side of the array
for(int j=i+1; j<list.size(); j++) {
if(list.get(j).getCount() < list.get(i).getCount())
minIndex = j;
}
//swaps the word with the smallest count to its new position.
//also swaps the word that was replaced, to where the word with the smallest count
//used to be
if(minIndex != i) {
int tmp = list.get(i);
list.set(i, list.get(minIndex));
list.set(minIndex, tmp);
}
}
}
}
// This method prints the top n occurring words in the
// list. In the event of a tie, use the first occurring
// word with that count.
public void printTopNWords(int n) {
// it said that I could break the list
// but I just challenged myself to see if I could do it
// without breaking the list
ArrayList<WordPair> copyOfList = new ArrayList<WordPair>(list);
// find how many unique words there are
int countOfUniqueWords=0;
for(int index=0; index < copyOfList.size(); index++)
{
if(copyOfList.get(index).getCount() > 0 )
countOfUniqueWords++;
}
// makes sure n stops at the number of unique words in the file
if(n > countOfUniqueWords)
n = countOfUniqueWords;
// makes sure that n is in bounds
if(n > 0)
{
// repeats this n amount of times
for(int numPrints=0; numPrints < n; numPrints++)
{
int indexOfMax=0;
WordPair max = copyOfList.get(indexOfMax);
// gets the wordPair with the highest frequency
// gets the index of the wordPair with the highest frequency
for(int i=1; i< copyOfList.size(); i++)
{
WordPair wordInList = copyOfList.get(i);
if(wordInList.getCount() > max.getCount())
{
indexOfMax = i;
max = copyOfList.get(indexOfMax);
}
}
// prints the max wordPair, then sets its count to -1
// so that the loop can find the next highest count.
System.out.print(max.getWord() + "("+max.getCount()+") ");
max.setCount(-1);
}
System.out.println();
}
// if n is less than 0 print out an error
else if (n < 0){
System.out.println("Error: n is less than 0");
}
// FORMAT FOR PRINT, use format exactly
// You may need to use your own variable names
// where 'max' below is the WordPair to print
//System.out.print(max.getWord() + "("+max.getCount()+") ");
}
}
|
package com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.widget.verticalviewpager.a;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.ImageView.ScaleType;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.i;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.s;
import com.tencent.mm.plugin.sns.ui.am;
class b$7 implements Runnable {
final /* synthetic */ b nHy;
b$7(b bVar) {
this.nHy = bVar;
}
public final void run() {
int i = 0;
if (b.a(this.nHy) != null) {
if ((b.d(this.nHy).nIh || !TextUtils.isEmpty(b.d(this.nHy).nIg)) && !b.l(this.nHy)) {
b.m(this.nHy);
b.a(this.nHy).nHL.setVisibility(0);
b.a(this.nHy).nHI.setScaleType(ScaleType.CENTER_CROP);
b.a(this.nHy).nHL.getViewTreeObserver().addOnPreDrawListener(new 1(this));
a o = b.o(this.nHy);
ViewGroup viewGroup = b.a(this.nHy).nHL;
while (true) {
int i2 = i;
if (i2 < o.nHg.nIi.size()) {
i a = am.a(viewGroup.getContext(), (s) o.nHg.nIi.get(i2), viewGroup, o.bgColor);
if (a != null) {
if (a.getView().getParent() != null && (a.getView().getParent() instanceof ViewGroup)) {
((ViewGroup) a.getView().getParent()).removeView(a.getView());
}
a.getView().setTag(a);
viewGroup.addView(a.getView());
}
i = i2 + 1;
} else {
return;
}
}
}
}
}
}
|
package JavaLangClasses;
/**
* A method 'freeMemory()' is used to get amount of free memory Java Virtual
* Machine in bytes.
*
* A method 'gc()' is used to activate garbage collector.
*
* A method 'totalMemory()' is used to get amount of total memory Java Virtual
* Machine in bytes.
*
* @author Bohdan Skrypnyk
*/
public class MemoryDemo {
public static void main(String args[]) {
Runtime rn = Runtime.getRuntime();
double mem1, mem2;
Integer num[] = new Integer[10000];
System.out.println("Total memory : " + rn.totalMemory() / Math.pow(2, 20) + " Megabyte");
mem1 = rn.freeMemory() / Math.pow(2, 20); // get free memory in JVM
System.out.println("Free memory : " + Math.round(mem1 * 100) / 100.0 + " Megabyte");
rn.gc(); // run garbage collector
mem1 = rn.freeMemory() / Math.pow(2, 20); // get free memory in JVM
System.out.println("Total memory after cleaning: " + Math.round(mem1 * 100) / 100.0 + " Megabyte");
for (int i = 0; i < num.length; i++) { // allocate memory for the object Integer
num[i] = new Integer(i);
}
mem2 = rn.freeMemory() / Math.pow(2, 20); // get free memory in JVM
System.out.println("Total memory after allocation: " + Math.round(mem2 * 100) / 100.0 + " Megabyte");
System.out.println("Used memory for allocation of the type Integer: " + Math.round((mem2 - mem1) * 100) / 100.0 + " Megabyte");
for (int i = 0; i < num.length; i++) {// remove the object Integer
num[i] = null;
}
rn.gc(); // run garbage collector
mem2 = rn.freeMemory() / Math.pow(2, 20); // get free memory in JVM
System.out.println("Total memory after cleaning objects of the type Integer: " + Math.round(mem2 * 100) / 100.0 + " Megabyte");
}
}
|
package com.example.firebaselogin.Controllers;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.Html;
import com.example.firebaselogin.R;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Objects;
public class FunctionController {
// Property
Activity activity;
// Constructor
public FunctionController(Activity activity) {
this.activity = activity;
}
// Methods
public void changeStatusBar(String color){
String colorFull = "#" + color;
activity.getWindow().setStatusBarColor(Color.parseColor(colorFull));
}
public void dialog(String title, String message, int icon, String type){
MaterialAlertDialogBuilder dialogBuilder;
dialogBuilder = (type.equals("error")) ? new MaterialAlertDialogBuilder(activity, R.style.dialogError) :
new MaterialAlertDialogBuilder(activity, R.style.dialogSuccess);
dialogBuilder
.setTitle(Html.fromHtml(title))
.setMessage(Html.fromHtml(message))
.setIcon(icon)
.setBackground(activity.getResources().getDrawable(R.drawable.bg_dialog))
.setPositiveButton("Exit", null)
.show();
}
@SuppressLint("UseCompatLoadingForDrawables")
public void dialog(String title, String message, int icon, boolean isInternetDialog){
MaterialAlertDialogBuilder dialogBuilder = new MaterialAlertDialogBuilder(activity, R.style.dialog);
dialogBuilder
.setTitle(Html.fromHtml(title))
.setMessage(Html.fromHtml(message))
.setIcon(icon)
.setBackground(activity.getResources().getDrawable(R.drawable.bg_dialog))
.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Objects.requireNonNull(activity).finish();
}
})
.setCancelable(false)
.show();
}
/**
* @return if the network is on or off (true or false)
*/
public boolean isConnected(){
ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnectedOrConnecting()) return true; // Connected
else return false; // Disconnected
}
/**
* @param price double parameter to R$
* @return
*/
public static String toBrazilianCoin(double price){
Locale ptBr = new Locale("pt", "BR");
return NumberFormat.getCurrencyInstance(ptBr).format(price);
}
}
|
package com.ibm.jikesbt;
/*
* Licensed Material - Property of IBM
* (C) Copyright IBM Corp. 1998, 2003
* All rights reserved
*/
/**
Represents an opc_ldc or opc_ldc_w instruction.
Typically created by one of the {@link BT_Ins#make} methods.
* @author IBM
**/
public final class BT_ConstantClassIns extends BT_ConstantIns {
public BT_Class value;
BT_ConstantClassIns(int opcode, int index, BT_Class value) {
super(opcode, index);
this.value = value;
}
BT_ConstantClassIns(int opcode, int index, String className, BT_Repository repo) {
super(opcode, index);
this.value = repo.forName(className);;
}
protected int constantIndex(BT_ConstantPool pool) {
return pool.indexOfClassRef(value);
}
public String getInstructionTarget() {
return getJavaLangClass().useName();
}
public void resolve(BT_CodeAttribute code, BT_ConstantPool pool) {
opcode = BT_Misc.overflowsUnsignedByte(constantIndex(pool)) ? opc_ldc_w : opc_ldc;
}
public boolean optimize(BT_CodeAttribute code, int n, boolean strict) {
BT_InsVector ins = code.getInstructions();
boolean result = false;
// optimize ldc "Class"; ldc "Class" to
// ldc "String"; dup
//
if (ins.size() > n + 1
&& ins.elementAt(n).isLoadConstantClassIns()
&& ins.elementAt(n + 1).isLoadConstantClassIns()) {
BT_Class s1 = ((BT_ConstantClassIns) ins.elementAt(n)).getValue();
BT_Class s2 = ((BT_ConstantClassIns) ins.elementAt(n + 1)).getValue();
if (s1.equals(s2)) {
return code.replaceInstructionsAtWith(1, n + 1, make(opc_dup));
}
}
if (!result) {
result = super.optimize(code, n, strict);
}
return result;
}
String appendValueTo(String other) {
return other + value.getName();
}
public boolean isPushConstantIns() {
return false;
}
public boolean isLoadConstantClassIns() {
return true;
}
public int size() {
return (opcode == opc_ldc_w) ? 3 : 2;
}
public int maxSize() {
return 3;
}
public String toString() {
return getPrefix()
+ BT_Misc.opcodeName[opcode]
+ " (java.lang.Class) \""
+ value.getName()
+ "\"";
}
public String toAssemblerString(BT_CodeAttribute code) {
return BT_Misc.opcodeName[opcode]
+ " (java.lang.Class) \""
+ value.getName()
+ "\"";
}
public BT_Class getValue() {
return value;
}
public Object clone() {
return new BT_ConstantClassIns(opcode, -1, value);
}
public BT_Class getJavaLangClass() {
return value.repository.findJavaLangClass();
}
public void link(BT_CodeAttribute code) {
BT_ClassReferenceSite site = getJavaLangClass().addReferenceSite(this, code);
if(site != null) {
code.addReferencedClass(site);
}
}
public void unlink(BT_CodeAttribute code) {
getJavaLangClass().removeClassReferenceSite(this);
code.removeReferencedClass(this);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.