text stringlengths 10 2.72M |
|---|
package com.project.hadar.AcadeMovie.Activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.project.hadar.AcadeMovie.Analytics.AnalyticsManager;
import com.project.hadar.AcadeMovie.R;
import com.project.hadar.AcadeMovie.Adapter.ReviewsAdapter;
import com.project.hadar.AcadeMovie.Model.Movie;
import com.project.hadar.AcadeMovie.Model.ProfileWidget;
import com.project.hadar.AcadeMovie.Model.Review;
import com.project.hadar.AcadeMovie.Model.UserDetails;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ReservationSummaryActivity extends AppCompatActivity
{
private static final String TAG ="ReservationSummaryActivity";
private static final int MAX_CHAR = 5;
private Movie m_movie;
private String m_key;
private UserDetails m_userDetails;
private TextView m_movieNameTextView;
private TextView m_dateTextView;
private TextView m_CinemaLocationTextView;
private TextView m_genreTextView;
private TextView m_textViewTicketType1;
private TextView m_textViewTicketType2;
private TextView m_textViewTicketType3;
private TextView m_textViewTotalPrice;
private TextView m_textViewReviewCount;
private ImageButton m_profileWidgetImageButton;
private List<Review> m_reviewsList = new ArrayList<>();
private RecyclerView m_recyclerViewMovieReviews;
private ImageView m_imageViewMoviePic;
private RatingBar m_ratingBarForMovie;
private AnalyticsManager m_analyticsManager = AnalyticsManager.getInstance();
@Override
protected void onCreate(Bundle i_savedInstanceState)
{
Log.e(TAG, "onCreate() >>");
super.onCreate(i_savedInstanceState);
setContentView(R.layout.activity_reservation_summary);
findViews();
getMovieIntent();
getUserDetailsAndContinueOnCreate();
setReviewsAdapter();
setListenerToReview();
Log.e(TAG, "onCreate() <<");
}
@Override
protected void onResume()
{
super.onResume();
setListenerToReview();
}
@SuppressWarnings("ConstantConditions")
private void getUserDetailsAndContinueOnCreate()
{
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("Users/"
+ FirebaseAuth.getInstance().getCurrentUser().getUid());
userRef.addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange (DataSnapshot dataSnapshot)
{
m_userDetails = dataSnapshot.getValue(UserDetails.class);
displayUserImage();
setMovieDetails();
}
@Override
public void onCancelled (DatabaseError d)
{
}
}
);
}
private void setReviewsAdapter()
{
Log.e(TAG, "setReviewsAdapter() >>");
ReviewsAdapter reviewsAdapter = new ReviewsAdapter(m_reviewsList);
m_recyclerViewMovieReviews.setAdapter(reviewsAdapter);
Log.e(TAG, "setReviewsAdapter() <<");
}
//Note for me: Check if can be replaced with List.contains()
private boolean doesReviewListContainAReview(Review i_review)
{
boolean reviewFound = false;
for(int i = 0; i<m_reviewsList.size(); ++i)
{
if(m_reviewsList.get(i).getM_userEmail() != null &&
m_reviewsList.get(i).getM_userEmail().equals(i_review.getM_userEmail()))
{
reviewFound = true;
break;
}
}
return reviewFound;
}
private void setListenerToReview()
{
Log.e(TAG, "setListenerToReview() >>");
m_reviewsList.clear();
DatabaseReference movieReviewsRef = FirebaseDatabase.getInstance().getReference("Movie/" + m_key + "/reviews");
movieReviewsRef.addListenerForSingleValueEvent(new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot snapshot)
{
Log.e(TAG, "onDataChange() >> Movie/" );
for (DataSnapshot dataSnapshot : snapshot.getChildren())
{
Review review = dataSnapshot.getValue(Review.class);
if (!(doesReviewListContainAReview(review)))
{
m_reviewsList.add(review);
}
}
m_recyclerViewMovieReviews.getAdapter().notifyDataSetChanged();
Log.e(TAG, "onDataChange(Review) <<");
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled(Review) >>" + databaseError.getMessage());
}
});
Log.e(TAG, "setListenerToReview() <<");
}
private void findViews()
{
Log.e(TAG, "findViews() >>");
m_dateTextView = findViewById(R.id.textViewDate);
m_movieNameTextView = findViewById(R.id.textViewMovieName);
m_CinemaLocationTextView = findViewById(R.id.textViewCinemaLocation);
m_genreTextView = findViewById(R.id.textViewGenre);
m_profileWidgetImageButton = findViewById(R.id.profile_widget);
m_recyclerViewMovieReviews = findViewById(R.id.MovieReview);
m_recyclerViewMovieReviews.setHasFixedSize(true);
m_recyclerViewMovieReviews.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
m_recyclerViewMovieReviews.setItemAnimator(new DefaultItemAnimator());
m_imageViewMoviePic = findViewById(R.id.imageViewMoviePic);
m_textViewTicketType1 = findViewById(R.id.textViewTicketType1);
m_textViewTicketType2 = findViewById(R.id.textViewTicketType2);
m_textViewTicketType3 = findViewById(R.id.textViewTicketType3);
m_textViewTotalPrice = findViewById(R.id.textViewTotalPrice);
m_ratingBarForMovie = findViewById(R.id.ratingBarForMovie);
m_textViewReviewCount = findViewById(R.id.textViewReviewCount);
LayerDrawable stars = (LayerDrawable) m_ratingBarForMovie.getProgressDrawable();
stars.getDrawable(2).setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP);
stars.getDrawable(0).setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
stars.getDrawable(1).setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
Log.e(TAG, "findViews() <<");
}
private void getMovieIntent()
{
Log.e(TAG, "getMovieIntent() >>");
m_key = getIntent().getStringExtra("Key");
m_movie = (Movie) getIntent().getSerializableExtra("Movie");
Log.e(TAG, "getMovieIntent() <<");
}
private void setMovieDetails()
{
Log.e(TAG, "setMovieDetails() >>");
m_textViewTicketType1.setVisibility(View.INVISIBLE);
m_textViewTicketType2.setVisibility(View.INVISIBLE);
m_textViewTicketType3.setVisibility(View.INVISIBLE);
m_movieNameTextView.setText(m_movie.getM_name());
m_dateTextView.setText(m_movie.getM_date());
m_CinemaLocationTextView.setText(m_movie.getM_cinemaLocation());
m_genreTextView.setText(m_movie.getM_genre());
m_ratingBarForMovie.setRating(m_movie.getM_averageRating());
m_textViewReviewCount.setText("(" + m_movie.getM_reviewsCount() + ")");
setMovieImage();
setMoviePurchase();
Log.e(TAG, "setMovieDetails() <<");
}
@SuppressLint("SetTextI18n")
private void setMoviePurchase()
{
Log.e(TAG, "setMoviePurchase() >>");
int value;
m_textViewTotalPrice.setText(limitStrToMaxChar(String.valueOf(m_userDetails.getMoviesPurchaseMap().get(m_key).getM_purchaseAmount())) + "$");
Map<String, Integer> purchaseMap = m_userDetails.getMoviesPurchaseMap().get(m_key).getM_mapOfTypeTicketsAndQuantity();
if((value= purchaseMap.get("Standard")) != 0)
{
m_textViewTicketType1.setText(String.valueOf(value) + " Standard");
m_textViewTicketType1.setVisibility(View.VISIBLE);
}
if((value= purchaseMap.get("Student")) != 0)
{
m_textViewTicketType2.setText(String.valueOf(value) + " Student");
m_textViewTicketType2.setVisibility(View.VISIBLE);
}
if((value= purchaseMap.get("Soldier")) != 0)
{
m_textViewTicketType3.setText(String.valueOf(value) + " Soldier");
m_textViewTicketType3.setVisibility(View.VISIBLE);
}
Log.e(TAG, "setMoviePurchase() <<");
}
private void setMovieImage()
{
Log.e(TAG, "setMovieImage() >>");
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
storageReference.child("Movie Pictures/" + m_movie.getM_thumbImage())
.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>()
{
@Override
public void onSuccess(Uri uri)
{
Log.e(TAG, "pic src= " + uri.toString());
Glide.with(getApplicationContext()).load(uri.toString()).into(m_imageViewMoviePic);
}
});
Log.e(TAG, "setMovieImage() <<");
}
public void onAddReviewClick(View i_View)
{
Log.e(TAG, "onAddReviewClick() >>");
Intent intent = new Intent(getApplicationContext(),ReviewActivity.class);
intent.putExtra("Movie", m_movie);
intent.putExtra("Key", m_key);
intent.putExtra("UserEmail", m_userDetails.getUserEmail());
startActivity(intent);
Log.e(TAG, "onAddReviewClick() <<");
}
public void onClickProfileWidgetImageButton(View i_View)
{
Log.e(TAG, "onClickProfileWidgetImageButton() >>");
ProfileWidget.onClickProfileWidget(this, m_profileWidgetImageButton, m_userDetails);
Log.e(TAG, "onClickProfileWidgetImageButton() <<");
}
@Override
public void onBackPressed()
{
super.onBackPressed();
goToCinemaMainActivity();
}
private void goToCinemaMainActivity()
{
Intent cinemaMainActivity = new Intent(getApplicationContext(), CinemaMainActivity.class);
startActivity(cinemaMainActivity);
finish();
}
private void displayUserImage()
{
Log.e(TAG, "displayUserImage() >>");
ProfileWidget.displayUserImage(getApplicationContext(), m_profileWidgetImageButton, m_userDetails);
Log.e(TAG, "displayUserImage() <<");
}
public void onBuyMoreTicketsClick(View i_view)
{
Log.e(TAG, "onBuyMoreTicketsClick() >>");
m_analyticsManager.trackRepeatPurchase(m_movie);
m_analyticsManager.setUserProperty(m_userDetails);
Intent SelectTicketsIntent = new Intent(getApplicationContext(), SelectTicketsActivity.class);
SelectTicketsIntent.putExtra("Movie", m_movie);
SelectTicketsIntent.putExtra("Key", m_key);
startActivity(SelectTicketsIntent);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
Log.e(TAG, "onBuyMoreTicketsClick() <<");
}
private String limitStrToMaxChar(String i_Str)
{
String resStr = String.valueOf(i_Str);
int maxLength = (resStr.length() < MAX_CHAR)?resStr.length():MAX_CHAR;
return (resStr.substring(0, maxLength));
}
} |
package com.example.bbarroo.awesome;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class Bulletin_comment_main extends AppCompatActivity {
int sel;
TextView btn_comment;
Bulletin_comment_LVA adapter;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bulletin_detail);
ListView listview = findViewById(R.id.comment);
btn_comment = findViewById(R.id.comment_write);
Intent intent = getIntent();
sel = intent.getExtras().getInt("name");
adapter = new Bulletin_comment_LVA() ;
listview.setAdapter(adapter);
// 아이템 추가하는 방법 (제목, 내용, 이름, 시간)
adapter.addItem("어사화ㅂㅈ더ㅏㅣㅁㄴ으","어사화ㄷㄷ");
adapter.addItem("어서ㅂㅈㄷㅂ와","모두너");
adapter.addItem("어서ㅂㅈㄷㅂ와","모두너");
adapter.addItem("어서ㅂㅈㄷㅂ와","모두너");
adapter.addItem("어서ㅂㅈㄷㅂ와","모두너");
adapter.addItem("어서ㅂㅈㄷㅂ와","모두너");
adapter.addItem("어서ㅂㅈㄷㅂ와","모두너");
adapter.addItem("어서ㅂㅈㄷㅂ와","모두너");
adapter.addItem("어서ㅂㅈㄷㅂ와","모두너");
adapter.addItem("어서ㅂㅈㄷㅂ와","모두너");
adapter.addItem("어서ㅂㅈㄷㅂ와","모두너");
btn_comment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*Intent intent=new Intent(Bulletin_comment_main.this, Bulletin_Main.class);
intent.putExtra("name",sel);
startActivity(intent);*/
adapter.notifyDataSetChanged();
}
});
}
}
|
package br.com.caelum.vraptor.dao;
import java.io.File;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.caelum.vraptor.infra.CriadorDeSession;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.models.Categoria;
import br.com.caelum.vraptor.models.Playlist;
import br.com.caelum.vraptor.models.Video;
@Component
public class VideoDao {
private final Session session;
public VideoDao() {
this.session = CriadorDeSession.getSession();
}
public void salva(Video video) {
Transaction tx = session.beginTransaction();
session.save(video);
tx.commit();
}
public List<Playlist> listaTudo() {
return this.session.createCriteria(Video.class).list();
}
public List<Video> listaPorPlaylist(long playlistId) {
List<Video> videos = (List<Video>)session.createQuery( "from Video where playlist_id=:playlist_id" )
.setLong( "playlist_id",playlistId)
.list();
System.out.println(videos);
return videos;
}
public Video carrega(Long id) {
return (Video) this.session.load(Video.class, id);
}
public void atualiza(Video video) {
Transaction tx = session.beginTransaction();
this.session.update(video);
tx.commit();
}
public void remove(Video video) {
Transaction tx = session.beginTransaction();
this.session.delete(video);
tx.commit();
}
}
|
package jetris.model;
import static jetris.model.Block.Color.BLUE;
import static jetris.model.Block.Color.CYAN;
import static jetris.model.Block.Color.GREEN;
import static jetris.model.Block.Color.MAGENTA;
import static jetris.model.Block.Color.ORANGE;
import static jetris.model.Block.Color.RED;
import static jetris.model.Block.Color.YELLOW;
import com.google.common.collect.ImmutableList;
import jetris.model.Block.Color;
/**
* Represents a tetromino
*/
final class Tetromino extends GameObject {
/**
* Tetromino shapes, each known by its letter name.
* <pre>
* _ _ _ _
* I : |_|_|_|_|
* _
* J : |_|_ _
* |_|_|_|
* L : _
* _ _|_|
* |_|_|_|
* O : _ _
* |_|_|
* |_|_|
* S : _ _
* _|_|_|
* |_|_|
* T : _
* _|_|_
* |_|_|_|
* Z : _ _
* |_|_|_
* |_|_|
* </pre>
*/
enum Shape {
I,
J,
L,
O,
S,
T,
Z;
}
private final ImmutableList<Block> blocks;
private final Shape shape;
Tetromino(Shape shape) {
this.shape = shape;
this.blocks = blocksFor(shape);
}
ImmutableList<Block> blocks() {
return blocks;
}
Tetromino moveLeft() {
ImmutableList.Builder<Block> builder = ImmutableList.builder();
for (Block block : blocks) {
builder.add(block.moveLeft());
}
return new Tetromino(shape, builder.build());
}
Tetromino moveRight() {
ImmutableList.Builder<Block> builder = ImmutableList.builder();
for (Block block : blocks) {
builder.add(block.moveRight());
}
return new Tetromino(shape, builder.build());
}
Tetromino moveDown() {
ImmutableList.Builder<Block> builder = ImmutableList.builder();
for (Block block : blocks) {
builder.add(block.moveDown());
}
return new Tetromino(shape, builder.build());
}
Tetromino rotateLeft() {
return rotateRight().rotateRight().rotateRight();
}
Tetromino rotateRight() {
if (shape == Shape.O) {
return this;
}
return rotate90Degrees();
}
private Tetromino rotate90Degrees() {
/*
* As y axis points down not up, standard transformation
* matrices need to be inverted. Therefore we apply 270
* transform matrix to affect 90 degree turn around
* first block.
*/
int centreX = blocks.get(0).x();
int centreY = blocks.get(0).y();
ImmutableList.Builder<Block> builder = ImmutableList.builder();
for (Block block : blocks) {
int x = ((centreY - block.y()) + centreX);
int y = (-1 * (centreX - block.x())) + centreY;
builder.add(new Block(block.color(), x, y));
}
return new Tetromino(shape, builder.build());
}
private Tetromino(Shape shape,
ImmutableList<Block> blocks) {
this.shape = shape;
this.blocks = blocks;
}
private static ImmutableList<Block> blocksFor(Shape shape) {
switch (shape) {
case I: return blocksFor(CYAN, 1,0, 0,0, 2,0, 3,0);
case J: return blocksFor(BLUE, 1,1, 0,0, 0,1, 2,1);
case L: return blocksFor(ORANGE, 1,1, 2,0, 0,1, 2,1);
case O: return blocksFor(YELLOW, 0,0, 1,0, 0,1, 1,1);
case S: return blocksFor(GREEN, 1,1, 1,0, 2,0, 0,1);
case T: return blocksFor(MAGENTA, 1,1, 1,0, 0,1, 2,1);
default:
assert shape == Shape.Z;
return blocksFor(RED, 1,1, 0,0, 1,0, 2,1);
}
}
/*
* Returns list of colored blocks, centered around the first
* set of x,y coordinates
*/
private static ImmutableList<Block> blocksFor(Color color,
int x1, int y1,
int x2, int y2,
int x3, int y3,
int x4, int y4) {
return ImmutableList.of(new Block(color, x1, y1),
new Block(color, x2, y2),
new Block(color, x3, y3),
new Block(color, x4, y4));
}
}
|
package com.tencent.mm.plugin.sns.storage;
public class b$b {
public String ntt = "";
public String nzA = "";
public String nzz = "";
public String url = "";
}
|
package com.rc.app;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DraggedTest extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DraggedTest frame = new DraggedTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public DraggedTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(660, 500);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
add(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setBorder(BorderFactory.createLineBorder(Color.orange, 2));
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBackground(Color.GRAY);
panel_1.setBounds(82, 85, 130, 130);
panel.add(panel_1);
JPanel panel_2 = new JPanel();
panel_2.setBackground(Color.LIGHT_GRAY);
panel_2.setBounds(261, 85, 130, 130);
panel.add(panel_2);
JPanel panel_3 = new JPanel();
panel_3.setBackground(Color.MAGENTA);
panel_3.setBounds(450, 85, 130, 130);
panel.add(panel_3);
JPanel panel_4 = new JPanel();
panel_4.setBackground(Color.ORANGE);
panel_4.setBounds(261, 285, 130, 130);
panel.add(panel_4);
MyListener m = new MyListener();
panel_1.addMouseListener(m);
panel_1.addMouseMotionListener(m);
panel_2.addMouseListener(m);
panel_2.addMouseMotionListener(m);
panel_3.addMouseListener(m);
panel_3.addMouseMotionListener(m);
panel_4.addMouseListener(m);
panel_4.addMouseMotionListener(m);
}
// 写一个类继承鼠标监听器的适配器,这样就可以免掉不用的方法。
class MyListener extends MouseAdapter{
//这两组x和y为鼠标点下时在屏幕的位置和拖动时所在的位置
int newX,newY,oldX,oldY;
//这两个坐标为组件当前的坐标
int startX,startY;
@Override
public void mousePressed(MouseEvent e) {
//此为得到事件源组件
Component cp = (Component)e.getSource();
//当鼠标点下的时候记录组件当前的坐标与鼠标当前在屏幕的位置
startX = cp.getX();
startY = cp.getY();
oldX = e.getXOnScreen();
oldY = e.getYOnScreen();
}
@Override
public void mouseDragged(MouseEvent e) {
Component cp = (Component)e.getSource();
//拖动的时候记录新坐标
newX = e.getXOnScreen();
newY = e.getYOnScreen();
//设置bounds,将点下时记录的组件开始坐标与鼠标拖动的距离相加
cp.setBounds(startX+(newX - oldX), startY+(newY - oldY), cp.getWidth(), cp.getHeight());
}
}
} |
package com.bingo.code.example.design.decorator.module;
/**
* װ�����ӿڣ�ά��һ��ָ���������Ľӿڶ���
* ������һ��������ӿ�һ�µĽӿ�
*/
public abstract class Decorator extends Component {
/**
* �����������
*/
protected Component component;
/**
* ���췽���������������
* @param component �������
*/
public Decorator(Component component) {
this.component = component;
}
public void operation() {
//ת������������������ת��ǰ��ִ��һЩ���Ӷ���
component.operation();
}
}
|
package vn.edu.techkids.controllers;
import vn.edu.techkids.controllers.enemyplanes.EnemyPlaneControllerManager;
import vn.edu.techkids.models.GameObject;
import vn.edu.techkids.views.GameDrawer;
import vn.edu.techkids.views.ImageDrawer;
import java.awt.*;
import java.util.Iterator;
import java.util.Vector;
/**
* Created by Ngoc on 5/13/2016.
*/
public class BombController extends SingleController implements Colliable {
public BombController(GameObject gameObject, GameDrawer gameDrawer) {
super(gameObject, gameDrawer);
CollisionPool.getInst().add(this);
}
private static BombController inst;
public static BombController getInst(){
if(inst == null){
GameObject gameObject = new GameObject(300,200,50,50);
ImageDrawer imageDrawer = new ImageDrawer("resources/bomb.png");
inst = new BombController(gameObject,imageDrawer);
}
return inst;
}
@Override
public void onCollide(Colliable c) {
if (c instanceof PlaneController) {
EnemyPlaneControllerManager enemyPlaneControllerManager = EnemyPlaneControllerManager.getInst();
Vector<SingleController> enemyVector = enemyPlaneControllerManager.getSingleControllerVector();
Iterator<SingleController> enemyIterator = enemyVector.iterator();
while (enemyIterator.hasNext()) {
SingleController singleController = enemyIterator.next();
enemyIterator.remove();
}
this.getGameObject().setAlive(false);
}
}
@Override
public void paint(Graphics g) {
if (this.getGameObject().isAlive()) {
super.paint(g);
}
}
}
|
package hr.unipu.java;
import java.util.Scanner;
public class Main {
private static MaxNumberOfQuestions max;
public static void main (String[] args) {
Quiz quiz = new Quiz();
ShortAnswerQuestion question = new ShortAnswerQuestion("U kojem jeziku se programira za Android?", "Java");
quiz.addQuestion(question);
Scanner scanner = new Scanner(System.in);
String izbor;
String pitanje;
String odgovor;
System.out.println("Ako želite unijeti novo pitanje pritisnite tipku 1.");
System.out.println("Ako ne želite unijeti novo pitanje pritisnite tipku 2.");
izbor = scanner.nextLine();
while (izbor.equalsIgnoreCase("1")) try {
System.out.println("Upišite pitanje: ");
pitanje = scanner.nextLine();
System.out.println("Unesite odgovor na pitanje koje ste upisali: ");
odgovor = scanner.nextLine();
ShortAnswerQuestion NovoPitanje = new ShortAnswerQuestion(pitanje, odgovor);
quiz.addQuestion(NovoPitanje);
if (quiz.getNoOfQuestions() < 5) {
System.out.println("Želite li unijeti još pitanja?");
System.out.println("Ako ne želite unijeti još pitanja pritisnite broj 2.");
izbor = scanner.nextLine();
}
else {
throw new MaxNumberOfQuestions("Došli ste do maksimalnog broja pitanja.");
}
if (izbor.equalsIgnoreCase("2")) {
int tocno = 0;
for (int i = 0; i < quiz.getNoOfQuestions(); i++) {
System.out.println(quiz.getQuestion(i));
String NoviOdgovor = scanner.nextLine();
if (quiz.isCorrectAnswer(i, NoviOdgovor)) {
tocno++;
System.out.println("Točno.");
}
else {
System.out.println("Netočno.");
}
}
double brojPitanja = quiz.getNoOfQuestions();
double rezultat = tocno / brojPitanja * 100;
System.out.println("Odgovorili ste točno na %.2f", rezultat);
System.out.println("% ("+tocno + "/" + quiz.getNoOfQuestions() + ") pitanja");
}
}
catch (MaxNumberOfQuestions) {
System.out.println(max.getMessage());
izbor = " 2";
}
System.out.println("Ispit je spreman.");
}
}
// Domaca zadaca 06
// Marijela Milicevic
// FIPU - nastavni smjer |
package com.rui.cn.service;
import com.rui.cn.dao.log.EventLogDao;
import com.rui.cn.dao.order.UserOrderDao;
import com.rui.cn.domain.log.EventLog;
import com.rui.cn.domain.order.UserOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.transaction.Transactional;
import java.util.List;
/**
* Created by caibosi on 2018-07-25.
*/
@Component
public class OrderService {
@Autowired
UserOrderDao userOrderDao;
@Autowired
EventLogDao eventLogDao;
@Transactional(rollbackOn = Exception.class)
public void newOrder(String userId,String productCode,int quantity){
UserOrder userOrder = new UserOrder();
userOrder.setUserId(userId);
userOrder.setProductCode(productCode);
userOrder.setQuantity(quantity);
userOrderDao.save(userOrder);
EventLog eventLog = new EventLog();
eventLog.setOperation("new order");
eventLog.setOperator(userId);
eventLogDao.save(eventLog);
List<EventLog> all = eventLogDao.findAll();
all.forEach(x -> System.out.println("添加后测试------------》"+x.getOperation()));
eventLogDao.deleteAll();
int i=1/0;
}
@Transactional(rollbackOn = Exception.class)
public void newOrderRollback(String userId,String productCode,int quantity){
UserOrder userOrder = new UserOrder();
userOrder.setUserId(userId);
userOrder.setProductCode(productCode);
userOrder.setQuantity(quantity);
userOrderDao.save(userOrder);
EventLog eventLog = new EventLog();
eventLog.setOperation("new order");
eventLog.setOperator(userId);
eventLogDao.save(eventLog);
throw new RuntimeException("test jta rollback");
}
@Transactional(rollbackOn = Exception.class)
public void delete(int i) {
userOrderDao.deleteAll();
eventLogDao.deleteAll();
}
} |
package com.tencent.mm.plugin.voip.model;
class j$4 implements Runnable {
final /* synthetic */ j oKq;
j$4(j jVar) {
this.oKq = jVar;
}
public final void run() {
this.oKq.oJY.bKz();
}
}
|
package tree;
public class HuffmanTreeNode implements Comparable<HuffmanTreeNode>{
int weight;
HuffmanTreeNode left_node;
HuffmanTreeNode right_node;
int length_node;
public HuffmanTreeNode(int weight) {
this.weight = weight;
length_node = 0;
}
public HuffmanTreeNode(int weight,HuffmanTreeNode leftNode,HuffmanTreeNode rightNode) {
this.weight = weight;
length_node = 0;
left_node = leftNode;
right_node = rightNode;
}
@Override
public int compareTo(HuffmanTreeNode node) {
if(this.weight >= node.weight) {
return 1;
}
return -1;
}
}
|
package cityUnknown;
public class NPC {
private int patience;
private int stength;
private int courage;
private String speak;
public NPC(int p, int s, int c, String sp) {
this.patience = p;
this.stength = s;
this.courage = c;
this.speak = sp;
}
public int getPatience() {
return patience;
}
public void setPatience(int patience) {
this.patience = patience;
}
public int getStength() {
return stength;
}
public void setStength(int stength) {
this.stength = stength;
}
public int getCourage() {
return courage;
}
public void setCourage(int courage) {
this.courage = courage;
}
public String getSpeak() {
return speak;
}
public void setSpeak(String speak) {
this.speak = speak;
}
}
|
package exceptions.eigenexcepties;
import javax.security.auth.login.FailedLoginException;
public class OnjuistWachtwoordExceptie extends FailedLoginException {
public OnjuistWachtwoordExceptie() {
super("Er is een onjuist wachtwoord ingevuld!");
}
}
|
package com.revolut.web.dto;
import java.math.BigDecimal;
public class AccountDTO {
private Long id;
private String holder;
private BigDecimal balance;
public AccountDTO() {
}
public AccountDTO(Long id, String holder, BigDecimal balance) {
this.id = id;
this.holder = holder;
this.balance = balance;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getHolder() {
return holder;
}
public void setHolder(String holder) {
this.holder = holder;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
}
|
package array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Exercise13 {
public List<List<Integer>> deleteRowColOfMatrix(int[][] a, int row, int col) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
for (int i = 0; i < a.length; i++) {
if (row != i) {
ArrayList<Integer> r = new ArrayList<>();
for (int j = 0; j < a[0].length; j++)
if (j != col) r.add(a[i][j]);
res.add(r);
}
}
return res;
}
}
|
package ThreadOrderAccess;
public class main {
public static void main(String[] args) {
Order1 order = new Order1();
new Thread(() -> {
for(int i=0; i<10;i++){
order.pushOrder();
}
},"pushOrder").start();
new Thread(() -> {
for(int i=0; i<10;i++){
order.searchLab();
}
},"searchLab").start();
new Thread(() -> {
for(int i=0; i<10;i++){
order.confirmOrder();
}
},"confirmOrder").start();
}
}
|
package com.tencent.mm.plugin.shake.ui;
import android.os.MessageQueue.IdleHandler;
import com.tencent.mm.R;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.plugin.shake.ui.ShakeReportUI.4;
import com.tencent.mm.ui.base.s;
class ShakeReportUI$4$1 implements IdleHandler {
final /* synthetic */ 4 nbi;
ShakeReportUI$4$1(4 4) {
this.nbi = 4;
}
public final boolean queueIdle() {
s.a(this.nbi.nbh, 0, this.nbi.nbh.getString(R.l.shake_set_mute_tips));
au.HU();
c.DT().set(4117, Boolean.valueOf(true));
return false;
}
}
|
package com.mounika.task;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
* Created by Mounika on 6/9/2017.
*/
public class VideoFragment extends Fragment {
RecyclerView videoRecyclerView;
RecyclerView.Adapter videoRecyclerViewAdapter;
MainActivity TabsActivity;
RecyclerView.LayoutManager videoLayoutManager;
Context context;
public ArrayList<Integer> image = new ArrayList<>();
public ArrayList<String> title = new ArrayList<>();
public ArrayList<String> time = new ArrayList<>();
public ArrayList<String> desc = new ArrayList<>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
image.add(R.drawable.cardone);
image.add(R.drawable.cardtwo);
image.add(R.drawable.cardthree);
image.add(R.drawable.cardforu);
title.add("EMPTINESS FT.JUSTIN TIBLEKAR");
title.add("I'M FALLING LOVE WITH YOU");
title.add("BABY FT.JUSTIN BABER");
title.add("WHITE HORSE FT.TAYLOR SWIFT");
time.add("18 HOURS AGO");
time.add("20 HOURS AGO");
time.add("22 HOURS AGO");
time.add("24 HOURS AGO");
desc.add("Lorem Ipsum is simply dummy text of the printing and typesetting indusry.");
desc.add("Lorem Ipsum is simply dummy text of the printing and typesetting indusry.");
desc.add("Lorem Ipsum is simply dummy text of the printing and typesetting indusry.");
desc.add("Lorem Ipsum is simply dummy text of the printing and typesetting indusry.");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_video, container, false);
videoRecyclerView = ((RecyclerView) view.findViewById(R.id.videoRecyclerView));
TabsActivity = new MainActivity();
initViews();
return view;
}
private void initViews() {
Log.i("init", "initViews() called");
videoLayoutManager = new LinearLayoutManager(getActivity());
videoRecyclerView.setLayoutManager(videoLayoutManager);
videoRecyclerViewAdapter = new VideoAdapter(getContext(),image,title,time,desc);
videoRecyclerView.setAdapter(videoRecyclerViewAdapter);
videoRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener(){
GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener(){
@Override public boolean onSingleTapUp(MotionEvent e){
return true;
}
});
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e){
View child = rv.findChildViewUnder(e.getX(), e.getY());
if(child != null && gestureDetector.onTouchEvent(e)){
Intent i=new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"));
startActivity(i);
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e){
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept){
}
});
}
} |
package com.lumadimusalia.su_cafeteria2;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.lumadimusalia.su_cafeteria2.bean.Order;
public class OrderSuccessActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_success);
Order order = FirebaseDatabase.order;
TextView price = findViewById(R.id.total_price);
TextView items = findViewById(R.id.no_of_items);
price.setText("Ksh. "+ order.getTotalPrice());
items.setText(""+ order.getItems().size() +" items ordered");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.logout) {
//todo: implement logout logic
Toast.makeText(this, "Logout pressed", Toast.LENGTH_LONG).show();
startActivity(new Intent(this, MainActivity.class));
}
return super.onOptionsItemSelected(item);
}
}
|
package edu.wayne.cs.severe.redress2.utils;
import edu.wayne.cs.severe.redress2.entity.AttributeDeclaration;
import edu.wayne.cs.severe.redress2.entity.MethodDeclaration;
import edu.wayne.cs.severe.redress2.entity.refactoring.RefactoringOperation;
import edu.wayne.cs.severe.redress2.entity.refactoring.formulas.mf.MoveFieldPredFormula;
import edu.wayne.cs.severe.redress2.entity.refactoring.formulas.mm.MoveMethodPredFormula;
import edu.wayne.cs.severe.redress2.entity.refactoring.opers.MoveField;
import edu.wayne.cs.severe.redress2.entity.refactoring.opers.MoveMethod;
import edu.wayne.cs.severe.redress2.entity.refactoring.opers.RefactoringType;
import java.util.ArrayList;
import java.util.List;
public class ExtractClassUtils {
public static List<AttributeDeclaration> getAttributesToMove(RefactoringOperation ref,
MoveFieldPredFormula preFormMF) {
List<AttributeDeclaration> attrs = new ArrayList<AttributeDeclaration>();
List<RefactoringOperation> subRefs = ref.getSubRefs();
for (RefactoringOperation subRef : subRefs) {
if (subRef.getRefType() instanceof MoveField) {
AttributeDeclaration attr = preFormMF.getAttribute(subRef);
attrs.add(attr);
}
}
return attrs;
}
public static List<MethodDeclaration> getMethodsToMove(RefactoringOperation ref,
MoveMethodPredFormula preFormMM) {
List<MethodDeclaration> methods = new ArrayList<MethodDeclaration>();
List<RefactoringOperation> subRefs = ref.getSubRefs();
for (RefactoringOperation subRef : subRefs) {
if (subRef.getRefType() instanceof MoveMethod) {
MethodDeclaration method = preFormMM.getMethod(subRef);
methods.add(method);
}
}
return methods;
}
public static double numFieldsToMove(RefactoringOperation ref) {
List<RefactoringOperation> subRefs = ref.getSubRefs();
if (subRefs == null) {
return 0;
}
int num = 0;
// for each sub-refactoring
for (RefactoringOperation subRef : subRefs) {
RefactoringType refType = subRef.getRefType();
// it is a move field
if (refType instanceof MoveField) {
++num;
}
}
return num;
}
public static double numMethodsToMove(RefactoringOperation ref) {
List<RefactoringOperation> subRefs = ref.getSubRefs();
if (subRefs == null) {
return 0;
}
int num = 0;
// for each sub-refactoring
for (RefactoringOperation subRef : subRefs) {
RefactoringType refType = subRef.getRefType();
// it is a move method
if (refType instanceof MoveMethod) {
++num;
}
}
return num;
}
}
|
/*
* generated by Xtext
*/
package com.rockwellcollins.atc;
import org.eclipse.xtext.conversion.IValueConverterService;
import org.eclipse.xtext.generator.IGenerator;
import org.eclipse.xtext.naming.IQualifiedNameProvider;
import org.eclipse.xtext.scoping.IGlobalScopeProvider;
import org.eclipse.xtext.scoping.impl.ImportUriGlobalScopeProvider;
import org.eclipse.xtext.serializer.tokens.ICrossReferenceSerializer;
import com.rockwellcollins.atc.limp.converter.LimpValueConverterService;
import com.rockwellcollins.atc.limp.naming.LimpQualifiedNameProvider;
import com.rockwellcollins.atc.limp.serializer.LimpCrossReferenceSerializer;
/**
* Use this class to register components to be used at runtime / without the Equinox extension registry.
*/
public class LimpRuntimeModule extends com.rockwellcollins.atc.AbstractLimpRuntimeModule {
@Override
public Class<? extends IGlobalScopeProvider> bindIGlobalScopeProvider() {
return ImportUriGlobalScopeProvider.class;
}
public Class<? extends IGenerator> bindIGenerator() {
return IGenerator.NullGenerator.class;
}
@SuppressWarnings("restriction")
public Class<? extends ICrossReferenceSerializer> bindICrossReferenceSerializer() {
return LimpCrossReferenceSerializer.class;
}
@Override
public Class<? extends IQualifiedNameProvider> bindIQualifiedNameProvider() {
return LimpQualifiedNameProvider.class;
}
@Override
public Class<? extends IValueConverterService> bindIValueConverterService() {
return LimpValueConverterService.class;
}
}
|
package com.yougou.yop.api.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import com.yougou.dto.output.QueryExpressCompanyOuputDto;
import com.yougou.dto.output.QueryLogisticsCompanyOuputDto;
import com.yougou.outside.api.IOutsideOrderApiService;
import com.yougou.outside.api.domain.JitDelivery;
import com.yougou.outside.api.domain.JitDeliveryDetail;
import com.yougou.tools.common.utils.DateUtil;
import com.yougou.wms.wpi.common.exception.WPIBussinessException;
import com.yougou.wms.wpi.expresssoc.domain.ExpressSocDomain;
import com.yougou.wms.wpi.expresssoc.service.IExpressSocDomainService;
import com.yougou.wms.wpi.logisticscompany.domain.LogisticsCompanyDomain;
import com.yougou.wms.wpi.logisticscompany.service.ILogisticsCompanyDomainService;
import com.yougou.yop.api.IMerchantApiLogisticsService;
@Service(value="merchantApiLogisticsService")
public class MerchantApiLogisticsService implements IMerchantApiLogisticsService {
private static final Log logger = LogFactory.getLog(MerchantApiLogisticsService.class);
@Resource
private ILogisticsCompanyDomainService logisticsCompanyService;
@Resource
private IExpressSocDomainService expressSocService;
@Resource
private IOutsideOrderApiService outsideOrderApiService;
@Override
public List<QueryLogisticsCompanyOuputDto> getLogisticscompany()
throws Exception {
com.yougou.wms.wpi.common.pagefinder.PageFinder<LogisticsCompanyDomain> pageFinder = logisticsCompanyService.queryPageFinderLogisticsCompany(1, Integer.MAX_VALUE, 1, 2, null);
if (pageFinder == null) {
throw new RuntimeException("系统内部异常, 请稍后再试.");
}
List<LogisticsCompanyDomain> list = pageFinder.getData();
List<QueryLogisticsCompanyOuputDto> querydtos = new ArrayList<QueryLogisticsCompanyOuputDto>();
QueryLogisticsCompanyOuputDto dto = null;
if (CollectionUtils.isNotEmpty(list)) {
for (LogisticsCompanyDomain domain : list) {
dto = new QueryLogisticsCompanyOuputDto();
dto.setLogistics_company_code(domain.getLogisticCompanyCode());
dto.setLogistics_company_name(domain.getLogisticsCompanyName());
querydtos.add(dto);
}
}
return querydtos;
}
@Override
public List<QueryExpressCompanyOuputDto> getExpresscompany()
throws Exception {
List<QueryExpressCompanyOuputDto> list = null;
try {
List<ExpressSocDomain> expresss = expressSocService.getExpressSocDomain();
if (CollectionUtils.isNotEmpty(expresss)) {
list = new ArrayList<QueryExpressCompanyOuputDto>();
QueryExpressCompanyOuputDto dto = null;
for (ExpressSocDomain express : expresss) {
dto = new QueryExpressCompanyOuputDto();
dto.setExpress_company_code(express.getExpressNo());
dto.setExpress_company_name(express.getExpressName());
list.add(dto);
}
}
} catch (WPIBussinessException e) {
logger.error("query expressSocService list exception : ", e);
throw new RuntimeException("系统内部异常, 请稍后再试.");
}
return list;
}
@Override
public List<String> getStorageNo(Map<String, Object> parameterMap)
throws Exception {
// TODO Auto-generated method stub
String poNo = (String) parameterMap.get("po_no"); // po 单号
String warehouseCode = (String) parameterMap.get("warehouse"); //唯品会仓编码
String sizeStr = (String) parameterMap.get("size"); // 每次获取的数量
int size = 0;
try{
size = Integer.parseInt(sizeStr);
}catch(Exception e){
size=20;
logger.error("唯品会JIT获取入库编号转换获取数量size exception : ", e);
}
List<String> storageNos= outsideOrderApiService.getStorageNo(poNo, warehouseCode, size);
logger.warn("po_no:"+poNo+";warehoseCode:"+warehouseCode+"获取入库编码结果:"+storageNos);
return storageNos;
}
@Override
public Boolean importDeliveryDetail(Map<String, Object> parameterMap) {
// TODO Auto-generated method stub
JitDelivery jitDelivery = new JitDelivery();
String poNo = (String) parameterMap.get("po_no"); // po 单号
String deliveryNo = (String) parameterMap.get("delivery_no"); //物流单号
String warehouse = (String) parameterMap.get("warehouse"); //唯品会仓编码
String arrivalTime = (String) parameterMap.get("arrival_time"); //要求到货时间
String deliveryListStr = (String) parameterMap.get("delivery_list"); // 出仓单明细,即:发货明细
String deliveryTime = (String) parameterMap.get("delivery_time"); // 发货时间
String raceTime = (String) parameterMap.get("race_time"); // 预计收货时间
String storageNo = (String) parameterMap.get("storage_no"); //入库编号
String orderSubNo = (String) parameterMap.get("order_sub_no"); //优购子订单号
String carrierCode = (String) parameterMap.get("carrier_code"); //承运商编码
Date arrivalDate = DateUtil.parseDate(arrivalTime, "yyyy-MM-dd HH:mm:ss");
Date deliveryDate = DateUtil.parseDate(deliveryTime, "yyyy-MM-dd HH:mm:ss");
jitDelivery.setArrivalTime( arrivalDate);
jitDelivery.setDeliveryNo(deliveryNo);
jitDelivery.setDeliveryTime(deliveryDate);
jitDelivery.setPoNo(poNo);
jitDelivery.setStorageNo(storageNo);
jitDelivery.setYougouOrderNO(orderSubNo);
jitDelivery.setWarehouseCode(warehouse);
jitDelivery.setCarrierCode(carrierCode);
List<JitDeliveryDetail> deliveryDetailList = getDeliveryDetailList(
poNo, deliveryListStr, storageNo);
jitDelivery.setDetailList(deliveryDetailList);
;
logger.warn("po_no:"+poNo+";warehoseCode:"+warehouse+"导入出仓单明细参数:"+ToStringBuilder.reflectionToString(jitDelivery));
Boolean result = outsideOrderApiService.importDeliveryDetail(jitDelivery);
logger.warn("po_no:"+poNo+";warehoseCode:"+warehouse+"导入出仓单明细结果:"+result);
return result;
}
/**
* 从出仓单明细字段中拆分获取明细信息封装至DTO中
* @param poNo
* @param deliveryListStr
* @param storageNo
* @return
*/
private List<JitDeliveryDetail> getDeliveryDetailList(String poNo,
String deliveryListStr, String storageNo) {
List<Map<String,Object>> deliveryList = new ArrayList<Map<String,Object>>();
if(StringUtils.isNotBlank(deliveryListStr)){
String[] deliveryArr = deliveryListStr.trim().split("#");
for(String delivery : deliveryArr){
Map<String,Object> map = new HashMap<String,Object>();
String[] deliveryInfos = delivery.split(",");
if(deliveryInfos.length!=4){
logger.error("po_no:"+poNo+";storage_no:"+storageNo + "在导入出仓单明细时,明细数据格式不正确!");
throw new RuntimeException("po_no:"+poNo+";storage_no:"+storageNo + "在导入出仓单明细时,明细数据格式不正确!");
}
for(String deliveryInfo : deliveryInfos){
String[] deliveryEntry = deliveryInfo.split("=");
map.put(deliveryEntry[0], deliveryEntry[1]);
}
deliveryList.add(map);
}
}else{
logger.error("po_no:"+poNo+";storage_no:"+storageNo + "在导入出仓单明细时,明细为空!");
throw new RuntimeException("po_no:"+poNo+";storage_no:"+storageNo + "在导入出仓单明细时,明细为空!");
}
List<JitDeliveryDetail> deliveryDetailList = new ArrayList<JitDeliveryDetail>();
for(Map<String,Object> map : deliveryList){
JitDeliveryDetail deliveryDetail = new JitDeliveryDetail();
int amount = 0;
try{
amount = Integer.parseInt((String) map.get("amount"));
}catch(Exception e){
logger.error("po_no:"+poNo+";storage_no:"+storageNo + "在导入出仓单明细时,商品数量不是整数数字格式!");
throw new RuntimeException("po_no:"+poNo+";storage_no:"+storageNo + "在导入出仓单明细时,商品数量不是整数数字格式!");
}
deliveryDetail.setAmount(String.valueOf(amount));
deliveryDetail.setBarcode((String)map.get("barcode"));
deliveryDetail.setBoxNo((String)map.get("box_no"));
deliveryDetail.setPickNo((String)map.get("pick_no"));
deliveryDetailList.add(deliveryDetail);
}
return deliveryDetailList;
}
public static void main(String[] args) {
Date date = DateUtil.parseDate("2016-07-09 12:10:09", "yyyy-MM-dd HH:mm:ss");
System.out.println(DateUtil.format(date,"yyyy-MM-dd HH:mm:ss"));
}
}
|
package javabasico.aula19labs;
import java.util.Scanner;
/**
* @author Kim Tsunoda
* Objetivo Criar um vetor A com 5 elementos inteiros. Escreva um programa que imprima a tabuada de cada um dos elementos do vetor A.
*/
public class Exercicio32 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int[] vetorA = new int[5];
for (int i=0; i <vetorA.length; i++) {
System.out.println("Digite um valor para o vetor A posicao " + i);
vetorA[i] = scan.nextInt();
}
System.out.print("Vetor A ");
for (int i=0 ; i < vetorA.length ; i++) {
System.out.print(vetorA [i] + " ");
}
for (int i=0 ; i < vetorA.length ; i++) {
System.out.println("\n" + "Tabuada do " + vetorA[i]);
for (int j=1; j <=10; j++ ) {
System.out.println(vetorA[i] + " X " + j + " = " + (vetorA[i] * j));
}
}
}
}
|
package chapter09.Exercise09_09;
public class TestRegularPolygon {
public static void main(String[] args) {
RegularPolygon rg1 = new RegularPolygon();
RegularPolygon rg2 = new RegularPolygon(6, 4);
RegularPolygon rg3 = new RegularPolygon(10, 4, 5.6, 7.8);
System.out.println("Regular polygon 1\nArea: " + rg1.getArea() + " Perimeter: " + rg1.getPerimeter());
System.out.println("\nRegular polygon 2\nArea: " + rg2.getArea() + " Perimeter: " + rg2.getPerimeter());
System.out.println("\nRegular polygon 3\nArea: " + rg3.getArea() + " Perimeter: " + rg3.getPerimeter());
}
}
|
package day31interfacecollections;
/*
1) If it is not must, do not use same names for variables in parent interfaces
2) If you need to use same names for variables in parent interfaces, when you call variables
do not forget to use "interface names" otherwise you will get Compile Time Error
*/
public interface I01 {
int v1 = 2000;
String name1 = "Audi";
}
interface I02 {
int v1 = 3000;
String name2 = "Honda";
}
class Car implements I01, I02{
public static void main(String[] args) {
System.out.println(name1); // Audi
System.out.println(name2);// Honda
System.out.println(I01.v1);// 2000
System.out.println(I02.v1);// 3000
}
}
|
package co.nos.noswallet.network.websockets.model;
public class PendingBlocksCredentialsBag {
public String balance, amount;
public String previousBlock, frontier;
public String accountBalance;
public String work;
public String blockHash;
public PendingBlocksCredentialsBag() {
}
public PendingBlocksCredentialsBag(PendingBlocksCredentialsBag previous) {
this.balance = previous.balance;
this.amount = previous.amount;
this.previousBlock = previous.previousBlock;
this.frontier = previous.frontier;
this.accountBalance = previous.accountBalance;
this.work = previous.work;
this.blockHash = previous.blockHash;
}
public PendingBlocksCredentialsBag balance(String val) {
this.balance = val;
return this;
}
public PendingBlocksCredentialsBag amount(String val) {
this.amount = val;
return this;
}
public PendingBlocksCredentialsBag previousBlock(String val) {
this.previousBlock = val;
return this;
}
public PendingBlocksCredentialsBag frontier(String val) {
this.frontier = val;
return this;
}
public PendingBlocksCredentialsBag accountBalance(String val) {
this.accountBalance = val;
return this;
}
public PendingBlocksCredentialsBag proofOfWork(String val) {
this.work = val;
return this;
}
public PendingBlocksCredentialsBag blockHash(String val) {
this.blockHash = val;
return this;
}
public PendingBlocksCredentialsBag clear() {
this.balance = null;
this.amount = null;
this.frontier = null;
this.previousBlock = null;
this.accountBalance = null;
this.work = null;
this.blockHash = null;
return this;
}
}
|
package com.jim.multipos.ui.vendor_item_managment.presenter;
import android.support.v4.app.Fragment;
import com.jim.multipos.config.scope.PerFragment;
import com.jim.multipos.ui.vendor_item_managment.fragments.VendorItemFragment;
import com.jim.multipos.ui.vendor_item_managment.fragments.VendorItemPresenterModule;
import com.jim.multipos.ui.vendor_item_managment.fragments.VendorItemView;
import dagger.Binds;
import dagger.Module;
/**
* Created by developer on 20.11.2017.
*/
@Module(includes = {
VendorItemPresenterModule.class
})
public abstract class VendorItemFragmentModule {
@Binds
@PerFragment
abstract Fragment provideFragment(VendorItemFragment vendorItemFragment);
@Binds
@PerFragment
abstract VendorItemView provideProductsClassFragment(VendorItemFragment vendorItemFragment);
}
|
package com.pangpang6.books.javapoet;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import org.junit.Test;
import javax.lang.model.element.Modifier;
import java.io.IOException;
import java.util.Date;
public class MyTest {
@Test
public void test02() throws IOException {
MethodSpec.Builder result = MethodSpec.methodBuilder("main")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(void.class)
.addParameter(String[].class, "args")
.addException(Exception.class);
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
//.addMethod(computeRange("multiply10to20", 10, 20, "*"))
//.addMethod(whatsMyName("jiangjiguang"))
.addMethod(result.build())
.build();
JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld)
.build();
javaFile.writeTo(System.out);
}
@Test
public void test01() throws IOException {
MethodSpec main = MethodSpec.methodBuilder("main")
.addStatement("long now = $T.currentTimeMillis()", System.class)
.beginControlFlow("if ($T.currentTimeMillis() < now)", System.class)
.addStatement("$T.out.println($S)", System.class, "Time travelling, woo hoo!")
.nextControlFlow("else if ($T.currentTimeMillis() == now)", System.class)
.addStatement("$T.out.println($S)", System.class, "Time stood still!")
.nextControlFlow("else")
.addStatement("$T.out.println($S)", System.class, "Ok, time still moving forward")
.endControlFlow()
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(computeRange("multiply10to20", 10, 20, "*"))
//.addMethod(whatsMyName("jiangjiguang"))
//.addMethod(testT02())
.build();
JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld)
.build();
StringBuilder sb = new StringBuilder();
javaFile.writeTo(sb);
System.out.println(sb);
}
private MethodSpec computeRange(String name, int from, int to, String op) {
return MethodSpec.methodBuilder(name)
.returns(int.class)
.addStatement("int result = 0")
.beginControlFlow("for (int i = $L; i < $L; i++)", from, to)
.addStatement("result = result $L i", op)
.endControlFlow()
.addStatement("return result")
.build();
}
private static MethodSpec whatsMyName(String name) {
return MethodSpec.methodBuilder(name)
.returns(String.class)
.addStatement("return $S", name)
.build();
}
private MethodSpec testT() {
MethodSpec today = MethodSpec.methodBuilder("today")
.returns(Date.class)
.addStatement("return new $T()", Date.class)
.build();
return today;
}
private MethodSpec testT02() {
ClassName hoverboard = ClassName.get("com.mattel", "Hoverboard");
MethodSpec today = MethodSpec.methodBuilder("tomorrow")
.returns(hoverboard)
.addStatement("return new $T()", hoverboard)
.build();
return today;
}
}
|
package fi.jjc.graphics.matrix;
import java.awt.geom.Rectangle2D;
import org.lwjgl.opengl.GL11;
import fi.jjc.math.Angle;
import fi.jjc.math.Vector3;
/**
* Matrix stack handler.
*
* @author Jens ┼kerblom
*/
public class MatrixHandler
{
/**
* @return the current matrix stack.
*/
public static MatrixStack getCurrentStack()
{
return MatrixStack.fromGL(GL11.glGetInteger(GL11.GL_MATRIX_MODE));
}
/**
* Sets a matrix stack to the current.
*
* @param curStack
* stack to set.
*/
public static void setCurrentStack(MatrixStack curStack)
{
GL11.glMatrixMode(curStack.getGLModeConstant());
}
/**
* Multiplies the current matrix with the translation matrix.
*
* @param v
* translation.
*/
public static void translate(Vector3 v)
{
GL11.glTranslated(v.getX(), v.getY(), v.getZ());
}
/**
* Multiplies the current matrix with the scaling matrix.
*
* @param v
* scaling.
*/
public static void scale(Vector3 v)
{
GL11.glScaled(v.getX(), v.getY(), v.getZ());
}
/**
* Multiplies the current matrix with the rotation matrix.
*
* @param a
* rotation.
*
* @param v
* unit axis vector.
*/
public static void rotate(Angle a, Vector3 v)
{
GL11.glRotatef((float) a.asDegrees(),
(float) v.getX(),
(float) v.getY(),
(float) v.getZ());
}
/**
* Multiplies the projection matrix with the orthogonal projection matrix of depth (z) range
* [-1, 1] and the specified xy range.
*
* @param rect
* xy range.
*/
public static void ortho2D(Rectangle2D rect)
{
int cur = GL11.glGetInteger(GL11.GL_MATRIX_MODE);
if (cur != GL11.GL_PROJECTION)
{
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glOrtho(rect.getMinX(), rect.getMaxX(), rect.getMinY(), rect.getMaxY(), 1.0, -1.0);
GL11.glMatrixMode(cur);
}
else
{
GL11.glOrtho(rect.getMinX(), rect.getMaxX(), rect.getMinY(), rect.getMaxY(), 1.0, -1.0);
}
}
// TODO Perspective, frustum, ortho projections
}
|
/*
* 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 Modelo.obligaciones;
import objetos.Fecha;
import objetos.Periodo;
import objetos.Regimen;
/**
*
* @author princessdiana
*/
public class Cedular extends Impuestos {
private Float totalCasaHabitacion;
private Float totalLocalComercial;
public Cedular(Periodo per){
super(Regimen.CEDULAR, per);
}
@Override
public Float calculaRecargos() {
return (float)2.0;
}
@Override
public Float calculoImpuesto() {
return null;
}
@Override
public Float totalPagar() {
Float total = totalCasaHabitacion * (float)0.10 + totalLocalComercial * (float)0.25;
Float iva = (totalCasaHabitacion + totalLocalComercial) * (float)0.16;
return total + iva;
}
}
|
package demo9.ingredients.chicago;
import demo9.ingredients.Dough;
public class ThickCrustDough implements Dough {
}
|
package GameObjects;
import java.awt.image.BufferedImage;
import Game.Animation;
import Game.State;
import Game.Tuple;
public abstract class AnimatedObject extends GameObject {
protected Animation animation;
protected int spriteFrame;
protected State state;
protected boolean disposeAfterAnimation;
protected boolean disposed;
public AnimatedObject(int x, int y, int width, int height, Animation animation) {
super(x, y, width, height);
this.animation = animation;
this.spriteFrame = 0;
this.state = State.STOPPED;
this.disposeAfterAnimation = false;
this.disposed = false;
}
public AnimatedObject(int x, int y, Animation animation) {
super(x, y, animation.getWidth(), animation.getHeight());
this.animation = animation;
this.spriteFrame = 0;
this.state = State.STOPPED;
this.disposeAfterAnimation = false;
this.disposed = false;
}
public AnimatedObject(int x, int y, Animation animation, boolean disposeAfterAnimation, State state) {
super(x, y, animation.getWidth(), animation.getHeight());
this.animation = animation;
this.spriteFrame = 0;
this.state = state;
this.disposeAfterAnimation = disposeAfterAnimation;
this.disposed = false;
}
public AnimatedObject(int x, int y, Animation animation, State state) {
super(x, y, animation.getWidth(), animation.getHeight());
this.animation = animation;
this.spriteFrame = 0;
this.state = state;
this.disposeAfterAnimation = false;
this.disposed = false;
}
public boolean disposed() {
return disposed;
}
public void setState(State state) {
this.state = state;
}
public State getState() {
return this.state;
}
public void updateGraphics() {
Tuple<BufferedImage[], Integer> stateSprites = this.animation.getStateSprites(this.state);
BufferedImage[] spriteFrames = stateSprites.getX();
if(disposeAfterAnimation && this.spriteFrame + 1 == spriteFrames.length * stateSprites.getY()) {
disposed = true;
} else {
this.spriteFrame = (this.spriteFrame + 1) % (spriteFrames.length * stateSprites.getY());
}
}
public BufferedImage getSprite() {
Tuple<BufferedImage[], Integer> stateSprites = this.animation.getStateSprites(this.state);
return stateSprites.getX()[this.spriteFrame / stateSprites.getY()];
}
public abstract void setObjectBehind(GameObject object);
}
|
package com.tencent.mm.plugin.brandservice;
import android.os.Looper;
import com.tencent.mm.ac.z;
import com.tencent.mm.kernel.api.c;
import com.tencent.mm.kernel.b.f;
import com.tencent.mm.kernel.b.g;
import com.tencent.mm.kernel.e;
import com.tencent.mm.model.p;
import com.tencent.mm.plugin.brandservice.a.b;
import com.tencent.mm.plugin.brandservice.ui.timeline.d;
import com.tencent.mm.plugin.messenger.foundation.a.a.f.a;
import com.tencent.mm.plugin.messenger.foundation.a.i;
import com.tencent.mm.plugin.messenger.foundation.a.o;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.aa;
import com.tencent.mm.storage.r;
import com.tencent.mm.storage.s;
public class PluginBrandService extends f implements c, b {
private a dYI = new 3(this);
private r.c hnE = new 4(this);
public void installed() {
alias(b.class);
}
public void configure(g gVar) {
addBrandServiceEvent();
if (gVar.ES()) {
pin(new p(c.class));
((o) com.tencent.mm.kernel.g.n(o.class)).setBizTimeLineCallback(new 1(this));
}
}
public void execute(g gVar) {
com.tencent.mm.bg.c.Um("brandservice");
}
public void onAccountInitialized(e.c cVar) {
((i) com.tencent.mm.kernel.g.l(i.class)).bcY().a(this.dYI, Looper.getMainLooper());
z.Ne().a(this.hnE, Looper.getMainLooper());
z.Nf().a(this.hnE, Looper.getMainLooper());
d dVar = new d();
if (s.auK()) {
x.i("MicroMsg.BizTimeLineMigrateImp", "migrateMainCell");
int intValue = ((Integer) com.tencent.mm.kernel.g.Ei().DT().get(aa.a.sZY, Integer.valueOf(0))).intValue();
if ((intValue & 1) == 0) {
((i) com.tencent.mm.kernel.g.l(i.class)).FW().Ys("officialaccounts");
com.tencent.mm.kernel.g.Ei().DT().a(aa.a.sZY, Integer.valueOf(intValue | 1));
}
}
}
public void onAccountRelease() {
((i) com.tencent.mm.kernel.g.l(i.class)).bcY().a(this.dYI);
z.Ne().a(this.hnE);
z.Nf().a(this.hnE);
}
private void addBrandServiceEvent() {
com.tencent.mm.sdk.b.a.sFg.b(new 2(this));
}
}
|
package com.timaimee.vpbluetoothsdkdemo.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.orhanobut.logger.Logger;
import com.timaimee.vpbluetoothsdkdemo.R;
import com.timaimee.vpbluetoothsdkdemo.adapter.GridAdatper;
import com.timaimee.vpbluetoothsdkdemo.oad.activity.OadActivity;
import com.veepoo.protocol.VPOperateManager;
import com.veepoo.protocol.listener.base.IBleNotifyResponse;
import com.veepoo.protocol.listener.base.IBleWriteResponse;
import com.veepoo.protocol.listener.data.IAllHealthDataListener;
import com.veepoo.protocol.listener.data.ICheckWearDataListener;
import com.veepoo.protocol.listener.data.ICountDownListener;
import com.veepoo.protocol.listener.data.IDeviceFuctionDataListener;
import com.veepoo.protocol.listener.data.IAlarm2DataListListener;
import com.veepoo.protocol.listener.data.IScreenLightListener;
import com.veepoo.protocol.listener.data.IScreenStyleListener;
import com.veepoo.protocol.listener.data.ISpo2hDataListener;
import com.veepoo.protocol.listener.data.ISportModelStateListener;
import com.veepoo.protocol.listener.data.IWomenDataListener;
import com.veepoo.protocol.model.datas.AlarmData2;
import com.veepoo.protocol.model.datas.BatteryData;
import com.veepoo.protocol.model.datas.CheckWearData;
import com.veepoo.protocol.model.datas.CountDownData;
import com.veepoo.protocol.model.datas.FunctionDeviceSupportData;
import com.veepoo.protocol.model.datas.ScreenLightData;
import com.veepoo.protocol.model.datas.ScreenStyleData;
import com.veepoo.protocol.model.datas.Spo2hData;
import com.veepoo.protocol.model.datas.SportData;
import com.veepoo.protocol.model.datas.SportModelStateData;
import com.veepoo.protocol.model.datas.TimeData;
import com.veepoo.protocol.model.datas.WomenData;
import com.veepoo.protocol.model.enums.ELanguage;
import com.veepoo.protocol.model.enums.ESocailMsg;
import com.veepoo.protocol.model.enums.EWomenStatus;
import com.veepoo.protocol.model.settings.Alarm2Setting;
import com.veepoo.protocol.model.settings.BpSetting;
import com.veepoo.protocol.model.settings.CheckWearSetting;
import com.veepoo.protocol.model.settings.ContentSetting;
import com.veepoo.protocol.model.settings.ContentSmsSetting;
import com.veepoo.protocol.model.settings.CountDownSetting;
import com.veepoo.protocol.model.settings.LongSeatSetting;
import com.veepoo.protocol.model.settings.AlarmSetting;
import com.veepoo.protocol.model.datas.AlarmData;
import com.veepoo.protocol.model.enums.EBPDetectModel;
import com.veepoo.protocol.model.datas.BpData;
import com.veepoo.protocol.model.datas.BpSettingData;
import com.veepoo.protocol.model.settings.CustomSetting;
import com.veepoo.protocol.model.settings.CustomSettingData;
import com.veepoo.protocol.model.datas.DrinkData;
import com.veepoo.protocol.model.enums.EOprateStauts;
import com.veepoo.protocol.model.enums.ESex;
import com.veepoo.protocol.model.datas.FatigueData;
import com.veepoo.protocol.model.datas.FindDeviceData;
import com.veepoo.protocol.model.datas.FunctionSocailMsgData;
import com.veepoo.protocol.model.enums.EFunctionStatus;
import com.veepoo.protocol.model.datas.HeartData;
import com.veepoo.protocol.model.settings.HeartWaringSetting;
import com.veepoo.protocol.model.datas.HeartWaringData;
import com.veepoo.protocol.model.datas.LanguageData;
import com.veepoo.protocol.model.datas.LongSeatData;
import com.veepoo.protocol.model.datas.NightTurnWristeData;
import com.veepoo.protocol.model.datas.OriginData;
import com.veepoo.protocol.model.datas.OriginHalfHourData;
import com.veepoo.protocol.model.datas.PersonInfoData;
import com.veepoo.protocol.model.datas.PwdData;
import com.veepoo.protocol.listener.data.IAlarmDataListener;
import com.veepoo.protocol.listener.data.IBPDetectDataListener;
import com.veepoo.protocol.listener.data.IBPSettingDataListener;
import com.veepoo.protocol.listener.data.ICameraDataListener;
import com.veepoo.protocol.listener.data.ICustomSettingDataListener;
import com.veepoo.protocol.listener.data.IDrinkDataListener;
import com.veepoo.protocol.listener.data.IFatigueDataListener;
import com.veepoo.protocol.listener.data.IFindDeviceDatalistener;
import com.veepoo.protocol.listener.data.IFindPhonelistener;
import com.veepoo.protocol.listener.data.IHeartDataListener;
import com.veepoo.protocol.listener.data.IHeartWaringDataListener;
import com.veepoo.protocol.listener.data.ILanguageDataListener;
import com.veepoo.protocol.listener.data.ILongSeatDataListener;
import com.veepoo.protocol.listener.data.INightTurnWristeDataListener;
import com.veepoo.protocol.listener.data.IOriginDataListener;
import com.veepoo.protocol.listener.data.IPwdDataListener;
import com.veepoo.protocol.listener.data.IPersonInfoDataListener;
import com.veepoo.protocol.listener.data.IBatteryDataListener;
import com.veepoo.protocol.listener.data.ISleepDataListener;
import com.veepoo.protocol.listener.data.ISocialMsgDataListener;
import com.veepoo.protocol.listener.data.ISportDataListener;
import com.veepoo.protocol.model.datas.SleepData;
import com.veepoo.protocol.model.settings.NightTurnWristSetting;
import com.veepoo.protocol.model.settings.ScreenSetting;
import com.veepoo.protocol.model.settings.WomenSetting;
import com.veepoo.protocol.operate.CameraOperater;
import com.veepoo.protocol.util.VpBleByteUtil;
import com.veepoo.protocol.util.VPLogger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Created by timaimee on 2017/2/8.
*/
public class OperaterActivity extends Activity implements AdapterView.OnItemClickListener {
private final static String TAG = OperaterActivity.class.getSimpleName();
int level = 1;
TextView tv1, tv2, tv3;
GridView mGridView;
List<Map<String, String>> mGridData = new ArrayList<>();
GridAdatper mGridAdapter;
Context mContext = null;
private String deviceaddress;
private final static String PWD_COMFIRM = "1.设备密码-验证";
private final static String PERSONINFO_SYNC = "2.个人信息-设置";
private final static String PWD_MODIFY = "设备密码-修改";
private final static String HEART_DETECT_START = "测量心率-开始";
private final static String HEART_DETECT_STOP = "测量心率-结束";
private final static String BP_DETECT_START = "测量血压-开始";
private final static String BP_DETECT_STOP = "测量血压-结束";
private final static String BP_DETECTMODEL_SETTING = "血压模式-设置";
private final static String BP_DETECTMODEL_SETTING_ADJUSTE = "血压模式[动态调整]-设置";
private final static String BP_DETECTMODEL_SETTING_ADJUSTE_CANCEL = "血压模式[动态调整]-取消";
private final static String BP_DETECTMODEL_READ = "血压模式-读取";
private final static String SPORT_CURRENT_READ = "当前计步-读取";
private final static String CAMERA_START = "拍照模式-开始";
private final static String CAMERA_STOP = "拍照模式-停止";
private final static String ALARM_SETTING = "闹钟-设置";
private final static String ALARM_READ = "闹钟-读取";
private final static String ALARM_NEW_READ = "新闹钟-读取";
private final static String ALARM_NEW_ADD = "新闹钟-添加";
private final static String ALARM_NEW_MODIFY = "新闹钟-修改";
private final static String ALARM_NEW_DELETE = "新闹钟-删除";
private final static String LONGSEAT_SETTING_OPEN = "久坐-打开";
private final static String LONGSEAT_SETTING_CLOSE = "久坐-关闭";
private final static String LONGSEAT_READ = "久坐-读取";
private final static String LANGUAGE_CHINESE = "语言设置-中文";
private final static String LANGUAGE_ENGLISH = "语言设置-英文";
private final static String BATTERY = "电池状态-读取";
private final static String NIGHT_TURN_WRIST_OPEN = "夜间转腕-打开";
private final static String NIGHT_TURN_WRIST_CLOSE = "夜间转腕-关闭";
private final static String NIGHT_TURN_WRIST_READ = "夜间转腕-读取";
private final static String NIGHT_TURN_WRIST_CUSTOM_TIME = "夜间转腕-自定义时间";
private final static String NIGHT_TURN_WRIST_CUSTOM_TIME_LEVEL = "夜间转腕-自定义时间和等级";
private final static String DISCONNECT = "蓝牙连接-断开";
private final static String FINDPHONE = "手机防丢";
private final static String CHECK_WEAR_SETING_OPEN = "佩戴检测-打开";
private final static String CHECK_WEAR_SETING_CLOSE = "佩戴检测-关闭";
private final static String FINDDEVICE_SETTING_OPEN = "设备防丢-打开";
private final static String FINDDEVICE_SETTING_CLOSE = "设备防丢-关闭";
private final static String FINDDEVICE_READ = "设备防丢-读取";
private final static String DEVICE_COUSTOM_READ = "个性化-读取";
private final static String DEVICE_COUSTOM_SETTING = "个性化-设置";
private final static String SOCIAL_MSG_SETTING = "社交消息提醒-设置";
private final static String SOCIAL_MSG_READ = "社交消息提醒-读取设置";
private final static String SOCIAL_MSG_SEND = "社交消息提醒-发送内容";
private final static String HEARTWRING_READ = "心率报警-读取";
private final static String HEARTWRING_OPEN = "心率报警-打开";
private final static String HEARTWRING_CLOSE = "心率报警-关闭";
private final static String SPO2H_OPEN = "血氧-读取";
private final static String SPO2H_CLOSE = "血氧-结束";
private final static String FATIGUE_OPEN = "疲劳度-读取";
private final static String FATIGUE_CLOSE = "疲劳度-结束";
private final static String WOMEN_SETTING = "女性状态-设置";
private final static String WOMEN_READ = "女性状态-读取";
private final static String COUNT_DOWN_WATCH = "倒计时-手表单独使用";
private final static String COUNT_DOWN_APP = "倒计时-App使用";
private final static String SCREEN_LIGHT_SETTING = "屏幕调节-设置";
private final static String SCREEN_LIGHT_READ = "屏幕调节-读取";
public final static String SCREEN_STYLE_READ = "屏幕样式-读取";
public final static String SCREEN_STYLE_SETTING = "屏幕样式-设置";
private final static String AIM_SPROT_CALC = "目标步数-计算";
private final static String INSTITUTION_TRANSLATION = "公英制转换";
private final static String READ_HEALTH_DRINK = "读取健康数据-饮酒";
private final static String READ_HEALTH_SLEEP = "读取健康数据-睡眠";
private final static String READ_HEALTH_SLEEP_FROM = "读取健康数据-睡眠-从哪天起";
private final static String READ_HEALTH_SLEEP_SINGLEDAY = "读取健康数据-睡眠-读这天";
private final static String READ_HEALTH_ORIGINAL = "读取健康数据-5分钟";
private final static String READ_HEALTH_ORIGINAL_FROM = "读取健康数据-从哪天起";
private final static String READ_HEALTH_ORIGINAL_SINGLEDAY = "读取健康数据-读这天";
private final static String READ_HEALTH = "读取健康数据-全部";
public final static String SPORT_MODE_ORIGIN_READSTAUTS = "读取状态-运动模式";
public final static String SPORT_MODE_ORIGIN_START = "开启-运动模式";
public final static String SPORT_MODE_ORIGIN_END = "结束-运动模式";
public final static String CLEAR_DEVICE_DATA = "清除数据";
private final static String OAD = "固件升级";
private final static String READ_SP = "读取SP";
String[] oprateStr = new String[]{
PWD_COMFIRM, PERSONINFO_SYNC, PWD_MODIFY,
HEART_DETECT_START, HEART_DETECT_STOP, BP_DETECT_START, BP_DETECT_STOP, BP_DETECTMODEL_SETTING, BP_DETECTMODEL_READ,
BP_DETECTMODEL_SETTING_ADJUSTE_CANCEL, BP_DETECTMODEL_SETTING_ADJUSTE,
SPORT_CURRENT_READ, CAMERA_START, CAMERA_STOP, ALARM_SETTING, ALARM_READ, ALARM_NEW_READ, ALARM_NEW_ADD, ALARM_NEW_MODIFY, ALARM_NEW_DELETE,
LONGSEAT_SETTING_OPEN, LONGSEAT_SETTING_CLOSE, LONGSEAT_READ, LANGUAGE_CHINESE, LANGUAGE_ENGLISH,
BATTERY, NIGHT_TURN_WRIST_OPEN, NIGHT_TURN_WRIST_CLOSE, NIGHT_TURN_WRIST_READ, NIGHT_TURN_WRIST_CUSTOM_TIME, NIGHT_TURN_WRIST_CUSTOM_TIME_LEVEL,
DISCONNECT, DEVICE_COUSTOM_READ, DEVICE_COUSTOM_SETTING, FINDPHONE,
CHECK_WEAR_SETING_OPEN, CHECK_WEAR_SETING_CLOSE,
FINDDEVICE_SETTING_OPEN, FINDDEVICE_SETTING_CLOSE, FINDDEVICE_READ,
SOCIAL_MSG_SETTING, SOCIAL_MSG_READ, SOCIAL_MSG_SEND, HEARTWRING_READ, HEARTWRING_OPEN, HEARTWRING_CLOSE,
SPO2H_OPEN, SPO2H_CLOSE, FATIGUE_OPEN, FATIGUE_CLOSE, WOMEN_SETTING, WOMEN_READ,
COUNT_DOWN_WATCH, COUNT_DOWN_APP, SCREEN_LIGHT_SETTING, SCREEN_LIGHT_READ, SCREEN_STYLE_READ, SCREEN_STYLE_SETTING, AIM_SPROT_CALC, INSTITUTION_TRANSLATION,
READ_HEALTH_SLEEP, READ_HEALTH_SLEEP_FROM, READ_HEALTH_SLEEP_SINGLEDAY, READ_HEALTH_DRINK, READ_HEALTH_ORIGINAL,
READ_HEALTH_ORIGINAL_FROM, READ_HEALTH_ORIGINAL_SINGLEDAY, READ_HEALTH,
OAD, READ_SP, SPORT_MODE_ORIGIN_READSTAUTS, SPORT_MODE_ORIGIN_START, SPORT_MODE_ORIGIN_END, CLEAR_DEVICE_DATA
};
Message msg;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
String s = msg.obj.toString();
Toast.makeText(mContext, s, Toast.LENGTH_LONG).show();
switch (msg.what) {
case 1:
tv1.setText(s + "\n");
break;
case 2:
tv2.setText(s + "\n");
break;
case 3:
tv3.setText(s + "\n");
break;
}
}
};
WriteResponse writeResponse = new WriteResponse();
/**
* 密码验证获取以下信息
*/
int watchDataDay = 3;
int contactMsgLength = 0;
int allMsgLenght = 4;
private int deviceNumber = -1;
private String deviceVersion;
private String deviceTestVersion;
boolean isOadModel = false;
boolean isNewSportCalc = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_operate);
mContext = getApplicationContext();
deviceaddress = getIntent().getStringExtra("deviceaddress");
tv1 = (TextView) super.findViewById(R.id.tv1);
tv2 = (TextView) super.findViewById(R.id.tv2);
tv3 = (TextView) super.findViewById(R.id.tv3);
initGridView();
// listenDeviceCallbackData();
}
private void initGridView() {
mGridView = (GridView) findViewById(R.id.main_gridview);
for (int i = 0; i < oprateStr.length; i++) {
Map<String, String> map = new HashMap<>();
map.put("str", oprateStr[i]);
mGridData.add(map);
}
mGridAdapter = new GridAdatper(this, mGridData);
mGridView.setAdapter(mGridAdapter);
mGridView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String oprater = mGridData.get(position).get("str");
Toast.makeText(mContext, oprater, Toast.LENGTH_SHORT).show();
tv1.setText("");
tv2.setText("");
tv3.setText("");
if (oprater.equals(HEART_DETECT_START)) {
VPOperateManager.getMangerInstance(mContext).startDetectHeart(writeResponse, new IHeartDataListener() {
@Override
public void onDataChange(HeartData heart) {
String message = "heart:\n" + heart.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(HEART_DETECT_STOP)) {
VPOperateManager.getMangerInstance(mContext).stopDetectHeart(writeResponse);
} else if (oprater.equals(BP_DETECT_START)) {
tv1.setText(BP_DETECT_START + ",等待50s...");
VPOperateManager.getMangerInstance(mContext).startDetectBP(writeResponse, new IBPDetectDataListener() {
@Override
public void onDataChange(BpData bpData) {
String message = "BpData date statues:\n" + bpData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, EBPDetectModel.DETECT_MODEL_PUBLIC);
} else if (oprater.equals(BP_DETECT_STOP)) {
tv1.setText(BP_DETECT_STOP);
VPOperateManager.getMangerInstance(mContext).stopDetectBP(writeResponse, EBPDetectModel.DETECT_MODEL_PUBLIC);
} else if (oprater.equals(BP_DETECTMODEL_SETTING)) {
boolean isOpenPrivateModel = true;
boolean isAngioAdjuste = false;
BpSetting bpSetting = new BpSetting(isOpenPrivateModel, 111, 88);
//是否开启动态血压调整模式,功能标志位在密码验证的返回
bpSetting.setAngioAdjuste(isAngioAdjuste);
VPOperateManager.getMangerInstance(mContext).settingDetectBP(writeResponse, new IBPSettingDataListener() {
@Override
public void onDataChange(BpSettingData bpSettingData) {
String message = "BpSettingData:\n" + bpSettingData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, bpSetting);
} else if (oprater.equals(BP_DETECTMODEL_READ)) {
VPOperateManager.getMangerInstance(mContext).readDetectBP(writeResponse, new IBPSettingDataListener() {
@Override
public void onDataChange(BpSettingData bpSettingData) {
String message = "BpSettingData:\n" + bpSettingData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(SPORT_MODE_ORIGIN_END)) {
VPOperateManager.getMangerInstance(mContext).stopSportModel(writeResponse, new ISportModelStateListener() {
@Override
public void onSportModelStateChange(SportModelStateData sportModelStateData) {
String message = "运动模式状态:" + sportModelStateData.toString();
Logger.t(TAG).i(message);
}
});
} else if (oprater.equals(SPORT_MODE_ORIGIN_READSTAUTS)) {
VPOperateManager.getMangerInstance(mContext).readSportModelState(writeResponse, new ISportModelStateListener() {
@Override
public void onSportModelStateChange(SportModelStateData sportModelStateData) {
String message = "运动模式状态" + sportModelStateData.toString();
Logger.t(TAG).i(message);
}
});
} else if (oprater.equals(SPORT_MODE_ORIGIN_START)) {
VPOperateManager.getMangerInstance(mContext).startSportModel(writeResponse, new ISportModelStateListener() {
@Override
public void onSportModelStateChange(SportModelStateData sportModelStateData) {
String message = "运动模式状态" + sportModelStateData.toString();
Logger.t(TAG).i(message);
}
});
} else if (oprater.equals(CLEAR_DEVICE_DATA)) {
VPOperateManager.getMangerInstance(mContext).clearDeviceData(writeResponse);
finish();
} else if (oprater.equals(BP_DETECTMODEL_SETTING_ADJUSTE)) {
boolean isOpenPrivateModel = false;
boolean isAngioAdjuste = true;
BpSetting bpSetting = new BpSetting(isOpenPrivateModel, 111, 88);
//是否开启动态血压调整模式,功能标志位在密码验证的返回
bpSetting.setAngioAdjuste(isAngioAdjuste);
VPOperateManager.getMangerInstance(mContext).settingDetectBP(writeResponse, new IBPSettingDataListener() {
@Override
public void onDataChange(BpSettingData bpSettingData) {
String message = "BpSettingData:\n" + bpSettingData.toString();
Logger.t(TAG).i(message);
// sendMsg(message, 1);
}
}, bpSetting);
} else if (oprater.equals(BP_DETECTMODEL_SETTING_ADJUSTE_CANCEL)) {
boolean isOpenPrivateModel = false;
boolean isAngioAdjuste = true;
BpSetting bpSetting = new BpSetting(isOpenPrivateModel, 111, 88);
//是否开启动态血压调整模式,功能标志位在密码验证的返回
bpSetting.setAngioAdjuste(isAngioAdjuste);
VPOperateManager.getMangerInstance(mContext).cancelAngioAdjust(writeResponse, new IBPSettingDataListener() {
@Override
public void onDataChange(BpSettingData bpSettingData) {
String message = "BpSettingData:\n" + bpSettingData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, bpSetting);
} else if (oprater.equals(PWD_COMFIRM)) {
boolean is24Hourmodel = false;
VPOperateManager.getMangerInstance(mContext).confirmDevicePwd(writeResponse, new IPwdDataListener() {
@Override
public void onPwdDataChange(PwdData pwdData) {
String message = "PwdData:\n" + pwdData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
deviceNumber = pwdData.getDeviceNumber();
deviceVersion = pwdData.getDeviceVersion();
deviceTestVersion = pwdData.getDeviceTestVersion();
}
}, new IDeviceFuctionDataListener() {
@Override
public void onFunctionSupportDataChange(FunctionDeviceSupportData functionSupport) {
String message = "FunctionDeviceSupportData:\n" + functionSupport.toString();
Logger.t(TAG).i(message);
sendMsg(message, 2);
EFunctionStatus newCalcSport = functionSupport.getNewCalcSport();
if (newCalcSport != null && newCalcSport.equals(EFunctionStatus.SUPPORT)) {
isNewSportCalc = true;
} else {
isNewSportCalc = false;
}
watchDataDay = functionSupport.getWathcDay();
contactMsgLength = functionSupport.getContactMsgLength();
allMsgLenght = functionSupport.getAllMsgLength();
VPLogger.i("数据读取处理,ORIGIN_DATA_DAY:" + watchDataDay);
}
}, new ISocialMsgDataListener() {
@Override
public void onSocialMsgSupportDataChange(FunctionSocailMsgData socailMsgData) {
String message = "FunctionSocailMsgData:\n" + socailMsgData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 3);
}
}, new ICustomSettingDataListener() {
@Override
public void OnSettingDataChange(CustomSettingData customSettingData) {
String message = "FunctionCustomSettingData:\n" + customSettingData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 4);
}
}, "0000", is24Hourmodel);
} else if (oprater.equals(PWD_MODIFY)) {
VPOperateManager.getMangerInstance(mContext).modifyDevicePwd(writeResponse, new IPwdDataListener() {
@Override
public void onPwdDataChange(PwdData pwd) {
String message = "PwdData:\n" + pwd.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, "0000");
} else if (oprater.equals(SPORT_CURRENT_READ)) {
VPOperateManager.getMangerInstance(mContext).readSportStep(writeResponse, new ISportDataListener() {
@Override
public void onSportDataChange(SportData sportData) {
String message = "当前计步:\n" + sportData.getStep();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(PERSONINFO_SYNC)) {
VPOperateManager.getMangerInstance(mContext).syncPersonInfo(writeResponse, new IPersonInfoDataListener() {
@Override
public void OnPersoninfoDataChange(EOprateStauts EOprateStauts) {
String message = "同步个人信息:\n" + EOprateStauts.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, new PersonInfoData(ESex.MAN, 178, 60, 20, 8000));
} else if (oprater.equals(CAMERA_START)) {
VPOperateManager.getMangerInstance(mContext).startCamera(writeResponse, new ICameraDataListener() {
@Override
public void OnCameraDataChange(CameraOperater.COStatus oprateStauts) {
String message = "打开拍照:\n" + oprateStauts.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(CAMERA_STOP)) {
VPOperateManager.getMangerInstance(mContext).stopCamera(writeResponse, new ICameraDataListener() {
@Override
public void OnCameraDataChange(CameraOperater.COStatus oprateStauts) {
String message = "关闭拍照:\n" + oprateStauts.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(ALARM_SETTING)) {
List<AlarmSetting> alarmSettingList = new ArrayList<>(3);
AlarmSetting alarmSetting1 = new AlarmSetting(14, 10, true);
AlarmSetting alarmSetting2 = new AlarmSetting(15, 20, true);
AlarmSetting alarmSetting3 = new AlarmSetting(16, 30, true);
alarmSettingList.add(alarmSetting1);
alarmSettingList.add(alarmSetting2);
alarmSettingList.add(alarmSetting3);
VPOperateManager.getMangerInstance(mContext).settingAlarm(writeResponse, new IAlarmDataListener() {
@Override
public void onAlarmDataChangeListener(AlarmData alarmData) {
String message = "设置闹钟:\n" + alarmData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, alarmSettingList);
} else if (oprater.equals(ALARM_READ)) {
VPOperateManager.getMangerInstance(mContext).readAlarm(writeResponse, new IAlarmDataListener() {
@Override
public void onAlarmDataChangeListener(AlarmData alarmData) {
String message = "读取闹钟:\n" + alarmData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(ALARM_NEW_READ)) {
VPOperateManager.getMangerInstance(mContext).readAlarm2(writeResponse, new IAlarm2DataListListener() {
@Override
public void onAlarmDataChangeListListener(AlarmData2 alarmData2) {
String message = "读取闹钟[新版]:\n" + alarmData2.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(ALARM_NEW_DELETE)) {
int deleteID = 1;
Alarm2Setting alarm2Setting = getMultiAlarmSetting();
alarm2Setting.setAlarmId(deleteID);
VPOperateManager.getMangerInstance(mContext).deleteAlarm2(writeResponse, new IAlarm2DataListListener() {
@Override
public void onAlarmDataChangeListListener(AlarmData2 alarmData2) {
String message = "删除闹钟[新版]:\n" + alarmData2.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
//String bluetoothAddress, int alarmId, int alarmHour, int alarmMinute, String repeatStatus, int scene, String unRepeatDate, boolean isOpen
}, alarm2Setting);
} else if (oprater.equals(ALARM_NEW_ADD)) {
Alarm2Setting alarm2Setting = getMultiAlarmSetting();
VPOperateManager.getMangerInstance(mContext).addAlarm2(writeResponse, new IAlarm2DataListListener() {
@Override
public void onAlarmDataChangeListListener(AlarmData2 alarmData2) {
String message = "添加闹钟[新版]:\n" + alarmData2.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, alarm2Setting);
} else if (oprater.equals(ALARM_NEW_MODIFY)) {
Alarm2Setting alarm2Setting = getMultiAlarmSetting();
int modifyID = 2;
alarm2Setting.setAlarmId(modifyID);
alarm2Setting.setAlarmHour(10);
alarm2Setting.setOpen(false);
VPOperateManager.getMangerInstance(mContext).modifyAlarm2(writeResponse, new IAlarm2DataListListener() {
@Override
public void onAlarmDataChangeListListener(AlarmData2 alarmData2) {
String message = "修改闹钟[新版]:\n" + alarmData2.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, alarm2Setting);
} else if (oprater.equals(LONGSEAT_SETTING_OPEN)) {
VPOperateManager.getMangerInstance(mContext).settingLongSeat(writeResponse, new LongSeatSetting(10, 35, 11, 45, 60, true), new ILongSeatDataListener() {
@Override
public void onLongSeatDataChange(LongSeatData longSeat) {
String message = "设置久坐-打开:\n" + longSeat.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(LONGSEAT_SETTING_CLOSE)) {
VPOperateManager.getMangerInstance(mContext).settingLongSeat(writeResponse, new LongSeatSetting(10, 40, 12, 40, 40, false), new ILongSeatDataListener() {
@Override
public void onLongSeatDataChange(LongSeatData longSeat) {
String message = "设置久坐-关闭:\n" + longSeat.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(LONGSEAT_READ)) {
VPOperateManager.getMangerInstance(mContext).readLongSeat(writeResponse, new ILongSeatDataListener() {
@Override
public void onLongSeatDataChange(LongSeatData longSeat) {
String message = "设置久坐-读取:\n" + longSeat.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(LANGUAGE_CHINESE)) {
VPOperateManager.getMangerInstance(mContext).settingDeviceLanguage(writeResponse, new ILanguageDataListener() {
@Override
public void onLanguageDataChange(LanguageData languageData) {
String message = "设置语言(中文):\n" + languageData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, ELanguage.CHINA);
} else if (oprater.equals(LANGUAGE_ENGLISH)) {
VPOperateManager.getMangerInstance(mContext).settingDeviceLanguage(writeResponse, new ILanguageDataListener() {
@Override
public void onLanguageDataChange(LanguageData languageData) {
String message = "设置语言(英文):\n" + languageData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, ELanguage.ENGLISH);
} else if (oprater.equals(BATTERY)) {
VPOperateManager.getMangerInstance(mContext).readBattery(writeResponse, new IBatteryDataListener() {
@Override
public void onDataChange(BatteryData batteryData) {
String message = "电池等级:\n" + batteryData.getBatteryLevel() + "\n" + "电量:" + batteryData.getBatteryLevel() * 25 + "%";
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(NIGHT_TURN_WRIST_READ)) {
VPOperateManager.getMangerInstance(mContext).readNightTurnWriste(writeResponse, new INightTurnWristeDataListener() {
@Override
public void onNightTurnWristeDataChange(NightTurnWristeData nightTurnWristeData) {
String message = "夜间转腕-读取:\n" + nightTurnWristeData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(NIGHT_TURN_WRIST_OPEN)) {
VPOperateManager.getMangerInstance(mContext).settingNightTurnWriste(writeResponse, new INightTurnWristeDataListener() {
@Override
public void onNightTurnWristeDataChange(NightTurnWristeData nightTurnWristeData) {
String message = "夜间转腕-打开:\n" + nightTurnWristeData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, true);
} else if (oprater.equals(NIGHT_TURN_WRIST_CLOSE)) {
VPOperateManager.getMangerInstance(mContext).settingNightTurnWriste(writeResponse, new INightTurnWristeDataListener() {
@Override
public void onNightTurnWristeDataChange(NightTurnWristeData nightTurnWristeData) {
String message = "夜间转腕-关闭:\n" + nightTurnWristeData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, false);
} else if (oprater.equals(NIGHT_TURN_WRIST_CUSTOM_TIME)) {
final boolean isOpen = true;
TimeData startTime = new TimeData(10, 0);
TimeData endTime = new TimeData(20, 0);
VPOperateManager.getMangerInstance(mContext).settingNightTurnWriste(writeResponse, new INightTurnWristeDataListener() {
@Override
public void onNightTurnWristeDataChange(NightTurnWristeData nightTurnWristeData) {
String message = "夜间转腕-" + isOpen + ":\n" + nightTurnWristeData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, isOpen, startTime, endTime);
} else if (oprater.equals(NIGHT_TURN_WRIST_CUSTOM_TIME_LEVEL)) {
final boolean isOpen = true;
TimeData startTime = new TimeData(10, 0);
TimeData endTime = new TimeData(20, 0);
level++;
Logger.t(TAG).i("夜间转腕-" + level);
NightTurnWristSetting nightTurnWristSetting = new NightTurnWristSetting(isOpen, startTime, endTime, level);
VPOperateManager.getMangerInstance(mContext).settingNightTurnWriste(writeResponse, new INightTurnWristeDataListener() {
@Override
public void onNightTurnWristeDataChange(NightTurnWristeData nightTurnWristeData) {
String message = "夜间转腕-" + isOpen + ":\n" + nightTurnWristeData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, nightTurnWristSetting);
} else if (oprater.equals(DISCONNECT)) {
VPOperateManager.getMangerInstance(mContext).disconnectWatch(writeResponse);
finish();
} else if (oprater.equals(FINDPHONE)) {
VPOperateManager.getMangerInstance(mContext).settingFindPhoneListener(new IFindPhonelistener() {
@Override
public void findPhone() {
String message = "(监听到手环要查找手机)-where is the phone,make some noise!";
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(DEVICE_COUSTOM_READ)) {
VPOperateManager.getMangerInstance(mContext).readCustomSetting(writeResponse, new ICustomSettingDataListener() {
@Override
public void OnSettingDataChange(CustomSettingData customSettingData) {
String message = "个性化状态-公英制/时制(12/24)/5分钟测量开关(心率/血压)-读取:\n" + customSettingData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(DEVICE_COUSTOM_SETTING)) {
boolean isHaveMetricSystem = true;
boolean isMetric = true;
boolean is24Hour = true;
boolean isOpenAutoHeartDetect = true;
boolean isOpenAutoBpDetect = true;
VPOperateManager.getMangerInstance(mContext).changeCustomSetting(writeResponse, new ICustomSettingDataListener() {
@Override
public void OnSettingDataChange(CustomSettingData customSettingData) {
String message = "个性化状态-公英制/时制(12/24)/5分钟测量开关(心率/血压)-设置:\n" + customSettingData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, new CustomSetting(isHaveMetricSystem, isMetric, is24Hour, isOpenAutoHeartDetect, isOpenAutoBpDetect));
} else if (oprater.equals(CHECK_WEAR_SETING_OPEN)) {
CheckWearSetting checkWearSetting = new CheckWearSetting();
checkWearSetting.setOpen(true);
VPOperateManager.getMangerInstance(mContext).setttingCheckWear(writeResponse, new ICheckWearDataListener() {
@Override
public void onCheckWearDataChange(CheckWearData checkWearData) {
String message = "佩戴检测-打开:\n" + checkWearData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, checkWearSetting);
} else if (oprater.equals(CHECK_WEAR_SETING_CLOSE)) {
CheckWearSetting checkWearSetting = new CheckWearSetting();
checkWearSetting.setOpen(false);
VPOperateManager.getMangerInstance(mContext).setttingCheckWear(writeResponse, new ICheckWearDataListener() {
@Override
public void onCheckWearDataChange(CheckWearData checkWearData) {
String message = "佩戴检测-关闭:\n" + checkWearData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, checkWearSetting);
} else if (oprater.equals(FINDDEVICE_SETTING_OPEN)) {
VPOperateManager.getMangerInstance(mContext).settingFindDevice(writeResponse, new IFindDeviceDatalistener() {
@Override
public void onFindDevice(FindDeviceData findDeviceData) {
String message = "防丢-打开:\n" + findDeviceData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, true);
} else if (oprater.equals(FINDDEVICE_SETTING_CLOSE)) {
VPOperateManager.getMangerInstance(mContext).settingFindDevice(writeResponse, new IFindDeviceDatalistener() {
@Override
public void onFindDevice(FindDeviceData findDeviceData) {
String message = "防丢-关闭:\n" + findDeviceData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, false);
} else if (oprater.equals(FINDDEVICE_READ)) {
VPOperateManager.getMangerInstance(mContext).readFindDevice(writeResponse, new IFindDeviceDatalistener() {
@Override
public void onFindDevice(FindDeviceData findDeviceData) {
String message = "防丢-读取:\n" + findDeviceData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(SOCIAL_MSG_READ)) {
VPOperateManager.getMangerInstance(mContext).readSocialMsg(writeResponse, new ISocialMsgDataListener() {
@Override
public void onSocialMsgSupportDataChange(FunctionSocailMsgData socailMsgData) {
String message = " 社交信息提醒-读取:\n" + socailMsgData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(SOCIAL_MSG_SETTING)) {
FunctionSocailMsgData socailMsgData = new FunctionSocailMsgData();
socailMsgData.setPhone(EFunctionStatus.SUPPORT);
socailMsgData.setMsg(EFunctionStatus.SUPPORT);
socailMsgData.setWechat(EFunctionStatus.SUPPORT_OPEN);
socailMsgData.setQq(EFunctionStatus.SUPPORT_OPEN);
socailMsgData.setFacebook(EFunctionStatus.SUPPORT_CLOSE);
socailMsgData.setTwitter(EFunctionStatus.SUPPORT_OPEN);
socailMsgData.setWhats(EFunctionStatus.SUPPORT_OPEN);
socailMsgData.setSina(EFunctionStatus.UNSUPPORT);
socailMsgData.setFlickr(EFunctionStatus.UNSUPPORT);
socailMsgData.setLinkin(EFunctionStatus.UNSUPPORT);
socailMsgData.setLine(EFunctionStatus.UNSUPPORT);
socailMsgData.setInstagram(EFunctionStatus.UNSUPPORT);
socailMsgData.setSnapchat(EFunctionStatus.UNSUPPORT);
socailMsgData.setSkype(EFunctionStatus.UNSUPPORT);
VPOperateManager.getMangerInstance(mContext).settingSocialMsg(writeResponse, new ISocialMsgDataListener() {
@Override
public void onSocialMsgSupportDataChange(FunctionSocailMsgData socailMsgData) {
String message = " 社交信息提醒-设置:\n" + socailMsgData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, socailMsgData);
} else if (oprater.equals(SOCIAL_MSG_SEND)) {
/**电话,可以只传电话号码**/
// ContentSetting contentphoneSetting0 = new ContentPhoneSetting(ESocailMsg.PHONE, contactMsgLength, allMsgLenght,"0755-86562490");
/**电话,传联系人姓名以及电话号码,最终显示的联系人姓名**/
// ContentSetting contentphoneSetting1 = new ContentPhoneSetting(ESocailMsg.PHONE, contactMsgLength, allMsgLenght,"深圳市维亿魄科技有限公司", "0755-86562490");
// VPOperateManager.getMangerInstance(mContext).sendSocialMsgContent(writeResponse, contentphoneSetting0);
/**短信,可以只传电话号码**/
ContentSetting contentsmsSetting0 = new ContentSmsSetting(ESocailMsg.SMS, contactMsgLength, allMsgLenght, "0755-86562490", "公司研发的项目主要在医疗健康智能穿戴、智能家居、新型智能交友产品、飞机航模、智能安全锁五个领域方面");
/**短信,传联系人姓名以及电话号码,最终显示的联系人姓名**/
ContentSetting contentsmsSetting1 = new ContentSmsSetting(ESocailMsg.SMS, contactMsgLength, allMsgLenght, "深圳市维亿魄科技有限公司", "0755-86562490", "公司研发的项目主要在医疗健康智能穿戴、智能家居、新型智能交友产品、飞机航模、智能安全锁五个领域方面");
VPOperateManager.getMangerInstance(mContext).sendSocialMsgContent(writeResponse, contentsmsSetting1);
/**第三方APP推送,发送前先通过密码验证获取FunctionSocailMsgData的状态**/
// ContentSetting contentsociaSetting = new ContentSocailSetting(ESocailMsg.WECHAT, contactMsgLength, allMsgLenght, "veepoo", "公司研发的项目主要在医疗健康智能穿戴、智能家居、新型智能交友产品、飞机航模、智能安全锁五个领域方面");
// VPOperateManager.getMangerInstance(mContext).sendSocialMsgContent(writeResponse, contentsociaSetting);
} else if (oprater.equals(HEARTWRING_READ)) {
VPOperateManager.getMangerInstance(mContext).readHeartWarning(writeResponse, new IHeartWaringDataListener() {
@Override
public void onHeartWaringDataChange(HeartWaringData heartWaringData) {
String message = "心率报警-读取:\n" + heartWaringData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(HEARTWRING_OPEN)) {
VPOperateManager.getMangerInstance(mContext).settingHeartWarning(writeResponse, new IHeartWaringDataListener() {
@Override
public void onHeartWaringDataChange(HeartWaringData heartWaringData) {
String message = "心率报警-打开:\n" + heartWaringData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, new HeartWaringSetting(120, 110, true));
} else if (oprater.equals(HEARTWRING_CLOSE)) {
VPOperateManager.getMangerInstance(mContext).settingHeartWarning(writeResponse, new IHeartWaringDataListener() {
@Override
public void onHeartWaringDataChange(HeartWaringData heartWaringData) {
String message = "心率报警-关闭:\n" + heartWaringData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, new HeartWaringSetting(120, 110, false));
} else if (oprater.equals(SPO2H_OPEN)) {
VPOperateManager.getMangerInstance(mContext).startDetectSPO2H(writeResponse, new ISpo2hDataListener() {
@Override
public void onSpO2HADataChange(Spo2hData spo2HData) {
if (spo2HData.getValue() == 0) {
return;
}
String message = "血氧-开始:\n" + spo2HData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(SPO2H_CLOSE)) {
VPOperateManager.getMangerInstance(mContext).stopDetectSPO2H(writeResponse, new ISpo2hDataListener() {
@Override
public void onSpO2HADataChange(Spo2hData spo2HData) {
String message = "血氧-结束:\n" + spo2HData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(FATIGUE_OPEN)) {
VPOperateManager.getMangerInstance(mContext).startDetectFatigue(writeResponse, new IFatigueDataListener() {
@Override
public void onFatigueDataListener(FatigueData fatigueData) {
String message = "疲劳度-开始:\n" + fatigueData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(FATIGUE_CLOSE)) {
VPOperateManager.getMangerInstance(mContext).stopDetectFatigue(writeResponse, new IFatigueDataListener() {
@Override
public void onFatigueDataListener(FatigueData fatigueData) {
String message = "疲劳度-结束:\n" + fatigueData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(WOMEN_SETTING)) {
VPOperateManager.getMangerInstance(mContext).settingWomenState(writeResponse, new IWomenDataListener() {
@Override
public void onWomenDataChange(WomenData womenData) {
String message = "女性状态-设置:\n" + womenData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, new WomenSetting(EWomenStatus.PREING, new TimeData(2016, 3, 1), new TimeData(2017, 1, 14)));
} else if (oprater.equals(WOMEN_READ)) {
VPOperateManager.getMangerInstance(mContext).readWomenState(writeResponse, new IWomenDataListener() {
@Override
public void onWomenDataChange(WomenData womenData) {
String message = "女性状态-读取:\n" + womenData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(COUNT_DOWN_WATCH)) {
int second = 7;
boolean isOpenWatchUI = false;
boolean isCountDownByWatch = false;
CountDownSetting countDownSetting = new CountDownSetting(second, isOpenWatchUI, isCountDownByWatch);
VPOperateManager.getMangerInstance(mContext).settingCountDown(writeResponse, countDownSetting, new ICountDownListener() {
@Override
public void OnCountDownDataChange(CountDownData countDownData) {
String message = "倒计时-watch:\n" + countDownData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(COUNT_DOWN_APP)) {
int second = 11;
boolean isOpenWatchUI = true;
boolean isCountDownByWatch = false;
CountDownSetting countDownSetting = new CountDownSetting(second, isOpenWatchUI, isCountDownByWatch);
VPOperateManager.getMangerInstance(mContext).settingCountDown(writeResponse, countDownSetting, new ICountDownListener() {
@Override
public void OnCountDownDataChange(CountDownData countDownData) {
String message = "倒计时-App:\n" + countDownData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(AIM_SPROT_CALC)) {
Intent intent = new Intent(OperaterActivity.this, AimSportCalcActivity.class);
intent.putExtra("isnewsportcalc", isNewSportCalc);
startActivity(intent);
} else if (oprater.equals(SCREEN_LIGHT_SETTING)) {
//默认的是【22:00-07:00】设置成2档,其他时间设置成4档,用户可以自定义
VPOperateManager.getMangerInstance(mContext).settingScreenLight(writeResponse, new IScreenLightListener() {
@Override
public void onScreenLightDataChange(ScreenLightData screenLightData) {
String message = "屏幕调节数据-设置:" + screenLightData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, new ScreenSetting(22, 0, 7, 0, 2, 4));
} else if (oprater.equals(SCREEN_LIGHT_READ)) {
VPOperateManager.getMangerInstance(mContext).readScreenLight(writeResponse, new IScreenLightListener() {
@Override
public void onScreenLightDataChange(ScreenLightData screenLightData) {
String message = "屏幕调节数据-读取:" + screenLightData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(SCREEN_STYLE_READ)) {
VPOperateManager.getMangerInstance(mContext).readScreenStyle(writeResponse, new IScreenStyleListener() {
@Override
public void onScreenStyleDataChange(ScreenStyleData screenLightData) {
String message = "屏幕样式-读取:" + screenLightData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
});
} else if (oprater.equals(SCREEN_STYLE_SETTING)) {
int screenstyle = 2;
VPOperateManager.getMangerInstance(mContext).settingScreenStyle(writeResponse, new IScreenStyleListener() {
@Override
public void onScreenStyleDataChange(ScreenStyleData screenLightData) {
String message = "屏幕样式-设置:" + screenLightData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
}, screenstyle);
} else if (oprater.equals(INSTITUTION_TRANSLATION)) {
Intent intent = new Intent(OperaterActivity.this, InstitutionActivity.class);
startActivity(intent);
} else if (oprater.equals(READ_HEALTH_SLEEP)) {
VPOperateManager.getMangerInstance(mContext).readSleepData(writeResponse, new ISleepDataListener() {
@Override
public void onSleepDataChange(SleepData sleepData) {
String message = "睡眠数据-返回:" + sleepData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
@Override
public void onSleepProgress(float progress) {
String message = "睡眠数据-读取进度:" + "progress=" + progress;
Logger.t(TAG).i(message);
}
@Override
public void onSleepProgressDetail(String day, int packagenumber) {
String message = "睡眠数据-读取进度:" + "day=" + day + ",packagenumber=" + packagenumber;
Logger.t(TAG).i(message);
}
@Override
public void onReadSleepComplete() {
String message = "睡眠数据-读取结束";
Logger.t(TAG).i(message);
}
}, watchDataDay
);
} else if (oprater.equals(READ_HEALTH_SLEEP_FROM)) {
int beforeYesterday = 2;
VPOperateManager.getMangerInstance(mContext).readSleepDataFromDay(writeResponse, new ISleepDataListener() {
@Override
public void onSleepDataChange(SleepData sleepData) {
String message = "睡眠数据-返回:" + sleepData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
@Override
public void onSleepProgress(float progress) {
String message = "睡眠数据-读取进度:" + "progress=" + progress;
Logger.t(TAG).i(message);
}
@Override
public void onSleepProgressDetail(String day, int packagenumber) {
String message = "睡眠数据-读取进度:" + "day=" + day + ",packagenumber=" + packagenumber;
Logger.t(TAG).i(message);
}
@Override
public void onReadSleepComplete() {
String message = "睡眠数据-读取结束";
Logger.t(TAG).i(message);
}
}
, beforeYesterday, watchDataDay);
} else if (oprater.equals(READ_HEALTH_SLEEP_SINGLEDAY)) {
int yesterday = 1;
VPOperateManager.getMangerInstance(mContext).readSleepDataSingleDay(writeResponse, new ISleepDataListener() {
@Override
public void onSleepDataChange(SleepData sleepData) {
String message = "睡眠数据-返回:" + sleepData.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
@Override
public void onSleepProgress(float progress) {
String message = "睡眠数据-读取进度:" + "progress=" + progress;
Logger.t(TAG).i(message);
}
@Override
public void onSleepProgressDetail(String day, int packagenumber) {
String message = "睡眠数据-读取进度:" + "day=" + day + ",packagenumber=" + packagenumber;
Logger.t(TAG).i(message);
}
@Override
public void onReadSleepComplete() {
String message = "睡眠数据-读取结束";
Logger.t(TAG).i(message);
}
}, yesterday, watchDataDay);
} else if (oprater.equals(READ_HEALTH_DRINK)) {
VPOperateManager.getMangerInstance(mContext).readDrinkData(writeResponse, new IDrinkDataListener() {
@Override
public void onDrinkDataChange(int packagenumber, DrinkData drinkdata) {
String message = "饮酒数据-返回:" + drinkdata.toString();
Logger.t(TAG).i(message);
sendMsg(message, 1);
}
@Override
public void onReadDrinkComplete() {
String message = "饮酒数据-读取结束";
Logger.t(TAG).i(message);
}
});
} else if (oprater.equals(READ_HEALTH_ORIGINAL)) {
VPOperateManager.getMangerInstance(mContext).readOriginData(writeResponse, new IOriginDataListener() {
@Override
public void onOringinFiveMinuteDataChange(OriginData originData) {
String message = "健康数据-返回:" + originData.toString();
Logger.t(TAG).i(message);
}
@Override
public void onReadOriginProgress(float progress) {
String message = "健康数据[5分钟]-读取进度:" + progress;
Logger.t(TAG).i(message);
}
@Override
public void onReadOriginProgressDetail(int date, String dates, int all, int num) {
}
@Override
public void onOringinHalfHourDataChange(OriginHalfHourData originHalfHourData) {
String message = "健康数据[30分钟]-返回:" + originHalfHourData.toString();
Logger.t(TAG).i(message);
}
@Override
public void onReadOriginComplete() {
String message = "健康数据-读取结束";
Logger.t(TAG).i(message);
}
}, watchDataDay);
} else if (oprater.equals(READ_HEALTH_ORIGINAL_FROM)) {
int yesterday = 1;
VPOperateManager.getMangerInstance(mContext).readOriginDataFromDay(writeResponse, new IOriginDataListener() {
@Override
public void onOringinFiveMinuteDataChange(OriginData originData) {
String message = "健康数据[5分钟]-返回:" + originData.toString();
Logger.t(TAG).i(message);
}
@Override
public void onOringinHalfHourDataChange(OriginHalfHourData originHalfHourData) {
String message = "健康数据[30分钟]-返回:" + originHalfHourData.toString();
Logger.t(TAG).i(message);
}
@Override
public void onReadOriginProgress(float progress) {
String message = "健康数据[5分钟]-读取进度:" + progress;
Logger.t(TAG).i(message);
}
@Override
public void onReadOriginProgressDetail(int date, String dates, int all, int num) {
}
@Override
public void onReadOriginComplete() {
String message = "健康数据-读取结束";
Logger.t(TAG).i(message);
}
}, yesterday, 10, watchDataDay);
} else if (oprater.equals(READ_HEALTH_ORIGINAL_SINGLEDAY)) {
int today = 0;
VPOperateManager.getMangerInstance(mContext).readOriginDataSingleDay(writeResponse, new IOriginDataListener() {
@Override
public void onOringinFiveMinuteDataChange(OriginData originData) {
String message = "健康数据[5分钟]-返回:" + originData.toString();
Logger.t(TAG).i(message);
}
@Override
public void onOringinHalfHourDataChange(OriginHalfHourData originHalfHourData) {
String message = "健康数据[30分钟]-返回:" + originHalfHourData.toString();
Logger.t(TAG).i(message);
}
@Override
public void onReadOriginProgress(float progress) {
String message = "健康数据[5分钟]-读取进度:" + progress;
Logger.t(TAG).i(message);
}
@Override
public void onReadOriginProgressDetail(int date, String dates, int all, int num) {
}
@Override
public void onReadOriginComplete() {
String message = "健康数据-读取结束";
Logger.t(TAG).i(message);
}
}, today, 1, watchDataDay);
} else if (oprater.equals(READ_HEALTH)) {
VPOperateManager.getMangerInstance(mContext).readAllHealthData(new IAllHealthDataListener() {
@Override
public void onProgress(float progress) {
String message = "onAllProgress:" + progress;
Logger.t(TAG).i(message);
}
@Override
public void onOringinFiveMinuteDataChange(OriginData originData) {
String message = "onOringinFiveMinuteDataChange:" + originData;
Logger.t(TAG).i(message);
}
@Override
public void onOringinHalfHourDataChange(OriginHalfHourData originHalfHourData) {
String message = "onOringinHalfHourDataChange:" + originHalfHourData;
Logger.t(TAG).i(message);
}
@Override
public void onReadOriginComplete() {
String message = "onReadOriginComplete";
Logger.t(TAG).i(message);
}
@Override
public void onSleepDataChange(SleepData sleepData) {
String message = "onSleepDataChange:" + sleepData;
Logger.t(TAG).i(message);
}
@Override
public void onReadSleepComplete() {
String message = "onReadSleepComplete";
Logger.t(TAG).i(message);
}
}, watchDataDay);
} else if (oprater.equals(OAD)) {
if (deviceNumber < 0) {
Toast.makeText(mContext, "请先通过密码验证,获取版本号!", Toast.LENGTH_LONG).show();
return;
}
boolean isOadModel = getIntent().getBooleanExtra("isoadmodel", false);
deviceaddress = getIntent().getStringExtra("deviceaddress");
Intent intent = new Intent(OperaterActivity.this, OadActivity.class);
intent.putExtra("deviceaddress", deviceaddress);
intent.putExtra("isoadmodel", isOadModel);
intent.putExtra("devicenumber", deviceNumber);
intent.putExtra("deviceversion", deviceVersion);
intent.putExtra("devicetestversion", deviceTestVersion);
startActivity(intent);
} else if (oprater.equals(READ_SP)) {
String shareperence = VPOperateManager.getMangerInstance(mContext).traversalShareperence();
Logger.t(TAG).i(shareperence);
}
}
@NonNull
private Alarm2Setting getMultiAlarmSetting() {
int hour = 2;
int minute = 0;
int scene = 1;
boolean isOpen = true;
String repestStr = "1000010";
String unRepeatDdate = "0000-00-00";
return new Alarm2Setting(hour, minute, repestStr, scene, unRepeatDdate, isOpen);
}
private void sendMsg(String message, int what) {
msg = Message.obtain();
msg.what = what;
msg.obj = message;
mHandler.sendMessage(msg);
}
/**
* 写入的状态返回
*/
class WriteResponse implements IBleWriteResponse {
@Override
public void onResponse(int code) {
Logger.t(TAG).i("write cmd status:" + code);
}
}
/**
* 返回设备的数据
*/
public void listenDeviceCallbackData() {
VPOperateManager.getMangerInstance(mContext).listenDeviceCallbackData(new IBleNotifyResponse() {
@Override
public void onNotify(UUID service, UUID character, byte[] value) {
Logger.t(TAG).i("设备返回的数据:" + Arrays.toString(VpBleByteUtil.byte2HexToStrArr(value)));
}
});
}
}
|
/**
* @Description:
* @Author: zhoutao29203
* @Date: 2021/1/27 23:47
* @Copyright: 2020 Hundsun All rights reserved.
*/
public class NioServer {
}
|
/*
* 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 com.mcc.poliklinik.services;
import com.mcc.poliklinik.entities.Jadwal;
import com.mcc.poliklinik.repositories.JadwalRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author ASUS
*/
@Service
public class JadwalService {
@Autowired
JadwalRepository jadwalRepository;
public List<Jadwal> getAll() {
return jadwalRepository.findAll();
}
public void save(Jadwal jadwal) {
jadwalRepository.save(jadwal);
}
public void delete(Integer id) {
jadwalRepository.delete(new Jadwal(id));
}
public Jadwal findById(Integer id) {
return jadwalRepository.findById(id).get();
}
}
|
package com.xml;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class AptDealHistoryDomTest{
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
File file = new File("src/xml/AptDealHistory.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//DocumentBuilder : dom parser
DocumentBuilder parser = factory.newDocumentBuilder();
// 파싱된 문서의 꼭대기(전체) /
Document doc = parser.parse(file);
// 핸들러 불 필요..
// 루트 element --> employees
Element root = doc.getDocumentElement();
//System.out.println("root element: " + root.getNodeName());
String input = sc.nextLine();
NodeList list = doc.getElementsByTagName("item");
List<Apt> alist = new ArrayList<Apt>();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i); // Employee 1개
if(node.getNodeType() == Node.ELEMENT_NODE) {
Element ele = (Element) node;
String name = ele.getElementsByTagName("아파트").item(0).getTextContent();
if(!name.contains(input)) {
continue;
}
String beob = ele.getElementsByTagName("법정동").item(0).getTextContent();
String price = ele.getElementsByTagName("거래금액").item(0).getTextContent();
Apt apt = new Apt();
apt.setName(name);
apt.setBeop(beob);
apt.setPrice(price);
alist.add(apt);
}
}
for (Apt a : alist) {
System.out.println(a);
}
}
}
|
package Cards;
import Map.Country;
import java.util.ArrayList;
import java.util.Arrays;
public class Hand {
private ArrayList<Card> hand;
private String[] exchangeCardCommands = {
"iii",
"ica",
"iac",
"ccc",
"cia",
"cai",
"aaa",
"aic",
"aci"};
private ArrayList<String[]> exchangeCardTypes = new ArrayList<>(Arrays.asList(new String[] {"Infantry","Infantry","Infantry"},
new String[] {"Cavalry","Cavalry","Cavalry"},
new String[] {"Artillery","Artillery","Artillery"},
new String[] {"Infantry","Cavalry","Artillery"}));
public Hand(){
hand = new ArrayList<Card>();
}
public void add(Card card){
hand.add(card);
}
//when you turn in cards this will remove the cards from the hand
public void removeCards(ArrayList<Integer> indices){
ArrayList<Card> toRemove = new ArrayList<>();
for(Integer n:indices){
toRemove.add(hand.get(n));
}
hand.removeAll(toRemove);
}
//if check is set to true then cards wont be removed only a boolean will be returned
private boolean hasCardsInHand(String[] types, boolean check) {
Card blankCard = new Card("", new Country());
//creates a copy of the hand to alter
ArrayList<Card> tempHand = (ArrayList<Card>) hand.clone();
//arraylist to store indexes of cards to be removed
ArrayList<Integer> indexes = new ArrayList<>();
//counter for how many cards match the types
int counter = 0;
//compares types we're looking for with the cards in the hand
//counter reaches 3 if all cards are present
//they will be removed and the function returns true
//otherwise it returns false
for (int i = 0; i < types.length; i++) {
for (int j = 0; j < tempHand.size(); j++) {
if (tempHand.get(j).getType().equals(types[i])) {
counter++;
tempHand.set(j, blankCard);
indexes.add(j);
break;
}
}
if (counter == 3)
break;
}
if (counter == 3) {
if (check == false)
removeCards(indexes);
return true;
}
return false;
}
//returns true if a player must turn in cards
public boolean mustTurnIn() {
return hand.size()>=5;
}
//returns the hand
public ArrayList<Card> getCards() {
return hand;
}
public boolean validExchangeCommand(String input)
{
for(String command: exchangeCardCommands)
{
if(command.equalsIgnoreCase(input))
{
return true;
}
}
return false;
}
public boolean exchangeCards(String input)
{
if(validExchangeCommand(input))
{
if(input.equalsIgnoreCase("iii"))
{
return hasCardsInHand(exchangeCardTypes.get(0), false);
}
else if(input.equalsIgnoreCase("ccc"))
{
return hasCardsInHand(exchangeCardTypes.get(1), false);
}
else if(input.equalsIgnoreCase("aaa"))
{
return hasCardsInHand(exchangeCardTypes.get(2),false);
}
else
{
return hasCardsInHand(exchangeCardTypes.get(3), false);
}
}
return false;
}
public boolean canExchange(){
for(String[] types:exchangeCardTypes){
if(hasCardsInHand(types, true)){
return true;
}
}
return false;
}
}
|
package com.smxknife.guava.cache.callbackwithnull;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
/**
* @author smxknife
* 2020/9/7
*/
public class Main {
public static void main(String[] args) throws ExecutionException {
Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(100).build();
String aaa = cache.get("aaa", new Callable<String>() {
@Override
public String call() throws Exception {
return null;
}
});
System.out.println(aaa);
}
}
|
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.servlet.*;
import javax.servlet.http.*;
import activities.db.*;
public class mostrarUsers extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException, ServletException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("GET Request. No Form Data Posted");
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
ArrayList data = new ArrayList();
try{
DBInteraction db = new DBInteraction();
data = db.mostrarUss();
req.getRequestDispatcher("lista_users.jsp").include(req, res);
for(int i=0;i<data.size();i++) {
Usuarios u = (Usuarios) data.get(i);
String nia = u.getNIA();
String nombre = u.getNombre();
String apellido = u.getApellido();
String email = u.getMail();
String telefono = u.getTelefono();
RequestDispatcher boxes_disponible=req.getRequestDispatcher("usuarios_libres.jsp?nia="+nia+"&nombre="+nombre+"&apellido="+apellido+"&telefono="+telefono+"&email="+email);
boxes_disponible.include(req, res);
}
db.close();
RequestDispatcher end=req.getRequestDispatcher("end.jsp");
end.include(req, res);
}catch(Exception e){ }
}//doPost end
}//class end
|
package com.mrhan.text.tatl;
/**
* 模板操作的类型<br/>
* 主要包含单条操作,和多条操作<br/>
* 那个,为什么需要定义两种呢?
* <br/>
* 对于不同操作,提供接口方法是不同的
*<br/>
* 单条操作是不会嵌套操作的,而多条,则会嵌套单条/多条的操作
*/
public enum ActionType {
/**
* 单条操作
* */
ACTION__SINGLE,
/**
* 操作集,多条操作
*/
ACTION_BLOCK
}
|
package note;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import ECSConnecter.CloudConnecter;
import XMLReader.CloudData;
/**
*
* @author Kobe Ebanks
*
*/
public class ListFiles implements Runnable{
/**
* The Map must include:userCode, page;
* could in include: number;
*/
private Map<String, String> map;
/**
* include messages of Objects in an ArrayList;
*/
private ArrayList<CloudData> data;
public ListFiles(Map<String, String> map){
this.map = map;
}
@Override
public void run() {
// TODO Auto-generated method stub
CloudConnecter conn = new CloudConnecter(map);
try {
conn.getXML();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.readXML();
data = conn.getData();
}
/**
* @return the data
*/
public ArrayList<CloudData> getData() {
return data;
}
}
|
package com.app.artclass.database;
import android.app.backup.BackupAgent;
import android.app.backup.BackupDataInput;
import android.app.backup.BackupDataOutput;
import android.os.ParcelFileDescriptor;
import com.app.artclass.Logger;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import java.io.IOException;
public class BackupManager extends BackupAgent {
private static BackupManager classInstance;
private static GoogleSignInAccount userGoogleAccount;
public static BackupManager getInstance(){
if(classInstance==null){
classInstance = new BackupManager();
}
return classInstance;
}
public BackupManager() {
Logger.getInstance().appendLog(getClass(),"init");
}
@Override
public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) throws IOException {
Logger.getInstance().appendLog(getClass(),"backup");
}
@Override
public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException {
Logger.getInstance().appendLog(getClass(),"restore");
}
// public void initGoogleAccount(GoogleSignInAccount account){
// if(account!=null) {
// userGoogleAccount = account;
// Logger.getInstance().appendLog(getClass(),"account updated");
// }else{
// Logger.getInstance().appendLog(getClass(),"account not found");
// }
// }
}
|
package com.bin.spring.transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service("bookShopService")
public class BookShopServiceImpl implements BookShopService {
@Autowired
private BookShopDao bookShopDao ;
/*
* 事务的传播行为.
* 1. 使用propagation指定事务的传播行为,即当前的事务方法被另外的事务方法调用时,
* 如何使用事务,默认取值为REQUIRED,即使用调用方法的事务.
* REQUIRES_NEW 使用自己的事务,调用的方法的事务挂起.
*
* 2. 使用isolation指定事务的隔离级别.最常用的READ_COMMITTED.
*
* 3. 默认情况下Spring的声明式事务对所有的运行时异常进行回滚.也可以通过对应的属性进行设置.
* noRollbackFor={UserAccountException.class}对哪个异常不进行回滚.非运行时异常,
* 是必须捕捉的,所以可以在捕捉后自行选择是否rollback,还是提交.
*
* 4. 使用readOnly指定事务是否为只读.表示这个事务只读取数据但不更新数据,可以帮助数据库引擎
* 优化事务.若真的是一个只读取数据库值的方法,应该设置readOnly=true.
*
* 5. 使用timeout单位是秒,指定强制回滚之前事务可以占用的时间.事务执行中,占用的时间超出了设定时间,,就强制回滚.
*
*/
// 添加事务注解.
@Transactional(propagation=Propagation.REQUIRES_NEW,
isolation=Isolation.READ_COMMITTED,
noRollbackFor={UserAccountException.class},
readOnly=false,
timeout=1)
@Override
public void purchase(String username, String isbn) {
// 1.获取书的单价.
int price = bookShopDao.findBookPriceByIsbn(isbn) ;
// 2.获取书的库存
bookShopDao.updateBookStock(isbn);
// 3.更新用户余额
bookShopDao.updateUserAccount(username, price);
}
}
|
package utils.state.actions;
public interface IActionsState {
public void doneTodos();
public void removeTodos();
}
|
package mude.srl.ssc.rest.controller.resource;
import java.util.ArrayList;
import java.util.List;
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.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import mude.srl.ssc.config.endpoint.ServiceEndpoint;
import mude.srl.ssc.entity.Plc;
import mude.srl.ssc.entity.Resource;
import mude.srl.ssc.entity.beans.Prenotazione;
import mude.srl.ssc.entity.beans.ResourceWithPlc;
import mude.srl.ssc.entity.utils.Response;
import mude.srl.ssc.service.dati.PlcService;
@RestController
@CrossOrigin(origins = { "http://localhost:8000", "http://127.0.0.1:8000"})
public class ResourceController {
@Autowired
private PlcService plcService;
@RequestMapping(path = ServiceEndpoint.RESOURCE, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<ResourceWithPlc>> resourceList() {
List<ResourceWithPlc> _res = new ArrayList<>();
try {
List<Resource> res = plcService.getResource(null);
if (res != null && !res.isEmpty()) {
for (Resource r : res) {
_res.add(new ResourceWithPlc(r));
}
}
} catch (Exception e) {
return new ResponseEntity<List<ResourceWithPlc>>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return ResponseEntity.ok(_res);
}
@ResponseBody
@RequestMapping(path = ServiceEndpoint.RESOURCE_RESERVATIONS, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public Response<List<Prenotazione>> resourceReservationsList() {
Response<List<Prenotazione>> resp = new Response<List<Prenotazione>>();
try {
List<Prenotazione> res = plcService.getReservationBeans(null);
resp.setResult(res);
resp.setTotalResult(Long.valueOf(res.size()));
} catch (Exception e) {
resp.setFault(true);
resp.setErrorMessage(e.getMessage());
resp.setException(e);
}
return resp;
}
@ResponseBody
@RequestMapping(path = ServiceEndpoint.LIST_PLC, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Response<List<Plc>> plcList() {
Response<List<Plc>> resp = new Response<List<Plc>>();
try {
List<Plc> res = plcService.getPlcList(null);
resp.setResult(res);
resp.setTotalResult(Long.valueOf(res.size()));
} catch (Exception e) {
resp.setFault(true);
resp.setErrorMessage(e.getMessage());
resp.setException(e);
}
return resp;
}
}
|
package com.rbgt.mb.enums;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonFormat.Shape;
import lombok.*;
/**
* @project_name: mb
* @package_name: com.rbgt.mb.enums
* @name: Status
* @author: 俞春旺
* @date: 2020/4/4 20:56
* @day_name_full: 星期六
* @remark: 无
**/
@Getter
@NoArgsConstructor
@AllArgsConstructor
@JsonFormat(shape = Shape.OBJECT)
public enum Status {
OFFLINE(0, "直播未开始"),
ONLINE(1, "直播中"),
OVER(2, "直播已结束");
private int code;
private String name;
@Override
public String toString() {
return code+"";
}
}
|
package exceptions;
public class IncorrectQuantityTests extends Exception {
public IncorrectQuantityTests(String msg) {
super(msg);
}
}
|
package br.com.scd.demo.session;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface SessionRepository extends CrudRepository<SessionEntity, Long> {
Optional<SessionEntity> findByTopicId(Long topicId);
}
|
package org.browsexml.timesheetjob.web;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.browsexml.timesheetjob.model.Constants;
import org.browsexml.timesheetjob.model.HoursWorkedExport;
import org.browsexml.timesheetjob.model.HoursWorkedReport;
import org.browsexml.timesheetjob.model.PayPer;
import org.browsexml.timesheetjob.model.StudentHoursExportReport;
import org.springframework.web.servlet.view.AbstractView;
public class ExportExcelView extends AbstractView {
private static Log log = LogFactory.getLog(ExportExcelView.class);
/** The content type for an Excel response */
private static final String CONTENT_TYPE = "application/vnd.ms-excel";
/** The extension to look for existing templates */
private static final String EXTENSION = ".xml";
public ExportExcelView() {
setContentType(CONTENT_TYPE);
}
protected boolean generatesDownloadContent() {
return true;
}
@Override
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) {
File f = new File(".");
log.debug("Path = " + f.getAbsolutePath());
List<HoursWorkedExport> sums =
(List<HoursWorkedExport>) model.get("hours");
response.setContentType(getContentType());
ServletOutputStream out = null;
try {
out = response.getOutputStream();
out.write(header().getBytes());
} catch (IOException e1) {
e1.printStackTrace();
return;
}
PayPer payPeriod = (PayPer) model.get("period");
for (HoursWorkedExport sum: sums) {
printLine(out, sum, payPeriod);
}
log.debug("renderMerged model = " +model);
try {
out.write(footer().getBytes());
} catch (IOException e1) {
e1.printStackTrace();
return;
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void printLine(OutputStream out, HoursWorkedExport hour, PayPer per) {
StringBuffer x = new StringBuffer("<Row>");
x.append("<Cell><Data ss:Type=\"String\">" + hour.getBatchNumber() + "</Data></Cell>");
x.append("<Cell><Data ss:Type=\"String\">" + hour.getDepartment() + "</Data></Cell>");
x.append("<Cell><Data ss:Type=\"DateTime\">" + Constants.excelDateFormat.format(
per.getBeginDate()) + "</Data></Cell>");
x.append("<Cell><Data ss:Type=\"DateTime\">" + Constants.excelDateFormat.format(
per.getEndDate()) + "</Data></Cell>");
x.append("<Cell><Data ss:Type=\"String\">" + hour.getName() + "</Data></Cell>");
x.append("<Cell><Data ss:Type=\"String\">" + hour.getPeopleId() + "</Data></Cell>");
x.append("<Cell><Data ss:Type=\"String\">" + Constants.formatFixed(hour.getHours()) + "</Data></Cell>");
x.append("<Cell><Data ss:Type=\"String\">" + Constants.formatFixed(hour.getRate()) + "</Data></Cell>");
x.append("<Cell><Data ss:Type=\"String\">" + hour.getAwardCode().toLowerCase() + "</Data></Cell>");
x.append("<Cell><Data ss:Type=\"String\">" + hour.getWorkcode().toLowerCase() + "</Data></Cell>");
x.append("</Row>");
try {
out.write(x.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public String header() {
StringBuffer x = new StringBuffer();
x.append("<?xml version=\"1.0\"?>");
x.append("<?mso-application progid=\"Excel.Sheet\"?>");
x.append("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
x.append(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
x.append(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
x.append(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
x.append(" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
x.append(" <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">");
x.append(" <WindowHeight>10005</WindowHeight>");
x.append(" <WindowWidth>10005</WindowWidth>");
x.append(" <WindowTopX>120</WindowTopX>");
x.append(" <WindowTopY>135</WindowTopY>");
x.append(" <ProtectStructure>False</ProtectStructure>");
x.append(" <ProtectWindows>False</ProtectWindows>");
x.append(" </ExcelWorkbook>");
x.append(" <Styles>");
x.append(" <Style ss:ID=\"Default\" ss:Name=\"Normal\">");
x.append(" <Alignment ss:Vertical=\"Bottom\"/>");
x.append(" <Borders/>");
x.append(" <Font ss:FontName=\"Arial\"/>");
x.append(" <Interior/>");
x.append(" <NumberFormat/>");
x.append(" <Protection/>");
x.append(" </Style>");
x.append(" <Style ss:ID=\"s62\">");
x.append(" <NumberFormat ss:Format=\"mm/dd/yy;@\"/>");
x.append(" </Style>");
x.append(" <Style ss:ID=\"s63\">");
x.append(" <Alignment ss:Horizontal=\"Right\" ss:Vertical=\"Bottom\"/>");
x.append(" <NumberFormat ss:Format=\""$"#,##0.00_);\\("$"#,##0.00\\)\"/>");
x.append(" </Style>");
x.append(" <Style ss:ID=\"s65\">");
x.append(" <Interior ss:Color=\"#00FFFF\" ss:Pattern=\"Solid\"/>");
x.append(" </Style>");
x.append(" <Style ss:ID=\"s66\">");
x.append(" <Alignment ss:Horizontal=\"Right\" ss:Vertical=\"Bottom\"/>");
x.append(" <Interior ss:Color=\"#00FFFF\" ss:Pattern=\"Solid\"/>");
x.append(" <NumberFormat ss:Format=\""$"#,##0.00_);\\("$"#,##0.00\\)\"/>");
x.append(" </Style>");
x.append(" </Styles>");
x.append(" <Worksheet ss:Name=\"Departmental Current Period\">");
x.append(" <Table>");
x.append(" <Column ss:AutoFitWidth=\"0\" ss:Width=\"78\"/>");
x.append(" <Column ss:AutoFitWidth=\"0\" ss:Width=\"39\"/>");
x.append(" <Column ss:StyleID=\"s62\" ss:AutoFitWidth=\"0\" ss:Width=\"64.5\"/>");
x.append(" <Column ss:StyleID=\"s62\" ss:AutoFitWidth=\"0\" ss:Width=\"63.75\"/>");
x.append(" <Column ss:Width=\"174\"/>");
x.append(" <Column ss:AutoFitWidth=\"0\" ss:Width=\"66.75\"/>");
x.append(" <Column ss:StyleID=\"s63\" ss:AutoFitWidth=\"0\"/>");
x.append(" <Column ss:StyleID=\"s63\" ss:AutoFitWidth=\"0\" ss:Width=\"45\"/>");
x.append(" <Column ss:Index=\"11\" ss:Width=\"56.25\" ss:Span=\"1\"/>");
x.append(" <Column ss:Index=\"13\" ss:Width=\"51.75\"/>");
x.append(" <Column ss:Width=\"51.75\"/>");
x.append(" <Row ss:StyleID=\"s65\">");
x.append(" <Cell><Data ss:Type=\"String\">Batch</Data></Cell>");
x.append(" <Cell><Data ss:Type=\"String\">Dept</Data></Cell>");
x.append(" <Cell ss:StyleID=\"s66\"><Data ss:Type=\"String\">Begin</Data></Cell>");
x.append(" <Cell ss:StyleID=\"s66\"><Data ss:Type=\"String\">End</Data></Cell>");
x.append(" <Cell><Data ss:Type=\"String\">Name</Data></Cell>");
x.append(" <Cell><Data ss:Type=\"String\">PeopleId</Data></Cell>");
x.append(" <Cell ss:StyleID=\"s66\"><Data ss:Type=\"String\">Hours</Data></Cell>");
x.append(" <Cell ss:StyleID=\"s66\"><Data ss:Type=\"String\">Rate</Data></Cell>");
x.append(" <Cell ss:StyleID=\"s66\"><Data ss:Type=\"String\">Pay Code</Data></Cell>");
x.append(" <Cell ss:StyleID=\"s66\"><Data ss:Type=\"String\">Type</Data></Cell>");
x.append(" </Row>");
return x.toString();
}
public String footer() {
StringBuffer x = new StringBuffer();
x.append(" </Table>");
x.append(" <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
x.append(" <Selected/>");
x.append(" <ProtectObjects>False</ProtectObjects>");
x.append(" <ProtectScenarios>False</ProtectScenarios>");
x.append(" </WorksheetOptions>");
x.append(" </Worksheet>");
x.append("</Workbook>");
return x.toString();
}
}
|
package net.suntrans.haipopeiwang.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import net.suntrans.haipopeiwang.App;
import net.suntrans.haipopeiwang.BaseActivity;
import net.suntrans.haipopeiwang.R;
import net.suntrans.haipopeiwang.utils.LogUtil;
import net.suntrans.haipopeiwang.utils.UiUtils;
import io.fogcloud.sdk.easylink.api.EasyLink;
import io.fogcloud.sdk.easylink.helper.EasyLinkCallBack;
import io.fogcloud.sdk.easylink.helper.EasyLinkParams;
/**
* Created by Looney on 2018/3/2.
* Des:
*/
public class AutoLinkActivity extends BaseActivity {
public static void start(Context context) {
Intent starter = new Intent(context, AutoLinkActivity.class);
context.startActivity(starter);
}
private EasyLink easyLink;
private AlertDialog dialog;
private View start;
private EditText ssid;
private EditText passwordTx;
@Override
public int getLayoutResId() {
return R.layout.activity_autolink;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setBackArrowEnable(true);
setToolBarTitle(getString(R.string.title_auto_link));
easyLink = new EasyLink(this);
start = findViewById(R.id.start);
ssid = findViewById(R.id.ssid);
passwordTx = findViewById(R.id.password);
listenwifichange();
dialog = new AlertDialog.Builder(AutoLinkActivity.this)
.setCancelable(false)
.create();
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (TextUtils.isEmpty(ssid.getText().toString()) || TextUtils.isEmpty(passwordTx.getText().toString())) {
UiUtils.showToast(getString(R.string.tips_contain_ssid_password));
return;
}
start.setEnabled(false);
startEasyLink(ssid.getText().toString(), passwordTx.getText().toString());
View view = LayoutInflater.from(AutoLinkActivity.this)
.inflate(R.layout.item_loading, null, false);
view.findViewById(R.id.close)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopEasyLink();
start.setEnabled(true);
dialog.dismiss();
}
});
dialog.setView(view);
dialog.show();
}
});
}
int settedCount = 0;
private void startEasyLink(String ssid, String password) {
EasyLinkParams params = new EasyLinkParams();
params.ssid = ssid;
params.password = password;
params.runSecond = 60000;
params.sleeptime = 50;
App.Companion.getSharedPreferences()
.edit()
.putString(ssid, password)
.apply();
// easylinkP2P.startEasyLink(params, new EasyLinkCallBack() {
// @Override
// public void onSuccess(int code, String message) {
// UiUtils.showToast(message);
//
// }
//
// @Override
// public void onFailure(int code, String message) {
//
// }
// });
easyLink.startEasyLink(params, new EasyLinkCallBack() {
@Override
public void onSuccess(int code, String message) {
settedCount++;
LogUtil.i("AutoLinkActivity",message);
}
@Override
public void onFailure(int code, String message) {
}
});
}
@Override
protected void onDestroy() {
stopEasyLink();
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
private void stopEasyLink() {
//
easyLink.stopEasyLink(new EasyLinkCallBack() {
@Override
public void onSuccess(int code, String message) {
}
@Override
public void onFailure(int code, String message) {
}
});
// easylinkP2P.stopEasyLink(new EasyLinkCallBack() {
// @Override
// public void onSuccess(int code, String message) {
//
// }
//
// @Override
// public void onFailure(int code, String message) {
//
// }
// });
}
private void listenwifichange() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
ssid.setText(easyLink.getSSID());
String password = App.Companion.getSharedPreferences().getString(easyLink.getSSID(), "");
passwordTx.setText(password);
}
}
}
};
}
|
package com.folcike.gamepanelf.services;
import com.folcike.gamepanelf.model.Game;
import com.folcike.gamepanelf.model.Machine;
import com.folcike.gamepanelf.model.Server;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.sftp.OpenMode;
import net.schmizz.sshj.sftp.RemoteFile;
import net.schmizz.sshj.sftp.RemoteResourceInfo;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import net.schmizz.sshj.xfer.FileSystemFile;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import sun.nio.ch.IOUtil;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
@Service
public final class SSHService {
public void runInstallScript(Server server) throws IOException {
Machine machine = server.getMachine();
Game game = server.getGame();
SSHClient sshClient = getClient(machine);
try {
File installScript = new File(game.getInstallScriptPath());
sshClient.newSCPFileTransfer().upload(game.getInstallScriptPath(), getHomePath(machine));
Session session = sshClient.startSession();
session.exec(String.format("chmod +x %s", getHomePath(machine) + installScript.getName())).join();
Session.Command command = session.exec(runInBash(getHomePath(machine) + installScript.getName() + getInstallParams(server)));
command.join();
String response = IOUtils.readFully(command.getInputStream()).toString();
if (!response.equals("ok")) {
throw new IOException(String.format("Script execution failed: %s", response));
}
sshClient.newSCPFileTransfer().upload(game.getStartScriptPath(), getScriptRootPath(machine, game));
sshClient.newSCPFileTransfer().upload(game.getStopScriptPath(), getScriptRootPath(machine, game));
} finally {
sshClient.disconnect();
}
}
public void runStartScript(Server server) throws IOException {
Machine machine = server.getMachine();
Game game = server.getGame();
SSHClient sshClient = getClient(machine);
try {
Session session = sshClient.startSession();
session.exec(runInBash(getStartScriptPath(machine, game))).join();
} finally {
sshClient.disconnect();
}
}
private String runInBash(String cmd){
return "bash " + cmd;
}
public void runStopScript(Server server) throws IOException {
Machine machine = server.getMachine();
Game game = server.getGame();
SSHClient sshClient = getClient(machine);
try {
Session session = sshClient.startSession();
session.exec(runInBash(getStopScriptPath(machine, game)));
} finally {
sshClient.disconnect();
}
}
public List<RemoteResourceInfo> getFileList(Server server, String path) throws IOException{
Machine machine = server.getMachine();
Game game = server.getGame();
SSHClient sshClient = getClient(machine);
try {
return sshClient.newSFTPClient().ls(getScriptRootPath(machine, game) + path);
} finally {
sshClient.disconnect();
}
}
public String getFileContent(Server server, String path) throws IOException{
Machine machine = server.getMachine();
Game game = server.getGame();
SSHClient sshClient = getClient(machine);
try{
RemoteFile file = sshClient.newSFTPClient().open(getFilePath(machine, game, path));
int fileLength = Math.toIntExact(file.length());
byte[] buffer = new byte[fileLength];
file.read(0, buffer, 0, fileLength);
return new String(buffer);
} finally {
sshClient.disconnect();
}
}
public void deleteFile(Server server, String path) throws IOException{
Machine machine = server.getMachine();
Game game = server.getGame();
SSHClient sshClient = getClient(machine);
try{
sshClient.newSFTPClient().rm(getFilePath(machine, game, path));
} finally {
sshClient.disconnect();
}
}
public void writeToFile(Server server, String path, String data) throws IOException{
Machine machine = server.getMachine();
Game game = server.getGame();
SSHClient sshClient = getClient(machine);
try{
Set<OpenMode> modes = new HashSet<>(2);
modes.add(OpenMode.CREAT);
modes.add(OpenMode.TRUNC);
RemoteFile file = sshClient.newSFTPClient().open(getFilePath(machine, game, path), modes);
byte[] dataBytes = data.getBytes();
file.write(0, dataBytes, 0, dataBytes.length);
} finally {
sshClient.disconnect();
}
}
public String readConfigFile(Server server) throws IOException {
return getFileContent(server, getConfigFilePath(server));
}
public void writeConfigFile(Server server, String data) throws IOException {
writeToFile(server, getConfigFilePath(server), data);
}
private SSHClient getClient(Machine machine) throws IOException {
SSHClient sshClient = new SSHClient();
sshClient.addHostKeyVerifier(new PromiscuousVerifier());
sshClient.connect(machine.getHostname());
sshClient.authPassword(machine.getUsername(), machine.getPassword());
sshClient.useCompression();
return sshClient;
}
private String getHomePath(Machine machine) {
return String.format("/home/%s/", machine.getUsername());
}
private String getScriptRootPath(Machine machine, Game game) {
return getHomePath(machine) + game.getScriptRootPath();
}
private String getStartScriptPath(Machine machine, Game game) {
File startScript = new File(game.getStartScriptPath());
return getScriptPath(machine, game, startScript);
}
private String getStopScriptPath(Machine machine, Game game) {
File stopScript = new File(game.getStopScriptPath());
return getScriptPath(machine, game, stopScript);
}
private String getScriptPath(Machine machine, Game game, File file) {
return getScriptRootPath(machine, game) + file.getName();
}
private String getFilePath(Machine machine, Game game, String path){
return getScriptRootPath(machine, game) + path;
}
private String getConfigFilePath(Server server){
Game game = server.getGame();
Machine machine = server.getMachine();
return getHomePath(machine) + game.getConfigRootPath() + game.getConfigFileName();
}
private String getInstallParams(Server server){
try {
return server.getId() + " " + InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
}
|
package de.szut.dqi12.extremepong.menu;
import de.szut.dqi12.extremepong.PongMainRender;
import de.szut.dqi12.extremepong.util.Bounds;
import de.szut.dqi12.extremepong.util.Screen;
public class Controller {
private Spieler[] spieler = new Spieler[4];
private static Controller instance = null;
private View view;
private Fehlermeldung fehler = null;
public static Controller getInstance() {
if (instance == null) {
instance = new Controller();
}
return instance;
}
private Controller(){
}
public void SpielEnde(int winner) {
// der View wird den Gewinner uebergeben und sie Sichtbar gemacht.
this.view.setPunkte(winner);
view.setVisible(true);
}
public Spieler[] getSpieler() {
// Getter fuer Spieler.
return spieler;
}
public void startGame(View view) {
// wennn das Menue richtig benutzt wurde wird ein Objekt von
// PongMainRender erzeugt und die View unsichtbar gemacht.
if (this.checkInput(view)) {
this.returnValues();
view.setVisible(false);
// Pong (lwjgl)
if(PongMainRender.DEBUG) System.out.println("[+] Spiel gestartet!");
PongMainRender.getInstance().renderPong();
} else {
// Falls der/die User was falsch eingeben haben, wird eine Fehlermeldung ausgeben
this.fehler = new Fehlermeldung("Falsche Eingabe!!!", new Bounds(Screen.WIDTH/2, Screen.HEIGHT/2, 400, 400));
this.fehler.move();
}
}
private boolean checkInput(View view) {
// Die eingaben des Useres werden auf Vollstendigkeit ueberprueft.
// Ist die Eingabe richtig, wird ein true zurueckgegeben, sonst ein
// false.
this.view = view;
for (int i = 0; i < view.getTastenFelder().length; i++) {
if (view.getTastenFelder()[i].getText().length() != 1) {
return false;
}
for(int b=0; b< view.getTastenFelder().length;b++){
if(b!=i){
if(view.getTastenFelder()[i].getText().equals(view.getTastenFelder()[b].getText())){
return false;
}
}
}
}
if (!view.getPufalse().isSelected() && !view.getPutrue().isSelected()) {
return false;
}
return true;
}
private void returnValues() {
// Dem Memberarray von Spielern werden Werte uebegeben.
for (int i = 0; i < 4; i++) {
this.spieler[i] = new Spieler();
this.spieler[i].setTaste1(view.getTastenFelder()[i * 2].getText()
.toCharArray()[0]);
this.spieler[i].setTaste2(view.getTastenFelder()[i * 2 + 1]
.getText().toCharArray()[0]);
}
}
}
|
package miguel.mvp.ui.search;
import miguel.mvp.model.SearchResult;
import miguel.mvp.ui.MVPBase.LoadingContentErrorView;
import miguel.mvp.ui.MVPBase.Presenter;
public interface SearchContract {
interface SearchView extends LoadingContentErrorView<SearchResult> { }
interface SearchPresenter extends Presenter<SearchView> {
void doSearch(String term);
}
}
|
package com.forsrc.utils;
import java.util.Scanner;
/**
* The interface File read line scanner adapter.
*/
public interface FileReadLineScannerAdapter extends FileReadLineAdapter {
/**
* Init.
*
* @param scanner the scanner
*/
public void init(Scanner scanner);
}
|
package com.cnk.travelogix.suppliers.helper;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.cnk.travelogix.supplier.mappings.product.model.SupplierProductModel;
import com.cnk.travelogix.suppliers.constants.SuppliersConstants;
import com.cnk.travelogix.suppliers.events.CheckFileStatusEvent;
import de.hybris.platform.core.Registry;
import de.hybris.platform.servicelayer.event.EventService;
import de.hybris.platform.servicelayer.exceptions.AmbiguousIdentifierException;
import de.hybris.platform.servicelayer.exceptions.ModelNotFoundException;
import de.hybris.platform.servicelayer.search.FlexibleSearchService;
import de.hybris.platform.util.Config;
public class ProcessFileDataHelper implements Callable<List<String>> {
/** The Constant LOGGER. */
private static final Logger LOG = Logger.getLogger(ProcessFileDataHelper.class);
/** The Constant lineItem. */
private File file;
/** The event service. */
private EventService eventService;
/** The list for error **/
private List<String> errorLines = null;
/** The flexible service. */
private FlexibleSearchService flexibleSearchService;
public ProcessFileDataHelper(final File file) {
this.file = file;
}
@Override
public List<String> call() throws IOException {
LOG.info("Inside the run method- Start");
errorLines = new ArrayList<>();
process(file, errorLines);
LOG.info("Inside the run method- End");
return errorLines;
}
/**
*
* @param line
* @throws IOException
*/
private void process(final File file, final List<String> errorLines) {
if (null != file) {
String line = StringUtils.EMPTY;
try(BufferedReader reader = new BufferedReader(new FileReader(file));) {
while ((line = reader.readLine()) != null) {
setEmailParams(line);
}
} catch (IOException ioe) {
LOG.error("IO Exception occured.", ioe);
errorLines.add(line);
}
LOG.info("Inside the processLineItem method- End");
}
}
public void setEmailParams(String line)
{
final CheckFileStatusEvent event = new CheckFileStatusEvent();
LOG.info("Inside the processLineItem method- Start");
final String[] column = line.split(SuppliersConstants.SPLIT_OPERATOR);
Registry.activateMasterTenant();
if (StringUtils.isNotBlank(column[14])) {
LOG.info("Inside the if, since we have the action type.");
// Checking the flag for type of email to be sent.
if (StringUtils.equalsIgnoreCase(column[14], "U")) {
event.setEmailId(Config.getParameter("add.update.emailId.reference"));
event.setEmailJourney("Update");
}
if (StringUtils.equalsIgnoreCase(column[14], "D")) {
event.setEmailId(Config.getParameter("delete.emailId.reference"));
event.setEmailJourney("Delete");
}
LOG.info("Triggering the email from if loop.");
eventService.publishEvent(event);
} else {
LOG.info("Inside the else, since we do not have the action type.");
SupplierProductModel supplierProductModel = new SupplierProductModel();
if (StringUtils.isNotBlank(column[4])) {
supplierProductModel.setAddress(column[4]);
}
if (StringUtils.isNotBlank(column[5])) {
supplierProductModel.setTelephone(column[5]);
}
if (StringUtils.isNotBlank(column[6])) {
supplierProductModel.setCountry(column[6]);
}
if (StringUtils.isNotBlank(column[7])) {
supplierProductModel.setCity(column[7]);
}
if (StringUtils.isNotBlank(column[8])) {
supplierProductModel.setLocation(column[8]);
}
LOG.info("All attributes are set now for the model.");
getSupplierModel(supplierProductModel,event);
}
}
public void getSupplierModel(SupplierProductModel supplierProductModel,CheckFileStatusEvent event)
{
try {
SupplierProductModel supplierProductNewModel = flexibleSearchService.getModelByExample(supplierProductModel);
LOG.info("Supplier model found with the details of the line."+supplierProductNewModel);
} catch (final ModelNotFoundException mnfe) {
LOG.error("Supplier product model not found in the DB.", mnfe);
event.setEmailId(Config.getParameter("add.update.emailId.reference"));
eventService.publishEvent(event);
} catch (final AmbiguousIdentifierException aie) {
LOG.error(" Multiple Supplier product model found in the DB.", aie);
}
}
public void setEventService(EventService eventService) {
this.eventService = eventService;
}
public void setFlexibleSearchService(FlexibleSearchService flexibleSearchService) {
this.flexibleSearchService = flexibleSearchService;
}
}
|
// Sun Certified Java Programmer
// Chapter 1, P61_2
// Declarations and Access Control
public class CoffeeTest2 {
public static void main(String[] args) {
Coffee2 drink = new Coffee2();
drink.size = Coffee2.CoffeeSize.BIG; // enclosing class name required
}
}
|
package com.beiyelin.crawler.service.impl;
import com.beiyelin.commonsql.jpa.BaseDomainCRUDServiceImpl;
import com.beiyelin.crawler.entity.Weather;
import com.beiyelin.crawler.repository.WeatherRepository;
import com.beiyelin.crawler.service.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Description:
* @Author: newmann
* @Date: Created in 22:46 2018-02-11
*/
@Service("weatherService")
public class WeatherServiceImpl extends BaseDomainCRUDServiceImpl<Weather> implements WeatherService {
private WeatherRepository weatherRepository;
@Autowired
public void setWeatherRepository(WeatherRepository repository){
this.weatherRepository = repository;
super.setSuperRepository(repository);
}
}
|
package io.algo;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class DirectedGraph {
static Map<Vertex, List<Edge>> dGraph = new ConcurrentHashMap<>();
static class Vertex {
private String label;
public Vertex(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
@Override
public int hashCode() {
return label.hashCode();
}
@Override
public boolean equals(Object obj) {
Vertex vtx = (Vertex) obj;
return vtx.getLabel().equals(this.getLabel());
}
@Override
public String toString() {
return "Vertex{" +
"label='" + label + '\'' +
'}';
}
}
static class Edge {
private String srcVtx, destVtx;
public Edge(String srcVtx, String destVtx) {
this.srcVtx = srcVtx;
this.destVtx = destVtx;
}
public String getSrcVtx() {
return srcVtx;
}
public String getDestVtx() {
return destVtx;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Edge edge = (Edge) o;
return Objects.equals(srcVtx, edge.srcVtx) &&
Objects.equals(destVtx, edge.destVtx);
}
@Override
public int hashCode() {
return Objects.hash(srcVtx, destVtx);
}
@Override
public String toString() {
return "Edge{" +
"srcVtx='" + srcVtx + '\'' +
", destVtx='" + destVtx + '\'' +
'}';
}
}
public static void addVertex(String label) {
dGraph.putIfAbsent(new Vertex(label), new CopyOnWriteArrayList<>());
}
public static void addEdge(String src, String dest) {
Vertex vertex = new Vertex(src);
Edge edge = new Edge(src, dest);
if (dGraph.containsKey(vertex)) {
dGraph.get(vertex).add(edge);
} else {
List<Edge> edges = new CopyOnWriteArrayList<>();
edges.add(edge);
addVertex(src);
dGraph.get(vertex).add(edge);
}
}
public static void displayGraph() {
dGraph.forEach((Vertex k, List<Edge> v) -> {
v.forEach(op -> {
System.out.println(k.getLabel() + " -> " + op.getDestVtx());
});
});
}
public static void removeVertex(String label) {
Vertex vertex = new Vertex(label);
dGraph.remove(vertex);
dGraph.forEach((k, v) -> {
v.stream().filter(o -> o.getDestVtx().equals(vertex.getLabel())).forEach(p -> v.remove(p));
});
}
public static void removeEdge(String label, String dest) {
dGraph.forEach((k,v) -> {
v.remove(new Edge(label, dest));
});
}
public static void main(String[] args) {
addVertex("P");
addVertex("Q");
addVertex("R");
addVertex("T");
addVertex("S");
addEdge("P", "Q");
addEdge("P", "T");
addEdge("R", "P");
addEdge("R", "S");
addEdge("T", "R");
addEdge("T", "S");
System.out.println("Displaying Graph");
displayGraph();
System.out.println("Removing R");
removeVertex("R");
displayGraph();
System.out.println("Removing Edge P to Q");
removeEdge("P", "Q");
displayGraph();
}
}
|
package p3.control;
import p3.Exceptions.CommandExecuteException;
import p3.Exceptions.CommandParseException;
import p3.logic.game.Game;
public class PrintModeCommand extends Command{
public static final String symbol = "p";
public static final String name = "printmode";
public static final String help = "Changes the print mode [Relase | Debug].";
private String mode;
public PrintModeCommand() {
super(PrintModeCommand.symbol, PrintModeCommand.name, PrintModeCommand.help);
}
public PrintModeCommand(String mode) {
super(PrintModeCommand.symbol, PrintModeCommand.name, PrintModeCommand.help);
this.mode = mode;
}
public void execute(Game game) throws CommandExecuteException {
game.changePrintMode(this.mode);
}
public Command parse(String[] commandWords) throws CommandParseException {
if ((commandWords[0].equals(PrintModeCommand.name) || commandWords[0].equals(PrintModeCommand.symbol))) {
if (commandWords.length == 2) {
return new PrintModeCommand(commandWords[1]);
}
else
throw new CommandParseException("[ERROR]: print (p) takes 1 argument: 'printMode'.\n");
}
else {
return null;
}
}
}
|
package com.github.vinja.locate;
public class WatchedDirInfo {
private String alias;
private String startDir;
private String excludes;
private int depth;
private int watchId;
public String getStartDir() {
return startDir;
}
public void setStartDir(String startDir) {
this.startDir = startDir;
}
public String getExcludes() {
return excludes;
}
public void setExcludes(String excludes) {
this.excludes = excludes;
}
public int getDepth() {
return depth;
}
public void setDepth(int depth) {
this.depth = depth;
}
public int getWatchId() {
return watchId;
}
public void setWatchId(int watchId) {
this.watchId = watchId;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getAlias() {
return alias;
}
}
|
package com.espendwise.manta.model.view;
// Generated by Hibernate Tools
import com.espendwise.manta.model.ValueObject;
import java.util.Locale;
/**
* LogonOptionView generated by hbm2java
*/
public class LogonOptionView extends ValueObject implements java.io.Serializable {
private static final long serialVersionUID = -1;
public static final String DOMAIN = "domain";
public static final String STORE_ID = "storeId";
public static final String DATASOURCE = "datasource";
public static final String UI_OPTION = "uiOption";
public static final String LOCALE = "locale";
private String domain;
private Long storeId;
private String datasource;
private UiOptionView uiOption;
private Locale locale;
public LogonOptionView() {
}
public LogonOptionView(String domain) {
this.setDomain(domain);
}
public LogonOptionView(String domain, Long storeId, String datasource, UiOptionView uiOption, Locale locale) {
this.setDomain(domain);
this.setStoreId(storeId);
this.setDatasource(datasource);
this.setUiOption(uiOption);
this.setLocale(locale);
}
public String getDomain() {
return this.domain;
}
public void setDomain(String domain) {
this.domain = domain;
setDirty(true);
}
public Long getStoreId() {
return this.storeId;
}
public void setStoreId(Long storeId) {
this.storeId = storeId;
setDirty(true);
}
public String getDatasource() {
return this.datasource;
}
public void setDatasource(String datasource) {
this.datasource = datasource;
setDirty(true);
}
public UiOptionView getUiOption() {
return this.uiOption;
}
public void setUiOption(UiOptionView uiOption) {
this.uiOption = uiOption;
setDirty(true);
}
public Locale getLocale() {
return this.locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
setDirty(true);
}
}
|
package tw6a;
abstract class Class
{
String carName;
int chassiNum;
String modelName;
public Car(String carName, int chassiNum, String modelName)
{
this.carName = carName;
this.chassiNum = chassiNum;
this.modelName = modelName;
}
public void startCar()
{
System.out.println("the car has started");
};
abstract public void operateSterring();
}
class MarutiCar extends Car implements A
{
int mileage ;
String enginenum;
public MarutiCar(String carName, int chassiNum, String modelName, int mileage, String enginenum)
{
super(carName, chassiNum, modelName);
this.mileage = mileage;
this.enginenum = enginenum;
}
public void startCar()
{
System.out.println("Starting the car with Electronic ignition");
}
public void operateSterring()
{
System.out.println("turning left and right as needed\n");
}
@Override
public void disp()
{
}
}
class BMWcar extends Car
{
float emissionlevel;
int numAirbag;
public BMWcar(String carname, int chassinum, String modelname, float emissionlevel, int numAirbag)
{
super(carname, chassinum, modelname);
this.emissionlevel = emissionlevel;
this.numAirbag = numAirbag;
}
public void startaCar()
{
System.out.println("starting the car with a remote and Peizoelectric effect");
}
public void operateSterring()
{
System.out.println("BMW turning left and right and is easy to operate since it is power stering");
}
}
class Driver
{
String drivername;
int age;
char gender;
public Driver(String drivername, int age, char gender)
{
super();
this.drivername = drivername;
this.age = age;
this.gender = gender;
}
public void drivercar(Car c)
{
System.out.println("Driver name is " + this.drivername + " and is driving " + c.carName);
c.startCar();
c.operateSterring();
}
}
public class TW6a {
public static void main(String[] args) {
MarutiCar m = new MarutiCar("Zen", 11223, "2002 model",18,"EN4333");
BMWcar b = new BMWcar("BMW AS - 8",3322, "2010 model",12.32f ,4);
Driver d = new Driver("vivek",19,'M');
Car c;
c=m;
d.drivercar(c);
c=b;
d.drivercar(c);
}
}
|
package Simulation;
public class Util {
public static boolean isNaN(float val) {
return val != val;
}
public static float distanceSquared( float x, float y) {
return x * x + y * y;
}
public static float distance( float x, float y ) {
return sqrt( x * x + y * y );
}
public static float distanceSquared( float x1, float y1, float x2, float y2 ) {
return distanceSquared( x1-x2, y1-y2 );
}
public static float distance( float x1, float y1, float x2, float y2 ) {
return distance( x1-x2, y1-y2 );
}
public static float distance( Vector2f a, Vector2f b) {
return distance( a.getX(), a.getY(), b.getX(), b.getY() );
}
public static float distanceSquared( Vector2f a, Vector2f b ) {
return distanceSquared( a.getX(), a.getY(), b.getX(), b.getY() );
}
public static float distance( float[] point ) {
float sum = 0;
for( int i = 0; i < point.length; ++i )
sum += point[i] * point[i];
return sqrt(sum);
}
public static int minMax(int val, int min, int max) {
return ( val > max ) ? max : ( ( val < min ) ? min : val );
}
public static float minMax(float val, float min, float max) {
return ( val > max ) ? max : ( ( val < min ) ? min : val );
}
public static float[] minMaxLength( float[] point, float min, float max ) {
float dist = distance( point );
if( dist >= min && dist <= max )
return point;
float scale = ( dist > max ? max : min ) / dist;
for( int i = 0; i < point.length; ++i )
point[i] *= scale;
return point;
}
public static float dotProduct( float[] a, float[] b ) {
float ret = 0;
int i = -1, len = Math.min(a.length, b.length);
while( ++i < len )
ret += a[i] * b[i];
return ret;
}
public static float sum(float... vals) {
float ret = 0;
for( int i = 0; i < vals.length; ++i )
ret += vals[i];
return ret;
}
public static float avg(float... vals) {
float ret = sum(vals);
if( vals.length > 0 )
ret /= (float)vals.length;
return ret;
}
public static float invert(float val) {
if( val != 0 )
val = 1f / val;
return val;
}
public static float min(float a, float b) {
return a > b ? b : a;
}
public static float max(float a, float b) {
return a > b ? a : b;
}
public static float abs(float a) {
return a < 0 ? -a : a;
}
public static float square( float val ) {
return val*val;
}
public static int round(float val) {
float r = val % 1;
return (int)(r >= 0.5f ? val - r + 1 : val - r);
}
public static float exp(float val) {
return (float)Math.exp(val);
}
public static float sqrt(float val) {
return (float)Math.sqrt(val);
}
public static float sin(float theta) {
return (float)Math.sin(theta);
}
public static float cos(float theta) {
return (float)Math.cos(theta);
}
public static float atan2(float x, float y) {
return (float)Math.atan2(x, y);
}
public static float[] polarToCartesian(float r, float theta) {
return new float[] { r * sin(theta), r * cos(theta) };
}
public static float[] cartesianToPolar(float x, float y) {
return new float[] { distance(x, y), atan2(x, y) };
}
public static String getString(float[] data) {
return join(" ",data);
}
public static String join( String separator, float[] data) {
String ret = "";
for( int i = 0; i < data.length; ++i ) {
if( i > 0 )
ret += separator;
ret += data[i];
}
return ret;
}
}
|
package ls.example.t.zero2line.util;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/10
* desc : utils about messenger
* </pre>
*/
public class MessengerUtils {
private static java.util.concurrent.ConcurrentHashMap<String, ls.example.t.zero2line.util.MessengerUtils.MessageCallback> subscribers = new java.util.concurrent.ConcurrentHashMap<>();
private static java.util.Map<String, ls.example.t.zero2line.util.MessengerUtils.Client> sClientMap = new java.util.HashMap<>();
private static ls.example.t.zero2line.util.MessengerUtils.Client sLocalClient;
private static final int WHAT_SUBSCRIBE = 0x00;
private static final int WHAT_UNSUBSCRIBE = 0x01;
private static final int WHAT_SEND = 0x02;
private static final String KEY_STRING = "MESSENGER_UTILS";
public static void register() {
if (isMainProcess()) {
if (isServiceRunning(ls.example.t.zero2line.util.MessengerUtils.ServerService.class.getName())) {
android.util.Log.i("MessengerUtils", "Server service is running.");
return;
}
android.content.Intent intent = new android.content.Intent(Utils.getApp(), ls.example.t.zero2line.util.MessengerUtils.ServerService.class);
Utils.getApp().startService(intent);
return;
}
if (sLocalClient == null) {
ls.example.t.zero2line.util.MessengerUtils.Client client = new ls.example.t.zero2line.util.MessengerUtils.Client(null);
if (client.bind()) {
sLocalClient = client;
} else {
android.util.Log.e("MessengerUtils", "Bind service failed.");
}
} else {
android.util.Log.i("MessengerUtils", "The client have been bind.");
}
}
public static void unregister() {
if (isMainProcess()) {
if (!isServiceRunning(ls.example.t.zero2line.util.MessengerUtils.ServerService.class.getName())) {
android.util.Log.i("MessengerUtils", "Server service isn't running.");
return;
}
android.content.Intent intent = new android.content.Intent(Utils.getApp(), ls.example.t.zero2line.util.MessengerUtils.ServerService.class);
Utils.getApp().stopService(intent);
}
if (sLocalClient != null) {
sLocalClient.unbind();
}
}
public static void register(final String pkgName) {
if (sClientMap.containsKey(pkgName)) {
android.util.Log.i("MessengerUtils", "register: client registered: " + pkgName);
return;
}
ls.example.t.zero2line.util.MessengerUtils.Client client = new ls.example.t.zero2line.util.MessengerUtils.Client(pkgName);
if (client.bind()) {
sClientMap.put(pkgName, client);
} else {
android.util.Log.e("MessengerUtils", "register: client bind failed: " + pkgName);
}
}
public static void unregister(final String pkgName) {
if (sClientMap.containsKey(pkgName)) {
ls.example.t.zero2line.util.MessengerUtils.Client client = sClientMap.get(pkgName);
client.unbind();
} else {
android.util.Log.i("MessengerUtils", "unregister: client didn't register: " + pkgName);
}
}
public static void subscribe(@android.support.annotation.NonNull final String key, @android.support.annotation.NonNull final ls.example.t.zero2line.util.MessengerUtils.MessageCallback callback) {
subscribers.put(key, callback);
}
public static void unsubscribe(@android.support.annotation.NonNull final String key) {
subscribers.remove(key);
}
public static void post(@android.support.annotation.NonNull String key, @android.support.annotation.NonNull android.os.Bundle data) {
data.putString(KEY_STRING, key);
if (sLocalClient != null) {
sLocalClient.sendMsg2Server(data);
} else {
android.content.Intent intent = new android.content.Intent(Utils.getApp(), ls.example.t.zero2line.util.MessengerUtils.ServerService.class);
intent.putExtras(data);
Utils.getApp().startService(intent);
}
for (ls.example.t.zero2line.util.MessengerUtils.Client client : sClientMap.values()) {
client.sendMsg2Server(data);
}
}
private static boolean isMainProcess() {
return Utils.getApp().getPackageName().equals(Utils.getCurrentProcessName());
}
private static boolean isAppInstalled(@android.support.annotation.NonNull final String pkgName) {
android.content.pm.PackageManager packageManager = Utils.getApp().getPackageManager();
try {
return packageManager.getApplicationInfo(pkgName, 0) != null;
} catch (android.content.pm.PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
private static boolean isServiceRunning(final String className) {
android.app.ActivityManager am =
(android.app.ActivityManager) Utils.getApp().getSystemService(android.content.Context.ACTIVITY_SERVICE);
//noinspection ConstantConditions
java.util.List<android.app.ActivityManager.RunningServiceInfo> info = am.getRunningServices(0x7FFFFFFF);
if (info == null || info.size() == 0) return false;
for (android.app.ActivityManager.RunningServiceInfo aInfo : info) {
if (className.equals(aInfo.service.getClassName())) return true;
}
return false;
}
private static boolean isAppRunning(@android.support.annotation.NonNull final String pkgName) {
int uid;
android.content.pm.PackageManager packageManager = Utils.getApp().getPackageManager();
try {
android.content.pm.ApplicationInfo ai = packageManager.getApplicationInfo(pkgName, 0);
if (ai == null) return false;
uid = ai.uid;
} catch (android.content.pm.PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
android.app.ActivityManager am = (android.app.ActivityManager) Utils.getApp().getSystemService(android.content.Context.ACTIVITY_SERVICE);
if (am != null) {
java.util.List<android.app.ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(Integer.MAX_VALUE);
if (taskInfo != null && taskInfo.size() > 0) {
for (android.app.ActivityManager.RunningTaskInfo aInfo : taskInfo) {
if (pkgName.equals(aInfo.baseActivity.getPackageName())) {
return true;
}
}
}
java.util.List<android.app.ActivityManager.RunningServiceInfo> serviceInfo = am.getRunningServices(Integer.MAX_VALUE);
if (serviceInfo != null && serviceInfo.size() > 0) {
for (android.app.ActivityManager.RunningServiceInfo aInfo : serviceInfo) {
if (uid == aInfo.uid) {
return true;
}
}
}
}
return false;
}
static class Client {
String mPkgName;
android.os.Messenger mServer;
java.util.LinkedList<android.os.Bundle> mCached = new java.util.LinkedList<>();
@android.annotation.SuppressLint("HandlerLeak")
android.os.Handler mReceiveServeMsgHandler = new android.os.Handler() {
@Override
public void handleMessage(android.os.Message msg) {
android.os.Bundle data = msg.getData();
if (data != null) {
String key = data.getString(KEY_STRING);
if (key != null) {
ls.example.t.zero2line.util.MessengerUtils.MessageCallback callback = subscribers.get(key);
if (callback != null) {
callback.messageCall(data);
}
}
}
}
};
android.os.Messenger mClient = new android.os.Messenger(mReceiveServeMsgHandler);
android.content.ServiceConnection mConn = new android.content.ServiceConnection() {
@Override
public void onServiceConnected(android.content.ComponentName name, android.os.IBinder service) {
android.util.Log.d("MessengerUtils", "client service connected " + name);
mServer = new android.os.Messenger(service);
int key = Utils.getCurrentProcessName().hashCode();
android.os.Message msg = android.os.Message.obtain(mReceiveServeMsgHandler, WHAT_SUBSCRIBE, key, 0);
msg.replyTo = mClient;
try {
mServer.send(msg);
} catch (android.os.RemoteException e) {
android.util.Log.e("MessengerUtils", "onServiceConnected: ", e);
}
sendCachedMsg2Server();
}
@Override
public void onServiceDisconnected(android.content.ComponentName name) {
android.util.Log.w("MessengerUtils", "client service disconnected:" + name);
mServer = null;
if (!bind()) {
android.util.Log.e("MessengerUtils", "client service rebind failed: " + name);
}
}
};
Client(String pkgName) {
this.mPkgName = pkgName;
}
boolean bind() {
if (android.text.TextUtils.isEmpty(mPkgName)) {
android.content.Intent intent = new android.content.Intent(Utils.getApp(), ls.example.t.zero2line.util.MessengerUtils.ServerService.class);
return Utils.getApp().bindService(intent, mConn, android.content.Context.BIND_AUTO_CREATE);
}
if (isAppInstalled(mPkgName)) {
if (isAppRunning(mPkgName)) {
android.content.Intent intent = new android.content.Intent(mPkgName + ".messenger");
intent.setPackage(mPkgName);
return Utils.getApp().bindService(intent, mConn, android.content.Context.BIND_AUTO_CREATE);
} else {
android.util.Log.e("MessengerUtils", "bind: the app is not running -> " + mPkgName);
return false;
}
} else {
android.util.Log.e("MessengerUtils", "bind: the app is not installed -> " + mPkgName);
return false;
}
}
void unbind() {
android.os.Message msg = android.os.Message.obtain(mReceiveServeMsgHandler, WHAT_UNSUBSCRIBE);
msg.replyTo = mClient;
try {
mServer.send(msg);
} catch (android.os.RemoteException e) {
android.util.Log.e("MessengerUtils", "unbind: ", e);
}
try {
Utils.getApp().unbindService(mConn);
} catch (Exception ignore) {/*ignore*/}
}
void sendMsg2Server(android.os.Bundle bundle) {
if (mServer == null) {
mCached.addFirst(bundle);
android.util.Log.i("MessengerUtils", "save the bundle " + bundle);
} else {
sendCachedMsg2Server();
if (!send2Server(bundle)) {
mCached.addFirst(bundle);
}
}
}
private void sendCachedMsg2Server() {
if (mCached.isEmpty()) return;
for (int i = mCached.size() - 1; i >= 0; --i) {
if (send2Server(mCached.get(i))) {
mCached.remove(i);
}
}
}
private boolean send2Server(android.os.Bundle bundle) {
android.os.Message msg = android.os.Message.obtain(mReceiveServeMsgHandler, WHAT_SEND);
msg.setData(bundle);
msg.replyTo = mClient;
try {
mServer.send(msg);
return true;
} catch (android.os.RemoteException e) {
android.util.Log.e("MessengerUtils", "send2Server: ", e);
return false;
}
}
}
public static class ServerService extends android.app.Service {
private final java.util.concurrent.ConcurrentHashMap<Integer, android.os.Messenger> mClientMap = new java.util.concurrent.ConcurrentHashMap<>();
@android.annotation.SuppressLint("HandlerLeak")
private final android.os.Handler mReceiveClientMsgHandler = new android.os.Handler() {
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case WHAT_SUBSCRIBE:
mClientMap.put(msg.arg1, msg.replyTo);
break;
case WHAT_SEND:
sendMsg2Client(msg);
consumeServerProcessCallback(msg);
break;
case WHAT_UNSUBSCRIBE:
mClientMap.remove(msg.arg1);
break;
default:
super.handleMessage(msg);
}
}
};
private final android.os.Messenger messenger = new android.os.Messenger(mReceiveClientMsgHandler);
@android.support.annotation.Nullable
@Override
public android.os.IBinder onBind(android.content.Intent intent) {
return messenger.getBinder();
}
@Override
public int onStartCommand(android.content.Intent intent, int flags, int startId) {
if (intent != null) {
android.os.Bundle extras = intent.getExtras();
if (extras != null) {
android.os.Message msg = android.os.Message.obtain(mReceiveClientMsgHandler, WHAT_SEND);
msg.replyTo = messenger;
msg.setData(extras);
sendMsg2Client(msg);
consumeServerProcessCallback(msg);
}
}
return START_NOT_STICKY;
}
private void sendMsg2Client(final android.os.Message msg) {
for (android.os.Messenger client : mClientMap.values()) {
try {
if (client != null) {
client.send(msg);
}
} catch (android.os.RemoteException e) {
e.printStackTrace();
}
}
}
private void consumeServerProcessCallback(final android.os.Message msg) {
android.os.Bundle data = msg.getData();
if (data != null) {
String key = data.getString(KEY_STRING);
if (key != null) {
ls.example.t.zero2line.util.MessengerUtils.MessageCallback callback = subscribers.get(key);
if (callback != null) {
callback.messageCall(data);
}
}
}
}
}
public interface MessageCallback {
void messageCall(android.os.Bundle data);
}
}
|
// Sun Certified Java Programmer
// Chapter 3, P215
// Assignments
class Tester215 {
public static void main(String[] args) {
Foo h = new Foo();
h.setName("Bill");
System.out.println(h.getName());
h.bar();
System.out.println(h.getName());
}
}
|
package com.tencent.mm.pluginsdk.ui.d;
import android.text.Spanned;
import android.view.View;
import android.widget.TextView;
import com.tencent.mm.kiss.widget.textview.StaticTextView;
import com.tencent.mm.sdk.platformtools.x;
public final class e {
private static int I(View view, int i) {
if (view instanceof TextView) {
if (((TextView) view).getLayout() == null) {
return 0;
}
return ((TextView) view).getLayout().getLineEnd(i);
} else if (!(view instanceof StaticTextView)) {
return 0;
} else {
if (((StaticTextView) view).getTvLayout() == null) {
return 0;
}
return ((StaticTextView) view).getTvLayout().getLineEnd(i);
}
}
public static boolean a(View view, Spanned spanned) {
if (!(view == null || spanned == null || (!(view instanceof TextView) && !(view instanceof StaticTextView)))) {
int lineCount = view instanceof TextView ? ((TextView) view).getLineCount() : view instanceof StaticTextView ? ((StaticTextView) view).getLineCount() : 0;
if (lineCount != 1 || spanned.length() <= 500) {
for (int i = 1; i < lineCount; i++) {
if (I(view, i) - I(view, i - 1) > 500) {
x.e("MicroMsg.InvalidTextCheck", "error black dot");
return true;
}
}
} else {
x.e("MicroMsg.InvalidTextCheck", "error black dot");
return true;
}
}
return false;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.acceleratorfacades.cartfileupload;
import java.io.InputStream;
/**
* This interface supports asynchronous processing of file upload to create a SavedCart.
*/
public interface SavedCartFileUploadFacade
{
/**
* Creates SavedCart from the file uploaded in asynchronous fashion. This will create a @
* {@link de.hybris.platform.acceleratorservices.cartfileupload.events.SavedCartFileUploadEvent} event which is
* captured by event listener @
* {@link de.hybris.platform.acceleratorservices.cartfileupload.events.SavedCartFileUploadEventListener} to trigger a
* business process.
*
* @param fileStream
* Input stream of the file
* @param fileName
* File Name
* @param fileFormat
* File Format
*/
void createCartFromFileUpload(InputStream fileStream, String fileName, String fileFormat);
}
|
/**
*
*/
package dynamicProgramming;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author ssingh
*
*/
public class WordBreak {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> wordSet = new HashSet<String>(wordDict);
boolean[] dp = new boolean[s.length() + 1];
// dp[i] represents if s.substring(0, i) is wordbreakable.
dp[0] = true;
for (int i = 1; i < dp.length; i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && wordSet.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
/**
* @param args
*/
public static void main(String[] args) {
// String[] words = new String[] { "lee", "leetco", "leet", "tco",
// "des", "code" };
// List<String> wordDict = Arrays.asList(words);
//
// WordBreak wb = new WordBreak();
// System.out.println(wb.wordBreak("leetcode", wordDict));
// System.out.println(wb.wordBreak("tcodes", wordDict));
// System.out.println(wb.wordBreak("tcodess", wordDict));
// System.out.println(wb.wordBreak("deslee", wordDict));
// System.out.println(wb.wordBreak("codelee", wordDict));
// System.out.println(wb.wordBreak("cdelee", wordDict));
// System.out.println(wb.wordBreak("leecodetco", wordDict));
// System.out.println(wb.wordBreak("leecodetcodess", wordDict));
// System.out.println(wb.wordBreak("leecodetcolee", wordDict));
String[] words = new String[] { "a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa",
"aaaaaaaaaa" };
List<String> wordDict = Arrays.asList(words);
WordBreak wb = new WordBreak();
System.out.println(wb.wordBreak(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
wordDict));
}
}
|
package pl.wenusix.familiada.model;
import java.util.List;
public class QuestionModel {
private String question;
private int level;
private List<AnswerInputModel> answers;
public String getQuestion() {
return question;
}
public int getLevel() {
return level;
}
public List<AnswerInputModel> getAnswers() {
return answers;
}
}
|
package org.scilab.forge.jlatexmath.geom;
import org.robovm.apple.coregraphics.CGPoint;
import org.scilab.forge.jlatexmath.platform.geom.Point2D;
public class Point2DI implements Point2D{
private CGPoint point;
public Point2DI(double x, double y) {
point = new CGPoint((float) x, (float) y);
}
@Override
public double getX() {
// TODO Auto-generated method stub
return point.getX();
}
@Override
public double getY() {
// TODO Auto-generated method stub
return point.getY();
}
@Override
public void setX(double x) {
// TODO Auto-generated method stub
point.setX(x);
}
@Override
public void setY(double y) {
// TODO Auto-generated method stub
point.setY(y);
}
}
|
package gdut.ff.generator.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import gdut.ff.generator.util.PropertyUtil;
import gdut.ff.generator.util.StringUtil;
import gdut.ff.generator.util.TypeAliasRegistry;
/**
* @author liuffei
* @date 2018-03-28
* @description
*/
public class DataSourceConnect {
public Map<String, Class<?>> typeAliases = new TypeAliasRegistry().getTYPE_ALIASES();
/**
* 建立数据库连接
* @return
*/
public Connection getConnect() {
try {
//1.加载驱动
Class.forName(PropertyUtil.JDBC_DRIVER);
//2.连接
Connection connection = DriverManager.getConnection(PropertyUtil.JDBC_URL, PropertyUtil.JDBC_USERNAME, PropertyUtil.JDBC_PASSWORD);
return connection;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 关闭
* @param connection
*/
public void close(Connection connection,Statement statement,ResultSet resultSet) {
if(null != connection) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != statement) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != resultSet) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 查询数据库全部的表
*/
public List<String> QueryAllTable() {
Connection conn = null;
Statement prepareStatement = null;
ResultSet resultSet = null;
List<String> tables = new LinkedList<String>();
try {
conn = getConnect();
String sql = "SHOW TABLES";
prepareStatement = conn.prepareStatement(sql);
resultSet = prepareStatement .executeQuery(sql);
while(resultSet.next()) {
tables.add(resultSet.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
close(conn,prepareStatement,resultSet);
return tables;
}
/**
* 查询一张表全部的字段
* @param tableName
* @param databaseName
* @return
*/
public List<Map<String,Object>> queryColumn(String tableName,String databaseName) {
Connection conn = null;
Statement prepareStatement = null;
ResultSet resultSet = null;
List<Map<String,Object>> columns = new LinkedList<Map<String,Object>>();
try {
conn = getConnect();
String sql = "SELECT COLUMN_COMMENT,COLUMN_NAME,DATA_TYPE,IS_NULLABLE,CHARACTER_MAXIMUM_LENGTH,COLUMN_KEY FROM information_schema.`COLUMNS` WHERE TABLE_NAME = '"+tableName+"' AND TABLE_SCHEMA = '"+databaseName+"'";
prepareStatement = conn.prepareStatement(sql);
resultSet = prepareStatement.executeQuery(sql);
while(resultSet.next()) {
String columnComment = resultSet.getString(1);
String columnName = resultSet.getString(2);
String dataType = resultSet.getString(3);
String isNullable = resultSet.getString(4);
int length = resultSet.getInt(5);
String primaryKey = resultSet.getString(6);
Map<String,Object> column = new HashMap<String,Object>();
column.put("columnComment", columnComment);
column.put("propertyName", StringUtil.tableColumnToClassProperty(columnName.toLowerCase()));
column.put("dataType", dataType);
column.put("isNullable", isNullable.toLowerCase().equals("yes") ? "true" : "false");
column.put("length", length);
column.put("primaryKey", primaryKey);
column.put("javaType", typeAliases.get(dataType) != null ? typeAliases.get(dataType).getSimpleName() : "String");
column.put("columnName", columnName.toLowerCase());
columns.add(column);
}
} catch (SQLException e) {
e.printStackTrace();
}
close(conn,prepareStatement,resultSet);
return columns;
}
/**
* 获取连接的数据库的名称
* @param url
* @return
*/
public String getDatabaseName() {
int index1 = PropertyUtil.JDBC_URL.lastIndexOf("/");
int index2 = PropertyUtil.JDBC_URL.lastIndexOf("?");
if(index2 > -1) {
//http://127.0.0.1:8080/xxx?
return PropertyUtil.JDBC_URL.substring(index1+1,index2);
}else {
//http://127.0.0.1:8080/xxx
return PropertyUtil.JDBC_URL.substring(index1+1);
}
}
}
|
package com.bowlong.sql;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicInt {
/*
* 【以get开头】的函数 是先取值,再改变 ;【以get结尾】的函数 是先改变,再取值
*/
private AtomicInteger count = null;
public AtomicInt() {
count = new AtomicInteger();
}
public AtomicInt(int curval) {
count = new AtomicInteger(curval);
}
// method 方法
// 如果当前值 == 预期值,则以原子方式将该值设置为给定的更新值。
public boolean compareAndSet(int expect, int update) {
return count.compareAndSet(expect, update);
}
// 如果当前值 == 预期值,则以原子方式将该值设置为给定的更新值。
public boolean weakCompareAndSet(int expect, int update) {
return count.weakCompareAndSet(expect, update);
}
// 以 double 形式返回指定的数值。
public double doubleValue() {
return count.doubleValue();
}
// 以 float 形式返回指定的数值。
public float floatValue() {
return count.floatValue();
}
// 以 int 形式返回指定的数值。
public int intValue() {
return count.intValue();
}
// 获取当前值
public int get() {
return count.get();
}
// 设置当前值
public void set(int newValue) {
count.set(newValue);
}
// 以原子方式将给定值与当前值相加。
public int getAndAdd(int delta) {
return count.getAndAdd(delta);
}
// 以原子方式将给定值与当前值相加
public int addAndGet(int delta) {
return count.addAndGet(delta);
}
// 以原子方式将当前值减 1。
public int getAndDecrement() {
return count.getAndDecrement();
}
// 以原子方式将当前值减 1。
public int decrementAndGet() {
return count.decrementAndGet();
}
// 以原子方式将当前值加 1。
public int getAndIncrement() {
return count.getAndIncrement();
}
// 以原子方式将当前值加 1。
public int incrementAndGet() {
return count.incrementAndGet();
}
// 以原子方式设置为给定值,并返回旧值。
public int getAndSet(int newValue) {
return count.getAndSet(newValue);
}
}
|
package com.shoplite.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.shoplite.model.Usuario;
import com.shoplite.repository.IUsuario;
@Service
public class UsuarioService {
@Autowired
private IUsuario repoUser;
public Usuario crearUsuarios( Usuario user) {
return repoUser.save(user);
}
public List<Usuario> listUsers() {
return repoUser.findAll();
}
public Usuario veficarUser(String user, String pass) {
return repoUser.usuarioByUseryPass(user, pass);
}
}
|
package pl.coderslab.charity.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import pl.coderslab.charity.entity.Category;
import pl.coderslab.charity.entity.Donation;
import pl.coderslab.charity.entity.Institution;
import pl.coderslab.charity.service.CharityUserService;
import pl.coderslab.charity.service.DonationService;
import javax.validation.Valid;
@Controller
@RequestMapping("/donations")
@RequiredArgsConstructor
public class DonationController {
private final DonationService donationService;
private final CharityUserService charityUserService;
@ModelAttribute
public void getLoggedUserName(Authentication authentication, Model model) {
if (authentication == null) return;
String userFirstName = charityUserService.getUserFirstName(authentication);
if (userFirstName != null) {
model.addAttribute("userFirstName", userFirstName);
}
}
@GetMapping("/form")
public String form(Model model) {
Iterable<Institution> allInstitutions = donationService.findAllActiveInstitutions();
model.addAttribute("institutions", allInstitutions);
Iterable<Category> allCategories = donationService.findAllCategories();
model.addAttribute("categories", allCategories);
model.addAttribute("donation", new Donation());
return "/donation/form";
}
@PostMapping("/form")
public String processForm(@Valid Donation donation, BindingResult bindingResult, Authentication authentication, Model model) {
if (!bindingResult.hasErrors()) {
donationService.saveDonation(authentication, donation);
} else {
String errorMsg = donationService.prepareErrorMsg(bindingResult.getFieldErrors());
model.addAttribute("errorMsg", errorMsg);
}
return "/donation/form-confirmation";
}
}
|
package com.fight.job.executor.handler;
import com.fight.job.core.biz.model.ReturnT;
import com.fight.job.core.handler.IJobHandler;
import com.fight.job.core.handler.annotation.JobHandler;
import org.springframework.stereotype.Component;
import java.util.Collections;
/**
* DemoJobHandler.
*/
@Component
@JobHandler(value = "demoJobHandler")
public class DemoJobHandler implements IJobHandler {
@Override
public ReturnT<String> execute(String... params) throws Exception {
System.out.println("Hello world, fight-job!");
if ((params != null) && params.length > 0) {
for (String param : params) {
System.out.println(param);
}
}
return ReturnT.SUCCESS;
}
}
|
package com.puti.pachong.entity.pachong;
import lombok.Data;
@Data
public class CaijiConfig {
// 导出目录
private String exportDir;
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 hybris AG
* All rights reserved.
*
* This software is the confidential and proprietary information of hybris
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with hybris.
*
*
*/
package com.cnk.travelogix.b2c.storefront.controllers.misc;
import de.hybris.platform.acceleratorstorefrontcommons.controllers.AbstractController;
import de.hybris.platform.acceleratorstorefrontcommons.forms.AddToCartOrderForm;
import de.hybris.platform.commercefacades.order.converters.populator.GroupCartModificationListPopulator;
import de.hybris.platform.commercefacades.order.data.CartData;
import de.hybris.platform.commercefacades.order.data.CartModificationData;
import de.hybris.platform.commercefacades.order.data.CnkCartEntryModificationData;
import de.hybris.platform.commercefacades.order.data.OrderEntryData;
import de.hybris.platform.commercefacades.product.ProductFacade;
import de.hybris.platform.commerceservices.order.CommerceCartModificationException;
import de.hybris.platform.util.Config;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jgroups.util.UUID;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cnk.travelogix.b2c.facades.order.B2cCartFacade;
import com.cnk.travelogix.b2c.storefront.controllers.ControllerConstants;
import com.cnk.travelogix.b2c.storefront.forms.AddFlightToCartForm;
import com.cnk.travelogix.b2c.storefront.forms.AddHotelToCartForm;
import com.cnk.travelogix.b2c.storefront.forms.FlightLine;
import com.cnk.travelogix.b2c.storefront.forms.FlightLineDetail;
import com.cnk.travelogix.common.core.cart.data.AirlineIATAData;
import com.cnk.travelogix.common.core.cart.data.CommonFlightDetailInfoData;
import com.cnk.travelogix.common.core.cart.data.CommonFlightInfoData;
import com.cnk.travelogix.common.core.cart.data.OrderFlightDetailInfoData;
import com.cnk.travelogix.common.core.cart.data.OrderRoomDetailInfoData;
import com.cnk.travelogix.common.core.cart.data.OrderTicketInfoData;
import com.cnk.travelogix.common.core.cart.data.PriceInfoData;
import com.cnk.travelogix.common.core.enums.CnkRoomType;
import com.cnk.travelogix.common.core.enums.PassengerType;
import com.cnk.travelogix.common.facades.product.CnkProductSearchFacade;
import com.cnk.travelogix.common.facades.product.data.flight.FlightData;
import com.cnk.travelogix.common.facades.product.data.flight.FlightDetailData;
/**
* Controller for Add to Cart functionality which is not specific to a certain page.
*/
@Controller
@Scope("tenant")
public class AddToCartController extends AbstractController
{
private static final String QUANTITY_ATTR = "quantity";
private static final String TYPE_MISMATCH_ERROR_CODE = "typeMismatch";
private static final String ERROR_MSG_TYPE = "errorMsg";
private static final String QUANTITY_INVALID_BINDING_MESSAGE_KEY = "basket.error.quantity.invalid.binding";
private static final String SHOWN_PRODUCT_COUNT = "b2cstorefront.storefront.minicart.shownProductCount";
private static final String MINICART_PROD_COUNT = "minicartProdCount";
private static final Logger LOG = Logger.getLogger(AddToCartController.class);
@Resource(name = "b2cCartFacade")
private B2cCartFacade b2cCartFacade;
@Resource(name = "accProductFacade")
private ProductFacade productFacade;
@Resource(name = "groupCartModificationListPopulator")
private GroupCartModificationListPopulator groupCartModificationListPopulator;
@Resource(name = "flightSearchFacade")
CnkProductSearchFacade CnkProductSearchFacade;
@RequestMapping(value = "/cart/add/hotel", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public Map addToCart(final Model model, @Valid final AddHotelToCartForm form, final BindingResult bindingErrors,
final HttpSession session) throws ParseException
{
final Map map = new HashMap();
if (bindingErrors.hasErrors())
{
map.put("status", "addtocart-failed");
map.put("errors", bindingErrors);
// return getViewWithBindingErrorMessages(model, bindingErrors);
return map;
}
//validateForm(form);
final String qtyString = form.getNumberOfRoom();
final long qty = Long.parseLong(qtyString);
if (StringUtils.isEmpty(qtyString) || qty <= 0)
{
model.addAttribute(ERROR_MSG_TYPE, "basket.error.quantity.invalid");
model.addAttribute(QUANTITY_ATTR, Long.valueOf(0L));
}
else
{
try
{
//For edit mode, first remove, then add new entries.
final String originalGrpId = form.getOriginalGroupId();
if (originalGrpId != null && StringUtils.isNotEmpty(originalGrpId))
{
b2cCartFacade.removeHotel(originalGrpId);
}
final OrderRoomDetailInfoData room = populateRoomDataFromForm(form);
final CartModificationData cartModification = b2cCartFacade.addHotelToCart(room, qty);
model.addAttribute(QUANTITY_ATTR, Long.valueOf(cartModification.getQuantityAdded()));
model.addAttribute("cartCode", cartModification.getCartCode());
final List<CnkCartEntryModificationData> entries = cartModification.getEntries();
model.addAttribute("entries", entries);
if (cartModification.getQuantityAdded() == 0L)
{
model.addAttribute(ERROR_MSG_TYPE, "basket.information.quantity.noItemsAdded." + cartModification.getStatusCode());
}
else if (cartModification.getQuantityAdded() < qty)
{
model.addAttribute(ERROR_MSG_TYPE,
"basket.information.quantity.reducedNumberOfItemsAdded." + cartModification.getStatusCode());
}
}
catch (final CommerceCartModificationException ex)
{
logDebugException(ex);
model.addAttribute(ERROR_MSG_TYPE, "basket.error.occurred");
model.addAttribute(QUANTITY_ATTR, Long.valueOf(0L));
}
}
// model.addAttribute("product", productFacade.getProductForCodeAndOptions(form.getHotelId(), Arrays.asList(ProductOption.BASIC)));
// model.addAttribute("entries", b2cCartFacade.getSessionCart().getEntries());
final CartData cart = b2cCartFacade.getSessionCart();
model.addAttribute("cart", cart);
//return "redirect:/cart";
//return ControllerConstants.Views.Fragments.Cart.MiniCartFragment;
session.setAttribute(MINICART_PROD_COUNT, cart.getTotalUnitCount());
map.put("totalCount", cart.getTotalUnitCount());
map.put("status", "addtocart-success");
return map;
}
@RequestMapping(value = "/cart/add/flight", method = RequestMethod.POST)
@ResponseBody
public Map addFlightToCart(final Model model,
@Valid @ModelAttribute("addFlightToCartForm") final AddFlightToCartForm addFlightToCartForm,
final BindingResult bindingErrors, final HttpSession session) throws ParseException
{
final Map map = new HashMap();
if (bindingErrors.hasErrors())
{
map.put("status", "addtocart-failed");
map.put("errors", bindingErrors);
return map;
}
int qty = 0;
if (addFlightToCartForm.isBooking())
{
qty = addFlightToCartForm.getFlights().size();
}
else
{
qty = addFlightToCartForm.getFlightIds().size();
}
if (qty == 0)
{
model.addAttribute(ERROR_MSG_TYPE, "basket.error.quantity.invalid");
model.addAttribute(QUANTITY_ATTR, Long.valueOf(0L));
}
else
{
try
{
//For edit mode, first remove, then add new entries.
final String originalGrpId = addFlightToCartForm.getOriginalGroupId();
if (originalGrpId != null && StringUtils.isNotEmpty(originalGrpId))
{
b2cCartFacade.removeEntriesByGroupId(originalGrpId);
}
final List<OrderFlightDetailInfoData> OrderFlightDetailInfoDatas = this
.populateOrderFlightDataFromForm(addFlightToCartForm);
final List<CartModificationData> cartModificationDataList = b2cCartFacade.addFlightsToCart(
OrderFlightDetailInfoDatas, model);
model.addAttribute("cartModificationDataList", cartModificationDataList);
}
catch (final CommerceCartModificationException ex)
{
logDebugException(ex);
model.addAttribute(ERROR_MSG_TYPE, "basket.error.occurred");
model.addAttribute(QUANTITY_ATTR, Long.valueOf(0L));
}
}
final CartData cart = b2cCartFacade.getSessionCart();
model.addAttribute("cart", cart);
session.setAttribute(MINICART_PROD_COUNT, cart.getTotalUnitCount());
map.put("totalCount", cart.getTotalUnitCount());
map.put("status", "addtocart-success");
return map;
}
@RequestMapping(value = "/cart/book/flight", method = RequestMethod.POST)
public String bookFlight(final Model model,
@Valid @ModelAttribute("addFlightToCartForm") final AddFlightToCartForm addFlightToCartForm,
final BindingResult bindingErrors) throws ParseException
{
if (bindingErrors.hasErrors())
{
return getViewWithBindingErrorMessages(model, bindingErrors);
}
//validateForm(form);
int qty = 0;
if (addFlightToCartForm.isBooking())
{
qty = addFlightToCartForm.getFlights().size();
}
else
{
qty = addFlightToCartForm.getFlightIds().size();
}
if (qty == 0)
{
model.addAttribute(ERROR_MSG_TYPE, "basket.error.quantity.invalid");
model.addAttribute(QUANTITY_ATTR, Long.valueOf(0L));
}
else
{
try
{
//For edit mode, first remove, then add new entries.
final String originalGrpId = addFlightToCartForm.getOriginalGroupId();
if (originalGrpId != null && StringUtils.isNotEmpty(originalGrpId))
{
b2cCartFacade.removeEntriesByGroupId(originalGrpId);
}
final List<OrderFlightDetailInfoData> OrderFlightDetailInfoDatas = this
.populateOrderFlightDataFromForm(addFlightToCartForm);
final List<CartModificationData> cartModificationDataList = b2cCartFacade.addFlightsToCart(
OrderFlightDetailInfoDatas, model);
model.addAttribute("cartModificationDataList", cartModificationDataList);
}
catch (final CommerceCartModificationException ex)
{
logDebugException(ex);
model.addAttribute(ERROR_MSG_TYPE, "basket.error.occurred");
model.addAttribute(QUANTITY_ATTR, Long.valueOf(0L));
}
}
model.addAttribute("cart", b2cCartFacade.getSessionCart());
return "redirect:/cart";
}
private OrderRoomDetailInfoData populateRoomDataFromForm(final AddHotelToCartForm form) throws ParseException
{
final OrderRoomDetailInfoData room = new OrderRoomDetailInfoData();
room.setHotelId(form.getHotelId());
room.setRoomId(form.getRoomId());
room.setRoomType(CnkRoomType.valueOf(form.getRoomType()));
room.setNumberOfAdult(form.getNumberOfAdult());
room.setNumberOfChild(form.getNumberOfChild());
room.setGroupId(form.getGroupId());
room.setRoomCheckinDate(form.getCheckInDate());
room.setRoomCheckoutDate(form.getCheckOutDate());
room.setNumberOfNight(form.getNumberOfNight());
return room;
}
/**
* Populate Order Flight Data From Form.
*
* @param form
* @return List<OrderFlightDetailInfoData>
* @throws ParseException
*/
private List<OrderFlightDetailInfoData> populateOrderFlightDataFromForm(final AddFlightToCartForm form) throws ParseException
{
List<FlightLine> flights = new ArrayList<FlightLine>();
if (form.isBooking())
{
if (CollectionUtils.isNotEmpty(form.getFlights()))
{
flights = form.getFlights();
}
}
else
{
if (CollectionUtils.isNotEmpty(form.getFlightIds()))
{
int index = 0;
for (final String flightProductId : form.getFlightIds())
{
final FlightData singleFlight = (FlightData) CnkProductSearchFacade.searchProductDetail(flightProductId);
flights.add(this.ConvertFlightDataToForm(singleFlight, form.getSelectedFareTypes().get(index)));
index++;
}
}
}
final List<OrderFlightDetailInfoData> orderFlightDetailInfos = new ArrayList<OrderFlightDetailInfoData>();
final String groupId = UUID.randomUUID().toString();
final int numberOfAdult = form.getNumberOfAdult();
final int numberOfChild = form.getNumberOfChild();
final int numberOfInfant = form.getNumberOfInfant();
String journeyType = form.getJourneyType();
if (journeyType.equals("oneway"))
{
journeyType = "ONE_WAY";
}
else if (journeyType.equals("twoway"))
{
journeyType = "RETURN";
}
else
{
journeyType = "MULTI_CITY";
}
int i = 1;
for (final FlightLine flightLine : flights)
{
if (flightLine != null)
{
final OrderFlightDetailInfoData orderFlightDetailInfoData = new OrderFlightDetailInfoData();
orderFlightDetailInfoData.setJourneyType(journeyType);
orderFlightDetailInfoData.setGroupId(groupId);
orderFlightDetailInfoData.setSequence(String.valueOf(i));
orderFlightDetailInfoData.setCommonFlightInfoData(copyFormCommonData(flightLine));
final List<OrderTicketInfoData> OrderTicketInfoDatas = this.generateOrderTicketData(flightLine, numberOfAdult,
numberOfChild, numberOfInfant, orderFlightDetailInfoData);
orderFlightDetailInfoData.setOrderTicketList(OrderTicketInfoDatas);
orderFlightDetailInfos.add(orderFlightDetailInfoData);
i++;
}
}
return orderFlightDetailInfos;
}
/**
* Convert Flight Data To Form.
*
* @param flightData
* @return FlightLine;
*/
private FlightLine ConvertFlightDataToForm(final FlightData flightData, final String fareType)
{
final FlightLine flightLine = new FlightLine();
final AirlineIATAData airlineIATAData = new AirlineIATAData();
if (flightData.getAirlineIATA() != null)
{
airlineIATAData.setAccountingCode(flightData.getAirlineIATA().getAccountingCode());
airlineIATAData.setAirlineName(flightData.getAirlineIATA().getAirlineName());
airlineIATAData.setAirlinePrefix(flightData.getAirlineIATA().getAirlinePrefix());
}
flightLine.setAirlineIATA(airlineIATAData);
flightLine.setArrivalTime(flightData.getArrivalTime());
flightLine.setCabinClass(flightData.getCabinClass());
flightLine.setDepartureTime(flightData.getDepartureTime());
flightLine.setDuration(flightData.getDuration());
flightLine.setFlightNumber(flightData.getFlightNumber());
flightLine.setFromCity(flightData.getFromSection() != null ? flightData.getFromSection().getCity() : StringUtils.EMPTY);
flightLine.setFromTerminal(flightData.getFromSection() != null ? flightData.getFromSection().getTerminal()
: StringUtils.EMPTY);
flightLine.setNumberOfStops(flightData.getNumberOfStops());
final PriceInfoData priceInfoData = new PriceInfoData();
if (!CollectionUtils.isEmpty(flightData.getFareSummary()))
{
priceInfoData
.setCostPrice(Double.parseDouble(flightData.getFareSummary().get(Integer.parseInt(fareType)).getWebPrice()));
}
flightLine.setPriceInfoData(priceInfoData);
flightLine.setToCity(flightData.getToSection() != null ? flightData.getToSection().getCity() : StringUtils.EMPTY);
flightLine.setToTerminal(flightData.getToSection() != null ? flightData.getToSection().getTerminal() : StringUtils.EMPTY);
final List<FlightLineDetail> flightLineDetails = new ArrayList<FlightLineDetail>();
if (CollectionUtils.isNotEmpty(flightData.getFlightDetails()))
{
for (final FlightDetailData flightDetailData : flightData.getFlightDetails())
{
final FlightLineDetail flightLineDetail = new FlightLineDetail();
flightLineDetail.setArrivalTime(flightDetailData.getArrivalTime());
flightLineDetail.setCabinClass(flightDetailData.getCabinClass());
flightLineDetail.setDepartureTime(flightDetailData.getDepartureTime());
flightLineDetail.setDuration(flightDetailData.getDuration());
flightLineDetail.setFlightNumber(flightDetailData.getFlightNumber());
flightLineDetail.setFromCity(flightDetailData.getFromSection() != null ? flightDetailData.getFromSection().getCity()
: StringUtils.EMPTY);
flightLineDetail.setFromTerminal(flightDetailData.getFromSection() != null ? flightDetailData.getFromSection()
.getTerminal() : StringUtils.EMPTY);
flightLineDetail.setToCity(flightDetailData.getToSection() != null ? flightDetailData.getToSection().getCity()
: StringUtils.EMPTY);
flightLineDetail.setToTerminal(flightDetailData.getToSection() != null ? flightDetailData.getToSection()
.getTerminal() : StringUtils.EMPTY);
flightLineDetails.add(flightLineDetail);
}
}
flightLine.getFlightDetails().addAll(flightLineDetails);
return flightLine;
}
/**
* Copy form data to common flight info.
*
* @param flightLine
* @return CommonFlightInfoData
*/
private CommonFlightInfoData copyFormCommonData(final FlightLine flightLine)
{
final CommonFlightInfoData commonFlightInfoData = new CommonFlightInfoData();
commonFlightInfoData.setAirlineIATAData(flightLine.getAirlineIATA());
commonFlightInfoData.setArrivalTime(flightLine.getArrivalTime());
commonFlightInfoData.setCabinClass(flightLine.getCabinClass());
commonFlightInfoData.setDepartureTime(flightLine.getDepartureTime());
commonFlightInfoData.setDuration(flightLine.getDuration());
commonFlightInfoData.setFlightNumber(flightLine.getFlightNumber());
commonFlightInfoData.setFromCity(flightLine.getFromCity());
commonFlightInfoData.setFromTerminal(flightLine.getFromTerminal());
commonFlightInfoData.setNumberOfStops(flightLine.getNumberOfStops());
commonFlightInfoData.setPriceInfo(flightLine.getPriceInfoData());
commonFlightInfoData.setToCity(flightLine.getToCity());
commonFlightInfoData.setToTerminal(flightLine.getToTerminal());
final List<CommonFlightDetailInfoData> commonFlightDetailInfoDatas = new ArrayList<CommonFlightDetailInfoData>();
if (CollectionUtils.isNotEmpty(flightLine.getFlightDetails()))
{
for (final FlightLineDetail FlightLineDetail : flightLine.getFlightDetails())
{
final CommonFlightDetailInfoData commonFlightDetailInfoData = new CommonFlightDetailInfoData();
commonFlightDetailInfoData.setArrivalTime(FlightLineDetail.getArrivalTime());
commonFlightDetailInfoData.setCabinClass(FlightLineDetail.getCabinClass());
commonFlightDetailInfoData.setDepartureTime(FlightLineDetail.getDepartureTime());
commonFlightDetailInfoData.setDuration(FlightLineDetail.getDuration());
commonFlightDetailInfoData.setFlightNumber(FlightLineDetail.getFlightNumber());
commonFlightDetailInfoData.setFromCity(FlightLineDetail.getFromCity());
commonFlightDetailInfoData.setFromTerminal(FlightLineDetail.getFromTerminal());
commonFlightDetailInfoData.setToCity(FlightLineDetail.getToCity());
commonFlightDetailInfoData.setToTerminal(FlightLineDetail.getToTerminal());
commonFlightDetailInfoDatas.add(commonFlightDetailInfoData);
}
}
commonFlightInfoData.setCommonFlightDetailList(commonFlightDetailInfoDatas);
return commonFlightInfoData;
}
/**
* Generate Order Ticket Data.
*
* @param flightLine
* @param numberOfAdult
* @param numberOfChild
* @param numberOfInfant
* @return List<OrderTicketInfoData>
*/
private List<OrderTicketInfoData> generateOrderTicketData(final FlightLine flightLine, final int numberOfAdult,
final int numberOfChild, final int numberOfInfant, final OrderFlightDetailInfoData orderFlightDetailInfoData)
{
final List<OrderTicketInfoData> OrderTicketInfoDatas = new ArrayList<OrderTicketInfoData>();
int i = 0;
int j = 0;
int k = 0;
while (i < numberOfAdult)
{
final OrderTicketInfoData orderTicketInfoData = new OrderTicketInfoData();
orderTicketInfoData.setCommonFlightInfoData(this.copyFormCommonData(flightLine));
orderTicketInfoData.setPassengerType(PassengerType.ADULT);
orderTicketInfoData.setOrderFlightDetailInfoData(orderFlightDetailInfoData);
final PriceInfoData priceInfoData = new PriceInfoData();
priceInfoData.setCostPrice(flightLine.getPriceInfoData().getCostPrice());
orderTicketInfoData.setPriceInfo(priceInfoData);
OrderTicketInfoDatas.add(orderTicketInfoData);
i++;
}
while (j < numberOfChild)
{
final OrderTicketInfoData orderTicketInfoData = new OrderTicketInfoData();
orderTicketInfoData.setCommonFlightInfoData(this.copyFormCommonData(flightLine));
orderTicketInfoData.setPassengerType(PassengerType.CHILD);
orderTicketInfoData.setOrderFlightDetailInfoData(orderFlightDetailInfoData);
final PriceInfoData priceInfoData = new PriceInfoData();
priceInfoData.setCostPrice(flightLine.getPriceInfoData().getCostPrice());
orderTicketInfoData.setPriceInfo(priceInfoData);
OrderTicketInfoDatas.add(orderTicketInfoData);
j++;
}
while (k < numberOfInfant)
{
final OrderTicketInfoData orderTicketInfoData = new OrderTicketInfoData();
orderTicketInfoData.setCommonFlightInfoData(this.copyFormCommonData(flightLine));
orderTicketInfoData.setPassengerType(PassengerType.INFANT);
orderTicketInfoData.setOrderFlightDetailInfoData(orderFlightDetailInfoData);
final PriceInfoData priceInfoData = new PriceInfoData();
priceInfoData.setCostPrice(flightLine.getPriceInfoData().getCostPrice());
orderTicketInfoData.setPriceInfo(priceInfoData);
OrderTicketInfoDatas.add(orderTicketInfoData);
k++;
}
return OrderTicketInfoDatas;
}
protected String getViewWithBindingErrorMessages(final Model model, final BindingResult bindingErrors)
{
for (final ObjectError error : bindingErrors.getAllErrors())
{
if (isTypeMismatchError(error))
{
model.addAttribute(ERROR_MSG_TYPE, QUANTITY_INVALID_BINDING_MESSAGE_KEY);
}
else
{
model.addAttribute(ERROR_MSG_TYPE, error.getDefaultMessage());
}
}
return ControllerConstants.Views.Fragments.Cart.AddToCartPopup;
}
protected boolean isTypeMismatchError(final ObjectError error)
{
return error.getCode().equals(TYPE_MISMATCH_ERROR_CODE);
}
@RequestMapping(value = "/cart/addGrid", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public final String addGridToCart(@RequestBody final AddToCartOrderForm form, final Model model)
{
final Set<String> multidErrorMsgs = new HashSet<String>();
final List<CartModificationData> modificationDataList = new ArrayList<CartModificationData>();
for (final OrderEntryData cartEntry : form.getCartEntries())
{
if (!isValidProductEntry(cartEntry))
{
LOG.error("Error processing entry");
}
else if (!isValidQuantity(cartEntry))
{
multidErrorMsgs.add("basket.error.quantity.invalid");
}
else
{
addEntryToCart(multidErrorMsgs, modificationDataList, cartEntry);
}
}
if (CollectionUtils.isNotEmpty(modificationDataList))
{
groupCartModificationListPopulator.populate(null, modificationDataList);
model.addAttribute("modifications", modificationDataList);
}
if (CollectionUtils.isNotEmpty(multidErrorMsgs))
{
model.addAttribute("multidErrorMsgs", multidErrorMsgs);
}
model.addAttribute("numberShowing", Integer.valueOf(Config.getInt(SHOWN_PRODUCT_COUNT, 3)));
return ControllerConstants.Views.Fragments.Cart.AddToCartPopup;
}
protected void logDebugException(final Exception ex)
{
if (LOG.isDebugEnabled())
{
LOG.debug(ex);
}
}
protected void addEntryToCart(final Set<String> multidErrorMsgs, final List<CartModificationData> modificationDataList,
final OrderEntryData cartEntry)
{
try
{
final long qty = cartEntry.getQuantity().longValue();
final CartModificationData cartModificationData = b2cCartFacade.addToCart(cartEntry.getProduct().getCode(), qty);
if (cartModificationData.getQuantityAdded() == 0L)
{
multidErrorMsgs.add("basket.information.quantity.noItemsAdded." + cartModificationData.getStatusCode());
}
else if (cartModificationData.getQuantityAdded() < qty)
{
multidErrorMsgs.add("basket.information.quantity.reducedNumberOfItemsAdded." + cartModificationData.getStatusCode());
}
modificationDataList.add(cartModificationData);
}
catch (final CommerceCartModificationException ex)
{
multidErrorMsgs.add("basket.error.occurred");
logDebugException(ex);
}
}
protected boolean isValidProductEntry(final OrderEntryData cartEntry)
{
return cartEntry.getProduct() != null && StringUtils.isNotBlank(cartEntry.getProduct().getCode());
}
protected boolean isValidQuantity(final OrderEntryData cartEntry)
{
return cartEntry.getQuantity() != null && cartEntry.getQuantity().longValue() >= 1L;
}
}
|
import javax.swing.*;
public class FormThreeFields {
private JPanel PanelThreeFields;
private JTextField firstNameField;
private JTextField surNameField;
private JTextField midNameField;
private JButton collapseButton;
private FormOneFields formOneFields;
private JFrame frame;
public FormThreeFields() {
}
public FormThreeFields(FormOneFields formOneFields, JFrame frame) {
this.formOneFields = formOneFields;
this.frame = frame;
collapseButton.addActionListener(e -> btnPressed(formOneFields));
}
public void setFormOneFields(FormOneFields formOneFields) {
this.formOneFields = formOneFields;
}
public JPanel getPanelThreeFields() {
return PanelThreeFields;
}
public JTextField getFirstNameField() {
return firstNameField;
}
public JTextField getSurNameField() {
return surNameField;
}
public JTextField getMidNameField() {
return midNameField;
}
public JButton getCollapseButton() {
return collapseButton;
}
public void viewFormOneFields() {
frame.setContentPane(formOneFields.getPanelFormFiled());
frame.setSize(formOneFields.getPanelFormFiled().getMinimumSize());
frame.repaint();
}
private void btnPressed(FormOneFields formOneFields) {
if (!firstNameField.getText().isEmpty() && !surNameField.getText().isEmpty() &&
(firstNameField.getText() + surNameField.getText() + midNameField.getText()).matches("^[\\p{L}\\p{Blank}.’\\-]+")) {
formOneFields.getFullNameField().setText(joinText());
viewFormOneFields();
} else {
JOptionPane.showMessageDialog(
PanelThreeFields,
"Заполните поля",
"Некорректный ввод, только буквы и - ",
JOptionPane.WARNING_MESSAGE
);
}
}
private String joinText() {
String first = firstNameField.getText();
String sur = surNameField.getText();
String mid = midNameField.getText();
return sur + " " + first + (mid.isEmpty() ? "" : (" " + mid));
}
}
|
package com.tencent.mm.plugin.mall.ui;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.wallet_core.model.w;
import com.tencent.mm.plugin.wallet_core.model.w.a;
import com.tencent.mm.plugin.wxpay.a.i;
import com.tencent.mm.ui.base.l;
import com.tencent.mm.ui.base.n.c;
class MallIndexUI$13 implements c {
final /* synthetic */ MallIndexUI lab;
final /* synthetic */ w lac;
MallIndexUI$13(MallIndexUI mallIndexUI, w wVar) {
this.lab = mallIndexUI;
this.lac = wVar;
}
public final void a(l lVar) {
lVar.add(0, 0, 0, this.lab.getString(i.mall_index_ui_my_msg));
lVar.add(0, 1, 1, this.lab.getString(i.wallet_index_ui_opt_modify_password));
lVar.add(0, 2, 2, this.lab.getString(i.wallet_index_ui_opt_wallet_secure));
lVar.add(0, 3, 3, this.lab.getString(i.wallet_index_ui_opt_common_questions));
if (MallIndexUI.h(this.lab).cec) {
lVar.add(0, 4, 4, this.lab.getString(i.wallet_index_ui_opt_wallet_switch));
}
int size = this.lac.list.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
lVar.add(0, i + 100, i + 100, ((a) this.lac.list.get(i)).pra);
h.mEJ.h(14409, new Object[]{Integer.valueOf(1), Integer.valueOf(r0.pqX), r0.pqY, r0.prb, r0.pqZ});
}
}
}
}
|
package org.fuserleer.tools;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import org.fuserleer.Context;
import org.fuserleer.crypto.CryptoException;
import org.fuserleer.crypto.ECKeyPair;
import org.fuserleer.crypto.Hash;
import org.fuserleer.crypto.Hash.Mode;
import org.fuserleer.executors.Executable;
import org.fuserleer.executors.Executor;
import org.fuserleer.ledger.atoms.Atom;
import org.fuserleer.ledger.atoms.Particle;
import org.fuserleer.ledger.atoms.UniqueParticle;
import org.fuserleer.logging.Logger;
import org.fuserleer.logging.Logging;
import org.fuserleer.network.messaging.Message;
import org.fuserleer.network.messaging.MessageProcessor;
import org.fuserleer.network.peers.ConnectedPeer;
import org.fuserleer.serialization.DsonOutput;
import org.fuserleer.serialization.DsonOutput.Output;
import org.fuserleer.serialization.SerializerId2;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.primitives.Longs;
public class Spamathon
{
private static final Logger spammerLog = Logging.getLogger("spammer");
private static Spamathon instance;
public static Spamathon getInstance()
{
if (instance == null)
instance = new Spamathon();
return instance;
}
@SerializerId2("spam.initiate.message")
public static class InitiateSpamMessage extends Message
{
@JsonProperty("iterations")
@DsonOutput(Output.ALL)
private int iterations;
@JsonProperty("rate")
@DsonOutput(Output.ALL)
private int rate;
@JsonProperty("uniques")
@DsonOutput(Output.ALL)
private int uniques;
InitiateSpamMessage()
{
super();
}
public InitiateSpamMessage(int iterations, int rate, int uniques)
{
super();
this.iterations = iterations;
this.rate = rate;
this.uniques = uniques;
}
public int getIterations()
{
return this.iterations;
}
public int getRate()
{
return this.rate;
}
public int getUniques()
{
return this.uniques;
}
}
private Executable spammer = null;
public class Spammer extends Executable
{
private final int iterations;
private final int rate;
private final int uniques;
private final CountDownLatch latch;
private volatile int processed = 0;
Spammer(int iterations, int rate, int uniques)
{
super();
this.iterations = iterations;
this.rate = rate;
this.uniques = uniques;
this.latch = new CountDownLatch(iterations);
Spamathon.this.spammer = this;
// GOT IT!
spammerLog.setLevels(Logging.ERROR | Logging.FATAL | Logging.INFO | Logging.WARN | Logging.WARN);
}
@Override
public void execute()
{
long start = System.currentTimeMillis();
List<ECKeyPair> owners = new ArrayList<ECKeyPair>();
try
{
for (int i = 0 ; i < this.iterations / Math.log(this.iterations) ; i++)
owners.add(new ECKeyPair());
}
catch (CryptoException ex)
{
// Should never happen //
throw new RuntimeException(ex);
}
try
{
int i = 0;
int batch = Math.max(1, this.rate);
List<Context> contexts = new ArrayList<Context>(Context.getAll());
while(i < this.iterations)
{
long batchStart = System.currentTimeMillis();
for (int b = 0 ; b < batch & i < this.iterations ; b++)
{
try
{
List<Particle> particles = new ArrayList<Particle>();
for (int u = 0 ; u < this.uniques ; u++)
{
long value = ThreadLocalRandom.current().nextLong();
Hash valueHash = new Hash(Longs.toByteArray(value), Mode.STANDARD);
ECKeyPair owner = owners.get(ThreadLocalRandom.current().nextInt(owners.size()));
UniqueParticle particle = new UniqueParticle(valueHash, owner.getIdentity());
try
{
particle.sign(owner);
}
catch (CryptoException cex)
{
spammerLog.info("Signing of "+particle.toString()+" with owner "+owner.getPublicKey()+" failed", cex);
continue;
}
particles.add(particle);
}
Atom atom = new Atom(particles);
try
{
if (spammerLog.hasLevel(Logging.DEBUG))
spammerLog.debug("Submitting "+(i+1)+"/"+this.iterations+" of spam atoms to ledger "+atom.getHash());
else if (i > 0 && i % 1000 == 0)
spammerLog.info("Submitted "+i+"/"+this.iterations+" of spam atoms to ledger");
// TODO selectable context
Collections.shuffle(contexts);
contexts.get(0).getLedger().submit(atom);
this.processed++;
i++;
}
catch (Throwable t)
{
spammerLog.error(t);
}
}
finally
{
this.latch.countDown();
}
}
try
{
long batchDuration = System.currentTimeMillis() - batchStart;
if (batchDuration < 1000)
Thread.sleep(TimeUnit.SECONDS.toMillis(1) - batchDuration);
}
catch (InterruptedException e)
{
// Do nothing //
}
}
}
finally
{
spammerLog.info("Spammer took "+(System.currentTimeMillis() - start)+"ms to perform "+this.iterations+" events");
}
Spamathon.this.spammer = null;
}
public int getNumIterations()
{
return this.iterations;
}
public int getNumProcessed()
{
return this.processed;
}
public boolean completed(long timeout, TimeUnit unit)
{
try
{
return this.latch.await(timeout, unit);
}
catch (InterruptedException e)
{
// DO NOTHING //
}
return false;
}
}
private Spamathon()
{
Context.get().getNetwork().getMessaging().register(InitiateSpamMessage.class, this.getClass(), new MessageProcessor<InitiateSpamMessage>()
{
@Override
public void process(InitiateSpamMessage message, ConnectedPeer peer)
{
if (Spamathon.this.spammer != null)
throw new IllegalStateException("Already an instance of spammer running");
spam(message.getIterations(), message.getRate(), message.getUniques());
}
});
}
public boolean isSpamming()
{
return this.spammer == null ? false : true;
}
public Spammer spam(int iterations, int rate, int uniques)
{
if (Spamathon.getInstance().isSpamming() == true)
throw new IllegalStateException("Already an instance of spammer running");
Spammer spammer = new Spammer(iterations, rate, uniques);
Executor.getInstance().submit(spammer);
return spammer;
}
}
|
package com.lubarov.daniel.blog;
import com.lubarov.daniel.bdb.SerializingDatabase;
import com.lubarov.daniel.data.option.Option;
import com.lubarov.daniel.data.serialization.StringSerializer;
public final class MiscStorage {
private static final SerializingDatabase<String, String> database = new SerializingDatabase<>(
Config.getDatabaseHome("misc"), StringSerializer.singleton, StringSerializer.singleton);
private MiscStorage() {}
public static Option<String> tryGetAdminPassword() {
return database.get("admin_password");
}
public static void setAdminPassword(String adminPassword) {
database.put("admin_password", adminPassword);
}
}
|
/*
HeroScribe
Copyright (C) 2002-2004 Flavio Chierichetti and Valerio Chierichetti
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 (not
later versions) as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.lightless.heroscribe.export;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.TreeSet;
import java.util.zip.GZIPInputStream;
import org.lightless.heroscribe.list.List;
import org.lightless.heroscribe.quest.QBoard;
import org.lightless.heroscribe.quest.QObject;
import org.lightless.heroscribe.quest.Quest;
public class ExportEPS {
private static int linesPerBlock = 500;
private static int[] appendPS(
String inPath,
PrintWriter out,
boolean printComments,
boolean divideInBlocks)
throws Exception {
BufferedReader in =
new BufferedReader(
new InputStreamReader(
new GZIPInputStream(new FileInputStream(inPath))));
int[] boundingBox = null;
String data = in.readLine();
int lines = 0;
while (data != null) {
if (printComments ||
(data.trim().length() > 0 && data.trim().charAt(0) != '%') ) {
if (divideInBlocks && lines % linesPerBlock == 0) {
if (lines != 0)
out.write(" } exec ");
out.write(" { ");
}
lines++;
out.println(data);
}
if (data.trim().startsWith("%%BoundingBox:")
&& boundingBox == null) {
String[] bit = data.split(" ");
boundingBox = new int[4];
for (int i = 0; i < 4; i++) {
boundingBox[i] = Integer.parseInt(bit[bit.length - 4 + i]);
}
}
data = in.readLine();
}
if (divideInBlocks && lines > 0)
out.write(" } exec ");
in.close();
return boundingBox;
}
public static void write(File file, Quest quest, List objects)
throws Exception {
PrintWriter out =
new PrintWriter(new BufferedWriter(new FileWriter(file)));
TreeSet set = new TreeSet();
Iterator iterator;
float bBoxWidth, bBoxHeight;
bBoxWidth = (quest.getWidth() * (quest.getBoard(0, 0).getWidth() + 2) +
(quest.getWidth() - 1) * objects.getBoard().adjacentBoardsOffset) * 19.2f;
bBoxHeight = (quest.getHeight() * (quest.getBoard(0, 0).getHeight() + 2) +
(quest.getHeight() - 1) * objects.getBoard().adjacentBoardsOffset) * 19.2f;
out.println("%!PS-Adobe-3.0 EPSF-3.0");
out.println("%%LanguageLevel: 2");
out.println("%%BoundingBox: 0 0 "
+ Math.round(Math.ceil(bBoxWidth))
+ " "
+ Math.round(Math.ceil(bBoxHeight)));
out.println("%%HiResBoundingBox: 0 0 " + bBoxWidth + " " + bBoxHeight);
out.println("/adjacentBoardsOffset " +
objects.getBoard().adjacentBoardsOffset + " def");
appendPS(objects.getVectorPath(quest.getRegion()), out, false, false);
out.println(
quest.getWidth() + " " + quest.getHeight() + " BoundingBox");
out.println(
"2 dict dup dup /showpage {} put /setpagedevice {} put begin");
for (int i = 0; i < quest.getWidth(); i++)
for (int j = 0; j < quest.getHeight(); j++) {
iterator = quest.getBoard(i, j).iterator();
while (iterator.hasNext())
set.add(((QObject) iterator.next()).id);
}
iterator = set.iterator();
while (iterator.hasNext()) {
String id = (String) iterator.next();
int[] boundingBox;
out.println("/Icon" + id + " << /FormType 1 /PaintProc { pop");
/* the postscript is divided in "{ } exec" blocks to broaden
* compatibility
*/
boundingBox =
appendPS(
objects.getVectorPath(id, quest.getRegion()),
out,
false,
true);
out.println(
" } bind /Matrix [1 0 0 1 0 0] /BBox ["
+ boundingBox[0]
+ " "
+ boundingBox[1]
+ " "
+ boundingBox[2]
+ " "
+ boundingBox[3]
+ "] >> def");
}
for (int column = 0; column < quest.getWidth(); column++)
for (int row = 0; row < quest.getHeight(); row++) {
QBoard board = quest.getBoard(column, row);
out.println(column + " " +
(quest.getHeight() - row - 1) + " StartBoard");
for (int i = 1; i <= board.getWidth(); i++)
for (int j = 1; j <= board.getHeight(); j++)
if (objects.board.corridors[i][j])
out.println(
i
+ " "
+ (board.getHeight() - j + 1)
+ " 1 1 Corridor");
for (int i = 1; i <= board.getWidth(); i++)
for (int j = 1; j <= board.getHeight(); j++)
if (board.isDark(i, j))
out.println(
i
+ " "
+ (board.getHeight() - j + 1)
+ " 1 1 Dark");
out.println("Grid");
out.println("EndBoard");
}
/* Bridges */
for (int column = 0; column < quest.getWidth(); column++)
for (int row = 0; row < quest.getHeight(); row++) {
QBoard board = quest.getBoard(column, row);
out.println(column + " " +
(quest.getHeight() - row - 1) + " StartBoard");
if ( column < quest.getWidth() - 1 )
for (int top = 1 ; top <= board.getHeight() ; top++ )
if ( quest.getHorizontalBridge(column, row, top) )
out.println((board.getHeight() - top + 1) + " HorizontalBridge");
if ( row < quest.getHeight() - 1 )
for (int left = 1 ; left <= board.getWidth() ; left++ )
if ( quest.getVerticalBridge(column, row, left) )
out.println(left + " VerticalBridge");
out.println("EndBoard");
}
for (int column = 0; column < quest.getWidth(); column++)
for (int row = 0; row < quest.getHeight(); row++) {
QBoard board = quest.getBoard(column, row);
out.println(column + " " +
(quest.getHeight() - row - 1) + " StartBoard");
iterator = board.iterator();
while (iterator.hasNext()) {
QObject obj = (QObject) iterator.next();
int width, height;
float x, y, xoffset, yoffset;
if (obj.rotation % 2 == 0) {
width = objects.getObject(obj.id).width;
height = objects.getObject(obj.id).height;
} else {
width = objects.getObject(obj.id).height;
height = objects.getObject(obj.id).width;
}
x = obj.left + width / 2.0f;
y = obj.top + height / 2.0f;
if (objects.getObject(obj.id).trap) {
out.println(
obj.left
+ " "
+ (board.getHeight() - obj.top - height + 2)
+ " "
+ width
+ " "
+ height
+ " Trap");
} else if (objects.getObject(obj.id).door) {
if (obj.rotation % 2 == 0) {
if (obj.top == 0)
y -= objects.getBoard().borderDoorsOffset;
else if (obj.top == board.getHeight())
y += objects.getBoard().borderDoorsOffset;
} else {
if (obj.left == 0)
x -= objects.getBoard().borderDoorsOffset;
else if (obj.left == board.getWidth())
x += objects.getBoard().borderDoorsOffset;
}
}
xoffset =
objects.getObject(obj.id).getIcon(
quest.getRegion()).xoffset;
yoffset =
objects.getObject(obj.id).getIcon(
quest.getRegion()).yoffset;
switch (obj.rotation) {
case 0 :
x += xoffset;
y += yoffset;
break;
case 1 :
x += yoffset;
y -= xoffset;
break;
case 2 :
x -= xoffset;
y -= yoffset;
break;
case 3 :
x -= yoffset;
y += xoffset;
break;
}
y = objects.getBoard().height - y + 2;
out.println("gsave");
out.println(x + " Unit " + y + " Unit translate");
out.println((obj.rotation * 90) + " rotate");
out.println("Icon" + obj.id + " execform");
out.println("grestore");
out.println();
}
out.println("EndBoard");
}
out.println("end");
out.println("%%EOF");
out.close();
}
}
|
package com.tencent.mm.plugin.wallet.balance.ui.lqt;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.SpannableString;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.tencent.mm.kernel.g;
import com.tencent.mm.platformtools.af;
import com.tencent.mm.platformtools.y;
import com.tencent.mm.plugin.wallet.balance.a.a.i;
import com.tencent.mm.plugin.wallet.balance.a.a.l;
import com.tencent.mm.plugin.wallet.balance.a.a.m;
import com.tencent.mm.plugin.wallet.balance.a.a.n;
import com.tencent.mm.plugin.wallet.balance.a.a.o;
import com.tencent.mm.plugin.wallet.balance.a.a.o.7;
import com.tencent.mm.plugin.wallet.balance.a.a.o.8;
import com.tencent.mm.plugin.wallet.balance.a.a.o.9;
import com.tencent.mm.plugin.wallet.balance.a.a.p;
import com.tencent.mm.plugin.wallet_core.d.b;
import com.tencent.mm.plugin.wallet_core.model.Bankcard;
import com.tencent.mm.plugin.wallet_core.model.Orders;
import com.tencent.mm.plugin.wallet_core.model.Orders.Commodity;
import com.tencent.mm.plugin.wallet_core.model.ab;
import com.tencent.mm.plugin.wallet_core.model.e;
import com.tencent.mm.plugin.wxpay.a.f;
import com.tencent.mm.pluginsdk.wallet.PayInfo;
import com.tencent.mm.protocal.c.arq;
import com.tencent.mm.protocal.c.awx;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.aa.a;
import com.tencent.mm.ui.widget.a.d;
import com.tencent.mm.wallet_core.c;
import com.tencent.mm.wallet_core.ui.formview.WalletFormView;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public class WalletLqtSaveFetchUI extends WalletLqtBasePresenterUI {
private int accountType;
private Dialog eBX;
private HashMap<String, Integer> lMb = new HashMap();
private int mode;
private Bankcard oZH;
private m oZk = ((m) w(m.class));
private n oZl = ((n) t(n.class));
private o pbE = new o(this.oZk, this.oZl, this);
private p pbF = new p(this.pbE);
private ViewGroup pbG;
private WalletFormView pbH;
private TextView pbI;
private TextView pbJ;
private Button pbK;
private ImageView pbL;
private TextView pbM;
private TextView pbN;
private ViewGroup pbO;
private TextView pbP;
private CheckBox pbQ;
private TextView pbR;
private TextView pbS;
private TextView pbT;
private CharSequence pbU;
private Bankcard pbV;
private int pbW;
private String pbX;
private String pbY;
private long pbZ = -1;
private String pca;
private boolean pcb = false;
static /* synthetic */ void a(WalletLqtSaveFetchUI walletLqtSaveFetchUI) {
Bankcard bankcard;
String str;
int i;
int i2;
View inflate;
walletLqtSaveFetchUI.lMb.clear();
d dVar = new d(walletLqtSaveFetchUI, 2, true);
List jc = i.oYM.jc(walletLqtSaveFetchUI.mode == 1);
if (jc == null || jc.size() == 0) {
com.tencent.mm.plugin.wallet.a.p.bNp();
jc = com.tencent.mm.plugin.wallet.a.p.bNq().bPG();
}
List linkedList = new LinkedList();
if (jc != null) {
for (Bankcard bankcard2 : jc) {
if (bankcard2.bOs()) {
com.tencent.mm.plugin.wallet.a.p.bNp();
if (!com.tencent.mm.plugin.wallet.a.p.bNq().bPp()) {
linkedList.add(bankcard2);
}
}
if (walletLqtSaveFetchUI.mode == 1 && (bankcard2.field_support_lqt_turn_in == 1 || bankcard2.bOs())) {
linkedList.add(bankcard2);
}
if (walletLqtSaveFetchUI.mode == 2 && (bankcard2.field_support_lqt_turn_out == 1 || bankcard2.bOs())) {
linkedList.add(bankcard2);
}
}
}
String str2 = walletLqtSaveFetchUI.oZH != null ? walletLqtSaveFetchUI.oZH.field_bindSerial : null;
if (bi.oW(str2)) {
str2 = walletLqtSaveFetchUI.pca;
if (bi.oW(walletLqtSaveFetchUI.pca)) {
g.Ek();
str = (String) g.Ei().DT().get(a.sZv, "");
i = 0;
i2 = 0;
while (i < linkedList.size()) {
bankcard2 = (Bankcard) linkedList.get(i);
int i3 = (bi.oW(bankcard2.field_bindSerial) || !str.equals(bankcard2.field_bindSerial)) ? i2 : i;
i++;
i2 = i3;
}
dVar.ofp = new 13(walletLqtSaveFetchUI, linkedList, dVar);
dVar.ofq = new 14(walletLqtSaveFetchUI, dVar, linkedList);
inflate = View.inflate(walletLqtSaveFetchUI, com.tencent.mm.plugin.wxpay.a.g.lqt_select_bankcard_header, null);
if (walletLqtSaveFetchUI.mode != 1) {
((TextView) inflate.findViewById(f.lqt_select_bankcard_title)).setText(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_save_alert_title);
((TextView) inflate.findViewById(f.lqt_select_bankcard_tip)).setText(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_save_alert_tip);
} else {
((TextView) inflate.findViewById(f.lqt_select_bankcard_title)).setText(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_fetch_alert_title);
((TextView) inflate.findViewById(f.lqt_select_bankcard_tip)).setText(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_fetch_alert_tip);
}
dVar.mqO = true;
dVar.uKk = i2;
dVar.uKi = true;
dVar.dS(inflate);
dVar.bXO();
}
}
str = str2;
i = 0;
i2 = 0;
while (i < linkedList.size()) {
bankcard2 = (Bankcard) linkedList.get(i);
int i32 = (bi.oW(bankcard2.field_bindSerial) || !str.equals(bankcard2.field_bindSerial)) ? i2 : i;
i++;
i2 = i32;
}
dVar.ofp = new 13(walletLqtSaveFetchUI, linkedList, dVar);
dVar.ofq = new 14(walletLqtSaveFetchUI, dVar, linkedList);
inflate = View.inflate(walletLqtSaveFetchUI, com.tencent.mm.plugin.wxpay.a.g.lqt_select_bankcard_header, null);
if (walletLqtSaveFetchUI.mode != 1) {
((TextView) inflate.findViewById(f.lqt_select_bankcard_title)).setText(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_fetch_alert_title);
((TextView) inflate.findViewById(f.lqt_select_bankcard_tip)).setText(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_fetch_alert_tip);
} else {
((TextView) inflate.findViewById(f.lqt_select_bankcard_title)).setText(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_save_alert_title);
((TextView) inflate.findViewById(f.lqt_select_bankcard_tip)).setText(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_save_alert_tip);
}
dVar.mqO = true;
dVar.uKk = i2;
dVar.uKi = true;
dVar.dS(inflate);
dVar.bXO();
}
static /* synthetic */ void i(WalletLqtSaveFetchUI walletLqtSaveFetchUI) {
Bundle bundle = new Bundle();
Parcelable parcelable = (PayInfo) walletLqtSaveFetchUI.sy.get("key_pay_info");
if (parcelable == null) {
parcelable = new PayInfo();
parcelable.bOd = "";
if (walletLqtSaveFetchUI.mode == 1) {
if (walletLqtSaveFetchUI.accountType == 0) {
parcelable.bVY = 45;
} else {
parcelable.bVY = 52;
}
} else if (walletLqtSaveFetchUI.accountType == 0) {
parcelable.bVY = 51;
} else {
parcelable.bVY = 53;
}
}
if (parcelable != null) {
bundle.putParcelable("key_pay_info", parcelable);
}
if (walletLqtSaveFetchUI.mode == 1) {
if (walletLqtSaveFetchUI.accountType == 0) {
bundle.putInt("key_scene", 45);
} else {
bundle.putInt("key_scene", 52);
}
bundle.putInt("key_bind_scene", 16);
} else {
if (walletLqtSaveFetchUI.accountType == 0) {
bundle.putInt("key_scene", 51);
} else {
bundle.putInt("key_scene", 53);
}
bundle.putInt("key_bind_scene", 17);
}
bundle.putBoolean("key_need_bind_response", true);
bundle.putInt("key_bind_scene", 0);
bundle.putBoolean("key_is_bind_bankcard", true);
com.tencent.mm.wallet_core.a.a(walletLqtSaveFetchUI, b.class, bundle, new c.a() {
public final Intent n(int i, Bundle bundle) {
x.i("MicroMsg.WalletLqtSaveFetchUI", "feedbackData: %s", new Object[]{bundle});
return null;
}
});
}
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
x.i("MicroMsg.WalletLqtSaveFetchUI", "WalletLqtSaveFetchUI onCreate");
this.pbH = (WalletFormView) findViewById(f.lqt_save_form);
this.pbK = (Button) findViewById(f.next_btn);
this.pbL = (ImageView) findViewById(f.bankcard_logo_iv);
this.pbM = (TextView) findViewById(f.lqt_save_balance_hint);
this.pbN = (TextView) findViewById(f.lqt_save_balance_hint2);
this.pbI = (TextView) findViewById(f.lqt_save_hint);
this.pbJ = (TextView) findViewById(f.lqt_balance_bankcard);
this.pbT = (TextView) findViewById(f.wallet_title);
this.pbO = (ViewGroup) findViewById(f.lqt_save_protocal_layout);
this.pbP = (TextView) findViewById(f.lqt_save_protocol_link_tv);
this.pbQ = (CheckBox) findViewById(f.lqt_save_protocol_agree_checkbox);
this.pbG = (ViewGroup) findViewById(f.main_content);
this.pbR = (TextView) findViewById(f.hint_1);
this.pbS = (TextView) findViewById(f.hint_2);
this.mode = getIntent().getIntExtra("lqt_save_fetch_mode", 1);
this.pbW = getIntent().getIntExtra("lqt_max_redeem_amount", -1);
this.pbX = getIntent().getStringExtra("lqt_redeem_invalid_amount_hint");
this.pbY = getIntent().getStringExtra("lqt_profile_wording");
this.accountType = getIntent().getIntExtra("lqt_account_type", 0);
if (this.mode == 1) {
g.Ek();
this.pca = (String) g.Ei().DT().get(a.sZw, "");
} else {
g.Ek();
this.pca = (String) g.Ei().DT().get(a.sZx, "");
}
if (bi.oW(this.pca)) {
g.Ek();
this.pca = (String) g.Ei().DT().get(a.sZv, "");
}
x.i("MicroMsg.WalletLqtSaveFetchUI", "onCreate, accountType: %s, mode: %s, mCurrentSerial: %s", new Object[]{Integer.valueOf(this.accountType), Integer.valueOf(this.mode), this.pca});
a(this.pbH, 2, false, false, false);
if (this.mode == 1) {
this.pbI.setText(getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_save_amount_hint));
this.pbK.setText(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_save_wording);
this.pbT.setText(getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_save_hint_bank_card_wording));
} else if (this.mode == 2) {
this.pbI.setText(getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_fetch_amount_hint));
this.pbK.setText(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_fetch_wording);
this.pbT.setText(getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_fetch_hint_bank_card_wording));
}
this.pbH.a(new 6(this));
this.pbK.setOnClickListener(new 7(this));
if (!bi.oW(this.pbY)) {
TextView textView = (TextView) findViewById(f.lqt_profile_wording);
textView.setText(this.pbY);
textView.setVisibility(0);
}
this.pbM.setText("");
this.pbM.setClickable(true);
this.pbM.setOnTouchListener(new com.tencent.mm.pluginsdk.ui.d.m(this));
jg(false);
if (this.mode == 1) {
this.pbG.setVisibility(4);
}
if (this.pbJ.findViewById(f.wallet_tips_msg) != null) {
this.pbJ.findViewById(f.wallet_tips_msg).setVisibility(8);
}
1 1 = new 1(this);
this.pbJ.setOnClickListener(1);
if (findViewById(f.change_bankcard_layout) != null) {
findViewById(f.change_bankcard_layout).setOnClickListener(1);
}
if (this.mode == 1) {
i iVar = i.oYM;
iVar.jf(true);
arq arq = iVar.oYG;
this.pbV = arq != null ? ab.a(arq.rTT) : null;
if (this.pbV == null) {
com.tencent.mm.plugin.wallet.a.p.bNp();
this.pbV = com.tencent.mm.plugin.wallet.a.p.bNq().paw;
}
if (this.pbV != null) {
String string = getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_balance_remain_wording_1, new Object[]{Double.valueOf(this.pbV.plV)});
int length = string.length();
CharSequence spannableString = new SpannableString(string + getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_balance_remain_wording_2));
spannableString.setSpan(new a(new 8(this)), length, spannableString.length(), 18);
this.pbU = spannableString;
this.pbM.setText(spannableString);
}
this.pbG.setVisibility(0);
}
bNb();
}
private void bNb() {
Bankcard bankcard;
int i;
List jc = i.oYM.jc(this.mode == 1);
if (jc == null || jc.size() == 0) {
com.tencent.mm.plugin.wallet.a.p.bNp();
jc = com.tencent.mm.plugin.wallet.a.p.bNq().bPG();
}
List linkedList = new LinkedList();
if (jc != null) {
for (Bankcard bankcard2 : jc) {
if (bankcard2.bOs()) {
com.tencent.mm.plugin.wallet.a.p.bNp();
if (!com.tencent.mm.plugin.wallet.a.p.bNq().bPp()) {
linkedList.add(bankcard2);
}
}
if (this.mode == 1 && bankcard2.field_support_lqt_turn_in == 1) {
linkedList.add(bankcard2);
}
if (this.mode == 2 && bankcard2.field_support_lqt_turn_out == 1) {
linkedList.add(bankcard2);
}
}
}
this.oZH = i.oYM.jb(this.mode == 1);
if (this.oZH == null) {
com.tencent.mm.plugin.wallet.a.p.bNp();
this.oZH = com.tencent.mm.plugin.wallet.a.p.bNq().paw;
}
String str = "MicroMsg.WalletLqtSaveFetchUI";
String str2 = "defaultBankcard: %s, save mCurrentSerial: %s";
Object[] objArr = new Object[2];
objArr[0] = this.oZH != null ? this.oZH.field_bindSerial : "";
objArr[1] = this.pca;
x.i(str, str2, objArr);
if (!bi.oW(this.pca)) {
for (i = 0; i < linkedList.size(); i++) {
bankcard2 = (Bankcard) linkedList.get(i);
if (!bi.oW(bankcard2.field_bindSerial) && this.pca.equals(bankcard2.field_bindSerial)) {
this.oZH = bankcard2;
}
}
}
if (this.oZH.bOs()) {
this.pbJ.setText(this.oZH.field_desc);
} else {
this.pbJ.setText(getString(com.tencent.mm.plugin.wxpay.a.i.wallet_balance_save_bankcard_tips, new Object[]{this.oZH.field_bankName, this.oZH.field_bankcardTail}));
}
this.pbJ.setText(this.oZH.field_desc);
this.pbJ.setVisibility(0);
this.pbL.setTag(this.oZH.field_bindSerial);
if (this.pbL != null) {
String str3 = "";
e h = b.h(this, this.oZH.field_bankcardType, this.oZH.bOr());
if (h != null) {
str3 = h.lCU;
}
this.pbL.setImageBitmap(null);
if (this.oZH.bOs()) {
this.pbL.setBackgroundResource(com.tencent.mm.plugin.wxpay.a.e.wallet_balance_manager_logo_small);
} else {
Bitmap a = y.a(new com.tencent.mm.plugin.wallet_core.ui.view.c(str3));
y.a(new 12(this));
if (!(a == null || a == null)) {
this.pbL.setImageBitmap(com.tencent.mm.sdk.platformtools.c.a(a, getResources().getDimensionPixelOffset(com.tencent.mm.plugin.wxpay.a.d.wallet_offline_bank_logo_width), getResources().getDimensionPixelOffset(com.tencent.mm.plugin.wxpay.a.d.wallet_offline_bank_logo_width), true, false));
}
}
}
this.pbR.setVisibility(8);
this.pbS.setVisibility(8);
if (this.mode == 2) {
if (!this.oZH.bOs() && !bi.oW(this.oZH.field_avail_save_wording)) {
this.pbR.setText(this.oZH.field_avail_save_wording);
this.pbR.setVisibility(0);
} else if (this.oZH.bOs()) {
boolean z;
i iVar = i.oYM;
if (this.mode == 1) {
z = true;
} else {
z = false;
}
if (!bi.oW(iVar.jd(z))) {
TextView textView = this.pbR;
i iVar2 = i.oYM;
if (this.mode == 1) {
z = true;
} else {
z = false;
}
textView.setText(iVar2.jd(z));
this.pbR.setVisibility(0);
}
}
if (!bi.oW(this.oZH.field_fetchArriveTimeWording)) {
this.pbS.setText(this.oZH.field_fetchArriveTimeWording);
this.pbS.setVisibility(0);
}
} else if (!(this.mode != 1 || this.oZH.bOs() || bi.oW(this.oZH.field_avail_save_wording))) {
this.pbR.setText(this.oZH.field_avail_save_wording);
this.pbR.setVisibility(0);
}
String string;
CharSequence spannableString;
if (this.mode == 1) {
setMMTitle(getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_save_wording));
ArrayList stringArrayListExtra = getIntent().getStringArrayListExtra("lqt_protocol_list");
boolean booleanExtra = getIntent().getBooleanExtra("lqt_is_show_protocol", false);
if (stringArrayListExtra == null || stringArrayListExtra.size() <= 0 || !booleanExtra) {
this.pbO.setVisibility(8);
} else {
this.pbO.setVisibility(0);
this.pbQ.setChecked(getIntent().getBooleanExtra("lqt_is_agree_protocol", false));
this.pbO.setOnClickListener(new 3(this));
this.pbQ.setOnCheckedChangeListener(new 4(this));
string = getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_protocol_agree_prefix);
i = string.length();
spannableString = new SpannableString(string + getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_protocol_agree_suffix));
spannableString.setSpan(new a(new 5(this, stringArrayListExtra)), i, spannableString.length(), 17);
this.pbP.setText(spannableString);
this.pbP.setClickable(true);
this.pbP.setOnTouchListener(new com.tencent.mm.pluginsdk.ui.d.m());
}
} else if (this.mode == 2) {
findViewById(f.wallet_info_tip).setVisibility(8);
this.pbO.setVisibility(8);
setMMTitle(getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_fetch_wording_title));
this.pbN.setVisibility(8);
l bMQ = l.bMQ();
int i2;
if (this.oZH == null || !this.oZH.bOs()) {
i2 = bMQ.oZa == null ? 0 : bMQ.oZa.rZW;
if (af.eyi) {
i2 = 100;
}
String string2 = getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_fetch_remain_wording_1_2, new Object[]{Double.valueOf(eY(String.valueOf(i2), "100"))});
int length = string2.length();
CharSequence spannableString2 = new SpannableString(string2 + getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_fetch_remain_wording_2));
spannableString2.setSpan(new a(new 10(this, i2)), length, spannableString2.length(), 18);
this.pbU = spannableString2;
this.pbM.setText(spannableString2);
if (bMQ.oZa != null && (bMQ.oZa.rZX > 0 || af.eyi)) {
i2 = bMQ.oZa.rZX;
this.pbN.setVisibility(0);
this.pbN.setText(getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_fetch_remain_real_wording, new Object[]{Double.valueOf(eY(String.valueOf(i2), "100"))}));
}
awx awx = bMQ.oZa;
if (!(awx == null || awx.rZY == null || awx.rZY.size() <= 0)) {
findViewById(f.wallet_info_tip).setVisibility(0);
findViewById(f.wallet_info_tip).setOnClickListener(new 11(this, awx));
}
} else {
i2 = getIntent().getIntExtra("lqt_balance", 0);
if (af.eyi) {
i2 = 100;
}
if (i2 > 0) {
string = getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_fetch_remain_wording_1, new Object[]{Double.valueOf(eY(String.valueOf(i2), "100"))});
i = string.length();
spannableString = new SpannableString(string + getString(com.tencent.mm.plugin.wxpay.a.i.wallet_lqt_fetch_remain_wording_2));
spannableString.setSpan(new a(new 9(this, i2)), i, spannableString.length(), 18);
this.pbU = spannableString;
this.pbM.setText(spannableString);
}
}
}
if (this.mode == 1) {
if (this.oZH == null || !this.oZH.bOs()) {
this.pbM.setText("");
} else {
this.pbM.setText(this.pbU);
}
}
this.pbH.setText(this.pbH.getText());
}
private List<Bankcard> bNc() {
List jc = i.oYM.jc(this.mode == 1);
if (jc == null || jc.size() == 0) {
com.tencent.mm.plugin.wallet.a.p.bNp();
jc = com.tencent.mm.plugin.wallet.a.p.bNq().bPG();
}
List<Bankcard> linkedList = new LinkedList();
if (jc != null) {
for (Bankcard bankcard : jc) {
if (bankcard.bOs()) {
com.tencent.mm.plugin.wallet.a.p.bNp();
if (!com.tencent.mm.plugin.wallet.a.p.bNq().bPp()) {
linkedList.add(bankcard);
}
}
if (this.mode == 1 && (bankcard.field_support_lqt_turn_in == 1 || bankcard.bOs())) {
linkedList.add(bankcard);
}
if (this.mode == 2 && (bankcard.field_support_lqt_turn_out == 1 || bankcard.bOs())) {
linkedList.add(bankcard);
}
}
}
return linkedList;
}
protected void onNewIntent(Intent intent) {
x.i("MicroMsg.WalletLqtSaveFetchUI", "onNewIntent");
super.onNewIntent(intent);
List bNc = bNc();
if (this.mode == 1) {
this.pbF.oZy.dX(this.mode, this.accountType).f(new 15(this, bNc));
}
}
private void jg(boolean z) {
if (!z) {
this.pbK.setEnabled(false);
} else if (this.pbO.getVisibility() == 0) {
if (this.pbQ.isChecked() && this.pcb) {
this.pbK.setEnabled(true);
} else {
this.pbK.setEnabled(false);
}
} else if (this.pcb) {
this.pbK.setEnabled(true);
}
}
public void onResume() {
super.onResume();
}
protected final int getLayoutId() {
return com.tencent.mm.plugin.wxpay.a.g.wallet_lqt_save_ui;
}
protected void onActivityResult(int i, int i2, Intent intent) {
super.onActivityResult(i, i2, intent);
o oVar = this.pbE;
if (i == o.oZi && i2 == -1) {
Orders orders = (Orders) intent.getParcelableExtra("key_orders");
if (orders != null && orders.ppf != null && orders.ppf.size() > 0) {
x.i("MicroMsg.LqtSaveFetchLogic", "onActivityResult, doQueryPurchaseResult, accountType: %s", new Object[]{Integer.valueOf(oVar.accountType)});
oVar.bOe = ((Commodity) orders.ppf.get(0)).bOe;
x.i("MicroMsg.LqtSaveFetchLogic", "doQueryPurchaseResult");
oVar.oZm.jh(false);
com.tencent.mm.vending.g.g.a(oVar.oZn, oVar.bOe, Integer.valueOf(oVar.oZo), Integer.valueOf(oVar.accountType)).c(oVar.oZl.oZe).f(new 7(oVar)).a(new com.tencent.mm.vending.g.d.a() {
public final void bd(Object obj) {
x.i("MicroMsg.LqtSaveFetchLogic", "doQueryPurchaseResult interrupt: %s", new Object[]{obj});
o.this.oZm.bNd();
if (o.this.eAc != null) {
o.this.eAc.ct(obj);
}
}
});
}
} else if (i == o.oZj && i2 == -1) {
String stringExtra = intent.getStringExtra("lqt_fetch_enc_pwd");
x.i("MicroMsg.LqtSaveFetchLogic", "onActivityResult, doRedeemFund, accountType: %s", new Object[]{Integer.valueOf(oVar.accountType)});
x.i("MicroMsg.LqtSaveFetchLogic", "doRedeemFund");
oVar.oZm.jh(true);
n.c cVar = oVar.oZl.oZf;
int i3 = oVar.oZp;
com.tencent.mm.vending.g.g.a(Integer.valueOf(i3), stringExtra, oVar.oZq, Integer.valueOf(oVar.accountType)).c(cVar).f(new 9(oVar)).a(new 8(oVar));
}
}
public final boolean d(int i, int i2, String str, com.tencent.mm.ab.l lVar) {
o oVar = this.pbE;
x.i("MicroMsg.LqtSaveFetchLogic", "onSceneEnd, errType: %s, errCode: %s, errMsg: %s, scene: %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str, lVar});
if (lVar instanceof com.tencent.mm.plugin.wallet_core.c.y) {
com.tencent.mm.plugin.wallet.a.p.bNp();
oVar.oZr = com.tencent.mm.plugin.wallet.a.p.bNq().paw;
if (oVar.eAc != null) {
oVar.eAc.v(new Object[]{lVar});
oVar.eAc.resume();
}
}
return super.d(i, i2, str, lVar);
}
public final void jh(boolean z) {
if (this.eBX != null && this.eBX.isShowing()) {
return;
}
if (z) {
this.eBX = com.tencent.mm.wallet_core.ui.g.a(this, false, null);
} else {
this.eBX = com.tencent.mm.wallet_core.ui.g.b(this, false, null);
}
}
public final void bNd() {
if (this.eBX != null) {
this.eBX.dismiss();
}
}
public final void bNe() {
boolean z;
int i = 0;
if (this.mode == 1) {
g.Ek();
g.Ei().DT().a(a.sZw, this.pca);
} else {
g.Ek();
g.Ei().DT().a(a.sZx, this.pca);
}
i iVar = i.oYM;
if (this.mode == 1) {
z = true;
} else {
z = false;
}
iVar.jf(z);
arq arq = z ? iVar.oYG : iVar.oYH;
if (arq != null) {
x.i("MicroMsg.LqtBindQueryInfoCache", "isReqAgainAfterDeal: %s", new Object[]{Boolean.valueOf(arq.rTV)});
i = arq.rTV;
}
if (i != 0) {
x.i("MicroMsg.WalletLqtSaveFetchUI", "saveOrfetchDone, req again after deal");
this.pbF.oZy.dX(this.mode, this.accountType);
}
}
public final void Kk(String str) {
Toast.makeText(this, str, 1).show();
}
public void onDestroy() {
super.onDestroy();
this.pbE = null;
this.pbF = null;
}
private static double eY(String str, String str2) {
try {
return new BigDecimal(bi.getDouble(str.trim(), 0.0d) == 0.0d ? "0" : str.trim()).divide(new BigDecimal(str2.trim()), 5, 2).doubleValue();
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.WalletLqtSaveFetchUI", e, "", new Object[0]);
return 0.0d;
}
}
private static int eZ(String str, String str2) {
try {
double d = bi.getDouble(str, 0.0d);
double d2 = bi.getDouble(str2, 0.0d);
if (d == 0.0d) {
str = "0";
}
BigDecimal bigDecimal = new BigDecimal(str);
if (d2 == 0.0d) {
str2 = "0";
}
return bigDecimal.multiply(new BigDecimal(str2)).intValue();
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.WalletLqtSaveFetchUI", e, "", new Object[0]);
return 0;
}
}
}
|
//Source code for Question 4.1 (a)(b)(c)
import java.util.Scanner;
import java.lang.Math;
public class Q4_1_abc{
public static void main(String[] args){
int sumA=0,sumB=0;
//For loop for Part (a)
for(int i=2;i<=100;i+=2){
sumA+=i;
}System.out.println("Sum of all even numbers between 1 and 100(inclusive): "+sumA);
//For loop for Part (b)
for(int x=1;x<=100;x++){
sumB+=x;
}System.out.println("Sum of all squares between 1 and 100(inclusive): "+sumB);
//For loop for Part (c)
for(int y=0;y<=20;y++){
System.out.println("2^"+y+"= "+(int)Math.pow(2,y));
}
}
}
|
package cn.eastseven.model;
/**
* 作者<br/>
* 出版社<br/>
* ISBN<br/>
* 出版日期<br/>
* 开本<br/>
* 页码<br/>
* 版次<br/>
*
* @author eastseven
*
*/
public class Book {
// key
private String isbn;
private String name;
private String author;
private String press;
private String pubTime;
private String format;// 开本
private String pageNumber;// 页码
private String revision;// 版次
private String price;
private String coverUrl;
private String url;
public Book() {}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPress() {
return press;
}
public void setPress(String press) {
this.press = press;
}
public String getPubTime() {
return pubTime;
}
public void setPubTime(String pubTime) {
this.pubTime = pubTime;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String getPageNumber() {
return pageNumber;
}
public void setPageNumber(String pageNumber) {
this.pageNumber = pageNumber;
}
public String getRevision() {
return revision;
}
public void setRevision(String revision) {
this.revision = revision;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getCoverUrl() {
return coverUrl;
}
public void setCoverUrl(String coverUrl) {
this.coverUrl = coverUrl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
return "Book [isbn=" + isbn + ", name=" + name + ", author=" + author
+ ", press=" + press + ", pubTime=" + pubTime + ", format="
+ format + ", pageNumber=" + pageNumber + ", revision="
+ revision + ", price=" + price + ", coverUrl=" + coverUrl
+ ", url=" + url
+ "]";
}
}
|
package PageObjectModel;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
public class Factory3 {
@Test
public void linkedIn () {
WebDriver driver = Factory3.openBrowser("FireFox", "www.firefox.com")
}
}
|
package jbyco.analysis.patterns.parameters;
/**
* The parameter value.
*/
public enum ParameterValue implements AbstractParameter {
/**
* The representation of null.
*/
NULL("null"),
/**
* The representation of this.
*/
THIS("this");
/**
* The abbreviation.
*/
private final String abbr;
/**
* Instantiates a new parameter value.
*
* @param abbr the abbreviation
*/
ParameterValue(String abbr) {
this.abbr = abbr;
}
/* (non-Javadoc)
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return this.abbr;
}
}
|
package com.example.userportal.service;
import com.example.userportal.domain.OrderStatus;
import com.example.userportal.service.dto.OrderStatusDTO;
import java.util.List;
public interface OrderStatusService {
OrderStatus getStatusById(int id);
List<OrderStatusDTO> getStatuses();
}
|
package be.axxes.bookrental.dao;
import be.axxes.bookrental.domain.Author;
import be.axxes.bookrental.domain.BookDescription;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource
public interface AuthorRepository extends JpaRepository<Author, String> {
Author findAuthorByFirstnameAndLastname(String firstname, String lastname);
}
|
/*
* 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 com.tmtmmobile.tmtm.dto;
import java.util.ArrayList;
/**
* @author ITIain
*/
public class UserUpdateinfo {
private int userId;
private String userName;
private String jobTitle;
private String userPhoneNumber;
private long birthDate;
private ArrayList<String> interests;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getUserPhoneNumber() {
return userPhoneNumber;
}
public void setUserPhoneNumber(String userPhoneNumber) {
this.userPhoneNumber = userPhoneNumber;
}
public long getBirthDate() {
return birthDate;
}
public void setBirthDate(long birthDate) {
this.birthDate = birthDate;
}
public ArrayList<String> getInterests() {
return interests;
}
public void setInterests(ArrayList<String> interests) {
this.interests = interests;
}
}
|
package com.mundo.web.support.wechat.miniprogram;
import com.mundo.core.util.HashUtil;
import com.mundo.core.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
/**
* UserInfoParser
*
* @author maomao
* @see <a href="https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html">开放数据校验与解密</a>
* @since 2019-03-30
*/
public class UserInfoParser {
private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoParser.class);
private static final Cipher CIPHER;
static {
final String aesCbcPadding = "AES/CBC/PKCS5Padding";
try {
CIPHER = Cipher.getInstance(aesCbcPadding);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
LOGGER.error("can not find such algorithm: {}", aesCbcPadding);
throw new UserInfoParserException(e);
}
}
/**
* 校验数据签名
*
* @param sessionKey 用户的会话密钥
* @param rawData 不包括敏感信息的原始数据字符串,用于计算签名
* @param signature 使用 sha1( rawData + sessionKey ) 得到字符串,用于校验用户信息
* @return true 校验成功;false 校验失败
* @see <a href="https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html#数据签名校验">数据签名校验</a>
*/
public static boolean checkSignature(final String sessionKey, final String rawData, final String signature) {
LOGGER.debug("rawData: {}", rawData);
LOGGER.debug("signature: {}", signature);
String hash = HashUtil.SHA1.hash(rawData + sessionKey);
LOGGER.debug("hash: {}", hash);
return Objects.equals(signature, hash);
}
/**
* 解密敏感数据
*
* @param sessionKey 用户的会话密钥
* @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
* @param iv 加密算法的初始向量
* @return 小程序用户信息 {@link UserInfo}
* @see <a href="https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html#加密数据解密算法">加密数据解密算法</a>
*/
public static UserInfo decryptData(final String sessionKey, final String encryptedData, final String iv) {
final byte[] sessionKeyBase64 = HashUtil.decode(sessionKey);
final byte[] encryptedDataBase64 = HashUtil.decode(encryptedData);
final byte[] ivBase64 = HashUtil.decode(iv);
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyBase64, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBase64);
CIPHER.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] userInfoBytes = CIPHER.doFinal(encryptedDataBase64);
String userInfoJson = new String(userInfoBytes);
LOGGER.debug("decrypt user info data: {}", userInfoJson);
return JsonUtil.toClass(userInfoJson, UserInfo.class);
} catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) {
throw new UserInfoParserException(e);
}
}
}
|
package abonne;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import bibliotheque.ClientFactory;
import bibliotheque.Client;
/**
*
* @author guydo
* represent a class to load different type of Users
*/
public class AbonneLoader implements ClientFactory{
@Override
public List<Client> getAbonneFromFile(String fileName) {
ArrayList<Client> liste = new ArrayList<Client>();
try {
BufferedReader buff = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
String line;
while((line = buff.readLine()) != null){ // read an entry
String tab[] = line.split(";");
if(tab.length == 4)
liste.add(new Abonne(tab[0], tab[1],Integer.valueOf(tab[2]),tab[3])); // convert it into a user and add it
}
buff.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return liste;
}
}
|
package com.logicalcode.recursion;
public class FactorialUseRec {
public static void main(String[] args) {
int value=factorial(5);
System.out.println("value:::"+value);
}
private static int factorial(int num) {
if (num == 1){
return 1;
}
else{
return(num * factorial(num-1));
}
}
}
|
package com.trey.fitnesstools;
public class Plate
{
private double weight;
private boolean enabled;
//whether or not this plate is a custom plate added by the user at runtime
private boolean custom;
//set the boolean fields to these constants instead of literals
public static final boolean CUSTOM_PLATE = true;
public static final boolean NOT_CUSTOM_PLATE = false;
public static final boolean PLATE_ENABLED = true;
public static final boolean PLATE_DISABLED = false;
public Plate(double weight,boolean enabled,boolean custom)
{
this.weight = weight;
this.enabled = enabled;
this.custom = custom;
}
//copy constructor
public Plate(Plate p)
{
weight = p.getWeight();
enabled = p.isEnabled();
custom = p.isCustom();
}
public double getWeight()
{
return weight;
}
public void setWeight(double weight)
{
this.weight = weight;
}
public boolean isEnabled()
{
return enabled;
}
public void setEnabled(boolean b)
{
enabled = b;
}
public boolean isCustom()
{
return custom;
}
public void setCustom(boolean b)
{
custom = b;
}
}
|
package com.tencent.mm.modelmulti;
import com.tencent.mm.g.a.hc;
import com.tencent.mm.kernel.g;
import com.tencent.mm.platformtools.ab;
import com.tencent.mm.pointers.PByteArray;
import com.tencent.mm.pointers.PInt;
import com.tencent.mm.protocal.MMProtocalJni;
import com.tencent.mm.protocal.s.b;
import com.tencent.mm.protocal.z;
import com.tencent.mm.sdk.b.a;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
public final class l {
public static boolean PJ() {
boolean z;
g.Ek();
if (bi.oV((String) g.Ei().DT().get(8195, null)).length() > 0) {
g.Ek();
if (bi.f((Integer) g.Ei().DT().get(15, null)) != 0) {
z = false;
x.i("MicroMsg.NewSyncMgr", "summerinit needInit ret[%b]", new Object[]{Boolean.valueOf(z)});
return z;
}
}
z = true;
x.i("MicroMsg.NewSyncMgr", "summerinit needInit ret[%b]", new Object[]{Boolean.valueOf(z)});
return z;
}
public static void a(int i, byte[] bArr, byte[] bArr2, long j) {
b bVar = new b();
PByteArray pByteArray = new PByteArray();
PByteArray pByteArray2 = new PByteArray();
PInt pInt = new PInt();
PInt pInt2 = new PInt();
PInt pInt3 = new PInt(0);
PInt pInt4 = new PInt(com.tencent.mm.plugin.game.gamewebview.jsapi.biz.b.CTRL_BYTE);
try {
x.i("MicroMsg.NewSyncMgr", "summerdiz dealWithPushResp unpack ret[%b], noticeid[%d]", new Object[]{Boolean.valueOf(MMProtocalJni.unpack(pByteArray2, bArr, bArr2, pByteArray, pInt, pInt2, pInt3, pInt4)), Integer.valueOf(pInt3.value)});
if (pInt3.value != 0) {
hc hcVar = new hc();
hcVar.bQo.bQp = pInt3.value;
boolean m = a.sFg.m(hcVar);
x.i("MicroMsg.NewSyncMgr", "summerdiz publish GetDisasterInfoEvent noticeid[%d] publish[%b]", new Object[]{Integer.valueOf(pInt3.value), Boolean.valueOf(m)});
pInt3.value = 0;
}
if (r3) {
bVar.qWC = pInt4.value;
if (pInt.value == -13) {
bVar.qWB = pInt.value;
x.e("MicroMsg.NewSyncMgr", "unpack push resp failed session timeout");
return;
}
int G = bVar.G(pByteArray2.value);
x.d("MicroMsg.NewSyncMgr", "bufToResp using protobuf ok");
bVar.qWB = G;
bVar.bufferSize = (long) bArr.length;
g.Ek();
byte[] WP = bi.WP(bi.oV((String) g.Ei().DT().get(8195, null)));
byte[] a = ab.a(bVar.qWX.rny);
g.Ek();
g.Eg().aW(bVar.qWX.hcd, bVar.qWX.rZx);
com.tencent.mm.kernel.a.gH(bVar.qWX.hcd);
if (bi.bC(a) || !z.h(WP, a)) {
x.e("MicroMsg.NewSyncMgr", "compareKeybuf syncKey failed");
return;
}
((com.tencent.mm.plugin.zero.b.b) g.l(com.tencent.mm.plugin.zero.b.b.class)).PM().a(bVar, i, j);
if (pInt3.value != 0) {
hc hcVar2 = new hc();
hcVar2.bQo.bQp = pInt3.value;
boolean m2 = a.sFg.m(hcVar2);
x.i("MicroMsg.NewSyncMgr", "summerdiz publish GetDisasterInfoEvent noticeid[%d] publish[%b]", new Object[]{Integer.valueOf(pInt3.value), Boolean.valueOf(m2)});
pInt3.value = 0;
return;
}
return;
}
x.e("MicroMsg.NewSyncMgr", "unpack push resp failed");
} catch (Throwable e) {
x.e("MicroMsg.NewSyncMgr", "unpack push resp failed: %s", new Object[]{e});
x.printErrStackTrace("MicroMsg.NewSyncMgr", e, "", new Object[0]);
}
}
}
|
package main.com.epam.site.dao;
import main.com.epam.site.exception.ProjectException;
/**
* Created by Вероника on 22.01.2016.
*/
public class XMLDaoException extends ProjectException {
private static final long serialVersionUID = 1;
public XMLDaoException(String message){
super(message);
}
public XMLDaoException(String message, Exception e){
super(message, e);
}
}
|
package notepad;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import jdialog.AboutDialog;
import jdialog.CalculatorDialog;
import jdialog.CalendarDialog;
import jdialog.FindorReplaceDialog;
import jdialog.FindDialog;
import jdialog.SetFontDialog;
public class Notepad extends JFrame {
/**
*
*/
public boolean nexte;
private static final long serialVersionUID = 1L;
private String unknowFile = "无标题";
private String separator = " - ";
private String fileName = "无标题";
private String title = " - 记事本";
private Font fontMenu = new Font("YaHei Consolas Hybrid", Font.PLAIN, 12);// 字体的单位:磅
private Font fontContent = new Font("YaHei Consolas Hybrid", Font.PLAIN, 16);
private String imagework = "F:\\EclipseImage";
private JPanel panBottom;
private JLabel labCol = new JLabel("第1行");
private JLabel labRow = new JLabel("第1列");
private JMenuItem mnuNew;
private JMenuItem mnuOpen;
private JMenuItem mnuSave;
private JMenuItem mnuSaveAs;
private JMenuItem mnuExit;
private JMenuItem mnuUndo;
private JMenuItem mnuCut;
private JMenuItem mnuCopy;
private JMenuItem mnuPaste;
private JMenuItem mnuDelete;
private JMenuItem mnuFind;
private JMenuItem mnuFindNext;
private JMenuItem mnuReplace;
private JMenuItem mnuGoto;
private JMenuItem mnuSelectAll;
private JMenuItem mnuDateTime;
private JCheckBoxMenuItem mnuAutoWarp;
private JMenuItem mnuFont;
private JCheckBoxMenuItem mnuStatus;
private JMenuItem mnuViewHelp;
private JMenuItem mnuAbout;
private JMenuItem mnuCalculator;
private Frame frame;
// private File projectPath = new
// File(ClassLoader.getSystemResource("").getPath()).getParentFile();
// private String workPath = this.projectPath.getAbsolutePath() +
// File.separator + "img" + File.separator;
public Font getFontMenu() {
return this.fontMenu;
}
@SuppressWarnings("unused")
private class MaxLengthDocument extends PlainDocument {
private static final long serialVersionUID = 1L;
int maxChars;
public MaxLengthDocument(int maxChars) {
this.maxChars = maxChars;
}
@Override
public void insertString(int offset, String s, AttributeSet a) throws BadLocationException {
if (this.getLength() + s.length() > this.maxChars) {
Toolkit.getDefaultToolkit().beep();
return;
}
super.insertString(offset, s, a);
}
}
private JScrollPane jspMain = new JScrollPane();
public JTextArea txtContent = new JTextArea();
public void setFontContent(Font fontContent) {
this.fontContent = fontContent;
this.txtContent.setFont(this.fontContent);
// this.txtContent.repaint();
}
private boolean isModify = false;
public Notepad() {
int fWidth = 800;
int fHeight = 600;
this.setSize(fWidth, fHeight);
// 设置窗体标题
this.setTitle(this.fileName);
// 设置窗体图标
ImageIcon icon = new ImageIcon(this.imagework + File.separator + "image.png");
this.setIconImage(icon.getImage());
icon.getDescription();
// 将菜单栏组装到窗体中
this.setJMenuBar(this.buildMenuBar());
// 主工作区
this.txtContent.setFont(this.fontMenu);
this.txtContent.setLineWrap(false);
this.jspMain.getViewport().add(this.txtContent);
this.add(this.jspMain, BorderLayout.CENTER);
// 添加监听器的方法
this.addListener();
JLabel lblStatus = new JLabel();
lblStatus.setFont(new Font("微软雅黑", Font.PLAIN, 12));
this.labCol = new JLabel("第1行");
this.labRow = new JLabel("第1列");
lblStatus.add(labCol);
lblStatus.add(labRow);
this.panBottom = new JPanel();
panBottom.setLayout(new GridLayout(1, 5));
this.lblmodify = new JLabel();
//panBottom.add(lblmodify);
panBottom.add(new JLabel());
panBottom.add(new JLabel());
panBottom.add(new JLabel());
panBottom.add(lblStatus);
panBottom.add(labCol);
panBottom.add(labRow);
panBottom.setBorder(new LineBorder(Color.GRAY));
//this.add(panBottom, BorderLayout.SOUTH);
this.mnuStatus.setSelected(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JLabel lblmodify;
/**
* 构建菜单栏
*
* @return
*/
private JMenuBar buildMenuBar() {
// 创建菜单组件
// 菜单栏
JMenuBar menuBar = new JMenuBar();
// 菜单
JMenu menuFile = new JMenu("文件(F)");
JMenu menuEdit = new JMenu("编辑(E)");
JMenu menuFormat = new JMenu("格式(O)");
JMenu menuView = new JMenu("查看(V)");
JMenu menuHelp = new JMenu("帮助(H)");
// 文件菜单
this.mnuNew = this.buildMenu(menuFile, "新建(N)");
this.mnuOpen = this.buildMenu(menuFile, "打开(O)...");
this.mnuSave = this.buildMenu(menuFile, "保存(S)");
this.mnuSaveAs = this.buildMenu(menuFile, "另存为(A)...");
menuFile.addSeparator();// 添加菜单的分隔线
this.mnuExit = this.buildMenu(menuFile, "退出(X)");
// 编辑菜单
this.mnuUndo = this.buildMenu(menuEdit, "撤销(U)");
menuEdit.addSeparator();
this.mnuCut = this.buildMenu(menuEdit, "剪切(T) Ctrl+X");
this.mnuCopy = this.buildMenu(menuEdit, "复制(C) Ctrl+C");
this.mnuPaste = this.buildMenu(menuEdit, "粘贴(P) Ctrl+V");
this.mnuDelete = this.buildMenu(menuEdit, "删除(L) Del");
menuEdit.addSeparator();
this.mnuFind = this.buildMenu(menuEdit, "查找(F)...");
this.mnuFindNext = this.buildMenu(menuEdit, "查找下一个(N)");
this.mnuReplace = this.buildMenu(menuEdit, "替换(R)...");
this.mnuGoto = this.buildMenu(menuEdit, "转到(G)...");
menuEdit.addSeparator();
this.mnuSelectAll = this.buildMenu(menuEdit, "全选(A)");
this.mnuDateTime = this.buildMenu(menuEdit, "时间/日期(D)");
// 格式菜单
// this.mnuAutoWarp = this.buildMenu(menuFormat, "自动换行(W)");
this.mnuAutoWarp = new JCheckBoxMenuItem("自动换行(W)");
menuFormat.setFont(this.fontMenu);
this.mnuAutoWarp.setFont(this.fontMenu);
menuFormat.add(this.mnuAutoWarp);
this.mnuFont = this.buildMenu(menuFormat, "字体(F)...");
// 查看菜单
// this.mnuStatus = this.buildMenu(menuView, "状态栏(S)");
this.mnuStatus = new JCheckBoxMenuItem("状态栏(S)");
menuView.setFont(this.fontMenu);
this.mnuStatus.setFont(this.fontMenu);
menuView.add(this.mnuStatus);
// 帮助菜单
this.mnuViewHelp = this.buildMenu(menuHelp, "查看帮助(H)");
menuHelp.addSeparator();
this.mnuAbout = this.buildMenu(menuHelp, "关于记事本(A)");
this.mnuCalculator=this.buildMenu(menuHelp, "计算器");
// 将菜单组装到菜单栏
menuBar.add(menuFile);
menuBar.add(menuEdit);
menuBar.add(menuFormat);
menuBar.add(menuView);
menuBar.add(menuHelp);
return menuBar;
}
/**
* 点击自动换行菜单项的状态改变事件处理方法
*/
/**
* 菜单的组装
*
* @param menu
* 菜单名
* @param menuText
* 菜单项文字
* @return
*/
private JMenuItem buildMenu(JMenu menu, String menuText) {
// 菜单的组装
JMenuItem mnuItem = new JMenuItem(menuText);// 菜单项
menu.setFont(this.fontMenu);// 设置菜单字体
mnuItem.setFont(this.fontMenu); // 设置菜单项字体
menu.add(mnuItem);// 将菜单项组装进菜单
return mnuItem;
}
@Override
public void setTitle(String fileName) {
super.setTitle(fileName + this.title);
}
// 增加监听器的方法
public void addListener() {
this.txtContent.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
this.changedUpdate(e);
}
@Override
public void insertUpdate(DocumentEvent e) {
this.changedUpdate(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
if (!isModify) {
//System.out.println("changedUpdate");
setModify("未保存");
}
}
});
// 点击新建文件菜单的操作
this.mnuNew.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!isModify) {
initContent();
} else {
int choose = JOptionPane.showConfirmDialog(null, "是否将更改保存到 " + unknowFile, title,
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
new ImageIcon(imagework + "image.png"));
// System.out.println(choose);
switch (choose) {
case JOptionPane.YES_OPTION:
try {
setSave();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
break;
case JOptionPane.NO_OPTION:
initContent();
break;
case JOptionPane.CANCEL_OPTION:
break;
default:
break;
}
}
}
});
this.mnuOpen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!isModify) {
openFile();
} else {
int choose = JOptionPane.showConfirmDialog(null, "是否将更改保存到 " + unknowFile, title,
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
new ImageIcon(imagework + "image.png"));
// System.out.println(choose);
switch (choose) {
case JOptionPane.YES_OPTION:
try {
setSave();
txtContent.setText(null);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
break;
case JOptionPane.NO_OPTION:
openFile();
break;
case JOptionPane.CANCEL_OPTION:
break;
default:
break;
}
}
}
});
this.mnuSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!isModify) {
}
try {
setSave();
txtContent.setText(" ");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
});
this.mnuSaveAs.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!isModify) {
}
try {
setSave();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
});
this.mnuExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!isModify) {
System.exit(0);
} else {
int choose = JOptionPane.showConfirmDialog(null, "是否将更改保存到 " + unknowFile, title,
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
new ImageIcon(imagework + "image.png"));
// System.out.println(choose);
switch (choose) {
case JOptionPane.YES_OPTION:
try {
setSave();
System.exit(0);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
break;
case JOptionPane.NO_OPTION:
System.exit(0);
break;
case JOptionPane.CANCEL_OPTION:
break;
default:
break;
}
}
}
});
this.mnuUndo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtContent.setText(null);
}
});
this.mnuCut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 调用JtextArea里面的删除复制粘贴功能
txtContent.cut();
}
});
this.mnuCopy.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtContent.copy();
}
});
this.mnuPaste.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtContent.paste();
}
});
this.mnuDelete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtContent.replaceSelection(null);
}
});
this.mnuSelectAll.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtContent.selectAll();
}
});
this.mnuFind.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SetFind();
}
});
this.mnuFindNext.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SetFind();
}
});
this.mnuReplace.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FindorReplace();
}
});
this.mnuDateTime.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showCalendar();
}
});
this.mnuFont.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setFontDialog();
}
});
this.txtContent.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
setLight();
}
});
this.mnuStatus.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mnuStatus();
}
});
this.mnuAutoWarp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setautoWarp();
}
});
this.mnuAbout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
aboutHandler();
}
});
this.mnuCalculator.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SetCalculator();
}
});
}
// 初始化内容区域
private void initContent() {
// 设置窗体标题
this.setTitle(this.unknowFile + this.separator + this.title);
this.txtContent.setText("");
this.setModify("新文件");
//this.setStatus(1, 1);
}
// private void setStatus(int row, int col) {// Count:1
//
// JPanel panStatus = ((JPanel) this.getContentPane().getComponent(1));
// JLabel lblStatus = (JLabel) panStatus.getComponent(3);
// lblStatus.setText("第 " + row + " 行/第 " + col + " 列");
// }
public void setModify(String modify) {
switch (modify) {
case "新文件":
case "未修改":
case "已保存":
this.isModify = false;
this.mnuSave.setEnabled(false);
break;
case "未保存":
this.isModify = true;
this.mnuSave.setEnabled(true);
break;
default:
modify = "";
}
//TODO
//JLabel lblmodify = (JLabel) ((JPanel) this.getContentPane().getComponent(1)).getComponent(0);
//lblmodify.setText(modify);
lblmodify.setText(modify);
}
// 捕捉光标状态栏
private void setLight() {
try {
int pos = this.txtContent.getCaretPosition();
int lineOfC = this.txtContent.getLineOfOffset(pos) + 1;
int col = pos - this.txtContent.getLineStartOffset(lineOfC - 1) + 1;
this.labCol.setText("第 " + String.valueOf(lineOfC) + " 行");
this.labRow.setText("第 " + String.valueOf(col) + " 列");
} catch (BadLocationException e) {
System.out.println("无法获得光标位置");
e.printStackTrace();
}
}
// 换行方法
private void setautoWarp() {
this.txtContent.setLineWrap(this.mnuAutoWarp.getState());
}
// 捕捉光标在文本区域
private void mnuStatus() {
if (mnuStatus.isSelected()) {
this.add(this.panBottom,BorderLayout.SOUTH);
this.repaint();
} else if(!mnuStatus.isSelected()){
this.remove(this.panBottom);
this.repaint();
}
}
// 日历
private void showCalendar() {
CalendarDialog frm = new CalendarDialog(this, "日历", true);
frm.setVisible(true);
}
//计算器
private void SetCalculator() {
CalculatorDialog cd=new CalculatorDialog(this, "计算器", true);
cd.setVisible(true);
}
// 查找、查找下一个、替换
private void FindorReplace() {
FindorReplaceDialog fod = new FindorReplaceDialog(this, "查找", true);
fod.setVisible(true);
}
//查找
private void SetFind() {
FindDialog rd=new FindDialog(this, "查找", true);
rd.setVisible(true);
}
// 获得帮助的窗口
private void aboutHandler() {
AboutDialog ad = new AboutDialog(this, "帮助", true);
ad.setVisible(true);
}
private void setSave() throws FileNotFoundException {
FileDialog fd = new FileDialog(frame, "保存文件", FileDialog.SAVE);
fd.setVisible(true);
try {
FileWriter fw = new FileWriter(fd.getDirectory() + fd.getFile() + ".txt");
String b = null;
b = this.txtContent.getText();
fw.write(b);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
txtContent.setText("");
}
// 设置字体方法
public void setFontDialog() {
JDialog dialog = new SetFontDialog(this, "字体", true);
dialog.setVisible(true);
}
// 打开文件操作方法
public void openFile() {
JFileChooser chooser = new JFileChooser(imagework);
javax.swing.filechooser.FileFilter filter1 = new FileNameExtensionFilter("网页文件(*.html,*jsp)", "html", "jsp");
chooser.setFileFilter(filter1);
javax.swing.filechooser.FileFilter filter2 = new FileNameExtensionFilter("文本文件(*.txt)", "txt");
chooser.setFileFilter(filter2);
int returnVal = chooser.showOpenDialog(this);
switch (returnVal) {
case JFileChooser.APPROVE_OPTION:
this.txtContent.setText(null);
File file = chooser.getSelectedFile();
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(file), Notepad.getFilecharset(file)));
String content;
while ((content = br.readLine()) != null) {
this.txtContent.append(content);
this.txtContent.append("\r\n");
}
br.close();
this.setModify("未修改");
//this.setStatus(1, 1);
this.txtContent.setFont(this.fontContent);
this.txtContent.getCaret().setDot(0);// 移动到文档最顶端
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
this.setTitle(file.getName() + title);
break;
case JFileChooser.CANCEL_OPTION:
break;
case JFileChooser.ERROR_OPTION:
break;
}
}
private static String getFilecharset(File sourceFile) {
String charset = "GBK";
byte[] first3Bytes = new byte[3];
try {
boolean checked = false;
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
bis.mark(0);
int read = bis.read(first3Bytes, 0, 3);
if (read == -1) {
bis.close();
return charset; // 文件编码为 ANSI
} else if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
charset = "UTF-16LE"; // 文件编码为 Unicode
checked = true;
} else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) {
charset = "UTF-16BE"; // 文件编码为 Unicode big endian
checked = true;
} else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB
&& first3Bytes[2] == (byte) 0xBF) {
charset = "UTF-8"; // 文件编码为 UTF-8
checked = true;
}
bis.reset();
if (!checked) {
while ((read = bis.read()) != -1) {
if (read >= 0xF0)
break;
if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK
break;
if (0xC0 <= read && read <= 0xDF) {
read = bis.read();
if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)
// (0x80
// - 0xBF),也可能在GB编码内
continue;
else
break;
} else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小
read = bis.read();
if (0x80 <= read && read <= 0xBF) {
read = bis.read();
if (0x80 <= read && read <= 0xBF) {
charset = "UTF-8";
break;
} else
break;
} else
break;
}
}
}
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
return charset;
}
}
|
package com.pine.template.mvvm;
import com.pine.template.base.BaseConstants;
/**
* Created by tanghongfeng on 2018/9/10.
*/
public interface MvvmConstants extends BaseConstants {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.