text
stringlengths 10
2.72M
|
|---|
package com.project1.web1.application;
public class DataBaseException extends RuntimeException {
public DataBaseException() {
super("Request is processing");
}
}
|
package com.buildbooster.inventory.validator;
|
package com.zhengsr.viewpagerlib;
import android.content.Context;
import android.support.annotation.Nullable;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.zhengsr.viewpagerlib.callback.BitmapListener;
public class GlideManager {
public static final int BITMAP_SCAN_CENTERN = 1;
public static final int BITMAP_SCAN_FIT = 2;
private static final String TAG = "zsr";
private BitmapListener mBitmapListener;
public GlideManager(Builder builder){
RequestOptions options = new RequestOptions()
.placeholder(builder.placeresid);
if (builder.eroorresid != 0){
options.error(builder.eroorresid);
}
switch (builder.type){
case BITMAP_SCAN_CENTERN:
options.centerCrop();
break;
case BITMAP_SCAN_FIT:
options.fitCenter();
break;
default:
break;
}
if (builder.setCircleCrop){
options.circleCrop();
}
if (builder.radius != 0){
options.transform(new RoundedCorners(builder.radius));
}
RequestBuilder requestBuilder = null;
requestBuilder = Glide.with(builder.context).load(builder.source);
if (builder.animtime > 0){
requestBuilder.transition(new DrawableTransitionOptions().crossFade(builder.animtime));
}
requestBuilder.apply(options)
.listener(new LoadListener())
.into(builder.imageView);
}
public GlideManager addLoadLstner(BitmapListener listener){
mBitmapListener = listener;
return this;
}
class LoadListener implements RequestListener {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
if (mBitmapListener != null){
mBitmapListener.onFailure(e);
}
return false;
}
@Override
public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
if (mBitmapListener != null){
mBitmapListener.onSuccess(resource);
}
return false;
}
}
public static class Builder{
Context context;
int eroorresid;
int placeresid;
Object source;
boolean setCircleCrop;
int radius = 0;
int type;
int animtime;
ImageView imageView;
public Builder setContext(Context context){
this.context = context;
return this;
}
public Builder setBitmapScanType(int type){
this.type = type;
return this;
}
public Builder setLoadingBitmap(int resid){
this.placeresid = resid;
return this;
}
public Builder setErrorBitmap(int resid){
this.eroorresid = resid;
return this;
}
public Builder setImgSource(Object source){
this.source = source;
return this;
}
public Builder setCircleCrop(boolean setCircleCrop){
this.setCircleCrop = setCircleCrop;
return this;
}
public Builder setRoundCrop(int radius){
this.radius = radius;
return this;
}
public Builder setAnimation(int animtime){
this.animtime = animtime;
return this;
}
public Builder setImageView(ImageView imageView){
this.imageView = imageView;
return this;
}
public GlideManager builder(){
return new GlideManager(this);
}
}
}
|
package com.yida.hanlp;
import java.util.List;
import com.hankcs.hanlp.HanLP;
/**
*********************
* @author yangke
* @version 1.0
* @created 2018年5月21日 下午5:47:01
***********************
*/
public class Test {
public static void main(String[] args) {
// 关键字提取
String content = "程序员(英文Programmer)是从事程序开发、维护的专业人员。一般将程序员分为程序设计人员和程序编码人员,但两者的界限并不非常清楚,特别是在中国。软件从业人员分为初级程序员、高级程序员、系统分析员和项目经理四大类。";
// 数值5表示提取5个关键词
List<String> extractKeyword = HanLP.extractKeyword(content, 5);
for (String string : extractKeyword) {
System.err.println(string);
}
}
}
|
/**
* Class to represent any three-in-a-row spaces on a SubBoard.
* Holds both the position of the line and the player that won the line (either 'x' or 'o').
* Can also represent no line through {@link Line#NONE} and ' ' as winner.
* @author Andy Burris and Kevin Harris
* @version 4 May 2020
*/
public class WinningLine {
private Line line;
private char winner;
public WinningLine(Line line, char winner){
this.line = line;
this.winner = winner;
}
/**
* @return winner that this represents (either 'x', 'o', or ' ')
*/
public char getWinner(){
return winner;
}
/**
* @return {@link Line} that this represents (any of the values of Line)
*/
public Line getLine(){
return line;
}
/**
* Utility method to check if this line represents a winner
* @return false if line is {@link Line#NONE} or char is ' ', true otherwise
*/
public boolean hasWinner(){
return line != Line.NONE && winner != ' ';
}
}
|
package lucene;
import java.util.List;
import java.util.Map;
import system.util.ProjectPath;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import edu.uci.ics.crawler4j.examples.custom.DBUtil;
/**
* @ TODO 为避免数据量过大,需进行分页处理;
* 专门用于处理数据库中类的索引
* 由于数据库中的表与IndexItem的对应关系不一致,需要统一对每张索引的表进行手动对应
*
*/
public class DBIndexUtil {
/**
* 根据主健生成单条记录的索引,随后关闭IndexWriter录
* @param indexDir 索引目录
* @param id 主键id
* @return
*/
public boolean indexMysqlNewsFocusById(String indexDir, String id) {
boolean flag = false;
String sql = "select * from news_focus where id="+id;
List<Map<String,Object>> list = DBUtil.queryFromMySql(sql);
for (Map<String, Object> map : list) {
IndexItem indexItem = changeNewsFocusMapToIndexItem(map);
flag = index(indexDir,indexItem);
}
Indexer indexer = new Indexer(ProjectPath.getIndexPath());
indexer.close();
return flag;
}
/**
* 对mysql-cy-news_focus建立索引,随后关闭IndexWriter
* @param indexDir
* @return
*/
public boolean indexMysqlNewsFocus(String indexDir){
boolean flag = false;
String sql = "select * from news_focus where isdelete='0'";
List<Map<String,Object>> list = DBUtil.queryFromMySql(sql);
for (Map<String, Object> map : list) {
IndexItem indexItem = changeNewsFocusMapToIndexItem(map);
flag = index(indexDir,indexItem);
}
Indexer indexer = new Indexer(ProjectPath.getIndexPath());
indexer.close();
return flag;
}
/**
* 对mongodb-nutch-webpage建立索引,随后关闭IndexWriter
* @param indexDir 索引目录
* @return
*/
public boolean indexMongoDB(String indexDir){
boolean flag = false;
DBCollection dbc = DBUtil.getDBCollection("nutch", "webpage");
DBCursor cursor = dbc.find(new BasicDBObject("contenttype","text/html"));
while(cursor.hasNext()){
DBObject dbo = cursor.next();
Map map = dbo.toMap();
IndexItem indexItem = changeWebPageMapToIndexItem(map);
flag = index(indexDir,indexItem);
}
Indexer indexer = new Indexer(ProjectPath.getIndexPath());
indexer.close();
return flag;
}
private boolean index(String indexDir,IndexItem indexItem ){
Indexer indexer = new Indexer(indexDir);
return indexer.create(indexItem);
}
private IndexItem changeNewsFocusMapToIndexItem(Map<String,Object> map){
IndexItem indexItem = new IndexItem();
indexItem.setAbscontent(returnStr(map.get("introduce")));
indexItem.setAdddate(returnStr(map.get("adddate")));
indexItem.setContent(returnStr(map.get("content")));
indexItem.setFilepath("");
indexItem.setId("mysql_newsfocus_"+returnStr(map.get("id")));
indexItem.setSrcdb("cy");
indexItem.setSrcid(returnStr(map.get("id")));
indexItem.setSrctab("news_focus");
indexItem.setSrctype("mysql");
indexItem.setTitle(returnStr(map.get("name")));
return indexItem;
}
private IndexItem changeWebPageMapToIndexItem(Map map){
IndexItem indexItem = new IndexItem();
indexItem.setAbscontent(null);
indexItem.setAdddate(returnStr(map.get("addtime")));
indexItem.setContent(returnStr(map.get("text")));
indexItem.setFilepath(null);
indexItem.setId("mongodb_nutch_"+returnStr(map.get("url")));
indexItem.setSrcdb("nutch");
indexItem.setSrcid(returnStr(map.get("_id")));
indexItem.setSrctab("webpage");
indexItem.setSrctype("mongodb");
indexItem.setTitle(returnStr(map.get("anchor")));
return indexItem;
}
private String returnStr(Object obj){
return obj!=null?obj.toString():"";
}
}
|
/**
* Copyright 2011 The Buzz Media, LLC
*
* 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.thebuzzmedia.common.util;
import java.io.IOException;
import java.io.InputStream;
import java.text.Format;
import java.text.NumberFormat;
public class ArrayUtilsBenchmark {
public static final int ITERS = 100;
public static final byte VAL = (byte) '#';
public static final byte[] VALS = { (byte) '[', (byte) '#', (byte) ']' };
public static final byte[] DATA = new byte[1024 * 65];
private static final Format FORMAT = NumberFormat.getInstance();
static {
InputStream is = ArrayUtilsBenchmark.class
.getResourceAsStream("65k.txt");
try {
is.read(DATA);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
indexOfValBenchmark();
indexOfValsBenchmark();
indexOfAnyValsBenchmark();
}
public static void indexOfValBenchmark() {
long time = System.currentTimeMillis();
for (int i = 0; i < ITERS; i++) {
if (ArrayUtils.indexOf(VAL, DATA) == -1)
throw new RuntimeException(
"indexOf returned -1, it shouldn't ever do this in this benchmark.");
}
System.out.println("indexOf byte\t\telapsed time: "
+ (System.currentTimeMillis() - time) + "ms\t("
+ FORMAT.format((DATA.length / 2) * ITERS) + " bytes scanned)");
}
public static void indexOfValsBenchmark() {
long time = System.currentTimeMillis();
for (int i = 0; i < ITERS; i++) {
if (ArrayUtils.indexOf(VALS, DATA) == -1)
throw new RuntimeException(
"indexOf returned -1, it shouldn't ever do this in this benchmark.");
}
System.out.println("indexOf byte[]\t\telapsed time: "
+ (System.currentTimeMillis() - time) + "ms\t("
+ FORMAT.format((DATA.length / 2) * ITERS) + " bytes scanned)");
}
public static void indexOfAnyValsBenchmark() {
long time = System.currentTimeMillis();
for (int i = 0; i < ITERS; i++) {
if (ArrayUtils.indexOfAny(VALS, DATA) == -1)
throw new RuntimeException(
"indexOf returned -1, it shouldn't ever do this in this benchmark.");
}
System.out.println("indexOfAny byte[]\telapsed time: "
+ (System.currentTimeMillis() - time) + "ms\t("
+ FORMAT.format((DATA.length / 2) * ITERS) + " bytes scanned)");
}
}
|
package algorithm_test.node;
/**
* Description:
*
* @author Baltan
* @date 2019-02-19 16:12
*/
public class HuffmanCodingNode {
private Byte data;
private int weight;
private HuffmanCodingNode left;
private HuffmanCodingNode right;
public Byte getData() {
return data;
}
public void setData(Byte data) {
this.data = data;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public HuffmanCodingNode getLeft() {
return left;
}
public void setLeft(HuffmanCodingNode left) {
this.left = left;
}
public HuffmanCodingNode getRight() {
return right;
}
public void setRight(HuffmanCodingNode right) {
this.right = right;
}
}
|
package jp.smartcompany.job.common;
/**
* @author xiao wenpeng
*/
public interface Regex {
String USERNAME = "^[a-zA-Z\\d]{2,16}$";
String DATE_YEAR = "^(1|2)\\d{3}$";
/**
* url不能以/或者/list结尾
*/
String MENU_URL = "^sys(\\/([a-zA-Z])+)+(?<!(\\/*list))$";
/**
* 用于shiro验证权限,尾部的权限根据系统需求还可以继续增加,目前暂定为(list|save|delete|update|select)五种
*/
String MENU_PERMS = "^[a-zA-Z,]+$";
String DATE = "^[1-9]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$";
String BASE64 = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
}
|
package com.tencent.mm.ui.chatting.g;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView.t;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.tencent.mm.R;
import com.tencent.mm.ak.o;
import com.tencent.mm.bg.d;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.s;
import com.tencent.mm.plugin.fav.ui.i;
import com.tencent.mm.sdk.platformtools.ao;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.bd;
import com.tencent.mm.ui.chatting.a.b.a;
import com.tencent.mm.ui.chatting.a.b.e;
public final class f extends b {
int gBh = -1;
private int jub = 0;
int tYk = 0;
public f(Context context) {
super(context);
}
public final int getType() {
return 3;
}
public final void cwG() {
this.tXZ.cwK();
g.Ek();
g.Em().H(new 1(this));
}
public final String Wm() {
return this.mContext.getString(R.l.all_history_music);
}
public final String cwJ() {
return this.mContext.getString(R.l.all_history_music);
}
public final e cwH() {
return new 2(this);
}
public final t m(ViewGroup viewGroup) {
return new b(this, LayoutInflater.from(viewGroup.getContext()).inflate(R.i.url_list_item, viewGroup, false));
}
public final void a(a aVar, int i) {
b bVar = (b) aVar;
a aVar2 = (a) EZ(i);
bVar.hrs.setText(i.f(this.mContext, aVar2.timestamp));
Bitmap a = o.Pf().a(aVar2.imagePath, com.tencent.mm.bp.a.getDensity(this.mContext), false);
if (a == null || a.isRecycled()) {
a = com.tencent.mm.pluginsdk.model.app.g.b(aVar2.appId, 1, com.tencent.mm.bp.a.getDensity(this.mContext));
if (a == null || a.isRecycled()) {
bVar.gmn.setImageResource(R.k.app_attach_file_icon_webpage);
bVar.jet.setText(bi.aG(aVar2.bhd, ""));
b.e(bVar.jet, this.tYa.tNU);
}
}
bVar.gmn.setImageBitmap(a);
bVar.jet.setText(bi.aG(aVar2.bhd, ""));
b.e(bVar.jet, this.tYa.tNU);
}
protected final void a(String str, String str2, String str3, int i, String str4, long j, long j2, bd bdVar) {
if ((str == null || str.length() == 0) && (str2 == null || str2.length() == 0)) {
x.e("MicroMsg.MusicHistoryListPresenter", "url, lowUrl both are empty");
return;
}
if (ao.isMobile(this.mContext) ? str2 != null && str2.length() > 0 : str == null || str.length() <= 0) {
str = str2;
}
Intent intent = new Intent();
intent.putExtra("msg_id", j);
intent.putExtra("rawUrl", str);
intent.putExtra("version_name", str3);
intent.putExtra("version_code", i);
intent.putExtra("usePlugin", true);
intent.putExtra("geta8key_username", this.gBf);
intent.putExtra("KPublisherId", "msg_" + Long.toString(j2));
intent.putExtra("KAppId", str4);
String i2 = i(bdVar, s.fq(this.gBf));
intent.putExtra("pre_username", i2);
intent.putExtra("prePublishId", "msg_" + Long.toString(j2));
if (bdVar != null) {
intent.putExtra("preUsername", i2);
}
intent.putExtra("preChatName", this.gBf);
intent.putExtra("preChatTYPE", com.tencent.mm.model.t.N(i2, this.gBf));
intent.putExtra("preMsgIndex", 0);
d.b(this.mContext, "webview", ".ui.tools.WebViewUI", intent);
}
protected static PackageInfo getPackageInfo(Context context, String str) {
String str2;
PackageInfo packageInfo = null;
if (str == null || str.length() == 0) {
str2 = packageInfo;
} else {
com.tencent.mm.pluginsdk.model.app.f bl = com.tencent.mm.pluginsdk.model.app.g.bl(str, true);
if (bl == null) {
Object str22 = packageInfo;
} else {
str22 = bl.field_packageName;
}
}
if (str22 == null) {
return packageInfo;
}
try {
return context.getPackageManager().getPackageInfo(str22, 0);
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.MusicHistoryListPresenter", e, "", new Object[0]);
return packageInfo;
}
}
}
|
package ayou.view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Menu extends Screen {
public class ClickListener extends MouseAdapter {
ScreenID buttonID;
public ClickListener(ScreenID buttonID) {
this.buttonID = buttonID;
}
public void mouseClicked(MouseEvent e) {
view.nextScreen(buttonID);
}
}
public Menu(Viewer view) {
super(view);
Dimension buttonD = new Dimension(100, 30);
Dimension fillerD = new Dimension(100, 10);
Dimension panelD = new Dimension(10, 200);
this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
JPanel panelTitle = new JPanel();
panelTitle.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel titreLbl = new JLabel("Hearth of Magic Duel");
titreLbl.setFont(new Font("Arial", Font.PLAIN, 80));
panelTitle.add(titreLbl);
this.add(panelTitle);
/*
* Buttons Panel
*/
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
this.add(buttonsPanel);
/*
* Left Buttons Panel
*/
JPanel leftButtonsPanel = new JPanel();
leftButtonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
leftButtonsPanel.setPreferredSize(new Dimension(100, 200));
buttonsPanel.add(leftButtonsPanel);
JButton gameBtn = new JButton("Game");
gameBtn.setPreferredSize(buttonD);
gameBtn.addMouseListener(new ClickListener(ScreenID.GAME));
leftButtonsPanel.add(gameBtn);
leftButtonsPanel.add(new Box.Filler(fillerD, fillerD, fillerD));
JButton optionsBtn = new JButton("Options");
optionsBtn.setForeground(Color.GRAY);
optionsBtn.setPreferredSize(buttonD);
// optionsBtn.addMouseListener(new ClickListener(ScreenID.OPTIONS));
leftButtonsPanel.add(optionsBtn);
buttonsPanel.add(new Box.Filler(panelD, panelD, panelD));
/*
* Right Buttons Panel
*/
JPanel rightButtonsPanel = new JPanel();
rightButtonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
rightButtonsPanel.setPreferredSize(new Dimension(100, 200));
buttonsPanel.add(rightButtonsPanel);
JButton rankBtn = new JButton("Ranking");
rankBtn.setForeground(Color.GRAY);
rankBtn.setPreferredSize(buttonD);
// rankBtn.addMouseListener(new ClickListener(ScreenID.RANKING));
rightButtonsPanel.add(rankBtn);
rightButtonsPanel.add(new Box.Filler(fillerD, fillerD, fillerD));
JButton quitBtn = new JButton("Quit");
quitBtn.setPreferredSize(buttonD);
quitBtn.addMouseListener(new ClickListener(ScreenID.QUIT));
rightButtonsPanel.add(quitBtn);
/*
* Sub Information Panel
*/
JPanel subPanel = new JPanel();
subPanel.setLayout(new BorderLayout());
subPanel.setMaximumSize(new Dimension(1280, 300));
subPanel.add(new Box.Filler(buttonD, buttonD, buttonD), BorderLayout.SOUTH);
this.add(subPanel);
JPanel playerPanel = new JPanel();
playerPanel.setLayout(new BoxLayout(playerPanel, BoxLayout.Y_AXIS));
subPanel.add(playerPanel, BorderLayout.EAST);
}
}
|
package com.lti.hrmanagementsystem.dao;
import com.lti.hrmanagementsystem.bean.LoginBean;
public interface LoginDAO {
public boolean validateUser(LoginBean loginBean);
public String updateUser(String userId, int status);
public int getuserStatus(String userId);
public String getUserType(String userId);
public String insertRecordLogin(LoginBean loginBean);
public String deleteRecordLogin(String userId);
}
|
package io.snapcard.exchange.rx;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.bitfinex.v1.BitfinexExchange;
import org.knowm.xchange.bitstamp.BitstampExchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public enum BitExchange {
BITFINEX(BitfinexExchange.class.getName()),
BITSTAMP(BitstampExchange.class.getName());
private static final Logger LOGGER = LoggerFactory.getLogger(BitExchange.class);
private final String exchangeName;
private final Exchange exchange;
BitExchange(String exchangeName) {
this.exchangeName = exchangeName;
this.exchange = ExchangeFactory.INSTANCE.createExchange(this.exchangeName);
}
public Ticker getTicker() {
// 250-500ms
Ticker ticker = null;
try {
ticker = exchange.getPollingMarketDataService().getTicker(CurrencyPair.BTC_USD);
} catch (IOException e) {
LOGGER.error("[Exception retrieving ticker]", e);
}
return ticker;
}
public String getExchangeName() {
return this.exchangeName;
}
public Exchange getExchange() {
return this.exchange;
}
}
|
package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import java.util.ArrayList;
import java.util.Random;
public class LevelScreen extends BaseScreen
{
private BaseActor bird;
private BaseActor eagle;
private ActorBeta background;
private ActorBeta endMessage;
boolean condicion=true;
private boolean win;
private int xposition;
private int yposition;
private float[] vector = new float[2];
int count = 1;
int velocidad = 9;
float conversion;
float norma;
float anchoPantalla;
float largoPantalla;
float impulso;
float resistenciaAire = .001f;
float birdX;
float birdY;
ArrayList<RockActor> lista;
boolean control=false;
Random randomGenerator;
float xp;
float yp;
public LevelScreen(SpaceshipGame spaceshipGame) {
super(spaceshipGame);
;
}
@Override
public void initialize() {
randomGenerator = new Random();
anchoPantalla = Gdx.graphics.getHeight();
largoPantalla = Gdx.graphics.getWidth();
xp=randomGenerator.nextFloat() * largoPantalla;
yp=randomGenerator.nextFloat() * anchoPantalla;
background = new ActorBeta();
background.setTexture(new Texture(Gdx.files.internal("bg.png")));
background.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
background.RectangleSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
mainStage.addActor(background);
eagle = new BaseActor(200, 300, mainStage);
String[] filenames1 =
{"eagle0.png","eagle1.png","eagle2.png","eagle3.png","eagle4.png"};
eagle.loadAnimation(filenames1,0.1f, true);
endMessage = new ActorBeta();
endMessage.setTexture(new Texture(Gdx.files.internal("gameover.png")));
endMessage.setPosition(180, 180);
endMessage.setVisible(false);
mainStage.addActor(endMessage);
bird = new BaseActor(40, 100, mainStage);
String[] filenames =
{"bird.png", "bird2.png", "bird3.png"};
bird.loadAnimation(filenames, 0.1f, true);
bird.getName();
lista =new ArrayList<RockActor>();
for(int i =0; i<4;i++){
new RockActor(randomGenerator.nextFloat() * largoPantalla, randomGenerator.nextFloat() * anchoPantalla, mainStage, lista);
}
win = false;
}
public void update ( float dt)
{
for (RockActor rockActor : lista){
if(!(bird.overlaps(rockActor))){
condicion=true;
}
}
for (RockActor rockActor : lista){
if(bird.overlaps(rockActor )&& condicion){
vector[0]=-1.1f*vector[0];
vector[1]=-1.1f*vector[1];
condicion=false;
}
}
// check win condition: turtle must be overlapping starfish
// check user input and creates new vector
xposition = Gdx.input.getX();
yposition = Gdx.input.getY();
//convierte de la posicion obtenida de la pantalla a la posicion de la libreria del juego
conversion = anchoPantalla - yposition;
if (Gdx.input.justTouched()) {
norma = (float) Math.sqrt((xposition - birdX) * (xposition - birdX) + (conversion - birdY) * (conversion - birdY));
vector[0] = ((xposition - birdX) / norma);
vector[1] = ((conversion - birdY) / norma);
impulso = (velocidad * norma / anchoPantalla);
}
impulso = impulso - resistenciaAire;
birdX += vector[0] * impulso;
birdY += vector[1] * impulso;
Gdx.app.log("ancho", String.valueOf(Gdx.graphics.getWidth()));
Gdx.app.log("yposition", String.valueOf(yposition));
Gdx.app.log("xposition", String.valueOf(xposition));
Gdx.app.log("turtleX", String.valueOf(birdX));
Gdx.app.log("turtleY", String.valueOf(birdY));
Gdx.app.log("impulso", String.valueOf(impulso));
if (bird.overlaps(eagle)) {
count++;
eagle.setPosition(randomGenerator.nextFloat() * largoPantalla-eagle.getWidth()/2, randomGenerator.nextFloat() * anchoPantalla-eagle.getHeight()/2);
impulso=impulso*1.2f;
}
if (anchoPantalla <= (birdY + bird.getHeight())) {
vector[1] = -vector[1];
impulso = (1 + (impulso / 1000)) * impulso;
}
if (0 >= birdY) {
vector[1] = -vector[1];
impulso = (1 + (impulso / 1000)) * impulso;
}
if (0 >= birdX) {
vector[0] = -vector[0];
impulso = (1 + (impulso / 1000)) * impulso;
}
if ((birdX + bird.getWidth()) >= largoPantalla) {
vector[0] = -vector[0];
impulso = (1 + (impulso / 1000)) * impulso;
}
if (birdX>=2000) {
endMessage.setVisible(true);
control=true;
}
bird.setPosition(birdX, birdY);
if (control==true && Gdx.input.justTouched( )) {
control=false;
endMessage.setVisible(false);
impulso=0;
birdX=40;
birdY=40;
vector[0]=0;
vector[1]=0;
for (RockActor rockActor : lista){
rockActor.setPosition(randomGenerator.nextFloat() * largoPantalla-eagle.getWidth()/2, randomGenerator.nextFloat() * anchoPantalla-eagle.getHeight()/2);
}
bird.setPosition(birdX, birdY);
}
}
}
|
package com.gsonkeno.utils;
import org.junit.Test;
import java.util.Map;
/**
* Created by gaosong on 2017-11-22
*/
public class ObjectUtilsTest {
@Test
public void testToString(){
float f = 1.822f;
System.out.println(ObjectUtils.toString(f));
Map map = null;
System.out.println(ObjectUtils.toString(map));
}
@Test
public void testToInt(){
float f = 2.10f;
System.out.println(ObjectUtils.toInt(f));
System.out.println(ObjectUtils.toInt("dad"));
}
@Test
public void testRegex(){
System.out.println("1314".matches("\\d+"));
System.out.println("13.14".matches("\\d+[.]\\d++"));
}
}
|
package Assignment_1_Most_Frequent_Word;
import edu.duke.FileResource;
import java.util.ArrayList;
public class WordFrequencies {
private ArrayList<String> myWords;
private ArrayList<Integer> myFreqs;
public WordFrequencies() {
this.myWords = new ArrayList<String>();
this.myFreqs = new ArrayList<Integer>();
}
public int findIndexOfMax(){
int maxValue = 0;
int maxIndex = 0;
for(int i=0;i<myFreqs.size();i++){
if(maxValue < myFreqs.get(i)){
maxValue = myFreqs.get(i);
maxIndex = i;
}
}
return maxIndex;
}
public void findUnique(){
myWords.clear();
myFreqs.clear();
FileResource fileResource = new FileResource();
for(String word : fileResource.words()){
if(word.length() > 0){
String lowerCaseWord = word.toLowerCase();
int indexOfWord = myWords.indexOf(lowerCaseWord);
if(indexOfWord == -1){
myWords.add(lowerCaseWord);
myFreqs.add(1);
}else{
myFreqs.set(indexOfWord, myFreqs.get(indexOfWord)+1);
}
}
}
}
public void tester(){
findUnique();
System.out.println("Number of unique words: "+myWords.size());
for (int i=0;i<myFreqs.size();i++){
System.out.println(myFreqs.get(i) + " " + myWords.get(i));
}
System.out.println("The word that occurs most often and its count are: "+myWords.get(findIndexOfMax())+" "+myFreqs.get(findIndexOfMax()));
}
}
|
package io.wizzie.metrics;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.integration.utils.IntegrationTestUtils;
import org.junit.ClassRule;
import org.junit.Test;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.utility.MountableFile;
import java.io.File;
import java.util.List;
import java.util.Properties;
import static org.junit.Assert.assertTrue;
public class KafkaMetricsTest {
private static final String METRICS_TOPIC = "metrics";
static String jarFile;
static {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
File fileAux = new File(classLoader.getResource("log4j2.xml").getFile());
for (File file : fileAux.getParentFile().listFiles()) {
if (file.getName().endsWith("-selfcontained.jar")) {
jarFile = file.getAbsolutePath();
}
}
}
@ClassRule
public static KafkaContainer kafka = new KafkaContainer("5.1.0")
.withEmbeddedZookeeper()
.withEnv("KAFKA_KAFKA_METRICS_REPORTERS", KafkaBrokerReporter.class.getName())
.withEnv("KAFKA_KAFKA_METRICS_POLLING_INTERVAL_SECS", "1")
.withEnv("KAFKA_METRICS_REPORTER_KAFKA_BROKER_REPORTER_TOPIC", METRICS_TOPIC)
.withEnv("KAFKA_METRICS_REPORTER_KAFKA_BROKER_REPORTER_BOOTSTRAP_SERVERS", "127.0.0.1:9092")
.withCopyFileToContainer(
MountableFile.forHostPath(jarFile),
"/usr/share/java/kafka/kafka-metric-reporter-selfcontained.jar"
);
@Test
public void checkThatReceiveSomeMetric() throws InterruptedException {
Properties consumerConfig = new Properties();
consumerConfig.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers());
consumerConfig.put(ConsumerConfig.GROUP_ID_CONFIG, "group-metrics-test");
consumerConfig.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
consumerConfig.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
consumerConfig.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
List<KeyValue<String, String>> results = IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(consumerConfig, METRICS_TOPIC, 10);
assertTrue(results.size() > 0);
for(KeyValue<String, String> result : results) {
assertTrue(result.value.contains("host"));
assertTrue(result.value.contains("component"));
assertTrue(result.value.contains("timestamp"));
assertTrue(result.value.contains("value"));
assertTrue(result.value.contains("monitor"));
assertTrue(result.value.contains("app_id"));
}
}
}
|
package com.github.emailtohl.integration.web.service.cms;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.transaction.Transactional;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.github.emailtohl.integration.core.StandardService;
import com.github.emailtohl.integration.core.config.CorePresetData;
import com.github.emailtohl.integration.core.user.UserService;
import com.github.emailtohl.integration.core.user.customer.CustomerService;
import com.github.emailtohl.integration.core.user.employee.EmployeeService;
import com.github.emailtohl.integration.core.user.entities.EmployeeRef;
import com.github.emailtohl.integration.core.user.entities.UserRef;
import com.github.emailtohl.integration.web.config.WebPresetData;
import com.github.emailtohl.integration.web.service.cms.entities.Article;
import com.github.emailtohl.integration.web.service.cms.entities.Comment;
import com.github.emailtohl.integration.web.service.cms.entities.Type;
import com.github.emailtohl.lib.exception.NotAcceptableException;
import com.github.emailtohl.lib.jpa.EntityBase;
import com.github.emailtohl.lib.jpa.Paging;
/**
* 文章服务实现
* @author HeLei
*/
@Service
@Transactional
public class ArticleServiceImpl extends StandardService<Article> implements ArticleService {
private static final Pattern IMG_PATTERN = Pattern.compile("<img\\b[^<>]*?\\bsrc[\\s\\t\\r\\n]*=[\\s\\t\\r\\n]*[\"\"']?[\\s\\t\\r\\n]*(?<imgUrl>[^\\s\\t\\r\\n\"\"'<>]*)[^<>]*?/?[\\s\\t\\r\\n]*>");
/**
* 缓存名
*/
public static final String CACHE_NAME = "article_cache";
public static final String CACHE_ALL = "article_cache_all";
ArticleRepository articleRepository;
CommentRepository commentRepository;
TypeRepository typeRepository;
UserService userService;
CustomerService customerService;
EmployeeService employeeService;
CorePresetData presetData;
WebPresetData webPresetData;
@Inject
public ArticleServiceImpl(ArticleRepository articleRepository, CommentRepository commentRepository,
TypeRepository typeRepository, UserService userService, CustomerService customerService,
EmployeeService employeeService, CorePresetData presetData, WebPresetData webPresetData) {
super();
this.articleRepository = articleRepository;
this.commentRepository = commentRepository;
this.typeRepository = typeRepository;
this.userService = userService;
this.customerService = customerService;
this.employeeService = employeeService;
this.presetData = presetData;
this.webPresetData = webPresetData;
}
@CacheEvict(value = CACHE_ALL)
@CachePut(value = CACHE_NAME, key = "#result.id")
@Override
public Article create(Article entity) {
// 实际上这里就可以校验body与title是必填项
validate(entity);
String body = entity.getBody();
// 若没有设置封面,则将第一幅图作为封面
if (!hasText(entity.getCover()) && hasText(body)) {
Matcher m = IMG_PATTERN.matcher(entity.getBody());
if (m.find()) {
entity.setCover(m.group(1));
}
}
// 若没有摘要,则选取前50字
String summary = entity.getSummary();
if (!hasText(summary) && hasText(body)) {
int size = body.length();
if (size > 50) {
summary = body.substring(0, 50) + "……";
} else {
summary = body;
}
entity.setSummary(summary.replaceAll(IMG_PATTERN.pattern(), ""));
}
Long userId = CURRENT_USER_ID.get();
UserRef userRef;
if (userId == null) {
userRef = presetData.user_anonymous.getCustomerRef();
} else {
userRef = userService.getRef(userId);
}
if (userRef == null) {
userRef = presetData.user_anonymous.getCustomerRef();
}
entity.setAuthor(userRef);
Type type = null;
if (entity.getType() != null) {
if (entity.getType().getId() != null) {
type = typeRepository.findById(entity.getType().getId()).orElse(null);
} else if (hasText(entity.getType().getName())) {
type = typeRepository.getByName(entity.getType().getName());
}
}
if (type == null) {
type = typeRepository.findById(webPresetData.unclassified.getId()).orElse(null);
}
if (type != null) {
entity.setType(type);
type.getArticles().add(entity);
}
return transientDetail(articleRepository.save(entity));
}
@Override
public boolean exist(Object matcherValue) {
return true;
}
@Cacheable(value = CACHE_NAME, key = "#root.args[0]", condition = "#result != null")
@Override
public Article get(Long id) {
Article a = articleRepository.find(id);
return transientDetail(a);
}
@Override
public Paging<Article> search(String query, Pageable pageable) {
Page<Article> page;
if (hasText(query)) {
page = articleRepository.search(query, pageable);
} else {
page = articleRepository.findAll(pageable);
}
List<Article> ls = page.getContent().stream().map(this::toTransient).collect(Collectors.toList());
return new Paging<>(ls, pageable, page.getTotalElements());
}
@Override
public Paging<Article> query(Article params, Pageable pageable) {
Page<Article> page = articleRepository.queryForPage(params, pageable);
List<Article> ls = page.getContent().stream().map(this::toTransient).collect(Collectors.toList());
return new Paging<>(ls, pageable, page.getTotalElements());
}
@Override
public List<Article> query(Article params) {
return articleRepository.queryForList(params).stream().map(this::toTransient).collect(Collectors.toList());
}
@Override
public Map<Long, Long> getCommentNumbers(Collection<Long> articleIds) {
return articleRepository.getCommentNumbers(articleIds);
}
@CachePut(value = CACHE_NAME, key = "#root.args[0]", condition = "#result != null")
@Override
public Article update(Long id, Article newEntity) {
Article a = articleRepository.find(id);
if (a == null) {
return null;
}
if (hasText(newEntity.getTitle())) {
a.setTitle(newEntity.getTitle());
}
if (hasText(newEntity.getSummary())) {
a.setSummary(newEntity.getSummary());
}
String body = newEntity.getBody();
if (hasText(body)) {
a.setBody(body);
}
if (hasText(newEntity.getKeywords())) {
a.setKeywords(newEntity.getKeywords());
}
if (hasText(newEntity.getCover())) {
a.setCover(newEntity.getCover());
}
// 若没有设置封面,则将第一幅图作为封面
body = a.getBody();
if (!hasText(a.getCover()) && hasText(body)) {
Matcher m = IMG_PATTERN.matcher(body);
if (m.find()) {
a.setCover(m.group(1));
}
}
// 若没有摘要,则选取前50字
String summary = a.getSummary();
if (!hasText(summary) && hasText(body)) {
int size = body.length();
if (size > 50) {
summary = body.substring(0, 50) + "……";
} else {
summary = body;
}
a.setSummary(summary.replaceAll(IMG_PATTERN.pattern(), ""));
}
Type type = null;
if (newEntity.getType() != null) {
if (newEntity.getType().getId() != null) {
type = typeRepository.findById(newEntity.getType().getId()).orElse(null);
} else if (hasText(newEntity.getType().getName())) {
type = typeRepository.getByName(newEntity.getType().getName());
}
}
if (type != null) {
a.setType(type);
type.getArticles().add(newEntity);
}
return transientDetail(a);
}
@CacheEvict(value = { CACHE_NAME, CACHE_ALL }, allEntries = true)
@Override
public void delete(Long id) {
Article a = articleRepository.find(id);
if (a == null) {
return;
}
a.getType().getArticles().remove(a); // 文章一定有个类型,所以连续调用
a.getComments().forEach(c -> c.setArticle(null));
articleRepository.delete(a);
}
@CacheEvict(value = CACHE_ALL)
@CachePut(value = CACHE_NAME, key = "#root.args[0]", condition = "#result != null")
@Override
public Article approve(long id, boolean canApproved) {
Article a = articleRepository.find(id);
if (a == null) {
return null;
}
a.setCanApproved(canApproved);
Long userId = CURRENT_USER_ID.get();
EmployeeRef empRef;
if (userId == null) {
empRef = presetData.user_bot.getEmployeeRef();
} else {
empRef = employeeService.getRef(userId);
}
if (empRef == null) {
empRef = presetData.user_bot.getEmployeeRef();
}
a.setApprover(empRef);
return transientDetail(a);
}
@CachePut(value = CACHE_NAME, key = "#root.args[0]", condition = "#result != null")
@Override
public Article canComment(Long id, boolean canComment) {
Article a = articleRepository.find(id);
if (a == null) {
return null;
}
a.setCanComment(canComment);
return transientDetail(a);
}
@Cacheable(value = CACHE_ALL)
@Override
public Map<Type, List<Article>> articleClassify() {
// 本系统中article.getType()是一定存在的
return articleRepository.findAll().stream()
.limit(100).filter(a -> a.getCanApproved() == null || a.getCanApproved())
.map(this::toTransient).peek(this::filterCommentOfArticle)
.collect(Collectors.groupingBy(article -> article.getType()));
}
private Pageable zeroToHundred = PageRequest.of(0, 100, Sort.Direction.DESC, EntityBase.MODIFY_TIME_PROPERTY_NAME);
@Override
public List<Article> recentArticles() {
return articleRepository.findAll(zeroToHundred).getContent()
.stream()/* .limit(100) */
.filter(a -> a.getCanApproved() == null || a.getCanApproved()).map(this::toTransient)
.peek(this::filterCommentOfArticle).collect(Collectors.toList());
}
@Cacheable(value = CACHE_NAME, key = "#root.args[0]", condition = "#result != null")
@Override
public Article readArticle(Long id) throws NotAcceptableException {
Article a = articleRepository.find(id);
if (a == null) {
return null;
}
if (a.getCanApproved() != null && !a.getCanApproved()) {
throw new NotAcceptableException("该文章还未审核通过!");
}
filterCommentOfArticle(a);
return transientDetail(a);
}
@Override
protected Article toTransient(Article source) {
if (source == null) {
return null;
}
Article target = new Article();
BeanUtils.copyProperties(source, target, "author", "approver", "type", "comments", "commentNumbers");
// BeanUtils不处理is开头的访问器
target.setCanApproved(source.getCanApproved());
// 只获取作者必要信息
target.setAuthor(transientUserRef(source.getAuthor()));
target.setApprover(transientEmployeeRef(source.getApprover()));
if (source.getType() != null) {
Type st = source.getType();
Type t = new Type();
t.setId(st.getId());
t.setCreateTime(st.getCreateTime());
t.setModifyTime(st.getModifyTime());
t.setName(st.getName());
t.setDescription(st.getDescription());
target.setType(t);
}
return target;
}
/**
* 对于文章来说,只需要展示用户名字,头像等基本信息即可
* 注意:本方法将所有评论载入,而不管该评论是否允许开放
*/
@Override
protected Article transientDetail(Article source) {
if (source == null) {
return null;
}
Article target = new Article();
BeanUtils.copyProperties(source, target, "author", "approver", "type", "comments", "commentNumbers");
target.setAuthor(transientUserRef(source.getAuthor()));
target.setApprover(transientEmployeeRef(source.getApprover()));
target.setType(getType(source.getType()));
target.setComments(transientComments(source.getComments()));
return target;
}
protected UserRef transientUserRef(UserRef source) {
if (source == null) {
return null;
}
UserRef target = new UserRef();
target.setId(source.getId());
target.setEmail(source.getEmail());
target.setCellPhone(source.getCellPhone());
target.setName(source.getName());
target.setNickname(source.getNickname());
target.setIconSrc(source.getIconSrc());
return target;
}
protected EmployeeRef transientEmployeeRef(EmployeeRef source) {
if (source == null) {
return null;
}
EmployeeRef target = new EmployeeRef();
target.setEmpNum(source.getEmpNum());
target.setId(source.getId());
target.setEmail(source.getEmail());
target.setCellPhone(source.getCellPhone());
target.setName(source.getName());
target.setNickname(source.getNickname());
target.setIconSrc(source.getIconSrc());
return target;
}
/**
* 过滤文章类型
*
* @param source
* @return
*/
protected Type getType(Type source) {
if (source == null)
return null;
Type target = new Type();
target.setId(source.getId());
target.setCreateTime(source.getCreateTime());
target.setModifyTime(source.getModifyTime());
target.setName(source.getName());
target.setDescription(source.getDescription());
target.setParent(getType(source.getParent()));
// 只要文章长度,不加载具体的文章
int size = source.getArticles().size();
for (int i = 0; i < size; i++) {
target.getArticles().add(new Article());
}
return target;
}
protected List<Comment> transientComments(List<Comment> comments) {
if (comments == null) {
return null;
}
return comments.stream().filter(c -> c.getApproved() == null || c.getApproved()).map(source -> {
Comment target = new Comment();
target.setId(source.getId());
target.setCreateTime(source.getCreateTime());
target.setModifyTime(source.getModifyTime());
target.setContent(source.getContent());
target.setReviewer(transientUserRef(source.getReviewer()));
target.setApprover(transientEmployeeRef(source.getApprover()));
target.setApproved(source.getApproved());
return target;
}).collect(Collectors.toList());
}
/**
* 过滤文章下的评论,主要用于前端
*
* @param article
*/
private void filterCommentOfArticle(Article article) {
if (article.getCanApproved() != null && !article.getCanApproved()) {
article.getComments().clear();
} else {
article.getComments().removeIf(comment -> !comment.getApproved());
}
}
}
|
// BaseBoundedBuffer.java
package mygroup;
import net.jcip.annotations.*;
import java.util.concurrent.locks.*;
public class BaseBoundedBuffer<V> {
@GuardedBy("this") private final V[] buf;
@GuardedBy("this") private int head;
@GuardedBy("this") private int tail;
@GuardedBy("this") private int count;
@SuppressWarnings("unchecked")
protected BaseBoundedBuffer(int capacity) {
this.buf = (V[]) new Object[capacity];
}
protected final synchronized boolean doPut(V v) {
if (isFull()) {
return false;
}
buf[tail] = v;
if (++ tail == buf.length) {
tail = 0;
}
++ count;
return true;
}
protected final synchronized V doTake() {
if (isEmpty()) {
return null;
}
V v = buf[head];
buf[head] = null;
if (++ head == buf.length) {
head = 0;
}
-- count;
return v;
}
protected boolean isFull() { return count == buf.length; }
protected boolean isEmpty() { return count == 0; }
public static void testBaseBoundedBuffer() {
BaseBoundedBuffer<Integer> bbbi = new BaseBoundedBuffer<>(2);
final String msg = "sleep 1s and try again";
new Thread(() -> {
for (int i = 0; i < 3; ++i) {
while (true) {
if (bbbi.doPut(i)) {
System.out.println("doPut() OK : " + i);
break;
} else {
System.out.println("doPut() failed : " + i + msg);
Helper.sleepForSeconds(1);
}
}
}
System.out.println("Thread 1 done");
}
).start();
Helper.sleepForSeconds(3);
new Thread(() -> {
for (int i = 0; i < 5; ++i) {
while (true) {
Integer I = bbbi.doTake();
if (I != null) {
System.out.println("doTake() OK : " + I.intValue());
break;
} else {
System.out.println("doTake() failed : " + i + msg);
Helper.sleepForSeconds(1);
}
}
}
System.out.println("Thread 2 done");
}
).start();
Helper.sleepForSeconds(3);
bbbi.doPut(9);
bbbi.doPut(10);
}
@ThreadSafe
static class GrumpyBoundedBuffer<V> extends BaseBoundedBuffer<V> {
public GrumpyBoundedBuffer(int capacity) { super(capacity); }
public synchronized void put(V v) throws RuntimeException {
if (isFull()) {
throw new RuntimeException("Buffer is full!");
}
doPut(v);
}
public synchronized V take() throws RuntimeException {
if (isEmpty()) {
throw new RuntimeException("Buffer is empty");
}
return doTake();
}
}
public static void testGrumpyBoundedBuffer() throws Exception {
GrumpyBoundedBuffer<Integer> gbbi = new GrumpyBoundedBuffer<>(2);
new Thread(() -> {
for (int i = 0; i < 3; ++i) {
while (true) {
try {
gbbi.put(i);
System.out.println("put() OK : " + i);
break;
} catch (Exception e) {
System.out.println("put() failed : " + i + ", sleep 1s and try again");
Helper.sleepForSeconds(1);
}
}
}
System.out.println("Thread 1 done");
}
).start();
Helper.sleepForSeconds(3);
new Thread(() -> {
for (int i = 0; i < 5; ++i) {
while (true) {
try {
Integer I = gbbi.take();
System.out.println("take() OK : " + I.intValue());
break;
} catch (Exception e) {
System.out.println("take() failed : " + i + ", sleep 1s and try again");
Helper.sleepForSeconds(1);
}
}
}
System.out.println("Thread 2 done");
}
).start();
Helper.sleepForSeconds(3);
gbbi.put(9);
gbbi.put(10);
}
@ThreadSafe
static class SleepyBoundedBuffer<V> extends BaseBoundedBuffer<V> {
private static final int SLEEPGRANULARITY = 20;
public SleepyBoundedBuffer(int capacity) { super(capacity); }
public void put(V v) throws InterruptedException {
while (true) {
synchronized(this) {
if (!isFull()) {
doPut(v);
return;
}
}
Thread.sleep(SLEEPGRANULARITY);
}
}
public V take() throws InterruptedException {
while (true) {
synchronized(this) {
if (!isEmpty()) {
return doTake();
}
}
Thread.sleep(SLEEPGRANULARITY);
}
}
}
public static void testSleepyBoundedBuffer() throws InterruptedException {
SleepyBoundedBuffer<Integer> sbbi = new SleepyBoundedBuffer<>(2);
new Thread(() -> {
for (int i = 0; i < 3; ++i) {
try {
sbbi.put(i);
} catch (InterruptedException ignored) {}
System.out.println("put() OK : " + i);
}
System.out.println("Thread 1 done");
}
).start();
Helper.sleepForSeconds(3);
new Thread(() -> {
for (int i = 0; i < 5; ++i) {
try {
Integer I = sbbi.take();
System.out.println("take() OK : " + I.intValue());
} catch (InterruptedException ignored) {}
}
System.out.println("Thread 2 done");
}
).start();
Helper.sleepForSeconds(1);
sbbi.put(9);
sbbi.put(10);
}
@ThreadSafe
static class BetterBuffer<V> extends BaseBoundedBuffer<V> {
public BetterBuffer(int capacity) { super(capacity); }
public void put(V v) throws InterruptedException {
while (isFull()) {
System.out.println("isFull, call wait");
wait();
System.out.println("return from wait");
}
boolean wasEmpty = isEmpty();
doPut(v);
if (wasEmpty) {
notifyAll();
}
}
public V take() throws InterruptedException {
while (isEmpty()) {
wait();
}
boolean wasFull = isFull();
V v = doTake();
if (wasFull) {
notifyAll();
}
return v;
}
}
public static void main(String[] args) throws InterruptedException {
ConditionalBoundedBuffer<Integer> cbbi = new ConditionalBoundedBuffer<>();
new Thread(() -> {
for (int i = 0; i < 3; ++i) {
try {
cbbi.put(i);
} catch (InterruptedException ignored) {}
System.out.println("put() OK : " + i);
}
System.out.println("Thread 1 done");
}
).start();
Helper.sleepForSeconds(3);
new Thread(() -> {
for (int i = 0; i < 5; ++i) {
try {
Integer I = cbbi.take();
System.out.println("take() OK : " + I.intValue());
} catch (InterruptedException ingored) {}
}
System.out.println("Thread 2 done");
}
).start();
Helper.sleepForSeconds(3);
cbbi.put(9);
cbbi.put(10);
}
}
@ThreadSafe
class ConditionalBoundedBuffer<T> {
protected final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
private static final int BUFFERSIZE = 2;
@GuardedBy("lock")
@SuppressWarnings("unchecked")
private final T[] items = (T[]) new Object[BUFFERSIZE];
@GuardedBy("lock") private int tail;
@GuardedBy("this") private int head;
@GuardedBy("this") private int count;
public void put(T x) throws InterruptedException {
lock.lock();
try {
while ( count == items.length ) { // 满,不能再放
notFull.await();
}
items[tail] = x;
if (++ tail == items.length) {
tail = 0;
}
++ count;
notEmpty.signal();
} finally {
lock.unlock();
}
}
public T take() throws InterruptedException {
lock.lock();
try {
while ( count == 0 ) {
notEmpty.await();
}
T x = items[tail];
if (++ head == items.length) {
head = 0;
}
-- count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}
|
package exercicio_002;
import java.util.Scanner;
public class Exercicio_002 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double raio, pi, perimetro, area;
pi = Math.PI;
System.out.print("Digite o raio do círculo: ");
raio = keyboard.nextDouble();
area = pi * raio * raio;
perimetro = pi * raio * 2;
System.out.println("A área do círculo é: " + area);
System.out.println("O perimetro do círculo é: " + perimetro);
}
}
|
package com.espendwise.manta.auth.ctx;
public @interface AppCtxComponent {
String name() default "";
String dependency() default "";
}
|
package com.lubarov.daniel.web.http.websocket;
import com.lubarov.daniel.data.option.Option;
import com.lubarov.daniel.data.sequence.Sequence;
import com.lubarov.daniel.data.serialization.ByteSink;
import com.lubarov.daniel.data.util.ToStringBuilder;
/**
* A complete data which may have been constructed from multiple fragments.
*/
public final class WebSocketMessage {
public static final class Builder {
private Option<WebSocketMessageType> type;
private Option<byte[]> data;
public Builder setType(WebSocketMessageType type) {
this.type = Option.some(type);
return this;
}
public Builder setData(byte[] data) {
this.data = Option.some(data);
return this;
}
public WebSocketMessage build() {
return new WebSocketMessage(this);
}
}
/**
* The type of the initial fragment. Shuold never be CONTINUATION.
*/
private final WebSocketMessageType type;
private final byte[] data;
private WebSocketMessage(Builder builder) {
type = builder.type.getOrThrow();
data = builder.data.getOrThrow();
}
public static WebSocketMessage fromFragments(Sequence<WebSocketFrame> fragments) {
ByteSink sink = new ByteSink();
for (WebSocketFrame fragment : fragments)
sink.giveAll(fragment.getUnmaskedPayload());
return new Builder()
.setType(WebSocketMessageType.fromOpcode(fragments.getFront().getOpcode()))
.setData(sink.getBytes())
.build();
}
public WebSocketMessageType getType() {
return type;
}
public byte[] getData() {
return data;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("type", type)
.append("dataLength", data.length)
.toString();
}
}
|
package pl.edu.agh.internetshop;
import java.math.BigDecimal;
public class Product {
public static final int PRICE_PRECISION = 2;
public static final int ROUND_STRATEGY = BigDecimal.ROUND_HALF_UP;
private BigDecimal discount;
private final String name;
private final BigDecimal price;
public Product(String name, BigDecimal price) {
this(name, price, BigDecimal.valueOf(1));
}
public Product(String name, BigDecimal price, BigDecimal discount) {
this.name = name;
this.price = price;
this.price.setScale(PRICE_PRECISION, ROUND_STRATEGY);
this.discount = discount;
}
public void setProductDiscount(BigDecimal discount) {
this.discount = discount;
}
public BigDecimal getProductDiscount() {
return this.discount;
}
public String getName() {
return name;
}
public BigDecimal getPrice() {
return price.multiply(discount);
}
}
|
package smart;
import smart.authentication.UserToken;
import smart.util.Helper;
import smart.lib.Json;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class TokenTests {
@Test
public void test() {
var salt = Helper.randomString(4);
UserToken userToken = new UserToken();
userToken.setSalt(salt);
var token = Json.decode(userToken.toString(), UserToken.class);
assert token != null;
Assertions.assertEquals(token.getSalt(), salt);
}
}
|
package com.saaolheart.mumbai;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.saaolheart.mumbai.common.utility.PdfGenerator;
import com.saaolheart.mumbai.configuration.repositoryconfig.CustomRepositoryImpl;
import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
@SpringBootApplication
@ComponentScan(basePackages= {"com.saaolheart.mumbai"})
@EnableJpaRepositories(repositoryBaseClass = CustomRepositoryImpl.class)
@EnableAutoConfiguration
public class SaaolHeartMumbaiApplication {
public static void main(String[] args) throws IOException, XDocReportException, Docx4JException {
SpringApplication.run(SaaolHeartMumbaiApplication.class, args);
/*
* DocxStamper<DocxContext> stamper = new DocxStamper<DocxContext>(new
* DocxStamperConfiguration()); DocxContext context = new DocxContext();
* context.setCompanyName("Johnwewewe"); List<String> str = new
* ArrayList<String>(); str.add("wqeqwe"); str.add("wqeqwqwee");
* str.add("wqeqwqweqe"); str.add("wqeqwweqwee"); str.add("wqeqwe");
* context.setStringList(str); InputStream template = new FileInputStream(new
* File(
* "/home/mohit/ProtechnicWorkspace/SaaolHearts/Project/Root/saaolheartmumbai/ThankYouNote_Template.docx"
* )); OutputStream out = new FileOutputStream("output_template.docx");
* stamper.stamp(template, context, out); out.close();
*
*
*/
// String templatePath = "/home/mohit/ProtechnicWorkspace/SaaolHearts/Project/Root/saaolheartmumbai/ThankYouNote_Template.docx";
//
// Map<String, Object> nonImageVariableMap = new HashMap<String, Object>();
// nonImageVariableMap.put("thank_you_date", "24-June-2013");
// nonImageVariableMap.put("name", "Rajani Jha");
// nonImageVariableMap.put("website", "www.sambhashanam.com");
// nonImageVariableMap.put("author_name", "Dhananjay Jha"); Map<String, String>
// imageVariablesWithPathMap =new HashMap<String, String>();
// imageVariablesWithPathMap.put("header_image_logo","/home/mohit/ProtechnicWorkspace/SaaolHearts/Project/Root/saaolheartmumbai/im.png");
//
// byte[] mergedOutput = PdfGenerator.mergeAndGeneratePDFOutput(templatePath, TemplateEngineKind.Velocity, nonImageVariableMap, imageVariablesWithPathMap);
// FileOutputStream os = new FileOutputStream("/home/mohit/ProtechnicWorkspace/SaaolHearts/Project/Root/saaolheartmumbai/"+System.nanoTime()+".pdf");
// os.write(mergedOutput);
// os.flush();
// os.close();
}
}
|
/*
* Copyright 2017 Sanjin Sehic
*
* 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 simple.actor;
import org.junit.runner.RunWith;
import alioli.Scenario;
import simple.actor.testing.SpyChannel;
import static com.google.common.truth.Truth.assertThat;
/** Tests for {@link Mailbox}. */
@RunWith(Scenario.Runner.class)
public class MailboxTest extends Scenario {
{
subject("connected mailbox", () -> {
final SpyChannel<Message> channel = new SpyChannel<>();
final Mailbox<Message> mailbox = new Mailbox<>(channel);
should("delegate sending of message to the connected channel", () -> {
final Message message = new Message();
mailbox.send(message);
assertThat(channel.getSentMessages()).containsExactly(message);
});
should("fail to send a message if the connected channel fails to send", () -> {
channel.stop();
assertThat(mailbox.send(new Message())).isFalse();
});
when("disconnected from the connected channel", () -> {
mailbox.disconnect();
should("not delegate sending of message to the channel anymore", () -> {
assertThat(mailbox.send(new Message())).isTrue();
assertThat(channel.getSentMessages()).isEmpty();
});
});
when("stopped", () -> {
mailbox.stop();
should("stop the connected channel", () -> {
assertThat(channel.isStopped()).isTrue();
});
});
});
subject("disconnected mailbox", () -> {
final Mailbox<Message> mailbox = new Mailbox<>();
should("succeed to send a message", () -> {
assertThat(mailbox.send(new Message())).isTrue();
});
when("a message is sent", () -> {
final Message message = new Message();
mailbox.send(message);
and("a channel is connected", () -> {
final SpyChannel<Message> channel = new SpyChannel<>();
mailbox.connect(channel);
should("resend all messages that were sent while being disconnected", () -> {
assertThat(channel.getSentMessages()).containsExactly(message);
});
});
});
when("stopped", () -> {
final Message message = new Message();
mailbox.send(message);
mailbox.stop();
should("fail to send a message", () -> {
assertThat(mailbox.send(new Message())).isFalse();
});
and("a channel is connected", () -> {
mailbox.send(new Message());
final SpyChannel<Message> channel = new SpyChannel<>();
mailbox.connect(channel);
should("stop the channel", () -> {
assertThat(channel.isStopped()).isTrue();
});
should("resend only messages that were sent before being stopped", () -> {
assertThat(channel.getSentMessages()).containsExactly(message);
});
});
});
});
}
private static final class Message {}
}
|
package com.example.mynovel;
import android.util.Log;
import com.mysql.jdbc.StringUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class collectionImple {
private static final String url = "jdbc:mysql://cdb-h1ubzfre.bj.tencentcdb.com:10129/mynovel?useUnicode=true&characterEncoding=UTF-8";
private static final String user = "root";//用户名
private static final String password = "15279909969aqw";
private Connection conn =null;
private PreparedStatement ps = null;
private ResultSet rs = null;
private static collectionImple coImple;
public collectionImple(){
}
public static collectionImple getInstance(){
if (coImple==null){
coImple = new collectionImple();
}
return coImple;
}
//查询所有收藏信息
public ArrayList<collection> getCollectionData(){
ArrayList<collection> collections = new ArrayList<collection>();
String sql = "select * from collection";
conn = DButil.getSqlConnection(url,user,password);
try{
if (conn!=null && !(conn.isClosed())){
ps = (PreparedStatement)conn.prepareStatement(sql);
if (ps!=null){
rs = ps.executeQuery();
if (rs!=null){
while (rs.next()){
collection co= new collection();
co.setUser(rs.getString(1));
co.setName(rs.getString(2));
co.setAuthor(rs.getString(3));
co.setType(rs.getString(4));
co.setUrl(rs.getString(5));
collections.add(co);
Log.d("error1", "getCollectionData: 取数据成功");
}
}
}
}
}catch (SQLException e){
e.printStackTrace();
}
DButil.closeAll(conn,ps,rs);
return collections;
}
//插入收藏小说数据库
public void insertCollection(collection co){
int result = -1;
String sql = "insert into collection(username,name,author,type,url)values(?,?,?,?,?)";
conn = DButil.getInstance().getSqlConnection(url,user,password);
try {
boolean closed = conn.isClosed();
if ((conn!=null)&& (!closed)){
ps = (PreparedStatement)conn.prepareStatement(sql);
String username = co.getUser();
String name = co.getName();
String author = co.getAuthor();
String type = co.getType();
String url = co.getUrl();
ps.setString(1,username);
ps.setString(2,name);
ps.setString(3,author);
ps.setString(4,type);
ps.setString(5,url);
result = ps.executeUpdate();
}
}catch (SQLException e){
e.printStackTrace();
}
DButil.closeAll(conn,ps);
}
//取消收藏数据库
public int deleteCollection(collection co){
int result = -1;
if (!StringUtils.isEmptyOrWhitespaceOnly(co.getName())){
conn = DButil.getSqlConnection(url,user,password);
String sql = "delete from collection where name = ?";
try{
boolean closed = conn.isClosed();
if((conn!=null)&& (!closed)){
ps = (PreparedStatement)conn.prepareStatement(sql);
ps.setString(1,co.getName());
result = ps.executeUpdate();
}
}catch (SQLException e){
e.printStackTrace();
}
}
DButil.closeAll(conn,ps);
return result;
}
}
|
package com.steatoda.commons.fields.service.async.crud;
import com.steatoda.commons.fields.FieldEnum;
import com.steatoda.commons.fields.FieldGraph;
import com.steatoda.commons.fields.HasEntityFields;
import com.steatoda.commons.fields.service.async.FieldsRequest;
import com.steatoda.commons.fields.service.async.FieldsServiceHandler;
/**
* <p>'Instance' part of 'Collection/Instance' CRUD async interface.</p>
*
* @see CollectionCRUDFieldsAsyncService
* @see CRUDFieldsAsyncService
*/
public interface InstanceCRUDFieldsAsyncService<I, C extends HasEntityFields<I, C, F>, F extends Enum<F> & FieldEnum> {
FieldsRequest get(FieldGraph<F> graph, FieldsServiceHandler<C> handler);
/**
* <p>Updates fields specified by {@code patch} and pulls {@code graph} when done.</p>
*
* <p>E.g. to update only field {@code bar} in entity {@code foo}, write something like:</p>
*
* <pre>
* modify(foo.clone(FieldGraph.of(Foo.Field.bar)), ...)
* </pre>
*
* @param patch patch containing fields to update (only modifiable fields will be updated)
* @param graph graph to pull into {@code entity} after modification
* @param handler asynchronous handler
*
* @return {@link FieldsRequest} describing this asynchronous operation
*/
FieldsRequest modify(C patch, FieldGraph<F> graph, FieldsServiceHandler<C> handler);
FieldsRequest delete(FieldsServiceHandler<Void> handler);
}
|
package cn.canlnac.onlinecourse.presentation.mapper;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import cn.canlnac.onlinecourse.domain.Course;
import cn.canlnac.onlinecourse.domain.SimpleUser;
import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity;
import cn.canlnac.onlinecourse.presentation.model.CourseModel;
@PerActivity
public class CourseModelDataMapper {
private final SimpleUserModelDataMapper simpleUserModelDataMapper;
@Inject
public CourseModelDataMapper(SimpleUserModelDataMapper simpleUserModelDataMapper) {
this.simpleUserModelDataMapper = simpleUserModelDataMapper;
}
public CourseModel transform(Course course) {
if (course == null) {
throw new IllegalArgumentException("Cannot transform a null value");
}
CourseModel courseModel = new CourseModel();
courseModel.setFavorite(course.isFavorite());
courseModel.setLike(course.isLike());
if (course.getAuthor() == null) {
course.setAuthor(new SimpleUser());
}
courseModel.setAuthor(simpleUserModelDataMapper.transform(course.getAuthor()));
courseModel.setId(course.getId());
courseModel.setFavoriteCount(course.getFavoriteCount());
courseModel.setCommentCount(course.getCommentCount());
courseModel.setDate(course.getDate());
courseModel.setDepartment(course.getDepartment());
courseModel.setIntroduction(course.getIntroduction());
courseModel.setName(course.getName());
courseModel.setLikeCount(course.getLikeCount());
courseModel.setWatchCount(course.getWatchCount());
courseModel.setPreviewUrl(course.getPreviewUrl());
return courseModel;
}
public List<CourseModel> transform(List<Course> courseList) {
List<CourseModel> courseModelList = new ArrayList<>(courseList.size());
CourseModel courseModel;
for (Course course : courseList) {
courseModel = transform(course);
if (course != null) {
courseModelList.add(courseModel);
}
}
return courseModelList;
}
}
|
package com.yksoul.pay.exception;
import com.yksoul.pay.domain.enums.PayErrorCodeEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author yk
* @version 1.0
* @date 2018-06-15
*/
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class EasyPayException extends RuntimeException {
@Getter
@Setter
private Integer errorCode;
public EasyPayException(Integer errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public EasyPayException(PayErrorCodeEnum payErrorCodeEnum) {
super(payErrorCodeEnum.getMessage());
this.errorCode = payErrorCodeEnum.getCode();
}
public EasyPayException() {
super();
}
public EasyPayException(String message) {
super(message);
}
public EasyPayException(String message, Throwable cause) {
super(message, cause);
}
public EasyPayException(Throwable cause) {
super(cause);
}
}
|
package unalcol.types.collection.vector;
import unalcol.clone.Clone;
/**
* <p>CloneService of Java Vectors.</p>
* <p>Copyright: Copyright (c) 2010</p>
*
* @author Jonatan Gomez Perdomo
* @version 1.0
*/
public class ImmutableVectorCloneService<T> extends Clone<ImmutableVector<T>> {
public ImmutableVectorCloneService() {
}
public static Object[] toArray(ImmutableVector<?> obj) {
int size = obj.size();
Object[] cl = new Object[size];
for (int i = 0; i < size; i++) {
cl[i] = Clone.create(obj.get(i));
}
return cl;
}
/**
* Clones a Java Vector
*
* @param obj The Java Vector to be cloned
* @return A clone of the Java Vector
*/
@SuppressWarnings("unchecked")
@Override
public ImmutableVector<T> clone(ImmutableVector<T> obj) {
return new ImmutableVector<T>((T[]) toArray(obj));
}
}
|
package cranshashtable2017;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/*******************************************************
* ‘*** Gui
‘*** Nick Crans
‘******************************************************
‘*** Creates the gui and parses the text from the document
‘***
‘***
‘******************************************************
‘*** 10/31/2017
‘******************************************************/
public class Gui extends JFrame implements ActionListener
{
private final GridBagLayout layout;
private final GridBagConstraints constraints;
private final JTextArea display;
private final JTextField enter;
private final JButton find;
private final JButton openFile;
private final JScrollPane scroll;
private Hashtable hMap;
/******************************************************
‘*** GUI
‘*** Nick Crans
‘******************************************************
‘*** Constructor
‘*** Initializes all the components for the window
‘******************************************************
‘*** 09/29/2017
‘******************************************************/
public Gui()
{
super("Hash Table");
layout = new GridBagLayout();
setLayout(layout);
constraints = new GridBagConstraints();
/***************************************************************
Help for this code was found on
http://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html
*/
display = new JTextArea("Display", 10, 20);
display.setEditable(false);
scroll = new JScrollPane(display);
/**********************************************************/
openFile = new JButton("Open File");
openFile.addActionListener(this);
enter = new JTextField ();
find = new JButton("Find Word");
find.addActionListener(this);
constraints.weightx = 1;
constraints.weighty = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponents(scroll);
constraints.gridwidth = 1;
addComponents(openFile);
addComponents(find);
addComponents(enter);
}
/******************************************************
‘*** addComponents
‘*** Nick Crans
‘******************************************************
‘*** Adds the components to the window. Takes the component
‘*** to be added as an parameter
‘******************************************************
‘*** 09/29/2017
‘******************************************************/
private void addComponents(Component com)
{
layout.setConstraints(com, constraints);
add(com);
}
/******************************************************
‘*** actionPerformed
‘*** Nick Crans
‘******************************************************
‘*** Adds functionality to the text area and button.
‘*** It also reads in the lines from a text file and parses
‘*** the lines into single words with no punctuation.
* Also tests if word is in table
‘******************************************************
‘*** 09/29/2017
‘******************************************************/
@Override
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == openFile)
{
JFileChooser choice = new JFileChooser();
int returnVal = choice.showOpenDialog(this);
hMap = new Hashtable();
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = choice.getSelectedFile();
ArrayList<String> lines = new ArrayList<String>();
String catchLines = "";
String temp = "";
String[] words;
try
{
FileReader read = new FileReader(file.getAbsolutePath());
BufferedReader buffedRead = new BufferedReader(read);
while((catchLines = buffedRead.readLine()) != null)
lines.add(catchLines);
for(int i = 0; i < lines.size(); i++)
{
temp += lines.get(i) + " ";
}
/***********************************************************
* Help for this code was found on
* https://docs.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html
* and https://www.tutorialspoint.com/java/java_string_split.htm
**********************************************************/
words = temp.split("-|\\s+");
for(int j = 0; j < words.length; j++)
{
String sent = words[j].replaceAll("[^a-zA-Z_0-9]", "").toLowerCase();
if(sent.isEmpty())
{
j++;
sent = words[j].replaceAll("[^a-zA-Z_0-9]", "").toLowerCase();
}
MapEntry entry = new MapEntry(sent, j);
if(hMap.contains(entry))
{
}
else
hMap.put(j, entry);
}
//**********************************************************
buffedRead.close();
//display.setText("Unique Word Count: " + "\n");
display.append("Unique Words:\n");
/*
Help for this code was found on https://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html#elements()
*/
Enumeration items = hMap.elements();
while(items.hasMoreElements())
{
display.append(items.nextElement().toString());
}
}
catch(IOException e)
{
}
}
}
if(event.getSource() == find)
{
String value = enter.getText();
Enumeration keys = hMap.keys();
int key;
if(value.compareTo("") == 0)
{
display.append("Please enter a word to find.\n");
}
else
{
String test;
while(keys.hasMoreElements())
{
key = (int) keys.nextElement();
test = hMap.get(key).toString();
test = test.replace("\n", "");
if(test.compareToIgnoreCase(value) == 0)
{
display.append(value + " is in the hash table.\n");
break;
}
else if(!keys.hasMoreElements())
display.append(value + " is not in the hash table.\n");
}
}
}
}
}
|
package com.mrhan.db.allrounddaos;
/**
* 实体类的字段信息
* 默认,外键
*/
public enum ColumentType {
/**
* 默认类型
*/
DEFAULT,
/**
* 字段为外键
*/
FORGINKEY,
/**
* 字段为主键
*/
PIRMARYKEY,
/**
* 字段为为一建
*/
UNIQUE
}
|
package edu.uci.ics.sdcl.firefly.report.descriptive;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import edu.uci.ics.sdcl.firefly.Worker;
import edu.uci.ics.sdcl.firefly.util.PropertyManager;
public class FileConsentDTO extends ConsentDTO{
//logPath: Should be path+fileName. Ex. "myFolder/myFile"
private String logPath;// = "C:/Users/igMoreira/Desktop/Dropbox/1.CrowdDebug-Summer2015/sampleDatalogs/consent-log-TestSample.log";
/**
* Will hold the data loaded from the database.
* Necessary not to keep connecting to the database.
*/
protected HashMap<String, Worker> workers = new HashMap<String, Worker>();
public FileConsentDTO(){
PropertyManager manager = PropertyManager.initializeSingleton();
this.logPath = manager.reportPath + manager.consentLogFileName;
System.out.println("consentDTO, logPath: "+logPath);
}
public FileConsentDTO(String path) {
this.logPath = path;
}
@Override
public HashMap<String, Worker> getWorkers() {
if((this.workers == null) || (this.workers.isEmpty()))
loadWorkers();
return this.workers;
}
@Override
protected void loadWorkers() {
BufferedReader log = null;
try {
log = new BufferedReader(new FileReader(logPath));
String line = null;
while((line = log.readLine()) != null)
{
if(line.equals(""))
continue;
String event = line.split("%")[1].replaceAll("\\s", "");
switch (event.toUpperCase()) {
case "CONSENT":loadConsent(line);break;
case "SKILLTEST": loadSkillTest(line);break;
case "SURVEY": loadSurvey(line); break;
case "FEEDBACK": loadFeedback(line); break;
case "QUIT": loadQuit(line); break;
case "ERROR": break;
default:
System.out.println("DATABASE ERROR: Invalid event on log. EVENT = "+event);
System.exit(0);
}
}
} catch (FileNotFoundException e) {
System.out.println("DATABASE ERROR: File could not be opened");
e.printStackTrace();
System.exit(0);
} catch (IOException e) {
System.out.println("DATABASE ERROR: Couldn't read file");
e.printStackTrace();
System.exit(0);
}
finally
{
try {
log.close();
} catch (IOException e) {
System.out.println("DATABASE ERROR: Could not close file");
e.printStackTrace();
System.exit(0);
}
}
}
/**
* Load the survey info and sets the
* content to the corresponding worker on
* the hashMap
* @param line: line containing the survey info
*/
private void loadSurvey(String line)
{
String result[] = line.split("%");
String workerId = result[3].trim();
Worker worker = this.workers.get(workerId);
if(worker != null)
{
for(int i=6; i< result.length-1; i+=2)
{
worker.addSurveyAnswer(result[i].trim(), result[i+1].trim());
}
}
}
/**
* Load the skill test info and sets the
* content to the corresponding worker on
* the hashMap
* @param line: line containing the skill test info
*/
private void loadSkillTest(String line)
{
String[] result = line.split("%");
String workerId = result[3].trim();
Worker worker = this.workers.get(workerId);
if ((worker != null)) {
boolean[] gradeMap = new boolean[5];
for (int i=0, j=0; i < result.length; i++) {
if(result[i].trim().equalsIgnoreCase("false") || result[i].trim().equalsIgnoreCase("true"))
{
gradeMap[j++] = Boolean.valueOf(result[i].trim());
}
else if(result[i].trim().equalsIgnoreCase("grade"))
worker.setGrade(Integer.parseInt(result[i+1].trim()));
else if(result[i].trim().equalsIgnoreCase("testDuration"))
worker.setSkillTestDuration(result[i+1].trim());
}
worker.setGradeMap(gradeMap);
}
}
/**
* Load the worker consent info and
* add in the workers hashMap
* @param line: The line of the log containing the consent info
*/
private void loadConsent(String line)
{
String[] result = line.split("%");
Worker worker = new Worker(result[3].trim(), result[5].trim(), null);
worker.setConsentDate(result[7].trim());
worker.setCurrentFileName(result[5].trim());
if(!(this.workers.containsKey(worker.getWorkerId())))
{
this.workers.put(worker.getWorkerId(), worker);
}
}
/**
* Load the worker feedback info and
* add in the designated worker.
* @param line: line containing the feedback data
*/
private void loadFeedback(String line)
{
String[] result = line.split("%");
String workerId = result[3].trim();
Worker worker = this.workers.get(workerId);
if(worker != null)
{
for (int i = 0; i < result.length; i++) {
if(result[i].trim().equalsIgnoreCase("feedback"))
worker.addSurveyAnswer("feedback", (i == (result.length -1)) ? "" : result[i+1]);
}
}
}
/**
* Load the worker quit info and
* add in the designated worker.
* @param line: line containing the quit data
*/
private void loadQuit(String line)
{
String[] result = line.split("%");
String workerId = result[3];
Worker worker = this.workers.get(workerId);
if(worker != null)
{
//for (int i = 0; i < result.length; i++) {
// if(result[i].trim().equalsIgnoreCase("answer"))
// worker.addQuitReason((i == (result.length -1)) ? "" : result[i+1].trim());
//}
worker.addQuitFileList(result[5]);
worker.addQuitReason(result[7]);
}
}
}
|
package com.tencent.mm.plugin.appbrand.ui.recents;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.tencent.mm.plugin.appbrand.ui.recents.h.a;
import com.tencent.mm.sdk.platformtools.x;
import java.util.ArrayList;
import java.util.List;
final class c extends h implements a {
ViewGroup goL;
private List<h> gzs;
private final a gzt;
c(Activity activity, ViewGroup viewGroup) {
if (activity == null || viewGroup == null) {
throw new IllegalStateException("Unexpected parameters");
}
this.gzt = new a(this, activity, (byte) 0);
ViewGroup linearLayout = new LinearLayout(viewGroup.getContext());
linearLayout.setOrientation(1);
this.goL = linearLayout;
linearLayout = this.goL;
List arrayList = new ArrayList(2);
e eVar = new e(activity, linearLayout);
eVar.gAw = this;
arrayList.add(eVar);
f fVar = new f(activity, linearLayout);
fVar.gAw = this;
arrayList.add(fVar);
this.gzs = arrayList;
a(this.gzs, this.goL);
aq(this.gzs);
}
private void a(List<h> list, ViewGroup viewGroup) {
if (list != null && list.size() != 0 && viewGroup != null) {
View view;
for (int i = 0; i < list.size(); i++) {
viewGroup.addView(((h) list.get(i)).aoh());
if (i != list.size() - 1) {
view = new View(viewGroup.getContext());
view.setBackgroundColor(-1);
LayoutParams layoutParams = new LinearLayout.LayoutParams(this.gzt.gzv, this.gzt.gzu);
layoutParams.gravity = 3;
viewGroup.addView(view, layoutParams);
}
}
Context context = viewGroup.getContext();
Drawable colorDrawable = new ColorDrawable(this.gzt.gzy);
view = new ImageView(context);
view.setImageDrawable(colorDrawable);
view.setBackgroundColor(-1);
LayoutParams layoutParams2 = new LinearLayout.LayoutParams(-1, this.gzt.gzz);
viewGroup.addView(view, 0, layoutParams2);
View imageView = new ImageView(context);
imageView.setImageDrawable(colorDrawable);
imageView.setBackgroundColor(-1);
viewGroup.addView(imageView, layoutParams2);
viewGroup.addView(new View(context), -1, this.gzt.gzx);
imageView = new ImageView(context);
imageView.setImageDrawable(colorDrawable);
imageView.setBackgroundColor(-1);
viewGroup.addView(imageView, -1, this.gzt.gzz);
}
}
private static void aq(List<h> list) {
if (list != null) {
for (h df : list) {
df.df(false);
}
}
}
final void aog() {
for (h aog : this.gzs) {
aog.aog();
}
}
final void onDetached() {
for (h onDetached : this.gzs) {
onDetached.onDetached();
}
}
final void onResume() {
for (h onResume : this.gzs) {
onResume.onResume();
}
}
final View aoh() {
return this.goL;
}
public final void a(h hVar, View view, boolean z) {
if (this.goL != null) {
h hVar2;
View childAt;
int i;
x.i("AppBrandLauncherRecentsListHeaderController", "onViewEnabledChanged [%s] [%s] [%b]", new Object[]{hVar, view, Boolean.valueOf(z)});
if (!(this.goL == null || this.gzs == null)) {
for (int i2 = 0; i2 < this.gzs.size() - 1; i2++) {
hVar2 = (h) this.gzs.get(i2);
if (hVar2 != null) {
if (hVar2.aol()) {
int i3 = i2 + 1;
while (true) {
int i4 = i3;
if (i4 >= this.gzs.size()) {
i3 = 0;
break;
}
h hVar3 = (h) this.gzs.get(i4);
if (hVar3 != null && hVar3.aol()) {
i3 = 1;
break;
}
i3 = i4 + 1;
}
if (i3 != 0) {
childAt = this.goL.getChildAt(this.goL.indexOfChild(hVar2.aoh()) + 1);
if (childAt != null) {
childAt.setVisibility(0);
}
}
} else {
childAt = this.goL.getChildAt(this.goL.indexOfChild(hVar2.aoh()) + 1);
if (childAt != null) {
childAt.setVisibility(8);
}
}
}
}
}
for (h hVar22 : this.gzs) {
childAt = hVar22.aoh();
if (childAt != null && childAt.getVisibility() == 0) {
x.i("AppBrandLauncherRecentsListHeaderController", "hasValidHeader %s", new Object[]{hVar});
i = 1;
break;
}
}
i = 0;
if (i != 0) {
this.goL.setVisibility(0);
} else {
this.goL.setVisibility(8);
}
}
}
}
|
package org.elasticsearch.hadoop.rest.bulk.bwc;
public class BulkOutputGeneratorV1 extends BulkOutputGeneratorBase {
@Override
protected String getSuccess() {
return " {\n" +
" \"$OP$\" : {\n" +
" \"_index\" : \"$IDX$\",\n" +
" \"_type\" : \"$TYPE$\",\n" +
" \"_id\" : \"$ID$\",\n" +
" \"_version\" : $VER$,\n" +
" \"_shards\" : {\n" +
" \"total\" : 2,\n" +
" \"successful\" : 1,\n" +
" \"failed\" : 0\n" +
" },\n" +
" \"status\" : $STAT$\n" +
" }\n" +
" }";
}
@Override
protected String getFailure() {
return " {\n" +
" \"$OP$\" : {\n" +
" \"_index\" : \"$IDX$\",\n" +
" \"_type\" : \"$TYPE$\",\n" +
" \"_id\" : \"$ID$\",\n" +
" \"status\" : $STAT$,\n" +
" \"error\" : \"$EMESG$\"\n" +
" }\n" +
" }";
}
@Override
protected Integer getRejectedStatus() {
return 429;
}
@Override
protected String getRejectionType() {
return "";
}
@Override
protected String getRejectionMsg() {
return "EsRejectedExecutionException[rejected execution (queue capacity 1) on org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$PrimaryPhase$1@22c141ba]";
}
}
|
package task3;
import java.util.List;
class Phone1{
String phone_id;
String phone_type;
int numphones;
String phone_no;
Phone1(String phone_id,String phone_type,int numphones,String phone_no){
this.phone_id=phone_id;
this.phone_type=phone_type;
this.numphones= numphones;
this.phone_no=phone_no;
}
}
public class Employee1 {
String ename;
int id;
List<Phone1> phone_details;
public Employee1(String ename,int id,List<Phone1> phone_details) {
this.ename=ename;
this.id=id;
this.phone_details=phone_details;
}
void display() {
System.out.println("employee name:"+ename+" "+"employ id:"+id);
System.out.println("phone id:"+phone_details.phone_id+" "+"phone type:"+phone_details.phone_type+" "+"number of phones:"+phone_details.numphones+"phone number:"+phone_details.phone_no);
}
public static void main(String[] args) {
Phone1 p=new Phone1("ID000749","mobile",1,"9898989898");
Phone1 p1=new Phone1("ID000459","lanline",2,"984802238") ;
List<Phone1> l1;
l1.add(p);
l1.add(p1);
Employee1 obj=new Employee1("sravani",51894876,l1);
// Employee1 obj1=new Employee1("Harshini",51894875,p1);
// obj1.display();
obj.display();
}
}
|
package uk.ac.ebi.pride.proteomes.pipeline.provider.generator.filter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.item.ItemProcessor;
import uk.ac.ebi.pride.proteomes.db.core.api.cluster.ClusterPsm;
import uk.ac.ebi.pride.proteomes.pipeline.mods.Modification;
import uk.ac.ebi.pridemod.ModReader;
import uk.ac.ebi.pridemod.model.PRIDEModPTM;
import uk.ac.ebi.pridemod.model.PTM;
import java.util.List;
import static uk.ac.ebi.pride.jmztab.model.MZTabUtils.translateCommaToTab;
/**
* User: ntoro
* Date: 06/12/2013
* Time: 10:29
*/
public class ClusterPsmItemMapMods implements ItemProcessor<ClusterPsm, ClusterPsm> {
private static final Log log = LogFactory.getLog(ClusterPsmItemMapMods.class);
public static final String SPLIT_CHAR = ":";
public ClusterPsm process(ClusterPsm item) throws Exception {
//Now they are preinserted in the DB, but it can be uncommented in the future
if (item.getModifications() != null && !item.getModifications().isEmpty()) {
String mappedMods = null;
String modColumn = item.getModifications();
//Avoids split neutral losses by the comma
modColumn = translateCommaToTab(modColumn);
// 0-MOD:00394,10-MOD:00587 -> (0,MOD:00394)(10,MOD:00587)
String[] mods = modColumn.split(",");
assert mods.length > 0;
mappedMods = mapModifications(mods[0]);
if (mappedMods == null || mappedMods.isEmpty()) {
log.debug("The provided modification " + mods[0] + " is not mappable");
log.debug("The cluster psm " + item.toString() + " will be filtered.");
return null;
}
if (mods.length > 1) {
for (int i = 1; i < mods.length; i++) {
//We assume that the modifications are sorted by position =
String aux = mapModifications(mods[i]);
if (aux == null || aux.isEmpty()) {
log.debug("The provided modification " + mods[i] + " is not mappable");
log.debug("The cluster psm " + item.toString() + " will be filtered.");
return null;
} else {
mappedMods = mappedMods + "," + aux;
}
}
}
item.setModifications(mappedMods);
}
return item;
}
/**
* Transform the modification string to a ModificationLocation. It will filtered neutral losses
*
* @param mod raw string from the cluster database (like 0-MOD:00394)
*/
protected static String mapModifications(String mod) {
ModReader modReader = ModReader.getInstance();
uk.ac.ebi.pride.proteomes.pipeline.mods.Modification mzTabMod = Modification.parseModification(mod);
if (mzTabMod == null) {
log.warn("Modification not parseable from the original mzTab: " + mod);
return null;
} else {
if (mzTabMod.getNeutralLoss() != null) {
log.warn("The modification contains a neutral loss: " + mzTabMod.getNeutralLoss() + ". It will be ignored.");
return null;
} else {
Modification.Type type = mzTabMod.getType();
if (!type.equals(Modification.Type.NEUTRAL_LOSS)) {
Double delta;
if (type.equals(Modification.Type.MOD) || type.equals(Modification.Type.UNIMOD)) {
String accession = mzTabMod.getType() + SPLIT_CHAR + mzTabMod.getAccession();
PTM ptm = modReader.getPTMbyAccession(accession);
if (ptm == null) {
log.debug("The provided modification " + accession + " cannot be found in the PSIMOD or Unimod ontology.");
return null;
}
delta = ptm.getMonoDeltaMass();
} else if (type.equals(Modification.Type.CHEMMOD)) {
try {
delta = Double.parseDouble(mzTabMod.getAccession());
} catch (NumberFormatException e) {
log.debug("Exception converting CHEMMOD: ", e.getCause());
return null;
}
} else if (type.equals(Modification.Type.PRDMOD)) {
//Modification already map
return mod;
} else {
log.debug("Modification with type: " + type + " cannot be mapped");
return null;
}
//We remap the modifications to PRIDE Mod
List<PTM> ptms = modReader.getPTMListByMonoDeltaMass(delta);
int count = 0;
for (PTM byMassPtm : ptms) { //If more than one we overwrite
if (byMassPtm instanceof PRIDEModPTM) {
String accValue = byMassPtm.getAccession().split(SPLIT_CHAR)[1];
mzTabMod.setAccession(accValue);
mzTabMod.setType(uk.ac.ebi.pride.proteomes.pipeline.mods.Modification.Type.PRDMOD);
log.debug("Mapped modification: " + mzTabMod.toString());
count++;
}
}
if (count == 0) {
log.debug("Modification with mass: " + delta + " can not be found in PRIDEMOD");
log.debug("The term " + mod + " needs to be added to PRIDEMOD");
return null;
} else if (count > 1) {
log.warn("Modification with mass: " + delta + " is mapped to more that one PRIDEMOD term");
}
}
}
}
return mzTabMod.toString();
}
}
|
package com.tt.miniapp.msg.file;
import com.a;
import com.tt.frontendapiinterface.ApiCallResult;
import com.tt.frontendapiinterface.b;
import com.tt.miniapp.msg.file.read.ApiReadFileCtrl;
import com.tt.miniapp.msg.file.write.ApiWriteFileCtrl;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.option.e.e;
public class FileSystemManager extends b {
private String functionName;
public FileSystemManager(String paramString1, String paramString2, int paramInt, e parame) {
super(paramString2, paramInt, parame);
this.functionName = paramString1;
}
public void act() {
byte b1;
ApiUnzipCtrl apiUnzipCtrl;
ApiUnlinkCtrl apiUnlinkCtrl;
ApiStatCtrl apiStatCtrl;
ApiReadDirCtrl apiReadDirCtrl;
ApiRmDirCtrl apiRmDirCtrl;
ApiRenameCtrl apiRenameCtrl;
ApiReadFileCtrl apiReadFileCtrl;
ApiMkDirCtrl apiMkDirCtrl;
ApiCopyFileCtrl apiCopyFileCtrl;
ApiAccessCtrl apiAccessCtrl;
ApiWriteFileCtrl<String, ApiCallResult> apiWriteFileCtrl;
ApiCallResult apiCallResult;
String str = this.functionName;
switch (str.hashCode()) {
default:
b1 = -1;
break;
case 1080408887:
if (str.equals("readdir")) {
b1 = 7;
break;
}
case 111449576:
if (str.equals("unzip")) {
b1 = 10;
break;
}
case 108628082:
if (str.equals("rmdir")) {
b1 = 6;
break;
}
case 103950895:
if (str.equals("mkdir")) {
b1 = 3;
break;
}
case 3540564:
if (str.equals("stat")) {
b1 = 8;
break;
}
case -506374511:
if (str.equals("copyFile")) {
b1 = 2;
break;
}
case -840447469:
if (str.equals("unlink")) {
b1 = 9;
break;
}
case -867956686:
if (str.equals("readFile")) {
b1 = 4;
break;
}
case -934594754:
if (str.equals("rename")) {
b1 = 5;
break;
}
case -1406748165:
if (str.equals("writeFile")) {
b1 = 0;
break;
}
case -1423461020:
if (str.equals("access")) {
b1 = 1;
break;
}
}
switch (b1) {
default:
str = null;
break;
case 10:
apiUnzipCtrl = new ApiUnzipCtrl(this.functionName);
break;
case 9:
apiUnlinkCtrl = new ApiUnlinkCtrl(this.functionName);
break;
case 8:
apiStatCtrl = new ApiStatCtrl(this.functionName);
break;
case 7:
apiReadDirCtrl = new ApiReadDirCtrl(this.functionName);
break;
case 6:
apiRmDirCtrl = new ApiRmDirCtrl(this.functionName);
break;
case 5:
apiRenameCtrl = new ApiRenameCtrl(this.functionName);
break;
case 4:
apiReadFileCtrl = new ApiReadFileCtrl(this.functionName);
break;
case 3:
apiMkDirCtrl = new ApiMkDirCtrl(this.functionName);
break;
case 2:
apiCopyFileCtrl = new ApiCopyFileCtrl(this.functionName);
break;
case 1:
apiAccessCtrl = new ApiAccessCtrl(this.functionName);
break;
case 0:
apiWriteFileCtrl = new ApiWriteFileCtrl(this.functionName);
break;
}
if (apiWriteFileCtrl != null) {
apiCallResult = apiWriteFileCtrl.invoke(this.mArgs);
} else {
String str1 = a.a("api is not supported in app: %s", new Object[] { this.functionName });
AppBrandLogger.e("FileSystemManager", new Object[] { str1 });
apiCallResult = ApiCallResult.a.b(this.functionName).d(str1).a();
}
callbackApiHandleResult(apiCallResult);
}
public String getActionName() {
return this.functionName;
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\msg\file\FileSystemManager.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package edu.wpi.cs.justice.cardmaker.http;
public class ShowCardRequest {
private final String cardId;
public ShowCardRequest(String cardId) {
super();
this.cardId = cardId;
}
public String getCardId() {
return cardId;
}
}
|
import java.util.Scanner;
public class PoD2 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Input four numbers: ");
int a,b,c,d;
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
d = sc.nextInt();
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println();
}
}
|
package fr.lteconsulting.commande.impl.modifdisque;
import fr.lteconsulting.Menu;
import fr.lteconsulting.commande.Commande;
import fr.lteconsulting.commande.ContexteExecution;
import fr.lteconsulting.modele.Disque;
import fr.lteconsulting.ui.SelectionDisque;
public class ModifierDisque implements Commande
{
@Override
public String getNom()
{
return "Modifier un disque";
}
@Override
public void executer( ContexteExecution contexte )
{
Disque disque = SelectionDisque.selectionnerDisque( "modification", contexte );
if( disque == null )
{
System.out.println( "Aucun disque sélectionné, on abandonne..." );
return;
}
disque.afficher( false );
Menu menu = new Menu( "Modification du disque '" + disque.getNom() + "'" );
menu.ajouterCommande( new ModifierTitreOuCodeBarreDisque( disque ) );
menu.ajouterCommande( new AjouterChansonDisque( disque ) );
// TODO menu.ajouterCommande( new SupprimerChansonDisque( disque ) );
// TODO menu.ajouterCommande( new ModifierChansonDisque( disque ) );
Commande commande = menu.saisirCommmande();
commande.executer( contexte );
}
}
|
package app.enums;
/**
* Created by Yixiu Liu on 11/29/2018.
*/
public enum Property {
STAGNANT_ITERATION, MAX_RUNTIME,MIN_TOUCHING,
ALGO_NAME_ANNEAL,
ALGO_NAME_GROW,
ANNEALINGTHRESHOLD,
GETSTATE_NAME,
GETDISTRICT_STATEID,
GETPRECINCT_DISTRICTID,
GETPOPULATION_DISTRICTID ,
LOADELECTIONDATA_DISTRICTID ,
GETDEMOGRAPHICS_PRECINCTID,
GETELECTIONDATA_PRECINCTID,
GETSTATECONSTITUTION_NAME,
}
|
package com.tencent.mm.plugin.wenote.ui.nativenote;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.wenote.model.nativenote.b.a;
import com.tencent.mm.plugin.wenote.model.nativenote.spans.b;
import com.tencent.mm.plugin.wenote.model.nativenote.spans.u;
class c$11 implements OnClickListener {
final /* synthetic */ a quY;
final /* synthetic */ c quZ;
c$11(c cVar, a aVar) {
this.quZ = cVar;
this.quY = aVar;
}
public final void onClick(View view) {
boolean z;
boolean z2 = true;
h.mEJ.h(14547, new Object[]{Integer.valueOf(7)});
b bVar = u.qtv;
if (this.quZ.quU) {
z = false;
} else {
z = true;
}
c.c(bVar, Boolean.valueOf(z));
c cVar = this.quZ;
if (this.quZ.quU) {
z2 = false;
}
cVar.quU = z2;
c.a(this.quZ, view, this.quZ.quU);
c.b(this.quY);
}
}
|
import java.util.Arrays;
// Class for a vector made of 3 components (i, j, k)
// Contains useful methods for calculating vectors
public class Vector3 {
// Default vector is 0, 0, 0
public float[] value = new float[]{0, 0, 0};
// Vector with set value
public Vector3(float i, float j, float k){
this.value = new float[]{i, j, k};
}
// 0, 0, 0
public Vector3(){
}
/**
* Calculating methods
**/
// Vector + Vector
public static Vector3 Add(Vector3 v1, Vector3 v2){
Vector3 total = new Vector3();
for(int i = 0; i < 3; i++){
total.value[i] = (v1.value[i] + v2.value[i]);
}
return total;
}
// Vector + Vector + Vector + Vector
public static Vector3 Add(Vector3 v1, Vector3 v2, Vector3 v3, Vector3 v4){
Vector3 total = new Vector3();
for(int i = 0; i < 3; i++){
total.value[i] = (v1.value[i] + v2.value[i] + v3.value[i] + v4.value[i]);
}
return total;
}
// Vector - Vector
public static Vector3 Subtract(Vector3 v1, Vector3 v2){
Vector3 total = new Vector3();
for(int i = 0; i < 3; i++){
total.value[i] = (v1.value[i] - v2.value[i]);
}
return total;
}
// Vector * Vector
public static Vector3 Multiply(Vector3 v1, Vector3 v2){
// cx = ay bz - az by
// cy = az bx - ax bz
// cz = ax by - ay bx
// x = 0 y = 1 z = 2
Vector3 total = new Vector3();
total.value[0] = (v1.value[1] * v2.value[2]) - (v1.value[2] * v2.value[1]);
total.value[1] = (v1.value[2] * v2.value[0]) - (v1.value[0] * v2.value[2]);
total.value[2] = (v1.value[0] * v2.value[1]) - (v1.value[1] * v2.value[0]);
return total;
}
// Vector * Constant
public static Vector3 Multiply(Vector3 v1, float f1){
Vector3 total = new Vector3();
for(int i = 0; i < 3; i++){
total.value[i] = (v1.value[i] * f1);
}
return total;
}
// Vector . Itself
public float dotProduct(){
float dotProduct = 0f;
dotProduct = (this.getValue()[0] * this.getValue()[0]) + (this.getValue()[1] * this.getValue()[1]) + (this.getValue()[2] * this.getValue()[2]);
return dotProduct;
}
public static float dotProduct(Vector3 v1, Vector3 v2){
float dotProduct = 0f;
dotProduct = (v1.getValue()[0] * v2.getValue()[0]) + (v1.getValue()[1] * v2.getValue()[1]) + (v1.getValue()[2] * v2.getValue()[2]);
return dotProduct;
}
// Getting magnitude/strength of vector
public float getMagnitude(){
float magnitude = (float)Math.sqrt(this.dotProduct());
return magnitude;
}
// Getting unit vector
public Vector3 getDirection(){
float magnitude = this.getMagnitude();
Vector3 direction = Vector3.Multiply(this, 1/magnitude);
return direction;
}
// Getters & Setters
public float[] getValue() {
return value;
}
public void setValue(float[] value) {
this.value = value;
}
// End
@Override
public String toString() {
return "" + Arrays.toString(value);
}
}
|
package com.base.level.test;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.base.StartCRMApp;
import com.base.common.util.DateUtils;
import com.base.crm.common.constants.CustomerLevelContainer;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = StartCRMApp.class)
public class LevelTest {
@Autowired
private CustomerLevelContainer level;
@Test
public void test(){
// System.err.println(level.levelMap);
System.err.println(DateUtils.getLastMonth());
}
}
|
package jcrawler.service.parser.domain;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.net.URI;
public class Page {
private Document document;
public Page(String content, URI baseUrl) throws IOException {
document = Jsoup.parse(content, baseUrl.toString());
}
public Document getDocument() {
return document;
}
}
|
package net.lax1dude.cs50_final_project.client.renderer.opengl;
import static org.lwjgl.opengles.GLES30.*;
import java.nio.ByteBuffer;
public class EaglVertexBuffer {
public final int glObject;
private int bufferSize;
private boolean destroyed = false;
public int getBufferSize() {
return bufferSize;
}
public EaglVertexBuffer() {
this.glObject = glGenBuffers();
this.bufferSize = -1;
}
public EaglVertexBuffer upload(ByteBuffer data, boolean once) {
glBindBuffer(GL_ARRAY_BUFFER, glObject);
if(data.remaining() != bufferSize) {
bufferSize = data.remaining();
glBufferData(GL_ARRAY_BUFFER, data, once ? GL_STATIC_DRAW : GL_DYNAMIC_DRAW);
}else {
glBufferSubData(GL_ARRAY_BUFFER, 0, data);
}
return this;
}
public EaglVertexBuffer upload(ByteBuffer data) {
return upload(data, true);
}
public EaglVertexBuffer uploadSub(int byteoffset, ByteBuffer data) {
if(data.remaining() + byteoffset > bufferSize) {
throw new IllegalArgumentException("Not enough space is allocated for this upload");
}
glBindBuffer(GL_ARRAY_BUFFER, glObject);
glBufferSubData(GL_ARRAY_BUFFER, byteoffset, data);
return this;
}
public void destroy() {
if(!destroyed) {
glDeleteBuffers(glObject);
destroyed = true;
}
}
public void finalize() {
if(!destroyed && EaglContext.contextAvailable()) {
EaglContext.log.warn("GL vertex buffer #{} leaked memory", glObject);
glDeleteBuffers(glObject);
destroyed = true;
}
}
}
|
package com.mobileappsco.training.surprise;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
/**
* Created by admin on 2/28/2016.
*/
public class Helpers {
public static void displayToastAndLog(Context mContext, int type, String message) {
switch (type) {
case Log.ERROR:
Log.e("MYAPP", message);
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
break;
case Log.INFO:
Log.i("MYAPP", message);
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
break;
case Log.VERBOSE:
Log.v("MYAPP", message);
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
break;
default:
Log.d("MYAPP", message);
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
break;
}
}
}
|
package controller.util.collectors.impl;
import controller.constants.FrontConstants;
import controller.exception.WrongInputDataException;
import controller.util.collectors.DataCollector;
import domain.Bus;
import domain.Schedule;
import org.apache.log4j.Logger;
import resource_manager.ResourceManager;
import javax.servlet.http.HttpServletRequest;
import java.sql.Date;
public class BusDataCollector extends DataCollector<Bus> {
private static ResourceManager resourceManager = ResourceManager.INSTANCE;
private static final Logger logger = Logger.getLogger(BusDataCollector.class);
@Override
public Bus retrieveData(HttpServletRequest request) throws WrongInputDataException {
logger.info("Retrieving bus data from request");
int counter = 7;
String plate = request.getParameter(FrontConstants.PLATE);
String model = request.getParameter(FrontConstants.MODEL);
String mileage = request.getParameter(FrontConstants.MILEAGE);
String inspection = request.getParameter(FrontConstants.INSPECTION);
String consumption = request.getParameter(FrontConstants.CONSUMPTION);
String release = request.getParameter(FrontConstants.RELEASE);
String seats = request.getParameter(FrontConstants.SEATS);
Bus bus = new Bus();
if (plate != null && plate.matches(resourceManager.getRegex("reg.plate"))) {
bus.setPlate(plate);
counter--;
}
if (model != null && model.matches(resourceManager.getRegex("reg.model"))) {
bus.setModel(model);
counter--;
}
if (mileage != null && mileage.matches(resourceManager.getRegex("reg.mileage"))) {
bus.setMileage(Integer.valueOf(mileage));
counter--;
}
if (inspection != null && inspection.matches(resourceManager.getRegex("reg.inspection"))
&& Date.valueOf(inspection).compareTo(new Date(System.currentTimeMillis())) < 0) {
bus.setInspection(Date.valueOf(inspection));
counter--;
}
if (consumption != null && consumption.matches(resourceManager.getRegex("reg.consumption"))) {
bus.setConsumption(Integer.valueOf(consumption));
counter--;
}
if (release != null && release.matches(resourceManager.getRegex("reg.release"))
&& Date.valueOf(release).compareTo(new Date(System.currentTimeMillis())) < 0) {
bus.setRelease(Date.valueOf(release));
counter--;
}
if (seats != null && seats.matches(resourceManager.getRegex("reg.seats"))) {
bus.setSeats(Integer.valueOf(seats));
counter--;
}
try {
Schedule schedule = new ScheduleDataCollector().retrieveData(request);
bus.setSchedule(schedule);
} catch (WrongInputDataException e) {
bus.setSchedule((Schedule) request.getAttribute(FrontConstants.SCHEDULE));
request.setAttribute(FrontConstants.BUS, bus);
throw new WrongInputDataException(e);
}
if (counter != 0) {
logger.warn("Not all input forms filled correctly");
request.setAttribute(FrontConstants.BUS, bus);
throw new WrongInputDataException("Not all input form filled correctly");
}
return bus;
}
}
|
/*
* (C) Copyright 2014, 2016 Hewlett Packard Enterprise Development LP
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.api.infrastructure.persistence.influxdb;
import com.google.common.base.Strings;
import com.google.inject.Inject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.Set;
import monasca.api.ApiConfig;
import monasca.api.domain.model.metric.MetricDefinitionRepo;
import monasca.api.domain.model.metric.MetricName;
import monasca.common.model.metric.MetricDefinition;
public class InfluxV9MetricDefinitionRepo implements MetricDefinitionRepo {
private static final Logger logger = LoggerFactory.getLogger(InfluxV9MetricDefinitionRepo.class);
private final ApiConfig config;
private final InfluxV9RepoReader influxV9RepoReader;
private final InfluxV9Utils influxV9Utils;
private final String region;
private final ObjectMapper objectMapper = new ObjectMapper();
@Inject
public InfluxV9MetricDefinitionRepo(ApiConfig config,
InfluxV9RepoReader influxV9RepoReader,
InfluxV9Utils influxV9Utils) {
this.config = config;
this.region = config.region;
this.influxV9RepoReader = influxV9RepoReader;
this.influxV9Utils = influxV9Utils;
}
boolean isAtMostOneSeries(String tenantId, String name, Map<String, String> dimensions)
throws Exception {
// Set limit to 2. We only care if we get 0, 1, or 2 results back.
String q = String.format("show series %1$s "
+ "where %2$s %3$s %4$s limit 2",
this.influxV9Utils.namePart(name, false),
this.influxV9Utils.privateTenantIdPart(tenantId),
this.influxV9Utils.privateRegionPart(this.region),
this.influxV9Utils.dimPart(dimensions));
logger.debug("Metric definition query: {}", q);
String r = this.influxV9RepoReader.read(q);
Series series = this.objectMapper.readValue(r, Series.class);
List<MetricDefinition> metricDefinitionList = metricDefinitionList(series,
tenantId,
name,
null,
null,
0);
logger.debug("Found {} metric definitions matching query", metricDefinitionList.size());
return metricDefinitionList.size() > 1 ? false : true;
}
@Override
public List<MetricDefinition> find(String tenantId, String name,
Map<String, String> dimensions,
DateTime startTime,
DateTime endTime,
String offset, int limit) throws Exception {
int startIndex = this.influxV9Utils.startIndex(offset);
String q = String.format("show series %1$s "
+ "where %2$s %3$s %4$s %5$s %6$s",
this.influxV9Utils.namePart(name, false),
this.influxV9Utils.privateTenantIdPart(tenantId),
this.influxV9Utils.privateRegionPart(this.region),
this.influxV9Utils.dimPart(dimensions),
this.influxV9Utils.limitPart(limit),
this.influxV9Utils.offsetPart(startIndex));
logger.debug("Metric definition query: {}", q);
String r = this.influxV9RepoReader.read(q);
Series series = this.objectMapper.readValue(r, Series.class);
List<MetricDefinition> metricDefinitionList = metricDefinitionList(series,
tenantId,
name,
startTime,
endTime,
startIndex);
logger.debug("Found {} metric definitions matching query", metricDefinitionList.size());
return metricDefinitionList;
}
@Override
public List<MetricName> findNames(String tenantId, Map<String, String> dimensions,
String offset, int limit) throws Exception {
//
// Use treeset to keep list in alphabetic/predictable order
// for string based offset.
//
List<MetricName> metricNameList = new ArrayList<>();
Set<String> matchingNames = new TreeSet<>();
String q = String.format("show series "
+ "where %1$s %2$s %3$s",
this.influxV9Utils.privateTenantIdPart(tenantId),
this.influxV9Utils.privateRegionPart(this.region),
this.influxV9Utils.dimPart(dimensions));
logger.debug("Metric name query: {}", q);
String r = this.influxV9RepoReader.read(q);
Series series = this.objectMapper.readValue(r, Series.class);
if (!series.isEmpty()) {
for (Serie serie : series.getSeries()) {
matchingNames.add(serie.getName());
}
}
List<String> filteredNames = filterMetricNames(matchingNames, limit, offset);
for (String filteredName : filteredNames) {
MetricName dimName = new MetricName(filteredName);
metricNameList.add(dimName);
}
logger.debug("Found {} metric definitions matching query", metricNameList.size());
return metricNameList;
}
private List<String> filterMetricNames(Set<String> matchingNames,
int limit,
String offset) {
Boolean haveOffset = !Strings.isNullOrEmpty(offset);
List<String> filteredNames = new ArrayList<>();
int remaining_limit = limit + 1;
for (String dimName : matchingNames) {
if (remaining_limit <= 0) {
break;
}
if (haveOffset && dimName.compareTo(offset) <= 0) {
continue;
}
filteredNames.add(dimName);
remaining_limit--;
}
return filteredNames;
}
private List<MetricDefinition> metricDefinitionList(Series series,
String tenantId,
String name,
DateTime startTime,
DateTime endTime,
int startIndex)
{
List<MetricDefinition> metricDefinitionList = new ArrayList<>();
if (!series.isEmpty()) {
int index = startIndex;
for (Serie serie : series.getSeries()) {
for (String[] values : serie.getValues()) {
MetricDefinition m = new MetricDefinition(serie.getName(),
this.influxV9Utils.getDimensions(values, serie.getColumns()));
//
// If start/end time are specified, ensure we've got measurements
// for this definition before we add to the return list
//
if (hasMeasurements(m, tenantId, startTime, endTime)) {
m.setId(String.valueOf(index++));
metricDefinitionList.add(m);
}
}
}
}
return metricDefinitionList;
}
private List<MetricName> metricNameList(Series series) {
List<MetricName> metricNameList = new ArrayList<>();
if (!series.isEmpty()) {
Serie serie = series.getSeries()[0];
for (String[] values : serie.getValues()) {
MetricName m = new MetricName(values[0]);
metricNameList.add(m);
}
}
return metricNameList;
}
private boolean hasMeasurements(MetricDefinition m,
String tenantId,
DateTime startTime,
DateTime endTime)
{
boolean hasMeasurements = true;
//
// Only make the additional query if startTime has been
// specified.
//
if (startTime == null) {
return hasMeasurements;
}
try {
String q = buildMeasurementsQuery(tenantId,
m.name,
m.dimensions,
startTime,
endTime);
String r = this.influxV9RepoReader.read(q);
Series series = this.objectMapper.readValue(r, Series.class);
hasMeasurements = !series.isEmpty();
} catch (Exception e) {
//
// If something goes wrong with the measurements query
// checking if there are current measurements, default to
// existing behavior and return the definition.
//
logger.error("Failed to query for measurements for: {}", m.name, e);
hasMeasurements = true;
}
return hasMeasurements;
}
private String buildMeasurementsQuery(String tenantId,
String name,
Map<String, String> dimensions,
DateTime startTime,
DateTime endTime) throws Exception
{
String q = String.format("select value, value_meta %1$s "
+ "where %2$s %3$s %4$s %5$s %6$s group by * slimit 1",
this.influxV9Utils.namePart(name, true),
this.influxV9Utils.privateTenantIdPart(tenantId),
this.influxV9Utils.privateRegionPart(this.region),
this.influxV9Utils.startTimePart(startTime),
this.influxV9Utils.dimPart(dimensions),
this.influxV9Utils.endTimePart(endTime));
logger.debug("Measurements query: {}", q);
return q;
}
}
|
package com.psl.flashnotes.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.google.gson.Gson;
import com.psl.flashnotes.bean.Answer;
import com.psl.flashnotes.bean.Globals;
import com.psl.flashnotes.bean.Notes;
import com.psl.flashnotes.bean.Queries;
import com.psl.flashnotes.bean.User;
import com.psl.flashnotes.service.AnswerService;
import com.psl.flashnotes.service.QueryService;
import com.psl.flashnotes.service.UserService;
@Controller
public class AnswerController {
@Autowired
private UserService userService;
@Autowired
private QueryService queryService;
@Autowired
private AnswerService answerService;
@RequestMapping(value = "/addAnswer/{queryId}", method = RequestMethod.GET)
public ModelAndView addAnswer(@PathVariable int queryId, HttpServletRequest request) {
System.out.println("Inside AnswerContr");
ModelAndView mav = new ModelAndView("answersOnQuery");// EDIT THE PAGE ACCORDINGLY
HttpSession session=request.getSession(false);
if(session!=null && session.getAttribute("userId")!=null){
String answerString = request.getParameter("answer");
Answer answer = new Answer();
// System.out.println(answerString);
answer.setAnswerContent(answerString);
Queries query = queryService.getQueriesById(queryId);
// System.out.println(query);
answer.setQuery(query);
session = request.getSession(false);
int userId = (Integer) session.getAttribute("userId");
User user = userService.getUserById(userId);
System.out.println(user);
answer.setUser(user);
// q.setUser(user); user to be identified by session
// Once query is added , notes page is to be refreshed and added query
// should be displayed
Gson gson=new Gson();
mav.addObject("addAnswer",gson.toJson(answerService.addAnswer(answer)));
return mav;
}
else{
mav.addObject("answer","Login first");
mav.setViewName("login");
return mav;
}
}
@RequestMapping(value = "/addAnswer1/{queryId}", method = RequestMethod.POST)
public @ResponseBody String addAnswer1(@RequestParam("answer") String answer,@PathVariable int queryId, HttpServletRequest request) {
System.out.println("Inside AnswerContr");
//ModelAndView mav = new ModelAndView("answersOnQuery");// EDIT THE PAGE ACCORDINGLY
HttpSession session=request.getSession(false);
if(session!=null && session.getAttribute("userId")!=null){
//String answerString = request.getParameter("answer");
Answer newAnswer = new Answer();
newAnswer.setAnswerContent(answer);
Queries query = queryService.getQueriesById(queryId);
System.out.println(query);
newAnswer.setQuery(query);
session = request.getSession(false);
int userId = (Integer) session.getAttribute("userId");
User user = userService.getUserById(userId);
System.out.println(user);
newAnswer.setUser(user);
// q.setUser(user); user to be identified by session
// Once query is added , notes page is to be refreshed and added query
// should be displayed
Gson gson=new Gson();
// mav.addObject("addAnswer",gson.toJson(answerService.addAnswer(answer)));
//return mav;
String json=gson.toJson(answerService.addAnswer(newAnswer));
return json;
}
else{
//mav.addObject("answer","Login first");
//mav.setViewName("login");
return "please Login first";
}
}
@RequestMapping("/getAllAnswers")
public ModelAndView getAllNotes(HttpServletRequest request) {
ModelAndView mav = new ModelAndView();
HttpSession session=request.getSession(false);
if(session!=null && session.getAttribute("userId")!=null){
List<Answer> answerList = answerService.getAllAnswer();
//mav.addObject("answerList", answerList);
Gson gson=new Gson();
mav.addObject("addAnswer",gson.toJson(answerList));
mav.setViewName("display");
return mav;
}
else{
mav.addObject("answer","Login first");
mav.setViewName("login");
return mav;
}
}
@RequestMapping(value = "getAnswer/{queryId}")
public ModelAndView getAnswer(@PathVariable int queryId,HttpServletRequest request) {
HttpSession session=request.getSession(false);
System.out.println(session);
ModelAndView mav = new ModelAndView();
if(session!=null){
List<Answer> answerList = answerService.getAnswer(queryId);
System.out.println(answerList);
Queries query=queryService.getQueriesById(queryId);
Gson gson=new Gson();
mav.addObject("answerList",gson.toJson(answerList));
mav.addObject("loggedInUser", Globals.userIdentity);
mav.addObject("query",gson.toJson(query));
//mav.addObject("answer", answer);
mav.setViewName("answersOnQuery");
return mav;
}
else{
mav.addObject("answer","Login first");
mav.setViewName("login");
return mav;
}
}
@RequestMapping(value = "/getAnswerById/{answerId}")
public ModelAndView getCourseById(@PathVariable int answerId,HttpServletRequest request) {
HttpSession session=request.getSession(false);
System.out.println(session);
ModelAndView mav = new ModelAndView();
if(session!=null){
Answer answer = answerService.getAnswerById(answerId);
System.out.println(answer);
Gson gson=new Gson();
mav.addObject("answer",gson.toJson(answer));
//mav.addObject("answer", answer);
mav.setViewName("answersOnQuery");
return mav;
}
else{
mav.addObject("answer","Login first");
mav.setViewName("login");
return mav;
}
}
@RequestMapping(value = "/updateAnswerLikes/{answerId}")
public ModelAndView updateLikes(@PathVariable int answerId,HttpServletRequest request) {
HttpSession session=request.getSession(false);
ModelAndView mav = new ModelAndView();
if(session!=null && session.getAttribute("userId")!=null){
mav.setViewName("answersOnQuery");// EDIT THE PAGE ACCORDINGLY
Gson gson=new Gson();
mav.addObject("answer",gson.toJson(answerService.updateLikes(answerId)));
return mav;
}
else{
// mav.addObject("answer","Login first");
mav.setViewName("login");
return mav;
}
}
@RequestMapping(value = "/updateAnswerLikes1/{answerId}")
public @ResponseBody String updateLikes1(@PathVariable int answerId,HttpServletRequest request) {
HttpSession session=request.getSession(false);
if(session!=null && session.getAttribute("userId")!=null){
Gson gson=new Gson();
String data = gson.toJson(answerService.updateLikes(answerId));
return data;
}
else{
// mav.addObject("answer","Login first");
// mav.setViewName("login");
return "Please Login to Continue";
}
}
@RequestMapping(value="/getAnswerByAuthor/{userId}")
public ModelAndView getAnswerByAuthor(@PathVariable int userId,HttpServletRequest request){
ModelAndView mav = new ModelAndView();
HttpSession session=request.getSession(false);
if(session!=null && session.getAttribute("userId")!=null){
List<Answer> answersList=answerService.getAnswerByAuthorId(userId);
Gson gson=new Gson();
mav.addObject("answerlistOfAuthor",gson.toJson(answersList));
// mav.addObject("answerlistOfAuthor", answersList);
System.out.println("answerList "+answersList);
mav.setViewName("display");
return mav;
}
else{
mav.addObject("answer","Login first");
mav.setViewName("login");
return mav;
}
}
}
|
package br.com.functional.programming.mock;
import br.com.functional.programming.dto.Person;
import java.util.List;
public interface PersonMock {
final Person MIKE = new Person("Mike", 20);
final Person NANCY = new Person("Nancy", 25);
final Person JOHN = new Person("John", 15);
final Person JULIE = new Person("Julie", 35);
final List<Person> PERSON_LIST_WITH_MIKE = List.of(MIKE, NANCY, JOHN, JULIE);
final List<Person> PERSON_LIST_WITHOUT_MIKE = List.of(NANCY, JOHN, JULIE);
}
|
package com.rx.rxmvvmlib.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.rx.rxmvvmlib.ui.base.AppManager;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* Created by wuwei
* 2020/12/31
* 佛祖保佑 永无BUG
*/
public abstract class IActivityLifecycleCallbacks {
private int appCount;
private boolean isRunInBackground = true;
public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
AppManager.getInstance().addActivity(activity);
}
public void onActivityStarted(@NonNull Activity activity) {
appCount++;
if (isRunInBackground) {
//应用从后台回到前台 需要做的操作
isRunInBackground = false;
back2App(activity);
}
}
public void onActivityResumed(@NonNull Activity activity) {
}
public void onActivityPaused(@NonNull Activity activity) {
if (activity.isFinishing()) {
AppManager.getInstance().removeActivity(activity);
}
}
public void onActivityStopped(@NonNull Activity activity) {
appCount--;
if (appCount == 0) {
//应用进入后台 需要做的操作
isRunInBackground = true;
leaveApp(activity);
}
}
public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
}
public void onActivityResult(@NonNull Activity activity, int requestCode, int resultCode, @Nullable Intent data) {
}
public void onActivityDestroyed(@NonNull Activity activity) {
}
public void onAppExit(@NonNull Activity activity) {
}
public abstract void back2App(Context context);
public abstract void leaveApp(Context context);
}
|
package com.gerray.fmsystem.LesseeModule;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.gerray.fmsystem.R;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.squareup.picasso.Picasso;
import java.text.DateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
public class RequestPopUp extends AppCompatActivity {
private TextInputEditText requestDescription;
private ImageView req_image;
private static final int PICK_IMAGE_REQUEST = 1;
private Uri mImageUri;
DatabaseReference databaseReference;
StorageReference mStorageRef;
StorageTask mUploadTask;
FirebaseAuth auth;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request_pop_up);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
getWindow().setLayout((int) (width * .9), (int) (height * .6));
requestDescription = findViewById(R.id.req_desc);
req_image = findViewById(R.id.request_imageView);
Button btnImage = findViewById(R.id.req_imageBtn);
btnImage.setOnClickListener(v -> openFileChooser());
Button btnAdd = findViewById(R.id.requestAdd);
btnAdd.setOnClickListener(v -> postRequest());
auth = FirebaseAuth.getInstance();
final FirebaseUser currentUser = auth.getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Requests");
assert currentUser != null;
mStorageRef = FirebaseStorage.getInstance().getReference().child("Facilities").child(currentUser.getUid());
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
Picasso.with(this).load(mImageUri).into(req_image);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void postRequest() {
progressDialog.setMessage("Sending Request");
progressDialog.show();
final String description = Objects.requireNonNull(requestDescription.getText()).toString().trim();
DateFormat dateFormat = DateFormat.getDateInstance();
Date date = new Date();
final String requestDate = dateFormat.format(date);
final String requestID = UUID.randomUUID().toString();
if (TextUtils.isEmpty(description)) {
Toast.makeText(this, "Add Description", Toast.LENGTH_SHORT).show();
return;
}
if (mImageUri != null) {
final StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(taskSnapshot -> {
fileReference.getDownloadUrl().addOnSuccessListener(uri -> {
final String downUri = uri.toString().trim();
LesseeRequestClass requestClass = new LesseeRequestClass(requestID, auth.getUid(), description, requestDate, downUri);
DatabaseReference dbLoc = databaseReference.push();
dbLoc.setValue(requestClass);
});
progressDialog.dismiss();
Toast.makeText(RequestPopUp.this, "Sent", Toast.LENGTH_SHORT).show();
RequestPopUp.this.finish();
})
.addOnFailureListener(e -> Toast.makeText(RequestPopUp.this, e.getMessage(), Toast.LENGTH_SHORT).show())
.addOnProgressListener(taskSnapshot -> {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressDialog.setProgress((int) progress);
});
} else {
LesseeRequestClass requestClass = new LesseeRequestClass(requestID, auth.getUid(), description, requestDate, null);
DatabaseReference dbLoc = databaseReference.push();
dbLoc.setValue(requestClass);
progressDialog.dismiss();
Toast.makeText(RequestPopUp.this, "Sent", Toast.LENGTH_SHORT).show();
RequestPopUp.this.finish();
}
}
}
|
package mocking;
import java.util.LinkedList;
import java.util.Queue;
public class Printer {
private Queue<PrintJob> jobs = new LinkedList<PrintJob>();
public void addToQueue(PrintJob job) {
jobs.add(job);
}
public boolean startPrinting() {
// complicated methode
return false;
}
}
|
package com.example.controller;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/user")
public class UserController {
@Autowired
UserService userService;
@PostMapping()
public Integer saveUser(@RequestBody User user) {
userService.save(user);
return user.getId();
}
@PutMapping()
public User updateUser(@RequestBody User user) throws Exception {
userService.updateById(user);
return user;
}
@DeleteMapping()
public void deleteUser(@RequestBody User user) throws Exception {
userService.delete(user);
}
@PostMapping("page")
public List<User> page(@RequestBody Map<String,Object> params, int pageNum, int size) throws Exception {
return userService.page(params, pageNum, size);
}
@PostMapping("like")
public List<User> like(@RequestBody User user){
return userService.like(user);
}
}
|
package com.epam.training.sportsbetting.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.epam.training.sportsbetting.web.service.PlayerService;
@Controller
public class PlayerController {
@Autowired
private PlayerService playerService;
@RequestMapping(value = "/home", method = RequestMethod.GET)
public ModelAndView showHome(ModelAndView model) {
playerService.getPlayerData(model);
return model;
}
@RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET)
public String showLogin() {
return "login";
}
@RequestMapping(value = "/saveplayer/{id}", method = RequestMethod.POST)
public String savePlayer(@RequestParam("name") String name, @RequestParam("birth") String birth,
@RequestParam("accountNumber") String accountNumber, @RequestParam("currency") String currency,
@RequestParam("balance") String balance) {
playerService.updatePlayer(name, birth, accountNumber, currency, balance);
return "redirect:/home";
}
@RequestMapping(value = "/logout", method = { RequestMethod.GET, RequestMethod.POST })
public String logoutPage(HttpServletRequest request, HttpServletResponse response) {
playerService.logoutUser(request, response);
return "redirect:/";
}
}
|
package com.classcheck.type;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.table.DefaultTableModel;
import com.change_vision.jude.api.inf.model.IClass;
import com.classcheck.analyzer.source.CodeVisitor;
import com.classcheck.autosource.Field;
import com.classcheck.autosource.Method;
import com.classcheck.autosource.MyClass;
import com.classcheck.autosource.MyClassCell;
import com.github.javaparser.ast.body.MethodDeclaration;
/**
* ソースコードで宣言されている参照型が
* テーブルと対応付けた型になっているか
* あるいは
* 「java」パッケージで定義されているクラスや
* 基本型
* であるか
* どうか調べるクラス
*
* @author masa
*
*/
public class ReferenceType {
private List<IClass> javaPackage;
private DefaultTableModel tableModel;
/** クラス図で定義された型 */
private String umlType;
/** ソースコードで定義された型 */
private String codeType;
private ReferenceType(List<IClass> javaPackage,DefaultTableModel tableModel){
this.javaPackage = javaPackage;
this.tableModel = tableModel;
}
public ReferenceType(List<IClass> javaPackage, DefaultTableModel tableModel,Method umlMethod,MethodDeclaration codeMethod) {
this(javaPackage,tableModel);
initMethod(umlMethod,codeMethod);
}
public ReferenceType(List<IClass> javaPackage,
DefaultTableModel tableModel, Field umlField,
StringBuilder fieldDefinition_sb) {
this(javaPackage,tableModel);
initField(umlField,fieldDefinition_sb);
}
private void initField(Field umlField,StringBuilder fieldDefinition_sb) {
this.umlType = umlField.getType();
this.codeType = fieldDefinition_sb.toString();
String splits[] = codeType.split("=");
splits = splits[0].split(" ");
//配列が「String args[]」のように後ろに[]が来るので型の後に来るように調整
if (codeType.contains("[]")) {
codeType = splits[splits.length - 2] + "[]";
}else{
codeType = splits[splits.length - 2];
}
System.out.println("umlType(R):"+umlType);
System.out.println("codeType(R):"+codeType);
}
private void initMethod(Method umlMethod, MethodDeclaration codeMethod) {
umlType = umlMethod.getReturntype();
String splits[] = codeMethod.getDeclarationAsString().split("\\(");
splits = splits[0].split(" ");
codeType = splits[splits.length - 2];
}
public boolean evaluate() {
boolean rtnVal = false;
//型が配列かどうか
boolean isArrayCode = false;
boolean isArrayUML = false;
Object column_0,column_1;
JComboBox box_1;
MyClass myClass;
CodeVisitor codeVisitor;
String umlClassName,codeClassName;
int row = 0;
if (umlType.contains("[]")) {
isArrayUML = true;
umlType = umlType.replaceAll("\\[\\]", "");
}
if(codeType.contains("[]")){
isArrayCode = true;
codeType = codeType.replaceAll("\\[\\]", "");
}
//ソースコードとクラス図の定義が同じ配列、あるいは単一であるか判断する
if (isArrayUML != isArrayCode) {
rtnVal = false;
return rtnVal;
}
//javaパッケージの中に定義されているクラスかどうか調べる
for(IClass iClass : javaPackage){
if (iClass.getName().equals(codeType)) {
if (iClass.getName().equals(umlType)) {
rtnVal = true;
return rtnVal;
}
}
}
//同じ基本型であるかどうかを調べる
if (new BasicType(umlType, codeType).evaluate()) {
rtnVal = true;
return rtnVal;
}
for (row = 0 ; row < tableModel.getRowCount() ; row++){
column_0 = tableModel.getValueAt(row, 0);
if (column_0 instanceof MyClassCell ){
myClass = ((MyClassCell) column_0).getMyClass();
umlClassName = myClass.getName();
if (umlClassName.equals(umlType)) {
rtnVal = true;
break;
}
}else{
rtnVal = false;
break;
}
}
if (rtnVal) {
column_1 = tableModel.getValueAt(row, 1);
/*
*なぜかテーブルのアイテムがCodeVisitorクラスと
*JComboBoxの時がある
*/
if(column_1 instanceof JComboBox){
box_1 = (JComboBox) column_1;
if (box_1.getSelectedItem() instanceof CodeVisitor){
codeVisitor = (CodeVisitor) box_1.getSelectedItem();
codeClassName = codeVisitor.getClassName();
System.out.println("codeClassName:"+codeClassName);
if (codeClassName.equals(codeType)) {
rtnVal = true;
}else{
rtnVal = false;
}
}
}else if(column_1 instanceof CodeVisitor){
codeVisitor = (CodeVisitor) column_1;
codeClassName = codeVisitor.getClassName();
System.out.println("codeClassName:"+codeClassName);
if (codeClassName.equals(codeType)) {
rtnVal = true;
}else{
rtnVal = false;
}
}
}
return rtnVal;
}
}
|
package com.smxknife.softmarket.common.comm;
public enum RespMsgType {
text, music, news, image, voice, video, wxcard
}
|
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class YanghuiAngile {
public static void main(String[] args) {
System.out.println("请输入行数");
Scanner scanner = new Scanner(System.in);
int rowNums = scanner.nextInt();
System.out.println(generate(rowNums));
}
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
// 处理为0的场景
if (numRows == 0) {
return res;
}
res.add(new ArrayList<Integer>());
res.get(0).add(1);
// 处理大于1的场景
for (int rowNum = 1; rowNum < numRows; rowNum++) {
List<Integer> preRow = res.get(rowNum - 1);
List<Integer> curRow = new ArrayList<Integer>();
// 前后都加一
curRow.add(1);
for (int j = 1; j < rowNum; j++) { // 遍历的时候从1开始,取上一个
curRow.add(preRow.get(j - 1) + preRow.get(j)); // 这个取法就很巧妙,遍历上一行 恰好从节点一开始取数据
}
curRow.add(1);
res.add(curRow);
}
return res;
}
public static void printList(List<List<Integer>> res) {
for (List<Integer> nums : res) {
System.out.println(nums);
}
}
}
|
package com.tencent.mm.plugin.record.ui;
import android.view.MenuItem;
import com.tencent.mm.g.a.cb;
import com.tencent.mm.g.a.ch;
import com.tencent.mm.g.a.mu;
import com.tencent.mm.pluginsdk.model.e;
import com.tencent.mm.sdk.b.a;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.ui.base.n$d;
class RecordMsgImageUI$9 implements n$d {
final /* synthetic */ RecordMsgImageUI mtp;
RecordMsgImageUI$9(RecordMsgImageUI recordMsgImageUI) {
this.mtp = recordMsgImageUI;
}
public final void onMMMenuItemSelected(MenuItem menuItem, int i) {
switch (menuItem.getItemId()) {
case 0:
RecordMsgImageUI.f(this.mtp);
return;
case 1:
RecordMsgImageUI recordMsgImageUI = this.mtp;
ch chVar = new ch();
e.a(chVar, recordMsgImageUI.getIntent().getIntExtra("key_favorite_source_type", 1), recordMsgImageUI.bqL());
chVar.bJF.bJM = 10;
chVar.bJF.activity = recordMsgImageUI;
a.sFg.m(chVar);
return;
case 2:
RecordMsgImageUI.g(this.mtp);
return;
case 3:
String h = RecordMsgImageUI.h(this.mtp);
if (!bi.oW(h)) {
mu muVar = (mu) RecordMsgImageUI.i(this.mtp).get(h);
if (muVar != null) {
cb cbVar = new cb();
cbVar.bJq.activity = this.mtp;
cbVar.bJq.bHL = muVar.bXK.result;
cbVar.bJq.bJr = muVar.bXK.bJr;
cbVar.bJq.bJt = 8;
RecordMsgImageUI.a(this.mtp, cbVar);
cbVar.bJq.bJs = muVar.bXK.bJs;
if (this.mtp.getIntent() != null) {
cbVar.bJq.bJx = this.mtp.getIntent().getBundleExtra("_stat_obj");
}
a.sFg.m(cbVar);
return;
}
return;
}
return;
default:
return;
}
}
}
|
package com.tencent.mm.plugin.fingerprint.b;
import com.tencent.mm.g.a.bq;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.q;
import com.tencent.mm.plugin.wallet_core.c.y;
import com.tencent.mm.sdk.platformtools.x;
class a$1 implements Runnable {
final /* synthetic */ bq jgn;
final /* synthetic */ a jgo;
a$1(a aVar, bq bqVar) {
this.jgo = aVar;
this.jgn = bqVar;
}
public final void run() {
if (this.jgn.bJb == null) {
return;
}
if (this.jgn.bJb.retCode == 0) {
x.i("MicroMsg.BaseFingerprintImp", "close finger print success!");
if (q.GS()) {
x.i("MicroMsg.BaseFingerprintImp", "now context is isPayUPay!");
return;
}
x.i("MicroMsg.BaseFingerprintImp", "do bound query, update data");
g.Ek();
g.Eh().dpP.a(new y(null, 19), 0);
return;
}
x.i("MicroMsg.BaseFingerprintImp", "close finger print failed!");
}
}
|
/**
* @author Mario de Leon
* @author Derek Banas
*
*
* Codigo del arbol binario y de un nodo codificado con
* ayuda de BINARY TREE IN JAVA por Derek Banas:
* http://www.newthinktank.com/2013/03/binary-tree-in-java/
*
*/
public class BinarySearchTree{
Nodo raiz;
public void addNodo(String ingles, String espaniol) {
Nodo nodo = new Nodo(ingles,espaniol);
if(raiz != null) {
//Establecer la raiz
Nodo esteNodo = raiz;
//Padre del nodo
Nodo padre;
while (true) {
//Se comienza desde la raiz
padre = esteNodo;
//Agregar nodo (ya sea izq o der)
if(ingles.compareTo(esteNodo.ingles) <= 0) {
//Este nodo va a la izq
esteNodo = esteNodo.hijoIzq;
if(esteNodo == null) {
padre.hijoIzq = nodo;
return;
}
}else { //Nodo va en la derecha
esteNodo = esteNodo.hijoDer;
if(esteNodo == null) {
padre.hijoDer = nodo;
return;
}
}
}
}else { //Si no hay raiz, este se vuelve raiz
raiz = nodo;
}
}
public Nodo findNodo(String ingles) {
//Se comienza desde arriba
Nodo esteNodo = raiz;
//Si no se encuentra se sigue buscando
while(esteNodo.ingles != ingles) {
//Izq
if(ingles.compareTo(esteNodo.ingles)<0) {
esteNodo = esteNodo.hijoIzq;
}else {
esteNodo = esteNodo.hijoDer;
}
//Si no hay nodo
if(esteNodo==null) {
return null;
}
}
return esteNodo;
}
//Ordenamiento del arbol: inOrder, preOrder, postOrder
public void inOrder(Nodo esteNodo) {
if(esteNodo != null) {
//Nodo izq
inOrder(esteNodo.hijoIzq);
//Nodo actual
System.out.println(esteNodo);
//Nodo der
inOrder(esteNodo.hijoDer);
}
}
public void preOrder(Nodo esteNodo) {
if(esteNodo != null) {
System.out.println(esteNodo);
//Nodo izq
inOrder(esteNodo.hijoIzq);
//Nodo der
inOrder(esteNodo.hijoDer);
}
}
public void postOrder(Nodo esteNodo) {
if(esteNodo != null) {
//Nodo izq
inOrder(esteNodo.hijoIzq);
//Nodo der
inOrder(esteNodo.hijoDer);
System.out.println(esteNodo);
}
}
}
class Nodo{
String ingles;
String espaniol;
Nodo hijoIzq;
Nodo hijoDer;
public String getIngles() { return ingles; }
public String getEspaniol() { return espaniol; }
Nodo(String ingles, String espaniol){
this.ingles = ingles;
this.espaniol = espaniol;
}
public String toString() {
return ingles + " es " + espaniol;
}
}
|
package dev.televex.fhgcore.commands;
import dev.televex.fhgcore.core;
import dev.televex.fhgcore.tags;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* All code Copyright (c) 2015 by Eric_1299. All Rights Reserved.
*/
public class back implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender instanceof Player) {
Player p = (Player) sender;
if (core.backdata.containsKey(p)) {
p.teleport(core.backdata.get(p));
p.sendMessage(tags.gtag + "Teleported to previous location.");
} else {
p.sendMessage(tags.etag + "You haven't teleported anywhere!");
}
return true;
} else {
sender.sendMessage(tags.player);
}
return true;
}
}
|
package com.tencent.mm.plugin.appbrand.widget.recentview;
import android.view.MenuItem;
import android.view.View;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.appbrand.appusage.u;
import com.tencent.mm.plugin.appbrand.n.d;
import com.tencent.mm.plugin.appbrand.n.f;
import com.tencent.mm.plugin.appbrand.report.AppBrandStatObject;
import com.tencent.mm.plugin.appbrand.widget.recentview.AppBrandRecentView.a;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.base.n;
class c$1 implements a {
final /* synthetic */ c gPw;
c$1(c cVar) {
this.gPw = cVar;
}
public final boolean a(View view, a aVar, float f, float f2) {
if (c.a(this.gPw) != null) {
c.a(this.gPw).a(view, aVar, f, f2);
}
if (aVar.type == 0) {
((f) g.l(f.class)).x(this.gPw.getContext(), 13);
} else {
this.gPw.setLayoutFrozen(true);
AppBrandStatObject appBrandStatObject = new AppBrandStatObject();
appBrandStatObject.scene = 1089;
((d) g.l(d.class)).a(this.gPw.getContext(), aVar.gOT.username, null, aVar.gOT.fmv, -1, null, appBrandStatObject);
}
return false;
}
public final boolean b(View view, final a aVar, float f, float f2) {
if (c.a(this.gPw) != null) {
c.a(this.gPw).b(view, aVar, f, f2);
}
x.i("MicroMsg.ConversationAppBrandRecentView", "[onItemLongClick] x:%s", new Object[]{Float.valueOf(f)});
if (aVar.type != 0) {
new com.tencent.mm.ui.widget.b.a(this.gPw.getContext()).a(view, 0, 0, new 1(this), new n.d() {
public final void onMMMenuItemSelected(MenuItem menuItem, int i) {
if (menuItem.getItemId() == 1 && aVar.position >= 0) {
c.b(c$1.this.gPw);
x.i("MicroMsg.ConversationAppBrandRecentView", "[onItemLongClick] Delete position:%s", new Object[]{Integer.valueOf(aVar.position)});
((u) g.l(u.class)).ap(aVar.gOT.username, aVar.gOT.fmv);
c$1.this.gPw.getRecentItemList().remove(aVar.position);
c$1.this.gPw.getAdapter().bn(aVar.position);
}
}
}, (int) f, (int) f2);
}
return false;
}
}
|
package com.shopping.etrade.mock;
import java.math.BigDecimal;
import com.shopping.etrade.dto.base.MoneyDTO;
import com.shopping.etrade.model.base.Money;
public class MoneyMocker {
public static Money generateMoney() {
Money money = new Money();
money.setAmount(BigDecimal.TEN);
money.setCurrency("TL");
return money;
}
public static MoneyDTO generateMoneyDTO() {
MoneyDTO moneyDTO = new MoneyDTO(BigDecimal.TEN, "TL");
return moneyDTO;
}
}
|
package assignment10.fitbit2;
import java.awt.Font;
import java.nio.charset.StandardCharsets;
import jssc.SerialPortException;
import sedgewick.Draw;
public class Fitbit2 {
final private SerialComm port;
public Chart stepWindow;
public Chart sleepWindow;
public Chart tempWindow;
public Draw summaryWindow;
private final Font SUM_TITLE = new Font("Title", Font.BOLD, 40);
private final Font SUM_TEXT = new Font("Text", Font.PLAIN, 20);
private int currentStepCount;
private int currentSleepTime;
private float currentTemp;
public static final int x_TEXT_AREA = 200;
public static final double Y_ZERO = 1.5;
public static final int CANVAS_WIDTH = 750;
public static final int CANVAS_HEIGHT = 400;
private long currentMillis = 1;
private long lastPedResetMillis = 0;
enum State {
waitMagic,
waitKey,
debug,
error,
timestamp,
pedometer,
sleep,
cx,
cy,
cz,
pedReset,
sleepReset,
filTemp
};
private State currentState;
public Fitbit2(String portname) {
port = new SerialComm("COM3", false);
currentState = State.waitMagic;
currentStepCount = 0;
currentSleepTime = 0;
currentTemp = 0;
stepWindow = new Chart("Steps", CANVAS_WIDTH, CANVAS_HEIGHT, "Time (s)", "Force (g)");
stepWindow.setBorders(5, 0.8);
stepWindow.setXscale(45, 5);
stepWindow.setDataPointInterval(200);
stepWindow.setYscale(-1,3, 1);
stepWindow.setPenRadius(0.01);
stepWindow.drawAxesAndTitle();
stepWindow.show();
stepWindow.addPlot("cx", Draw.BLUE);
stepWindow.addPlot("cy", Draw.GREEN);
stepWindow.addPlot("cz", Draw.RED);
stepWindow.allowAnnotationsFor("cz");
sleepWindow = new Chart("Sleep Time", CANVAS_WIDTH, CANVAS_HEIGHT, "Total time (s)", "Good sleep time (s)");
sleepWindow.setBorders(5, 5);
sleepWindow.setXscale(45, 5);
sleepWindow.setDataPointInterval(1000);
sleepWindow.setYscale(0, 30, 5);
sleepWindow.dynamicY = true;
sleepWindow.setPenRadius(0.01);
sleepWindow.drawAxesAndTitle();
sleepWindow.show();
sleepWindow.addPlot("sleep time", Draw.MAGENTA);
tempWindow = new Chart("Temperature", CANVAS_WIDTH, CANVAS_HEIGHT, "Time (s)", "Temperature (C)");
tempWindow.setBorders(5, 5);
tempWindow.setXscale(45, 5);
tempWindow.setDataPointInterval(1000);
tempWindow.setYscale(10, 30, 5);
tempWindow.setPenRadius(0.01);
tempWindow.drawAxesAndTitle();
tempWindow.show();
tempWindow.addPlot("temps", Draw.ORANGE);
summaryWindow = new Draw("summary");
summaryWindow.setCanvasSize(400, 400);
summaryWindow.setXscale(0, 400);
summaryWindow.setYscale(0, 400);
summaryWindow.enableDoubleBuffering();
}
public void run() {
while (true) {
try {
while (port.available()) {
switch (currentState) {
case waitMagic:
if (port.readByte() == '!') {
currentState = State.waitKey;
}
break;
case waitKey:
switch (port.readByte()) {
case (0x30) :
currentState = State.debug;
break;
case (0x31) :
currentState = State.error;
break;
case (0x32) :
currentState = State.timestamp;
break;
case (0x36) :
currentState = State.filTemp;
break;
case (0x37) :
currentState = State.pedometer;
break;
case (0x38) :
currentState = State.sleep;
break;
case (0x39) :
currentState = State.cx;
break;
case (0x3a) :
currentState = State.cy;
break;
case (0x3b) :
currentState = State.cz;
break;
case (0x3c) :
currentState = State.pedReset;
break;
case (0x3d) :
currentState = State.sleepReset;
break;
default :
System.out.println("!!!! ERROR IN KEY ZOMG !!!");
currentState = State.waitMagic;
}
break;
case debug:
System.out.print("Debug message: ");
int debugLength = 0;
debugLength += (port.readByte() & 0xff) << 8;
debugLength += port.readByte() & 0xff;
byte[] stringD = new byte[debugLength];
for (int i = 0; i < debugLength; i++) {
stringD[i] = port.readByte();
}
System.out.println(new String(stringD, StandardCharsets.UTF_8));
currentState = State.waitMagic;
break;
case error:
System.out.print("Error message: ");
int errorLength = 0;
errorLength += (port.readByte() & 0xff) << 8;
errorLength += port.readByte() & 0xff;
byte[] stringE = new byte[errorLength];
for (int i = 0; i < errorLength; i++) {
stringE[i] = port.readByte();
}
System.out.println(new String(stringE, StandardCharsets.UTF_8));
currentState = State.waitMagic;
break;
case timestamp:
System.out.print("Timestamp: ");
int time = 0;
time += ((port.readByte() & 0xff) << 24);
time += ((port.readByte() & 0xff) << 16);
time += ((port.readByte() & 0xff) << 8);
time += (port.readByte() & 0xff);
currentMillis = time;
System.out.println(time + " millis");
currentState = State.waitMagic;
break;
case filTemp:
System.out.print("Filtered temperature value: ");
int filtered = 0;
filtered += ((port.readByte() & 0xff) << 24);
filtered += ((port.readByte() & 0xff) << 16);
filtered += ((port.readByte() & 0xff) << 8);
filtered += (port.readByte() & 0xff);
currentTemp = Float.intBitsToFloat(filtered);
System.out.println(currentTemp + " C");
tempWindow.addDataPoint("temps", currentTemp);
tempWindow.plotData();
updateSummary();
currentState = State.waitMagic;
break;
case pedometer:
int steps = 0;
steps += ((port.readByte() & 0xff) << 8);
steps += (port.readByte() & 0xff);
currentStepCount = steps;
stepWindow.annotateLast("cz", 0, Integer.toString(currentStepCount));
System.out.println("Steps: " + steps);
currentState = State.waitMagic;
break;
case sleep:
System.out.print("Time asleep: ");
int sleepTime = 0;
sleepTime += ((port.readByte() & 0xff) << 24);
sleepTime += ((port.readByte() & 0xff) << 16);
sleepTime += ((port.readByte() & 0xff) << 8);
sleepTime += (port.readByte() & 0xff);
sleepWindow.addDataPoint("sleep time", sleepTime);
sleepWindow.plotData();
currentSleepTime = sleepTime;
System.out.println(sleepTime + " seconds");
currentState = State.waitMagic;
break;
case cx:
int cx = 0;
cx += ((port.readByte() & 0xff) << 24);
cx += ((port.readByte() & 0xff) << 16);
cx += ((port.readByte() & 0xff) << 8);
cx += (port.readByte() & 0xff);
System.out.println("X: " + Float.intBitsToFloat(cx));
stepWindow.addDataPoint("cx", Float.intBitsToFloat(cx));
currentState = State.waitMagic;
break;
case cy:
int cy = 0;
cy += ((port.readByte() & 0xff) << 24);
cy += ((port.readByte() & 0xff) << 16);
cy += ((port.readByte() & 0xff) << 8);
cy += (port.readByte() & 0xff);
System.out.println("Y: " + Float.intBitsToFloat(cy));
stepWindow.addDataPoint("cy", Float.intBitsToFloat(cy));
currentState = State.waitMagic;
break;
case cz:
int cz = 0;
cz += ((port.readByte() & 0xff) << 24);
cz += ((port.readByte() & 0xff) << 16);
cz += ((port.readByte() & 0xff) << 8);
cz += (port.readByte() & 0xff);
System.out.println("Z: " + Float.intBitsToFloat(cz));
stepWindow.addDataPoint("cz", Float.intBitsToFloat(cz));
stepWindow.plotData();
currentState = State.waitMagic;
break;
case pedReset:
stepWindow.currentFirstX = 0;
stepWindow.emptyPlots();
lastPedResetMillis = currentMillis - 1;
updateSummary();
currentState = State.waitMagic;
break;
case sleepReset:
sleepWindow.currentFirstX = 0;
sleepWindow.setYscale(0, 30, 5);
sleepWindow.emptyPlots();
updateSummary();
currentState = State.waitMagic;
break;
default:
System.out.println("!!!! ERROR IN VALUE ZOMG !!!");
currentState = State.waitMagic;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
private void updateSummary() {
double stepRate = 3600000*currentStepCount / (currentMillis - lastPedResetMillis);
summaryWindow.clear();
summaryWindow.setFont(SUM_TITLE);
summaryWindow.text(200, 350, "Data Summary");
summaryWindow.setFont(SUM_TEXT);
summaryWindow.textLeft(50, 275, "Step count: " + currentStepCount + " steps");
summaryWindow.textLeft(50, 200, "Step rate: " + String.format("%.0f", stepRate) + " steps per hour");
summaryWindow.textLeft(50, 125, "Sleep time: " + currentSleepTime + " seconds");
summaryWindow.textLeft(50, 50, "Temperature: " + String.format("%.2f", currentTemp) + " C");
summaryWindow.show();
}
public static void main(String[] args) {
Fitbit2 fitbit = new Fitbit2("COM3"); // Adjust this to be the right port for your machine
fitbit.run();
}
}
|
/*-
* -\-\-
* Spotify Styx Scheduler Service
* --
* Copyright (C) 2016 Spotify AB
* --
* 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.spotify.styx;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.spotify.styx.model.Workflow;
import com.spotify.styx.model.WorkflowId;
import java.util.Optional;
import java.util.concurrent.ConcurrentMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Simple in memory implementation of {@link WorkflowCache}.
*/
public class InMemWorkflowCache implements WorkflowCache {
private static final Logger LOG = LoggerFactory.getLogger(InMemWorkflowCache.class);
private final ConcurrentMap<WorkflowId, Workflow> workflowStore = Maps.newConcurrentMap();
@Override
public void store(Workflow workflow) {
LOG.debug("Adding to cache: {}", workflow);
workflowStore.put(workflow.id(), workflow);
}
@Override
public void remove(Workflow workflow) {
LOG.debug("Removing from cache: {}", workflow);
workflowStore.remove(workflow.id());
}
@Override
public Optional<Workflow> workflow(WorkflowId workflowId) {
return Optional.ofNullable(workflowStore.get(workflowId));
}
@Override
public ImmutableSet<Workflow> all() {
return ImmutableSet.copyOf(workflowStore.values());
}
}
|
package com.walkerwang.algorithm.bigcompany;
import java.util.LinkedList;
import java.util.Scanner;
/**
* 小明同学把1到n这n个数字按照一定的顺序放入了一个队列Q中。现在他对队列Q执行了如下程序:
while(!Q.empty()) //队列不空,执行循环
{
int x=Q.front(); //取出当前队头的值x
Q.pop(); //弹出当前队头
Q.push(x); //把x放入队尾
x = Q.front(); //取出这时候队头的值
printf("%d\n",x); //输出x
Q.pop(); //弹出这时候的队头
}
做取出队头的值操作的时候,并不弹出当前队头。
小明同学发现,这段程序恰好按顺序输出了1,2,3,...,n。现在小明想让你构造出原始的队列,你能做到吗?[注:原题样例第三行5有错,应该为3,以下已修正]
输入描述:
第一行一个整数T(T ≤ 100)表示数据组数,每组数据输入一个数n(1 ≤ n ≤ 100000),输入的所有n之和不超过200000。
输出描述:
对于每组数据,输出一行,表示原始的队列。数字之间用一个空格隔开,不要在行末输出多余的空格.
输入例子:
4
1
2
3
10
输出例子:
1
2 1
2 1 3
8 1 6 2 10 3 7 4 9 5
* @author walkerwang
*
*/
public class Netease03 {
public static LinkedList<Integer> linkedList;
public static int[] ret = new int[10000];
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int i = 1;
while(i <=n ) {
int x = in.nextInt();
get_arr(x);
i++;
}
}
public static void get_arr(int x) {
linkedList = new LinkedList<Integer>();
for (int i = 0; i < x; i++) {
linkedList.addLast(i + 1);
}
int sequence = 1;
while (!linkedList.isEmpty()) {
int xx = (int) linkedList.getFirst();
linkedList.removeFirst();
linkedList.addLast(xx);
xx = (int) linkedList.getFirst();
ret[xx - 1] = sequence;
linkedList.removeFirst();
sequence++;
}
for(int i = 0; i < x; i++) {
System.out.print(ret[i]);
if (i != x-1) {
System.out.print(" ");
} else {
System.out.print("\n");
}
}
}
}
|
package org.alienideology.jcord.internal.exception;
import org.alienideology.jcord.handle.oauth.Scope;
import java.util.Arrays;
/**
* ScopeException - When the identity try to access a resource outside of its scopes.
*
* @author AlienIdeology
*/
public class ScopeException extends Exception {
private Scope[] scopes;
public ScopeException(Scope... scopes) {
super("Missing scope(s): " + Arrays.toString(scopes));
this.scopes = scopes;
}
public ScopeException(String cause) {
super(cause);
this.scopes = null;
}
public Scope[] getMissingScopes() {
return scopes;
}
}
|
package api.service;
import api.model.Usuario;
import api.repository.AerogeradorRepository;
import api.arq.rest.CRUDService;
import api.arq.util.AutenticacaoUtil;
import api.model.Aerogerador;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class AerogeradorService extends CRUDService<Aerogerador> {
@Autowired
private AerogeradorRepository aerogeradorRepository;
AutenticacaoUtil autenticacaoUtil = new AutenticacaoUtil();
@Override
public void executarAntesDeSalvar(Aerogerador entidade) {
Optional<Usuario> usuarioAutenticado = autenticacaoUtil.getUsuarioAutenticado();
}
@Override
public void executarAposSalvar(Aerogerador entidade) {
}
@Override
public void executarAntesDeRemover(Aerogerador entidade) {
}
@Override
public void executarAposRemover(Aerogerador entidadePersistida) {
}
}
|
package io.github.leonkacowicz.tictactoe.ai;
import io.github.leonkacowicz.tictactoe.core.Board;
import io.github.leonkacowicz.tictactoe.core.CellState;
import io.github.leonkacowicz.tictactoe.core.Move;
import io.github.leonkacowicz.tictactoe.core.Player;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RandomPlayer implements Player {
@Override
public Move getNextMove(Board board) {
int size = board.size();
List<Integer> validMoves = new ArrayList<>();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (board.getCellState(i, j) == CellState.BLANK)
validMoves.add(i * size + j);
}
}
int intmove = validMoves.get(new Random().nextInt(validMoves.size()));
return new Move(intmove / size, intmove % size);
}
}
|
package chapter18;
import java.util.Scanner;
public class Exercise18_23 {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in);) {
System.out.println("Enter a binary number: ");
String bin = input.next();
int dec = bin2Dec(bin);
System.out.println("Decimal value of binary " + bin + " number is: " + dec);
}
}
public static int bin2Dec(String binaryString) {
if (binaryString.length() > 0)
return bin2Dec(binaryString, 0);
return Integer.parseInt(binaryString);
}
private static int bin2Dec(String binaryString, int power) {
String result = (Integer.parseInt(binaryString) * (int) Math.pow(2, power)) + "";
if (binaryString.length() > 1) {
int digit = Integer.parseInt(binaryString.charAt(binaryString.length() - 1) + "")
* (int) Math.pow(2, power);
result = (bin2Dec(binaryString.substring(0, (binaryString.length() - 1)), power + 1) + digit) + "";
}
return Integer.parseInt(result);
}
}
|
package largeassendingnumber;
public class Solutiontest {
public static void main(String [] args){
Solution s = new Solution();
int [] a = {1,3,8,2,6,4,5};
System.out.println(s.longest(a));
}
}
|
package com.charith.codility.PrimeAndCompositeNumbers.Flags;
public class Solution {
}
|
package com.tyss.cg.loanproject.controller;
import java.util.Scanner;
import com.tyss.cg.loanproject.services.ServicesImpl;
public class AdminController {
public static void main(String[] args) {
int again=1;
Scanner scanner = new Scanner(System.in);
ServicesImpl servicesImpl = new ServicesImpl();
int choice;
while(again==1) {
System.out.println("ADMIN operations:");
System.out.println(" 1> Display Admin details");
System.out.println(" 2> Add Admin details");
System.out.println(" 3> Delete Admin details");
System.out.println(" 4> Update Admin details");
System.out.println("Enter your choice: ");
choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
servicesImpl.displayAdmin();
break;
case 2:
servicesImpl.addAdmin();
break;
case 3:
servicesImpl.deleteAdmin();
break;
case 4:
servicesImpl.updateAdmin();
break;
default:
System.out.println("Wrong choice");
break;
}
System.out.println(" ");
System.out.println(" ");
System.out.println("try again?? {{{ yes (or) no }}}");
String tryagn = scanner.nextLine();
if (tryagn.toLowerCase().equals("yes")) {
again=1;
} else {
again=0;
}
}
System.out.println("application ended");
scanner.close();
}
}
|
package com.zilker.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.zilker.bean.User;
import com.zilker.constants.SQLConstants;
import com.zilker.util.DbConnect;
public class UserDAO {
private final static Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
public boolean registerUser(User user) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DbConnect.getConnection();
preparedStatement = connection.prepareStatement(SQLConstants.INSERT_PERSONAL_DETAILS);
preparedStatement.setString(1, user.getName());
preparedStatement.setString(2, user.getEmail());
preparedStatement.setString(3, user.getContact());
preparedStatement.setString(4, user.getRole());
preparedStatement.setString(5, user.getPassword());
preparedStatement.executeUpdate();
return true;
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, "Error in inserting personal details to DB.");
return false;
} finally {
DbConnect.closeConnection(connection, preparedStatement, resultSet);
}
}
public ArrayList<User> fetchDetails() {
String userName = "";
String mail = "";
String contact = "";
String role = "";
String password = "";
User object = null;
ArrayList<User> user = null;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
user = new ArrayList<User>();
connection = DbConnect.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM USER_DETAIL");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
userName = resultSet.getString(2);
mail = resultSet.getString(3);
contact = resultSet.getString(4);
role = resultSet.getString(5);
password = resultSet.getString(6);
object = new User(userName, mail, contact, role, password);
user.add(object);
}
return user;
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, "Error in validating login credentials from DB.");
return null;
}finally {
DbConnect.closeConnection(connection, preparedStatement, resultSet);
}
}
}
|
package com.zhouyi.business.core.model;
import java.io.Serializable;
import java.math.BigDecimal;
public class LedenCollectGCurrency implements Serializable {
private String wpbh;
private String hbzldm;
private BigDecimal hbmz;
private String jldw;
private static final long serialVersionUID = 1L;
public String getWpbh() {
return wpbh;
}
public void setWpbh(String wpbh) {
this.wpbh = wpbh;
}
public String getHbzldm() {
return hbzldm;
}
public void setHbzldm(String hbzldm) {
this.hbzldm = hbzldm;
}
public BigDecimal getHbmz() {
return hbmz;
}
public void setHbmz(BigDecimal hbmz) {
this.hbmz = hbmz;
}
public String getJldw() {
return jldw;
}
public void setJldw(String jldw) {
this.jldw = jldw;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", wpbh=").append(wpbh);
sb.append(", hbzldm=").append(hbzldm);
sb.append(", hbmz=").append(hbmz);
sb.append(", jldw=").append(jldw);
sb.append("]");
return sb.toString();
}
}
|
package com.mrice.txl.appthree.ui.me;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mrice.txl.appthree.R;
import com.mrice.txl.appthree.adapter.HomeAdapter;
import com.mrice.txl.appthree.bean.MultipleItem;
import com.mrice.txl.appthree.ui.home.PubData;
import com.mrice.txl.appthree.view.webview.WebViewActivity;
import java.util.List;
/**
* Created by Mr on 2017/12/1.
*/
public class KJFragment2 extends Fragment {
private List<MultipleItem> datas;
private HomeAdapter adapter;
private RecyclerView recyclerView;
public KJFragment2() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.layout_kj2, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initView();
}
private void initView() {
recyclerView = (RecyclerView) getActivity().findViewById(R.id.mlv);
datas = PubData.getPageData2();
adapter = new HomeAdapter(datas);
//创建布局管理
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
//条目点击事件
adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
Intent i = new Intent(getActivity(), KJDetailsActivity.class);
if ("双色球".equals(datas.get(position).getTitle())) {
i.putExtra("position", 1);
} else if ("七乐彩".equals(datas.get(position).getTitle())) {
i.putExtra("position", 2);
} else if ("大乐透".equals(datas.get(position).getTitle())) {
i.putExtra("position", 3);
} else if ("七星彩".equals(datas.get(position).getTitle())) {
i.putExtra("position", 4);
} else if ("排列三".equals(datas.get(position).getTitle())) {
i.putExtra("position", 5);
} else if ("排列五".equals(datas.get(position).getTitle())) {
i.putExtra("position", 6);
} else if ("排列五".equals(datas.get(position).getTitle())) {
i.putExtra("position", 7);
} else if ("排列五".equals(datas.get(position).getTitle())) {
i.putExtra("position", 8);
}
startActivity(i);
}
});
}
}
|
import de.btobastian.sdcf4j.Command;
import de.btobastian.sdcf4j.CommandExecutor;
import sx.blah.discord.handle.obj.IMessage;
/**Command for saying the current player list and queue size for the gather object associated with this channel. Must be used in command channel.
* @author cameron
* @see #GatherQueueObject
* @see GatherObject#queueString()
*/
public class CommandList implements CommandExecutor
{
/**The function that is called when the command is used
* @param message
* @see https://github.com/BtoBastian/sdcf4j
* @see #CommandList
*/
@Command(aliases = {"!list", "!queue"}, description = "Check the current player list")
public void onCommand(IMessage message)
{
GatherObject gather = DiscordBot.getGatherObjectForChannel(message.getChannel());
if(gather==null) return;
String currentQueue = gather.queueString();
if(!currentQueue.isEmpty())
{
DiscordBot.sendMessage(gather.getCommandChannel(), "Current **queue** ("+gather.numPlayersInQueue()+"/"+gather.getMaxQueueSize()+"): "+currentQueue);
return;
}
else
{
DiscordBot.sendMessage(gather.getCommandChannel(), "Queue is **empty**");
return;
}
}
}
|
package ru.vise.rest;
import com.google.gson.Gson;
import javax.ws.rs.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
@Path("/formbuilder")
public class FormBuilder {
@GET
@Path("/form")
public String BuildForm(@QueryParam("formname") String formname) {
// return new Gson().toJson(BuildMapList());
return readFromJson("/Users/maksimovvladislav/IdeaProjects/ViseFrontEnd/forms/SimpleEgo.json");
// return "";
}
private String readFromJson(String fileName) {
// String fileName = "D:\\Repository\\java vise\\ViseFrontEnd\\forms\\SimpleEgo.json";
//String fileName = "SimpleEgo.json";
File file = new File(fileName);
try {
Scanner scanner = new Scanner(file);
String json;
json = scanner.useDelimiter("//advcdgv").next();
return json;
} catch (FileNotFoundException e) {
return "File not found";
}
}
private List<Map<String, String>> BuildMapList() {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map;
// Create capital node
map = new HashMap<String, String>();
map.put("name", "capital");
map.put("id", "initCapital");
map.put("attr_id", "1");
map.put("placeholder", "Initial capital...");
map.put("title", "Initial Capital");
map.put("type", "text");
map.put("value", "10");
map.put("label", "Initial Capital");
list.add(map);
// Create mu node
map = new HashMap<String, String>();
map.put("name", "mu");
map.put("id", "mu");
map.put("attr_id", "2");
map.put("placeholder", "Mu...");
map.put("title", "Mu");
map.put("type", "text");
map.put("value", "0.1");
map.put("label", "Mu");
list.add(map);
// Create select variation node
map = new HashMap<String, String>();
map.put("name", "var");
map.put("id", "var");
map.put("attr_id", "9");
map.put("title", "Variation");
map.put("label", "Variation");
map.put("options", "mu,sigma");
map.put("inputType", "select");
list.add(map);
return list;
}
}
|
package com.tencent.mm.plugin.facedetect.model;
import com.tencent.mm.model.at;
public final class e {
private static long iNr = -1;
private static long iNs = -1;
private static float iNt = -1.0f;
public static void df(long j) {
iNr = j;
}
public static boolean aJE() {
return Boolean.parseBoolean(at.dBv.I("last_login_face_use_debug_mode", "false"));
}
public static boolean aJF() {
return Boolean.parseBoolean(at.dBv.I("last_login_face_is_force_upload_face", "false"));
}
public static boolean aJG() {
return Boolean.parseBoolean(at.dBv.I("last_login_face_save_correct_debug_mode", "false"));
}
public static boolean aJH() {
return Boolean.parseBoolean(at.dBv.I("last_login_face_save_final_debug_mode", "false"));
}
public static boolean aJI() {
return Boolean.parseBoolean(at.dBv.I("last_login_face_save_lip_reading", "false"));
}
public static boolean aJJ() {
return Boolean.parseBoolean(at.dBv.I("last_login_face_save_final_voice", "false"));
}
public static void eD(boolean z) {
at.dBv.T("last_login_face_use_debug_mode", String.valueOf(z));
}
public static void eE(boolean z) {
at.dBv.T("last_login_face_save_correct_debug_mode", String.valueOf(z));
}
public static void eF(boolean z) {
at.dBv.T("last_login_face_save_final_debug_mode", String.valueOf(z));
}
public static void eG(boolean z) {
at.dBv.T("last_login_face_save_lip_reading", String.valueOf(z));
}
public static void eH(boolean z) {
at.dBv.T("last_login_face_save_final_voice", String.valueOf(z));
}
public static void eI(boolean z) {
at.dBv.T("last_login_face_is_force_upload_face", String.valueOf(z));
}
}
|
package com.kh.efp.Search.controller;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
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.bind.annotation.RequestParam;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.kh.efp.Search.model.service.SearchService;
import com.kh.efp.Search.model.vo.Search;
import com.twitter.penguin.korean.KoreanPosJava;
import com.twitter.penguin.korean.KoreanTokenJava;
import com.twitter.penguin.korean.TwitterKoreanProcessorJava;
import com.twitter.penguin.korean.phrase_extractor.KoreanPhraseExtractor;
import com.twitter.penguin.korean.tokenizer.KoreanTokenizer;
import scala.collection.Seq;
@Controller
public class SearchController {
@Autowired SearchService seachservice ;
@RequestMapping(value="/searchResult.search")
public String searchResultFoward(String value, Model model){
//필터한 결과를 list로 전달
ArrayList<String> list = filterBox(value);
// band = 밴드 결과 , contents = 게시글 검색결과
HashMap<String, ArrayList<Search>> searchResult = new HashMap<String, ArrayList<Search>>();
//만약 검색한 값들이 없다면 값 비움
if(list.size() != 0){
searchResult = seachservice.selectSearchAll(list);
}else{
searchResult.put("band", new ArrayList<Search>());
searchResult.put("contents", new ArrayList<Search>());
}
/*System.out.println("조회된 밴드 - ");
for(Search s : searchResult.get("band")){
System.out.println(s);
}
System.out.println();
System.out.println("조회된 게시글 - ");
for(Search s : searchResult.get("contents")){
System.out.println(s);
}*/
model.addAttribute("result", value); //검색한 값
model.addAttribute("band", searchResult.get("band")); //밴드 검색결과
model.addAttribute("contents", searchResult.get("contents")); //게시글 검색결과
return "searchPage/searchResult";
}
//스크롤시 밴드 리스트 5개씩 생성
@RequestMapping(value="/newBandList.search", method=RequestMethod.GET)
public void newBandList(@RequestParam("page") String page, @RequestParam("value") String value, HttpServletResponse res){
//검색 결과 정리후 반환
ArrayList<String> list = filterBox(value);
int pageNum = Integer.parseInt(page);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("bandList", list);
map.put("startPage", pageNum);
map.put("endPage", pageNum+4);
ArrayList<Search> fiveBandResult = seachservice.selectFiveBand(map);
String jsons = new Gson().toJson(fiveBandResult);
res.setCharacterEncoding("UTF-8");
try {
res.getWriter().print(jsons);
} catch (IOException e) {
e.printStackTrace();
}
}
//넘어온 검색할 값을 정리후 반환
public ArrayList<String> filterBox(String value){
//스크립트 인젝션을 방지할 < or > 제거
String text = value.replaceAll("<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?(\\s)*(/)?>", "");
CharSequence normalized = TwitterKoreanProcessorJava.normalize(text);
Seq<KoreanTokenizer.KoreanToken> tokens = TwitterKoreanProcessorJava.tokenize(normalized);
int textLength = TwitterKoreanProcessorJava.tokensToJavaStringList(tokens).size();
List<KoreanTokenJava> n = TwitterKoreanProcessorJava.tokensToJavaKoreanTokenList(tokens);
List<KoreanPhraseExtractor.KoreanPhrase> phrases = TwitterKoreanProcessorJava.extractPhrases(tokens, true, true);
//모든 검색문을 공백단위로 분리해서 리스트에 넣는다
ArrayList<String> list = new ArrayList<String>();
String[] arr = text.split(" ");
//검색할 리스트중 비어있는 공백은 전부 제거
for(int i=0; i<arr.length; i++){
if(arr[i].length() != 0 || !arr[i].isEmpty()){
list.add(arr[i]);
}
}
//그후 다시 정규화 후 분할하여 각각 리스트에 넣는다
for(int i=0; i < textLength ; i++){
if(n.get(i).getPos().equals(KoreanPosJava.Noun)){
list.add(n.get(i).getText());
}else if(n.get(i).getPos().equals(KoreanPosJava.Hashtag)){
list.add(n.get(i).getText().substring(1));
}
}
//또 구문단위로도 넣는다.
for(int i=0; i < phrases.size() ; i++)
list.add(phrases.get(i).text());
return list;
}
//더 많은 게시글보기시 forward
@RequestMapping(value="/searchMorePost.search")
public String searchMorePostFoward(String value, Model model){
//필터한 결과를 list로 전달
ArrayList<String> list = filterBox(value);
// band = 밴드 결과 , contents = 게시글 검색결과
ArrayList<Search> searchResult = null;
//만약 검색한 값들이 없다면 값 비움
if(list.size() != 0){
searchResult = seachservice.selectSearchMorePost(list);
}
model.addAttribute("result", value); //검색한 값
model.addAttribute("contents", searchResult); //게시글 검색결과
return "searchPage/searchMorePost";
}
//스크롤시 게시글 리스트 5개씩 생성
@RequestMapping(value="/newContentsList.search", method=RequestMethod.GET)
public void newContentsList(@RequestParam("page") String page, @RequestParam("value") String value, HttpServletResponse res){
//검색 결과 정리후 반환
ArrayList<String> list = filterBox(value);
int pageNum = Integer.parseInt(page);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("contentsList", list);
map.put("startPage", pageNum);
map.put("endPage", pageNum+4);
ArrayList<Search> fiveContentsResult = seachservice.selectFiveContents(map);
String jsons = new Gson().toJson(fiveContentsResult);
res.setCharacterEncoding("UTF-8");
try {
res.getWriter().print(jsons);
} catch (IOException e) {
e.printStackTrace();
}
}
//자동 완성 ajax
@RequestMapping(value="/autoComplete.search", method=RequestMethod.GET)
public void autoComplet(@RequestParam("term") String term, HttpServletResponse res){
ArrayList<String> list = filterBox(term);
ArrayList<String> autoList = seachservice.selectAutoList(list);
if(autoList.size() == 0){
autoList.add("# 밴드검색 결과없음");
}
try {
res.setContentType("application/json");
res.setCharacterEncoding("UTF-8");
res.getWriter().print(new Gson().toJson(autoList));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.ev.srv.demopai.api;
import com.evo.api.springboot.exception.ApiException;
import com.ev.srv.demopai.model.Segmentation;
import com.ev.srv.demopai.service.SegmentationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;
import com.evo.api.springboot.exception.ApiException;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.*;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/api")
public class SegmentationController {
@Autowired
private SegmentationService service;
@ApiOperation(value = "Score for the last three closed months.", nickname = "getMonthlySegmentation", notes = "", response = Segmentation.class, responseContainer = "List", tags={ "segmentation", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = Segmentation.class, responseContainer = "List") })
@RequestMapping(value = "/segmentation",
produces = { "application/json" },
method = RequestMethod.GET)
public ResponseEntity<List<Segmentation>> getMonthlySegmentation( @ApiParam(value = "Entity code", required = true) @RequestParam(value = "codigoEntidad", required = true) String codigoEntidad, @ApiParam(value = "User BE", required = true) @RequestParam(value = "usuarioBE", required = true) String usuarioBE, @ApiParam(value = "Contract BE", required = true) @RequestParam(value = "acuerdoBE", required = true) String acuerdoBE, @ApiParam(value = "Account where the score is assigned.", required = true) @RequestParam(value = "associatedAccountId", required = true) String associatedAccountId) throws ApiException{
return new ResponseEntity<List<Segmentation>>(service.getMonthlySegmentation(codigoEntidad, usuarioBE, acuerdoBE, associatedAccountId), HttpStatus.NOT_IMPLEMENTED);
}
}
|
/**
*
*/
package com.yougou.merchant.api.supplier.service;
import java.util.List;
import com.yougou.merchant.api.supplier.vo.ImageJmsVo;
import com.yougou.merchant.api.supplier.vo.TaobaoImage;
/**
* 招商图片处理相关服务(供商家中心使用)
*
* @author huang.tao
*
*/
public interface IMerchantImageService {
void addImageJms(ImageJmsVo message);
/**
* 查询jms消息列表
*
* @param message
* @return
*/
List<ImageJmsVo> queryImageJmsList(ImageJmsVo message);
List<ImageJmsVo> queryImageJmsList(ImageJmsVo message, Integer pageNo, Integer pageSize);
Integer queryImageJmsCount(ImageJmsVo message);
/**
* 修改jms消息的状态
*
* @param message
*/
void updateImageJmsStatus(ImageJmsVo message);
List<ImageJmsVo> queryImageJmsListByIds(String[] ids) throws Exception;
List<ImageJmsVo> getUntreated() throws Exception;
/**
* 批量置为作废
* @param ids
* @throws Exception
*/
void updateImageJmsStatusInvalid(String[] ids) throws Exception;
/**
* 删除7天一起的消息
* @throws Exception
*/
void delMessage() throws Exception;
/**
* 更新淘宝图片转换为优购的地址
* @param imgId
* @param imgUrl
*/
void updateTaobaoItemImgURL(Long numIid,String oldImgUrl,String newImgUrl,String thumbnailURL);
/**
* 更新淘宝图片转换为优购的描述字符串
* @param numIid
* @param desc
*/
void updateTaobaoImgDesc(Long numIid,String desc,String defaultPic);
/**
* 更新淘宝图片角度图
* @param numIid
* @param desc
*/
void updateTaobaoItemImgAngle(Long numIid,String anglePic);
/**
* 批量更新淘宝图片转换为优购的地址
* @param taobaoImages
*/
void updateTaobaoItemImgURLBatch(List<TaobaoImage> taobaoImages);
}
|
package com.example.trending;
import java.util.List;
public interface ParentView {
void success(List<ListBean> listBeans);
void error(String error);
}
|
package arrayJava;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayCopyOfMethod {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int a[] = new int [5];
System.out.println("Enter Array");
for (int i = 0; i < 5; i++) {
a[i] = sc.nextInt();
}
System.out.println("Copy of aaray a into b ");
int b[] = Arrays.copyOf(a, 5);
for (int i = 0; i < 5; i++) {
System.out.println(b[i]);
}
}
}
|
package br.ufc.ong.model;
public enum Status {
PENDENTE("Ocorrencia pendente"),
CONFIRMADO("Ocorrencia confirmada"),
CANCELADO("Ocorrencia cancelada"),
ADOTADO("Animal da ocorrencia adotado"),
ADOCAO("Animal da Ocorrencia apto para a adoção");
private String descricao;
Status(String descricao){
this.descricao = descricao;
}
public String getNome() {
return descricao;
}
}
|
package com.tencent.mm.modelsimple;
import android.content.Intent;
import com.tencent.mm.modelsimple.k.1.1;
import com.tencent.mm.plugin.account.ui.DisasterUI;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.x;
class k$1$1$1 implements Runnable {
final /* synthetic */ 1 efu;
k$1$1$1(1 1) {
this.efu = 1;
}
public final void run() {
x.i("MicroMsg.NetSceneGetDisasterInfo", "summerdize NetSceneGetDisasterInfo onGYNetEnd manualauthSucc showtony[%b]", new Object[]{Boolean.valueOf(ad.chV())});
Intent intent = new Intent();
intent.putExtra("key_disaster_content", this.efu.efr);
intent.putExtra("key_disaster_url", this.efu.efs);
intent.setClass(ad.getContext(), DisasterUI.class).addFlags(268435456);
ad.getContext().startActivity(intent);
}
}
|
package com.research.hadoop.join.reduce;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
import java.util.Iterator;
/**
* @fileName: JoinReducer.java
* @description: JoinReducer.java类说明
* @author: by echo huang
* @date: 2020-03-27 11:45
*/
public class JoinReducer extends Reducer<TextPair, Text, IntWritable, Text> {
@Override
protected void reduce(TextPair key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
Iterator<Text> iterator = values.iterator();
Text stationName = new Text(iterator.next());
while (iterator.hasNext()) {
Text record = iterator.next();
Text outValue = new Text(stationName.toString() + "\t" + record);
context.write(new IntWritable(key.getId()), outValue);
}
}
}
|
package de.raidcraft.skillsandeffects.pvp.skills.physical;
import de.raidcraft.skills.api.combat.EffectType;
import de.raidcraft.skills.api.combat.action.Attack;
import de.raidcraft.skills.api.exceptions.CombatException;
import de.raidcraft.skills.api.hero.Hero;
import de.raidcraft.skills.api.persistance.SkillProperties;
import de.raidcraft.skills.api.profession.Profession;
import de.raidcraft.skills.api.skill.AbstractSkill;
import de.raidcraft.skills.api.skill.SkillInformation;
import de.raidcraft.skills.api.trigger.TriggerHandler;
import de.raidcraft.skills.api.trigger.TriggerPriority;
import de.raidcraft.skills.api.trigger.Triggered;
import de.raidcraft.skills.tables.THeroSkill;
import de.raidcraft.skills.trigger.EntityDeathTrigger;
import de.raidcraft.skills.util.ConfigUtil;
import de.raidcraft.skillsandeffects.pvp.effects.misc.DeathStrikeEffect;
import org.bukkit.configuration.ConfigurationSection;
/**
* @author Silthus
*/
@SkillInformation(
name = "Death Strike",
description = "Heilt den Benutzter um einen Teil der Leben. Kann nur nach einem Todestoß genutzt werden.",
types = {EffectType.PHYSICAL, EffectType.DAMAGING, EffectType.HEALING},
queuedAttack = true
)
public class DeathStrike extends AbstractSkill implements Triggered {
private ConfigurationSection healAmount;
public DeathStrike(Hero hero, SkillProperties data, Profession profession, THeroSkill database) {
super(hero, data, profession, database);
}
@Override
public void load(ConfigurationSection data) {
healAmount = data.getConfigurationSection("heal-amount");
}
public int getHealAmount() {
return (int) ConfigUtil.getTotalValue(this, healAmount);
}
@TriggerHandler(ignoreCancelled = true, priority = TriggerPriority.MONITOR, filterTargets = false)
public void onEntityDeath(EntityDeathTrigger trigger) {
Attack attack = trigger.getEvent().getCharacter().getLastDamageCause();
if (attack != null && attack.isAttacker(getHolder()) && canUseAbility()) {
try {
addEffect(DeathStrikeEffect.class);
} catch (CombatException ignored) {
// ignored
}
}
}
}
|
package plane_Owner;
import planes.CivilAircraft;
import planes.CivilAircraftType;
import planes.Plane;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
public class Company implements Corporation {
private String name;
private List<Plane> airplanes;
private String id;
public Company(String name) {
Objects.requireNonNull(name, " Company name can not be NULL");
this.name = name;
airplanes = new ArrayList<>();
id = UUID.randomUUID().toString();
}
public String getName() {
return name;
}
public List<Plane> getAirplanes() {
return airplanes;
}
public void addPlane(CivilAircraft plane) {
if (plane.getCivilType().equals(CivilAircraftType.GENERAL)) {
throw new IllegalArgumentException("Not possible to add General type Civil Aircraft planes to company. Only Commercial airplanes are allowed");
}
airplanes.add(plane);
}
public String getId() {
return id;
}
@Override
public String toString() {
return "Company{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Company)) return false;
Company company = (Company) o;
return getName().equals(company.getName()) && (getAirplanes() != null ? getAirplanes().equals(company.getAirplanes()) : company.getAirplanes() == null) && getId().equals(company.getId());
}
@Override
public int hashCode() {
int result = getName().hashCode();
result = 31 * result + (getAirplanes() != null ? getAirplanes().hashCode() : 0);
result = 31 * result + getId().hashCode();
return result;
}
}
|
package misc.exceptions;
public class EmptyContainerException extends RuntimeException {
public EmptyContainerException() {
super();
}
public EmptyContainerException(String message) {
super(message);
}
public EmptyContainerException(String message, Throwable cause) {
super(message, cause);
}
public EmptyContainerException(Throwable cause) {
super(cause);
}
}
|
package practice.test;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import practice.entity.College;
import practice.entity.Student;
import practice.entity.University;
import practice.service.StudentService;
public class TestStudents {
@Test
public void testAscending() {
List<Student> students = new ArrayList<>();
University university = new University(generateRandomString(6) + " " + generateRandomString(4));
String collegeCode = generateRandomString(3);
String collegeName = generateRandomString(6) + " " + generateRandomString(4) + " " + generateRandomString(5)
+ " " + generateRandomString(4);
College college = new College(collegeCode, collegeName, university);
String studentName = generateRandomString(6) + " " + generateRandomString(4);
Student st = new Student(studentName, college);
students.add(st);
StudentService service = new StudentService();
students = service.sortAscending(students);
for (Student s : students) {
System.out.println(s.toString());
}
}
@Test
public void testAscending1() {
String[] studentName = new String[5];
String[] collegeName = new String[5];
String[] collegeCode = new String[5];
String[] universityName = new String[5];
List<Student> students = new ArrayList<>();
studentName[0] = "golu";
studentName[1] = "utkarsh";
studentName[2] = "aman";
studentName[3] = "aman";
studentName[4] = "aman";
collegeName[0] = "oist";
collegeName[1] = "lnct";
collegeName[2] = "tit";
collegeName[3] = "tit";
collegeName[4] = "rkdf";
collegeCode[0] = "0105";
collegeCode[1] = "0101";
collegeCode[2] = "0102";
collegeCode[3] = "0109";
collegeCode[4] = "0104";
universityName[0] = "rgpv";
universityName[1] = "uit";
universityName[2] = "barkatullah";
universityName[3] = "harward";
universityName[4] = "magadh";
for (int i = 0; i < 5; i++) {
University universities = new University(universityName[i]);
College colleges = new College(collegeCode[i], collegeName[i], universities);
Student studds = new Student(studentName[i], colleges);
students.add(studds);
}
StudentService service = new StudentService();
students = service.sortAscending(students);
for (Student s : students) {
System.out.println(s.toString());
}
}
@Test
public void testDescending() {
String[] studentName = new String[5];
String[] collegeName = new String[5];
String[] collegeCode = new String[5];
String[] universityName = new String[5];
List<Student> students = new ArrayList<>();
studentName[0] = "golu";
studentName[1] = "utkarsh";
studentName[2] = "aman";
studentName[3] = "aman";
studentName[4] = "lincon";
collegeName[0] = "oist";
collegeName[1] = "lnct";
collegeName[2] = "tit";
collegeName[3] = "truba";
collegeName[4] = "rkdf";
collegeCode[0] = "0105";
collegeCode[1] = "0101";
collegeCode[2] = "0109";
collegeCode[3] = "0102";
collegeCode[4] = "0104";
universityName[0] = "rgpv";
universityName[1] = "uit";
universityName[2] = "barkatullah";
universityName[3] = "harward";
universityName[4] = "magadh";
for (int i = 0; i < 5; i++) {
University universities = new University(universityName[i]);
College colleges = new College(collegeCode[i], collegeName[i], universities);
Student studds = new Student(studentName[i], colleges);
students.add(studds);
}
StudentService service = new StudentService();
students = service.sortDescending(students);
for (Student s : students) {
System.out.println(s.toString());
}
}
private String generateRandomString(int size) {
String str = "";
double random = Math.random();
String sample = "abcdefghijklmnopqrstuvwxyz";
String sampleCapital = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i = (int) (random * sampleCapital.length()); // TYPECASTING
str += sampleCapital.charAt(i);
for (int x = 0; x < size - 1; x++) {
random = Math.random();
int index = (int) (random * sample.length()); // TYPECASTING
str += sample.charAt(index);
}
return str;
}
}
|
package com.tencent.mm.plugin.setting.ui.setting;
import android.content.Intent;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class SettingDeleteAccountInputPassUI$2 implements OnMenuItemClickListener {
final /* synthetic */ SettingDeleteAccountInputPassUI mQM;
SettingDeleteAccountInputPassUI$2(SettingDeleteAccountInputPassUI settingDeleteAccountInputPassUI) {
this.mQM = settingDeleteAccountInputPassUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
this.mQM.YC();
this.mQM.startActivity(new Intent(this.mQM, SettingDeleteAccountUI.class));
return true;
}
}
|
/**
* Generated classes for the example based on the EURent scenario published by the EU business rule conference http://www.eurobizrules.org.
*/
package example.nz.org.take.compiler.eurent.generated;
|
/*
* This software is licensed under the MIT License
* https://github.com/GStefanowich/MC-Server-Protection
*
* Copyright (c) 2019 Gregory Stefanowich
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* 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 OR COPYRIGHT HOLDERS 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.
*/
package net.theelm.sewingmachine.chat.commands;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.command.CommandRegistryAccess;
import net.minecraft.command.argument.EntityArgumentType;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.theelm.sewingmachine.base.ServerCore;
import net.theelm.sewingmachine.chat.enums.ChatRooms;
import net.theelm.sewingmachine.chat.interfaces.PlayerChat;
import net.theelm.sewingmachine.chat.utilities.ChatRoomUtilities;
import net.theelm.sewingmachine.commands.abstraction.SewCommand;
import net.theelm.sewingmachine.objects.MessageRegion;
import net.theelm.sewingmachine.utilities.CommandUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
/**
* Created on Mar 18 2021 at 1:07 PM.
* By greg in SewingMachineMod
*/
public final class TagUserCommand implements SewCommand {
@Override
public void register(@NotNull CommandDispatcher<ServerCommandSource> dispatcher, @NotNull CommandRegistryAccess registry) {
CommandUtils.register(dispatcher, "@", "tag user", builder -> builder
.then(CommandManager.argument("player", EntityArgumentType.player())
.then(CommandManager.argument("message", StringArgumentType.greedyString())
.executes(this::tagPlayerMessage)
)
.executes(this::tagPlayer)
)
);
}
private int tagPlayer(@NotNull CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
return this.sendTaggedMessage(
context,
""
);
}
private int tagPlayerMessage(@NotNull CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
return this.sendTaggedMessage(
context,
StringArgumentType.getString(context, "message")
);
}
private int sendTaggedMessage(@NotNull CommandContext<ServerCommandSource> context, @NotNull String text) throws CommandSyntaxException {
ServerCommandSource source = context.getSource();
ServerPlayerEntity from = source.getPlayerOrThrow();
ServerPlayerEntity to = EntityArgumentType.getPlayer(context, "player");
// The chatroom to send the message in
MessageRegion room = ((PlayerChat)from).getChatRoom();
return Command.SINGLE_SUCCESS;
}
}
|
package mainDemo;
import javax.persistence.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import entity.Course;
import entity.Instructor;
import entity.InstructorDetail;
public class EagarLazyDemo {
public static void main(String[] args) {
//create session factory
SessionFactory factory = new Configuration()
.configure()
.addAnnotatedClass(Instructor.class)
.addAnnotatedClass(InstructorDetail.class)
.addAnnotatedClass(Course.class)
.buildSessionFactory();
//create session
Session session = factory.getCurrentSession();
//insert in to database using save()
try {
//start a transaction
session.beginTransaction();
//get the instructor from database using getter - option1
Instructor tempInstructor = session.get(Instructor.class, 13);
System.out.println("### instructor : "+tempInstructor);
System.out.println("### courses : "+tempInstructor.getCourses());
//option-2 using HQL
// org.hibernate.query.Query<Instructor> query = session.createQuery("select i from Instructor i join fetch i.courses where i.id=:p_instructorId", Instructor.class);
// query.setParameter("p_instructorId", 13);
// Instructor tempIns= query.getSingleResult();
// System.out.println("instructor using HQL "+tempIns);
//commit transaction
session.getTransaction().commit();
System.out.println("### Done.............");
} finally {
session.close();
factory.close();
}
}
}
|
package com.inspectorpi.inspectorpicontroller02;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.inspectorpi.inspectorpicontroller02.Connections.SensorsThread;
import com.inspectorpi.inspectorpicontroller02.Message.MessageReceive;
import com.inspectorpi.inspectorpicontroller02.Message.MessageResponse;
import com.inspectorpi.inspectorpicontroller02.queue.ProcessQueue;
import com.inspectorpi.inspectorpicontroller02.queue.ReceivingQueue;
import com.inspectorpi.inspectorpicontroller02.queue.SubmissionQueue;
import com.inspectorpi.inspectorpicontroller02.Connections.MessageConnection;
import com.inspectorpi.inspectorpicontroller02.Connections.RemoteWebcamRunnable;
import org.json.JSONObject;
public class RunningActivity extends AppCompatActivity{
RelativeLayout layout_joystick;
JoyStickClass js;
public SurfaceView mV;
RemoteWebcamRunnable ct;
Thread tWebcam;
Thread tClient;
Thread tProcessing;
TextView IRFront;
TextView IRLeft;
TextView IRRight;
SensorsThread t_sens;
volatile String sensorsString = "No data";
private boolean cloud;
SubmissionQueue submissionQueue;
ReceivingQueue receivingQueue;
private String serverIpAddress;
private int serverPort = 8888;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_running_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.serverIpAddress = getIntent().getExtras().getString("ip");
this.cloud = getIntent().getExtras().getBoolean("cloud");
layout_joystick = (RelativeLayout)findViewById(R.id.layout_joystick);
this.IRFront = (TextView) findViewById(R.id.textViewIRFront);
this.IRLeft = (TextView) findViewById(R.id.textViewIRLeft);
this.IRRight = (TextView) findViewById(R.id.textViewIRRight);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
mV = (SurfaceView)this.findViewById(R.id.surface);
ct = new RemoteWebcamRunnable(this,this.serverIpAddress,mV);
tWebcam = new Thread(ct);
submissionQueue = new SubmissionQueue();
receivingQueue = new ReceivingQueue();
t_sens = new SensorsThread(this.sensorsString, cloud);
t_sens.start();
tProcessing = new Thread(new ProcessQueue(receivingQueue,submissionQueue,tWebcam,t_sens,IRFront,IRLeft,IRRight));
MessageConnection myClient = new MessageConnection(serverIpAddress, serverPort,receivingQueue,submissionQueue);
tClient = new Thread(myClient);
tClient.start();
tProcessing.start();
js = new JoyStickClass(getApplicationContext()
, layout_joystick, R.drawable.image_button);
js.setStickSize(150, 150);
js.setLayoutSize(500, 500);
js.setLayoutAlpha(150);
js.setStickAlpha(100);
js.setOffset(90);
js.setMinimumDistance(50);
layout_joystick.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
try {
onTouchJoystick(arg0, arg1);
} catch (InterruptedException e) {
return false;
}
return true;
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, t_sens.getDataSensors(), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
try {
this.submissionQueue.putElement(MessageResponse.CAM_STOP);
this.submissionQueue.putElement(MessageResponse.GEN_EXIT);
} catch (InterruptedException e) {
e.printStackTrace();
}
super.onDestroy();
this.t_sens.interrupt();
this.tWebcam.interrupt();
this.tClient.interrupt();
this.tProcessing.interrupt();
}
protected void onTouchJoystick(View arg0, MotionEvent arg1) throws InterruptedException {
js.drawStick(arg1);
if (arg1.getAction() == MotionEvent.ACTION_DOWN
|| arg1.getAction() == MotionEvent.ACTION_MOVE) {
int direction = js.get8Direction();
if (direction == JoyStickClass.STICK_UP) {
this.submissionQueue.offerElement(MessageResponse.MOT_UP);
} else if (direction == JoyStickClass.STICK_UPRIGHT) {
this.submissionQueue.offerElement(MessageResponse.MOT_UP_RIGHT);
} else if (direction == JoyStickClass.STICK_RIGHT) {
this.submissionQueue.offerElement(MessageResponse.MOT_RIGHT);
} else if (direction == JoyStickClass.STICK_DOWNRIGHT) {
this.submissionQueue.offerElement(MessageResponse.MOT_DOWN_RIGHT);
} else if (direction == JoyStickClass.STICK_DOWN) {
this.submissionQueue.offerElement(MessageResponse.MOT_DOWN);
} else if (direction == JoyStickClass.STICK_DOWNLEFT) {
this.submissionQueue.offerElement(MessageResponse.MOT_DOWN_LEFT);
} else if (direction == JoyStickClass.STICK_LEFT) {
this.submissionQueue.offerElement(MessageResponse.MOT_LEFT);
} else if (direction == JoyStickClass.STICK_UPLEFT) {
this.submissionQueue.offerElement(MessageResponse.MOT_UP_LEFT);
} else if (direction == JoyStickClass.STICK_NONE){
}
} else if (arg1.getAction() == MotionEvent.ACTION_UP) {
this.submissionQueue.offerElement(MessageResponse.MOT_STOP);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.