text
stringlengths 10
2.72M
|
|---|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.ider.ytb_tv.ui.fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v17.leanback.app.BackgroundManager;
import android.support.v17.leanback.app.DetailsFragment;
import android.support.v17.leanback.widget.Action;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.ClassPresenterSelector;
import android.support.v17.leanback.widget.DetailsOverviewRow;
import android.support.v17.leanback.widget.DetailsOverviewRowPresenter;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.ImageCardView;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.OnActionClickedListener;
import android.support.v17.leanback.widget.OnItemViewClickedListener;
import android.support.v17.leanback.widget.Presenter;
import android.support.v17.leanback.widget.Row;
import android.support.v17.leanback.widget.RowPresenter;
import android.support.v4.app.ActivityOptionsCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.ider.ytb_tv.data.CustService;
import com.ider.ytb_tv.data.ResourceEntry;
import com.ider.ytb_tv.db.DBManager;
import com.ider.ytb_tv.ui.Adapter.PaginationAdapter;
import com.ider.ytb_tv.ui.activity.DescriptionActivity;
import com.ider.ytb_tv.ui.activity.DetailsActivity;
import com.ider.ytb_tv.ui.activity.MainActivity;
import com.ider.ytb_tv.data.Movie;
import com.ider.ytb_tv.ui.activity.PlaybackOverlayActivity;
import com.ider.ytb_tv.R;
import com.ider.ytb_tv.utils.BitmapUtil;
import com.ider.ytb_tv.utils.JsonParser;
import com.ider.ytb_tv.utils.OkhttpManager;
import com.ider.ytb_tv.utils.Utils;
import com.ider.ytb_tv.ui.presenter.DetailsDescriptionPresenter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
/*
* LeanbackDetailsFragment extends DetailsFragment, a Wrapper fragment for leanback details screens.
* It shows a detailed view of video and its meta plus related videos.
*
*/
public class VideoDetailsFragment extends DetailsFragment {
public static final String TAG = "VideoDetailsFragment";
private static final int ACTION_WATCH_TRAILER = 1;
private static final int ACTION_DESCRIPTION = 2;
private static final int ACTION_COLLECT = 3;
private static final int DETAIL_THUMB_WIDTH = 274;
private static final int DETAIL_THUMB_HEIGHT = 274;
private Movie mSelectedMovie;
private int mPlaylistPosition;
private boolean isFav;
private ArrayObjectAdapter mAdapter;
private ClassPresenterSelector mPresenterSelector;
private DetailsDescriptionPresenter mDetailsDescriptionPresenter;
private DBManager dbManager;
private PaginationAdapter relatedAdapter;
private BackgroundManager mBackgroundManager;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mSelectedMovie = getActivity().getIntent().getParcelableExtra(DetailsActivity.MOVIE);
mPlaylistPosition = getActivity().getIntent().getIntExtra(DetailsActivity.PLAYLIST_POSITION, -1);
isFav = getActivity().getIntent().getBooleanExtra(DetailsActivity.COLLECTED, false);
dbManager = DBManager.getInstance(getActivity().getApplicationContext());
mBackgroundManager = BackgroundManager.getInstance(getActivity());
mBackgroundManager.attach(getActivity().getWindow());
if (mSelectedMovie != null) {
Utils.log(TAG, mSelectedMovie.getId());
setupAdapter();
setupDetailsOverviewRow();
setupDetailsOverviewRowPresenter();
setupMovieListRow();
setupMovieListRowPresenter();
setOnItemViewClickedListener(new ItemViewClickedListener());
} else {
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate DetailsFragment");
super.onCreate(savedInstanceState);
}
@Override
public void onStop() {
super.onStop();
}
private void setupAdapter() {
mPresenterSelector = new ClassPresenterSelector();
mAdapter = new ArrayObjectAdapter(mPresenterSelector);
setAdapter(mAdapter);
}
private void setupDetailsOverviewRow() {
final DetailsOverviewRow row = new DetailsOverviewRow(mSelectedMovie);
row.setImageDrawable(getResources().getDrawable(R.drawable.default_background));
int width = Utils.convertDpToPixel(getActivity()
.getApplicationContext(), DETAIL_THUMB_WIDTH);
int height = Utils.convertDpToPixel(getActivity()
.getApplicationContext(), DETAIL_THUMB_HEIGHT);
Glide.with(getActivity())
.load(mSelectedMovie.getCardImageUrl())
.centerCrop()
.error(R.drawable.default_background)
.into(new SimpleTarget<GlideDrawable>(width, height) {
@Override
public void onResourceReady(GlideDrawable resource,
GlideAnimation<? super GlideDrawable>
glideAnimation) {
Log.d(TAG, "details overview card image url ready: " + resource);
row.setImageDrawable(resource);
mAdapter.notifyArrayItemRangeChanged(0, mAdapter.size());
}
});
row.addAction(new Action(ACTION_WATCH_TRAILER, getResources().getString(
R.string.watch_1)));
// row.addAction(new Action(ACTION_DESCRIPTION, getResources().getString(R.string.description_1)));
row.addAction(new Action(ACTION_COLLECT, isFav ? getResources().getString(R.string.remove_favorite) : getResources().getString(R.string.favorite_1)));
mAdapter.add(row);
}
private void setupDetailsOverviewRowPresenter() {
mDetailsDescriptionPresenter = new DetailsDescriptionPresenter();
// Set detail background and style.
DetailsOverviewRowPresenter detailsPresenter =
new DetailsOverviewRowPresenter(mDetailsDescriptionPresenter);
detailsPresenter.setBackgroundColor(getResources().getColor(R.color.selected_background));
detailsPresenter.setStyleLarge(true);
// Hook up transition element.
detailsPresenter.setSharedElementEnterTransition(getActivity(),
DetailsActivity.SHARED_ELEMENT_NAME);
detailsPresenter.setOnActionClickedListener(new OnActionClickedListener() {
@Override
public void onActionClicked(Action action) {
if (action.getId() == ACTION_WATCH_TRAILER) {
Intent intent = new Intent(getActivity(), PlaybackOverlayActivity.class);
intent.putExtra(DetailsActivity.MOVIE, mSelectedMovie);
intent.putExtra(DetailsActivity.PLAYLIST_POSITION, mPlaylistPosition);
startActivity(intent);
} else if (action.getId() == ACTION_DESCRIPTION) {
showFullDescription(mDetailsDescriptionPresenter.getDescription());
} else if (action.getId() == ACTION_COLLECT) {
if(isFav) {
dbManager.deleteMovie(mSelectedMovie);
action.setLabel1(getResources().getString(R.string.favorite_1));
mAdapter.notifyArrayItemRangeChanged(0, mAdapter.size());
sendFavactionBroadcast(DetailsActivity.ACTION_FAVORITE_REMOVED, mSelectedMovie);
isFav = false;
} else {
dbManager.insertMovie(mSelectedMovie);
action.setLabel1(getResources().getString(R.string.remove_favorite));
mAdapter.notifyArrayItemRangeChanged(0, mAdapter.size());
sendFavactionBroadcast(DetailsActivity.ACTION_FAVORITE_ADDED, mSelectedMovie);
isFav = true;
}
}
}
});
mPresenterSelector.addClassPresenter(DetailsOverviewRow.class, detailsPresenter);
}
private void setupMovieListRow() {
String subcategory = getString(R.string.related_movies);
HeaderItem header = new HeaderItem(subcategory);
relatedAdapter = new PaginationAdapter(getActivity());
mAdapter.add(new ListRow(header, relatedAdapter));
}
private void setupMovieListRow(ArrayList<Movie> movies) {
for(Movie movie : movies) {
relatedAdapter.add(movie);
}
}
public void requestDescription(final CustService service) {
Observable
.create(new Observable.OnSubscribe<Movie>() {
@Override
public void call(Subscriber<? super Movie> subscriber) {
subscriber.onNext(service.setVideoDescription(mSelectedMovie));
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Movie>() {
@Override
public void call(Movie movie) {
Utils.log(TAG, "setItem, " + movie.getDescription());
((DetailsOverviewRow)mAdapter.get(0)).setItem(movie);
mAdapter.notifyArrayItemRangeChanged(0, mAdapter.size());
}
});
}
public void requestRelatedVideos(final CustService service) {
Observable
.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
String result = service.getRelateVideos(null, mSelectedMovie.getId());
subscriber.onNext(result);
}
})
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.map(new Func1<String, ArrayList<Movie>>() {
@Override
public ArrayList call(String s) {
ArrayList<ResourceEntry> list = JsonParser.parseRelateOrSearchVideos(s);
return service.setVideosDuration(list);
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<ArrayList<Movie>>() {
@Override
public void call(ArrayList<Movie> movies) {
setupMovieListRow(movies);
}
});
}
private void setupMovieListRowPresenter() {
mPresenterSelector.addClassPresenter(ListRow.class, new ListRowPresenter());
}
private final class ItemViewClickedListener implements OnItemViewClickedListener {
@Override
public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof Movie) {
Movie movie = (Movie) item;
Log.d(TAG, "Item: " + item.toString());
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra(getResources().getString(R.string.movie), movie);
intent.putExtra(getResources().getString(R.string.should_start), true);
Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
getActivity(),
((ImageCardView) itemViewHolder.view).getMainImageView(),
DetailsActivity.SHARED_ELEMENT_NAME).toBundle();
getActivity().startActivity(intent, bundle);
}
}
}
private void showFullDescription(String description) {
Intent intent = new Intent(getActivity(), DescriptionActivity.class);
intent.putExtra(DescriptionActivity.DESCRIPTION, description);
Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
getActivity(),
mDetailsDescriptionPresenter.holder.getBody(),
DescriptionActivity.SHARED_ELEMENT
).toBundle();
getActivity().startActivity(intent, bundle);
}
private void sendFavactionBroadcast(String action, Movie movie) {
Intent intent = new Intent();
intent.setAction(action);
intent.putExtra(DetailsActivity.MOVIE, movie);
getActivity().sendBroadcast(intent);
}
}
|
package GameControls;
/**
* This thread controls all of the games actions with the exception of drawing the display.
*
**/
import Objects.*;
import Sprites.*;
import Utilities.*;
public class GameControl implements Runnable {
double globalTimer = 0; // Contains the time since the game started (or
// restarted)
double startTime; // Contains the time of game start (or restart)
double lastSpawn; // The game time at which the last spawn occured
double spawnInterval; // The frequency at which enemies should be spawned
public GameControl() { // Begins a new game upon execution
newGame();
}
public void newGame() { // Reverts all the game settings to the new game state.
startTime = System.nanoTime();
//Wall walls = new Wall();
GameInfo.projectiles.clear();
GameInfo.players.clear();
GameInfo.enemies.clear();
GameInfo.spawns.clear();
GameInfo.geoms.clear();
GameInfo.effects.clear();
//GameInfo.objects.add(walls);
GameInfo.playerScore = 0;
GameInfo.playerMultiplier = 1;
GameInfo.difficulty = 1;
GameInfo.spawns.add(new SpawnPoint(30, 30));
GameInfo.spawns.add(new SpawnPoint(1100, 30));
GameInfo.spawns.add(new SpawnPoint(1100, 700));
GameInfo.spawns.add(new SpawnPoint(30, 700));
lastSpawn = 0;
spawnInterval = 4;
for(int x = GameInfo.xBegin+100; x<GameInfo.xEnd; x+=100){
GameInfo.effects.add(new Line(true, x, 15));
}
for(int y = GameInfo.yBegin+100; y<GameInfo.yEnd; y+=100){
GameInfo.effects.add(new Line(false, y, 15));
}
Player ryan = new Player();
ryan.setYLoc(300);
ryan.setXLoc(500);
GameInfo.players.add(ryan);
}
public void run() { // Performs regular game functions.
while (true) {
updateTime();
//double startTime;
//startTime = System.nanoTime();
MoveObjects();
//double moveTime = System.nanoTime()-startTime;
//startTime = System.nanoTime();
CheckCollisions();
//double collisionTime = System.nanoTime()-startTime;
//startTime = System.nanoTime();
CheckSpawns();
//double spawnTime = System.nanoTime()-startTime;
//double fullTime = spawnTime+collisionTime+moveTime;
//System.out.println("Time moving objects: "+moveTime/fullTime*100);
//System.out.println("Time checking collisions: "+collisionTime/fullTime*100);
//System.out.println("Time checking spawns: "+spawnTime/fullTime*100);
//System.out.println();
try {
Thread.sleep(20); // Prevents the run method from being called
// more often then necessary
} catch (InterruptedException e) {
e.printStackTrace();
}
if (UserInput.Restart == true) { // Check if the user requested a new game
newGame();
}
}
}
public void MoveObjects() {
//double startTime = System.nanoTime();
for (int i = 0; i < GameInfo.enemies.size(); i++) {
GameInfo.enemies.get(i).move();
}
for (int i = 0; i < GameInfo.players.size(); i++) {
GameInfo.players.get(i).move();
}
for (int i = 0; i < GameInfo.geoms.size(); i++) {
GameInfo.geoms.get(i).move();
}
for (int i = 0; i < GameInfo.projectiles.size(); i++) {
GameInfo.projectiles.get(i).move();
}
for (int i = 0; i < GameInfo.effects.size(); i++) {
GameInfo.effects.get(i).move();
}
//System.out.println("Move Objects time: "+(System.nanoTime()-startTime));
}
public void CheckSpawns() {
//double startTime = System.nanoTime();
if (GameInfo.globalTimer - lastSpawn > (spawnInterval)) {
for (int i = 0; i < GameInfo.spawns.size(); i++) {
SpawnPoint spawner = GameInfo.spawns.get(i);
spawner.spawn(GameInfo.difficulty);
}
lastSpawn = GameInfo.globalTimer;
}
//System.out.println("Check Spawns time: "+(System.nanoTime()-startTime));
}
public void CheckCollisions() {
//double startTime = System.nanoTime();
//Check for collisions between players an enemies
for (int i = 0; i < GameInfo.players.size(); i++) {
Coordinates playerCoords = new Coordinates(GameInfo.players.get(i).getXLoc(),GameInfo.players.get(i).getYLoc());
for (int j = 0; j < GameInfo.enemies.size(); j++) {
Coordinates enemyCoords = new Coordinates(GameInfo.enemies.get(j).getXLoc(),GameInfo.enemies.get(j).getYLoc());
double distance = NuetralUtilities.calcDistance(playerCoords, enemyCoords);
if (distance < GameInfo.enemies.get(j).getSize()+ GameInfo.players.get(i).getSize()) {
GameInfo.players.get(i).hit();
GameInfo.enemies.get(j).hit();
}
}
for(int j = 0; j < GameInfo.geoms.size(); j++){
Coordinates geomCoords = new Coordinates(GameInfo.geoms.get(j).getXLoc(),GameInfo.geoms.get(j).getYLoc());
double distance = NuetralUtilities.calcDistance(playerCoords, geomCoords);
if(distance < GameInfo.geoms.get(j).getSize()+GameInfo.players.get(i).getSize()){
GameInfo.geoms.get(j).hit();
}
}
}
//Check for collisions between enemies and objects
for (int i = 0; i < GameInfo.enemies.size(); i++ ){
for (int j = 0; j < GameInfo.projectiles.size(); j++) {
Coordinates enemyCoords = new Coordinates(GameInfo.enemies.get(i).getXLoc(), GameInfo.enemies.get(i).getYLoc());
Coordinates objectCoords = new Coordinates(GameInfo.projectiles.get(j).getXLoc(), GameInfo.projectiles.get(j).getYLoc());
double distance = NuetralUtilities.calcDistance(enemyCoords, objectCoords);
if (distance < GameInfo.enemies.get(i).getSize()+GameInfo.projectiles.get(j).getSize()) {
if(GameInfo.projectiles.get(j).isAlive()){
GameInfo.enemies.get(i).hit();
GameInfo.projectiles.get(j).hit();
}
}
}
}
//Remove objects which have been destroyed
for(int i=GameInfo.players.size()-1; i>=0; i--){
if(GameInfo.players.get(i).isAlive()==false){
GameInfo.players.remove(i);
}
}
for(int i=GameInfo.enemies.size()-1; i>=0; i--){
if(GameInfo.enemies.get(i).isAlive()==false){
GameInfo.enemies.remove(i);
}
}
for(int i=GameInfo.projectiles.size()-1; i>=0; i--){
if(GameInfo.projectiles.get(i).isAlive()==false){
GameInfo.projectiles.remove(i);
}
}
for(int i=GameInfo.effects.size()-1; i>=0; i--){
if(GameInfo.effects.get(i).isAlive()==false){
GameInfo.effects.remove(i);
}
}
for(int i=GameInfo.geoms.size()-1; i>=0; i--){
if(GameInfo.geoms.get(i).isAlive()==false){
GameInfo.geoms.remove(i);
}
}
//System.out.println("Check Collisions time: "+(System.nanoTime()-startTime));
}
//Update the global game timer
public void updateTime() {
GameInfo.globalTimer = (System.nanoTime() - startTime) / (Math.pow(10, 9));
}
}
|
package jpa;
import java.util.List;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLIndividual;
import org.semanticweb.owlapi.model.OWLOntology;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.MemberValuePair;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import ORM.InheritanceMapping;
import ORM.InheritanceStrategy;
import OWL.ClassIRI;
import OWL.DataPropertyIRI;
import genericcode.GenericClass;
public class JavaClass extends GenericClass{
private List<AnnotationExpr> annotations = null;
private NodeList<Modifier> modifiers = null;
NodeList<ClassOrInterfaceType> extendeds = null;
private List<FieldDeclaration> fields;
public JavaClass(OWLOntology o, ClassOrInterfaceDeclaration node) {
super(o, "class__" + node.getNameAsString());
this.setCodeName(node.getNameAsString());
this.setDataProperty(DataPropertyIRI.TYPE_NAME, node.getNameAsString());
// super(((NodeWithSimpleName<ClassOrInterfaceDeclaration>) node).getNameAsString());
this.annotations = ((BodyDeclaration<ClassOrInterfaceDeclaration>) node).getAnnotations();
this.modifiers = ((TypeDeclaration<ClassOrInterfaceDeclaration>) node).getModifiers();
this.fields = node.findAll(FieldDeclaration.class);
this.extendeds = node.getExtendedTypes();
this.setIsAbstract();
this.setIsEntity();
this.classAssertion(ClassIRI.CLASS);
if(this.is_abstract()) {
this.classAssertion(ClassIRI.ABSTRACT_CLASS);
}
if(this.isEntity()) {
this.classAssertion(ClassIRI.ENTITY_CLASS);
}
}
public List<FieldDeclaration> getFields(){
return this.fields;
}
public void setIsEntity() {
this.setEntity(false);
for (AnnotationExpr ann : this.annotations) {
if (ann.getNameAsString().equals("Entity")) {
this.setEntity(true);
}
}
}
public void setIsAbstract() {
this.set_abstract(false);
for(Modifier m : this.modifiers) {
if(m.getKeyword().asString().equals("abstract")) {
this.set_abstract(true);
}
}
}
@Override
public String getSuperclassName() {
for(Node n : this.extendeds) {
return ((NodeWithSimpleName<ClassOrInterfaceDeclaration>) n).getNameAsString();
}
return null;
}
@Override
public InheritanceStrategy getCodeInheritanceStrategy() {
AnnotationExpr ann = this.getAnnotation("Inheritance");
if (ann==null) return InheritanceStrategy.SINGLE_TABLE;
List<MemberValuePair> members = ann.findAll(MemberValuePair.class);
for(MemberValuePair m : members) {
if(m.getName().toString().equals("strategy")) {
String value = m.getValue().toString().replace("\"", "").toLowerCase();
value = value.replace("inheritancetype.", "");
switch(value) {
case "joined":
return InheritanceStrategy.TABLE_PER_CLASS;
case "table_per_class":
return InheritanceStrategy.TABLE_PER_CONCRETE_CLASS;
case "single_table":
return InheritanceStrategy.SINGLE_TABLE;
default:
System.out.println("[WARN] Estratégia de herança não reconhecida.");
System.out.println("\tTable per Concrete Class utilizado");
return InheritanceStrategy.TABLE_PER_CONCRETE_CLASS;
}
}
}
return InheritanceStrategy.SINGLE_TABLE;
}
public AnnotationExpr getAnnotation(String annotation) {
for(AnnotationExpr ann : this.annotations) {
if(ann.getNameAsString().equals(annotation)) return ann;
}
return null;
}
@Override
public String getCodeTableName() {
AnnotationExpr ann = this.getAnnotation("Table");
if(ann==null) return this.getCodeName();
List<MemberValuePair> members = ann.findAll(MemberValuePair.class);
for(MemberValuePair m : members) {
if(m.getName().toString().equals("name")) {
return m.getValue().toString().replace("\"", "");
}
}
return this.getCodeName();
}
@Override
public String toCode() {
// TODO Auto-generated method stub
return null;
}
@Override
public String toCode(InheritanceMapping im) {
// TODO Auto-generated method stub
return null;
}
// public boolean hasAnnotation(String annotation) {
// for(AnnotationExpr ann : this.annotations) {
// if(ann.getNameAsString().equals(annotation)) return true;
// }
// return false;
// }
//
// @Override
// public String getTableName() {
//
// for (AnnotationExpr ann : this.getAnnotations()) {
// if (ann.getNameAsString().equals("Table")) {
// List<MemberValuePair> members = ann.findAll(MemberValuePair.class);
// for(MemberValuePair m : members) {
// if(m.getName().toString().equals("name")) {
// return m.getValue().toString().replace("\"", "");
// }
// }
// }
// }
//
// return this.codeName;
// }
//
//
//
// @Override
// public void setInheritanceStrategy(GenericClass supremeMother) {
// if(supremeMother.getInheritanceStrategy()==null) {
// supremeMother.setInheritanceStragegy(supremeMother.getCodeInheritanceStrategy());
// }
// this.setInheritanceStragegy(supremeMother.getInheritanceStrategy());
// // TODO Auto-generated method stub
//
// }
}
|
package com.baytie.baytie.Menu.MyPoints;
/**
* Created by PRINCE on 11/29/2016.
*/
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import com.baytie.baytie.Delivery.DeliveryMenuInfoActivity;
import com.baytie.baytie.MyApp;
import com.baytie.baytie.R;
import com.baytie.baytie.Reservation.RestaurantList;
import com.baytie.context.ConstValues;
import com.baytie.vo.LoyaltyPointVO;
import com.baytie.vo.OrderDetailVO;
import com.baytie.vo.RestaurantVO;
import com.squareup.picasso.Picasso;
import java.lang.reflect.Array;
import java.util.ArrayList;
/**
* Created by Administrator on 9/14/2016.
*/
public class MyPointListViewAdapter extends BaseAdapter {
private ArrayList<LoyaltyPointVO> orderItemList = new ArrayList<LoyaltyPointVO>();
private Context mContext;
public MyPointListViewAdapter(Context context, ArrayList<LoyaltyPointVO> orderList) {
this.mContext = context;
this.orderItemList = orderList;
}
@Override
public int getCount() {
return orderItemList.size();
}
@Override
public Object getItem(int position) {
return orderItemList.get(position);
}
public void setOrderItemList(ArrayList<LoyaltyPointVO> itemList)
{
this.orderItemList = itemList;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
if (convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.sub_mypoint, parent, false);
}
ImageView restImg = (ImageView) convertView.findViewById(R.id.imgRestaurant);
TextView restName = (TextView) convertView.findViewById(R.id.txtRestName);
TextView txtOrderNo = (TextView) convertView.findViewById(R.id.txtOrderNo);
TextView txtDate = (TextView) convertView.findViewById(R.id.edtDate);
TextView txtPTGainedUsed = (TextView) convertView.findViewById(R.id.txtPTGainedUsed);
TextView txt_UsedPoint = (TextView) convertView.findViewById(R.id.txt_UsedPoint);
TextView txtbalance = (TextView) convertView.findViewById(R.id.txtbalance);
TextView txtAmount = (TextView) convertView.findViewById(R.id.txtAmount);
LoyaltyPointVO item = orderItemList.get(position);
//restName.setText(listItem.getRestName());
//edtOrderNo.setText(listItem.getOrderNo());
//edtAmount.setText(listItem.getAmount());
if (item.getRestaurant().getLogo() != null) {
if (item.getRestaurant().getLogo().contains("/")) {
String[] pathArray = item.getRestaurant().getLogo().split("/");
String imgUrl = "";
if (pathArray.length > 2) {
imgUrl = ConstValues.baseUri + pathArray[pathArray.length - 2] + "/" + pathArray[pathArray.length - 1];
Picasso.with(mContext)
.load(imgUrl)
.placeholder(R.drawable.restro_detault) // optional
.error(R.drawable.restro_detault) // optional
.into(restImg);
}
}
}
// String payment = item.getPayment_method();
// if(payment != null)
// {
// switch(Integer.valueOf(payment))
// {
// case 1:
// txtBalance.setText("Cash");
// break;
// case 2:
// txtBalance.setText("Knet");
// break;
// case 3:
// txtBalance.setText("Credit Card");
// break;
// }
// }
String amount = item.getOrder().getTotal();
if(!item.getOrder().getTotal().contains("."))
amount = amount + ".000";
txtAmount.setText(amount);
restName.setText(item.getRestaurant().getRestroName());
txtOrderNo.setText(item.getOrder().getOrder_no());
txtDate.setText(item.getOrder().getUpdated_time());
txtPTGainedUsed.setText(item.getGained_mataam_point() + "pt");
txtbalance.setText(item.getBalance_mataam_point() + "pt");
return convertView;
}
}
|
package tersletsky.ru;
import java.io.IOException;
import javax.servlet.http.*;
@SuppressWarnings("serial")
public class class1Servlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String var1 = req.getParameter("var1");
String var2 = req.getParameter("var2");
String var3 = req.getParameter("var3");
String var4 = req.getParameter("var4");
String var5 = req.getParameter("var5");
MobilePhone iPhone = new MobilePhone();
MobilePhone Nexus = new MobilePhone();
MobilePhone Meizu = new MobilePhone();
MobilePhone SGS = new MobilePhone();
MobilePhone Yota = new MobilePhone();
MobilePhone Nokia = new MobilePhone();
if (var5.equals("5")) {
resp.getWriter().println(
"<table>");
resp.getWriter().println("<tr>");
int dec = 0;
for ( long t = 1; t <= 6; t++) {
if (dec == 1) {
resp.getWriter().println("</tr>");
resp.getWriter().println("<tr>");
dec = 0;
}
dec++;
String ret = "";
if (t == 1) {
ret = "1. Apple";
} else if (t == 2) {
ret = "2. LG";
} else if (t == 3) {
ret = "3. Meizu";
} else if (t == 4) {
ret = "4. Samsung";
} else if (t == 5) {
ret = "5. Yota";
} else {
ret = "6. Nokia";
}
resp.getWriter().println("<td>");
resp.getWriter().println(ret + "</td>");
}
resp.getWriter().println("</tr>");
resp.getWriter().println("</table>");
/*
resp.getWriter().println("<option value=" + "0" + ">");
resp.getWriter().println(iPhone.getManufacturer());
resp.getWriter().println("</option>");
resp.getWriter().println("<option value=" + "1" + ">");
resp.getWriter().println(Nexus.getManufacturer());
resp.getWriter().println("</option>");
resp.getWriter().println("<option value=" + "2" + ">");
resp.getWriter().println(Meizu.getManufacturer());
resp.getWriter().println("</option>");
resp.getWriter().println("<option value=" + "3" + ">");
resp.getWriter().println(SGS.getManufacturer());
resp.getWriter().println("</option>");
resp.getWriter().println("<option value=" + "4" + ">");
resp.getWriter().println(Yota.getManufacturer());
resp.getWriter().println("</option>");
resp.getWriter().println("<option value=" + "5" + ">");
resp.getWriter().println(Nokia.getManufacturer());
resp.getWriter().println("</option>");*/
}
if (var5.equals("4")) {
String operation = req.getParameter("operation");
String result;
iPhone.setInfo("Apple", "iPhone 6 Plus", "USA");
Nexus.setInfo("LG", "Nexus 5", "USA");
Meizu.setInfo("Meizu", "MX4", "China");
SGS.setInfo("Samsung", "Galaxy S6 Edge", "South Korea");
Yota.setInfo("Yota", "YotaPhone 2", "Russia");
Nokia.setInfo("Nokia", "3310", "Finland");
if(operation.equals("0")){
result = "Company: " + iPhone.getManufacturer() + ", Model: " + iPhone.getModel() + ", Made in " + iPhone.getMadeIn();
} else if(operation.equals("1")){
result = "Company: " + Nexus.getManufacturer() + ", Model: " + Nexus.getModel() + ", Made in " + Nexus.getMadeIn();
} else if (operation.equals("2")){
result = "Company: " + Meizu.getManufacturer() + ", Model: " + Meizu.getModel() + ", Made in " + Meizu.getMadeIn();
} else if (operation.equals("3")){
result = "Company: " + SGS.getManufacturer() + ", Model: " + SGS.getModel() + ", Made in " + SGS.getMadeIn();
} else if (operation.equals("4")){
result = "Company: " + Yota.getManufacturer() + ", Model: " + Yota.getModel() + ", Made in " + Yota.getMadeIn();
} else {
result = "Company: " + Nokia.getManufacturer() + ", Model: " + Nokia.getModel() + ", Made in " + Nokia.getMadeIn();
}
resp.getWriter().println(result);
}
}
}
|
package org.jaxws.wsdl2html.service;
import java.util.List;
import javax.jws.WebService;
import org.jaxws.bytecodes2stub.service.ByteCodePackageLoadingService;
import org.jaxws.stub2html.model.WebServiceStubSet;
import org.jaxws.stub2html.service.WebServiceStubSetFactory;
import org.jaxws.stub2html.view.WebServiceDisplayEngine;
import org.jaxws.stub2html.view.freemarker.ClasspathFreemarkerWebServiceDisplayEngine;
import org.jaxws.stub2html.view.freemarker.FreemarkerWebServiceDisplayEngine;
import org.jaxws.wsdl2bytecodes.model.ByteCodePackage;
import org.jaxws.wsdl2bytecodes.service.Wsdl2ByteCodes;
import org.jaxws.wsdl2bytecodes.service.WsdlImportException;
/**
*
* @author chenjianjx
*
*/
public class Wsdl2Html {
public static String generateHtml(String byteCodesDirParent, String wsdlUrl, WebServiceDisplayEngine displayEngine, boolean isDebug) throws WsdlImportException {
ByteCodePackage byteCodePackage = Wsdl2ByteCodes.generate(byteCodesDirParent, wsdlUrl, isDebug);
Class<?> webServiceClass = getWebServiceClass(byteCodePackage);
WebServiceStubSet serviceStubSet = WebServiceStubSetFactory.createWebServiceStubSet(webServiceClass);
return displayEngine.displayWebSerivce(serviceStubSet);
}
/**
*
*
*
* @param wsdlUrl
* @param isDebug
* @return
* @throws WsdlImportException
*/
public static String generateHtml(String wsdlUrl, boolean isDebug) throws WsdlImportException {
FreemarkerWebServiceDisplayEngine displayEngine = ClasspathFreemarkerWebServiceDisplayEngine.createEngine();
String byteCodesDirParent = System.getProperty("java.io.tmpdir") + "/wsdl2html";
return generateHtml(byteCodesDirParent, wsdlUrl, displayEngine, isDebug);
}
public static String generateHtml(String wsdlUrl) throws WsdlImportException {
return generateHtml(wsdlUrl, false);
}
private static Class<?> getWebServiceClass(ByteCodePackage byteCodePackage) {
List<Class<?>> allClasses = ByteCodePackageLoadingService.loadAll(byteCodePackage);
for (Class<?> clazz : allClasses) {
if (clazz.isInterface() && clazz.isAnnotationPresent(WebService.class)) {
return clazz;
}
}
throw new IllegalStateException("No WebService Class found ! ");
}
}
|
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 2;
int c = 3;
long iterations = 100000000l;
long start = System.currentTimeMillis();
long end;
float exec_time;
for (int i = 0; i <= iterations; i++)
a += b * 2 + c - i;
end = System.currentTimeMillis();
exec_time = (float)(end - start) / 1000;
System.out.println("Java: " + exec_time + " seconds");
}
}
|
package com.beike.dao.CodeOperator;
import java.util.Map;
/**
* 发码商品质信息接口
* @author yurenli
*
*/
public interface CodeOperatorConfigureDao {
public Map<String,String> findProductNumByGoodsId(Long goodsId,String apiType);
}
|
/*
* Copyright 2017 Lantrack Corporation All Rights Reserved.
*
* The source code contained or described herein and all documents related to
* the source code ("Material") are owned by Lantrack Corporation or its suppliers
* or licensors. Title to the Material remains with Lantrack Corporation or its
* suppliers and licensors. The Material contains trade secrets and proprietary
* and confidential information of Lantrack or its suppliers and licensors. The
* Material is protected by worldwide copyright and trade secret laws and
* treaty provisions.
* No part of the Material may be used, copied, reproduced, modified, published
* , uploaded, posted, transmitted, distributed, or disclosed in any way
* without Lantrack's prior express written permission.
*
* No license under any patent, copyright, trade secret or other intellectual
* property right is granted to or conferred upon you by disclosure or delivery
* of the Materials, either expressly, by implication, inducement, estoppel or
* otherwise. Any license under such intellectual property rights must be
* express and approved by Intel in writing.
*
*/
package net.lantrack.project.base.service.impl;
import net.lantrack.framework.sysbase.dao.SysDictDao;
import net.lantrack.framework.sysbase.model.dict.DictModel;
import net.lantrack.project.base.service.DictBaseService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 基础字典等接口的管理
* 2018年3月27日
* @author lin
*/
@Service
public class DictBaseServiceImpl implements DictBaseService {
protected Logger logger = (Logger) LogManager.getLogger(DictBaseServiceImpl.class);
@Autowired
private SysDictDao sysDictDao;
@Override
public List<DictModel> queryDictByTypeAndDepart(String dictType, Integer depart) {
if(StringUtils.isBlank(dictType)||depart==null){
return null;
}
try {
return this.sysDictDao.getDictByTypeAndPid(dictType, depart);
} catch (Exception e) {
e.printStackTrace();
this.logger.error("queryDictByTypeAndDepart ERROR:dictType:{},depart:{},errMsg:{}"
,dictType,depart,e.getMessage());
return null;
}
}
@Override
public Map<String, String> queryDictMapByTypeAndDepart(String dictType, Integer depart) {
List<DictModel> list = queryDictByTypeAndDepart(dictType,depart);
Map<String, String> map = new HashMap<>();
if(list==null) {
return map;
}
for(DictModel dict:list) {
map.put(dict.getId(), dict.getValue());
}
return map;
}
}
|
package com.letscrawl.base.db.redis;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Component;
import com.letscrawl.base.bean.AbstractObject;
import com.letscrawl.base.bean.Crawler;
@Component
public class RedisMethods extends AbstractObject {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@EnableConnectionFailureRetryOnRedis
public <T> void pushToQueue(String queueKey, T objectToPush) {
redisTemplate.opsForList().leftPush(queueKey, objectToPush);
}
@EnableConnectionFailureRetryOnRedis
public <T> T popFromQueue(String queueKey, Class<T> requiredType) {
return requiredType.cast(redisTemplate.opsForList().rightPop(queueKey));
}
@EnableConnectionFailureRetryOnRedis
public <T> T blockPopAndPush(String srcQueueKey, String destQueueKey,
Class<T> requiredType) {
return requiredType.cast(redisTemplate.opsForList()
.rightPopAndLeftPush(srcQueueKey, destQueueKey, 0,
TimeUnit.MILLISECONDS));
}
@EnableConnectionFailureRetryOnRedis
public <T> void removeFromQueue(String queueKey, T objectToRemove) {
redisTemplate.opsForList().remove(queueKey, 0, objectToRemove);
}
@EnableConnectionFailureRetryOnRedis
public long getQueueSize(String queueKey) {
return redisTemplate.opsForList().size(queueKey);
}
@EnableConnectionFailureRetryOnRedis
public <T> void addToSet(String setKey, T objectToAdd) {
redisTemplate.opsForSet().add(setKey, objectToAdd);
}
@EnableConnectionFailureRetryOnRedis
public void renameKey(String oldKey, String newKey) {
redisTemplate.rename(oldKey, newKey);
}
@EnableConnectionFailureRetryOnRedis
public void acquireLock(String lockKey) {
BoundValueOperations<String, Object> lockOperations = redisTemplate
.boundValueOps(lockKey);
boolean success = false;
do {
Long currentTime = new Date().getTime();
if (!lockOperations.setIfAbsent(currentTime)) {
Long startTime1 = (Long) lockOperations.get();
if (startTime1 == null) {
continue;
}
// 重试直到获取同步锁或者超时为止
while (!lockOperations.setIfAbsent(currentTime)
&& currentTime - startTime1 < Crawler.NEXT_DEPTH_URL_QUEUE_LOCK_TIMEOUT_MILLISECOND) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
logger.error("Thread.sleep(long)执行失败", e);
}
currentTime = new Date().getTime();
}
// 判断同步锁是否超时
if (currentTime - startTime1 >= Crawler.NEXT_DEPTH_URL_QUEUE_LOCK_TIMEOUT_MILLISECOND) {
logger.info("同步锁超时");
Long startTime2 = (Long) lockOperations
.getAndSet(currentTime);
if (startTime2 == null || startTime1.equals(startTime2)) {
success = true;
}
} else {
success = true;
}
} else {
success = true;
}
} while (!success);
}
@EnableConnectionFailureRetryOnRedis
public void releaseLock(String lockKey) {
redisTemplate.delete(lockKey);
}
@EnableConnectionFailureRetryOnRedis
public <T> boolean isContainedInSet(String setKey, T objectToDetermine) {
return redisTemplate.opsForSet().isMember(setKey, objectToDetermine);
}
@EnableConnectionFailureRetryOnRedis
public boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
@EnableConnectionFailureRetryOnRedis
public <T> Object executeSessionCallback(SessionCallback<T> session) {
return redisTemplate.execute(session);
}
@EnableConnectionFailureRetryOnRedis
public void expire(String key, long timeout, TimeUnit timeUnit) {
redisTemplate.expire(key, timeout, timeUnit);
}
@EnableConnectionFailureRetryOnRedis
public <T> boolean setValueIfAbsent(String key, T value) {
return redisTemplate.opsForValue().setIfAbsent(key, value);
}
@EnableConnectionFailureRetryOnRedis
public <T> T getValue(String key, Class<T> requiredType) {
return requiredType.cast(redisTemplate.opsForValue().get(key));
}
@EnableConnectionFailureRetryOnRedis
public void deleteKey(String key) {
redisTemplate.delete(key);
}
}
|
package com.soft1841.timer;
import javax.swing.*;
import java.awt.*;
public class DrawCircleFrame extends JFrame {
private JTextArea textArea;
private JScrollPane scrollPane;
public DrawCircleFrame(){
init();
setTitle("绘制随机大小同心圆");
setExtendedState(MAXIMIZED_BOTH);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public void init(){
textArea = new JTextArea();
textArea.setSize(500,600);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
scrollPane = new JScrollPane(textArea);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setOpaque(false);
add(scrollPane, BorderLayout.EAST);
scrollPane.setBounds(0,0,500,600);
DrawCircleThread dt = new DrawCircleThread();
dt.setjFrame(this);
Thread thread1 = new Thread(dt);
thread1.start();
TxtThread t = new TxtThread();
t.setTextArea(textArea);
Thread thread2 = new Thread(t);
thread2.start();
}
public static void main(String[] args) {
new DrawCircleFrame();
}
}
|
package com.marketplace.service;
import com.marketplace.dto.AuthDto;
import com.marketplace.repository.AdminRepository;
import com.marketplace.security.UserPrinciple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
AdminRepository adminRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Optional<AuthDto> optionalAuthDto = adminRepository.getByEmailWithPasswordAndRole(email);
// Optional<Admin> optionalAdmin = adminRepository.findByEmail(email);
if (optionalAuthDto.isPresent()) {
return UserPrinciple.build(optionalAuthDto.get());
} throw new UsernameNotFoundException("No User found with email: " + email);
}
}
|
package com.jacksonsmolenko.iwmy.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.jacksonsmolenko.iwmy.ImageManager;
import com.jacksonsmolenko.iwmy.R;
import com.jacksonsmolenko.iwmy.cooltools.CoolFragmentManager;
import com.jacksonsmolenko.iwmy.cooltools.CoolRecyclerAdapter;
import com.jacksonsmolenko.iwmy.fragments.user.EventDetailsFragment;
import com.oleksiykovtun.iwmy.speeddating.data.Event;
import java.util.List;
public class EventRecyclerAdapter extends CoolRecyclerAdapter {
private boolean showCity = false;
public EventRecyclerAdapter(List dataSet) {
super(dataSet);
}
public EventRecyclerAdapter(List dataSet, boolean showCity) {
super(dataSet);
this.showCity = showCity;
}
public class ViewHolder extends CoolRecyclerAdapter.ViewHolder {
public TextView nameAndAgeTextView;
public TextView dateTextView;
public TextView descriptionView;
public ImageView photoImageView;
public Button details;
public ViewHolder(View view) {
super(view);
nameAndAgeTextView = (TextView) view.findViewById(R.id.label_event_organizer_and_place);
dateTextView = (TextView) view.findViewById(R.id.label_event_time);
descriptionView = (TextView) view.findViewById(R.id.label_event_description);
photoImageView = (ImageView) view.findViewById(R.id.event_photo);
details = (Button) view.findViewById(R.id.details_button);
}
}
// TODO delete this one :)
@Override
public int getItemCount(){
return 3;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(
LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_event_list_item, parent, false));
}
@Override
public void onBindViewHolder(CoolRecyclerAdapter.ViewHolder holder, int position) {
((ViewHolder)holder).details.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CoolFragmentManager.showAtTop(new EventDetailsFragment());
}
});
// Event event = (Event) (dataSet.get(position));
// ((ViewHolder) holder).nameAndAgeTextView.setText(event.getPlace() + " ("
// + event.getMinAllowedAge() + " - " + event.getMaxAllowedAge() + ")");
// ((ViewHolder) holder).dateTextView.setText(event.getTime()
// + ((showCity && !event.getCity().isEmpty()) ? (" / " + event.getCity()) : ""));
// ((ViewHolder) holder).descriptionView.setText(event.getDescription());
// ImageManager.setEventThumbnail(((ViewHolder) holder).photoImageView, event.getThumbnail());
// ((ViewHolder) holder).details.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// CoolFragmentManager.showAtTop(new EventDetailsFragment());
// }
// });
}
}
|
package firstDuck.behavior;
/**
* description
*
* @author 金聖聰
* @version v1.0
* @email jinshengcong@163.com
*/
public interface IQuackBehavior {
/**
* 叫
*
* @return void
* @author 金聖聰
* @email jinshengcong@163.com
* @version v1.0
* @date 2021/01/13 23:11
*/
void quack();
}
|
package school.lemon.changerequest.java.banking.impl;
public enum OperationType {
WITHDRAW,
DEPOSIT,
ADD_INTEREST,
SET_RATE
}
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class ListMenu {
Scanner scanner = new Scanner(System.in);
NhanVien nv;
HanhChinh hc;
TiepThi tt;
TruongPhong tp;
ArrayList<NhanVien> arr = new ArrayList<>();
public void menu() {
do {
System.out.println("MENU");
System.out.println("1. Nhập thông tin nhân viên từ bàn phím");
System.out.println("2. Xuât thông tin tất cả nhân viên");
System.out.println("3. Tìm thông tin nhân viên theo mã nhân viên");
System.out.println("4. Xóa nhân viên theo mã nhân viên");
System.out.println("5. Cập nhật thông tin nhân viên theo mã nhân viên");
System.out.println("6. Tìm nhân viên theo khoảng lương");
System.out.println("7. Sắp xếp nhân viên theo họ và tên");
System.out.println("8. Sắp xếp nhân viên theo thu nhập");
System.out.println("9. Xuất 5 nhân viên có thu nhập cao nhất");
System.out.println("0. exit");
System.out.println("-------------------------------------------");
int choose = scanner.nextInt();
switch(choose)
{
case 1:
add();
break;
case 2:
show();
break;
case 3:
find();
break;
case 4:
delete();
break;
case 5:
update();
break;
case 6:
findBySalary();
break;
case 7:
sortByName();
break;
case 8:
sortBySalary();
break;
case 9:
top();
break;
case 0:
System.exit(0);
default:
break;
}
}while(true);
}
private void add() {
boolean flag1 = false, flag2 = false;
do {
System.out.println("Nhập chức vụ nhân viên cần thêm:");
System.out.println("1. Nhân Viên Hành Chính");
System.out.println("2. Nhân Viên Tiếp Thị");
System.out.println("3. Trưởng Phòng");
int chon = scanner.nextInt();
if(chon == 1) {
hc = new HanhChinh();
hc.nhap();
for(NhanVien x : arr) {
if(hc.id == x.id) {
System.out.println("Id Nhân Viên Bị Trùng Lặp, Vui Lòng Bắt Đầu Lại");
System.out.println("..............................................");
flag2=true;
}
}
if(flag2 == false) {
hc.ten = hc.ten.trim();
hc.ten = hc.ten.replaceAll("\\s+", " ");
hc.ten =hc.ten.substring(0,1).toUpperCase() + hc.ten.substring(1).toLowerCase();
String temp[] = hc.ten.split(" ");
String hoTen="";
for (int i = 0; i < temp.length; i++) {
hoTen += String.valueOf(temp[i].charAt(0)).toUpperCase() + temp[i].substring(1);
if (i < temp.length - 1)
hoTen += " ";
}
hc.ten=hoTen;
arr.add(hc);
}
}else if(chon == 2) {
tt = new TiepThi();
tt.nhap();
for(NhanVien x : arr) {
if(tt.id == x.id) {
System.out.println("Id Nhân Viên Bị Trùng Lặp, Vui Lòng Bắt Đầu Lại");
System.out.println("..............................................");
flag2=true;
}
}
if(flag2 == false) {
arr.add(tt);
}
}else if(chon == 3){
tp = new TruongPhong();
tp.nhap();
for(NhanVien x : arr) {
if(tp.id == x.id) {
System.out.println("Id Nhân Viên Bị Trùng Lặp, Vui Lòng Bắt Đầu Lại");
System.out.println("..............................................");
flag2=true;
}
}
if(flag2 == false) {
arr.add(tp);
}
}else {
System.out.println("Vui Lòng Chọn Chính Xác");
flag1 = true;
}
}while(flag1);
}
private void show() {
for(NhanVien x: arr) {
x.xuat();
}
}
private void find() {
boolean find = false, flag = false;
do {
System.out.println("Vui lòng nhập mã nhân viên cần hiển thị:");
int id =scanner.nextInt();
for(NhanVien x: arr) {
if(x.id == id) {
x.xuat();
flag = true;
}
}
if(flag == false) {
System.out.println("Mã Nhân Viên Không Chính Xác");
System.out.println("Bạn có muốn thử lại: 1. Có -- 2. Về Menu");
int thulai = scanner.nextInt();
if(thulai == 1) {
find = true;
}else {
find=false;
}
}
}while(find);
}
private void delete() {
boolean delete = false, flag = false;
do {
System.out.println("Vui lòng nhập mã nhân viên cần xóa:");
int id =scanner.nextInt();
for(NhanVien x: arr) {
if(x.id == id) {
x.xuat();
System.out.println("Bạn có chắc chắc muốn xóa nhân viên này không: nhấn 1 để xác nhận");
int xoa = scanner.nextInt();
if(xoa == 1) {
arr.remove(x);
}else {
delete = false;
}
flag = true;
}
}
if(flag == false) {
System.out.println("Mã Nhân Viên Không Chính Xác");
System.out.println("Bạn có muốn thử lại: 1. Có -- 2. Về Menu");
int thulai = scanner.nextInt();
if(thulai == 1) {
delete = true;
}else {
delete=false;
}
}
}while(delete);
}
private void update() {
boolean update = false, flag = false;
do {
System.out.println("Vui lòng nhập mã nhân viên cần hiển thị:");
int id =scanner.nextInt();
for(NhanVien x: arr) {
if(x.id == id) {
x.xuat();
x.nhap();
flag = true;
}
}
if(flag == false) {
System.out.println("Mã Nhân Viên Không Chính Xác");
System.out.println("Bạn có muốn thử lại: 1. Có -- 2. Về Menu");
int thulai = scanner.nextInt();
if(thulai == 1) {
update = true;
}else {
update=false;
}
}
}while(update);
}
private void findBySalary() {
System.out.println("Nhập Khoảng Lương Cần Tìm:");
System.out.println("Từ: ");
double luongTu = Double.parseDouble(scanner.nextLine());
System.out.println("Đến: ");
double luongDen = Double.parseDouble(scanner.nextLine());
for( NhanVien x: arr) {
if(x.thuNhap >= luongTu && x.thueThuNhap <= luongDen) {
x.xuat();
}
}
}
private void sortByName() {
Collections.sort(arr, new Comparator<NhanVien>() {
@Override
public int compare(NhanVien nv1, NhanVien nv2) {
return (nv1.ten.compareTo(nv2.ten));
}
});
}
private void sortBySalary() {
Collections.sort(arr, new Comparator<NhanVien>() {
@Override
public int compare(NhanVien nv1, NhanVien nv2) {
if (nv1.thuNhap < nv2.thuNhap) {
return -1;
} else {
if (nv2.thuNhap == nv2.thuNhap) {
return 0;
} else {
return 1;
}
}
}
});
}
private void top() {
sortBySalary();
int count = 0;
for(NhanVien x: arr) {
count+=1;
if(count<=5) {
x.xuat();
}
}
}
}
|
/*
* 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 fiuba.algo3.modelo;
import java.util.ArrayList ;
import fiuba.algo3.modelo.SuperposicionEventoException ;
/**
*
* @author brahvic
*/
public class ContenedorDeEventos {
private ArrayList<Evento> misEventos ;
public ContenedorDeEventos(){
this.misEventos = new ArrayList();
}
public boolean existeEventoEnFecha(int anio, int mes, int dia, int hora) {
return this.misEventos.contains(new Evento(anio,mes,dia,hora));
}
public void agregarEvento(String nombreEvento, int anio, int mes, int dia, int hora) throws SuperposicionEventoException {
if (existeEventoEnFecha(anio,mes,dia,hora)){
throw new SuperposicionEventoException() ;
}else{
this.misEventos.add(new Evento(nombreEvento,anio,mes,dia,hora));
}
}
public void agregarEvento(int semanasRepeticion, String nombreEvento, int anio, int mes, int dia, int hora) throws SuperposicionEventoException {
while (semanasRepeticion>0){
this.agregarEvento(nombreEvento, anio, mes, dia+(7*(semanasRepeticion-1)), hora);
semanasRepeticion = semanasRepeticion-1;
}
}
}
|
package com.example.push.controller;
import com.example.push.mapper.SysUserMapper;
import com.example.push.model.SysUser;
import com.example.push.model.view.SysUserVo;
import com.example.push.util.CheckUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
/**
* @author: Farben
* @description: LoginController 系统登录页面
* @create: 2019/8/30-13:36
**/
@Controller
public class LoginController extends BaseController{
private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
@Autowired
SysUserMapper sysUserMapper;
/**
* 跳转到login页面
*
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login() {
ModelAndView view = new ModelAndView("login");
return view;
}
/**
* 跳转到index页面
*
* @return
*/
@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView index() {
Subject subject = SecurityUtils.getSubject();
//查询用户信息
String loginName=(String) subject.getPrincipal();
Integer sysId= (Integer) SecurityUtils.getSubject().getSession().getAttribute("sysId");
String chinaName= (String) SecurityUtils.getSubject().getSession().getAttribute("chinaName");
String departName= (String) SecurityUtils.getSubject().getSession().getAttribute("departName");
//非匿名登录条件下,sysId为空需要查询数据库更新数据
if(CheckUtil.isEmpty(sysId)&&!CheckUtil.isEmpty(loginName)){
SysUserVo user =sysUserMapper.selectVoByLoginName(loginName);
sysId=user.getId();
chinaName=user.getChinaName();
departName=user.getDepartName();
SecurityUtils.getSubject().getSession().setAttribute("sysId",sysId);
SecurityUtils.getSubject().getSession().setAttribute("chinaName",chinaName);
SecurityUtils.getSubject().getSession().setAttribute("department",user.getDepartment());
SecurityUtils.getSubject().getSession().setAttribute("departName",departName);
SecurityUtils.getSubject().getSession().setAttribute("sysToken",user.getSysToken());
}
ModelAndView view = new ModelAndView("index");
view.addObject("loginName", loginName);
view.addObject("chinaName", chinaName);
view.addObject("departName", departName);
return view;
}
/**
* 用户登录
*
* @param request
* @param loginName
* @param passWord
* @param captcha
* @param model
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginUser(HttpServletRequest request, String loginName, String passWord, boolean rememberMe, String captcha, Model model) {
//如果有点击 记住我
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginName, passWord, rememberMe);
//UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
Subject subject = SecurityUtils.getSubject();
try {
//登录操作
subject.login(usernamePasswordToken);
return "redirect:index";
} catch (Exception e) {
//登录失败从request中获取shiro处理的异常信息 shiroLoginFailure:就是shiro异常类的全类名
String exception = (String) request.getAttribute("shiroLoginFailure");
String msg=exception;
if (e instanceof UnknownAccountException) {
msg="用户名或密码错误!";
model.addAttribute("msg", msg);
}
if (e instanceof IncorrectCredentialsException) {
msg="用户名或密码错误!";
model.addAttribute("msg", msg);
}
if (e instanceof LockedAccountException) {
msg="账号已被锁定,请联系管理员!";
model.addAttribute("msg", msg);
}
logger.info("登录系统错误,登录名:{},错误原因:{}", loginName, msg);
//返回登录页面
return "login";
}
}
}
|
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.converter;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.util.MimeTypeUtils;
/**
* A {@link MessageConverter} that supports MIME type "application/octet-stream" with the
* payload converted to and from a byte[].
*
* @author Rossen Stoyanchev
* @since 4.0
*/
public class ByteArrayMessageConverter extends AbstractMessageConverter {
public ByteArrayMessageConverter() {
super(MimeTypeUtils.APPLICATION_OCTET_STREAM);
}
@Override
protected boolean supports(Class<?> clazz) {
return (byte[].class == clazz);
}
@Override
@Nullable
protected Object convertFromInternal(
Message<?> message, @Nullable Class<?> targetClass, @Nullable Object conversionHint) {
return message.getPayload();
}
@Override
@Nullable
protected Object convertToInternal(
Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) {
return payload;
}
}
|
public class Solution{
//method one
public static int multiply1(int x,int y){
int smaller = x>y?y:x;
int bigger = smaller==x?y:x;
HashMap<Integer,Integer> cache = new HashMap<>();
return divide1(smaller,bigger,cache);
}
private static int divide1(int x,int y,HashMap<Integer,Integer> cache){
if(x==0){return 0;}
if(x==1){return y;}
if(cache.containsKey(x)){return cache.get(x);}
int mid = x>>1;
int res = divide1(mid,y) + divide1(x-mid,y);
cache.put(x,res);
return res;
}
//method two
public static int multiply2(int x,int y){
int smaller = x>y?y:x;
int bigger = smaller==x?y:x;
return divide(smaller,bigger);
}
private static int divide2(int x,int y){
if(x==0){return 0;}
if(x==1){return y;}
int mid = x>>1;
int first = divide2(mid,y);
int second = 0;
if(x%2==0){
second = first;
}else{
second = first + y;
}
return first + second;
}
}
|
package com.github.yangxy81118.loghunter.distribute.bean;
public class ActionConstraints {
public static final int ACTION_REGISTER = 100;
public static final int ACTION_LOG_CONFIG_EDIT = 1000;
public static final int RESPONSE_OK = 200;
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class bj10828 {
public static int[] stack;
public static int size=0;
public static void main(String[] args) throws IOException{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(br.readLine());
StringTokenizer st;
StringBuilder sb = new StringBuilder();
stack=new int[n];
for(int i=0;i<n;i++){
st=new StringTokenizer(br.readLine()," ");
switch(st.nextToken()){
case "push":
stack[size]=Integer.parseInt(st.nextToken());
size++;
break;
case "pop":
if(size == 0) {
sb.append(-1).append('\n');
}
else {
sb.append(stack[size - 1]).append('\n');
stack[size - 1] = 0;
size--;
}
break;
case "size":
sb.append(size).append('\n');
break;
case "empty":
if(size==0){
sb.append(1).append('\n');
}
else{
sb.append(0).append('\n');
}
break;
case "top":
if(size==0){
sb.append(-1).append('\n');
}
else{
sb.append(stack[size-1]).append('\n');
}
break;
}
}
System.out.println(sb);
}
}
|
/**
*
*/
package br.com.lucro.manager.dao;
import br.com.lucro.manager.model.FileOperationResumeCielo;
/**
* @author "Georjuan Taylor"
*
*/
public interface FileOperationResumeCieloDAO extends CRUD<FileOperationResumeCielo> {
}
|
package com.herve.recycleview_demo;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Herve on 2016/01/07.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private Context context;
private int count = 0;
private OnItemClicklistener onItemClicklistener;
private List<Integer> Data = new ArrayList();
public MyAdapter(Context context) {
this.context = context;
}
public void setCount(int count) {
this.count = count;
}
public int getCount() {
return count;
}
public void setData(ArrayList<Integer> Data) {
this.Data = Data;
}
public void addAllData(ArrayList<Integer> Data) {
Data.addAll(Data);
}
@Override
public int getItemCount() {
return Data.size();
}
public void insertData(int data) {
this.Data.add(data);
}
public void deleteData(int location) {
Data.remove(location);
}
public void deleteAllData() {
Data = new ArrayList();
}
public void removeAll() {
Data.removeAll(Data);
}
public interface OnItemClicklistener {
void onItemClickListener(View view, int position);
}
public void setOnItemClicklistener(OnItemClicklistener onItemClicklistener) {
this.onItemClicklistener = onItemClicklistener;
Log.i("Herve不应该啊", "setOnItemClicklistener: ");
}
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(final MyAdapter.ViewHolder holder, final int position) {
//加载地三个位置的Imageview为查看更多
if (position == 3) {
Glide.with(context).load(R.mipmap.community_details_more_selected_touch).into(holder.imageView);
} else {
Glide.with(context).load(R.mipmap.image2).into(holder.imageView);
}
//如果点击了某个,则触发回调函数
if (onItemClicklistener != null) {
holder.imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClicklistener.onItemClickListener(holder.imageView, position);
}
});
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private FrameLayout frameLayout01;
public ViewHolder(View v) {
super(v);
imageView = (ImageView) v.findViewById(R.id.iv_film_logo);
frameLayout01 = (FrameLayout) v.findViewById(R.id.frameLayout01);
}
}
}
|
package kr.co.shop.batch.order.model.master;
import kr.co.shop.batch.order.model.master.base.BaseOcOrderZeroBankbookFailureDetails;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Data
public class OcOrderZeroBankbookFailureDetails extends BaseOcOrderZeroBankbookFailureDetails {
}
|
import java.util.Scanner;
public class M6_1Exception {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
String[] categories = {"PCs", "Notebooks", "Tablets", "Phones", "Аccessories"};
scanner.close();
try {
System.out.println(categories[choice]);
} catch(Exception e) {
System.out.println("Wrong option");
}
}
}
|
package dev.liambloom.softwareEngineering.chapter4;
public class Exercises {
public static void main (String[] args) {
exercise21(500);
}
public static double exercise1 (int n) {
// There's probably a formula for this, but I don't know it
double total = 0;
for (double i = 1; i <= n; i++) {
total += 1 / i;
}
return total;
}
public static String exercise2 (String str, int repititions) {
String returnValue = "";
for (int i = 0; i < repititions; i++) {
returnValue += str;
}
return returnValue;
}
public static String exercise3 (int month, int day) {
double date = month + day / 100;
if (date > 3.16 && date < 6.15) return "spring";
else if (date > 6.16 && date < 9.15) return "summer";
else if (date > 9.16 && date < 9.15) return "fall";
else return "winter";
}
public static final int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static int exercise4 (int month) {
return daysInMonth[month];
}
public static int exercise5 (int base, int exponent) {
return (int) Math.pow(base, exponent);
}
public static void exercise6 (int min, int max) {
for (int i = min; i <= max; i++) {
System.out.print(i + " ");
}
System.out.println();
}
public static void exercise7 (int size) {
//System.out.println("Exercise 7")
final double CENTER = (size - 1) / 2.0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < -Math.abs(i - CENTER) + CENTER; j++) System.out.print("o");
System.out.print("x");
for (int j = 0; j < 2 * Math.abs(i - CENTER) - 1; j++) System.out.print("o");
if (size % 2 == 0 || i != CENTER) System.out.print("x");
for (int j = 0; j < -Math.abs(i - CENTER) + CENTER; j++) System.out.print("o");
System.out.println();
}
System.out.println();
}
public static void exercise8 () {
Ask.seperator = '?';
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int nums = Ask.forInt("How many numbers do you want to enter");
for (int i = 0; i < nums; i++) {
int next = Ask.forInt("Number " + (i + 1));
min = Math.min(min, next);
max = Math.max(max, next);
}
System.out.printf("Smallest = %d\n", min);
System.out.printf("Largest = %d\n", max);
}
public static void exercise9 () {
Ask.seperator = '?';
int sum = 0;
int max = Integer.MIN_VALUE;
int nums = Ask.forInt("How many integers");
for (int i = 0; i < nums; i++) {
int next = Ask.forInt("Next integer");
if (next % 2 == 0) {
sum += next;
max = Math.max(max, next);
}
}
System.out.printf("Even sum = %d, Even max = %d\n", sum, max);
}
public static void exercise10 () {
Ask.seperator = ':';
Ask.prompt("Enter a student record");
String name = Ask.console.next();
int grades = Ask.console.nextInt();
double average = 0;
for (int i = 0; i < grades; i++) {
average += Ask.console.nextDouble() / grades;
}
Ask.console.nextLine();
System.out.printf("%s's grade is ", name);
System.out.println(average); // IDK why putting it in using "%f" adds "0"s
}
public static void exercise10Better () { // This version does not require you to say how many grades you're inputing, it works regardless
Ask.seperator = ':';
String[] grades = Ask.forString("Enter a student record").split(" ");
double average = 0;
for (int i = 1; i < grades.length; i++) {
average += Double.parseDouble(grades[i]) / (grades.length - 1);
}
System.out.printf("%s's grade is %f", grades[0], average);
}
public static void exercise11 (int names) {
String longest = "";
for (int i = 1; i <= names; i++) {
String name = Ask.forToken("Name #" + i);
if (longest.length() < name.length()) longest = name;
}
System.out.printf("%s's name is longest", longest.toUpperCase().charAt(0) + longest.substring(1).toLowerCase());
}
public static String exercise12 (int a, int b, int c) {
if (a == b && b == c) return "equilateral";
else if (a == b || b == c || a == c) return "isoceles";
else return "scaline";
}
public static double exercise13 (int ...nums) {
double total = 0;
for (int i = 0; i < nums.length; i++) total += nums[i];
return total / nums.length;
}
public static double exercise14 (int base, int exponent) {
return Math.pow(base, exponent);
}
public static double exercise15 (int grade) {
if (grade < 60) return 0.0;
else if (grade >= 60 && grade <= 62) return 0.7;
else if (grade >= 95) return 4.0;
else return (double) grade / 10 - 5.5;
}
public static void exercise16 () {
Ask.seperator = ':';
String str = Ask.forToken("Enter a word").toLowerCase();
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) reversed += str.charAt(i);
if (str.equals(reversed)) System.out.println("It's a palendrome");
else System.out.println("It's not a palendrome");
}
public static String exercise17 (String str) {
String reversed = "";
for (int i = 0; i < str.length() / 2; i++) {
reversed += str.charAt(2 * i + 1);
reversed += str.charAt(2 * i);
}
if (str.length() % 2 != 0) reversed += str.charAt(str.length() - 1);
return reversed;
}
public static int exercise18 (String str) {
boolean inword = false;
int wordcount = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') inword = false;
else if (!inword) {
inword = true;
wordcount++;
}
}
return wordcount;
}
public static int exercise19 (double x, double y) {
if (x == 0 || y == 0) throw new IllegalArgumentException("The point (" + x + ", " + y + ") is not in any quadrant");
if (x > 0) {
if (y > 0) return 1;
else return 4;
}
else {
if (y > 0) return 2;
else return 3;
}
}
public static int exercise20 (int a, int b, int c) { // I don't know if this is the intended behaviour, the for is confusing
int unique = 3;
if (a == b) unique--;
if (a == c || b == c) unique--;
return unique;
}
public static void exercise21 (int max) {
String perfect = "";
for (int i = 1; i <= max; i++) {
int sumOfFactors = 0;
for (int j = 1; j <= i / 2; j++) if (i % j == 0) sumOfFactors += j;
if (sumOfFactors == i) perfect += i + " ";
}
System.out.printf("Perfect number up to %d: %s%n", max, perfect);
}
}
|
package assignment6;
/**
* @author Jamie Lewis
*
*/
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// create Person objects
Person person1 = new Person("Jamie", "Lewis");
Person person2 = new Person("Jamie", "Lewis");
Person person3 = new Person(person1);
//compare Person objects using == and .equals()
if(person1 == person2) {
System.out.println("person1 is equal to person2 using the == test");
} else {
System.out.println("person1 and person2 are not equal using the == test");
}
if(person1.equals(person2)) {
System.out.println("person1 is equal to person2 using the equals() method");
} else {
System.out.println("person1 and person2 are not equal using the equals() method");
}
if(person1.equals(person3)) {
System.out.println("person1 is equal to person3 using the equals() method");
} else {
System.out.println("person1 and person3 are not equal using the equals() method");
}
// print Person objects using .toString()
System.out.println("person1 is " + person1.toString());
System.out.println("person2 is " + person2.toString());
System.out.println("person3 is " + person3.toString());
}
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge;
import java.util.List;
/**
* <a href="http://oj.leetcode.com/problems/4sum/">4Sum</a>
* <p/>
* Copyright 2013 LeetCode
* <p/>
* Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all
* unique quadruplets in the array which gives the sum of target.
* <p/>
* Note:
* <p/>
* Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ? b ? c ? d)
* The solution set must not contain duplicate quadruplets.
* For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
* <p/>
* A solution set is:
* (-1, 0, 0, 1)
* (-2, -1, 1, 2)
* (-2, 0, 0, 2)
* <p/>
*
* @see <a href="http://discuss.leetcode.com/questions/199/4sum">Leetcode discussion</a>
*/
public interface FourSum {
List<List<Integer>> fourSum(int[] num, int target);
}
|
package com.test.hello;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/**
* @author bianxh
* 程序入口
* 任务核心算法见 Dijkstra 类,本任务的主要思路是先求得任一节点A到其他节点B(也可以是出发节点A)的最小路径集合Set(最小路径指路径中除了起止节点之外,中间不包括重复站点)。
* 用出发点和终止节点、出发点和终止点距离、出发点和终止点的节点数目进行约束,计算出目标结果。
* 计算方法是:由最短路径集合Set发起自由组合(核心思想逐条遍历路径,然后在路径的任何一个节点C上,从上面的Set中截取C出发并且截止到C节点的循环路径,并且匹配终止节点,循环插入,得到符合条件的路径集合.
* 本题目#6 #7 #10计算的路径结果就暂存在sPathSet中.
*/
public class Main {
private static Dijkstra sDijkstra = null; // 算法类
private static String sStationStr = ""; // 站点String(包含所有站点)
public static Map<String,Integer> sAllRouteMapFromStart = new HashMap<String,Integer>();//封装从出发点计算,所有最短路径的路线和距离
static ArrayList<String> nodeDistanceList = new ArrayList<String>(); // 站点以及距离集信息存放
private static HashSet<String> sPathSet = new HashSet<String>(); // 存放跟进条件检索出来的路径信息
// 初始化路径和距离信息,格式(起点+终点+距离)
private static String[] nodeRouteStr = new String[]{
"AB5",
"BC4",
"CD8",
"DC8",
"DE6",
"AD5",
"CE2",
"EB3",
"AE7"
};
public static void main(String[] args) {
initData(); // 数据和变量初始化,必须调用
// 1.The distance of the route A-B-C.
// Output #1: 9
System.out.println("Output #1:" + Utils.getRouteDistance("A-B-C", nodeRouteStr));
//2. The distance of the route A-D.
//Output #2: 5
System.out.println("Output #2:" + Utils.getRouteDistance("A-D", nodeRouteStr));
//3. The distance of the route A-D-C.
//Output #3: 13
System.out.println("Output #3:" + Utils.getRouteDistance("A-D-C", nodeRouteStr));
//4. The distance of the route A-E-B-C-D.
//Output #4: 22
System.out.println("Output #4:" + Utils.getRouteDistance("A-E-B-C-D", nodeRouteStr));
//5. The distance of the route A-E-D.
//Output #5: NO SUCH ROUTE
System.out.println("Output #5:" + Utils.getRouteDistance("A-E-D", nodeRouteStr));
//6. The number of trips starting at C and ending at C with a maximum of 3 stops. In the sample data below, there are two such trips: C-D-C (2 stops). and C-E-B-C (3 stops).
//Output #6: 2
sPathSet.clear();
sPathSet = computeAllPossiblyPath("C", "C", 3 + 1); // 途径3个站点,实际上总共4个站点
System.out.println("Output #6:" + sPathSet.size());
// sPathSet = computeAllPossiblyPath("A", "C", 5);
// 7. The number of trips starting at A and ending at C with exactly 4 stops. In the sample data below, there are three such trips: A to C (via B,C,D); A to C (via D,C,D); and A to C (via D,E,B).
// Output #7: 3
sPathSet.clear();
sPathSet = computeAllPossiblyPath("A", "C", 4 + 1, true); // 途径4个站点,实际上总共5个站点
System.out.println("Output #7:" + sPathSet.size());
// 8. The length of the shortest route (in terms of distance to travel) from A to C.
// Output #8: 9
ArrayList<String> strList = computePathFromStartToEnd("A", "C");
int minDistance = Integer.MAX_VALUE;
for (String str : strList) {
int dis = Integer.parseInt(Utils.getRouteDistance(str, nodeRouteStr));
if (minDistance > dis) {
minDistance = dis;
}
}
System.out.println("Output #8:" + minDistance);
// 9. The length of the shortest route (in terms of distance to travel) from B to B.
// Output #9: 9
strList.clear();
strList = computePathFromStartToEnd("B", "B");
minDistance = Integer.MAX_VALUE;
for (String str : strList) {
int dis = Integer.parseInt(Utils.getRouteDistance(str, nodeRouteStr));
if (minDistance > dis) {
minDistance = dis;
}
}
System.out.println("Output #9:" + minDistance);
// 10. The number of different routes from C to C with a distance of less than 30. In the sample data, the trips are: CDC, CEBC, CEBCDC, CDCEBC, CDEBC, CEBCEBC, CEBCEBCEBC.
// Output #10: 7
sPathSet.clear();
sPathSet = computeDistance("C", "C", 30);
System.out.println("Output #10:" + sPathSet.size());
}
/**
* 数据及变量初始化
*/
private static void initData() {
// 计算站点
sStationStr = computeStationStr(nodeRouteStr);
// System.out.println("station:" + sStationStr);
// 站点距离信息数组转换为List
for(String nodeInfo : nodeRouteStr) {
nodeDistanceList.add(nodeInfo);
}
// 计算以每一个station为起点,到其他每一个station的最短路径
sDijkstra=new Dijkstra();
for(int index = 0; index < sStationStr.length(); index ++) {
computeRouteFromStartNode(String.valueOf(sStationStr.charAt(index)));
}
// for(String path : sAllRouteMapFromStart.keySet()) {
// System.out.println("录入新路径:{" + path + " : " + sAllRouteMapFromStart.get(path) + "}");
// }
}
/**
* 获取起点到终点,距离小于maxDistance的所有路径
* @param startNodeName
* @param endNodeName
* @param maxDistance
* @return
*/
private static HashSet<String> computeDistance(String startNodeName, String endNodeName, int maxDistance) {
HashSet<String> pathSet = new HashSet<String>();
// Note: 需要设置上限,在这里使用maxDistance来限定index不太合理,需要继续优化
for(int index = 0; index < maxDistance; index ++) {
if (pathSet != null) {
pathSet.clear();
}
HashSet<String> allPossiblyPathSet = computeAllPossiblyPath(startNodeName, endNodeName, index);
if (allPossiblyPathSet != null && allPossiblyPathSet.size() > 0) {
for (String path : allPossiblyPathSet) {
String disStr = Utils.getRouteDistance(path, nodeRouteStr);
int pathDistance = -1;
try {
pathDistance = Integer.parseInt(disStr);
} catch (Exception e) {
// TODO: handle exception
}
if (pathDistance >= 0 && pathDistance < maxDistance) {
pathSet.add(path);
}
}
}
}
// if (pathSet != null && pathSet.size() > 0) {
// for (String path : pathSet) {
// System.out.println("pathSetDistance:{" + path + ":" + Utils.getRouteDistance(path, nodeRouteStr) + "}");
// }
// }
return pathSet;
}
/**
* 计算起点到终点所有可能符合约束条件的路径集合,约束条件(是否精确计算路径中的站点+路径中的站点数目)
* @param startNodeName 起点
* @param endNodeName 终点
* @param nodeSize 站点数目要求,返回nodeSize以内的路径
* @return 符合条件的路径结果集合
*/
private static HashSet<String> computeAllPossiblyPath(String startNodeName, String endNodeName, int nodeSize) {
return computeAllPossiblyPath(startNodeName, endNodeName, nodeSize, false);
}
/**
* 计算起点到终点所有可能符合约束条件的路径集合,约束条件(是否精确计算路径中的站点+路径中的站点数目)
* @param startNodeName 起点
* @param endNodeName 终点
* @param nodeSize 站点数目要求
* @param isReturnExactlyByNodeSize 是否精确返回匹配站点数目的路径结果, 如果为false,则返回nodeSize以内的路径
* @return 符合条件的路径结果集合
*/
private static HashSet<String> computeAllPossiblyPath(String startNodeName, String endNodeName, int nodeSize, boolean isReturnExactlyByNodeSize) {
if (nodeSize < 1) {
return null;
}
HashSet<String> pathSet = new HashSet<String>();
// 计算起点到终点的所有路径,除了起点之外,路径中没有重复站点
// String startStation = "A";
// String endStation = "C";
ArrayList<String> returnList = computePathFromStartToEnd(startNodeName, endNodeName);
// 计算起点到终点的所有路径,路径中间可以无限循环,用站点数目进行约束
// final int STATIONMAXNUM = 5;
for (String path : returnList) {
HashSet<String> tmpPathSet = getPath(path, nodeSize);
if (pathSet != null && tmpPathSet != null) {
pathSet.addAll(tmpPathSet);
}
}
ArrayList<String> toRemoveFromSet = new ArrayList<String>();
// 计算需要remove的路径
for (String str : pathSet) {
// 如果要求精确返回,就从set中移除掉站点数和要求不一致的数据
if (isReturnExactlyByNodeSize && (str.length() != nodeSize)) {
toRemoveFromSet.add(str);
}
}
// pathSet执行remove操作
for (String str : toRemoveFromSet) {
pathSet.remove(str);
}
// // 打印最终的路径结果集
// for (String str : pathSet) {
// System.out.println("pathSet:{" + str + "}");
// }
return pathSet;
}
// private static String pathStart = "";
/**
* 获取起点到终点的所有可能路径(站点数目限制)
* @param srcPath 起点到终点的站点路径
* @param stationSize 限制的站点数目
* @return srcPath路径下遍历出来的在限制站点数目内的路径集合
*/
private static HashSet<String> getPath(String srcPath, int stationSize) {
HashSet<String> pathSet = new HashSet<String>(); // 存放最终输出的路径信息
String pathStart = ""; // 暂时存放检索的路径
srcPath = srcPath.replace("->", "");
int insertNum = stationSize - srcPath.length(); // 可以插入的站点数目
if (insertNum < 0) {
return null;
}
if (insertNum == 0) { // 如果没有可以插入的,直接返回原数据
pathSet.add(srcPath);
}
for(int index = 0; index < srcPath.length(); index++) { // 获取每个重复站点的路径
String station = srcPath.substring(index, index +1);
ArrayList<String> list = computePathFromStartToEnd(station, station);
// System.out.println("srcPath0:{" + srcPath + "}"); // 不插入本身算一条路径
// 插入起点和终点都为当前站点的多条路径
for(String insert : list) {
insert = insert.replace("->", "");
int stationIndex = srcPath.lastIndexOf(station); // 重复站点插入到站点序列最后一个位置
String endStation = srcPath.substring(srcPath.length() - 1);
// 插入的途径点中包含目的站点,途径目的站点为目的
if (insert.indexOf(endStation) != -1) {
String tmpInsert = insert;
// 计算insert起点到最后一个结束站点
int end = tmpInsert.lastIndexOf(endStation);
tmpInsert = tmpInsert.substring(0, end + 1);
// 计算插入多少次可以不越界
int insertNum1 = (stationSize - srcPath.substring(0, stationIndex).length()) / tmpInsert.length();
// 循环插入途径路径
for (int index0 = 0; index0 < insertNum1; index0 ++) {
String tmpStr = tmpInsert;
if (index0 >= 1) {
// 判断临时插入的末尾节点下是否包含起始节点,如果包含,则可以循环插入
boolean isTmpInsertEndNodeContainsStartNode = MapBuilder.isContainsChild(tmpInsert.substring(tmpInsert.length() - 1), tmpInsert.substring(0, 1));
if (isTmpInsertEndNodeContainsStartNode) {
for (int index1 = 0; index1 < index0; index1 ++) {
tmpStr += tmpInsert;
}
}
}
pathStart = srcPath.substring(0, stationIndex) + tmpStr;
// System.out.println("pathStart:{" + pathStart + "}");
pathSet.add(pathStart);
}
}
// 插入的途径站点中没有目的站点,正常插入
// 计算插入多少次可以不越界
int insertNum2 = (stationSize - srcPath.substring(0, stationIndex).length() - srcPath.substring(stationIndex + 1, srcPath.length()).length()) / insert.length();
// 循环插入途径路径
for (int index0 = 0; index0 < insertNum2; index0 ++) {
String tmpStr = insert;
if (index0 >= 1) {
// 判断临时插入的末尾节点下是否包含起始节点,如果包含,则可以循环插入
boolean isTmpInsertEndNodeContainsStartNode = MapBuilder.isContainsChild(insert.substring(insert.length() - 1), insert.substring(0, 1));
if (isTmpInsertEndNodeContainsStartNode) {
for (int index1 = 0; index1 < index0; index1 ++) {
tmpStr += insert;
}
}
}
pathStart = srcPath.substring(0, stationIndex) + tmpStr + srcPath.substring(stationIndex + 1, srcPath.length());
// System.out.println("pathStart1:{" + pathStart + "}");
pathSet.add(pathStart);
}
}
}
return pathSet;
}
/**
* 计算起点到终点的最短路径,包含所有途径站点,除了起点之外,路径中没有重复的站点
*/
private static ArrayList<String> computePathFromStartToEnd(String start, String end) {
ArrayList<String> returnList = new ArrayList<String>();
ArrayList<String> routeListFromStart = getRouteList(start);
// 计算起点到终点的途径站点
int size = routeListFromStart.size();
String[] arr = (String[])routeListFromStart.toArray(new String[size]);
String viaWay = computeStationStr(arr); // 途径站点
viaWay = viaWay.replace(start, "");
// System.out.println("viaWay :{" + viaWay + "}");
// 获取途径站点到start的可能路径, 殊途同归
for(int index = 0; index < viaWay.length(); index ++) {
returnList.addAll(getViaStationBackStartStion(start, end, String.valueOf(viaWay.charAt(index))));
}
// 删除重复元素
for(int i=0;i<returnList.size();i++){
for(int j=i+1;j<returnList.size();j++){
if(returnList.get(i).equals(returnList.get(j))){ //String值相等,则删除
returnList.remove(j);
}
}
}
// System.out.println("returnList: " + returnList);
return returnList;
}
/**
* 获取start站点经由途径站点viaStation,到end站点的路径
* 计算起点到终点的最短路径,包含单一途径站点
* @param startStation
* @param viaStation
* @param routeListFromStart
*/
private static ArrayList<String> getViaStationBackStartStion(String startStation, String endStation, String viaStation) {
ArrayList<String> returnList = new ArrayList<String>();
// 起始点到途径点的路线
ArrayList<String> routeListFromStartToVia = getRouteList(startStation, viaStation);
// 途经点到终点的路线
ArrayList<String> routeListFromViaToEnd = getRouteList(viaStation, endStation);
// 如果路线可以走通
if((routeListFromStartToVia != null && routeListFromStartToVia.size() > 0)
&& (routeListFromViaToEnd != null && routeListFromViaToEnd.size() > 0)) {
for (String path0 : routeListFromStartToVia) {
for (String path1 : routeListFromViaToEnd) {
// System.out.println("match {" + path0 + " : " + path1 + "}");
path1 = path1.replace(viaStation, ""); // 删掉途径站点
returnList.add(path0 + path1);
}
}
}
return returnList;
}
/**
* 获取起点对应的路径列表
* @param startStation
*/
private static ArrayList<String> getRouteList(String startStation) {
ArrayList<String> routeList = new ArrayList<String>();
for(String path : sAllRouteMapFromStart.keySet()) {
// 获取起始站点最短路径对应的终点列表
if (path.startsWith(startStation)) {
routeList.add(path);
// System.out.println("routeList add:{" + path + "}");
}
}
return routeList;
}
/**
* 获取起点和终点对应的路径列表
* @param startStation
*/
private static ArrayList<String> getRouteList(String startStation, String endStation) {
ArrayList<String> routeList = new ArrayList<String>();
for(String path : sAllRouteMapFromStart.keySet()) {
// 获取起始站点最短路径对应的终点列表
if (path.startsWith(startStation) && path.endsWith(endStation)) {
routeList.add(path);
// System.out.println("routeList1 add:{" + path + "}");
}
}
return routeList;
}
private static String computeStationStr(String[] nodeRouteStr) {
String returnStr = ""; // 存放站点集合
for (String str : nodeRouteStr) { // 拆分到每一条路线输入
for (char ch : str.toCharArray()) {
if ((ch <= 'Z' && ch >= 'A')) { //找到站点,以单个字母为判断标准
if (returnStr.indexOf(String.valueOf(ch)) == -1) { // 站点String(包含所有站点)是否包含当前站点
returnStr += String.valueOf(ch);
}
}
}
}
return returnStr;
}
/**
* 计算以startNodeName为起点,到每一个node的最短路径
* @param startNodeName
*/
private static void computeRouteFromStartNode(String startNodeName) {
Node start=sDijkstra.init(startNodeName, nodeDistanceList);
sDijkstra.computePath(start);
Map<String,Integer> currentRouteMapFromStart = sDijkstra.printPathInfo();
sAllRouteMapFromStart.putAll(currentRouteMapFromStart);
currentRouteMapFromStart.clear();
currentRouteMapFromStart = null;
}
}
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xeonqi.com.ece150;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.ChannelListener;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.xeonqi.com.ece150.DeviceListFragment.DeviceActionListener;
/**
* An activity that uses WiFi Direct APIs to discover and connect with available
* devices. WiFi Direct APIs are asynchronous and rely on callback mechanism
* using interfaces to notify the application of operation success or failure.
* The application should also register a BroadcastReceiver for notification of
* WiFi state related events.
*/
public class WiFiDirectActivity extends Activity implements ChannelListener, DeviceActionListener, SensorEventListener {
public static final String TAG = "HW3-Wifi-direct";
private WifiP2pManager mManager;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;
private final IntentFilter intentFilter = new IntentFilter();
private Channel mChannel;
private BroadcastReceiver mReceiver = null;
// private SensorManager sensorManager;
static final int SHAKE_THRESHOLD = 18;
static int conn_flag = 0;
private SensorManager mSensorManager;
private float mAccel; // acceleration apart from gravity
private float mAccelCurrent; // current acceleration including gravity
private float mAccelLast; // last acceleration including gravity
/**
* @param isWifiP2pEnabled the isWifiP2pEnabled to set
*/
public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
this.isWifiP2pEnabled = isWifiP2pEnabled;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* get Sensor Events */
final DeviceListFragment listFragment = (DeviceListFragment) getFragmentManager().findFragmentById(R.id.frag_list);
// final DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager().findFragmentById(R.id.frag_detail);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
/* get P2P Events */
// Indicates a change in the Wi-Fi P2P status.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
// Indicates a change in the list of available peers.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
// Indicates the state of Wi-Fi P2P connectivity has changed.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
// Indicates this device's details have changed.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
// mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
// @Override
// public void onSuccess() {
// // Code for when the discovery initiation is successful goes here.
// // No services have actually been discovered yet, so this method
// // can often be left blank. Code for peer discovery goes in the
// // onReceive method, detailed below.
// Toast toast = Toast.makeText(getApplicationContext(), "Discover devices successfully.", Toast.LENGTH_LONG);
// toast.show();
// }
// @Override
// public void onFailure(int reasonCode) {
// // Code for when the discovery initiation fails goes here.
// // Alert the user that something went wrong.
// Toast toast = Toast.makeText(getApplicationContext(), "Failed to discover devices.", Toast.LENGTH_LONG);
// toast.show();
// }
// });
}
@Override
public void onSensorChanged(SensorEvent se) {
// float x = se.values[0];
// float y = se.values[1];
// float z = se.values[2];
// mAccelLast = mAccelCurrent;
// mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
// float delta = mAccelCurrent - mAccelLast;
// mAccel = mAccel * 0.9f + delta; // perform low-cut filter
//
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void connectChosen(){
if (!isWifiP2pEnabled) Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning, Toast.LENGTH_SHORT).show();
else {
final DeviceListFragment listFragment = (DeviceListFragment) getFragmentManager().findFragmentById(R.id.frag_list);
listFragment.onInitiateDiscovery();
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode, Toast.LENGTH_SHORT).show();
}
});
}
}
private final SensorEventListener mSensorListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
float x = se.values[0];
float y = se.values[1];
float z = se.values[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta; // perform low-cut filter
if (mAccel > 12) {
Toast toast = Toast.makeText(getApplicationContext(), "Device has shaken.", Toast.LENGTH_LONG);
toast.show();
connectChosen();
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
final DeviceListFragment listFragment = (DeviceListFragment) getFragmentManager().findFragmentById(R.id.frag_list);
final DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager().findFragmentById(R.id.frag_detail);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
/** register the BroadcastReceiver with the intent values to be matched */
registerReceiver(mReceiver, intentFilter);
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
/** register the BroadcastReceiver with the intent values to be matched */
mSensorManager.unregisterListener(mSensorListener);
}
/**
* Remove all peers and clear all fields. This is called on
* BroadcastReceiver receiving a state change event.
*/
public void resetData() {
final DeviceListFragment listFragment = (DeviceListFragment) getFragmentManager().findFragmentById(R.id.frag_list);
final DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager().findFragmentById(R.id.frag_detail);
if (listFragment != null) {
listFragment.clearPeers();
}
if (fragmentDetails != null) {
fragmentDetails.resetViews();
}
}
@Override
public void showDetails(WifiP2pDevice device) {
final DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager().findFragmentById(R.id.frag_detail);
fragmentDetails.showDetails(device);
}
@Override
public void connect(WifiP2pConfig config) {
// TODO: this part may need some coding
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Connection succeeded.", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int reason) {
Toast.makeText(WiFiDirectActivity.this, "Connection failed.", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void disconnect() {
// TODO: this part may need some coding
final DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager().findFragmentById(R.id.frag_detail);
fragmentDetails.resetViews();
mManager.removeGroup(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this, "Disconnection failed.", Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess() {
fragmentDetails.getView().setVisibility(View.GONE);
}
});
}
@Override
public void onChannelDisconnected() {
// TODO: this part may need some coding
if (mManager != null && !retryChannel) {
Toast.makeText(this, "Channel lost.", Toast.LENGTH_LONG).show();
resetData();
retryChannel = true;
mManager.initialize(this, getMainLooper(), this);
} else Toast.makeText(this, "Channel lost permanently, probably. Try Disable/Re-Enable P2P.", Toast.LENGTH_LONG).show();
}
@Override
public void cancelDisconnect() {
// TODO: this part may need some coding
if (mManager != null) {
final DeviceListFragment listFragment = (DeviceListFragment) getFragmentManager().findFragmentById(R.id.frag_list);
if (listFragment.getDevice() == null
|| listFragment.getDevice().status == WifiP2pDevice.CONNECTED) {
disconnect();
} else if (listFragment.getDevice().status == WifiP2pDevice.AVAILABLE || listFragment.getDevice().status == WifiP2pDevice.INVITED) {
mManager.cancelConnect(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Connection cancelled", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this, "Connection cancelling failed. Error Code: " + reasonCode, Toast.LENGTH_SHORT).show();
}
});
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_items, menu);
return true;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.atn_direct_enable:
if (mManager != null && mChannel != null) {
// Since this is the system wireless settings activity, it's
// not going to send us a result. We will be notified by
// WiFiDeviceBroadcastReceiver instead.
startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
} else {
Log.e(TAG, "channel or manager is null");
}
return true;
case R.id.atn_direct_discover:
if (!isWifiP2pEnabled) {
Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning,
Toast.LENGTH_SHORT).show();
return true;
}
final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
fragment.onInitiateDiscovery();
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode, Toast.LENGTH_SHORT).show();
}
});
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
/**
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or distribute
* this software, either in source code form or as a compiled binary, for any
* purpose, commercial or non-commercial, and by any means.
*
* In jurisdictions that recognize copyright laws, the author or authors of this
* software dedicate any and all copyright interest in the software to the
* public domain. We make this dedication for the benefit of the public at large
* and to the detriment of our heirs and successors. We intend this dedication
* to be an overt act of relinquishment in perpetuity of all present and future
* rights to this software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to [http://unlicense.org]
*/
package ch.bfh.bti7301.w2013.battleship.game.players;
import ch.bfh.bti7301.w2013.battleship.game.Coordinates;
import ch.bfh.bti7301.w2013.battleship.game.Missile.MissileState;
import ch.bfh.bti7301.w2013.battleship.game.Game;
import ch.bfh.bti7301.w2013.battleship.game.Missile;
import ch.bfh.bti7301.w2013.battleship.game.Player;
import ch.bfh.bti7301.w2013.battleship.game.Ship;
import ch.bfh.bti7301.w2013.battleship.network.Connection;
/**
* @author simon
*
*/
public class LocalPlayer extends GenericPlayer {
@Override
public Missile placeMissile(Missile m) {
// Do some sanity checks
if (!playerBoard.withinBoard(m.getCoordinates())) {
throw new RuntimeException(
"Coordinates of missile not within board!");
}
if (m.getMissileState() != MissileState.FIRED) {
throw new RuntimeException("Missle has state "
+ m.getMissileState() + ", needs to be FIRED!");
}
for (Ship s : playerBoard.getPlacedShips()) {
for (Coordinates c : s.getCoordinatesForShip()) {
if (c.equals(m.getCoordinates())) {
// It's a hit!
s.setDamage(m.getCoordinates());
if (s.isSunk()) {
m.setMissileState(MissileState.SUNK);
m.setSunkShip(s);
if (playerBoard.checkAllShipsSunk()) {
m.setMissileState(MissileState.GAME_WON);
}
} else {
m.setMissileState(MissileState.HIT);
}
getBoard().placeMissile(m);
return m;
}
}
}
m.setMissileState(MissileState.MISS);
getBoard().placeMissile(m);
return m;
}
@Override
public void setPlayerState(PlayerState status) {
// Prevent infinite loops:
if (status == getPlayerState()
// Also, for test cases where we connect the client to itself:
|| (status == PlayerState.GAME_WON && getPlayerState() == PlayerState.GAME_LOST)
|| (status == PlayerState.GAME_LOST && getPlayerState() == PlayerState.GAME_WON))
return;
// This occurs when the player presses "ready" and the opponents is already "ready"
Player opponent = Game.getInstance().getOpponent();
if (status == PlayerState.READY
&& opponent.getPlayerState() == PlayerState.READY) {
status = PlayerState.WAITING;
opponent.setPlayerState(PlayerState.PLAYING);
}
super.setPlayerState(status);
Connection.getInstance().sendStatus(status);
}
}
|
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
/**
* Response written from {@code @ResponseBody} method.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
class ResponseBodyTests {
@Test
void json() throws Exception {
standaloneSetup(new PersonController()).defaultResponseCharacterEncoding(UTF_8).build()
// We use a name containing an umlaut to test UTF-8 encoding for the request and the response.
.perform(get("/person/Jürgen").characterEncoding(UTF_8).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(content().encoding(UTF_8))
.andExpect(content().string(containsString("Jürgen")))
.andExpect(jsonPath("$.name").value("Jürgen"))
.andExpect(jsonPath("$.age").value(42))
.andExpect(jsonPath("$.age").value(42.0f))
.andExpect(jsonPath("$.age").value(equalTo(42)))
.andExpect(jsonPath("$.age").value(equalTo(42.0f), Float.class))
.andExpect(jsonPath("$.age", equalTo(42)))
.andExpect(jsonPath("$.age", equalTo(42.0f), Float.class));
}
@RestController
private static class PersonController {
@GetMapping("/person/{name}")
Person get(@PathVariable String name) {
Person person = new Person(name);
person.setAge(42);
return person;
}
}
@SuppressWarnings("unused")
private static class Person {
private final String name;
private int age;
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
}
}
|
package com.example.ethereum.DTO;
public class ContractCreationDto {
private String creator;
private String coach;
private String coachee;
public ContractCreationDto(String creator, String coach, String coachee){
this.creator=creator;
this.coach=coach;
this.coachee=coachee;
}
public ContractCreationDto(){}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getCoach() {
return coach;
}
public void setCoach(String coach) {
this.coach = coach;
}
public String getCoachee() {
return coachee;
}
public void setCoachee(String coachee) {
this.coachee = coachee;
}
}
|
import org.junit.*;
import static org.junit.Assert.*;
import org.fluentlenium.adapter.FluentTest;
import org.junit.ClassRule;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
public class AppTest extends FluentTest {
public WebDriver webDriver = new HtmlUnitDriver();
public WebDriver getDefaultDriver() {
return webDriver;
}
@ClassRule
public static ServerRule server = new ServerRule();
@Test
public void checkAllergyCounter_1_Eggs() {
Allergies testApp = new Allergies();
ArrayList<String> arrayTest = new ArrayList<String>();
arrayTest.add("eggs");
assertEquals(arrayTest, testApp.checkAllergy(1));
}
@Test
public void checkAllergyCounter_2_Peanuts() {
Allergies testApp = new Allergies();
ArrayList<String> arrayTest = new ArrayList<String>();
arrayTest.add("peanuts");
assertEquals(arrayTest, testApp.checkAllergy(2));
}
}
|
package com.leo_sanchez.columbiatennisladder.Login;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;
import com.leo_sanchez.columbiatennisladder.ApplicationLogic.AccountLogic;
import com.leo_sanchez.columbiatennisladder.ApplicationLogic.IAccountLogic;
import com.leo_sanchez.columbiatennisladder.Main.MainActivity;
import com.leo_sanchez.columbiatennisladder.Models.AuthenticationResult;
import com.leo_sanchez.columbiatennisladder.R;
public class LoginActivity extends AppCompatActivity {
IAccountLogic accountLogic;
public LoginActivity(){
//TODO: Research Depenency Injection on Android...
this.accountLogic = new AccountLogic();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
protected void authenticate(View view){
closeKeyboard(view);
String email = ((TextView) findViewById(R.id.userName)).getText().toString();
String password = ((TextView) findViewById(R.id.etPassword)).getText().toString();
if(email.isEmpty()|| email == null || password.isEmpty() || password == null){
Toast.makeText(getApplicationContext(), "Please enter your information", Toast.LENGTH_SHORT).show();
return;
}
AuthenticationResult authenticationResult = new AuthenticationResult();
try{
authenticationResult = accountLogic.LogIn(email, password);
}
catch(Exception exception) {
//TODO: Research exception handling and login.
}
if(authenticationResult.isAuthenticated == false){
handleErrorAuthentication(authenticationResult);
} else {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
}
private void closeKeyboard(View view){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
private void handleErrorAuthentication(AuthenticationResult authenticationResult) {
Toast.makeText(getApplicationContext(), authenticationResult.errorMessage, Toast.LENGTH_LONG).show();
}
}
|
package DesignPattern.Decorator;
public class Haircut extends Decorator {
public Haircut(Modeling model) {
super(model);
System.out.println("haircut cost 500 USD");
setPrice(500f);
// TODO Auto-generated constructor stub
}
}
|
/*
* Copyright (c) 2017-2020 Peter G. Horvath, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.blausql;
import com.github.blausql.core.util.TextUtils;
import com.github.blausql.ui.components.WaitDialog;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.googlecode.lanterna.TerminalFacade;
import com.googlecode.lanterna.gui.Action;
import com.googlecode.lanterna.gui.GUIScreen;
import com.googlecode.lanterna.gui.Window;
import com.googlecode.lanterna.gui.dialog.DialogButtons;
import com.googlecode.lanterna.gui.dialog.DialogResult;
import com.googlecode.lanterna.gui.dialog.MessageBox;
import com.googlecode.lanterna.gui.dialog.TextInputDialog;
import com.googlecode.lanterna.terminal.TerminalSize;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
//CHECKSTYLE.OFF: FinalClass: must be extensible for the testing frameworks
public class TerminalUI {
private static final int LINE_SIZE_DIFF = 8;
private TerminalUI() {
// no instances
}
private static GUIScreen getGUIScreen() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
static final GUIScreen INSTANCE = TerminalFacade.createGUIScreen();
}
public static void init() {
getGUIScreen().getScreen().startScreen();
}
static void close() {
getGUIScreen().getScreen().stopScreen();
}
public static void showErrorMessageFromThrowable(Throwable throwable) {
StringBuilder sb = new StringBuilder();
final Throwable rootCause = Throwables.getRootCause(throwable);
if (rootCause instanceof ClassNotFoundException) {
sb.append("Class not found: ").append(rootCause.getMessage());
} else if (throwable instanceof SQLException) {
sb.append(extractMessageFrom(throwable));
} else {
String rootCauseMessage = extractMessageFrom(rootCause);
if (!Strings.isNullOrEmpty(rootCauseMessage)) {
sb.append(rootCauseMessage);
} else {
Throwable t = throwable;
while (t != null) {
String extractedMessage = extractMessageFrom(t);
if (!extractedMessage.isEmpty()) {
if (sb.length() > 0) {
sb.append(": ");
}
sb.append(extractedMessage);
}
t = t.getCause();
}
StringWriter stringWriter = new StringWriter();
try (PrintWriter pw = new PrintWriter(stringWriter)) {
rootCause.printStackTrace(pw);
}
String fullStackTrace = stringWriter.toString();
sb.append(fullStackTrace);
}
}
String theString = sb.toString();
showErrorMessageFromString(theString);
}
public static void showErrorMessageFromString(String errorMessage) {
showErrorMessageFromString("Error", errorMessage);
}
public static void showErrorMessageFromString(String dialogTitle, String errorMessage) {
final int columns = getGUIScreen().getScreen().getTerminalSize().getColumns();
final int maxLineLen = columns - LINE_SIZE_DIFF;
String multilineErrorMsgString = TextUtils.breakLine(errorMessage, maxLineLen);
MessageBox.showMessageBox(getGUIScreen(), dialogTitle, multilineErrorMsgString);
}
public static String extractMessageFrom(Throwable t) {
StringBuilder sb = new StringBuilder();
if (t instanceof SQLException) {
SQLException sqlEx = (SQLException) t;
String sqlState = sqlEx.getSQLState();
if (!Strings.isNullOrEmpty(sqlState)) {
sb.append("SQLState: ").append(sqlState)
.append(TextUtils.LINE_SEPARATOR);
}
int errorCode = sqlEx.getErrorCode();
sb.append("Error Code: ").append(errorCode)
.append(TextUtils.LINE_SEPARATOR);
}
String localizedMessage = t.getLocalizedMessage();
String message = t.getMessage();
if (localizedMessage != null && !"".equals(localizedMessage)) {
sb.append(localizedMessage);
} else if (message != null && !"".equals(message)) {
sb.append(message);
}
String throwableAsString = sb.toString();
return throwableAsString.trim();
}
public static void showMessageBox(String title, String messageText) {
MessageBox.showMessageBox(getGUIScreen(), title, messageText);
}
public static DialogResult showMessageBox(String title,
String message, DialogButtons buttons) {
return MessageBox.showMessageBox(getGUIScreen(), title, message, buttons);
}
public static String showTextInputDialog(
final String title, final String description, final String initialText, final int textBoxWidth) {
return TextInputDialog.showTextInputBox(getGUIScreen(), title, description, initialText, textBoxWidth);
}
public static void showWindowCenter(Window w) {
getGUIScreen().showWindow(w, GUIScreen.Position.CENTER);
}
public static void showWindowFullScreen(Window w) {
getGUIScreen().showWindow(w, GUIScreen.Position.FULL_SCREEN);
}
public static Window showWaitDialog(String title, String text) {
return showWaitDialog(title, text, null);
}
public static Window showWaitDialog(String title, String text, Action onCancel) {
final Window w = new WaitDialog(title, text, onCancel);
getGUIScreen().runInEventThread(new Action() {
public void doAction() {
showWindowCenter(w);
}
});
return w;
}
public static void runInEventThread(Action action) {
getGUIScreen().runInEventThread(action);
}
public static TerminalSize getTerminalSize() {
return getGUIScreen().getScreen().getTerminalSize();
}
}
//CHECKSTYLE.ON
|
package com.sohu.live56.view.main.player;
import com.sohu.live56.view.BaseFragment;
/**
* Created by jingbiaowang on 2015/8/14.
* 直播事件。
*/
public interface LiveEvent extends BasePlayEvent {
public void onPrepareLive(String roomName);
public void puaseLive();
void onRegistSuccess();
void onResiterFailure(String msg);
}
interface BasePlayEvent extends BaseFragment.OnFragmentInteractionListener {
public void stopVideo();
public void onLiveLoading();
public void onLiveLoaded();
}
|
package demo;
import model.Game;
import ui.elements.Label;
import java.awt.*;
public class FrameCounter extends Label {
int frame = 1;
long last = System.currentTimeMillis();
Game game;
public FrameCounter(int x, int y, Game aGame) {
super("" + 1, x, y);
game = aGame;
}
@Override
public void draw(Graphics2D g) {
super.draw(g);
this.frame = (frame % this.game.getFps()) + 1;
this.setText("Frame: " + frame);
}
}
|
package lib.basenet.utils;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by zhaoyu1 on 2017/3/9.
*/
public final class FileUtils {
public static final void saveFile(InputStream is, File file) throws IOException {
InputStream inputStream = is;
if (null != inputStream) {
FileOutputStream fos = null;
int len = 0;
try {
byte[] bys = new byte[4 * 1024];
fos = new FileOutputStream(file);
while ((len = inputStream.read(bys)) != -1) {
fos.write(bys, 0, len);
}
fos.flush();
} finally {
if (fos != null) {
fos.close();
}
}
}
}
public static final void saveFile(byte[] bytes, File file) throws IOException {
if (bytes != null) {
FileOutputStream fos = new FileOutputStream(file);
//byte[] bys = new byte[4 * 1024];
fos.write(bytes);
fos.flush();
fos.close();
}
}
public static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
if(TextUtils.isEmpty(type)) {
type = "application/octet-stream";
}
return type;
}
public static void deleteFile(String path) {
File file = new File(path);
if(file.exists()) {
file.delete();
}
}
}
|
import java.util.ArrayList;
public class ArrayListMethodclearcontains {
public static void main(String () args){
/* clear
This method will remove all elements in the ArrayList.
Methode signature is as follow:
void clear()
*/
List<String> flag = new ArrayList<>();
flag.add ("Tonga");
flag.add ("Canada");
flag.add ("Slovenia");
flag.add ("Benin");
flag.add ("Mongolia");
flag.add ("Bolivia");
System.out.println(flag.size());
// Size will be 6.
flag.clear;
// This will remove all the flags.
System.out.println(flag.size());
// Outcome will be 0.
/* contains
This method is looking for the exact value in the ArrayList.
Method signature is as follow:
boolean contains(Object object)
*/
List<String> state = new ArrayList<>();
state.add ("South Australia");
state.add ("Northern Territory");
state.add ("Tasmania");
System.out.println(state.contains("Queensland"));
// Outcome will be false because Queensland is not in the list
System.out.println(state.contains("Tasmania"));
// Outcome will be true because Tasmania is in the list.
}
}
|
package com.codigo.smartstore.webapi.controllers;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.codigo.smartstore.webapi.SmartstoreWebapiApplication;
@RestController
public class RestartController {
@PostMapping("/restart")
public void restart() {
SmartstoreWebapiApplication.restart();
}
}
|
package online.lahloba.www.lahloba.data.model.vm_helper;
import android.graphics.Bitmap;
import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;
import online.lahloba.www.lahloba.BR;
import online.lahloba.www.lahloba.data.model.ProductItem;
public class SellerAddProductHelper extends BaseObservable {
int error = 0;
String categoryId;
Bitmap myBitmap;
public String fStepEnName;
public String fStepArName;
public String fStepPrice;
public SellerAddProductHelper() {
}
public Bitmap getMyBitmap() {
return myBitmap;
}
public void setMyBitmap(Bitmap myBitmap) {
this.myBitmap = myBitmap;
}
@Bindable
public String getfStepEnName() {
return fStepEnName;
}
@Bindable
public void setfStepEnName(String fStepEnName) {
this.fStepEnName = fStepEnName;
notifyPropertyChanged(BR.fStepEnName);
}
@Bindable
public String getfStepArName() {
return fStepArName;
}
@Bindable
public void setfStepArName(String fStepArName) {
this.fStepArName = fStepArName;
notifyPropertyChanged(BR.fStepArName);
}
@Bindable
public String getfStepPrice() {
return fStepPrice;
}
@Bindable
public void setfStepPrice(String fStepPrice) {
this.fStepPrice = fStepPrice;
notifyPropertyChanged(BR.fStepPrice);
}
@Bindable
public int getError() {
return error;
}
@Bindable
public void setError(int error) {
this.error = error;
notifyPropertyChanged(BR.error);
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
}
|
package com.example.objectbox.presenter;
import android.app.Activity;
import android.text.TextUtils;
import android.widget.Toast;
import com.example.objectbox.bean.Student;
import com.example.objectbox.bean.Student_;
import com.example.objectbox.bean.Teacher;
import com.example.objectbox.bean.Teacher_;
import com.example.objectbox.util.ObjectBox;
import java.util.List;
import io.objectbox.Box;
import io.objectbox.query.QueryBuilder;
public class ManyToManyPresenter {
private Activity activity;
private final Box<Teacher> teacherBox;
private final Box<Student> studentBox;
public ManyToManyPresenter(Activity activity) {
this.activity = activity;
teacherBox = ObjectBox.get().boxFor(Teacher.class);
studentBox = ObjectBox.get().boxFor(Student.class);
}
/**
* 添加一个老师
* @param rondom_id
* @param teacherName
*/
public List<Teacher> addTeacher(int rondom_id,String teacherId, String teacherName,String studentId) {
Teacher teacher = new Teacher();
teacher.setName(TextUtils.isEmpty(teacherName) ? "老师" + rondom_id + "号" : teacherName);
if (TextUtils.isEmpty(studentId)){
teacherBox.put(teacher);
}else if(!TextUtils.isEmpty(teacherId)&&!TextUtils.isEmpty(studentId)){//若果老师与学生ID不为空 则绑定在一起
Teacher teacher1 = teacherBox.query().equal(Teacher_.id, Long.parseLong(teacherId)).build().findUnique();
Student student = studentBox.query().equal(Student_.id, Long.parseLong(studentId)).build().findUnique();
if(teacher1==null||student==null){
Toast.makeText(activity, "未找到该老师或学生无法绑定一起", Toast.LENGTH_SHORT).show();
}else if(teacher1!=null&&student!=null){
teacher1.students.add(student);
teacherBox.put(teacher1);
}
}else{
Student student = studentBox.query().equal(Student_.id, Long.parseLong(studentId)).build().findUnique();
if (student==null){
Toast.makeText(activity, "未找到该学生", Toast.LENGTH_SHORT).show();
}else{
student.teachers.add(teacher);
studentBox.put(student);
}
}
return queryTeacher("", "");
}
/**
* 删除老师
*
* @param teacherId
* @param teacherName
*/
public List<Teacher> deleteTeacher(String teacherId, String teacherName) {
if (TextUtils.isEmpty(teacherId) && TextUtils.isEmpty(teacherName)) {//删除最后一个老师
List<Teacher> teachers = teacherBox.query().build().find();
if(teachers.size()>0) teacherBox.remove(teachers.get(teachers.size()-1));
} else if (TextUtils.isEmpty(teacherId)) {//删除指定名字
teacherBox.query().equal(Teacher_.name, teacherName).build().remove();
} else if (TextUtils.isEmpty(teacherName)) {//删除指定ID
teacherBox.query().equal(Teacher_.id, Long.parseLong(teacherId)).build().remove();
} else {//删除指定ID与名字
teacherBox.query().equal(Teacher_.id, Long.parseLong(teacherId)).equal(Teacher_.name, teacherName).build().remove();
}
return queryTeacher("", "");
}
/**
* 修改老师名字
*
* @param teacherId
* @param teacherName
*/
public List<Teacher> updateTeacher(String teacherId, String teacherName) {
if (TextUtils.isEmpty(teacherId) && TextUtils.isEmpty(teacherName)) {
Toast.makeText(activity, "请输入要修改的老师ID与修改后的老师昵称", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(teacherId)) {
Toast.makeText(activity, "请输入要修改的老师ID", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(teacherName)) {
Toast.makeText(activity, "请输入修改后的老师昵称", Toast.LENGTH_SHORT).show();
} else {
Teacher unique = teacherBox.query().equal(Teacher_.id, Long.parseLong(teacherId)).build().findUnique();
if(unique==null){
Toast.makeText(activity, "未找到该老师", Toast.LENGTH_SHORT).show();
}else{
unique.setName(teacherName);
teacherBox.put(unique);
}
}
return queryTeacher("", "");
}
/**
* 查询某个老师
*
* @param teacherId
* @param teacherName
*/
public List<Teacher> queryTeacher(String teacherId, String teacherName) {
QueryBuilder<Teacher> query = teacherBox.query();
if (!TextUtils.isEmpty(teacherId) && !TextUtils.isEmpty(teacherName)) {
query.equal(Teacher_.id, Long.parseLong(teacherId)).equal(Teacher_.name, teacherName);
} else if (!TextUtils.isEmpty(teacherId)) {
query.equal(Teacher_.id, Long.parseLong(teacherId));
} else if (!TextUtils.isEmpty(teacherName)) {
query.contains(Teacher_.name, teacherName);
}
return query.build().find();
}
/**
* 添加一个学生
* @param rondom_id
* @param teacherId
* @param studentName
* @return
*/
public List<Student> addStudent(int rondom_id, String teacherId, String studentName,String studentId) {
Student student = new Student();
student.setName(TextUtils.isEmpty(studentName) ? "学生" + rondom_id + "号" : studentName);
if (TextUtils.isEmpty(teacherId)) {//给最后一个老师添加学生
List<Teacher> teachers = teacherBox.query().build().find();
if (teachers.size() > 0) {
Teacher teacher = teachers.get(teachers.size() - 1);
teacher.students.add(student);
teacherBox.put(teacher);
}else{
studentBox.put(student);
}
} else if(!TextUtils.isEmpty(teacherId)&&!TextUtils.isEmpty(studentId)){
Teacher teacher = teacherBox.query().equal(Teacher_.id, Long.parseLong(teacherId)).build().findUnique();
Student student1 = studentBox.query().equal(Student_.id, Long.parseLong(studentId)).build().findUnique();
if(teacher==null||student1==null){
Toast.makeText(activity, "未找到该老师或学生无法绑定一起", Toast.LENGTH_SHORT).show();
}else if(teacher!=null&&student1!=null){
teacher.students.add(student);
teacherBox.put(teacher);
}
}else {//给指定老师添加学生
Teacher unique = teacherBox.query().equal(Teacher_.id, Long.parseLong(teacherId)).build().findUnique();
if(unique!=null){
unique.students.add(student);
teacherBox.put(unique);
}else {
Toast.makeText(activity, "未找到该老师", Toast.LENGTH_SHORT).show();
}
}
return queryStudent(teacherId, null);
}
/**
* 删除一个学生
*
* @param teacherId
* @param studentId
* @param studentName
* @return
*/
public List<Student> deleteStudent(String teacherId, String studentId, String studentName) {
if (TextUtils.isEmpty(teacherId) && TextUtils.isEmpty(studentId) && TextUtils.isEmpty(studentName)) {//删除最后一名学生
List<Student> students = studentBox.query().build().find();
if(students.size()>0) studentBox.remove(students.get(students.size()-1));
} else if (TextUtils.isEmpty(teacherId) && TextUtils.isEmpty(studentId)) {//根据学生昵称删除
studentBox.query().equal(Student_.name, studentName).build().remove();
} else if (TextUtils.isEmpty(teacherId) && TextUtils.isEmpty(studentName)) {//根据学生id删除
studentBox.query().equal(Student_.id, Long.parseLong(studentId)).build().remove();
} else if (TextUtils.isEmpty(teacherId) && TextUtils.isEmpty(studentName)) {//根据老师id删除
QueryBuilder<Student> query = studentBox.query();
query.link(Student_.teachers).equal(Teacher_.id, Long.parseLong(teacherId)).build();
query.build().remove();
} else if (TextUtils.isEmpty(teacherId)) {//根据学生昵称与学生id删除
studentBox.query().equal(Student_.id, Long.parseLong(studentId)).equal(Student_.name, studentName).build().remove();
} else if (TextUtils.isEmpty(studentId)) {//根据老师id 与学生名删除
QueryBuilder<Student> equal = studentBox.query().equal(Student_.name, studentName);
equal.link(Student_.teachers).equal(Teacher_.id, Long.parseLong(teacherId));
equal.build().remove();
} else {//根据老师id与学生id删除
QueryBuilder<Student> equal = studentBox.query().equal(Student_.id, Long.parseLong(studentId));
equal.link(Student_.teachers).equal(Teacher_.id, Long.parseLong(teacherId));
equal.build().remove();
}
return queryStudent(teacherId, null);
}
/**
* 修改学生昵称
*
* @param teacherId
* @param studentId
* @param studentName
* @return
*/
public List<Student> updateStudent(String teacherId, String studentId, String studentName) {
if (TextUtils.isEmpty(studentName)) {
Toast.makeText(activity, "请输入学生昵称", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(teacherId) && TextUtils.isEmpty(studentId)) {
Toast.makeText(activity, "请输入要修改的老师ID或学生ID", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(teacherId)) {
Student unique = studentBox.query().equal(Student_.id, Long.parseLong(studentId)).build().findUnique();
if (unique == null) {
Toast.makeText(activity, "找不到该学生", Toast.LENGTH_SHORT).show();
} else {
unique.setName(studentName);
studentBox.put(unique);
}
} else if (TextUtils.isEmpty(studentId)) {
Toast.makeText(activity, "请输入学生ID", Toast.LENGTH_SHORT).show();
} else {
QueryBuilder<Student> equal = studentBox.query().equal(Student_.id, Long.parseLong(studentId));
equal.link(Student_.teachers).equal(Teacher_.id, Long.parseLong(teacherId));
Student unique = equal.build().findUnique();
if (unique == null) {
Toast.makeText(activity, "找不到该学生", Toast.LENGTH_SHORT).show();
} else {
unique.setName(studentName);
studentBox.put(unique);
}
}
return queryStudent(teacherId, studentId);
}
/**
* 查询学生
*
* @param teacherId
* @param studentId
* @return
*/
public List<Student> queryStudent(String teacherId, String studentId) {
QueryBuilder<Student> query = studentBox.query();
if (!TextUtils.isEmpty(teacherId) && !TextUtils.isEmpty(studentId)) {
QueryBuilder<Student> equal = query.equal(Student_.id, Long.parseLong(studentId));
equal.link(Student_.teachers).equal(Teacher_.id, Long.parseLong(teacherId));
} else if (!TextUtils.isEmpty(teacherId)) {
Teacher teacher = teacherBox.query().equal(Teacher_.id, Long.parseLong(teacherId)).build().findUnique();
if (teacher == null) {
Toast.makeText(activity, "未找到该学生", Toast.LENGTH_SHORT).show();
} else {
return teacher.students;
}
} else if (!TextUtils.isEmpty(studentId)) {
query.equal(Student_.id, Long.parseLong(studentId));
}
return query.build().find();
}
}
|
package com.basho.riak.client.api;
public class RiakException extends Exception
{
public RiakException()
{
super();
}
public RiakException(String message)
{
super(message);
}
public RiakException(String message, Throwable cause)
{
super(message, cause);
}
public RiakException(Throwable cause)
{
super(cause);
}
}
|
package xhu.wncg;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author BZhao
* @version 2017/10/24.
*/
@SpringBootApplication
@Controller
public class FireSystemApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(FireSystemApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
return application.sources(FireSystemApplication.class);
}
/**
* 进入网站,跳转到登录界面
* @return index
*/
@RequestMapping("/")
public String index(){
return "forward:/login.html";
}
}
|
package sun.study.java.algorithm;
public class HeapSort2 {
public static int[] sort(int[] target){
int[] arr = target.clone();
return arr;
}
private void generateHeap(int[] arr,int p){
if(p>=0){
}
}
}
|
/*
* Copyright 2013 Basho Technologies Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.basho.riak.client.api.convert;
import com.basho.riak.client.api.convert.reflection.AnnotationUtil;
import com.basho.riak.client.api.cap.VClock;
import com.basho.riak.client.core.query.Location;
import com.basho.riak.client.core.query.Namespace;
import com.basho.riak.client.core.query.RiakObject;
import com.basho.riak.client.core.util.BinaryValue;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* The Converter acts as a bridge between the core and the user level API, specifically
* for ORM.
* <p>
* Subclasses will override the {@link #fromDomain(java.lang.Object) } and
* {@link #fromDomain(java.lang.Object) } methods to convert the value portion
* of a {@code RiakObject} to a domain object.
* </p>
*
* @author Brian Roach <roach at basho dot com>
* @param <T> the type to convert to
* @since 2.0
*/
public abstract class Converter<T>
{
protected final Type type;
public Converter(Type type)
{
this.type = type;
}
@SuppressWarnings("unchecked")
protected final T newDomainInstance()
{
try
{
Class<?> rawType = type instanceof Class<?>
? (Class<?>) type
: (Class<?>) ((ParameterizedType) type).getRawType();
Constructor<?> constructor = rawType.getConstructor();
return (T) constructor.newInstance();
}
catch (Exception ex)
{
throw new ConversionException(ex);
}
}
/**
* Converts from a RiakObject to a domain object.
*
* @param obj the RiakObject to be converted
* @param location The location of this RiakObject in Riak
* @return an instance of the domain type T
*/
public T toDomain(RiakObject obj, Location location)
{
T domainObject;
if (obj.isDeleted())
{
domainObject = newDomainInstance();
}
else
{
domainObject = toDomain(obj.getValue(), obj.getContentType());
AnnotationUtil.populateIndexes(obj.getIndexes(), domainObject);
AnnotationUtil.populateLinks(obj.getLinks(), domainObject);
AnnotationUtil.populateUsermeta(obj.getUserMeta(), domainObject);
AnnotationUtil.setContentType(domainObject, obj.getContentType());
AnnotationUtil.setVTag(domainObject, obj.getVTag());
}
AnnotationUtil.setKey(domainObject, location.getKey());
AnnotationUtil.setBucketName(domainObject, location.getNamespace().getBucketName());
AnnotationUtil.setBucketType(domainObject, location.getNamespace().getBucketType());
AnnotationUtil.setVClock(domainObject, obj.getVClock());
AnnotationUtil.setTombstone(domainObject, obj.isDeleted());
AnnotationUtil.setLastModified(domainObject, obj.getLastModified());
return domainObject;
}
/**
* Convert the value portion of a RiakObject to a domain object.
* <p>
* Implementations override this method to convert the value contained in
* a {@code RiakObject} to an instance of a domain object.
* </p>
* @param value the value portion of a RiakObject to convert to a domain object
* @param contentType The content type of the RiakObject
* @return a new instance of the domain object
*/
public abstract T toDomain(BinaryValue value, String contentType) throws ConversionException;
/**
* Convert from a domain object to a RiakObject.
* <p>
* The domain object itself may be completely annotated with everything
* required to produce a RiakObject except for the value portion.
* This will prefer annotated
* items over the {@code Location} passed in.
* </p>
* @param domainObject a domain object to be stored in Riak.
* @param namespace the namespace in Riak
* @param key the key for the object
* @return data to be stored in Riak.
*/
public OrmExtracted fromDomain(T domainObject, Namespace namespace, BinaryValue key)
{
BinaryValue bucketName = namespace != null ? namespace.getBucketName() : null;
BinaryValue bucketType = namespace != null ? namespace.getBucketType() : null;
key = AnnotationUtil.getKey(domainObject, key);
bucketName = AnnotationUtil.getBucketName(domainObject, bucketName);
bucketType = AnnotationUtil.getBucketType(domainObject, bucketType);
if (bucketName == null)
{
throw new ConversionException("Bucket name not provided via namespace or domain object");
}
VClock vclock = AnnotationUtil.getVClock(domainObject);
String contentType =
AnnotationUtil.getContentType(domainObject, RiakObject.DEFAULT_CONTENT_TYPE);
RiakObject riakObject = new RiakObject();
AnnotationUtil.getUsermetaData(riakObject.getUserMeta(), domainObject);
AnnotationUtil.getIndexes(riakObject.getIndexes(), domainObject);
AnnotationUtil.getLinks(riakObject.getLinks(), domainObject);
ContentAndType cAndT = fromDomain(domainObject);
contentType = cAndT.contentType != null ? cAndT.contentType : contentType;
riakObject.setContentType(contentType)
.setValue(cAndT.content)
.setVClock(vclock);
// We allow an annotated object to omit @BucketType and get the default
Namespace ns;
if (bucketType == null)
{
ns = new Namespace(bucketName);
}
else
{
ns = new Namespace(bucketType, bucketName);
}
OrmExtracted extracted = new OrmExtracted(riakObject, ns, key);
return extracted;
}
/**
* Provide the value portion of a RiakObject from the domain object.
* <p>
* Implementations override this method to provide the value portion of the
* RiakObject to be stored from the supplied domain object.
* </p>
* @param domainObject the domain object.
* @return A BinaryValue to be stored in Riak
*/
public abstract ContentAndType fromDomain(T domainObject) throws ConversionException;
/**
* Encapsulation of ORM data extracted from a domain object.
* <p>
* This allows for user-defined POJOs to encapsulate everything required to
* query Riak.
*</p>
*
*/
public static class OrmExtracted
{
private final RiakObject riakObject;
private final Namespace namespace;
private final BinaryValue key;
public OrmExtracted(RiakObject riakObject, Namespace namespace, BinaryValue key)
{
this.riakObject = riakObject;
this.namespace = namespace;
this.key = key;
}
/**
* @return the riakObject
*/
public RiakObject getRiakObject()
{
return riakObject;
}
/**
* @return the namespace
*/
public Namespace getNamespace()
{
return namespace;
}
public boolean hasKey()
{
return key != null;
}
public BinaryValue getKey()
{
return key;
}
}
protected class ContentAndType
{
private final BinaryValue content;
private final String contentType;
public ContentAndType(BinaryValue content, String contentType)
{
this.content = content;
this.contentType = contentType;
}
}
}
|
public class arrayBUb {
private long[] a; // create the reference array
private int nElem; // create the size of array
public arrayBUb(int size) {
a = new long[size]; // create the size of array
nElem = 0;
}
public void insert(long value){ // Add insert method to insert value in the array.
a[nElem] = value;
nElem++;
}
public void display() {
for (int i = 0; i < nElem; i++)
System.out.print(a[i] + " "); //display the array
System.out.println(" ");
}
public void bubbleSort(){
for (int j = 0; j < nElem-1 ; j++) // Add inner and outer loop
for (int k = 0; k < nElem - j - 1; k++)
if(a[k] > a[k+1]){
int temp = (int) a[k]; // swap the numbers which is biggest.
a[k] = a[k+1];
a[k+1] = temp;
}
}
}
|
package enshud.interlanguage.ilstatement;
import java.util.HashSet;
import enshud.interlanguage.iloperand.AbstractILOperand;
import enshud.interlanguage.iloperand.AbstractILVariableOperand;
import enshud.interlanguage.iloperand.ILIndexedVariableOperand;
import enshud.interlanguage.iloperand.ILSimpleVariableOperand;
public class ILReadStatement extends AbstractILStatement {
public AbstractILOperand operand;
public ILReadStatement(AbstractILOperand operand) {
this.operand = operand;
}
@Override
public String toString() {
return String.format("read %s", operand);
}
@Override
public HashSet<ILSimpleVariableOperand> getRefSet() {
var refSet = new HashSet<ILSimpleVariableOperand>();
if(operand instanceof ILIndexedVariableOperand)
refSet.add(((ILIndexedVariableOperand)operand).index);
return refSet;
}
@Override
public HashSet<ILSimpleVariableOperand> getDefSet() {
var defSet = new HashSet<ILSimpleVariableOperand>();
if(operand instanceof ILSimpleVariableOperand)
defSet.add((ILSimpleVariableOperand)operand);
return defSet;
}
@Override
public void replaceOperandDefinition(AbstractILVariableOperand oldOperand, AbstractILVariableOperand newOperand) {
if(operand.equals(oldOperand))
operand = newOperand;
}
}
|
package entity;
import java.util.Date;
public class Weight {
private Integer weight_id;
private String weight_name;
private Integer flag;
private Date date;
private Date sys_date;
public Integer getWeight_id() {
return weight_id;
}
public void setWeight_id(Integer weight_id) {
this.weight_id = weight_id;
}
public String getWeight_name() {
return weight_name;
}
public void setWeight_name(String weight_name) {
this.weight_name = weight_name;
}
public Integer getFlag() {
return flag;
}
public void setFlag(Integer flag) {
this.flag = flag;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Date getSys_date() {
return sys_date;
}
public void setSys_date(Date sys_date) {
this.sys_date = sys_date;
}
}
|
package com.zarbosoft.luxem.tree;
public class Typed {
public String name;
public Object value;
public Typed(final String type, final Object value) {
this.name = type;
this.value = value;
}
}
|
/*
* 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.ut.healthelink.security;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
*
* @author chadmccue
*/
public class encryptObject {
private String keyString = "abq@#$72#PBI@a^BOSj)(*SBN@#$PHX#@LKjCHSdSFOj<.,098CRP";
/**
* Encrypts and encodes the Object and IV for url inclusion
*
* @param input
* @return
* @throws Exception
*/
public String[] encryptObject(Object obj) throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(stream);
try {
// Serialize the object
out.writeObject(obj);
byte[] serialized = stream.toByteArray();
// Setup the cipher and Init Vector
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[cipher.getBlockSize()];
new SecureRandom().nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
// Hash the key with SHA-256 and trim the output to 128-bit for the key
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(keyString.getBytes());
byte[] key = new byte[16];
System.arraycopy(digest.digest(), 0, key, 0, key.length);
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
// encrypt
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
// Encrypt & Encode the input
byte[] encrypted = cipher.doFinal(serialized);
byte[] base64Encoded = Base64.encodeBase64(encrypted);
String base64String = new String(base64Encoded);
String urlEncodedData = URLEncoder.encode(base64String, "UTF-8");
// Encode the Init Vector
byte[] base64IV = Base64.encodeBase64(iv);
String base64IVString = new String(base64IV);
String urlEncodedIV = URLEncoder.encode(base64IVString, "UTF-8");
return new String[]{urlEncodedData, urlEncodedIV};
} finally {
stream.close();
out.close();
}
}
}
|
package org.hpin.webservice.dao;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.hpin.common.core.orm.BaseDao;
import org.hpin.webservice.bean.ErpReportdetailPDFContent;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
@Repository
public class ErpReportdetailPDFContentDao extends BaseDao {
/**
* 根据code和username查询对应的报告数据;
* 查询中只能查询报告状态为基因的及reportType='0'
* <p>Description: </p>
* @author herny.xu
* @date 2017年4月11日
*/
public List<ErpReportdetailPDFContent> findByCodeAndUserName(String code, String username) {
List<ErpReportdetailPDFContent> list = null;
String sql = "select pdfc.* from ERP_REPORTDETAIL_PDFCONTENT pdfc " +
"inner join erp_customer cus on cus.code =pdfc.code and cus.name=pdfc.username " +
"inner join erp_events event on event.EVENTS_NO = cus.EVENTS_NO " +
"inner join hl_customer_relationship_pro pro on pro.id = event.CUSTOMERRELATIONSHIPPRO_ID " +
"inner join T_PROJECT_TYPE ty on ty.id = pro.PROJECT_TYPE " +
"where " +
"pdfc.reportType='0' and pdfc.code = '" + code + "' and pdfc.username = '" + username + "' and pdfc.matchstate in (2, 12) " +
"and ty.PROJECT_TYPE = 'PCT_001'" ;
BeanPropertyRowMapper<ErpReportdetailPDFContent> rowMapper = new BeanPropertyRowMapper<ErpReportdetailPDFContent>(ErpReportdetailPDFContent.class);
try {
list = this.getJdbcTemplate().query(sql, rowMapper);
} catch(DataAccessException e) {
list = null;
}
return list;
}
public void save(ErpReportdetailPDFContent pdfContent){
this.getHibernateTemplate().save(pdfContent);
}
public void save(List<ErpReportdetailPDFContent> pdfContentList){
this.getHibernateTemplate().saveOrUpdateAll(pdfContentList);
}
public int saveList(List<ErpReportdetailPDFContent> list){
Integer count = 0;
if(!list.isEmpty()){
for (int i = 0; i < list.size(); i++) {
this.getHibernateTemplate().save(list.get(i));
count++;
}
}
return count;
}
public List<ErpReportdetailPDFContent> findByProps(String code, String pdfName) throws Exception{
List<ErpReportdetailPDFContent> list = null;
if(StringUtils.isNotEmpty(code)){
String hql = " from ErpReportdetailPDFContent where 1=1 and code = ? and pdfName = ?";
list = this.getHibernateTemplate().find(hql,new Object[]{code, pdfName});
}
return list;
}
}
|
/**
*
*/
package com.PIM.persistence;
import com.PIM.API.Product;
/**
* @author Henrik Lundin
*
*/
public interface IProductPersistenceService {
void CreateProduct(Product product);
}
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.desktopapp.client.filemanager.images;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
public class Images {
public interface ImageResources extends ClientBundle {
ImageResource arrow_in();
ImageResource arrow_out();
ImageResource bin_closed();
ImageResource bullet_go();
ImageResource cross();
ImageResource disk();
ImageResource folder();
ImageResource folder_add();
ImageResource page_white();
ImageResource page_white_add();
ImageResource script();
ImageResource script_add();
ImageResource table();
ImageResource table_add();
ImageResource textfield_rename();
ImageResource world();
ImageResource world_add();
}
private static ImageResources imageResources;
public static ImageResources getImageResources() {
if (imageResources == null) {
imageResources = GWT.create(ImageResources.class);
}
return imageResources;
}
}
|
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.time.StopWatch;
/**
* This class represents the methods used to get the time precision of a
* simulation of mm1 queue
*
* @author Madhuri Gurumurthy
*
*/
public class DiscreteMM1 {
// lambda-arrival rate, mu-mean service rate
private double lambda, mu;
StopWatch stopWatch = new StopWatch();
private Random rand;
/**
* @param lambda
* @param mu
*/
public DiscreteMM1(double lambda, double mu) {
rand = new Random();
this.lambda = lambda;
this.mu = mu;
}
/**
* Sample from exponential distribution with parameter mu
*
* @param mu
* the parameter of the exponential distribution
* @return a sample from the exp. dist.
*/
public double exponential(double mu) {
return -Math.log(rand.nextDouble()) / mu;
}
/**
* To calculate interarrival time, which is exponential
*
* @return interarrivalTime.
*/
private double interarrivalTime() {
return exponential(lambda);
}
/**
* To calculate service time, which is exponential
*
* @return serviceTime.
*/
private double serviceTime() {
return exponential(mu);
}
/**
* method to simulate the mm1 queue
*
* @param N
* @return
*/
public List simulate(int N) {
List<Long> timeTaken = new ArrayList<Long>();
// initialisation
int jobNumber = 0; // job number
double waitingTimeOfAJob = 0.0; // waiting time of job n
// we assume that initially the system is empty
double sumOfWaitingTime = 0.0; // sum of the waiting times
double sumOfSquaresOfWaitingTimes = 0.0; // sum of squares of the
// waiting times
double sumOfResponseTime = 0.0; // sum of the response times
double sumOfSquareOfResponseTimes = 0.0; // sum of squares of the
// response times
long beginTime = System.nanoTime();
stopWatch.reset();
stopWatch.start();
while (jobNumber < N) {
double interArrivalTimeOfCustomer = interarrivalTime(); // interarrival
// time
// of
// customer
// n
double serviceTimeOfCustomer = serviceTime(); // service time of
// customer n
double responseTimeOfACustomer = waitingTimeOfAJob
+ serviceTimeOfCustomer; // sojourn time of customer n
sumOfResponseTime = sumOfResponseTime + responseTimeOfACustomer;
sumOfSquareOfResponseTimes = sumOfSquareOfResponseTimes
+ responseTimeOfACustomer * responseTimeOfACustomer;
sumOfWaitingTime = sumOfWaitingTime + waitingTimeOfAJob; // add
// waiting
// time
// of
// customer
// n
sumOfSquaresOfWaitingTimes = sumOfSquaresOfWaitingTimes
+ waitingTimeOfAJob * waitingTimeOfAJob;
waitingTimeOfAJob = Math.max(waitingTimeOfAJob
+ serviceTimeOfCustomer - interArrivalTimeOfCustomer, 0); // waiting
// time
// of
// customer
// n+1
jobNumber++;
}
double meanWaitingTime = sumOfWaitingTime / N;
double rho = lambda / mu;
double wt = rho / (mu - lambda);
stopWatch.stop();
timeTaken.add(0, System.nanoTime() - beginTime);
timeTaken.add(1, stopWatch.getNanoTime());
return timeTaken;
}
public static void main(String[] arg) {
long[] timeTakenBySystemNano = new long[500];
long[] timeTakenByStopWatch = new long[500];
long systemMean = 0;
long stopWatchMean = 0;
double lambda = 0.05;
for (int i = 0; i < 500; i++) {
if (lambda <= 0.95) {
lambda += 0.05;
}
if (lambda > 0.95) {
lambda = 0.05;
}
DiscreteMM1 s = new DiscreteMM1(lambda, 1.0);
List timeTaken = s.simulate(100000 / 2);
timeTakenBySystemNano[i] = (long) timeTaken.get(0);
timeTakenByStopWatch[i] = (long) timeTaken.get(1);
}
for (int i = 0; i < 500; i++) {
systemMean += timeTakenBySystemNano[i];
stopWatchMean += timeTakenByStopWatch[i];
}
long systemMeanAvg = systemMean / 500;
long stopWatchMeanAvg = stopWatchMean / 500;
System.out.println("Mean of system=" + systemMeanAvg);
System.out.println("Mean of stop=" + stopWatchMeanAvg);
long[] systemDeviations = new long[500];
long[] stopWatchDeviations = new long[500];
for (int i = 0; i < 500; i++) {
systemDeviations[i] = timeTakenBySystemNano[i] - systemMeanAvg;
stopWatchDeviations[i] = timeTakenByStopWatch[i] - stopWatchMeanAvg;
}
long systemDeviationSquareSum = 0;
long stopWatchDeviationSquareSum = 0;
// getting the squares of deviations
for (int i = 0; i < 500; i++) {
systemDeviationSquareSum += (systemDeviations[i] * systemDeviations[i]);
stopWatchDeviationSquareSum += (stopWatchDeviations[i] * stopWatchDeviations[i]);
}
long systemVariance = (systemDeviationSquareSum / (500 - 1));
long stopWatchVariance = (stopWatchDeviationSquareSum / (500 - 1));
System.out.println("-----------------------");
System.out.println("systemVariance=" + systemVariance);
System.out.println("stopWatchVariance" + stopWatchVariance);
double systemStdDeviation = Math.sqrt(systemVariance);
double stopWatchStdDeviation = Math.sqrt(stopWatchVariance);
System.out.println(" System deviation=" + systemStdDeviation);
System.out.println(" Stop Watch deviation=" + stopWatchStdDeviation);
}
}
|
package com.auro.scholr.core.common;
public enum Upipsp {
Sbi,
imobile,
pockets,
ezeepay,
eazypay,
icici,
okicici,
hdfcbank,
payzapp,
okhdfcbank,
rajgovhdfcbank,
andb,
axisgo,
axis,
pingpay,
lime,
axisbank,
okaxis,
abfspay,
barodampay,
Boi,
mahb,
cnrb,
centralbank,
cbin,
cboi,
pnb,
unionbankofindia,
unionbank,
uboi,
hsbc,
Idbi,
idbibank,
kotak,
kaypay,
kmb,
kmbl,
obc,
Ubi,
united,
utbi,
Yesbank,
yesbankltd,
kvb,
karurvysyabank,
kvbank,
jkb,
apl,
fbl,
axisb,
indusind,
yesbank,
oksbi,
hdfcbankjd,
myicici,
ikwik,
ybl,
ibl,
rmhdfcbank,
barodapay,
idfcbank,
upi,
paytm,
}
|
/** #number-theory */
import java.util.Scanner;
class PalindromicSeries {
public static boolean isPalindromicSeries(int n) {
char[] digitsArr = String.valueOf(n).toCharArray();
int digits = digitsArr.length;
int digitsSum = 0;
for (int i = 0; i < digits; i++) {
digitsSum += digitsArr[i] - '0';
}
// check
for (int left = 0, right = digitsSum - 1; left < right; left++, right--) {
if (digitsArr[left % digits] != digitsArr[right % digits]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcases = sc.nextInt();
int n;
boolean ret;
for (int t = 0; t < testcases; t++) {
n = sc.nextInt();
ret = isPalindromicSeries(n);
System.out.println(ret ? "YES" : "NO");
}
}
}
|
package webley;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
//This is the main driver program.
public class Webley {
public static void main(String[] args) {
Map<Integer,Double> priceList = new HashMap<Integer,Double>(); //variable to store the prices
Map<Integer,String> itemsList = new HashMap<Integer,String>(); //variable to store the items
List<List<Double>> combinationOfPrices = new ArrayList<>(); //variable which will have the combination of prices
List<List<String>> combinationOfDishes = new ArrayList<>(); //variable which will have the combination of dishes
String filepath; //user input for file path
String printchoice; //user input for viewing combination of items or combination of price
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Filepath : ");
filepath = scanner.next();
try{
CreateWebley createwebley = new CreateWebley(); //new instance to read the file
createwebley.readFile(filepath); //reading the file
WebleyData wb = createwebley.getWebleyData();
priceList = wb.getPriceList(); //retrieving the prices
itemsList = wb.getItemsList(); //retrieving the items
WebleyCombinations wc = new WebleyCombinations(); //instantiating new class to find the combinations
combinationOfPrices = wc.findCombinations(wb); //method call to find all combinations and store it in the variable "targetCombinations"
if(combinationOfPrices.size()==0){ //if no combination found
System.out.println("Sorry. There is no Combination of dishes that match the Target Price");
}
else{ //combinations found...find the keys to the values in the Map and print them
WebleyOperations webleyOp = new WebleyOperations();
combinationOfDishes = webleyOp.retrieveKeys(combinationOfPrices, priceList, itemsList); //items and prices have same keys. So find keys of anyone
System.out.println("Select 1 to view Prices.\nSelect 2 to view Items.\nSelect q to Quit.\n"); //pretty printing the result with choice given to User.
printchoice = scanner.next();
while(!printchoice.equalsIgnoreCase("q")){
switch(printchoice){
case "1": webleyOp.prettyPrintPrices(combinationOfPrices);
break;
case "2": webleyOp.prettyPrintDishes(combinationOfDishes);
break;
default: System.out.println("Enter 1 for Prices, 2 for Items, q to Quit.");
break;
}
System.out.println("\n\nSelect 1 to view Prices.\nSelect 2 to view Items.\nSelect q to Quit.\n");
printchoice = scanner.next();
}
scanner.close(); //stop accepting input and exit
}
} catch(WebleyException we){
System.out.println(we.getErrorCode());
System.out.println(we.getErrorMessage());
}
}
}
|
package org.itachi.cms.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import java.util.HashMap;
import java.util.Map;
/**
* Created by itachi on 2017/3/18.
* User: itachi
* Date: 2017/3/18
* Time: 19:56
*/
abstract class BaseAction {
protected static final String APPLICATION_JSON_UTF8 = MediaType.APPLICATION_JSON + ";charset=UTF-8";
protected static final String SUCCESS ="success";
@Context
protected HttpServletRequest request;
@Context
protected HttpServletResponse response;
@Context
protected UriInfo uriInfo;
protected Map<String, String> getQueryParameters() throws Exception {
Map<String, String> map = new HashMap<>();
MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();
for (String key : parameters.keySet()) {
map.put(key, parameters.get(key).get(0));
}
return map;
}
}
|
package be.kdg.fastrada.services;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* Test for the Login Service.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("live")
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/dispatcher-servlet.xml", "file:src/main/webapp/WEB-INF/security-servlet.xml"})
public class TestLoginService {
@Autowired
private LoginService service;
@Test
public void testLoadUsername() {
UserDetails userDetails = service.loadUserByUsername("fastrada.groep8@gmail.com");
assertEquals(userDetails.getUsername(), "fastrada.groep8@gmail.com");
}
@Test(expected = UsernameNotFoundException.class)
public void testLoadWrongUsername() {
UserDetails userDetails = service.loadUserByUsername("WrongUsername");
assertNull(userDetails);
}
}
|
package com.yea.core.serializer.pool;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import com.yea.core.exception.YeaException;
import com.yea.core.serializer.ISerializer;
public class SerializePool {
private GenericObjectPool<ISerializer> serializerPool;
public SerializePool() {
this(new SerializeFactory());
}
public SerializePool(SerializeFactory serializeFactory) {
this(serializeFactory, 10, 3, -1, 1800000);
}
public SerializePool(SerializeFactory serializeFactory, final int maxTotal, final int minIdle, final long maxWaitMillis, final long minEvictableIdleTimeMillis) {
serializerPool = new GenericObjectPool<ISerializer>(serializeFactory);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
// 最大池对象总数
config.setMaxTotal(maxTotal);
// 最小空闲数
config.setMinIdle(minIdle);
// 最大等待时间, 默认的值为-1,表示无限等待
config.setMaxWaitMillis(maxWaitMillis);
// 退出连接的最小空闲时间 默认1800000毫秒
config.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
serializerPool.setConfig(config);
}
public ISerializer borrow() {
try {
return getPool().borrowObject();
} catch (final Exception ex) {
throw new YeaException("不能获取池对象");
}
}
public void restore(final ISerializer object) {
object.setCompress(null);
getPool().returnObject(object);
}
private GenericObjectPool<ISerializer> getPool() {
return serializerPool;
}
}
|
package cas2xb3_finalprototype;
public class AirportVertex implements Comparable<AirportVertex> {
public String name; // label for vertex
public int uid; // unique identifier for vertex (index)
public String airportCode;
public AirportVertex(String v, String code, int i) {
name = v;
uid = i;
airportCode = code;
}
public int getID(){
return this.uid;
}
public String getAirportCode(){
return this.airportCode;
}
public String toString() {
return name;
}
public int compareTo(AirportVertex other) {
return name.compareTo(other.name);
}
}
|
package metaapp.view.widget;
public interface ListWidget {
}
|
package com.asgab.util;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.asgab.entity.User;
import com.asgab.service.user.UserService;
@Component
@Transactional
public class ApplicationContext {
@Autowired
private UserService userService;
public static List<User> payingUsers = new ArrayList<User>();
public static Long lastSyncTime = CommonUtil.getCurrentDateTime();
public synchronized void init() {
userService.initPayingUsers();
System.out.println("init end");
}
}
|
package com.training.ifaces;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import com.training.domain.BloodDonor;
@WebService
public interface DonationRequest {
@WebMethod
public BloodDonor getRequest(@WebParam(name="bldGroup")String bldGroup);
}
|
package ejercicionotasprom;
import java.util.Scanner;
public class Ejercicionotasprom {
public static void main(String[] args) {
// TODO code application logic here
Scanner Entrada=new Scanner(System.in);
float [] n;
float prom,acu=0,apro=0,desa=0,acua=0,acud=0,proma,promd;
n=new float[5];
for (int i=0;i<5;i++){
System.out.print("INGRESE NOTAS DEL 0 A 20: ");
n[i]=Entrada.nextFloat();
acu=acu+n[i];
if (n[i]>10&&n[i]<21){
apro++;
acua=acua+n[i];
}else{
desa++;
acud=acud+n[i];
}
}
prom=acu/5;
proma=acua/apro;
promd=acud/desa;
System.out.println("PROMEDIO TOTAL: "+prom);
System.out.println("APROBADOS: "+apro);
System.out.println("DESAPROBADOS: "+desa);
System.out.println("PROMEDIO APROBADOS: "+proma);
System.out.println("PROMEDIO DESAPROBADOS: "+promd);
for(int i=0;i<5;i++){
if (n[i]>10){
System.out.println("NOTAS APROBADAS: "+n[i]);
}
}
for(int i=0;i<5;i++){
if (n[i]<11){
System.out.println("NOTAS DESAPROBADAS: "+n[i]);
}
}
}
}
|
package swea_d2;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution_1979_어디에단어가들어갈수있을까 {
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
for (int tc = 1; tc <= T; tc++) {
StringTokenizer st = new StringTokenizer(br.readLine().trim());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
int[][] arr = new int[N][N];
int idx = 0;
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine().trim());
for (int j = 0; j < N; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
for (int i = 0; i < N; i++) {
int blank = 0;
for (int j = 0; j < N; j++) {
if (arr[i][j] == 1)
blank++;
else {
if (blank == K)
idx++;
blank = 0;
}
}
if (blank == K)
idx++;
}
for (int j = 0; j < N; j++) {
int blank = 0;
for (int i = 0; i < N; i++) {
if (arr[i][j] == 1)
blank++;
else {
if (blank == K)
idx++;
blank = 0;
}
}
if (blank == K)
idx++;
}
System.out.println("#"+tc+" "+idx);
}
}
}
|
package com.nantian.foo.web.auth.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "menu_auth")
public class MenuAuth implements Serializable{
private Long id;
private Long menuId;
private Long authId;
public MenuAuth() {
}
public MenuAuth(Long id,Long menuId,Long authId)
{
this.id=id;
this.menuId=id;
this.authId=id;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name = "auth_id")
public Long getAuthId() {
return authId;
}
public void setAuthId(Long authId) {
this.authId = authId;
}
@Basic
@Column(name = "menu_id")
public Long getMenuId() {
return menuId;
}
public void setMenuId(Long menuId) {
this.menuId = menuId;
}
}
|
package app;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Settings extends Window{
JButton backButton;
public Settings(WindowManager manager) {
super(manager);
mainPanel.setBackground(Color.GREEN);
backButton = new GButton("Back",Color.CYAN);
backButton.addMouseListener(new ButtonListener(this));
mainPanel.add(backButton);
}
@Override
public void mousePress(MouseEvent e) {
if (e.getSource()==backButton) {
super.manager.changeState("menu");
}
}
}
|
package com.edasaki.rpg.spells.crusader;
import java.util.ArrayList;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import com.edasaki.core.utils.RParticles;
import com.edasaki.rpg.PlayerDataRPG;
import com.edasaki.rpg.spells.Spell;
import com.edasaki.rpg.spells.SpellEffect;
import de.slikey.effectlib.util.ParticleEffect;
public class Cleave extends SpellEffect {
@Override
public boolean cast(final Player p, PlayerDataRPG pd, int level) {
int damage = pd.getDamage(true);
switch (level) {
case 1:
damage *= 1.2;
break;
case 2:
damage *= 1.4;
break;
case 3:
damage *= 1.6;
break;
case 4:
damage *= 1.8;
break;
case 5:
damage *= 2.0;
break;
case 6:
damage *= 2.2;
break;
case 7:
damage *= 2.4;
break;
case 8:
damage *= 2.6;
break;
case 9:
damage *= 2.8;
break;
case 10:
damage *= 3.0;
break;
}
Vector direction = p.getLocation().getDirection().normalize();
double x = direction.getX();
double y = direction.getY();
double z = direction.getZ();
double radians = Math.atan(z / x);
if (x < 0)
radians += Math.PI;
ArrayList<Location> arc = new ArrayList<Location>();
Location start = p.getLocation().clone().add(0, -1, 0);
arc.add(start.clone().add(direction.multiply(1.5)));
Vector v = new Vector();
v.setY(y);
v.setX(Math.cos(radians - 2 * Math.PI / 9));
v.setZ(Math.sin(radians - 2 * Math.PI / 7));
arc.add(start.clone().add(v.multiply(1.5)));
v = new Vector();
v.setY(y);
v.setX(Math.cos(radians - Math.PI / 9));
v.setZ(Math.sin(radians - Math.PI / 9));
arc.add(start.clone().add(v.multiply(1.5)));
v = new Vector();
v.setY(y);
v.setX(Math.cos(radians + Math.PI / 9));
v.setZ(Math.sin(radians + Math.PI / 9));
arc.add(start.clone().add(v.multiply(1.5)));
v = new Vector();
v.setY(y);
v.setX(Math.cos(radians + 2 * Math.PI / 9));
v.setZ(Math.sin(radians + 2 * Math.PI / 9));
arc.add(start.clone().add(v.multiply(1.5)));
ArrayList<Entity> hit = new ArrayList<Entity>();
RParticles.showWithSpeed(ParticleEffect.EXPLOSION_LARGE, arc.get(0).clone().add(0, 1.5, 0), 0, 2);
for (int k = 0; k < 8; k++) {
for (Location loc : arc) {
hit.addAll(Spell.damageNearby(damage, p, loc, 2, hit));
loc.add(0, 0.5, 0);
}
}
Spell.notify(p, "You slice forward with your sword.");
return true;
}
}
|
package N2_All_indexes_array_MVC;
/**
* Created by HP on 19.07.2017.
*/
public class Model {
//internal array of the modal
private int array[];
public int[] getArray() {
return array;
}
public void setArray(int[] array) {
this.array = array;
}
/**
* this method check does the array contain number
* @param number
* @return true if array contains number, false - in the other case
*/
public boolean isContainsNumber(int number){
for (int i = 0; i < array.length; i++) {
if(array[i] == number){
return true;
}
}
return false;
}
/**
* this method return array of indexes where elements equals number
* @param number
* @return array of indexes elements equals number
*/
public int[] getIndexesArray(int number){
int j = 0;
int[] indexesArray = new int[getCountNumberIntoArray(number)];
for (int i = 0; i < array.length; i++) {
if(array[i] == number){
indexesArray[j] = i;
j++;
}
}
return indexesArray;
}
/**
* this method find amount elements of the array equals number
* @param number
* @return amount elements equals number
*/
private int getCountNumberIntoArray(int number){
int counter = 0;
for (int i = 0; i < array.length; i++) {
if(array[i] == number){
counter++;
}
}
return counter;
}
}
|
package com.mario.bean;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.apache.olingo.odata2.api.annotation.edm.EdmEntitySet;
import org.apache.olingo.odata2.api.annotation.edm.EdmEntityType;
import org.apache.olingo.odata2.api.annotation.edm.EdmKey;
import org.apache.olingo.odata2.api.annotation.edm.EdmProperty;
import lombok.Getter;
import lombok.Setter;
@EdmEntityType
@EdmEntitySet
@Entity
@Table(name="Address")
public class Address {
@Getter
@Setter
@EdmKey
@EdmProperty
@Id
private Integer id;
@Getter
@Setter
@EdmProperty
private String country;
@Getter
@Setter
@EdmProperty
private String city;
@Getter
@Setter
@EdmProperty
private String street;
@Getter
@Setter
//@EdmProperty
@ManyToOne
@JoinColumn(name="creator_person_id", referencedColumnName="person_id")
public Person creator;
}
|
package org.apache.kazon.mapreduce;
public class KazonMapReduceJob {
}
|
package dk.webbies.tscreate.analysis.jsdoc;
import com.google.gson.Gson;
import com.google.javascript.jscomp.newtypes.Declaration;
import com.google.javascript.jscomp.parsing.parser.trees.Comment;
import dk.webbies.tscreate.analysis.TypeAnalysis;
import dk.webbies.tscreate.analysis.declarations.typeCombiner.TypeReducer;
import dk.webbies.tscreate.analysis.declarations.types.*;
import dk.webbies.tscreate.analysis.unionFind.HasPrototypeNode;
import dk.webbies.tscreate.declarationReader.DeclarationParser;
import dk.webbies.tscreate.jsnap.JSNAPUtil;
import dk.webbies.tscreate.jsnap.Snap;
import dk.webbies.tscreate.paser.AST.FunctionExpression;
import dk.webbies.tscreate.util.Pair;
import dk.webbies.tscreate.util.Util;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static java.util.Collections.*;
/**
* Created by erik1 on 29-04-2016.
*/
public class JSDocParser {
private final Snap.Obj globalObject;
private final TypeAnalysis typeAnalysis;
private DeclarationParser.NativeClassesMap nativeClasses;
private TypeReducer combiner;
public JSDocParser(Snap.Obj globalObject, TypeAnalysis typeAnalysis, DeclarationParser.NativeClassesMap nativeClasses, TypeReducer typeReducer) {
this.globalObject = globalObject;
this.typeAnalysis = typeAnalysis;
this.nativeClasses = nativeClasses;
combiner = typeReducer;
}
public FunctionType parseFunctionDoc(Snap.Obj closure, Comment comment) {
List<FunctionType.Argument> arguments = new ArrayList<>();
DeclarationType ret = null;
List<Tag> tags = parseComment(comment.value);
int argCounter = 0;
for (Tag tag : tags) {
switch (tag.title.toUpperCase()) {
case "PARAM":
String argName = tag.name;
if (argName == null) { // TODO: If argName contains ".", then collect into object.
argName = "arg" + argCounter++;
}
if (argName.contains(".")) {
argName = argName.replace(".", "");
}
arguments.add(new FunctionType.Argument(argName, toDeclarationType(tag.type, closure)));
break;
case "RETURN":
case "RETURNS":
// assert ret == null; // There is a JSDoc standard, but it doesn't seem that anyone read that.
ret = toDeclarationType(tag.type, closure);
break;
case "STATIC":case "CLASS":case "CONSTRUCTOR":case "LICENSE":case "PRIVATE":case "EVENT":case "MEMBEROF":case "PROTECTED":case "CONSTANT":case "EXTENDS":case "EXAMPLE":case "FIRES":case "SEE":case "NAME":case "NAMESPACE":
break;
default:
// throw new RuntimeException("Don't know how to handle: " + tag.title);
break;
}
}
if (ret == null) {
// System.err.println("Return: null");
ret = PrimitiveDeclarationType.Void(EMPTY_SET);
}
return new FunctionType(closure.function.astNode, ret, arguments, EMPTY_SET);
}
public DeclarationType parseMemberDoc(Snap.Obj closure, Comment comment) {
DeclarationType ret = null;
List<Tag> tags = parseComment(comment.value);
for (Tag tag : tags) {
switch (tag.title.toUpperCase()) {
case "MEMBER":case "TYPE":
assert ret == null;
ret = toDeclarationType(tag.type, closure);
break;
case "METHOD":
ret = new FunctionType(PrimitiveDeclarationType.Void(Collections.EMPTY_SET), Collections.EMPTY_LIST, Collections.EMPTY_SET, Collections.EMPTY_LIST);
break;
case "PRIVATE":case "DEFAULT":case "SEE":case "READONLY":case "MEMBEROF":case "LINK":case "EXAMPLE":
break;
case "PARAM":
ret = parseFunctionDoc(closure, comment);
break;
default:
break;
}
}
return ret;
}
public static boolean isClass(FunctionExpression functionExpression) {
if (functionExpression == null) {
return false;
}
if (functionExpression.jsDoc != null) {
return parseComment(functionExpression.jsDoc.value).stream().map(feature -> feature.title.toUpperCase()).anyMatch(title -> title.equals("CLASS") || title.equals("CONSTRUCTOR"));
}
return false;
}
private DeclarationType toDeclarationType(Type type, Snap.Obj closure) {
if (type == null || type.type == null) {
return PrimitiveDeclarationType.Void(Collections.EMPTY_SET);
}
switch (type.type) {
case "NameExpression":
DeclarationType dec = fromHeapValue(type.name, closure);
if (dec != null) {
return dec;
}
switch (type.name.toLowerCase()) {
case "number":
case "int":
return PrimitiveDeclarationType.Number(EMPTY_SET);
case "string":
return PrimitiveDeclarationType.String(EMPTY_SET);
case "void":
return PrimitiveDeclarationType.Void(EMPTY_SET);
case "any":
case "null":
return PrimitiveDeclarationType.Any(EMPTY_SET);
case "boolean":
case "bool":
case "true":
case "false":
return PrimitiveDeclarationType.Boolean(EMPTY_SET);
case "array":
return new NamedObjectType("Array", false);
case "functon":
case "function":
return new FunctionType(null, PrimitiveDeclarationType.Void(EMPTY_SET), EMPTY_LIST, EMPTY_SET);
case "object":
return new NamedObjectType("Object", false);
case "domelement":
return new NamedObjectType("Element", false);
case "date":
return new NamedObjectType("Date", false);
}
System.err.println("Don't know how to handle the name: " + type.name);
return PrimitiveDeclarationType.Void(EMPTY_SET);
case "TypeApplication":
if (type.expression.type.equals("NameExpression") && type.expression.name.toLowerCase().equals("array") && type.applications != null && !type.applications.isEmpty()) {
return new NamedObjectType("Array", false, toDeclarationType(type.applications.iterator().next(), closure));
}
if (type.expression.type.equals("NameExpression")) {
return new NamedObjectType(type.expression.name, false);
}
throw new RuntimeException("Don't know how to handle this typeApplication, expression: " + type.expression.type);
case "UnionType":
return new UnionDeclarationType(type.elements.stream().map(subtype -> toDeclarationType(subtype, closure)).collect(Collectors.toList()));
case "OptionalType": // TODO: Handle?
return toDeclarationType(type.expression, closure);
case "RestType": // TODO: Handle?
return toDeclarationType(type.expression, closure);
case "NullLiteral": // In TypeScript, anything can be null, so this type doesn't make sense in TypeScript.
case "UndefinedLiteral":
return PrimitiveDeclarationType.Void(EMPTY_SET);
case "AllLiteral":
return PrimitiveDeclarationType.Any(EMPTY_SET);
case "NonNullableType":
case "NullableType":
return toDeclarationType(type.expression, closure);
case "FunctionType":
AtomicInteger argCounter = new AtomicInteger(0);
List<FunctionType.Argument> args = type.params.stream().map(arg -> toDeclarationType(arg, closure)).map(arg -> new FunctionType.Argument("arg" + argCounter.incrementAndGet(), arg)).collect(Collectors.toList());
DeclarationType returnType = toDeclarationType(type.result, closure);
if (returnType == null) {
returnType = PrimitiveDeclarationType.Void(EMPTY_SET);
}
return new FunctionType(null, returnType, args, EMPTY_SET);
case "RecordType":
Map<String, DeclarationType> fields = type.fields.stream().map(field -> new Pair<>(field.key, toDeclarationType(field.value, closure))).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
return new UnnamedObjectType(fields, EMPTY_SET);
case "ArrayType": // Really a tuple from TypeScript, but I can't export that as of now.
return new NamedObjectType("Array", false, new CombinationType(combiner, type.elements.stream().map(subtype -> toDeclarationType(subtype, closure)).collect(Collectors.toList())));
default:
throw new RuntimeException("Don't know how to handle: " + type.type);
}
}
private DeclarationType fromHeapValue(String path, Snap.Obj closure) {
if (path == null) {
return null;
}
Snap.Obj env = closure.env;
while (env != null) {
try {
Snap.Value value = JSNAPUtil.lookupRecursive(env, path);
if (value instanceof Snap.Obj && ((Snap.Obj) value).function != null) {
Snap.Obj obj = (Snap.Obj) value;
return typeAnalysis.getTypeFactory().getType(new HasPrototypeNode(typeAnalysis.getSolver(), (Snap.Obj) obj.getProperty("prototype").value));
} else {
return typeAnalysis.getTypeFactory().getType(typeAnalysis.getHeapFactory().fromValue(value));
}
} catch (AssertionError | RuntimeException ignored) { }
env = env.env;
}
return null;
}
public static void main(String[] args) throws IOException {
String docExample = "/**\n\n" +
" * A short hand way of creating a movieclip from an array of frame ids\r\n" +
" *\n\n" +
" * @static\n\n" +
" * @param {string[]} the array of frames ids the movieclip will use as its texture frames\n\n" +
" */=";
List<Tag> tags = parseComment(docExample);
System.out.println(tags.size());
tags = parseComment(docExample);
System.out.println(tags.size());
tags = parseComment(docExample);
System.out.println(tags.size());
tags = parseComment(docExample);
System.out.println(tags.size());
}
private static List<Tag> parseComment(String doc) {
try {
return new Gson().fromJson(NodeRunner.getInstance().parseComment(doc), JSDoc.class).tags;
} catch (IOException e) {
throw new RuntimeException();
}
}
private static final class NodeRunner {
static NodeRunner instance = null;
private final Process process;
private final FlushableStreamGobbler inputGobbler;
public synchronized static NodeRunner getInstance() throws IOException {
if (instance == null) {
instance = new NodeRunner();
}
return instance;
}
private NodeRunner() throws IOException {
process = Runtime.getRuntime().exec("node " + "node_modules/doctrine-cli/index.js --unwrap --sloppy --multiple");
inputGobbler = new FlushableStreamGobbler(process.getInputStream());
new Util.StreamGobbler(process.getErrorStream(), new CountDownLatch(1));
}
synchronized String parseComment(String doc) throws IOException {
process.getOutputStream().write(doc.getBytes());
process.getOutputStream().write(0);
process.getOutputStream().flush();
try {
return inputGobbler.getResult();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
private static class FlushableStreamGobbler extends Thread {
BufferedInputStream is;
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
private FlushableStreamGobbler(InputStream is) {
this.is = new BufferedInputStream(is);
this.start();
}
public String getResult() throws InterruptedException {
return queue.take();
}
@Override
public void run() {
try {
StringBuilder builder = new StringBuilder();
while (true) {
char character = (char) is.read();
// System.out.println("Read: " + Character.toString(character));
if (Character.toString(character).equals("\n")) {
queue.put(builder.toString());
builder = new StringBuilder();
} else {
builder.append(character);
}
}
} catch (InterruptedException | IOException ioe) {
ioe.printStackTrace();
throw new RuntimeException(ioe);
}
}
}
public static final class JSDoc {
public String description;
public List<Tag> tags;
}
public static final class Tag {
public String title;
public String description;
public String name;
public Type type;
}
public static final class Type {
public String type;
public Type expression;
public List<Type> applications;
public List<Type> params;
public Type result;
public List<Type> elements;
public String name;
public List<FieldType> fields;
}
public static final class FieldType {
public String key;
public Type value;
}
}
|
package com.wsp.ciliwunggame;
import android.app.Activity;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class ArenaActivity extends Activity implements OnClickListener {
public Canvas _canvas;
public boolean _ketLooping;
public int _x, _y;
public ImageView[] _ivSampah = new ImageView[5];
private LinearLayout.LayoutParams[] p = new LinearLayout.LayoutParams[5];
private int[] _top = new int[5];
private int _time;
Handler handlerMovingSampah = new Handler() {
public void handleMessage(Message msg) {
if (_top[0] == 10) {
_top[0] = 500;
// _time -= 10;
} else {
_top[0] -= 2;
}
// String perc = String.valueOf(_top).toString();
p[0].setMargins(0, _top[0], 10, 10);
_ivSampah[0].setLayoutParams(p[0]);
if (_top[0] < 200) {
if (_top[1] == 10) {
_top[1] = 500;
// _time -= 10;
} else {
_top[1] -= 2;
}
// String perc = String.valueOf(_top).toString();
p[1].setMargins(0, _top[1], 10, 10);
_ivSampah[1].setLayoutParams(p[1]);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.arena);
_top[0] = 500;
_top[1] = 510;
_time = 50;
_ivSampah[0] = new ImageView(this);
_ivSampah[0].setImageResource(R.drawable.gs_bunga);
_ivSampah[1] = new ImageView(this);
_ivSampah[1].setImageResource(R.drawable.gs_kalengminuman);
p[0] = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 60);
p[0].setMargins(0, _top[0], 10, 10);
_ivSampah[0].setLayoutParams(p[0]);
p[1] = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 60);
p[1].setMargins(0, _top[1], 10, 10);
_ivSampah[1].setLayoutParams(p[1]);
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
mainLayout.addView(_ivSampah[0]);
mainLayout.addView(_ivSampah[1]);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStart() {
super.onStart();
Thread bg = new Thread(new Runnable() {
public void run() {
try {
while (true) {
Thread.sleep(_time);
handlerMovingSampah.sendMessage(handlerMovingSampah
.obtainMessage());
}
} catch (Throwable t) {
t.printStackTrace();
} finally {
// finish();
}
}
});
bg.start();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
}
|
package jd.controllers;
import jd.Util.AppMappings;
import jd.Util.AppUtils;
import jd.persistence.model.Aviation;
import jd.persistence.model.Price;
import jd.persistence.model.Product;
import jd.persistence.repository.AviationRepository;
import jd.persistence.repository.SvcgroupRepository;
import jd.persistence.repository.PriceRepository;
import jd.persistence.repository.ProductRepository;
import org.jsondoc.core.annotation.Api;
import org.jsondoc.core.annotation.ApiMethod;
import org.jsondoc.core.annotation.ApiPathParam;
import org.jsondoc.core.pojo.ApiStage;
import org.jsondoc.core.pojo.ApiVisibility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
/**
* Created by eduardom on 9/13/16.
*/
@RestController
@RequestMapping(value = AppMappings.PRODUCTS)
@Api(
name="Products",
description = "Establece procedimientos para la gestion de productos y precios",
group = "Productos",
visibility = ApiVisibility.PUBLIC,
stage = ApiStage.RC
)
public class ProductController {
ProductRepository productRepository;
AppUtils utils;
@Autowired
SvcgroupRepository svcgroupRepository;
@Autowired
AviationRepository aviation;
@Autowired
PriceRepository priceRepository;
@Autowired
public ProductController(ProductRepository productRepository){
this.productRepository = productRepository;
}
//show all products
@RequestMapping(method = RequestMethod.GET)
public List<Product> showAllProducts(){
try{
return productRepository.findAll();
}catch(Exception e){
return null;
}
}
//show all products by group id
@RequestMapping(value = "/group/{group_id}", method = RequestMethod.GET)
public Set<Product> showProductsGroup(@PathVariable Long group_id){
try{
return svcgroupRepository.findOne(group_id).getProducts();
}catch(Exception e){
return null;
}
}
//show products by id
@RequestMapping(value = "/{product_id}", method = RequestMethod.GET)
public Object showProduct(@PathVariable Long product_id){
Hashtable<String, String> message = new Hashtable<String, String>();
try{
return productRepository.findOne(product_id);
}catch(Exception e){
message.put("message","Producto no encontrado");
return message;
}
}
//add a price from product
@RequestMapping(value = "/prices/{product_id}", method = RequestMethod.POST)
public Object setPrices(@RequestBody Price price, @PathVariable Long product_id){
Hashtable<String, String> message = new Hashtable<String, String>();
try {
Product product= productRepository.findOne(product_id);
return productRepository.save(product);
}catch (Exception e){
message.put("message","Producto no pudo ser actualizado err: "+e.getCause());
return null;
}
}
//update a product
@RequestMapping(method = RequestMethod.PUT)
public Object updateProduct(@RequestBody Product product){
Hashtable<String, String> message = new Hashtable<String, String>();
try {
return productRepository.save(product);
}catch (Exception e){
message.put("message","Producto no pudo ser actualizado err: "+e.getCause());
return null;
}
}
//retrieve a price from product
@RequestMapping(value = "/prices/{location}/{aviationtype}/{myaircraft}/{landingdate}", method = RequestMethod.GET)
@ApiMethod(description = "Permite al usuario conocer los servicios disponibles para su aeronave en una localidad especifica")
public Object getPricesFromLocation(
@ApiPathParam(name = "location", description= "localidad o destino") @PathVariable long location,
@ApiPathParam(name = "aviationtype", description= "Tipo de aviación ej. comercial") long aviationtype,
@ApiPathParam(name = "landingdate", description= "fecha de aterrizaje") long landingdate,
@ApiPathParam(name = "myaircraft", description= "aeronave que pertenece al usuario, la que va a viajar") long myaircraft
){
Hashtable<String, String> message = new Hashtable<String, String>();
try {
return null ;// productRepository.save(product);
}catch (Exception e){
message.put("message","Producto no pudo ser actualizado err: "+e.getCause());
return null;
}
}
//update a price from product
@RequestMapping(value = "/prices", method = RequestMethod.PUT)
public Object updatePrice(@RequestBody Price price){
Hashtable<String, String> message = new Hashtable<String, String>();
try {
return priceRepository.save(price);
}catch (Exception e){
message.put("message","precio no pudo ser actualizado err: "+e.getCause());
return null;
}
}
@RequestMapping(value = "/findbytag/{tag}", method = RequestMethod.GET)
public Object findByTag(@PathVariable String tag){
try {
return productRepository.findBynameContaining(tag);
}catch (Exception e){
return null;
}
}
//AVIATION TYPE
@RequestMapping(value = "/aviationtype", method = RequestMethod.GET)
public List<Aviation> ShowAviationType(){
try {
return aviation.findAll();
}catch (Exception e){
return null;
}
}
}
|
package com.nts.android.logs;
import java.text.SimpleDateFormat;
import java.util.Locale;
import com.nts.cash.log.LogsWriter;
import android.util.Log;
public class LoggerLogAndroid implements LogsWriter {
//static private boolean enabled= true;
static private boolean enabledT= true;
static private boolean enabledD= true;
static private boolean enabledI= true;
static private boolean enabledW= true;
static private boolean enabledE= true;
static private boolean enabledF= true;
//final static private boolean enabledLocation= true;
public void setEnabled(boolean enabled) {
}
@Override
synchronized public void t(String tag, String message) {
if (isT()) Log.v(tag, message);
}
@Override
synchronized public void d(String tag, String message) {
if (isD()) Log.d(tag, new SimpleDateFormat("mm:ss:SSS", Locale.getDefault()).format(System.currentTimeMillis()) + "_" + message);
}
@Override
synchronized public void i(String tag, String message) {
if (isI()) Log.i(tag, message);
}
@Override
synchronized public void w(String tag, String message) {
if (isW()) Log.w(tag, message);
}
@Override
synchronized public void e(String tag, String message) {
if (isE()) Log.e(tag, message);
}
@Override
synchronized public void f(String tag, String message) {
if (isF()) Log.e(tag, message);
}
synchronized public void t(String tag, String format, Object... args) {
//if (isT()) Log.v(tag, String.format(format, args) + ((enabledLocation) ? getLocation() : ""));
if (isT()) Log.v(tag, (format != null) ? String.format(format, args) : String.valueOf(format));
}
synchronized public void d(String tag, String format, Object... args) {
//if (isD()) Log.d(tag, String.format(format, args) + ((enabledLocation) ? getLocation() : ""));
if (isD()) Log.d(tag, (format != null) ? String.format(format, args) : String.valueOf(format));
}
synchronized public void i(String tag, String format, Object... args) {
//if (isI()) Log.i(tag, String.format(format, args) + ((enabledLocation) ? getLocation() : ""));
if (isI()) Log.i(tag, (format != null) ? String.format(format, args) : String.valueOf(format));
}
synchronized public void w(String tag, String format, Object... args) {
//if (isW()) Log.w(tag, String.format(format, args) + ((enabledLocation) ? getLocation() : ""));
if (isW()) Log.w(tag, (format != null) ? String.format(format, args) : String.valueOf(format));
}
synchronized public void e(String tag, String format, Object... args) {
//if (isE()) Log.e(tag, String.format(format, args) + ((enabledLocation) ? getLocation() : ""));
if (isE()) Log.e(tag, (format != null) ? String.format(format, args) : String.valueOf(format));
}
@Override
synchronized public void f(String tag, String format, Object... args) {
//if (isF()) Log.e(tag, String.format(format, args) + ((enabledLocation) ? getLocation() : ""));
if (isF()) Log.e(tag, (format != null) ? String.format(format, args) : String.valueOf(format));
}
synchronized public void w(String tag, String message, Throwable e) {
//if (isW()) Log.w(tag, message + ((enabledLocation) ? getLocation() : ""), e);
if (isW()) Log.w(tag, message, e);
}
synchronized public void e(String tag, String message, Throwable e) {
//if (isE()) Log.e(tag, message + ((enabledLocation) ? getLocation() : ""), e);
if (isE()) Log.e(tag, message, e);
}
@Override
synchronized public void f(String tag, String message, Throwable e) {
//if (isF()) Log.e(tag, message + ((enabledLocation) ? getLocation() : ""), e);
if (isF()) Log.e(tag, message, e);
}
@Override
public boolean isT() {
return enabledT;
}
@Override
public boolean isD() {
return enabledD;
}
@Override
public boolean isI() {
return enabledI;
}
@Override
public boolean isW() {
return enabledW;
}
@Override
public boolean isE() {
return enabledE;
}
@Override
public boolean isF() {
return enabledF;
}
private static String getLocation() {
final String className = "";
final StackTraceElement[] traces = Thread.currentThread().getStackTrace();
boolean found = false;
for (int i = 0; i < traces.length; i++) {
StackTraceElement trace = traces[i];
try {
if (found) {
if (!trace.getClassName().startsWith(className)) {
Class<?> clazz = Class.forName(trace.getClassName());
return "[" + getClassName(clazz) + ":" + trace.getMethodName() + ":" + trace.getLineNumber() + "]: ";
}
}
else if (trace.getClassName().startsWith(className)) {
found = true;
continue;
}
}
catch (ClassNotFoundException e) {
}
}
return " ";
}
private static String getClassName(Class<?> clazz) {
if (clazz != null) {
if (clazz.getSimpleName() != null) {
if (!clazz.getSimpleName().isEmpty())
return clazz.getSimpleName();
}
return getClassName(clazz.getEnclosingClass());
}
return "";
}
}
|
/*
* Copyright (c) 2016 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.webadmin.tprofile;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.server.api.AttributesManagement;
import pl.edu.icm.unity.server.api.AuthenticationManagement;
import pl.edu.icm.unity.server.api.GroupsManagement;
import pl.edu.icm.unity.server.api.IdentitiesManagement;
import pl.edu.icm.unity.server.utils.UnityMessageSource;
import pl.edu.icm.unity.types.authn.CredentialRequirements;
import pl.edu.icm.unity.types.basic.AttributeType;
import pl.edu.icm.unity.types.basic.IdentityType;
import pl.edu.icm.unity.types.translation.ActionParameterDefinition;
/**
* Responsible for creating {@link ActionParameterComponent}s.
* Design note: the factory is split in the way that it returns an intermediate Provider object
* that in turn returns final components. It was done to allow to create a reusable provider
* per user.
* @author K. Benedyczak
*/
@Component
public class ActionParameterComponentFactory
{
@Autowired
private UnityMessageSource msg;
@Autowired
private AttributesManagement attrsMan;
@Autowired
private IdentitiesManagement idMan;
@Autowired
private AuthenticationManagement authnMan;
@Autowired
private GroupsManagement groupsMan;
public Provider getComponentProvider() throws EngineException
{
return new Provider();
}
public class Provider
{
private List<String> groups;
private Collection<String> credReqs;
private Collection<String> idTypes;
private Collection<AttributeType> atTypes;
private Provider() throws EngineException
{
this.atTypes = attrsMan.getAttributeTypes();
this.groups = new ArrayList<>(groupsMan.getChildGroups("/"));
Collections.sort(groups);
Collection<CredentialRequirements> crs = authnMan.getCredentialRequirements();
credReqs = new TreeSet<String>();
for (CredentialRequirements cr: crs)
credReqs.add(cr.getName());
Collection<IdentityType> idTypesF = idMan.getIdentityTypes();
idTypes = new TreeSet<String>();
for (IdentityType it: idTypesF)
if (!it.getIdentityTypeProvider().isDynamic())
idTypes.add(it.getIdentityTypeProvider().getId());
}
public ActionParameterComponent getParameterComponent(ActionParameterDefinition param)
{
switch (param.getType())
{
case ENUM:
return new EnumActionParameterComponent(param, msg);
case UNITY_ATTRIBUTE:
return new AttributeActionParameterComponent(param, msg, atTypes);
case UNITY_GROUP:
return new BaseEnumActionParameterComponent(param, msg, groups);
case UNITY_CRED_REQ:
return new BaseEnumActionParameterComponent(param, msg, credReqs);
case UNITY_ID_TYPE:
return new BaseEnumActionParameterComponent(param, msg, idTypes);
case EXPRESSION:
return new ExpressionActionParameterComponent(param, msg);
case DAYS:
return new DaysActionParameterComponent(param, msg);
case LARGE_TEXT:
return new TextAreaActionParameterComponent(param, msg);
case I18N_TEXT:
return new I18nTextActionParameterComponent(param, msg);
case TEXT:
return new DefaultActionParameterComponent(param, msg, false);
case BOOLEAN:
return new BooleanActionParameterComponent(param, msg);
default:
return new DefaultActionParameterComponent(param, msg);
}
}
}
}
|
package com.git.cloud.iaas.openstack.service;
import com.alibaba.fastjson.JSONArray;
import com.git.cloud.cloudservice.model.po.CloudFlavorPo;
import com.git.cloud.iaas.openstack.model.FlavorRestModel;
import com.git.cloud.iaas.openstack.model.OpenstackIdentityModel;
import com.git.cloud.iaas.openstack.model.VmRestModel;
public interface OpenstackComputeService {
String getGroupHost(OpenstackIdentityModel model) throws Exception;
String getGroupHostRes(OpenstackIdentityModel model) throws Exception;
String getGroupHostResDetail(OpenstackIdentityModel model,String hostId) throws Exception;
String getFlavor(OpenstackIdentityModel model) throws Exception;
String getFlavorDetail(OpenstackIdentityModel model, String flavorId) throws Exception;
String createFlavor(OpenstackIdentityModel model, CloudFlavorPo flavor) throws Exception;
void configFlavorVm(OpenstackIdentityModel model, String flavorId, FlavorRestModel flavor) throws Exception;
void configFlavorHost(OpenstackIdentityModel model, String flavorId, FlavorRestModel flavor) throws Exception;
void operateVm(OpenstackIdentityModel model, String serverId, String type) throws Exception;
void operateVm(OpenstackIdentityModel model, String serverId, String type, int resultCode) throws Exception;
void resizeVm(OpenstackIdentityModel model, String serverId, String flavorId) throws Exception;
void updateVm(OpenstackIdentityModel model, String serverId, String serverName) throws Exception;
void moveVm(OpenstackIdentityModel model, String serverId, String hostName) throws Exception;
void operateHost(OpenstackIdentityModel model, String serverId, String type, int resultCode) throws Exception;
String getVNCConsole(OpenstackIdentityModel model, String serverId) throws Exception;
String getVNCConsolePhy(OpenstackIdentityModel model, String serverId) throws Exception;
String createVm(OpenstackIdentityModel model, VmRestModel vmRestModel,String ipData) throws Exception;
String createHost(OpenstackIdentityModel model, VmRestModel vmRestModel,String ipData) throws Exception;
String getServerDetail(OpenstackIdentityModel model, String serverId, boolean isVm) throws Exception;
String getServerState(OpenstackIdentityModel model, String serverId, boolean isVm) throws Exception;
String getServerList(OpenstackIdentityModel model) throws Exception;
String mountServerVolume(OpenstackIdentityModel model, String serverId, String volumeId, boolean isVm) throws Exception;
String getServerVolume(OpenstackIdentityModel model, String serverId, boolean isVm) throws Exception;
void unmountServerVolume(OpenstackIdentityModel model, String serverId, String volumeId, boolean isVm) throws Exception;
String getNetworkCard(OpenstackIdentityModel model, String serverId) throws Exception;
String getNetworkCardStatus(OpenstackIdentityModel model, String serverId,String portId) throws Exception;
void deleteNetworkCard(OpenstackIdentityModel model, String serverId ,String portId) throws Exception;
String addNetworkCard(OpenstackIdentityModel model, String serverId ,String portId) throws Exception;
void putComputeQuota(OpenstackIdentityModel model, String setProjectId) throws Exception;
void addSecurityGroup(OpenstackIdentityModel model, VmRestModel vmModel) throws Exception;
void removeSecurityGroup(OpenstackIdentityModel model, VmRestModel vmModel) throws Exception;
String createFloatingIp(OpenstackIdentityModel model, VmRestModel vmModel) throws Exception;
void deleteFloatingIp(OpenstackIdentityModel model, VmRestModel vmModel) throws Exception;
void addFloatingIp(OpenstackIdentityModel model, VmRestModel vmModel) throws Exception;
void removeFloatingIp(OpenstackIdentityModel model, VmRestModel vmModel) throws Exception;
JSONArray getAvailabilityZoneList(OpenstackIdentityModel model) throws Exception;
String createVmGroup(OpenstackIdentityModel model, String name, String policy) throws Exception;
String getServerGroupDetails(OpenstackIdentityModel model, String id) throws Exception;
String deleteVmGroup(OpenstackIdentityModel model, String id) throws Exception;
String getBaremetal(OpenstackIdentityModel model) throws Exception;
String getBaremetalDetail(OpenstackIdentityModel model,String hostId) throws Exception;
String createVmForGroup(OpenstackIdentityModel model,VmRestModel vmRestModel,String ipData) throws Exception;
String getBuildBareMetal(OpenstackIdentityModel model, String serverName) throws Exception;
String deleteHost(OpenstackIdentityModel model,String serverId)throws Exception ;
}
|
package com.github.vincedall.wenote;
public class ListItems {
private String title;
private String number;
private String date;
private long modifiedTime;
public ListItems(String title, String number, String date, long modifiedTime) {
this.title = title;
this.number = number;
this.date = date;
this.modifiedTime = modifiedTime;
}
public String getTitle(){
return title;
}
public String getNumber(){
return number;
}
public String getDate() { return date; }
public long getModifiedTime(){ return modifiedTime; }
public void setModifiedTime(long modifiedTime) { this.modifiedTime = modifiedTime; }
}
|
package com.example.parcial3capas.domain;
import org.springframework.validation.annotation.Validated;
import javax.persistence.*;
import javax.validation.constraints.*;
@Entity
@Table(schema = "public", name = "materia_estudiante")
public class MateriaxEstudiante {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "c_materia")
private Materia materia;
@Transient
private Integer codigoMateria;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "c_estudiante")
private Estudiante estudiante;
@Transient
private Integer codigoEstudiante;
@Id
@GeneratedValue(generator = "materia_estudiante_seq", strategy = GenerationType.AUTO)
@Column(name = "c_materia_estudiante")
private Integer codigoMateriaE;
@Column(name = "s_anio")
private String anio;
@Column(name = "s_ciclo")
private String ciclo;
@Column(name = "s_nota")
private String nota;
public MateriaxEstudiante() {
}
public Materia getMateria() {
return materia;
}
public void setMateria(Materia materia) {
this.materia = materia;
}
public Integer getCodigoMateria() {
return codigoMateria;
}
public void setCodigoMateria(Integer codigoMateria) {
this.codigoMateria = codigoMateria;
}
public Estudiante getEstudiante() {
return estudiante;
}
public void setEstudiante(Estudiante estudiante) {
this.estudiante = estudiante;
}
public Integer getCodigoEstudiante() {
return codigoEstudiante;
}
public void setCodigoEstudiante(Integer codigoEstudiante) {
this.codigoEstudiante = codigoEstudiante;
}
public Integer getCodigoMateriaE() {
return codigoMateriaE;
}
public void setCodigoMateriaE(Integer codigoMateriaE) {
this.codigoMateriaE = codigoMateriaE;
}
public String getAnio() {
return anio;
}
public void setAnio(String anio) {
this.anio = anio;
}
public String getCiclo() {
return ciclo;
}
public void setCiclo(String ciclo) {
this.ciclo = ciclo;
}
public String getNota() {
return nota;
}
public void setNota(String nota) {
this.nota = nota;
}
}
|
package com.codecool.app;
import java.util.List;
public class Player {
protected String name;
private Hand hand;
private int points = 0;
public Player(List<Card> cards){
this.hand = new Hand(cards);
}
public String getName(){
return name;
}
public Hand getHand(){
return hand;
}
public int getPoints(){
return points;
}
public void setPoints(){
points++;
}
public void setName(String playerName){
this.name = playerName;
}
}
|
package com.gxtc.huchuan.data;
import com.gxtc.commlibrary.data.BaseRepository;
import com.gxtc.huchuan.bean.pay.AccountBean;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.http.ApiObserver;
import com.gxtc.huchuan.http.ApiResponseBean;
import com.gxtc.huchuan.http.service.MineApi;
import com.gxtc.huchuan.ui.mine.editinfo.vertifance.VertifanceContract;
import java.util.HashMap;
import java.util.List;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by Administrator on 2017/6/26 0026.
*/
public class VertifanceRepository extends BaseRepository implements VertifanceContract.Source {
@Override
public void Vertifance(ApiCallBack<Object>callBack,HashMap<String,String> map) {
addSub(MineApi.getInstance().userRealAudit(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ApiObserver<ApiResponseBean<Object>>(callBack)));
// HashMap<String,String> map = new HashMap<>();
// map.put("token",token);
// map.put("token",token);
// map.put("token",token);
// map.put("token",token);
// if(!TextUtils.isEmpty(token)){
// map.put("token",token);
// }
}
@Override
public void VertifanceAccoun(ApiCallBack<List<AccountBean>> callBack, HashMap<String, String> map) {
addSub(MineApi.getInstance().getAccountSet(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ApiObserver<ApiResponseBean<List<AccountBean>>>(callBack)));
}
}
|
package com.kkwli.springcloud.service.impl;
import com.kkwli.springcloud.service.PaymentHystrixService;
import org.springframework.stereotype.Component;
/**
* @Author kkwli
* @Since 2021/9/25 14:04
*/
@Component
public class PaymentHystrixServiceImpl implements PaymentHystrixService {
@Override
public String paymentInfo_OK(Integer id) {
return "------PaymentHystrixServiceImpl fallback-paymentInfo_OK,/(ㄒoㄒ)/~~";
}
@Override
public String paymentInfo_TimeOut(Integer id) {
return "------PaymentHystrixServiceImpl fallback-paymentInfo_TimeOut,/(ㄒoㄒ)/~~";
}
}
|
/*
* Copyright (c) 2013 MercadoLibre -- All rights reserved
*/
package com.zauberlabs.bigdata.lamdaoa.batch.jobs.playercounter;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import com.zauberlabs.bigdata.lamdaoa.batch.jobs.util.CsvTupleSerializationFormat;
import com.zauberlabs.bigdata.lamdaoa.batch.jobs.util.TupleSerializationFormat;
/**
* For each entry with format <gameid,fragger, fragged> produces:
*
* fragger 1
*
*
* @since Jul 5, 2013
*/
public class PlayerFragCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
private TupleSerializationFormat format = new CsvTupleSerializationFormat();
@Override
protected final void map(LongWritable key, Text value,
Mapper<LongWritable, Text, Text, IntWritable>.Context ctx)
throws IOException, InterruptedException {
String[] tuple = format.deSerialize(value.toString());
if (checkTuple(tuple)) {
String fragger = tuple[1];
ctx.write(new Text(fragger), new IntWritable(1));
}
}
private boolean checkTuple(String[] tuple) {
return tuple != null && tuple.length == 3 && noEmptyElements(tuple);
}
private boolean noEmptyElements(String[] array) {
for (String string : array) {
if (string == null) {
return false;
}
}
return true;
}
}
|
package orm.integ.eao.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TableModels {
private static final Map<String, TableModel> models = new HashMap<>();
private static final Map<String, TableModel> tabNameModels = new HashMap<>();
private static Map<String, List<FieldInfo>> fkMap = new HashMap<>();
public static void putModel(TableModel model) {
if (model!=null) {
models.put(model.getObjectClass().getName(), model);
tabNameModels.put(model.getFullTableName().toLowerCase(), model);
}
}
@SuppressWarnings("unchecked")
public static <T extends TableModel> T getModel(Class<?> clazz) {
TableModel model = models.get(clazz.getName());
if (model==null) {
System.out.println(clazz.getName()+" 没有注册TableModel");
}
return (T) model;
}
public static List<FieldInfo> getForeignKeyFields(Class<? extends Entity> clazz) {
List<FieldInfo> list = fkMap.get(clazz.getName());
if (list==null) {
list = scanForeignKeys(clazz);
fkMap.put(clazz.getName(), list);
}
return list;
}
private static List<FieldInfo> scanForeignKeys(Class<? extends Entity> clazz) {
List<FieldInfo> fields = new ArrayList<>();
for (TableModel em: models.values()) {
for (FieldInfo field: em.fields) {
if (field.isForeignKey()) {
if (field.getMasterClass()==clazz) {
fields.add(field);
}
}
}
}
return fields;
}
@SuppressWarnings("unchecked")
public static <T extends TableModel> T getByTableName(String tableName) {
if (tableName==null) {
return null;
}
return (T) tabNameModels.get(tableName.toLowerCase());
}
}
|
package com.platform.au.entity;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Role implements Serializable{
private static final long serialVersionUID = 1L;
private String role_id;
private String role_code;
private String role_name;
private String description;
private String enable_flag;
public String getRole_id() {
return role_id;
}
public void setRole_id(String role_id) {
this.role_id = role_id;
}
public String getRole_code() {
return role_code;
}
public void setRole_code(String role_code) {
this.role_code = role_code;
}
public String getRole_name() {
return role_name;
}
public void setRole_name(String role_name) {
this.role_name = role_name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEnable_flag() {
return enable_flag;
}
public void setEnable_flag(String enable_flag) {
this.enable_flag = enable_flag;
}
}
|
package com.beike.common.entity.trx;
import java.util.Date;
import com.beike.common.enums.trx.VoucherStatus;
import com.beike.common.enums.trx.VoucherVerifySource;
/**
* @Title: Voucher.java
* @Package com.beike.common.entity.trx
* @Description: 凭证实体
* @date May 26, 2011 4:58:40 PM
* @author wh.cheng
* @version v1.0
*/
public class Voucher {
private Long id;
private Long guestId = 0L;
private Date createDate;
private Date activeDate;
private Date confirmDate;
private String voucherCode;
private VoucherStatus voucherStatus;
private VoucherVerifySource voucherVerifySource;
private String description = "";
private Long isPrefetch;// 是否被预。0:未被预取;1:被预取.
private Date prefetchDate;// 预取时间
/**
* 乐观锁版本号
*/
private Long version = 0L;
public Long getIsPrefetch() {
return isPrefetch;
}
public void setIsPrefetch(Long isPrefetch) {
this.isPrefetch = isPrefetch;
}
public Date getPrefetchDate() {
return prefetchDate;
}
public void setPrefetchDate(Date prefetchDate) {
this.prefetchDate = prefetchDate;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
private boolean isSendMerVou = false;// 是否使用的是商家凭证码(用户商家凭证码不足时候的短信模板切换)
public Voucher() {
}
public Voucher(Date createDate, String voucherCode,
VoucherStatus voucherStatus) {
this.createDate = createDate;
this.voucherCode = voucherCode;
this.voucherStatus = voucherStatus;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getGuestId() {
return guestId;
}
public void setGuestId(Long guestId) {
this.guestId = guestId;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getConfirmDate() {
return confirmDate;
}
public void setConfirmDate(Date confirmDate) {
this.confirmDate = confirmDate;
}
public String getVoucherCode() {
return voucherCode;
}
public void setVoucherCode(String voucherCode) {
this.voucherCode = voucherCode;
}
public VoucherStatus getVoucherStatus() {
return voucherStatus;
}
public void setVoucherStatus(VoucherStatus voucherStatus) {
this.voucherStatus = voucherStatus;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getActiveDate() {
return activeDate;
}
public void setActiveDate(Date activeDate) {
this.activeDate = activeDate;
}
/**
* @return the voucherVerifySource
*/
public VoucherVerifySource getVoucherVerifySource() {
return voucherVerifySource;
}
/**
* @param voucherVerifySource
* the voucherVerifySource to set
*/
public void setVoucherVerifySource(VoucherVerifySource voucherVerifySource) {
this.voucherVerifySource = voucherVerifySource;
}
public boolean isSendMerVou() {
return isSendMerVou;
}
public void setSendMerVou(boolean isSendMerVou) {
this.isSendMerVou = isSendMerVou;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Voucher other = (Voucher) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
|
package pl.manufacturer.object.example.pojo.simple;
import pl.manufacturer.object.example.pojo.test.Size;
public class SimpleEnumObject {
private Size size;
public Size getSize() {
return size;
}
public void setSize(Size size) {
this.size = size;
}
}
|
/*
* 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 panel;
import Auto.ChangeShow;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import javax.swing.JLabel;
import weixin.AdminMain;
/**
*
* @author jerry
*/
public class FriendsPanel extends javax.swing.JPanel {
/**
* 当前账号下的所有朋友的panel集合
*/
public HashMap one_admin_all_friends_panel = new HashMap();
/**
* 当前选中的要显示的朋友类型
* <br>
*/
public JLabel SelectJLabel;
/**
* Creates new form FriendsPanel
*/
public FriendsPanel() {
initComponents();
friends_list.getVerticalScrollBar().setUI(new ColorScrollBarUI(friends_list.getBackground(), Color.BLACK, 5));
friends_list.getViewport().setOpaque(false);
SelectJLabel = select_friend;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
my_nick_name = new javax.swing.JLabel();
out_login = new javax.swing.JButton();
search_friend = new javax.swing.JTextField();
friends_list = new javax.swing.JScrollPane();
show_friends_list = new javax.swing.JPanel();
select_type = new javax.swing.JPanel();
select_new_msg = new javax.swing.JLabel();
select_friend = new javax.swing.JLabel();
select_group = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jSeparator2 = new javax.swing.JSeparator();
setBackground(new java.awt.Color(46, 50, 56));
setMinimumSize(new java.awt.Dimension(237, 651));
setPreferredSize(new java.awt.Dimension(237, 651));
setSize(new java.awt.Dimension(237, 651));
my_nick_name.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
my_nick_name.setForeground(new java.awt.Color(255, 255, 255));
my_nick_name.setText("NickName");
out_login.setBackground(new java.awt.Color(46, 50, 56));
out_login.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/out.png"))); // NOI18N
out_login.setToolTipText("点击退出账号!");
out_login.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
out_login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
out_loginActionPerformed(evt);
}
});
search_friend.setBackground(new java.awt.Color(0, 0, 0));
search_friend.setForeground(new java.awt.Color(204, 204, 204));
search_friend.setText("搜索");
search_friend.setToolTipText("输入关键字后点击回车!进行搜索");
search_friend.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 5, true));
search_friend.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
search_friendFocusGained(evt);
}
});
search_friend.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
search_friendKeyPressed(evt);
}
});
friends_list.setBackground(new java.awt.Color(46, 50, 56));
friends_list.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
friends_list.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
friends_list.setOpaque(false);
friends_list.setPreferredSize(new java.awt.Dimension(0, 0));
show_friends_list.setOpaque(false);
show_friends_list.setPreferredSize(new java.awt.Dimension(237, 500));
javax.swing.GroupLayout show_friends_listLayout = new javax.swing.GroupLayout(show_friends_list);
show_friends_list.setLayout(show_friends_listLayout);
show_friends_listLayout.setHorizontalGroup(
show_friends_listLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 237, Short.MAX_VALUE)
);
show_friends_listLayout.setVerticalGroup(
show_friends_listLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 530, Short.MAX_VALUE)
);
friends_list.setViewportView(show_friends_list);
select_type.setBackground(new java.awt.Color(46, 50, 56));
select_new_msg.setBackground(new java.awt.Color(46, 50, 56));
select_new_msg.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
select_new_msg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon_new_msg.png"))); // NOI18N
select_new_msg.setToolTipText("点击查看新消息列表!");
select_new_msg.setName("last"); // NOI18N
select_new_msg.setOpaque(true);
select_new_msg.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
select_MouseClicked(evt);
}
});
select_friend.setBackground(new java.awt.Color(0, 0, 0));
select_friend.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
select_friend.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon_friend.png"))); // NOI18N
select_friend.setToolTipText("点击查看所有好友!");
select_friend.setName("friends"); // NOI18N
select_friend.setOpaque(true);
select_friend.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
select_MouseClicked(evt);
}
});
select_group.setBackground(new java.awt.Color(46, 50, 56));
select_group.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
select_group.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon_friends.png"))); // NOI18N
select_group.setToolTipText("点击查看所有群聊!");
select_group.setName("group"); // NOI18N
select_group.setOpaque(true);
select_group.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
select_MouseClicked(evt);
}
});
jSeparator1.setForeground(new java.awt.Color(0, 0, 0));
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator2.setForeground(new java.awt.Color(0, 0, 0));
jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);
javax.swing.GroupLayout select_typeLayout = new javax.swing.GroupLayout(select_type);
select_type.setLayout(select_typeLayout);
select_typeLayout.setHorizontalGroup(
select_typeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(select_typeLayout.createSequentialGroup()
.addContainerGap()
.addComponent(select_new_msg, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(select_friend, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(select_group)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
select_typeLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {select_friend, select_group, select_new_msg});
select_typeLayout.setVerticalGroup(
select_typeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(select_typeLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(select_typeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(select_new_msg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(select_typeLayout.createSequentialGroup()
.addGroup(select_typeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
.addComponent(select_friend, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(select_group, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(friends_list, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(my_nick_name)
.addGap(93, 93, 93)
.addComponent(out_login, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(select_type, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(search_friend)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(out_login, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(my_nick_name, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(10, 10, 10)
.addComponent(search_friend, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(select_type, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(friends_list, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
getAccessibleContext().setAccessibleParent(this);
}// </editor-fold>//GEN-END:initComponents
/**
* 点击朋友列表后的退出按钮,对当前账号进行退出
*
* @param evt
*/
private void out_loginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_out_loginActionPerformed
String WXUid = evt.getActionCommand();
ChangeShow.CloseOneWxAdmin(WXUid);
//还要清理消息框内容
AdminMain.all_msg_panel.removeAll();
AdminMain.all_msg_panel.repaint();
AdminMain.push_msg.setActionCommand("");
AdminMain.friend_name.setText("未选择好友");
}//GEN-LAST:event_out_loginActionPerformed
/**
* 选择显示用户类型的图标事件
*
* @param evt
*/
private void select_MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_select_MouseClicked
String WXUid = out_login.getActionCommand();
String type_name = evt.getComponent().getName();
//一样就不刷新
if (SelectJLabel.getName().equals(type_name)) {
return;
}
//不一样就改变老的颜色
SelectJLabel.setBackground(new Color(46, 50, 56));
//再改变新的颜色
evt.getComponent().setBackground(new Color(0, 0, 0));
//开始刷新
ChangeShow.REShowSelectTypeFriends(WXUid, type_name);
//最后改变控件
SelectJLabel = (JLabel) evt.getComponent();
}//GEN-LAST:event_select_MouseClicked
/**
* 搜索框获得焦点事件
*
* @param evt
*/
private void search_friendFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_search_friendFocusGained
String text_string = search_friend.getText();
if (text_string.equals("搜索")) {
search_friend.setText("");
}
}//GEN-LAST:event_search_friendFocusGained
/**
* 搜索框对 回车键的响应
*
* @param evt
*/
private void search_friendKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_search_friendKeyPressed
String WXUid = out_login.getActionCommand();
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
System.err.println("提交的搜索内容是:" + search_friend.getText());
ChangeShow.REShowSelectTypeFriends(WXUid, "search");
}
}//GEN-LAST:event_search_friendKeyPressed
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JScrollPane friends_list;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
public javax.swing.JLabel my_nick_name;
public javax.swing.JButton out_login;
public javax.swing.JTextField search_friend;
private javax.swing.JLabel select_friend;
private javax.swing.JLabel select_group;
private javax.swing.JLabel select_new_msg;
private javax.swing.JPanel select_type;
public javax.swing.JPanel show_friends_list;
// End of variables declaration//GEN-END:variables
}
|
package com.bawei.api;
import com.bawei.api.domain.ProductRpcReq;
import com.bawei.entity.Product;
import com.googlecode.jsonrpc4j.JsonRpcService;
import java.util.List;
/**
* 产品相关的rpc服务
*/
@JsonRpcService("rpc/product")
public interface ProductRpc {
// 复杂查询接口
List<Product> query(ProductRpcReq req);
// 单个查询接口
Product findOne(String id);
}
|
package com.rengu.operationsmanagementsuitev3.Controller;
import com.rengu.operationsmanagementsuitev3.Entity.ResultEntity;
import com.rengu.operationsmanagementsuitev3.Service.DeploymentDesignDetailService;
import com.rengu.operationsmanagementsuitev3.Utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
/**
* @program: OperationsManagementSuiteV3
* @author: hanchangming
* @create: 2018-09-04 13:13
**/
@RestController
@RequestMapping(value = "/deploymentdesigndetails")
public class DeploymentDesignDetailController {
private final DeploymentDesignDetailService deploymentDesignDetailService;
@Autowired
public DeploymentDesignDetailController(DeploymentDesignDetailService deploymentDesignDetailService) {
this.deploymentDesignDetailService = deploymentDesignDetailService;
}
@DeleteMapping(value = "/{deploymentDesignDetailId}")
public ResultEntity deleteDeploymentDesignDetailById(@PathVariable(value = "deploymentDesignDetailId") String deploymentDesignDetailId) {
return ResultUtils.build(deploymentDesignDetailService.deleteDeploymentDesignDetailById(deploymentDesignDetailId));
}
// 根据部署设计Id及设备Id进行扫描
@GetMapping(value = "/{deploymentDesignDetailId}/scan")
public ResultEntity scanDeploymentDesignDetailsByDeploymentDesignAndDevice(@PathVariable(value = "deploymentDesignDetailId") String deploymentDesignDetailId, @RequestParam(value = "extensions", required = false, defaultValue = "") String... extensions) throws InterruptedException, ExecutionException, IOException, TimeoutException {
return ResultUtils.build(deploymentDesignDetailService.scanDeploymentDesignDetailsById(deploymentDesignDetailId, extensions, ""));
}
}
|
package com.mwi.aws.dynamodb.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class OwnerConfigTest {
// private static OwnerConfigTest instance;
//
// public static OwnerConfig owner = new OwnerConfig();
// public static OwnerConfigTest getInstance(){
// if(instance==null){
// instance=new OwnerConfigTest();
// }
// return instance;
// }
//
// public OwnerConfigTest() {
// owner.setAddress("huayang street");
// owner.setOwner("taolin");
//
// Map contactMap = new HashMap();
//
// Contact contact = new Contact();
// contact.setContactName("tester1");
// contact.setEmail("tester1@qq.com");
// contact.setPhoneNumber("11111");
// contactMap.put(contact.getContactName(), contact);
//
// contact = new Contact();
// contact.setContactName("tester2");
// contact.setEmail("tester2@qq.com");
// contact.setPhoneNumber("22222");
// contactMap.put(contact.getContactName(), contact);
//
// contact = new Contact();
// contact.setContactName("tester3");
// contact.setEmail("tester3@qq.com");
// contact.setPhoneNumber("33333");
// contactMap.put(contact.getContactName(), contact);
//
// owner.setContacts(contactMap);
// }
//
// public OwnerConfig getOwner() {
// return owner;
// }
//
//
//
//
// public static void main(String[] args) {
//
// System.out.println(OwnerConfigTest.getInstance().getOwner().toJSON());
// }
}
|
package com.dokyme.alg4.sorting.application;
import com.dokyme.alg4.sorting.merge.Merge;
import com.dokyme.alg4.sorting.quick.Quick;
import edu.princeton.cs.algs4.StdOut;
import java.io.File;
import java.util.Comparator;
/**
* Created by intellij IDEA.But customed by hand of Dokyme.
*
* @author dokym
* @date 2018/5/31-19:58
* Description:
*/
public class FileSorter {
public static class FileSizeComparator implements Comparator<File> {
private Comparator comparator;
public FileSizeComparator(Comparator comparator) {
this.comparator = comparator;
}
@Override
public int compare(File o1, File o2) {
if (o1.getTotalSpace() == o2.getTotalSpace() && comparator != null) {
return comparator.compare(o1, o2);
}
return o1.getTotalSpace() > o2.getTotalSpace() ? 1 : -1;
}
}
public static class FileNameComparator implements Comparator<File> {
private Comparator comparator;
public FileNameComparator(Comparator comparator) {
this.comparator = comparator;
}
@Override
public int compare(File o1, File o2) {
if (o1.getName().equals(o2.getName()) && comparator != null) {
return comparator.compare(o1, o2);
}
return o1.getName().compareTo(o2.getName());
}
}
public static class ModifiedComparator implements Comparator<File> {
private Comparator comparator;
public ModifiedComparator(Comparator comparator) {
this.comparator = comparator;
}
@Override
public int compare(File o1, File o2) {
if (o1.lastModified() == o2.lastModified() && comparator != null) {
return comparator.compare(o1, o2);
}
return o1.lastModified() > o2.lastModified() ? 1 : -1;
}
}
public void sort(String path, Comparator c) {
File[] files = new File(path).listFiles();
new Merge().sort(files, c);
for (File f : files) {
StdOut.println(f.getName());
}
}
public static void main(String[] args) {
boolean asc = true;
String path = null;
Comparator c = null;
for (String arg : args) {
switch (arg) {
case "-t":
c = new ModifiedComparator(c);
break;
case "-n":
c = new FileNameComparator(c);
break;
case "-s":
c = new FileSizeComparator(c);
break;
default:
path = arg;
break;
}
}
if (path == null) {
StdOut.println("Error:Path is empty!");
}
new FileSorter().sort(path, c);
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.webui.common.bigtab;
import pl.edu.icm.unity.webui.common.Styles;
import com.vaadin.event.LayoutEvents.LayoutClickEvent;
import com.vaadin.event.LayoutEvents.LayoutClickListener;
import com.vaadin.server.Resource;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Image;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
/**
* A single clickable big tab. {@link BigTabs} groups this object instances.
* @author K. Benedyczak
*/
public class BigTab extends VerticalLayout
{
private final TabCallback callback;
public BigTab(int width, Unit unit, String label, String description, Resource image, TabCallback callback)
{
this.callback = callback;
if (image != null)
{
Image img = new Image();
img.setSource(image);
addComponent(img);
setComponentAlignment(img, Alignment.TOP_CENTER);
}
if (description != null)
setDescription(description);
if (label != null)
{
Label info = new Label(label);
info.setWidth(width, unit);
info.addStyleName(Styles.textCenter.toString());
addComponent(info);
setComponentAlignment(info, Alignment.TOP_CENTER);
}
addStyleName(Styles.bigTab.toString());
addLayoutClickListener(new LayoutClickListener()
{
@Override
public void layoutClick(LayoutClickEvent event)
{
select();
}
});
setMargin(new MarginInfo(true, false, true, false));
}
public void deselect()
{
addStyleName(Styles.bigTab.toString());
removeStyleName(Styles.bigTabSelected.toString());
}
public void select()
{
callback.onSelection(this);
removeStyleName(Styles.bigTab.toString());
addStyleName(Styles.bigTabSelected.toString());
}
public interface TabCallback
{
public void onSelection(BigTab src);
}
}
|
/*
* @(#) IXmlDsigInfoService.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ims.xmldsiginfo.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.esum.appframework.service.IBaseService;
/**
*
* @author sjyim@esumtech.com
* @version $Revision: 1.2 $ $Date: 2009/01/16 08:23:00 $
*/
public interface IXmlDsigInfoService extends IBaseService {
Object searchXmlDsigInfoId(Object object);
Object xmlDsigInfoDetail(Object object);
Object xmlDsigInfoPageList(Object object);
Object selectDsiNodeList (Object object);
void saveXmlDsigInfoExcel (Object object, HttpServletRequest request, HttpServletResponse response) throws Exception;
}
|
package KwonOkyo;
class WooDong implements Product {
int price=1300; //우동의 현재가격
private double bonusPoint = 0;
public int setPrice(int price) {return this.price = price;}
public int getPrice() {return this.price;}
public double getBonusPoint(){//가격의 10%만큼 보너스포인트 추가
bonusPoint = this.price*0.1;
return bonusPoint;
}
public String toString() { return "생생우동"; }
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.