text
stringlengths
10
2.72M
/* * LumaQQ - Java QQ Client * * Copyright (C) 2004 luma <stubma@163.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.tsinghua.lumaqq.ui.wizard.search; import static edu.tsinghua.lumaqq.resource.Messages.*; import static edu.tsinghua.lumaqq.ui.wizard.search.SearchWizardModel.*; import java.util.List; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.INewWizard; import org.eclipse.ui.IWorkbench; import edu.tsinghua.lumaqq.events.BaseQQListener; import edu.tsinghua.lumaqq.qq.QQ; import edu.tsinghua.lumaqq.qq.beans.AdvancedUserInfo; import edu.tsinghua.lumaqq.qq.beans.ClusterInfo; import edu.tsinghua.lumaqq.qq.beans.UserInfo; import edu.tsinghua.lumaqq.qq.events.QQEvent; import edu.tsinghua.lumaqq.qq.packets.Packet; import edu.tsinghua.lumaqq.qq.packets.in.AddFriendExReplyPacket; import edu.tsinghua.lumaqq.qq.packets.in.AdvancedSearchUserReplyPacket; import edu.tsinghua.lumaqq.qq.packets.in.ClusterCommandReplyPacket; import edu.tsinghua.lumaqq.qq.packets.in.SearchUserReplyPacket; import edu.tsinghua.lumaqq.qq.packets.out.AdvancedSearchUserPacket; import edu.tsinghua.lumaqq.qq.packets.out.ClusterCommandPacket; import edu.tsinghua.lumaqq.qq.packets.out.SearchUserPacket; import edu.tsinghua.lumaqq.resource.Resources; import edu.tsinghua.lumaqq.ui.MainShell; import edu.tsinghua.lumaqq.ui.wizard.IModelBasedWizard; /** * 搜索的wizard * * @author luma */ public class SearchWizard extends Wizard implements IModelBasedWizard, INewWizard { private MainShell main; private SearchResult userResult; private SearchResult clusterResult; private char expected; private boolean end; private boolean operating; private SearchWizardModel model; private int preNextFlag; private static final int PRE_NEXT_NONE = 0; private static final int PRE_NEXT_SEARCH_CLUSTER_BY_CATEGORY = 1; private BaseQQListener qqListener = new BaseQQListener() { @Override protected void OnQQEvent(QQEvent e) { switch(e.type) { case QQEvent.USER_SEARCH_OK: processSearchUserSuccess(e); break; case QQEvent.USER_ADVANCED_SEARCH_OK: processAdvancedSearchUserSuccess(e); break; case QQEvent.USER_ADVANCED_SEARCH_END: processAdvancedSearchUserEnd(e); break; case QQEvent.CLUSTER_SEARCH_OK: processSearchClusterSuccess(e); break; case QQEvent.CLUSTER_SEARCH_FAIL: processSearchClusterFail(e); break; case QQEvent.FRIEND_ADD_OK: case QQEvent.FRIEND_ADD_ALREADY: processAddFriendSuccess(e); break; case QQEvent.FRIEND_ADD_FAIL: processAddFriendFail(e); break; case QQEvent.FRIEND_ADD_DENY: processAddFriendDeny(e); break; case QQEvent.FRIEND_ADD_NEED_AUTH: processAddFriendNeedAuth(e); break; case QQEvent.FRIEND_AUTH_SEND_OK: case QQEvent.FRIEND_AUTHORIZE_SEND_OK: processAddFriendAuthSendSuccess(e); break; case QQEvent.FRIEND_AUTH_SEND_FAIL: case QQEvent.FRIEND_AUTHORIZE_SEND_FAIL: processAddFriendAuthSendFail(e); break; case QQEvent.CLUSTER_JOIN_OK: processJoinClusterSuccess(e); break; case QQEvent.CLUSTER_JOIN_FAIL: processJoinClusterFail(e); break; case QQEvent.CLUSTER_JOIN_DENY: processJoinClusterDenied(e); break; case QQEvent.CLUSTER_JOIN_NEED_AUTH: processJoinClusterNeedAuth(e); break; case QQEvent.CLUSTER_AUTH_SEND_FAIL: processJoinClusterAuthSendFail(e); break; case QQEvent.CLUSTER_AUTH_SEND_OK: processJoinClusterAuthSendSuccess(e); break; case QQEvent.SYS_TIMEOUT: switch(e.operation) { case QQ.QQ_CMD_SEARCH_USER: processSearchUserTimeout(e); break; case QQ.QQ_CMD_ADVANCED_SEARCH: processAdvancedSearchUserTimeout(e); break; case QQ.QQ_CMD_CLUSTER_CMD: processClusterCommandTimeout(e); break; case QQ.QQ_CMD_ADD_FRIEND_AUTH: processAddFriendAuthSendFail(e); break; case QQ.QQ_CMD_ADD_FRIEND_EX: processAddFriendExTimeout(e); break; } } } }; public SearchWizard() { model = new SearchWizardModel(); } /* (non-Javadoc) * @see org.eclipse.jface.wizard.IWizard#getStartingPage() */ @Override public IWizardPage getStartingPage() { return getPage(model.getStartingPage()); } /* (non-Javadoc) * @see org.eclipse.jface.wizard.IWizard#performFinish() */ @Override public boolean performFinish() { unhookListener(); main.getShellRegistry().deregisterSearchWizard(); return true; } /* (non-Javadoc) * @see org.eclipse.jface.wizard.IWizard#addPages() */ @Override public void addPages() { userResult = new SearchResult(); clusterResult = new SearchResult(); addPage(new SearchWhatWizardPage(PAGE_SEARCH_WHAT)); addPage(new HowToSearchUserWizardPage(PAGE_HOW_TO_SEARCH_USER)); addPage(new HowToSearchClusterWizardPage(main, PAGE_HOW_TO_SEARCH_CLUSTER)); addPage(new SearchUserAccurateWizardPage(PAGE_SEARCH_USER_ACCURATE)); addPage(new SearchUserAdvancedWizardPage(PAGE_SEARCH_USER_ADVANCED)); addPage(new SearchUserResultWizardPage(PAGE_SEARCH_USER_RESULT, userResult)); addPage(new SearchClusterResultWizardPage(PAGE_SEARCH_CLUSTER_RESULT, clusterResult)); addPage(new AddFriendClusterWizardPage(PAGE_ADD)); getShell().setImage(Resources.getInstance().getImage(Resources.icoSearch)); hookListener(); end = false; operating = false; preNextFlag = PRE_NEXT_NONE; } /* (non-Javadoc) * @see org.eclipse.jface.wizard.IWizard#getNextPage(org.eclipse.jface.wizard.IWizardPage) */ @Override public IWizardPage getNextPage(IWizardPage page) { preNextFlag = PRE_NEXT_NONE; String name = page.getName(); if(PAGE_SEARCH_WHAT.equals(name)) { switch(model.getSearchWhat()) { case SearchWizardModel.USER: return getPage(PAGE_HOW_TO_SEARCH_USER); case SearchWizardModel.CLUSTER: return getPage(PAGE_HOW_TO_SEARCH_CLUSTER); default: return null; } } else if(PAGE_HOW_TO_SEARCH_USER.equals(name)) { switch(model.getUserSearchMode()) { case ONLINE: return getPage(PAGE_SEARCH_USER_RESULT); case ACCURATE: return getPage(PAGE_SEARCH_USER_ACCURATE); case ADVANCED: return getPage(PAGE_SEARCH_USER_ADVANCED); default: return null; } } else if(PAGE_HOW_TO_SEARCH_CLUSTER.equals(name)) { switch(model.getClusterSearchMode()) { case BY_CATEGORY: preNextFlag = PRE_NEXT_SEARCH_CLUSTER_BY_CATEGORY; return page; default: return getPage(PAGE_SEARCH_CLUSTER_RESULT); } } else if(PAGE_SEARCH_USER_ACCURATE.equals(name)) { return getPage(PAGE_SEARCH_USER_RESULT); } else if(PAGE_SEARCH_USER_ADVANCED.equals(name)) { return getPage(PAGE_SEARCH_USER_RESULT); } else if(PAGE_SEARCH_USER_RESULT.equals(name)) { return getPage(PAGE_ADD); } else if(PAGE_SEARCH_CLUSTER_RESULT.equals(name)) { return getPage(PAGE_ADD); } else return null; } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection) */ public void init(IWorkbench workbench, IStructuredSelection selection) { } /** * 初始化,传递MainShell引用 * * @param m */ public void init(MainShell m) { this.main = m; setWindowTitle(search_title); setDefaultPageImageDescriptor(Resources.getInstance().getImageDescriptor(Resources.icoSearchWizard)); } public MainShell getMainShell() { return main; } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.ui.wizard.IModelBasedWizard#preNext() */ public void preNext() { switch(preNextFlag) { case PRE_NEXT_SEARCH_CLUSTER_BY_CATEGORY: getMainShell().getShellLauncher().searchCluster(model.getCategoryId()); break; } } /** * 处理添加好友超时事件 * * @param e */ private void processAddFriendExTimeout(QQEvent e) { Packet packet = (Packet)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; setAddPageStatus(ADD_TIMEOUT); } /** * 初始对方禁止添加好友事件 * * @param e */ private void processAddFriendDeny(QQEvent e) { Packet packet = (Packet)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; setAddPageStatus(ADD_DENY); } /** * 处理认证消息发送失败事件 */ private void processJoinClusterAuthSendFail(QQEvent e) { Packet packet = (Packet)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; setAddPageStatus(AUTH_TIMEOUT); } /** * 处理认证消息发送成功事件 */ private void processJoinClusterAuthSendSuccess(QQEvent e) { Packet packet = (Packet)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; setAddPageStatus(AUTH_SENT); } /** * 处理加入群需要认证事件 */ private void processJoinClusterNeedAuth(QQEvent e) { Packet packet = (Packet)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; setAddPageStatus(AUTH_INPUTING); } /** * 处理禁止加入群事件 */ private void processJoinClusterDenied(QQEvent e) { Packet packet = (Packet)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; setAddPageStatus(JOIN_DENY); } /** * 初始加入群失败事件 */ private void processJoinClusterFail(QQEvent e) { Packet packet = (Packet)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; setAddPageStatus(JOIN_TIMEOUT); } /** * 处理加入群成功事件 * @param e */ private void processJoinClusterSuccess(QQEvent e) { ClusterCommandReplyPacket packet = (ClusterCommandReplyPacket)e.getSource(); if(expected != packet.getSequence()) return; final int id = model.getSelectedModelId(); if(id == packet.clusterId) { operating = false; expected = 0; setAddPageStatus(JOIN_FINISHED); main.getBlindHelper().addCluster(id, false); } } /** * 处理认证信息发送失败事件 */ private void processAddFriendAuthSendFail(QQEvent e) { Packet packet = (Packet)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; setAddPageStatus(AUTH_TIMEOUT); } /** * 处理验证发送成功事件 */ private void processAddFriendAuthSendSuccess(QQEvent e) { Packet packet = (Packet)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; setAddPageStatus(AUTH_SENT); } /** * 处理添加好友需要验证事件 */ private void processAddFriendNeedAuth(QQEvent e) { Packet packet = (Packet)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; setAddPageStatus(AUTH_INPUTING); } /** * 处理添加好友失败事件 */ private void processAddFriendFail(QQEvent e) { Packet packet = (Packet)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; setAddPageStatus(ADD_DENY); } /** * 处理添加好友成功事件 * * @param e */ private void processAddFriendSuccess(QQEvent e) { AddFriendExReplyPacket packet = (AddFriendExReplyPacket)e.getSource(); if(expected != packet.getSequence()) return; final int id = model.getSelectedModelId(); if(id == packet.friendQQ) { operating = false; expected = 0; setAddPageStatus(ADD_FINISHED); } } /** * 处理群命令超时事件 * * @param e */ private void processClusterCommandTimeout(QQEvent e) { final ClusterCommandPacket packet = (ClusterCommandPacket)e.getSource(); if(expected != packet.getSequence()) return; switch(packet.getSubCommand()) { case QQ.QQ_CLUSTER_CMD_SEARCH_CLUSTER: processSearchClusterTimeout(e); break; case QQ.QQ_CLUSTER_CMD_JOIN_CLUSTER_AUTH: processJoinClusterAuthSendFail(e); break; case QQ.QQ_CLUSTER_CMD_JOIN_CLUSTER: processJoinClusterFail(e); break; } } /** * 处理搜索群命令超时事件 * * @param e */ private void processSearchClusterTimeout(QQEvent e) { ClusterCommandPacket packet = (ClusterCommandPacket)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; onSearchClusterError(); openError(message_box_common_timeout); } /** * 搜索群发生错误时 */ private void onSearchClusterError() { SearchClusterResultWizardPage page = (SearchClusterResultWizardPage)getPage(PAGE_SEARCH_CLUSTER_RESULT); page.onSearchClusterError(); } /** * 处理搜索群失败事件 * * @param e */ private void processSearchClusterFail(QQEvent e) { final ClusterCommandReplyPacket packet = (ClusterCommandReplyPacket)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; onSearchClusterError(); openError(packet.errorMessage); } /** * 处理搜索群成功事件 * * @param e */ private void processSearchClusterSuccess(QQEvent e) { final ClusterCommandReplyPacket packet = (ClusterCommandReplyPacket)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; showClusterPage(packet.clusters); } /** * @param e */ private void processAdvancedSearchUserTimeout(QQEvent e) { AdvancedSearchUserPacket packet = (AdvancedSearchUserPacket)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; onSearchUserError(); openError(error_timeout); } /** * @param e */ private void processAdvancedSearchUserEnd(QQEvent e) { AdvancedSearchUserReplyPacket packet = (AdvancedSearchUserReplyPacket)e.getSource(); if(expected != packet.getSequence()) return; operating = false; end = true; expected = 0; onSearchUserEnd(); } /** * @param e */ private void processAdvancedSearchUserSuccess(QQEvent e) { AdvancedSearchUserReplyPacket packet = (AdvancedSearchUserReplyPacket)e.getSource(); if(expected != packet.getSequence()) return; end = false; operating = false; expected = 0; showUserPage(packet.users); } /** * 初始搜索用户超时事件 * @param e */ private void processSearchUserTimeout(QQEvent e) { SearchUserPacket packet = (SearchUserPacket)e.getSource(); if(expected != packet.getSequence()) return; operating = false; expected = 0; onSearchUserError(); openError(error_timeout); } /** * 搜索发生错误时 */ private void onSearchUserError() { SearchUserResultWizardPage page = (SearchUserResultWizardPage)getPage(PAGE_SEARCH_USER_RESULT); page.onSearchUserError(); } /** * 打开错误提示框 * * @param message * 错误消息 */ private void openError(String message) { MessageDialog.openError(getShell(), message_box_common_fail_title, message); } /** * 处理搜索用户成功事件 * * @param e */ private void processSearchUserSuccess(QQEvent e) { SearchUserReplyPacket packet = (SearchUserReplyPacket)e.getSource(); if(expected != packet.getSequence()) return; end = false; operating = false; expected = 0; showUserPage(packet.users); } /** * 显示一页结果 * * @param page */ private void showUserPage(List<? extends Object> p) { SearchUserResultWizardPage page = (SearchUserResultWizardPage)getPage(PAGE_SEARCH_USER_RESULT); page.addPage(p); } /** * 显示一页结果 * * @param p */ private void showClusterPage(List<? extends Object> p) { SearchClusterResultWizardPage page = (SearchClusterResultWizardPage)getPage(PAGE_SEARCH_CLUSTER_RESULT); page.addPage(p); } /** * 在搜索用户结束时调用 */ private void onSearchUserEnd() { SearchUserResultWizardPage page = (SearchUserResultWizardPage)getPage(PAGE_SEARCH_USER_RESULT); page.onSearchEnd(); } /** * 设置添加页面的状态 * * @param status */ private void setAddPageStatus(int status) { model.setStatus(status); AddFriendClusterWizardPage page = (AddFriendClusterWizardPage)getPage(PAGE_ADD); page.refresh(); } /* (non-Javadoc) * @see org.eclipse.jface.wizard.IWizard#performCancel() */ @Override public boolean performCancel() { unhookListener(); main.getShellRegistry().deregisterSearchWizard(); return true; } /** * 根据搜索方式搜索 * * @param page */ public void doSearch(int page) { if(operating) return; operating = true; if(model.getSearchWhat() == USER) { switch(model.getUserSearchMode()) { case ONLINE: searchOnline(page); break; case ACCURATE: searchAccurate(page); break; case ADVANCED: searchAdvanced(page); break; default: operating = false; break; } } else if(model.getSearchWhat() == CLUSTER) { switch(model.getClusterSearchMode()) { case DEMO_CLUSTER: searchDemoCluster(); break; case BY_CLUSTER_ID: searchClusterById(); break; default: operating = false; break; } } } /** * 发送认证信息 * * @param message */ public void doAuth(String message) { if(operating) return; operating = true; Object selectedModel = model.getSelectedModel(); if(selectedModel == null) return; if(selectedModel instanceof UserInfo) { UserInfo user = (UserInfo)selectedModel; expected = main.getClient().user_SendAuth(user.qqNum, message); setAddPageStatus(AUTH_SENDING); } else if(selectedModel instanceof AdvancedUserInfo) { AdvancedUserInfo user = (AdvancedUserInfo)selectedModel; expected = main.getClient().user_SendAuth(user.qqNum, message); setAddPageStatus(AUTH_SENDING); } else if(selectedModel instanceof ClusterInfo) { ClusterInfo cluster = (ClusterInfo)selectedModel; expected = main.getClient().cluster_RequestJoin(cluster.clusterId, message); setAddPageStatus(AUTH_SENDING); } else operating = false; } /** * 添加好友或群 */ public void doAdd() { if(operating) return; operating = true; Object selectedModel = model.getSelectedModel(); if(selectedModel == null) return; if(selectedModel instanceof UserInfo) { UserInfo user = (UserInfo)selectedModel; expected = main.getClient().user_Add(user.qqNum); setAddPageStatus(ADDING); } else if(selectedModel instanceof AdvancedUserInfo) { AdvancedUserInfo user = (AdvancedUserInfo)selectedModel; expected = main.getClient().user_Add(user.qqNum); setAddPageStatus(ADDING); } else if(selectedModel instanceof ClusterInfo) { ClusterInfo cluster = (ClusterInfo)selectedModel; expected = main.getClient().cluster_Join(cluster.clusterId); setAddPageStatus(JOINING); } else operating = false; } /** * 搜索示范群 */ public void searchDemoCluster() { expected = ((HowToSearchClusterWizardPage)getPage(PAGE_HOW_TO_SEARCH_CLUSTER)).doSearch(); } /** * 根据群ID搜索 */ public void searchClusterById() { expected = ((HowToSearchClusterWizardPage)getPage(PAGE_HOW_TO_SEARCH_CLUSTER)).doSearch(); } /** * 高级搜索 * * @param page */ public void searchAdvanced(int page) { expected = ((SearchUserAdvancedWizardPage)getPage(PAGE_SEARCH_USER_ADVANCED)).doSearch(page); } /** * 搜索用户 * * @param page * 页号 */ public void searchOnline(int page) { expected = main.getClient().user_Search(page); } /** * 精确查找 * * @param page * 页号 */ public void searchAccurate(int page) { expected = ((SearchUserAccurateWizardPage)getPage(PAGE_SEARCH_USER_ACCURATE)).doSearch(page); } /** * 把自己加为QQ listener */ private void hookListener() { main.getClient().addQQListener(qqListener); } /** * 删除自己做为qq listener */ private void unhookListener() { main.getClient().removeQQListener(qqListener); } /** * @return Returns the end. */ public boolean isEnd() { return end; } /** * @return Returns the operating. */ public boolean isOperating() { return operating; } /** * @param end The end to set. */ public void setEnd(boolean end) { this.end = end; } /* (non-Javadoc) * @see org.eclipse.jface.wizard.IWizard#canFinish() */ @Override public boolean canFinish() { return ((AddFriendClusterWizardPage)getPage(PAGE_ADD)).isPageComplete(); } public Object getModel() { return model; } }
package com.fleet.quartz.dao; import com.fleet.quartz.entity.QuartzJob; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Map; /** * @author April Han */ @Mapper @Repository public interface QuartzJobDao { Integer insert(QuartzJob quartzJob); Integer delete(QuartzJob quartzJob); Integer deletes(Integer[] ids); Integer update(QuartzJob quartzJob); QuartzJob get(QuartzJob quartzJob); List<QuartzJob> list(Map<String, Object> map); List<Integer> idList(QuartzJob quartzJob); }
package com.tencent.mm.plugin.card.ui; import android.content.Context; import android.database.Cursor; import android.view.View; import android.view.ViewGroup; import com.tencent.mm.plugin.card.model.CardInfo; import com.tencent.mm.plugin.card.model.am; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.r; public class c extends r<CardInfo> { private final String TAG = "MicroMsg.CardAdapter"; private int count = 0; private int hBp; private com.tencent.mm.plugin.card.base.c hzI; public final /* synthetic */ Object a(Object obj, Cursor cursor) { CardInfo cardInfo = (CardInfo) obj; if (cardInfo == null) { cardInfo = new CardInfo(); } if (cursor.isClosed()) { x.e("MicroMsg.CardAdapter", "cursor is closed!"); } else { cardInfo.d(cursor); } return cardInfo; } public c(Context context, int i) { super(context, new CardInfo()); this.hBp = i; lB(true); this.hzI = new l(context, this); } public void WT() { x.v("MicroMsg.CardAdapter", "resetCursor"); Cursor nH = am.axi().nH(this.hBp); if (nH != null) { this.count = nH.getCount(); x.v("MicroMsg.CardAdapter", "card count:" + this.count); } setCursor(nH); notifyDataSetChanged(); } protected void WS() { aYc(); WT(); } public View getView(int i, View view, ViewGroup viewGroup) { return this.hzI.a(i, view, (CardInfo) getItem(i)); } public void release() { aYc(); this.hzI.release(); this.hzI = null; } }
package berlin.iconn.rbm.views; import berlin.iconn.rbm.main.AController; import berlin.iconn.rbm.main.BenchmarkModel; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.GridPane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.shape.RectangleBuilder; public class InImageDetectorController extends AController { @FXML private ImageView imgv_Image; @FXML private Label lbl_Recognition; @FXML private GridPane grid_Probabilities; private InImageDetectorModel model; private Rectangle rect; @FXML private AnchorPane view; /** * Initializes the controller class. * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { this.model = new InImageDetectorModel(this); this.update(); } @FXML private void btn_loadImageAction(ActionEvent event) { Image image = this.model.loadImage((int) imgv_Image.getFitWidth(), (int) imgv_Image.getFitHeight()); if(image == null){ return; } if (!image.isError()) { this.imgv_Image.setImage(image); this.model.detection(); int idx = 0; for(String name : this.model.getBenchmarkModel().getImageManager().getGroupNames()) { Label label = new Label(name); grid_Probabilities.add(label, 0, idx); idx++; } } else { System.out.println("error"); } } @FXML private void imgv_ImageMouseMovedAction(MouseEvent event) { if(this.model.getImageData() == null) return; HashMap<String, Double> probabilityMap = this.model.getProbabilityMap(event.getX(), event.getY()); if(probabilityMap == null) return; List<String> keys = new ArrayList(probabilityMap.keySet()); int index = 0; Double max = 0.0; int maxIdx = -1; int counter = 0; for(String key : keys) { Double value = probabilityMap.get(key); if(value > max) { max = value; maxIdx = counter; } counter++; } for(String key : keys) { final ProgressBar progressBar = new ProgressBar(); progressBar.setProgress(probabilityMap.get(key)); if(index == maxIdx) { progressBar.setStyle("-fx-accent: red;"); } else { progressBar.setStyle("-fx-accent: blue;"); } this.grid_Probabilities.add(progressBar, 1, index); index++; } if(rect != null) { view.getChildren().remove(rect); } rect = RectangleBuilder.create() .x(event.getX()) .y(event.getY() + 30) .width(28) .height(28) .stroke(Color.RED) .fill(Color.TRANSPARENT) .build(); view.getChildren().add(rect); } @Override public Node getView() { return this.view; } @Override public void update(){ } public void setBenchmarkModel(BenchmarkModel benchmarkModel) { this.model.setBenchmarkModel(benchmarkModel); } }
package com.mygdx.game.systems; import com.mygdx.game.MyGdxGame; import com.mygdx.game.Settings; import com.mygdx.game.components.CollectableComponent; import com.mygdx.game.components.PlayersAvatarComponent; import com.scs.basicecs.AbstractEntity; public class CollectorSystem { private MyGdxGame game; public CollectorSystem(MyGdxGame _game) { game = _game; } public void entityCollected(AbstractEntity collector, AbstractEntity coin) { coin.remove(); CollectableComponent cc = (CollectableComponent)coin.getComponent(CollectableComponent.class); switch (cc.type) { case Coin: PlayersAvatarComponent uic = (PlayersAvatarComponent)collector.getComponent(PlayersAvatarComponent.class); game.sfx.play("sfx/Collect_Point_00.wav"); if (uic != null) { uic.player.score += 1; if (uic.player.score >= Settings.WINNING_COINS) { game.setWinner(uic.player.playerIdx); } } game.ecs.addEntity(game.entityFactory.createRisingCoin(coin)); break; default: throw new RuntimeException("Unknown collectable type: " + cc.type); } } }
package com.tencent.mm.plugin.dbbackup; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.tencent.mm.model.au; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.platformtools.x; import java.util.Date; class d$9 extends BroadcastReceiver { final /* synthetic */ d iam; d$9(d dVar) { this.iam = dVar; } public final void onReceive(Context context, Intent intent) { String action = intent.getAction(); boolean z = true; switch (action.hashCode()) { case -2128145023: if (action.equals("android.intent.action.SCREEN_OFF")) { z = true; break; } break; case -1886648615: if (action.equals("android.intent.action.ACTION_POWER_DISCONNECTED")) { z = true; break; } break; case -1454123155: if (action.equals("android.intent.action.SCREEN_ON")) { z = false; break; } break; case 1019184907: if (action.equals("android.intent.action.ACTION_POWER_CONNECTED")) { z = true; break; } break; } switch (z) { case false: d.b(this.iam, true); break; case true: d.b(this.iam, false); break; case true: d.c(this.iam, true); break; case true: d.c(this.iam, false); break; } x.v("MicroMsg.SubCoreDBBackup", "Action received: %s, interactive: %s, charging: %s", new Object[]{action, Boolean.valueOf(d.i(this.iam)), Boolean.valueOf(d.j(this.iam))}); if (d.h(this.iam) && d.k(this.iam) == null && d.j(this.iam) && !d.i(this.iam)) { if (System.currentTimeMillis() - d.l(this.iam) < 86400000) { x.d("MicroMsg.SubCoreDBBackup", "Last backup time not matched."); return; } z = d.m(this.iam) < 10; d.a(this.iam, new 2(this, z, new 1(this, z))); au.Em().h(d.k(this.iam), d.g(this.iam)); x.i("MicroMsg.SubCoreDBBackup", "Auto database backup scheduled."); h.mEJ.h(11098, new Object[]{Integer.valueOf(10009), this.iam.hZW.format(new Date())}); } else if (d.k(this.iam) != null) { au.Em().cil().removeCallbacks(d.k(this.iam)); d.a(this.iam, null); x.i("MicroMsg.SubCoreDBBackup", "Auto database backup canceled."); h.mEJ.h(11098, new Object[]{Integer.valueOf(10010), this.iam.hZW.format(new Date())}); } else if (d.o(this.iam)) { this.iam.aCD(); d.d(this.iam, false); } } }
package commandline.command.mock; import commandline.annotation.CliArgument; import commandline.annotation.CliCommand; import commandline.command.Command; import commandline.command.ExecutableCommand; import org.jetbrains.annotations.NotNull; /** * User: gno, Date: 02.08.13 - 15:40 */ @CliCommand(name = InheritedArgumentTestCommand.COMMAND_NAME, description = InheritedArgumentTestCommand.COMMAND_DESCRIPTION) public class InheritedArgumentTestCommand extends ExecutableCommand { public static final String COMMAND_NAME = "inherited-argument-test-command"; public static final String COMMAND_DESCRIPTION = "This is a command description."; public static final String ARGUMENT_TEST_LONG_NAME = "test-argument"; public InheritedArgumentTestCommand() { super(); } @CliArgument(shortName = "t", longName = ARGUMENT_TEST_LONG_NAME, obligatory = false, description = "This is a test argument.", examples = {"example1"}) public void setTestArgument(String value) { } @Override public void execute(@NotNull Command command) { } }
package com.box.androidsdk.content.models; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import java.util.Map; /** * Class that represents a collection on Box. */ public class BoxCollection extends BoxEntity { public static final String TYPE = "collection"; public static final String FIELD_NAME = "name"; public static final String FIELD_COLLECTION_TYPE = "collection_type"; /** * Constructs an empty BoxCollection object. */ public BoxCollection() { super(); } /** * Constructs a BoxCollection with the provided map values * * @param object JsonObject representing this class */ public BoxCollection(JsonObject object) { super(object); } public static BoxCollection createFromId(String id) { JsonObject object = new JsonObject(); object.add(FIELD_ID, id); return new BoxCollection(object); } /** * Gets the name of the collection. * * @return the name of the collection. */ public String getName() { return getPropertyAsString(FIELD_NAME); } /** * Gets the type of the collection. Currently only "favorites" is supported. * * @return type of collection. */ public String getCollectionType() { return getPropertyAsString(FIELD_COLLECTION_TYPE); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapreduce; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import junit.framework.TestCase; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.examples.MultiFileWordCount; import org.apache.hadoop.examples.WordCount; import org.apache.hadoop.examples.WordCount.IntSumReducer; import org.apache.hadoop.examples.WordCount.TokenizerMapper; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.MiniMRCluster; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.LineRecordReader; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.ToolRunner; /** * A JUnit test to test min map-reduce cluster with local file system. */ public class TestMapReduceLocal extends TestCase { private static Path TEST_ROOT_DIR = new Path(System.getProperty("test.build.data","/tmp")); private static Configuration conf = new Configuration(); private static FileSystem localFs; static { try { localFs = FileSystem.getLocal(conf); } catch (IOException io) { throw new RuntimeException("problem getting local fs", io); } } public static Path writeFile(String name, String data) throws IOException { Path file = new Path(TEST_ROOT_DIR + "/" + name); localFs.delete(file, false); DataOutputStream f = localFs.create(file); f.write(data.getBytes()); f.close(); return file; } public static String readFile(String name) throws IOException { DataInputStream f = localFs.open(new Path(TEST_ROOT_DIR + "/" + name)); BufferedReader b = new BufferedReader(new InputStreamReader(f)); StringBuilder result = new StringBuilder(); String line = b.readLine(); while (line != null) { result.append(line); result.append('\n'); line = b.readLine(); } b.close(); return result.toString(); } public void testWithLocal() throws Exception { MiniMRCluster mr = null; try { mr = new MiniMRCluster(2, "file:///", 3); Configuration conf = mr.createJobConf(); runWordCount(conf); runMultiFileWordCount(conf); } finally { if (mr != null) { mr.shutdown(); } } } public static class TrackingTextInputFormat extends TextInputFormat { public static class MonoProgressRecordReader extends LineRecordReader { private float last = 0.0f; private boolean progressCalled = false; @Override public float getProgress() throws IOException { progressCalled = true; final float ret = super.getProgress(); assertTrue("getProgress decreased", ret >= last); last = ret; return ret; } @Override public synchronized void close() throws IOException { assertTrue("getProgress never called", progressCalled); super.close(); } } @Override public RecordReader<LongWritable, Text> createRecordReader( InputSplit split, TaskAttemptContext context) { return new MonoProgressRecordReader(); } } private void runWordCount(Configuration conf ) throws IOException, InterruptedException, ClassNotFoundException { final String COUNTER_GROUP = "org.apache.hadoop.mapreduce.TaskCounter"; localFs.delete(new Path(TEST_ROOT_DIR + "/in"), true); localFs.delete(new Path(TEST_ROOT_DIR + "/out"), true); writeFile("in/part1", "this is a test\nof word count test\ntest\n"); writeFile("in/part2", "more test"); Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCount.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setInputFormatClass(TrackingTextInputFormat.class); FileInputFormat.addInputPath(job, new Path(TEST_ROOT_DIR + "/in")); FileOutputFormat.setOutputPath(job, new Path(TEST_ROOT_DIR + "/out")); assertTrue(job.waitForCompletion(false)); String out = readFile("out/part-r-00000"); System.out.println(out); assertEquals("a\t1\ncount\t1\nis\t1\nmore\t1\nof\t1\ntest\t4\nthis\t1\nword\t1\n", out); Counters ctrs = job.getCounters(); System.out.println("Counters: " + ctrs); long mapIn = ctrs.findCounter(FileInputFormat.COUNTER_GROUP, FileInputFormat.BYTES_READ).getValue(); assertTrue(mapIn != 0); long combineIn = ctrs.findCounter(COUNTER_GROUP, "COMBINE_INPUT_RECORDS").getValue(); long combineOut = ctrs.findCounter(COUNTER_GROUP, "COMBINE_OUTPUT_RECORDS").getValue(); long reduceIn = ctrs.findCounter(COUNTER_GROUP, "REDUCE_INPUT_RECORDS").getValue(); long mapOut = ctrs.findCounter(COUNTER_GROUP, "MAP_OUTPUT_RECORDS").getValue(); long reduceOut = ctrs.findCounter(COUNTER_GROUP, "REDUCE_OUTPUT_RECORDS").getValue(); long reduceGrps = ctrs.findCounter(COUNTER_GROUP, "REDUCE_INPUT_GROUPS").getValue(); long mergedMapOutputs = ctrs.findCounter(COUNTER_GROUP, "MERGED_MAP_OUTPUTS").getValue(); long shuffledMaps = ctrs.findCounter(COUNTER_GROUP, "SHUFFLED_MAPS").getValue(); assertEquals("map out = combine in", mapOut, combineIn); assertEquals("combine out = reduce in", combineOut, reduceIn); assertTrue("combine in > combine out", combineIn > combineOut); assertEquals("reduce groups = reduce out", reduceGrps, reduceOut); assertEquals("Mismatch in mergedMapOutputs", mergedMapOutputs, 2); assertEquals("Mismatch in shuffledMaps", shuffledMaps, 2); String group = "Random Group"; CounterGroup ctrGrp = ctrs.getGroup(group); assertEquals(0, ctrGrp.size()); } public void runMultiFileWordCount(Configuration conf) throws Exception { localFs.delete(new Path(TEST_ROOT_DIR + "/in"), true); localFs.delete(new Path(TEST_ROOT_DIR + "/out"), true); writeFile("in/part1", "this is a test\nof " + "multi file word count test\ntest\n"); writeFile("in/part2", "more test"); int ret = ToolRunner.run(conf, new MultiFileWordCount(), new String[] {TEST_ROOT_DIR + "/in", TEST_ROOT_DIR + "/out"}); assertTrue("MultiFileWordCount failed", ret == 0); String out = readFile("out/part-r-00000"); System.out.println(out); assertEquals("a\t1\ncount\t1\nfile\t1\nis\t1\n" + "more\t1\nmulti\t1\nof\t1\ntest\t4\nthis\t1\nword\t1\n", out); } }
package consulting.ross.demo.osgi.impl.alarm; import consulting.ross.demo.osgi.envmon.Alarm; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** The simplest alarm. Alarms are stateful, repetitive * attention-grabbers. */ public class BasicAlarm implements Alarm { volatile ScheduledExecutorService es; @Override public void activate() { // Idempotent if ( es == null ) { es = Executors.newScheduledThreadPool(2); es.scheduleWithFixedDelay( () -> System.err.println("** ALARM!!!!!!"), 1, 1, TimeUnit.SECONDS); } } @Override public void deActivate() { // Idempotent if (es != null && !es.isShutdown()) { es.shutdownNow(); es = null; } } }
/** * @author smxknife * 2021/5/20 */ package com.smxknife.energy.datacenter.core;
/** * Copyright &copy; 2012-2014 <a href="http://www.iwantclick.com">iWantClick</a>iwc.shop All rights reserved. */ package com.beiyelin.account.service; import com.beiyelin.account.bean.AccountQuery; import com.beiyelin.account.bean.DepartmentQuery; import com.beiyelin.account.entity.Account; import com.beiyelin.account.entity.Department; import com.beiyelin.common.reqbody.PageReq; import com.beiyelin.common.resbody.PageResp; import com.beiyelin.commonsql.jpa.BaseDomainCRUDService; import com.beiyelin.commonsql.jpa.MasterDataCRUDService; import java.util.List; /** * 部门管理 * @author Newmann * @version 2017-03-18 */ public interface DepartmentService extends MasterDataCRUDService<Department> { // /** // * 取消 // */ // Department cancel(Department department); // /** // * 提交 // */ // Department submit(Department department); // /** // * 删除 // */ // boolean remove(Department department); // /** // * 完成 // */ // Department achieve(Department department); // /** // * 取消完成,返回提交状态 // */ // Department unachieve(Department department); // /** // * 锁定 // */ // Department lock(Department department); // /** // * 取消锁定 // */ // Department unlock(Department department); /** * 判断部门代码是否可用 * @param code * @return */ boolean checkCodeAvailable(String code); /** * 在修改部门代码的时候使用,所以要带上Id * @param code * @return */ boolean checkCodeAvailableWithId(String code,String id); /** * 获取所有可用的部门 * @return */ List<Department> findAllAvailableDepartments(); List<Department> fetchAvailableByCodeOrName(String searchStr); /** * 根据父部门的Id获取所有下级可用的部门 * @return */ List<Department> fetchAllByParentId(String parentId); /** * 支持前端的list界面查询 * @param departmentQuery * @param pageReq * @return */ PageResp<Department> fetchByDepartmentQuery(DepartmentQuery departmentQuery, PageReq pageReq); PageResp<Account> findAccountAvailablePools(String departmentId, AccountQuery accountQuery, PageReq pageReq); }
package com.example.gayathri.places; public class Review { private String name, time_created, rating, photo_url, text, user_url; public Review(){ } public Review(String name, String time_created, String rating, String photo_url, String text, String user_url) { this.name = name; this.time_created = time_created; this.rating = rating; this.photo_url = photo_url; this.text = text; this.user_url = user_url; } public String getUser_url() { return user_url; } public void setUser_url(String user_url) { this.user_url = user_url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTime_created() { return time_created; } public void setTime_created(String time_created) { this.time_created = time_created; } public String getRating() { return rating; } public void setRating(String rating) { this.rating = rating; } public String getPhoto_url() { return photo_url; } public void setPhoto_url(String photo_url) { this.photo_url = photo_url; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
package fr.lteconsulting.formations.client.components; import fr.lteconsulting.angular2gwt.client.JsArray; import fr.lteconsulting.angular2gwt.client.interop.ng.core.OnInit; import fr.lteconsulting.angular2gwt.ng.core.Component; import fr.lteconsulting.formations.client.dto.CollaborateurDTO; import fr.lteconsulting.formations.client.services.CollaborateurService; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; @Component( selector = "my-collaborateurs", templateUrl = "CollaborateursComponent.html", styles = ".selected { background-color: #bbb; }" ) @JsType public class CollaborateursComponent implements OnInit { public String filterText; public CollaborateurDTO selectedCollaborateur; public final String dateFormat = "dd MMM yyyy"; @JsProperty public JsArray<CollaborateurDTO> getCollaborateurs() { if( _collaborateurs == null ) return null; if( filterText == null ) return _collaborateurs; String realFilter = filterText.toLowerCase(); return _collaborateurs.filter( c -> (c.nom + " " + c.prenom + " " + c.codeAgence).toLowerCase().contains( realFilter ) ); } private JsArray<CollaborateurDTO> _collaborateurs; private CollaborateurService collaborateurService; public CollaborateursComponent( CollaborateurService collaborateurService ) { this.collaborateurService = collaborateurService; } @Override public void ngOnInit() { collaborateurService.getAll() .then( result -> { _collaborateurs = result; return null; } ); } public void selectCollaborateur( CollaborateurDTO collaborateur ) { selectedCollaborateur = collaborateur; } }
package com.hx.service; import com.hx.entity.SysLog; import com.hx.model.SysLogDataModel; import java.util.List; /** * 托盘管理操作日志Service接口 * */ public interface SysLogService { /** * 查询托盘管理操作日志 * * @param id 托盘管理操作日志ID * @return 托盘管理操作日志 */ public SysLog selectSysLogById(Integer id); /** * 查询托盘管理操作日志列表 * * @param model 托盘管理操作日志 * @return 托盘管理操作日志集合 */ public List<SysLog> selectSysLogList(SysLogDataModel model); /** * 新增托盘管理操作日志 * * @param SysLog 托盘管理操作日志 * @return 结果 */ public int insertSysLog(SysLog SysLog); /** * 修改托盘管理操作日志 * * @param SysLog 托盘管理操作日志 * @return 结果 */ public int updateSysLog(SysLog SysLog); /** * 批量删除托盘管理操作日志 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteSysLogByIds(String ids); /** * 删除托盘管理操作日志信息 * * @param id 托盘管理操作日志ID * @return 结果 */ public int deleteSysLogById(Long id); }
package com.ifre.form.api; /** * 个人信用贷 * * @author CaiPeng * */ public class ApiDemoGrxyd { private String gender; private String age; private String isOpen; private String liveCase; private String car; private String compJoinYear; private String isNative; private String creditCardAccount; private String queryTimesOne; private String rate; private String monthlyPay; private String monthlyPayment; public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getIsOpen() { return isOpen; } public void setIsOpen(String isOpen) { this.isOpen = isOpen; } public String getLiveCase() { return liveCase; } public void setLiveCase(String liveCase) { this.liveCase = liveCase; } public String getCar() { return car; } public void setCar(String car) { this.car = car; } public String getCompJoinYear() { return compJoinYear; } public void setCompJoinYear(String compJoinYear) { this.compJoinYear = compJoinYear; } public String getIsNative() { return isNative; } public void setIsNative(String isNative) { this.isNative = isNative; } public String getCreditCardAccount() { return creditCardAccount; } public void setCreditCardAccount(String creditCardAccount) { this.creditCardAccount = creditCardAccount; } public String getQueryTimesOne() { return queryTimesOne; } public void setQueryTimesOne(String queryTimesOne) { this.queryTimesOne = queryTimesOne; } public String getRate() { //<option value="-99">保密</option> if("0".equals(monthlyPay) || "0".equals(monthlyPayment)){ rate = "-99"; }else{ double temprate = Double.parseDouble(monthlyPay)/Double.parseDouble(monthlyPayment); if(temprate > 0 && temprate <= 1){ //<option value="1">大于等于0小于等于1</option> rate = "1"; }else if(temprate > 1 && temprate <= 2){ //<option value="2">大于1小于等于2</option> rate = "2"; }else if(temprate > 2 && temprate <= 3){ //<option value="3">大于2小于等于3</option> rate = "3"; }else if(temprate > 3 && temprate <= 7){ //<option value="4">大于3小于等于7</option> rate = "4"; }else if(temprate > 7){ //<option value="5">大于7</option> rate = "5"; }else{ rate = "-99"; } } return rate; } public void setRate(String rate) { this.rate = rate; } public String getMonthlyPay() { return monthlyPay; } public void setMonthlyPay(String monthlyPay) { this.monthlyPay = monthlyPay; } public String getMonthlyPayment() { return monthlyPayment; } public void setMonthlyPayment(String monthlyPayment) { this.monthlyPayment = monthlyPayment; } }
package com.beiyelin.account.repository; import com.beiyelin.account.entity.*; import com.beiyelin.commonsql.jpa.BaseDomainRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; /** * @Author: xinsh * @Description: * @Date: Created in 16:38 2018/1/3. */ @Repository public interface MenuLinkRepository extends BaseDomainRepository<MenuLink,String> { MenuLink findFirstByTargetLink(String targetLink); // Menu findFirstByNameAndIdIsNot(String name, String id); // // List<Menu> findByName(String name); // @Query(value = "select ml.* from " + MenuLink.TABLE_NAME + " ml inner join " + AccountMenuLink.TABLE_NAME + " am on ml.id = am.menu_link_id " + " where am.account_id = ?1", nativeQuery = true) List<MenuLink> fetchByAccountId(String accountId); @Query(value = "select ml.* from " + MenuLink.TABLE_NAME +" ml inner join " + RoleMenuLink.TABLE_NAME + " rp on ml.id = rp.menu_link_id " + " where rp.role_id = ?1",nativeQuery = true) List<MenuLink> fetchByRoleId(String roleId); @Query(value = "select ml.* from " + MenuLink.TABLE_NAME +" ml inner join " + AccountMenuLink.TABLE_NAME + " aml on ml.id = aml.menu_link_id " + " where aml.account_id = ?1 union " + "select ml.* from " + MenuLink.TABLE_NAME +" ml inner join " + RoleMenuLink.TABLE_NAME + " rml on ml.id = rml.menu_link_id inner join " + RoleAccount.TABLE_NAME + " ra on rml.role_id = ra.role_id " + " where ra.account_id = ?1" ,nativeQuery = true) List<MenuLink> fetchAllByAccountId(String accountId); }
package eu.su.mas.dedaleEtu.mas.behaviours; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import dataStructures.serializableGraph.SerializableSimpleGraph; import dataStructures.tuple.Couple; import eu.su.mas.dedale.env.Observation; import eu.su.mas.dedale.mas.AbstractDedaleAgent; import eu.su.mas.dedaleEtu.mas.agents.dummies.explo.ExploreCoopAgent; import eu.su.mas.dedaleEtu.mas.knowledge.MapRepresentation; import eu.su.mas.dedaleEtu.mas.knowledge.SMPosition; import eu.su.mas.dedaleEtu.mas.knowledge.SerializableMessage; import eu.su.mas.dedaleEtu.mas.knowledge.MapRepresentation.MapAttribute; import jade.core.AID; import jade.core.Agent; import jade.core.behaviours.FSMBehaviour; import jade.core.behaviours.OneShotBehaviour; import jade.core.behaviours.SimpleBehaviour; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import jade.lang.acl.UnreadableException; public class IsFinishedHuntAloneBehaviour extends OneShotBehaviour { /** * */ private static final long serialVersionUID = -7158228049276029011L; private MapRepresentation myMap; private HashMap<String,String>agents_pos; private int exitvalue=1; //1:continue; //2:fini chasse solo fsm(fini block ou passer chasse together fsm) private List<String>pos_avant_next; /** * * @param myagent * @param myMap known map of the world the agent is living in * @param agentNames name of the agents to share the map with */ //add attribute public IsFinishedHuntAloneBehaviour(final Agent myagent, MapRepresentation myMap,HashMap<String,String> pos,List<String>pos_avant_next) { super(myagent); this.myMap=myMap; this.myAgent=myagent; this.agents_pos=pos; this.pos_avant_next=pos_avant_next; } @Override public void action() { if(this.myMap==null) { this.myMap=((ExploreCoopAgent) this.myAgent).getMap(); } //System.out.println("HuntAloneBehaviour termine car communication"); String posavant=this.pos_avant_next.get(0); String nextNode=this.pos_avant_next.get(1); String myPosition=((AbstractDedaleAgent)this.myAgent).getCurrentPosition(); if(posavant.equals(myPosition)&& !this.agents_pos.containsValue(nextNode)&&((ExploreCoopAgent) this.myAgent).lstench().contains(nextNode)) { Boolean isblock=true; List<String>nodeAdj=this.myMap.getnodeAdjacent(nextNode); for (String node:nodeAdj) { if(!node.equals(myPosition)) { isblock=false; break; } } if(isblock==true) { exitvalue=2; ((ExploreCoopAgent) this.myAgent).set_fsm_exitvalue(3); System.out.println("HuntAloneBehaviour finished because block wumpus"); } } } public int onEnd() {return exitvalue;} }
package com.spr.service; /** * Created by saurav on 27/03/17. */ public class EdgeInsertion implements Runnable { public EdgeInsertion() { } @Override public void run() { } }
package com.jiuzhe.app.hotel.constants; public enum FacilityEnum { WIFI("wifi", 101), DUBBO_BED("双人床", 102), WINDOW("有窗", 103), SHOWER("卫浴", 104); // 成员变量 private String desc; private int index; // 构造方法 private FacilityEnum(String desc, int index) { this.desc = desc; this.index = index; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } }
import java.util.Scanner; public class Main { public static void main(String[] args) { double a; double sum = 0; double b = 0; double c; Scanner scan = new Scanner(System.in); for (int i = 1; i <= 2; i++) { a = scan.nextDouble(); if (a >= 0 && a <= 10) { sum += a; } else { System.out.println("nota invalida"); i = i - 1; } } System.out.printf("media = %.2f%n", sum / 2); while (b != 2) { sum = 0; System.out.println("novo calculo (1-sim 2-nao)"); for (int i = 1; i <= 1; i++) { b = scan.nextDouble(); if (b == 1) { for (int f = 1; f <= 2; f++) { c = scan.nextDouble(); if (c >= 0 && c <= 10) { sum += c; } else { System.out.println("nota invalida"); f = f - 1; } } System.out.printf("media = %.2f%n", sum / 2); } else if (b == 2) { break; } else { i = i - 1; System.out.println("novo calculo (1-sim 2-nao)"); } } } } }
package Client; import Shared.*; import Utilities.ColorPrint; import Utilities.FileIOBasics; import Utilities.GameJsonUtils; import Utilities.GameStringUtils; import java.util.ArrayList; import java.util.Scanner; public class GameClientController { Player own; BasicTCPClient client; ColorPrint printer; GameMap gameMap; FileIOBasics fileIO; GameJsonUtils jsonUtils; GameClientViewer viewer; Scanner scanner; GameStringUtils gsu; OrderHandler handler; CheckHelper checker; GameClientController (int port, String hostname) { printer = new ColorPrint(); fileIO = new FileIOBasics(); jsonUtils = new GameJsonUtils(); viewer = new GameClientViewer(); scanner = new Scanner(System.in); checker = new CheckHelper(); handler = new OrderHandler(); gsu = new GameStringUtils(); client = new BasicTCPClient(port, hostname); client.buildConnection(); } void setName() { System.out.println(client.receiveMessage()); String name; do { name = scanner.nextLine(); } while(!checker.checkName(name)); client.sendMessage(name); System.out.println("Waiting for other players..."); //build player own = new Player(name); } void InitializeMap() { // receive map String MapStr = client.receiveMessage(); // System.out.println(MapStr); gameMap = jsonUtils.readJsonToGameMap(MapStr, null); System.out.println("\nThis is the original map: \n"); viewer.printMap(gameMap, own, "simple"); System.out.println("Please input initial units for your each territory: "); int initUnits = gameMap.getInitUnits(); var territoryList = gameMap.getPlayerByName(own.getName()).getTerritories(); String initUnitsList; do { initUnitsList = scanner.nextLine(); } while(!checker.checkInitUnitsList(initUnitsList,initUnits,territoryList.size())); String[] strArray = initUnitsList.split(" "); // update territory int index = 0; for(var t: territoryList) { int unit = Integer.parseInt(strArray[index++]); Territory newt = new Territory(t.getName(),t.getAliasName(),unit,own); own.addTerritory(newt); } /* For test System.out.println("Now you have: "); for(var t: own.getTerritories()) { System.out.print(t.getName() + ' '); System.out.println(t.getUnits()); } */ // send player to server String ownStr = jsonUtils.writeUnits(own); client.sendMessage(ownStr); System.out.println("Waiting for other players..."); } int OneRound(int round) { String MapStr = client.receiveMessage(); jsonUtils.updateMap(MapStr, gameMap); own = gameMap.getPlayerByName(own.getName()); System.out.printf("\n>>>>>>>>>>>>>>>>>>>>> Round %d <<<<<<<<<<<<<<<<<<<<<\n\n",round); int status = getStatus(); ArrayList<OrderBasic> orderList = new ArrayList<>(); if(status == 0) { String in; while (true) { try { viewer.printMap(gameMap, own, "order"); System.out.println("Please input order: "); in = scanner.nextLine(); if (in.equals("commit")) break; OrderBasic order = gsu.strToOrder(gameMap, in, own); handler.execute(order); orderList.add(order); } catch (NumberFormatException e) { System.out.println("Invalid number format!"); } catch (Exception e) { System.out.println(); } System.out.println(); } // print order System.out.println("You order is: "); for (var order : orderList) { System.out.printf("%s %d units from %s to %s\n", order.getOrderType(), order.getUnits(), order.getFromT().getName(), order.getToT().getName()); } System.out.println(); } else if(status == -1){ System.out.println("You are watching the game: "); viewer.printMap(gameMap, own, "order"); } else { return status; } // send order list String orderStr = jsonUtils.writeOrderListToJson(orderList); client.sendMessage(orderStr); System.out.println("Waiting for other players..."); return status; } // get status: // status = 1: Has winner(you or other player), game finish // status = -1: You lose // status = 0: Game continue int getStatus(){ if(own.getTerritories().size() == gameMap.getTerritoryMap().size()) { System.out.println("Congrats, you win!"); return 1; } else if (own.getTerritories().size() == 0) { System.out.print("Sorry, you lose! "); Player winner = hasWinner(); if(winner != null) { System.out.printf("The winner is %s\n",winner.getName()); return 1; } return -1; } return 0; } Player hasWinner() { for(var p: gameMap.getPlayerMap().values()) { if(p.getTerritories().size() == gameMap.getTerritoryMap().size()) return p; } return null; } public static void main(String[] args) { var control = new GameClientController(6666, "localhost"); control.setName(); control.InitializeMap(); int round = 1, status = 0; while(control.client.isRunning() && status != 1) { status = control.OneRound(round++); } control.client.end(); } }
package com.example.viewpagerapi.retroift; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; public interface ApiInterface { @GET("rpld/xample-img.php") Call<List<ImgModel>> getImages(); }
package cabelino.noticiasCampusVitoria; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * Created by Cabelino on 08/09/2017. */ public class BancoNoticias extends SQLiteOpenHelper { public static final String TABLE_NAME = "NoticiasLocais"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_COMMENT = "comment"; private static final String DATABASE_NAME = "NoticiasLocais.db"; private static final int DATABASE_VERSION = 1; // Database creation sql statement private static final String DATABASE_CREATE = "create table " + TABLE_NAME + "( " + COLUMN_ID + " text primary key, " + "Data" + " text not null, " + "Hora" + " text not null, " + "Titulo" + " text not null, " + "Resumo" + " text not null, " + "Conteudo" + " text not null);"; public BancoNoticias(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase database) { database.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(BancoNoticias.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } }
package com.mrice.txl.appthree.base; import android.app.Dialog; import android.databinding.DataBindingUtil; import android.databinding.ViewDataBinding; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.mrice.txl.appthree.R; import com.mrice.txl.appthree.databinding.ActivityBaseBinding; import com.mrice.txl.appthree.utils.DialogFactory; import com.mrice.txl.appthree.utils.PerfectClickListener; import com.mrice.txl.appthree.view.ProgressDialog; import okhttp3.MediaType; import okhttp3.RequestBody; import rx.Subscription; import rx.subscriptions.CompositeSubscription; /** * Created by cai on 16/12/10. */ public abstract class BaseActivity<SV extends ViewDataBinding> extends AppCompatActivity implements View.OnClickListener { // 布局view protected SV bindingView; private LinearLayout llProgressBar; private View refresh; private ActivityBaseBinding mBaseBinding; private AnimationDrawable mAnimationDrawable; private CompositeSubscription mCompositeSubscription; protected String SUCCESS_CODE = "0"; protected <T extends View> T getView(int id) { return (T) findViewById(id); } //全局加载框 protected ProgressDialog progressDialog; protected BaseActivity context; //点击同一 view 最小的时间间隔,如果小于这个数则忽略此次单击。 private static long intervalTime = 800; //最后点击时间 private long lastClickTime = 0; //最后被单击的 View 的ID private long lastClickView = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = this; } @Override public void setContentView(@LayoutRes int layoutResID) { mBaseBinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.activity_base, null, false); bindingView = DataBindingUtil.inflate(getLayoutInflater(), layoutResID, null, false); // content RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); bindingView.getRoot().setLayoutParams(params); RelativeLayout mContainer = (RelativeLayout) mBaseBinding.getRoot().findViewById(R.id.container); mContainer.addView(bindingView.getRoot()); getWindow().setContentView(mBaseBinding.getRoot()); // 设置透明状态栏 // StatusBarUtil.setColor(this, CommonUtils.getColor(R.color.colorTheme1), 0); llProgressBar = getView(R.id.ll_progress_bar); refresh = getView(R.id.ll_error_refresh); ImageView img = getView(R.id.img_progress); // 加载动画 mAnimationDrawable = (AnimationDrawable) img.getDrawable(); // 默认进入页面就开启动画 if (!mAnimationDrawable.isRunning()) { mAnimationDrawable.start(); } setToolBar(); // 点击加载失败布局 refresh.setOnClickListener(new PerfectClickListener() { @Override protected void onNoDoubleClick(View v) { showLoading(); onRefresh(); } }); bindingView.getRoot().setVisibility(View.GONE); } /** * 设置titlebar */ protected void setToolBar() { // setSupportActionBar(mBaseBinding.toolBar); // ActionBar actionBar = getSupportActionBar(); // if (actionBar != null) { // //去除默认Title显示 // actionBar.setDisplayShowTitleEnabled(false); // actionBar.setDisplayHomeAsUpEnabled(true); // actionBar.setHomeAsUpIndicator(R.drawable.icon_back); // } // mBaseBinding.toolBar.setNavigationOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // onBackPressed(); // } // }); mBaseBinding.ivBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onBackPressed(); } }); } public void setBackAction(boolean visible) { mBaseBinding.ivBack.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); } public void setTitle(CharSequence text) { // mBaseBinding.toolBar.setTitle(text); mBaseBinding.title.setText(text); } protected void showLoading() { if (llProgressBar.getVisibility() != View.VISIBLE) { llProgressBar.setVisibility(View.VISIBLE); } // 开始动画 if (!mAnimationDrawable.isRunning()) { mAnimationDrawable.start(); } if (bindingView.getRoot().getVisibility() != View.GONE) { bindingView.getRoot().setVisibility(View.GONE); } if (refresh.getVisibility() != View.GONE) { refresh.setVisibility(View.GONE); } } protected void showContentView() { if (llProgressBar.getVisibility() != View.GONE) { llProgressBar.setVisibility(View.GONE); } // 停止动画 if (mAnimationDrawable.isRunning()) { mAnimationDrawable.stop(); } if (refresh.getVisibility() != View.GONE) { refresh.setVisibility(View.GONE); } if (bindingView.getRoot().getVisibility() != View.VISIBLE) { bindingView.getRoot().setVisibility(View.VISIBLE); } } protected void showError() { if (llProgressBar.getVisibility() != View.GONE) { llProgressBar.setVisibility(View.GONE); } // 停止动画 if (mAnimationDrawable.isRunning()) { mAnimationDrawable.stop(); } if (refresh.getVisibility() != View.VISIBLE) { refresh.setVisibility(View.VISIBLE); } if (bindingView.getRoot().getVisibility() != View.GONE) { bindingView.getRoot().setVisibility(View.GONE); } } /** * 失败后点击刷新 */ protected void onRefresh() { } public void addSubscription(Subscription s) { if (this.mCompositeSubscription == null) { this.mCompositeSubscription = new CompositeSubscription(); } this.mCompositeSubscription.add(s); } @Override public void onDestroy() { super.onDestroy(); if (this.mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) { this.mCompositeSubscription.unsubscribe(); } } public void removeSubscription() { if (this.mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) { this.mCompositeSubscription.unsubscribe(); } } protected Dialog showProgressDialog() { return showProgressDialog("正在加载中"); } protected Dialog showProgressDialog(int msgId) { String msg = getString(msgId); return showProgressDialog(msg); } protected Dialog showProgressDialog(String msg) { if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } progressDialog = DialogFactory.createProgressDialog(context, msg); if (!progressDialog.isShowing()) { progressDialog.setMessage(msg); progressDialog.show(); } return progressDialog; } public void hideProgressDialog() { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); progressDialog = null; } } @Override public void onClick(View view) { if (!isFastMultiClick(view)) { onViewClick(view); } } /** * 防短时重复点击回调 <br> * 子类使用 View.OnClickListener 设置监听事件时直接覆写该方法完成点击回调事件 * * @param view 被单击的View */ protected void onViewClick(View view) { //供字类重写用事件 } /** * 是否快速多次点击(连续多点击) * * @param view 被点击view,如果前后是同一个view,则进行双击校验 * @return 认为是重复点击时返回true。 */ private boolean isFastMultiClick(View view) { long time = System.currentTimeMillis() - lastClickTime; if (time < intervalTime && lastClickView == view.getId()) { lastClickTime = System.currentTimeMillis(); return true; } lastClickTime = System.currentTimeMillis(); lastClickView = view.getId(); return false; } public RequestBody getRequestBody(String json) { return RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), json); } }
package com.neo.test.curator; import java.util.concurrent.TimeUnit; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.utils.CloseableUtils; public class TestZKLock { public final static String ZK_HOST = "10.144.48.195:2181";// 172.19.253.121:2181,172.19.253.122:2181,172.19.253.123:2181 public static void main(String[] args) { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); final CuratorFramework zkclient = CuratorFrameworkFactory.newClient(ZK_HOST, retryPolicy); zkclient.start(); //testMutex(zkclient); testSemaphoreMutex(zkclient); CloseableUtils.closeQuietly(zkclient); } /** * 可重入锁 */ private static void testMutex(CuratorFramework client) { InterProcessMutex lock = null; try { lock = new InterProcessMutex(client, "/test_curator"); boolean res = false; res = lock.acquire(10, TimeUnit.SECONDS); System.out.println("InterProcessMutex not get lock-1" + res); //不阻塞 res = lock.acquire(10, TimeUnit.SECONDS); System.out.println("InterProcessMutex not get lock-2" + res); System.out.println("InterProcessMutex do something"); lock.release(); } catch (Exception e) { e.printStackTrace(); } finally { try { //但是要做两次release操作 lock.release(); //client.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("release lock"); } } /** * 不可重入锁 */ private static void testSemaphoreMutex(CuratorFramework client) { InterProcessSemaphoreMutex lock = null; try { lock = new InterProcessSemaphoreMutex(client, "/test_curator"); boolean res = false; res = lock.acquire(10, TimeUnit.SECONDS); System.out.println("InterProcessSemaphoreMutex not get lock-1" + res); //阻塞,并且返回false res = lock.acquire(10, TimeUnit.SECONDS); System.out.println("InterProcessSemaphoreMutex not get lock-2" + res); System.out.println("InterProcessSemaphoreMutex do something"); //只需一次释放锁 lock.release(); System.in.read(); } catch (Exception e) { e.printStackTrace(); } finally { try { //第二次释放会抛异常 lock.release(); //client.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("release lock"); } } }
package Entities.interfacePackage; /** * * @author Cowteriyaki * @author K * */ public interface Activation { public int timeToInactivation = 40; public void activate(); public void inactivate(double delta); public boolean isActivate(); }
package com.swqs.schooltrade.entity; import java.io.Serializable; import java.util.Date; import java.util.List; import com.swqs.schooltrade.entity.Image; import com.swqs.schooltrade.entity.User; public class Goods implements Serializable{ Integer id; String title; String content; Date createDate; Date editDate; User account; float originalPrice; float curPrice; List<Image> listImage; boolean sell; public boolean isSell() { return sell; } public void setSell(boolean sell) { this.sell = sell; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getEditDate() { return editDate; } public void setEditDate(Date editDate) { this.editDate = editDate; } public User getAccount() { return account; } public void setAccount(User account) { this.account = account; } public float getOriginalPrice() { return originalPrice; } public void setOriginalPrice(float originalPrice) { this.originalPrice = originalPrice; } public float getCurPrice() { return curPrice; } public void setCurPrice(float curPrice) { this.curPrice = curPrice; } public List<Image> getListImage() { return listImage; } public void setListImage(List<Image> listImage) { this.listImage = listImage; } }
package com.celtican.abilities; import com.celtican.BendingWeapons; import com.celtican.stamina.StaminaEntity; import com.celtican.utils.ItemHandler; import com.destroystokyo.paper.ParticleBuilder; import com.projectkorra.projectkorra.BendingPlayer; import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ability.AddonAbility; import com.projectkorra.projectkorra.ability.CoreAbility; import com.projectkorra.projectkorra.ability.FireAbility; import com.projectkorra.projectkorra.util.DamageHandler; import org.bukkit.*; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; public class CinderSlash extends FireAbility implements AddonAbility { private final static float DURATION = 5; private final static float SPEED = 0.5f; // duration x speed = radius in blocks of move private final static float RANGE = 3.5f; private final static float RADIUS = 1.5f; private final static float EXPLODE_RADIUS = 1.5f; private final static float EXPLODE_VELOCITY = 1; private final ParticleBuilder pb; private final Location loc; private int time = 0; public CinderSlash(Player player) { super(player); loc = GeneralMethods.getTargetedLocation(player, RANGE, false, true); loc.setY(player.getLocation().getY()); loc.getWorld().playSound(loc, Sound.BLOCK_FIRE_AMBIENT, SoundCategory.PLAYERS, 1, 1); loc.getWorld().spawnParticle(Particle.LAVA, loc, 15, 0.5f, 0.1f, 0.5f); loc.getWorld().spawnParticle(Particle.SMOKE_LARGE, loc, 10, 1f, 0.1f, 1f, 0); pb = new ParticleBuilder(Particle.FLAME).count(1).extra(0.02); StaminaEntity.getStaminaEntity(player).affect(1); bPlayer.addCooldown(this, ItemHandler.getAttackSpeedInTicks(player, player.getInventory().getItemInMainHand())*50L); List<Entity> entities = GeneralMethods.getEntitiesAroundPoint(loc, RADIUS); for (Entity entity : entities) { if (entity == player.getPlayer()) continue; if (entity instanceof LivingEntity && !entity.isDead()) { loc.getWorld().playSound(((LivingEntity) entity).getEyeLocation(), Sound.ENTITY_PLAYER_HURT_ON_FIRE, SoundCategory.PLAYERS, 1, 1.2f); } entity.setVelocity(entity.getLocation().subtract(loc.clone()).toVector().normalize().multiply(0.5f)); DamageHandler.damageEntity(entity, player.getPlayer(), ItemHandler.getDamage(player.getPlayer()), this); int ticksToBeOnFire = ItemHandler.getAttackSpeedInverseInTicks(player.getPlayer(), player.getInventory().getItemInMainHand()); entity.setFireTicks(entity.getFireTicks() + ticksToBeOnFire); } start(); } public static void leftClick(BendingPlayer player) { if (!player.getPlayer().isSneaking()) return; if (ItemHandler.getType(player.getPlayer().getInventory().getItemInMainHand()) != ItemHandler.ItemType.SWORD) return; if (!player.canBend(CoreAbility.getAbility("CinderSlash"))) return; Material type = player.getPlayer().getEyeLocation().getBlock().getType(); if (type == Material.WATER || type.isSolid()) return; if (!StaminaEntity.getStaminaEntity(player).has(1)) return; new CinderSlash(player.getPlayer()); } public static void rightClick(BendingPlayer player) { if (!player.getPlayer().isSneaking()) return; if (ItemHandler.getType(player.getPlayer().getInventory().getItemInMainHand()) != ItemHandler.ItemType.SWORD) return; if (!player.canBend(CoreAbility.getAbility("CinderSlash"))) return; Material type = player.getPlayer().getEyeLocation().getBlock().getType(); if (type == Material.WATER || type.isSolid()) return; if (!StaminaEntity.getStaminaEntity(player).has(1)) return; Location loc = GeneralMethods.getTargetedLocation(player.getPlayer(), RANGE, false, true); List<Entity> entities = GeneralMethods.getEntitiesAroundPoint(loc, EXPLODE_RADIUS); for (Entity entity : entities) { if (entity == player.getPlayer()) continue; if (entity instanceof LivingEntity && !entity.isDead()) { loc.getWorld().playSound(((LivingEntity) entity).getEyeLocation(), Sound.ENTITY_PLAYER_HURT_ON_FIRE, SoundCategory.PLAYERS, 1, 1.2f); } entity.setVelocity(entity.getLocation().subtract(loc.clone()).toVector().normalize().multiply(EXPLODE_VELOCITY/2)); DamageHandler.damageEntity(entity, player.getPlayer(), ItemHandler.getDamage(player.getPlayer())/2, getAbility("CinderSlash")); int ticksToBeOnFire = ItemHandler.getAttackSpeedInverseInTicks(player.getPlayer(), player.getPlayer().getInventory().getItemInMainHand()) * 2; entity.setFireTicks(entity.getFireTicks() + ticksToBeOnFire); } loc.getWorld().playSound(loc, Sound.BLOCK_FIRE_AMBIENT, SoundCategory.PLAYERS, 1, 1); loc.getWorld().playSound(loc, Sound.ENTITY_GENERIC_EXPLODE, SoundCategory.PLAYERS, 2, 1.5f); loc.add(0, 0.25f, 0); loc.getWorld().spawnParticle(Particle.SMOKE_LARGE, loc, 30, 1.25f, 0, 1.25f, 0.05f); loc.getWorld().spawnParticle(Particle.SMOKE_LARGE, loc, 20, 0.25f, 0.25f, 0.25f, 0.01f); loc.getWorld().spawnParticle(Particle.LAVA, loc, 15, 0.5f, 0.1f, 0.5f); player.getPlayer().setVelocity(player.getPlayer().getEyeLocation().getDirection().multiply(-1 * EXPLODE_VELOCITY)); player.addCooldown("CinderSlash", 600000); // ten minutes. I would put Integer.MAX_VALUE, but I'm setting a limit just in case something happens StaminaEntity.getStaminaEntity(player).affect(1); Bukkit.getScheduler().scheduleSyncDelayedTask(BendingWeapons.main, () -> explodingPlayers.add(player), ItemHandler.getAttackSpeedInTicks(player.getPlayer(), player.getPlayer().getInventory().getItemInMainHand())); } @Override public void progress() { float r = SPEED * time; float circ = (float) (r * Math.PI * 2); for (float i = 0; i <= circ; i += 0.8f) { float theta = (float) ((i/circ) * Math.PI * 2); float x = (float) (loc.getX() + r*Math.cos(theta)); float z = (float) (loc.getZ() + r*Math.sin(theta)); pb.location(loc.getWorld(), x, loc.getY() + 0.1, z).spawn(); } loc.getWorld().playSound(loc, Sound.BLOCK_FIRE_EXTINGUISH, SoundCategory.PLAYERS, 1, 1.5f); if (++time == DURATION) remove(); } @Override public boolean isSneakAbility() { return true; } @Override public boolean isHarmlessAbility() { return false; } @Override public long getCooldown() { return 0; } @Override public Location getLocation() { return loc; } @Override public void load() { } @Override public void stop() {} @Override public String getName() { return "CinderSlash"; } @Override public String getAuthor() { return BendingWeapons.AUTHOR; } @Override public String getVersion() { return BendingWeapons.version; } @Override public String getDescription() { return "§4§nSword-Based Move.\n" + "§4Shift-Left-Click:§c Scatter cinders in front of you and set creatures alight for a short time.\n" + "§4Shift-Right-Click:§c Launch yourself back and set creatures in front of you alight for a moderate time.\n" + "§cDuration of fire stacks."; } private static final ArrayList<BendingPlayer> explodingPlayers = new ArrayList<>(); public static void staticProgress() { for (int i = 0; i < explodingPlayers.size(); i++) if (!explodingPlayers.get(i).getPlayer().isOnline() || explodingPlayers.get(i).getPlayer().isOnGround()) // .isOnGround is the easiest solution, I may improve on this later explodingPlayers.remove(i--).removeCooldown("CinderSlash"); } }
/** * */ package factorys; import java.io.Serializable; import java.util.ArrayList; import exception.CadastroRefeicaoInvalidaException; import restaurante.Prato; import restaurante.Refeicao; import valida.VerificaRefeicao; /** * Fabrica de refeicoes * @author Gabriel Alves - Joao Carlos - Melissa Diniz - Thais Nicoly */ public class FactoryRefeicao implements Serializable{ private static final long serialVersionUID = 1L; public Refeicao criaRefeicao(String nomeRef, String descricaoRef, ArrayList<Prato> componentes) throws CadastroRefeicaoInvalidaException { VerificaRefeicao.verificaNomeRefvazio(nomeRef); VerificaRefeicao.verificaDescVazio(descricaoRef); return new Refeicao(nomeRef, descricaoRef, componentes); } }
package yincheng.gggithub.view.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Handler; import android.os.Looper; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import com.orhanobut.logger.Logger; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import yincheng.gggithub.R; /** * Created by yincheng on 2018/6/14/13:43. * github:luoyincheng */ public class TimerBossProgress extends ViewGroup { private int circleRadius; private int circleMargin; private int circleNum; private int circlrColor; private Timer timer; private TimerTask timerTask; private Handler handler; private List<Animation> shrinkAnimationList; private List<Animation> expandAnimationList; private List<Animation.AnimationListener> shrinkAnimationListenerList; private List<AnimRunnable> animRunnableList; public TimerBossProgress(Context context) { this(context, null); } public TimerBossProgress(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TimerBossProgress(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); Logger.i("---"); final TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TimerBossProgress, defStyleAttr, R.style.ti_BossProgress_default);// TODO: 2018/6/12 作用 try { circleRadius = (int) array.getDimension(R.styleable .TimerBossProgress_ti_circleRadius, 15); circleMargin = (int) array.getDimension(R.styleable.TimerBossProgress_ti_circleMargin, 15); circleNum = array.getInt(R.styleable.TimerBossProgress_ti_circleNum, 3); circlrColor = array.getColor(R.styleable.TimerBossProgress_ti_circleColor, getResources() .getColor(R.color.color_333)); } finally { array.recycle(); } init(); } @Override protected void onVisibilityChanged(@NonNull View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); Logger.i("---"); cancelTimer(); switch (visibility) { case View.GONE: Log.i("fadfasdf", "gone"); cancelAllAnimation(); break; case View.VISIBLE: Log.i("fadfasdf", "visible"); resetAllAnimation(); break; } /** * If you cancel an animation manually, you must call * {@link #reset()}before starting the animation again. */ } private void cancelAllAnimation() { // for (int i = 0; i < getChildCount(); i++) { // getChildAt(i).clearAnimation(); // } // for (Animation animation : shrinkAnimationList) // animation.cancel(); // for (Animation animation : expandAnimationList) // animation.cancel(); // animRunnableList.clear(); // shrinkAnimationListenerList.clear(); } private void resetAllAnimation() { for (Animation animation : shrinkAnimationList) animation.reset(); for (Animation animation : expandAnimationList) animation.reset(); } private void init() { Logger.i("---"); addChildren(); handler = new Handler(Looper.getMainLooper());// TODO: 2018/6/14 to un shrinkAnimationList = new ArrayList<>(); expandAnimationList = new ArrayList<>(); shrinkAnimationListenerList = new ArrayList<>(); animRunnableList = new ArrayList<>(); for (int i = 0; i < getChildCount(); i++) { int currentIndex = i; shrinkAnimationList.add(AnimationUtils.loadAnimation(this.getContext(), R.anim .anim_alpha_shrink)); expandAnimationList.add(AnimationUtils.loadAnimation(this.getContext(), R.anim .anim_alpha_expand)); shrinkAnimationListenerList.add(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { getChildAt(currentIndex).startAnimation(expandAnimationList.get(currentIndex)); } @Override public void onAnimationRepeat(Animation animation) { } }); animRunnableList.add(new AnimRunnable(i)); shrinkAnimationList.get(i).setAnimationListener(shrinkAnimationListenerList.get(i)); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Logger.i("---"); setMeasuredDimension(circleRadius * circleNum * 2 + (circleNum - 1) * circleMargin, circleRadius * 2); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { Logger.i("---"); for (int i = 0; i < getChildCount(); i++) { final View child = getChildAt(i); final int childWidth = circleRadius * 2; final int childHeight = circleRadius * 2; child.layout((childWidth + circleMargin) * i, 0, (childWidth + circleMargin) * i + childWidth, childHeight); } startTimer(); } @Override protected void onAttachedToWindow() { Logger.i("---"); super.onAttachedToWindow(); } private void addChildren() { for (int i = 0; i < circleNum; i++) addView(new TimerBossProgress.RoundedView(this)); } @Override protected void onDetachedFromWindow() { Logger.i("---"); super.onDetachedFromWindow(); cancelTimer(); } @Nullable @Override protected Parcelable onSaveInstanceState() { Logger.i("---"); return super.onSaveInstanceState(); } private void startTimer() { /** * 每次onLayout()都会重新启动timer,导致动画有断层,因此在这里排除timer和timertask正在运行的 */ if (timer != null && timerTask != null) return; cancelTimer(); if (timer == null) timer = new Timer(); if (timerTask == null) timerTask = new TimerTask() { @Override public void run() {//一次性发送四个viewAction到messageQueue中去 for (int i = 0; i < getChildCount(); i++) handler.postDelayed(animRunnableList.get(i), 150 * i); } }; timer.schedule(timerTask, 0, 800); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); Logger.i("---"); } //************************************************************************** private class AnimRunnable implements Runnable { private int viewIndex; public AnimRunnable(int viewIndex) { this.viewIndex = viewIndex; } @Override public void run() { getChildAt(viewIndex).startAnimation(shrinkAnimationList.get(viewIndex)); } } public void cancelTimer() { if (timer != null) { timer.cancel(); timer = null; } if (timerTask != null) { if (timerTask.cancel()) { Log.i("quxiao", "取消成功timertask"); } else { Log.i("quxiao", "取消失败timertask"); } timerTask = null; } } class RoundedView extends View { private int radius; private int color; private Paint paint; public RoundedView(TimerBossProgress parent) { super(parent.getContext()); this.radius = parent.circleRadius; this.color = parent.circlrColor; init(); } void init() { paint = new Paint(); paint.setColor(color); paint.setAntiAlias(true); paint.setStyle(Paint.Style.FILL); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(radius * 2, radius * 2); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(radius, radius, radius, paint); } } }
package Database; import Tools.Utils; public class DatabaseConditions { private int[] cars_first_crossroad; //= {12, 3, 43, 13}; private int[] cars_second_crossroad; //= {12, 4, 31, 2}; private int[] speed_limit_first_crossroad; // = {50, 50, 50, 50} private int[] speed_limit_second_crossroad; // = {50, 50, 50, 50} private int[] actual_speed_first_crossroad; // = {50, 50, 50, 50} private int[] actual_speed_second_crossroad; // = {50, 50, 50, 50} private double initial_time; //123 private double better_time; // 111 private double simulation_time; //222 private double initial_aws; private double better_aws; private double phase_time; private String better_distribution; // "15:5->10:10..." public DatabaseConditions(int[] cars_first_crossroad, int[] cars_second_crossroad, int[] speed_limit_first_crossroad, int[] speed_limit_second_crossroad, int[] actual_speed_first_crossroad, int[] actual_speed_second_crossroad, double initial_time, double better_time, double simulation_time, double initial_aws, double better_aws, double phase_time, String better_distribution) { this.cars_first_crossroad = cars_first_crossroad; this.cars_second_crossroad = cars_second_crossroad; this.speed_limit_first_crossroad = speed_limit_first_crossroad; this.speed_limit_second_crossroad = speed_limit_second_crossroad; this.actual_speed_first_crossroad = actual_speed_first_crossroad; this.actual_speed_second_crossroad = actual_speed_second_crossroad; this.initial_time = initial_time; this.better_time = better_time; this.simulation_time = simulation_time; this.initial_aws = initial_aws; this.better_aws = better_aws; this.phase_time = phase_time; this.better_distribution = better_distribution; } public int[] getCarsFirstCrossroad() { return cars_first_crossroad; } public int[] getCarsSecondCrossroad() { return cars_second_crossroad; } public int[] getSpeedLimitFirstCrossroad() { return speed_limit_first_crossroad; } public int[] getSpeedLimitSecondCrossroad() { return speed_limit_second_crossroad; } public int[] getActualSpeedFirstCrossroad() { return actual_speed_first_crossroad; } public int[] getActualSpeedSecondCrossroad() { return actual_speed_second_crossroad; } public double getInitialTime() { return initial_time; } public double getBetterTime() { return better_time; } public double getInitialAWS() { return initial_aws; } public double getBetterAWS() { return better_aws; } public double getPhaseTime() { return phase_time; } public String toString() { String res = ""; res += "First crossroad: \n" + "cars : " + Utils.arrayToString(cars_first_crossroad) + "\n" + "speed limit : " + Utils.arrayToString(speed_limit_first_crossroad) + "\n" + "actual speed : " + Utils.arrayToString(actual_speed_first_crossroad) + "\n" + "Second crossroad: \n" + "cars : " + Utils.arrayToString(cars_second_crossroad) + "\n" + "speed limit : " + Utils.arrayToString(speed_limit_second_crossroad) + "\n" + "actual speed : " + Utils.arrayToString(actual_speed_first_crossroad) + "\n"; return res; } }
package com.tencent.mm.plugin.boots.a; import com.tencent.mm.kernel.b.d; public interface e extends d { f getTinkerLogic(); }
package ict.kosovo.growth.basic; import java.util.Scanner; public class PrognozaPerNdeshje { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Rezultati i ndeshjes Cekia vs Kosova"); System.out.println("Sa gola shenon ekipi vendas"); int ekipiVendas = sc.nextInt(); System.out.println("Sa gola shenon ekipi mysafir"); int ekipiMysafir = sc.nextInt(); System.out.println("Cekia vs Kosova " + ekipiVendas + " - " + ekipiMysafir); } }
/* * Copyright 2011-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.neo4j.core.mapping.callback; import org.springframework.data.mapping.PersistentPropertyAccessor; import org.springframework.data.neo4j.core.mapping.Neo4jMappingContext; import org.springframework.data.neo4j.core.mapping.Neo4jPersistentEntity; import org.springframework.data.neo4j.core.mapping.Neo4jPersistentProperty; /** * Common logic for retrieving entity metadata from the context and incrementing the version property if necessary. * * @author Michael J. Simons * @soundtrack Body Count - Violent Demise: The Last Days */ final class OptimisticLockingSupport { private final Neo4jMappingContext mappingContext; OptimisticLockingSupport(Neo4jMappingContext mappingContext) { this.mappingContext = mappingContext; } Object getAndIncrementVersionPropertyIfNecessary(Object entity) { Neo4jPersistentEntity<?> neo4jPersistentEntity = (Neo4jPersistentEntity<?>) mappingContext .getRequiredNodeDescription(entity.getClass()); if (!neo4jPersistentEntity.hasVersionProperty()) { return entity; } PersistentPropertyAccessor<Object> propertyAccessor = neo4jPersistentEntity.getPropertyAccessor(entity); Neo4jPersistentProperty versionProperty = neo4jPersistentEntity.getRequiredVersionProperty(); if (!Long.class.isAssignableFrom(versionProperty.getType())) { return entity; } Long versionPropertyValue = (Long) propertyAccessor.getProperty(versionProperty); long newVersionValue = 0; if (versionPropertyValue != null) { newVersionValue = versionPropertyValue + 1; } propertyAccessor.setProperty(versionProperty, newVersionValue); return propertyAccessor.getBean(); } }
package action; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import svc.MemberDeleteService; import vo.ActionForward; public class MemberDeleteAction implements Action { public ActionForward execute(HttpServletRequest request,HttpServletResponse response) throws Exception{ ActionForward forward = null; String member_id = request.getParameter("member_id"); MemberDeleteService memberDeleteService = new MemberDeleteService(); boolean isDeleteSuccess = memberDeleteService.deleteMember(member_id); if(!isDeleteSuccess){ response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<script>"); out.println("alert('삭제 실패');"); out.println("history.back();"); out.println("</script>"); out.close(); } else { forward = new ActionForward(); forward.setRedirect(true); forward.setPath("memberListAction.do"); } return forward; } }
package com.ibanity.apis.client.http.handler; import com.ibanity.apis.client.exceptions.IbanityClientException; import com.ibanity.apis.client.exceptions.IbanityServerException; import com.ibanity.apis.client.jsonapi.ErrorResourceApiModel; import com.ibanity.apis.client.models.IbanityError; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ResponseHandler; import java.io.IOException; import java.util.List; import static com.ibanity.apis.client.utils.IbanityUtils.objectMapper; public class IbanityResponseHandler implements ResponseHandler<String> { private static final int CLIENT_ERROR = 400; private static final int SERVER_ERROR = 500; private static final String DEFAULT_ENCODING = "UTF-8"; @Override public String handleResponse(HttpResponse httpResponse) throws IOException { int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode >= SERVER_ERROR) { throw new IbanityServerException(parseErrors(httpResponse), statusCode); } else if (statusCode >= CLIENT_ERROR) { throw new IbanityClientException(parseErrors(httpResponse), statusCode); } return readResponseContent(httpResponse.getEntity()); } private List<IbanityError> parseErrors(HttpResponse httpResponse) { try { String payload = readResponseContent(httpResponse.getEntity()); return objectMapper().readValue(payload, ErrorResourceApiModel.class).getErrors(); } catch (Exception exception) { throw new RuntimeException("Invalid payload", exception); } } private static String readResponseContent(HttpEntity entity) throws IOException { return IOUtils.toString(entity.getContent(), DEFAULT_ENCODING); } }
package bloomfilter; import java.util.BitSet; public class BloomFilterHelper { public static SimpleBloomFilter OR(SimpleBloomFilter b0, SimpleBloomFilter b1) { int totalElements = b0.getTotalElements() + b1.getTotalElements(); BitSet bb0 = b0.getBitSet(); BitSet bb1 = b1.getBitSet(); BitSet bb = new BitSet(b0.getSize() > b1.getSize() ? b0.getSize() : b1.getSize()); bb.or(bb0); bb.or(bb1); return new SimpleBloomFilter(totalElements, bb); } public static SimpleBloomFilter AND(SimpleBloomFilter b0, SimpleBloomFilter b1) { BitSet bb0 = b0.getBitSet(); BitSet bb1 = b1.getBitSet(); BitSet bb = new BitSet(b0.getSize() > b1.getSize() ? b0.getSize() : b1.getSize()); bb.set(0, bb.size()); bb.and(bb0); bb.and(bb1); return new SimpleBloomFilter(bb.cardinality(), bb); } public static SimpleBloomFilter XOR(SimpleBloomFilter b0, SimpleBloomFilter b1) { BitSet bb0 = b0.getBitSet(); BitSet bb1 = b1.getBitSet(); BitSet bb = new BitSet(b0.getSize() > b1.getSize() ? b0.getSize() : b1.getSize()); bb.xor(bb0); bb.xor(bb1); return new SimpleBloomFilter(bb.cardinality(), bb); } }
import java.awt.Component; import java.awt.MediaTracker; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; public class SpriteManager { private static int TILE_W = 8; private static int TILE_H = 8; private String path; private BufferedImage spriteSheet; private Player player; public SpriteManager(String path, GamePanel pl) { this.path = path; try { spriteSheet = ImageIO.read(this.getClass().getResourceAsStream(path)); } catch (IOException e) { e.printStackTrace(); } for (int y = 0; y < spriteSheet.getHeight(); ++y) { for (int x = 0; x < spriteSheet.getWidth(); ++x) { int argb = spriteSheet.getRGB(x, y); if ((argb & 0x00FFFFFF) == 0x00FF00FF) { spriteSheet.setRGB(x, y, 0); } } } spriteSheet.getAlphaRaster(); createPlayer(pl); } private void createPlayer(Component comp) { BufferedImage playerImage = null; playerImage = spriteSheet.getSubimage(0, 0, TILE_W*4, TILE_H*4); } public Player getPlayer() { return player; } }
package com.epam.strings.text.expression.terminal; import com.epam.strings.text.expression.context.Context; public interface MathOperation { void interpret(Context context); }
/* * Copyright 2016 Johns Hopkins University * * 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. */ /** * Provides annotations used to map Java classes and members to OWL individuals and properties. * <p> * Java classes annotated with {@code @OwlIndividual} will have instances of those classes represented in RDF as an * OWL individual. Each class possessing the {@code @OwlIndividual} annotation should have exactly one field annotated * {@code @IndividualUri}, to be used as the resource identifier of the {@code @OwlIndividual}. * </p> * <p> * Class members annotated with {@code @OwlProperties} will be represented in RDF as an OWL Datatype property or Object * property, depending on the value of the annotation. The subject of the property will be the {@code @OwlIndividual}, * and the object of the property will be the value of the annotated field. * </p> * <p> * The values of class members may be transformed prior to being represented in RDF. The {@code @IndividualUri} and * {@code @OwlProperties} annotation possess a {@code transform} attribute, which specifies a * {@code Class<Function<Object,String>>} to be applied to the field value prior to being serialized as RDF. * </p> * * @author Elliot Metsger (emetsger@jhu.edu) */ package org.dataconservancy.cos.rdf.annotations;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package vista.lugaresDespripcion; import vista.ListaDePaquetes; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * * @author Alan */ public class LugaresOruro extends JFrame implements ActionListener{ JPanel panel = new JPanel(); private JComboBox lista; private JButton foto1,foto2,foto3,foto4; public LugaresOruro() { setTitle("Lugares Turisticos"); setBounds(500, 200, 1080, 800); setLocationRelativeTo(null); this.getContentPane().setBackground(new Color(32, 112, 193)); iniciarComponentes(); } private void iniciarComponentes() { colocarPaneles(); colocarEtiqueta(); colocarListaDesplegable(); colocarAreaDeTexto(); colocarBotones(); } private void colocarBotones(){ Button boton1 = new Button("paquetes"); boton1.setBounds(380,290,100,40); panel.add(boton1); ActionListener ac2 = new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { ListaDePaquetes v2 = new ListaDePaquetes("Oruro"); v2.setVisible(true); } }; boton1.addActionListener(ac2); Button boton2 = new Button("paquetes"); boton2.setBounds(380,490,100,40); panel.add(boton2); ActionListener ac3 = new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { ListaDePaquetes v2 = new ListaDePaquetes("Oruro"); v2.setVisible(true); } }; boton2.addActionListener(ac3); Button boton3 = new Button("paquetes"); boton3.setBounds(875,290,100,40); panel.add(boton3); ActionListener ac4 = new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { ListaDePaquetes v2 = new ListaDePaquetes("Oruro"); v2.setVisible(true); } }; boton3.addActionListener(ac4); Button boton4 = new Button("paquetes"); boton4.setBounds(875,490,100,40); panel.add(boton4); ActionListener ac5 = new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { ListaDePaquetes v2 = new ListaDePaquetes("Oruro"); v2.setVisible(true); } }; boton4.addActionListener(ac5); } private void colocarPaneles() { panel.setBackground(new Color(32, 112, 193)); panel.setLayout(null); this.getContentPane().add(panel); } private void colocarEtiqueta() { JLabel etiqueta = new JLabel("AGENCIA DE VIAJES", SwingConstants.LEFT);//crea la etiqueta panel.add(etiqueta); etiqueta.setBounds(10, 0, 500, 50); etiqueta.setForeground(Color.white); etiqueta.setFont(new Font("arial", Font.BOLD, 30)); //imagen1 ImageIcon imagen1 = new ImageIcon(getClass().getResource("/vista/LugaresTuristicos/Oruro/ElCarnaval/icono.jpg")); foto1 = new JButton(); foto1.setBounds(50,180,250,150); foto1.setIcon(new ImageIcon(imagen1.getImage().getScaledInstance(300,200,4))); foto1.addActionListener(this); panel.add(foto1); //imagen2 ImageIcon imagen2 = new ImageIcon(getClass().getResource("/vista/LugaresTuristicos/Oruro/CalaCala/icono.jpg")); foto2 = new JButton(); foto2.setBounds(550,180,250,150); foto2.setIcon(new ImageIcon(imagen2.getImage().getScaledInstance(300,200,4))); foto2.addActionListener(this); panel.add(foto2); //imagen3 ImageIcon imagen3 = new ImageIcon(getClass().getResource("/vista/LugaresTuristicos/Oruro/SalarDeCoipasa/icono.jpg")); foto3 = new JButton(); foto3.setBounds(50,380,250,150); foto3.setIcon(new ImageIcon(imagen3.getImage().getScaledInstance(300,200,4))); foto3.addActionListener(this); panel.add(foto3); //imagen4 ImageIcon imagen4 = new ImageIcon(getClass().getResource("/vista/LugaresTuristicos/Oruro/SantuarioDeLaVirgenDelSocavon/icono.jpg")); foto4 = new JButton(); foto4.setBounds(550,380,250,150); foto4.setIcon(new ImageIcon(imagen4.getImage().getScaledInstance(300,200,4))); foto4.addActionListener(this); panel.add(foto4); } private void colocarListaDesplegable(){ String[] opciones = {"La Paz","Cochabamba","Santa Cruz","Oruro","Potosí","Chuquisaca","Tarija","Beni","Pando"}; lista = new JComboBox(opciones); lista.setBounds(430,100,200,30); lista.setSelectedItem("Oruro"); lista.addActionListener(this); panel.add(lista); } private void colocarAreaDeTexto() { JTextArea contactanos = new JTextArea(); contactanos.setBounds(50, 610, 300, 300); contactanos.setBackground(null); contactanos.setForeground(Color.white); contactanos.setText("Contáctanos: \nAv. Ayacucho entre Colombia y Ecuador \n+591 62615493 \n4 4446666 \nCochabamba-Bolivia"); panel.add(contactanos); //Descripcion JTextArea descripcion1 = new JTextArea("El Carnaval de Oruro" +"\nUno de los grandes patrimonios de " + "\nBolivia, ofreciendo una de las fiestas" + "\nmas grandes de cultura general." + "\nVe y disfruta de nuestro Carnaval " + "\nademas de nuestro excelentes precios."); descripcion1.setBounds(320, 180, 220, 100); descripcion1.setBackground(null); descripcion1.setForeground(Color.white); panel.add(descripcion1); JTextArea descripcion2 = new JTextArea("El Salar de Coipasa" +"\nUna de las maravillas que nos ofrece " + "\nBolivia, junto a su majestuoso manto " + "\nblanco que junto en epoca de lluvias" + "\nse nota los efectos mas hermosos." + "\nAproveche nuestros excelentes precios"); descripcion2.setBounds(320, 385, 220, 100); descripcion2.setBackground(null); descripcion2.setForeground(Color.white); panel.add(descripcion2); JTextArea descripcion3 = new JTextArea("Cala Cala" +"\nUn lugar cuya descripcion no puede " + "\nofrecer bastante conocimiento al" + "\nrespecto de las antiguas culturas" + "\nque convivian en dicho lugar, a " + "\ntraves del arte rupestre."); descripcion3.setBounds(815, 180, 220, 100); descripcion3.setBackground(null); descripcion3.setForeground(Color.white); panel.add(descripcion3); JTextArea descripcion4 = new JTextArea("El Santuario de la Virgen del Socavon" +"\nUna escultura que no contempla años" + "\nde antiguedad, sino la importancia" + "\nque se le da por parte de toda la" + "\npoblacion de Oruro a la cual otorgo " + "\ndurante todo este tiempo."); descripcion4.setBounds(815, 385, 220, 100); descripcion4.setBackground(null); descripcion4.setForeground(Color.white); panel.add(descripcion4); } public void actionPerformed (ActionEvent e){ String elemento = (String)lista.getSelectedItem(); if (elemento.equals("Oruro") == true){ LugaresOruro ventana = new LugaresOruro(); this.setVisible(false); ventana.setVisible(true); } if (elemento.equals("Potosí") == true){ LugaresPotosi ventana = new LugaresPotosi(); this.setVisible(false); ventana.setVisible(true); } if (elemento.equals("Chuquisaca") == true){ LugaresChuquisaca ventana = new LugaresChuquisaca(); this.setVisible(false); ventana.setVisible(true); } if (elemento.equals("Tarija") == true){ LugaresTarija ventana = new LugaresTarija(); this.setVisible(false); ventana.setVisible(true); } if (elemento.equals("Beni") == true){ LugaresBeni ventana = new LugaresBeni(); this.setVisible(false); ventana.setVisible(true); } if (elemento.equals("La Paz") == true){ LugaresLaPaz ventana = new LugaresLaPaz(); this.setVisible(false); ventana.setVisible(true); ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } if (elemento.equals("Cochabamba") == true){ LugaresCochabamba ventana = new LugaresCochabamba(); this.setVisible(false); ventana.setVisible(true); ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } if (elemento.equals("Santa Cruz") == true){ LugaresSantaCruz ventana = new LugaresSantaCruz(); this.setVisible(false); ventana.setVisible(true); ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } if (elemento.equals("Pando") == true){ LugaresPando ventana = new LugaresPando(); this.setVisible(false); ventana.setVisible(true); ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } if (e.getSource()== foto1 ){ OruroElCarnaval nuevo = new OruroElCarnaval(); nuevo.setVisible(true); nuevo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } if (e.getSource()== foto2 ){ OruroCalaCala nuevo = new OruroCalaCala(); nuevo.setVisible(true); nuevo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } if (e.getSource()== foto3 ){ OruroSalarCoipasa nuevo = new OruroSalarCoipasa(); nuevo.setVisible(true); nuevo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } if (e.getSource()== foto4 ){ OruroVirgenSocavon nuevo = new OruroVirgenSocavon(); nuevo.setVisible(true); nuevo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } }
package com.example.dangkymonhoc; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import com.example.impl.myOnClickListener; public class DialogSinhVien extends Dialog { public DialogSinhVien(Context context, myOnClickListener myclick) { super(context); this.myListener = myclick; } myOnClickListener myListener; @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.dialog_sinh_vien); final EditText edtTen=findViewById(R.id.edtTenSinhVien); final EditText edtMa=findViewById(R.id.edtMaSinhVien); final EditText edtPhone=findViewById(R.id.edtPhone); final EditText edtPass=findViewById(R.id.edtPassword); Button btnLuu = (Button) findViewById(R.id.btnLuuSinhVien); btnLuu.setOnClickListener(new android.view.View.OnClickListener() { @Override public void onClick(View arg0) { myListener.onButtonClick(edtTen.getText().toString(),edtMa.getText().toString(),edtPhone.getText().toString(),edtPass.getText().toString()); edtMa.setText(""); edtPass.setText(""); edtPhone.setText(""); edtTen.setText(""); } }); Button btnHuy=findViewById(R.id.btnHuySinhVien); btnHuy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); } }
package com.wentongwang.mysports.views.fragment.home; import android.content.Context; import com.wangwentong.sports_api.interactor.InteractorCallback; import com.wangwentong.sports_api.interactor.SportsInteractor; import com.wangwentong.sports_api.model.SportsFirstClass; import com.wangwentong.sports_api.model.SportsSecondClass; import com.wentongwang.mysports.utils.Logger; import com.wentongwang.mysports.utils.ToastUtil; import java.util.List; /** * Created by Wentong WANG on 2016/10/13. */ public class HomeFragPresenter { private HomeFragView mView; private Context mContext; private List<SportsFirstClass> sportsList; private SportsInteractor sportsInteractor; public HomeFragPresenter(HomeFragView view) { mView = view; } /** * initial presenter * get Activity context * initial VolleyRequestManager * * @param context */ public void init(Context context) { this.mContext = context; this.sportsInteractor = new SportsInteractor(); } public void getSportEvents() { sportsInteractor.getSportEvents("001", new InteractorCallback<List<SportsFirstClass>>() { @Override public void onSuccess(List<SportsFirstClass> result) { mView.hideProgressBar(); mView.setHomeEventList(result); for (int i = 0; i < result.size(); i++) { List<SportsSecondClass> listSecond = result.get(i).getSports(); mView.SportsEventDetail(listSecond); } } @Override public void onFailed(String error) { mView.hideProgressBar(); Logger.e(error); ToastUtil.show(mContext, error, 1500); } }); } public void goToEventDetail(int groupPosition, int childPosition) { SportsSecondClass item = sportsList.get(groupPosition).getSports().get(childPosition); mView.goToEventDetail(item); } }
package and.controller; import and.model.Train; import and.service.TrainService; import java.io.IOException; import java.sql.SQLException; /** * Created by zephyr on 7/8/15. */ public class TrainController extends javax.servlet.http.HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { Train train; int[][] input = new int[2][4]; for(int i=0;i<2;i++){ for(int j=0;j<4;j++){ input[i][j] = Integer.parseInt(request.getParameter("input"+i+j)); } } /*for(int i=0;i<2;i++){ for(int j=0;j<4;j++){ System.out.println(input[i][j]); } }*/ float[] weight = new float[2]; for(int i=0;i<2;i++){ weight[i] = Float.parseFloat(request.getParameter("initweight" + i)); } /*for (float x : weight){ System.out.println(x); }*/ train=new Train(input,weight); TrainService service = null; try { service = new TrainService(); } catch (Exception e) { e.printStackTrace(); } Train trained = service.calculateWeight(train); float[] finWeight=trained.getWeights(); int it=trained.getIt(); try { service.storeWeights(finWeight); } catch (SQLException e) { e.printStackTrace(); } /*System.out.println(finWeight[0]); System.out.println(finWeight[1]);*/ request.setAttribute("weight1",finWeight[0]); request.setAttribute("weight2",finWeight[1]); request.setAttribute("iter",it); request.getRequestDispatcher("/view/train.jsp").forward(request,response); } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { } }
package com.e6soft.bpm; import java.util.HashMap; import java.util.Map; import javax.el.ExpressionFactory; import javax.el.ValueExpression; import org.junit.Test; import de.odysseus.el.util.SimpleContext; public class LearnTest { @Test public void test1() throws Exception{ ExpressionFactory factory = new de.odysseus.el.ExpressionFactoryImpl();// SimpleContext context = new de.odysseus.el.util.SimpleContext(); context.setFunction("math", "max", Math.class.getMethod("max", int.class, int.class)); context.setVariable("foo", factory.createValueExpression(0, int.class)); ValueExpression e = factory.createValueExpression(context, "${math:max(foo,bar)}", int.class); factory.createValueExpression(context, "${bar}", int.class).setValue(context, 1); System.out.println(e.getValue(context)); } @Test public void test2(){ ExpressionFactory factory = new de.odysseus.el.ExpressionFactoryImpl();// SimpleContext context = new de.odysseus.el.util.SimpleContext(); context.setVariable("param", factory.createValueExpression(1, int.class)); ValueExpression e1 = factory.createValueExpression(context, "${param>3}", Boolean.class); System.out.println(e1.getValue(context)); context.setVariable("param", factory.createValueExpression(11, int.class)); ValueExpression e2 = factory.createValueExpression(context, "${param>3}", Boolean.class); System.out.println(e2.getValue(context)); Map<String,Integer> param = new HashMap<String, Integer>(); param.put("a", 1); context.setVariable("param", factory.createValueExpression(param, Map.class)); ValueExpression e3 = factory.createValueExpression(context, "${param.a>3}", Boolean.class); System.out.println(e3.getValue(context)); param.put("a", 11); context.setVariable("param", factory.createValueExpression(param, Map.class)); ValueExpression e4 = factory.createValueExpression(context, "${param.a>3}", Boolean.class); System.out.println(e4.getValue(context)); } }
package com.estaine.colors.dto; import lombok.Data; @Data public class ValidateRequest { private String colors; }
package com.momori.wepic.model; import com.momori.wepic.WepicApplication; import java.util.ArrayList; import java.util.List; /** * Created by Hyeon on 2015-04-26. */ public class InviteModel { private WepicApplication context; private List<UserModel> inviteList; private List<String> selectedList; public InviteModel(){ this.context = WepicApplication.getInstance(); } public List<UserModel> getInviteList() { if(inviteList==null){ inviteList= this.context.getFbComponent().getFbFriendsList(); } return inviteList; } public void setInviteList(List<UserModel> inviteList) { this.inviteList = inviteList; } public List<String> getSelectedList() { if(selectedList==null){ this.selectedList = new ArrayList<>(); } return selectedList; } public void setSelectedList(List<String> selectedList) { this.selectedList = selectedList; } public void addSelectedExternal_id(String external_id){ getSelectedList().add(external_id); } public void removeSelectedExternal_id(String external_id){ getSelectedList().remove(external_id); } public int getSelectedCount(){ if(this.selectedList==null) return 0; return this.selectedList.size(); } }
package com.consumer; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import com.model.Address; import com.model.Customer; import com.model.CustomerStatus; import com.utils.Utils; @SpringBootTest public class CustomerJsonTest { @Autowired private Utils utils; private final Logger LOG = LoggerFactory.getLogger(CustomerJsonTest.class); @Test public void getJsonStringTest() { LOG.info("getJsonStringTest() started"); Customer customer = new Customer("C000000002", "Mahesh", "Manchala", "05-07-1982", "INDIA", "IN", "9493971459"); customer.setEmail("maheshmanchala92@gmail.com"); customer.setCustomerStatus(CustomerStatus.RESTORED); Address address = new Address(); address.setAddressLine1("1-25/2 SHEKALLA"); address.setAddressLine2("GOLLAPELLI"); address.setStreet("TELANGANA"); address.setPostalCode("50553"); customer.setAddress(address); String stringJson = utils.getJsonString(customer); assertEquals("{\"customerNumber\":\"C000000002\",\"firstName\":\"Mahesh\",\"lastName\":\"Manchala\"," + "\"birthdate\":\"05-07-1982\",\"country\":\"INDIA\",\"countryCode\":\"IN\"," + "\"mobileNumber\":\"9493971459\",\"email\":\"maheshmanchala92@gmail.com\"," + "\"customerStatus\":\"RESTORED\",\"address\":{\"addressLine1\":\"1-25/2 SHEKALLA\"," + "\"addressLine2\":\"GOLLAPELLI\",\"street\":\"TELANGANA\",\"postalCode\":\"50553\"}}",stringJson); LOG.info(stringJson); LOG.info("getJsonStringTest() completed"); } }
/* * Copyright (C) 2010-2012, Wan Lee, wan5332@gmail.com * Source can be obtained from git://github.com/wanclee/datashaper.git * BSD-style license. Please read license.txt that comes with source files */ /** * */ package com.psrtoolkit.datashaper.structure; import java.util.Arrays; import com.psrtoolkit.datashaper.exception.DataShaperException; /** * Dynamic array of primitive long types. <p> The data structure should be used * in place of java.util.ArrayList<Long> when a large number of long values are * used and purged frequently. DataShapers keeps thousands of record ID in * memory and throw them away when they are no longer need; therefore, * performance can be achieved by avoiding the use of java.lang.Long wrapper * class and java.util.ArrayList * * @author Wan * */ public class DynamicLongArray { long[] longArr = null; int defaultSize = 100; //marker for the last indexed cell in the array; //it is not the length of the array int lastPos = 0; public DynamicLongArray() { longArr = new long[defaultSize]; } /** * @param size the size of array to be used in the array initialization; if * size < defaultSize (which is 100), the default size will be used instead * @exception throws DataShaperException runtime exception; */ public DynamicLongArray(int size) { //TODO: handle size > Integer.MAX_VALUE scenario if (size <= 0) { throw new DataShaperException("Error: dynamic long array cannot be" + " initialized with zeor or negative size value)"); } if (size < defaultSize) { longArr = new long[defaultSize]; } else { longArr = new long[size]; } lastPos = 0; } /** * Get the element at the indexed position in the array * * @param position the zero-based integer value * @return the long value at the indexed position * @exception throws DataShaperException runtime exception; wraps * ArrayIndexOutOfBoundsException when it occurred */ public long get(int position) { if (position < 0) { StringBuilder message = new StringBuilder(200); message.append("Error: index to the dynamic long array").append(" cannot be negative (").append(position).append(")"); throw new DataShaperException(message.toString(), new ArrayIndexOutOfBoundsException()); } if (position >= longArr.length) { StringBuilder message = new StringBuilder(200); message.append("Error: index (").append(position).append(")").append(" is outside the dynamic long array boundary (").append(longArr.length).append(")"); throw new DataShaperException(message.toString(), new ArrayIndexOutOfBoundsException()); } return longArr[position]; } /** * Set into the array the value at the indexed position If the array is too * small, grow the array to the position value + default size and move the * last indexed position marker down * * @param position the zero-based integer value * @param value the long value to be placed in the indexed position * @exception throws DataShaperException runtime exception; wraps * ArrayIndexOutOfBoundsException when it occurred */ public void set(int position, long value) { if (position < 0) { StringBuilder message = new StringBuilder(200); message.append("Error: index to the dynamic long array").append(" cannot be negative (").append(position).append(")"); throw new DataShaperException(message.toString(), new ArrayIndexOutOfBoundsException()); } if (lastPos > longArr.length) { StringBuilder message = new StringBuilder(200); message.append("Error: internal state is inconsistent - the last ").append("indexed position (").append(lastPos).append(")").append(" is greater than the size of the array (").append(longArr.length).append(")"); throw new DataShaperException(message.toString()); } if (position >= longArr.length) { long[] temp = new long[position + defaultSize]; System.arraycopy(longArr, 0, temp, 0, longArr.length); longArr = temp; lastPos = position + 1; } else { if (position >= lastPos) { lastPos = position + 1; } } longArr[position] = value; } /** * Add the value to the last unoccupied cell of the array. If the array is * too small, grow the array by the default size and move the last indexed * position marker down * * @param value the primitive long value to be added to the last unoccupied * array cell * @exception throws DataShaperException runtime exception; */ public void add(long value) { if (lastPos > longArr.length) { StringBuilder message = new StringBuilder(200); message.append("Error: internal state is inconsistent - the last ").append("indexed position (").append(lastPos).append(")").append(" is greater than the size of the array (").append(longArr.length).append(")"); } if (lastPos == longArr.length) { long[] temp = new long[longArr.length + defaultSize]; System.arraycopy(longArr, 0, temp, 0, longArr.length); longArr = temp; } longArr[lastPos] = value; lastPos++; //move the last indexed position marker down } /** * Return the current physical length of the array * * @return the length of the array */ public int length() { return longArr.length; } /** * Return the last indexed position of the array This is the logical length * of the array. * * @return the last indexed position of the array; indicating the first * unoccupied cell position. */ public int lastpos() { return lastPos; } /** * Set the content of the array to 0L */ public void clear() { Arrays.fill(longArr, 0L); lastPos = 0; } //public void setlastpos(int lastpos) { this.lastPos = lastpos;} }
package com.mxf.course.service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.mxf.course.config.ScExtException; import com.mxf.course.dao.SquidMapper; import com.mxf.course.entity.SquidEntity; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by baimao * Time:2021/5/25 */ @Service public class SquidService { @Resource SquidMapper squidMapper; public PageInfo selectSquidByConditions(int currentPage, int pageSize, String name, String port,String ip){ PageHelper.startPage(currentPage,pageSize); List<SquidEntity> squidEntityList = squidMapper.selectAllSquidByConditions(port,ip,name); PageInfo pageInfo = new PageInfo(squidEntityList); return pageInfo; } public String insertSquid(String name,int port ) throws ScExtException { if (squidMapper.selectSquidByName(name)!=null){ throw new ScExtException("请勿重复添加相同地址"); } if (squidMapper.selectSquidByPorts(port)!=null){ throw new ScExtException("该端口已占用"); } String[] ips = name.split("\n"); String ip = name; if (ips.length > 1){ ip = ips[1]; } System.out.println(ip); SquidEntity squidEntity = new SquidEntity(); squidEntity.setName(name); squidEntity.setIp(ip); squidEntity.setDate(new Date()); squidEntity.setOutport(port); squidEntity.setStatus(0); if (squidMapper.insertSelective(squidEntity)<0){ throw new ScExtException("添加Squid失败"); } return "success"; } public String updateSquid(int port,int status) throws ScExtException { SquidEntity squidEntity = squidMapper.selectSquidByPorts(port); if (squidEntity==null){ throw new ScExtException("该主机未注册到服务器"); } squidEntity.setStatus(status); if (squidMapper.updateByPrimaryKeySelective(squidEntity)<0){ throw new ScExtException("修改Squid失败"); } return "success"; } public List<Integer> selectAllSquidPort(){ List<Integer> ports = squidMapper.selectAllPorts(); return ports; } }
package com.incuube.bot.services.util; import org.springframework.core.Ordered; public class HandlerOrderConstants { public static final int USER_HANDLER_VALUE = Ordered.HIGHEST_PRECEDENCE; public static final int ACTION_HANDLER_VALUE = 0; public static final int VALIDATION_HANDLER_VALUE = 100; public static final int PARAMS_DB_HANDLER_VALUE = 200; public static final int NEXT_ACTION_HANDLER_VALUE = Ordered.LOWEST_PRECEDENCE; }
import java.io.IOException; import java.io.FileOutputStream; import java.util.ArrayList; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; public class XmlSaveEngine { public void saveGame(String fileName, Board board, ArrayList<Player> players, int playerOnTurn) throws XMLStreamException { try { FileOutputStream outputStream = new FileOutputStream(fileName); XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory(); XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(outputStream); xmlStreamWriter.writeStartDocument(); xmlStreamWriter.writeStartElement("Evade"); xmlStreamWriter.writeStartElement("History"); for(Turn turn : board.getHistory()) { xmlStreamWriter.writeStartElement("Turn"); Position from = turn.getFrom(); xmlStreamWriter.writeStartElement("From"); xmlStreamWriter.writeStartElement("Row"); xmlStreamWriter.writeCharacters(Integer.toString(from.getRow())); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("Column"); xmlStreamWriter.writeCharacters(Integer.toString(from.getColumn())); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); Position to = turn.getTo(); xmlStreamWriter.writeStartElement("To"); xmlStreamWriter.writeStartElement("Row"); xmlStreamWriter.writeCharacters(Integer.toString(to.getRow())); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("Column"); xmlStreamWriter.writeCharacters(Integer.toString(to.getColumn())); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); } xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("Players"); for (int i = 0; i < players.size(); i++) { Player player = players.get(i); xmlStreamWriter.writeStartElement("Player"); xmlStreamWriter.writeAttribute("type", player.getClass().getName()); xmlStreamWriter.writeStartElement("Name"); xmlStreamWriter.writeCharacters(player.getName()); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("OnTurn"); xmlStreamWriter.writeCharacters(Boolean.valueOf(i == playerOnTurn).toString()); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("Level"); xmlStreamWriter.writeCharacters(player.getLevel().toString()); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("Sign"); xmlStreamWriter.writeCharacters(Integer.toString(player.getSign())); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); } xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.flush(); xmlStreamWriter.close(); outputStream.flush(); outputStream.close(); } catch (XMLStreamException e) { e.printStackTrace(); throw e; } catch (IOException e) { e.printStackTrace(); } } }
/* * Copyright 2017 University of Michigan * * 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 edu.umich.verdict.relation; import java.util.ArrayList; import java.util.List; import edu.umich.verdict.relation.expr.SelectElem; /** * Indicates that {@link SampleGroup#elems} can be computed by joining * {@link SampleGroup#sample}. * * @author Yongjoo Park * */ public class SampleGroup { private ApproxRelation sample; private List<SelectElem> elems; // private double cost; /** * * @param sample * ApproxRelation instance * @param elems * Expressions that can be answered using the sample. */ public SampleGroup(ApproxRelation sample, List<SelectElem> elems) { this.sample = sample; this.elems = new ArrayList<SelectElem>(); this.elems.addAll(elems); } public ApproxRelation getSample() { return sample; } public void setSample(ApproxRelation a) { sample = a; } public double samplingProb() { return sample.samplingProbability(); } public double cost() { return sample.cost(); } public String sampleType() { return sample.sampleType(); // String type = null; // for (ApproxRelation param : samples) { // if (type == null) { // type = param.sampleType; // } else { // if (type.equals("uniform")) { // if (param.sampleType.equals("stratified")) { // type = "stratified"; // } else { // type = "uniform"; // } // } else if (type.equals("stratified")) { // type = "stratified"; // } else if (type.equals("universe")) { // type = "universe"; // } // } // } // return type; } public List<SelectElem> getElems() { return elems; } // public Set<SampleParam> sampleSet() { // return samples; // } @Override public String toString() { return elems.toString() + " =>\n" + sample.toString(); } public boolean isEqualSample(SampleGroup o) { return sample.equals(o.getSample()); } public void addElem(List<SelectElem> e) { elems.addAll(e); } // public Pair<Set<SampleParam>, List<Expr>> unroll() { // return Pair.of(samples, elems); // } public SampleGroup duplicate() { // Set<SampleParam> copiedSamples = new HashSet<SampleParam>(samples); List<SelectElem> copiedElems = new ArrayList<SelectElem>(elems); return new SampleGroup(sample, copiedElems); } }
package com.spsc.szxq.url; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Url; /** * Created by allens on 2017/3/9. */ public interface IServices { @GET Call<ResponseBody> getAdressData(@Url String url); }
package com.rofour.baseball.dao.manager.bean; import java.util.Date; /** * @ClassName: MonitorContactsBean * @Description: 监控联系人实体 * @author: xulang * @Date: 2016-08-22 13:50 */ public class MonitorContactsBean { /** * 主键 */ private Long monitorContactId; /** * 监控项ID */ private Long monitorId; /** * 联系人姓名 */ private String contactName; /** * 联系电话 */ private String phone; /** * 邮箱 */ private String email; /** * 产生日期 */ private Date createTime; public MonitorContactsBean(Long monitorContactId, Long monitorId, String contactName, String phone, String email, Date createTime) { this.monitorContactId = monitorContactId; this.monitorId = monitorId; this.contactName = contactName; this.phone = phone; this.email = email; this.createTime = createTime; } public MonitorContactsBean() { super(); } public Long getMonitorContactId() { return monitorContactId; } public void setMonitorContactId(Long monitorContactId) { this.monitorContactId = monitorContactId; } public Long getMonitorId() { return monitorId; } public void setMonitorId(Long monitorId) { this.monitorId = monitorId; } public String getContactName() { return contactName; } public void setContactName(String contactName) { this.contactName = contactName == null ? null : contactName.trim(); } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone == null ? null : phone.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
package com.momori.wepic.presenter.inter; import android.content.Intent; /** * Created by Hyeon on 2015-04-18. */ public interface StartPresenter { public boolean isReadyToLogin(); public void startLogin(); public void onActivityResult(int requestCode, int resultCode, Intent data); }
package com.tencent.mm.plugin.bottle.ui; import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; public class ThrowBottleFooter extends LinearLayout { private a hnc; public ThrowBottleFooter(Context context, AttributeSet attributeSet) { super(context, attributeSet); } protected void onLayout(boolean z, int i, int i2, int i3, int i4) { super.onLayout(z, i, i2, i3, i4); if (this.hnc != null) { this.hnc.auE(); } } public void setOnLayoutChangeListener(a aVar) { this.hnc = aVar; } }
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> sol = new ArrayList<Integer>(); inorder(root, sol); return sol; } public void inorder(TreeNode n, List<Integer> sol){ if(n == null) return; inorder(n.left, sol); sol.add(n.val); inorder(n.right, sol); } }
import java.util.*; class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int[] arr = new int[101]; for(int i=0;i<N;i++){ arr[i] = sc.nextInt(); } int count =0; for(int i=0;i<N;i++){ int num = arr[i]; if(num==1) continue; boolean flag = false; for(int j =2;j<=Math.sqrt(num);j++){ if(num%j==0){ flag = true; break; } } if(!flag){ count++; } } System.out.println(count); } }
package br.usp.memoriavirtual.filtro; import java.io.IOException; import java.io.Serializable; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet Filter implementation class FiltroLogin */ @WebFilter("/FiltroLogin") public class FiltroLogin implements Filter, Serializable { /** * */ private static final long serialVersionUID = -2872604550129629756L; /** * Default constructor. */ public FiltroLogin() { } /** * @see Filter#destroy() */ public void destroy() { } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //System.out.println("Passei aqui linha 47: inicio do filtro" // + System.getProperty("com.sun.aas.instanceName")); HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String url = req.getRequestURL().toString(); HttpSession session = req.getSession(); Object user = null; user = req.getSession().getAttribute("usuario"); if (user == null) { ////System.out.println("Passei aqui linha 57: if user null"); session.setAttribute("url", url); resp.sendRedirect(req.getContextPath() + "/login.jsf"); return; } else { String urlDireta = null; //System.out.println("Passei aqui linha 65: if not null"); if (session.getAttribute("url") != null) { urlDireta = session.getAttribute("url").toString(); session.removeAttribute("url"); resp.sendRedirect(urlDireta); return; } } // pass the request along the filter chain chain.doFilter(request, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { } }
package com.workorder.ticket.controller; import javax.annotation.Resource; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.sowing.common.page.Page; import com.sowing.common.response.ListResponse; import com.workorder.ticket.controller.vo.common.OpLog; import com.workorder.ticket.service.BizLogService; /** * 操作日志管理 * * @author wzdong * @Date 2019年3月26日 * @version 1.0 */ @RestController public class BizLogController { @Resource private BizLogService bizLogService; /** * 获取操作日志 * * @return */ @GetMapping("/oplogs") public ListResponse<OpLog> getLogs(Page page) { return ListResponse.build(bizLogService.getOpLogs(page)); } }
package tests; import org.testng.Assert; import org.testng.annotations.Test; import pages.LinkedInHomePage; import pages.LinkedInSearchPage; import java.util.List; import static java.lang.Thread.sleep; public class LinkedInSearchTest extends BaseTest{ String userEmail = "mrentertheusername@gmail.com"; String userPass = "Aa14401440"; String searchTerm = "HR"; @Test public void basicSearchTest() { Assert.assertTrue(linkedInLoginPage.isLoaded(), "LoginPage is not loaded"); //LogIn LinkedInHomePage linkedInHomePage = linkedInLoginPage.login(userEmail, userPass); try { sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } //Validation Assert.assertTrue(linkedInHomePage.isLoaded(), "Home page is not loaded"); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } LinkedInSearchPage linkedInSearchPage = linkedInHomePage.search("hr"); Assert.assertTrue(linkedInSearchPage.isLoaded(), "SearchPage is not loaded"); //Assert.assertEquals(linkedInSearchPage.getSearchResultsCount(), 10, "Search results count is wrong"); try { sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } //Assert.assertTrue(linkedInSearchPage.allSearchResultsContainSearchterm(searchTerm),"Not all results contain required search term"); List<String> searchResults = linkedInSearchPage.getSearchResultsList(); for (String searchResult: searchResults){ Assert.assertTrue(searchResult.toLowerCase().contains(searchTerm), "searchterm " +searchTerm+" not found in \n" +searchResult); } } }
package com.bierocratie.security; import com.bierocratie.email.EmailSender; import com.bierocratie.model.security.Account; import com.bierocratie.model.security.Role; import javax.mail.MessagingException; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; /** * Created with IntelliJ IDEA. * User: pir * Date: 20/05/14 * Time: 18:12 * To change this template use File | Settings | File Templates. */ public class AdminGenerator { private static final String ADMIN_LOGIN = "bierocratie"; private static final String ADMIN_EMAIL = "pierre.gidel@gmail.com"; public static Account generateAdminAccount() throws MessagingException, UnsupportedEncodingException, NoSuchAlgorithmException { String password = PasswordGenerator.generatePassword(); Account admin = new Account(); admin.setLogin(ADMIN_LOGIN); admin.setPassword(PasswordHasher.hashPassword(password)); admin.setEmail(ADMIN_EMAIL); admin.setRole(Role.ADMIN); EmailSender.sendEmailWithCredentials(admin.getEmail(), admin.getLogin(), password); return admin; } }
package com.mathpar.students.savchenko; import com.mathpar.matrix.MatrixD; import com.mathpar.number.Ring; import com.mathpar.students.savchenko.exception.WrongDimensionsException; public class SVD { public static MatrixD[] getSVD(MatrixD A, Ring ring, boolean blockQR) throws WrongDimensionsException { double globalStart = System.nanoTime(); // 1. QR-разложение входной матрицы A. MatrixD[] qr; double st = System.nanoTime(); if (blockQR) { qr = BlockQR.blockQR(A, ring); } else { qr = givensQR(A, ring); } double en = System.nanoTime(); double lastTimeSec = ((en - st) / 1000000000); System.out.println("Time for QR: " + lastTimeSec + " seconds."); MatrixD Q = qr[0]; MatrixD R = qr[1]; // System.out.println("Матрица Q = "); // System.out.println(Q.toString() + "\n"); // System.out.println("Правая треугольная матрица R = "); // System.out.println(R.toString() + "\n"); // System.out.println("---------- Проверка: Матрица Q*R = "); // System.out.println(Q.multiplyMatr(R, ring).toString() + "\n"); // 2. Приведение матрицы R к двухдиагональному виду (D2). MatrixD Rt = R.transpose(ring); st = System.nanoTime(); MatrixD[] lr = leftTriangleToBidiagonal(Rt, ring); en = System.nanoTime(); lastTimeSec = ((en - st) / 1000000000); System.out.println("Time for D2: " + lastTimeSec + " seconds."); MatrixD L1 = lr[0]; MatrixD R1 = lr[1]; MatrixD D2 = L1.multiplyMatr(Rt, ring); D2 = D2.multiplyMatr(R1, ring); // System.out.println("D2 = \n" + D2.toString() + "\n"); // 3. Приведение матрицы D2 к диагональному виду (D1). st = System.nanoTime(); lr = bidiagonalToDiagonal(D2, ring); en = System.nanoTime(); lastTimeSec = ((en - st) / 1000000000); System.out.println("Time for D2 ---> D1: " + lastTimeSec + " seconds."); MatrixD L2 = lr[0]; MatrixD R2 = lr[1]; MatrixD D1 = L2.multiplyMatr(D2, ring); D1 = D1.multiplyMatr(R2, ring); // Utils.removeNonDiagonalValues(D1, ring); // System.out.println("D1 = \n" + D1.toString() + "\n"); // 4. Расчет SVD разложения для входной матрицы A. MatrixD U = Q.multiplyMatr(R1, ring).multiplyMatr(R2, ring); MatrixD V = L2.multiplyMatr(L1, ring); MatrixD A1 = U.multiplyMatr(D1, ring).multiplyMatr(V, ring); // System.out.println("Проверка SVD разложения. U*D1*V = \n"); // System.out.println(A1.toString()); double globalEnd = System.nanoTime(); double globalTime = ((globalEnd - globalStart) / 1000000000); System.out.println("Time all: " + globalTime + " seconds."); return new MatrixD[] {U, D1, V, A1}; } /** * Returns matrices Q, R such that Q*R = A */ public static MatrixD[] givensQR(MatrixD A, Ring ring) throws WrongDimensionsException { int colCounter = 1; int n = A.rowNum(); MatrixD Q = MatrixD.ONE(n, ring); MatrixD R = A.copy(); MatrixD GTemp; for (int i=0; i<n-1; i++) { // System.out.println("ИТЕРАЦИЯ " + i + "\n"); for (int j=n-1; j>colCounter-1; j--) { if (Math.abs(R.getElement(j, i).doubleValue()) > 0) { // System.out.println("ОБНУЛЯЕМ ЭЛЕМЕНТ " + j + ", " + i + "\n"); GTemp = Utils.getGivensRotationMatrix(n, j-1, j, R.getElement(j-1, i), R.getElement(j, i), ring); // System.out.println("МАТРИЦА ВРАЩЕНИЯ = " + "\n"); // System.out.println(GTemp.toString()+ "\n"); Q = Utils.rightMultiplyMatrixToGivens(Q, GTemp, j-1, j, ring); R = Utils.leftMultiplyGivensToMatrix(GTemp.transpose(ring), R, j-1, j, ring); // System.out.println("МАТРИЦА ВРАЩЕНИЯ t * Temp = " + "\n"); // System.out.println(R.toString() + "\n"); } } colCounter++; } return new MatrixD[]{Q, R}; } // Возвращает матрицы L, R. Матрица D2 = L*A*R имеет двухдиагональный вид. public static MatrixD[] leftTriangleToBidiagonal(MatrixD A, Ring ring) throws WrongDimensionsException { if (A.rowNum() != A.colNum()) throw new WrongDimensionsException(); int n = A.rowNum(); MatrixD left; MatrixD right; MatrixD Temp = A.copy(); MatrixD L = MatrixD.ONE(n, ring); MatrixD R = MatrixD.ONE(n, ring); // System.out.println("Обнуляем элементы в i-том столбце снизу вверх и i-той строке строке (если это не 'верхний y') \n"); for (int col=0; col<(n-1); col++) { for (int row=(n-1); row>(col); row--) { left = Utils.getGivensRotationMatrix(n, row-1, row, Temp.getElement(row-1, col), Temp.getElement(row, col), ring); left = left.transpose(ring); L = Utils.leftMultiplyGivensToMatrix(left, L, row-1, row, ring); Temp = Utils.leftMultiplyGivensToMatrix(left, Temp, row-1, row, ring); // System.out.println("Испортился ноль в " + (row-1) + ", " + row); if (row > (col+1)) { // Убираем y-ки если это не "верхний" y int i = row-1; int j = row; right = Utils.getGivensRotationMatrix(n, j-1, j, Temp.getElement(i, j-1), Temp.getElement(i, j), ring); R = Utils.rightMultiplyMatrixToGivens(R, right, j-1, j, ring); Temp = Utils.rightMultiplyMatrixToGivens(Temp, right, j-1, j, ring); } } // System.out.println("После " + (col+1) + " итерации матрица имеет вид \n"); // System.out.println(Temp.toString() + "\n"); } return new MatrixD[]{L, R}; } // Возвращает матрицы L, R, D1. Матрица D1 = L*A*R имеет диагональный вид. public static MatrixD[] bidiagonalToDiagonal(MatrixD A, Ring ring) throws WrongDimensionsException { if (A.rowNum() != A.colNum()) throw new WrongDimensionsException(); int n = A.rowNum(); MatrixD left; MatrixD right; MatrixD Temp = A.copy(); MatrixD L = MatrixD.ONE(n, ring); MatrixD R = MatrixD.ONE(n, ring); // System.out.println("Матрица имеет двухдиагональный вид. \n " + // "Применяем последовательное обнуление верхней/нижней диагонали, пока |элементы| > epsilon \n"); boolean side = true; int iterations = 0; while (!Utils.checkSecondDiagonalValues(Temp, n, ring)) { if (side) { // right for (int i=0; i<(n-1); i++) { int j = i+1; if (!Temp.getElement(i, j).isZero(ring)) { right = Utils.getGivensRotationMatrix(n, j - 1, j, Temp.getElement(i, j - 1), Temp.getElement(i, j), ring); R = Utils.rightMultiplyMatrixToGivens(R, right, j-1, j, ring); Temp = Utils.rightMultiplyMatrixToGivens(Temp, right, j-1, j, ring); iterations++; } } } else { // left for (int j=0; j<(n-1); j++) { int i = j+1; if (!Temp.getElement(i, j).isZero(ring)) { left = Utils.getGivensRotationMatrix(n, i - 1, i, Temp.getElement(i - 1, j), Temp.getElement(i, j), ring); left = left.transpose(ring); L = Utils.leftMultiplyGivensToMatrix(left, L, i-1, i, ring); Temp = Utils.leftMultiplyGivensToMatrix(left, Temp, i-1, i, ring); iterations++; } } } side = !side; // System.out.println("После " + iterations + " итерации матрица имеет вид \n"); // System.out.println(Temp.toString() + "\n"); } //System.out.println(" Количество итераций для получения диагональной матрицы = " + iterations + "."); return new MatrixD[]{L, R, Temp}; } }
/* * Copyright (C) 2019-2023 Hedera Hashgraph, 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.hedera.mirror.importer.parser.record.transactionhandler; import static com.hedera.mirror.importer.util.Utility.RECOVERABLE_ERROR; import com.hedera.mirror.common.domain.entity.Entity; import com.hedera.mirror.common.domain.entity.EntityId; import com.hedera.mirror.common.domain.transaction.RecordItem; import com.hedera.mirror.common.domain.transaction.TransactionType; import com.hedera.mirror.importer.domain.EntityIdService; import com.hedera.mirror.importer.parser.record.entity.EntityListener; import jakarta.inject.Named; import lombok.CustomLog; @CustomLog @Named class CryptoDeleteTransactionHandler extends AbstractEntityCrudTransactionHandler { CryptoDeleteTransactionHandler(EntityIdService entityIdService, EntityListener entityListener) { super(entityIdService, entityListener, TransactionType.CRYPTODELETE); } @Override public EntityId getEntity(RecordItem recordItem) { return EntityId.of(recordItem.getTransactionBody().getCryptoDelete().getDeleteAccountID()); } @Override protected void doUpdateEntity(Entity entity, RecordItem recordItem) { var transactionBody = recordItem.getTransactionBody().getCryptoDelete(); var obtainerId = entityIdService.lookup(transactionBody.getTransferAccountID()).orElse(EntityId.EMPTY); if (EntityId.isEmpty(obtainerId)) { log.error( RECOVERABLE_ERROR + "Unable to lookup ObtainerId at consensusTimestamp {}", recordItem.getConsensusTimestamp()); } else { entity.setObtainerId(obtainerId); } entityListener.onEntity(entity); recordItem.addEntityId(obtainerId); } }
package com; import java.sql.*; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.microsoft.*; import com.microsoft.sqlserver.*; //import com.microsoft.sqlserver.jdbc.SQLServerDriver; public class DAO { // Connect to your database. // Replace server name, username, and password with your credentials private static final String sproc = "{call [Ten Most Expensive Products] }"; public List<Customer> reporteClientes() throws SQLException { List<Customer> customers = new ArrayList<>(); Customer custom=new Customer(); String connectionString = "jdbc:sqlserver://127.0.0.1:1433;" + "database=Northwind;" + "user=sa;" + "password=holamarce25;"; // Declare the JDBC objects. Connection connection = null; Statement statement = null; ResultSet resultSet = null; connection = DriverManager.getConnection(connectionString); System.out.println("Conectado"); CallableStatement cs = connection.prepareCall(sproc); resultSet = cs.executeQuery(); while (resultSet.next()) { customers.add(new Customer(resultSet.getString("TenMostExpensiveProducts"),resultSet.getFloat("UnitPrice"))); } connection.close(); custom.companyname="pepito"; custom.precio=990; customers.add(custom); return customers; } /* public static void main(String[] args) throws SQLException { // TODO Auto-generated method stub System.out.println("TOdo guagua"); List<Customer> listica=reporteClientes(); Gson gson = new Gson(); String json = gson.toJson(listica); //pintamos el json en la consola para ver el resultado System.out.println(json); System.out.println("Hello Fucking \n World"); } */ }
package org.mlgb.dsps.monitor; import java.util.ArrayList; import java.util.List; /** * The design blueprint for producing messages. * Input rate is almost 50 msg/s. * @author Leo * */ public class UnderloadPlanning extends Planning{ public List<Integer> delayMilis; public int type; public UnderloadPlanning() { this.type = PlanningFactory.UNDER_LOADED; this.delayMilis = new ArrayList<>(); this.delayMilis.add(20); } }
package org.linqs.psl.LTR_Rec.modelSettings; import org.linqs.psl.LTR_Rec.modelSettings.ModelSetting; import org.linqs.psl.LTR_Rec.modelSettings.MovieLensSetting; import org.linqs.psl.LTR_Rec.modelSettings.JesterSetting; import org.linqs.psl.LTR_Rec.modelSettings.LastFMSetting; import org.linqs.psl.LTR_Rec.modelSettings.YelpSetting; public class ModelSettingFactory { public static ModelSetting getSetting(String settingName){ ModelSetting newModelSetting; switch(settingName) { case "movie_lens": newModelSetting = new MovieLensSetting(); break; case "jester": newModelSetting = new JesterSetting(); break; case "lastfm": newModelSetting = new LastFMSetting(); break; case "yelp": newModelSetting = new YelpSetting(); break; default: throw new IllegalArgumentException("setting must be one of: [movie_lens, jester, lastfm, yelp]"); } return newModelSetting; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controller; import dao.*; import entity.*; import java.io.Serializable; import java.util.List; import javax.enterprise.context.SessionScoped; import javax.inject.Inject; import javax.inject.Named; @Named(value="urunc") @SessionScoped public class UrunlerController implements Serializable{ private Urunler urun; private UrunlerDao urundao; public UrunlerController() { } @Inject private KategoriController katcon; public List<Urunler>getListurun() { return this.getUrundao().getUrunLists(); } public void filtre(Kategori k){ this.getUrundao().setUrunlist(null); filtrele(k); } public List<Urunler> filtrele(Kategori k){ if(k==null){ return this.getUrundao().getUrunLists(); } else{ this.getUrundao().setUrunlist(null); this.getUrundao().setUrunlist(this.getUrundao().getFiltrele(k)); return this.getUrundao().getUrunlist(); } } public void kaydeturun() { this.getUrundao().add(this.urun); this.urun=new Urunler(); } public void guncelleurun(){ this.getUrundao().guncelle(this.urun); this.urun=new Urunler(); } public void updateurun(Urunler u){ this.urun=u; } public void formtemizle(){ this.urun=new Urunler(); } public void deleteurun(Urunler u){ this.getUrundao().delete(u); } public Urunler getUrun() { if(this.urun==null) this.urun=new Urunler(); return urun; } public UrunlerDao getUrundao() { if(this.urundao==null) this.urundao=new UrunlerDao(); return urundao; } public KategoriController getKatcon() { if(this.katcon==null) this.katcon=new KategoriController(); return katcon; } }
package fr.unice.polytech.clapevents.model; public class Event { private int key; private String title; private String artists; private String date; private String place; private String address; private String category; private String description; private String pathToPhoto; private String pathToPhoto2; private String pathToPhotoPlace; private String pathToPhoto4; private int age; private int price; private boolean favorite; private int tickets; public Event(int key, String title, String artists, String date, String place, String address, String category, String description, String pathToPhoto, String pathToPhoto2, String pathToPhotoPlace, String pathToPhoto4, int age, int price, boolean favorite, int tickets) { this.key = key; this.title = title; this.artists = artists; this.date = date; this.place = place; this.address = address; this.category = category; this.description = description; this.pathToPhoto = pathToPhoto; this.pathToPhoto2 = pathToPhoto2; this.pathToPhotoPlace = pathToPhotoPlace; this.pathToPhoto4 = pathToPhoto4; this.age = age; this.price = price; this.favorite = favorite; this.tickets = tickets; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPathToPhoto2() { return pathToPhoto2; } public void setPathToPhoto2(String pathToPhoto2) { this.pathToPhoto2 = pathToPhoto2; } public String getPathToPhotoPlace() { return pathToPhotoPlace; } public void setPathToPhotoPlace(String pathToPhotoPlace) { this.pathToPhotoPlace = pathToPhotoPlace; } public String getPathToPhoto4() { return pathToPhoto4; } public void setPathToPhoto4(String pathToPhoto4) { this.pathToPhoto4 = pathToPhoto4; } public int getTickets() { return tickets; } public void setTickets(int tickets) { this.tickets = tickets; } public boolean isFavorite() { return favorite; } public void setFavorite(boolean favorite) { this.favorite = favorite; } public String getPathToPhoto() { return pathToPhoto; } public String getTitle() { return title; } public int getKey() { return key; } public String getPlace() { return place; } public String getDate() { return date; } public void setKey(int key) { this.key = key; } public void setTitle(String title) { this.title = title; } public String getArtists() { return artists; } public void setArtists(String artists) { this.artists = artists; } public void setDate(String date) { this.date = date; } public void setPlace(String place) { this.place = place; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setPathToPhoto(String pathToPhoto) { this.pathToPhoto = pathToPhoto; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
package Online; import com.badlogic.gdx.ai.GdxFileSystem; import de.tomgrill.gdxfirebase.core.GDXFirebase; public class FirestoreHelper { }
package LC200_400.LC200_250; import org.junit.Test; import java.util.Stack; /** * bad solution */ public class LC224_Basic_Calculater { @Test public void test() { System.out.println(calculate("(3-(5-(8)-(2+(9-(0-(8-(2))))-(4))-(4)))")); } public int calculate(String s) { int ans = 0; Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) != ')') { if (s.charAt(i) != ' ') stack.push(s.charAt(i)); } else { int tem = 0; while (true) { int inte = 0, flag = 0; Character c = stack.pop(); while (c >= '0' && c <= '9') { int t = 1; for (int ii = 0; ii < flag; ++ii) { t *= 10; } ++flag; inte += t * (c - '0'); c = stack.pop(); } if (c == '(') { tem += inte; break; } if (c == '-') tem += -inte; else tem += inte; } if (tem >= 0) stack.push('+'); else stack.push('-'); boolean isPos = true; while (!stack.isEmpty() && (stack.peek() == '+' || stack.peek() == '-')) { char ch = stack.pop(); if (ch == '-') { isPos = isPos == true ? false : true; } } if (isPos) { stack.push('+'); } else stack.push('-'); // push 48 into the stack Stack<Character> sta = new Stack<>(); tem = tem < 0 ? -tem : tem; while (tem >= 10) { int last = tem % 10; sta.push((char) (last + '0')); tem /= 10; } sta.push((char) (tem + '0')); for (int j = sta.size() - 1; j >= 0; --j) stack.push(sta.get(j)); } } for (int i = 0; i < stack.size(); ++i) { int tem = 0; boolean isPos = true; if (stack.get(i) == '-') { ++i; isPos = false; } else if (stack.get(i) == '+') { ++i; } while (i < stack.size() && stack.get(i) >= '0' && stack.get(i) <= '9') { tem = 10 * tem + stack.get(i) - '0'; ++i; } --i; if (!isPos) tem = -tem; ans += tem; } return ans; } }
package com.jamesball.learn.tictactoe; import java.util.Arrays; public class PlayerSwapper { public PlayerMark swap(PlayerMark currentPlayer) { return Arrays.stream(PlayerMark.values()) .filter(player -> player != currentPlayer) .findFirst() .orElseThrow(); } }
package ac.iie.nnts.Constant; public class Constant { public static long curTime = 0; public static int flag = 0;//0是异常检测;1是MIPS //DW public static double relativeError = 0.1;//DW相对误差 public static int expire = 1000; //窗口大小 public static int K = 4;//数组每行几位,即哈希值的位数 public static int L = 1;//数组有多少行,即哈希值的个数 //阈值 public static double alpha = 0.2;//阈值水平,小于窗口内数量的这个比例即为异常 public static double mean =0;//平均值 public static int n = 0; public static int DW_nums = 0; //文件路径 public static String dataPath = "D:/Documents/vscode/data/tao.csv"; public static String outputPath = "D:/Documents/vscode/data/tao_outliers_190731.txt"; //topK public static int topK=20; public static double[] topkBase = {-9.99,84.01,23.56}; public static String topKPath = "D:/Documents/vscode/data//tao_topk_190510.txt"; public static String topKcoll = "D:/Documents/vscode/data//tao_key.txt"; // public static Data base ;//基准向量 public static int timeRange=2000;//哪个时间段的topk }
package com.example.icebuild2; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class AttemptQuizActivity extends AppCompatActivity { private Toolbar mToolbar; private String currentBoardName; TextView questionTxt, TimerTextView; Button b1,b2,b3,b4; int correct=0,wrong=0, total=0, computerCount=0; int maxCounter=0; DatabaseReference QuizQuestionRef; DatabaseReference QuizRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_attempt_quiz); //////////////////////////////////////////////////////////////////////////////////////////// currentBoardName = getIntent().getStringExtra("BoardName"); //////////////////////////////////////////////////////////////////////////////////////////// QuizRef=FirebaseDatabase.getInstance().getReference().child("Board Quizzes").child(currentBoardName); //////////////////////////////////////////////////////////////////////////////////////////// initializeFields(); //////////////////////////////////////////////////////////////////////////////////////////// mToolbar=(Toolbar)findViewById(R.id.Attempt_Quiz_toolbar); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setTitle("Attempt Quiz of "+currentBoardName); //////////////////////////////////////////////////////////////////////////////////////////// QuizRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String maxString=dataSnapshot.child("Total_Questions").getValue().toString(); int max=Integer.parseInt(maxString); Toast.makeText(AttemptQuizActivity.this, "Check Counter: "+ max, Toast.LENGTH_SHORT).show(); maxCounter=max; updateQuestion(maxCounter); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); //////////////////////////////////////////////////////////////////////////////////////////// } private void initializeFields() { b1 = (Button) findViewById(R.id.OptionA); b2 = (Button) findViewById(R.id.OptionB); b3 = (Button) findViewById(R.id.OptionC); b4 = (Button) findViewById(R.id.OptionD); questionTxt = (TextView) findViewById(R.id.Question_TextView); TimerTextView =(TextView)findViewById(R.id.Timer_TextView); } private void updateQuestion(final int maxCounter) { reverseTimer(60, TimerTextView); computerCount++; if(computerCount> maxCounter) { Toast.makeText(getApplicationContext(),"Game Over "+ this.maxCounter,Toast.LENGTH_SHORT).show(); Intent myIntent = new Intent(AttemptQuizActivity.this,ResultActivity.class); myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); myIntent.putExtra("total",String.valueOf(total)); myIntent.putExtra("correct",String.valueOf(correct)); myIntent.putExtra("incorrect",String.valueOf(wrong)); myIntent.putExtra("BoardName",currentBoardName); startActivity(myIntent); this.finish(); }else{ //////////////////////////////////////////////////////////////////////////////////////// QuizQuestionRef = FirebaseDatabase.getInstance().getReference().child("Board Quizzes"). child(currentBoardName).child("Question_"+computerCount); //////////////////////////////////////////////////////////////////////////////////////// total++; //////////////////////////////////////////////////////////////////////////////////////// QuizQuestionRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull final DataSnapshot dataSnapshot) { final Question question = dataSnapshot.getValue(Question.class); questionTxt.setText(question.getQuestion()); b1.setText(question.getOption1()); b2.setText(question.getOption2()); b3.setText(question.getOption3()); b4.setText(question.getOption4()); //////////////////////////////////////////////////////////////////////////////// b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(b1.getText().toString().equals(question.getAnswer())) { //////////////////////////////////////////////////////////////////// Toast.makeText(getApplicationContext(),"Correct answer",Toast.LENGTH_SHORT).show(); b1.setBackgroundColor(Color.GREEN); correct = correct +1; //////////////////////////////////////////////////////////////////// Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { b1.setBackgroundColor(Color.parseColor("#03A9F4")); updateQuestion(maxCounter); } }, 1500); //////////////////////////////////////////////////////////////////// }else{ //////////////////////////////////////////////////////////////////// Toast.makeText(getApplicationContext(),"Incorrect",Toast.LENGTH_SHORT).show(); wrong = wrong+1; b1.setBackgroundColor(Color.RED); //////////////////////////////////////////////////////////////////// if(b2.getText().toString().equals(question.getAnswer())){ b2.setBackgroundColor(Color.GREEN); }else if(b3.getText().toString().equals(question.getAnswer())){ b3.setBackgroundColor(Color.GREEN); }else if(b4.getText().toString().equals(question.getAnswer())){ b4.setBackgroundColor(Color.GREEN); } //////////////////////////////////////////////////////////////////// Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { b1.setBackgroundColor(Color.parseColor("#03A9F4")); b2.setBackgroundColor(Color.parseColor("#03A9F4")); b3.setBackgroundColor(Color.parseColor("#03A9F4")); b4.setBackgroundColor(Color.parseColor("#03A9F4")); updateQuestion(maxCounter); } }, 1500); //////////////////////////////////////////////////////////////////// } } }); //////////////////////////////////////////////////////////////////////////////// b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(b2.getText().toString().equals(question.getAnswer())) { //////////////////////////////////////////////////////////////////// Toast.makeText(getApplicationContext(),"Correct answer",Toast.LENGTH_SHORT).show(); b2.setBackgroundColor(Color.GREEN); correct = correct +1; //////////////////////////////////////////////////////////////////// Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { b2.setBackgroundColor(Color.parseColor("#03A9F4")); updateQuestion(maxCounter); } }, 1500); //////////////////////////////////////////////////////////////////// }else{ //////////////////////////////////////////////////////////////////// Toast.makeText(getApplicationContext(),"Incorrect",Toast.LENGTH_SHORT).show(); wrong = wrong+1; b2.setBackgroundColor(Color.RED); //////////////////////////////////////////////////////////////////// if(b1.getText().toString().equals(question.getAnswer())){ b1.setBackgroundColor(Color.GREEN); }else if(b3.getText().toString().equals(question.getAnswer())){ b3.setBackgroundColor(Color.GREEN); }else if(b4.getText().toString().equals(question.getAnswer())){ b4.setBackgroundColor(Color.GREEN); } //////////////////////////////////////////////////////////////////// Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { b1.setBackgroundColor(Color.parseColor("#03A9F4")); b2.setBackgroundColor(Color.parseColor("#03A9F4")); b3.setBackgroundColor(Color.parseColor("#03A9F4")); b4.setBackgroundColor(Color.parseColor("#03A9F4")); updateQuestion(maxCounter); } }, 1500); //////////////////////////////////////////////////////////////////// } } }); //////////////////////////////////////////////////////////////////////////////// b3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(b3.getText().toString().equals(question.getAnswer())) { //////////////////////////////////////////////////////////////////// Toast.makeText(getApplicationContext(),"Correct answer",Toast.LENGTH_SHORT).show(); b3.setBackgroundColor(Color.GREEN); correct = correct +1; //////////////////////////////////////////////////////////////////// Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { b3.setBackgroundColor(Color.parseColor("#03A9F4")); updateQuestion(maxCounter); } }, 1500); //////////////////////////////////////////////////////////////////// }else{ //////////////////////////////////////////////////////////////////// Toast.makeText(getApplicationContext(),"Incorrect",Toast.LENGTH_SHORT).show(); wrong = wrong+1; b3.setBackgroundColor(Color.RED); //////////////////////////////////////////////////////////////////// if(b1.getText().toString().equals(question.getAnswer())){ b1.setBackgroundColor(Color.GREEN); }else if(b2.getText().toString().equals(question.getAnswer())){ b2.setBackgroundColor(Color.GREEN); }else if(b4.getText().toString().equals(question.getAnswer())){ b4.setBackgroundColor(Color.GREEN); } //////////////////////////////////////////////////////////////////// Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { b1.setBackgroundColor(Color.parseColor("#03A9F4")); b2.setBackgroundColor(Color.parseColor("#03A9F4")); b3.setBackgroundColor(Color.parseColor("#03A9F4")); b4.setBackgroundColor(Color.parseColor("#03A9F4")); updateQuestion(maxCounter); } }, 1500); //////////////////////////////////////////////////////////////////// } } }); //////////////////////////////////////////////////////////////////////////////// b4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(b4.getText().toString().equals(question.getAnswer())) { //////////////////////////////////////////////////////////////////// Toast.makeText(getApplicationContext(),"Correct answer",Toast.LENGTH_SHORT).show(); b4.setBackgroundColor(Color.GREEN); correct = correct +1; //////////////////////////////////////////////////////////////////// Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { b4.setBackgroundColor(Color.parseColor("#03A9F4")); updateQuestion(maxCounter); } }, 1500); //////////////////////////////////////////////////////////////////// }else{ //////////////////////////////////////////////////////////////////// Toast.makeText(getApplicationContext(),"Incorrect",Toast.LENGTH_SHORT).show(); wrong = wrong+1; b4.setBackgroundColor(Color.RED); //////////////////////////////////////////////////////////////////// if(b1.getText().toString().equals(question.getAnswer())){ b1.setBackgroundColor(Color.GREEN); }else if(b2.getText().toString().equals(question.getAnswer())){ b2.setBackgroundColor(Color.GREEN); }else if(b3.getText().toString().equals(question.getAnswer())){ b3.setBackgroundColor(Color.GREEN); } //////////////////////////////////////////////////////////////////// Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { b1.setBackgroundColor(Color.parseColor("#03A9F4")); b2.setBackgroundColor(Color.parseColor("#03A9F4")); b3.setBackgroundColor(Color.parseColor("#03A9F4")); b4.setBackgroundColor(Color.parseColor("#03A9F4")); updateQuestion(maxCounter); } }, 1500); //////////////////////////////////////////////////////////////////// } } }); //////////////////////////////////////////////////////////////////////////////// } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } public void reverseTimer(int Seconds,final TextView tv){ final CountDownTimer time = new CountDownTimer(Seconds* 1000+1000, 1000) { int seconds=0; int minutes=0; public void onTick(long millisUntilFinished) { seconds = (int) (millisUntilFinished / 1000); minutes = seconds / 60; seconds = seconds % 60; tv.setText(String.format("%02d", minutes) + ":" + String.format("%02d", seconds)); } public void onFinish() { if(!(computerCount>maxCounter)) { tv.setText("Completed"); Intent myIntent = new Intent(AttemptQuizActivity.this, ResultActivity.class); myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); myIntent.putExtra("total", String.valueOf(total)); myIntent.putExtra("correct", String.valueOf(correct)); myIntent.putExtra("incorrect", String.valueOf(wrong)); myIntent.putExtra("BoardName",currentBoardName); startActivity(myIntent); } } }; time.cancel(); time.start(); if(computerCount>maxCounter){ time.cancel(); } } }
package uw.cse.dineon.user.general.test; import uw.cse.dineon.library.DineOnUser; import uw.cse.dineon.library.util.TestUtility; import uw.cse.dineon.user.DineOnUserApplication; import uw.cse.dineon.user.R; import uw.cse.dineon.user.general.ProfileActivity; import android.app.Instrumentation; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.TextView; public class ProfileActivityTest extends ActivityInstrumentationTestCase2<ProfileActivity> { private DineOnUser dineOnUser; private ProfileActivity mActivity; private Instrumentation mInstrumentation; public ProfileActivityTest() { super(ProfileActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); dineOnUser = TestUtility.createFakeUser(); dineOnUser.getUserInfo().setPhone("0-123-456-789"); this.setActivityInitialTouchMode(false); mInstrumentation = this.getInstrumentation(); Intent addEvent = new Intent(); setActivityIntent(addEvent); DineOnUserApplication.setDineOnUser(this.dineOnUser, null); mActivity = getActivity(); } @Override protected void tearDown() throws Exception { super.tearDown(); this.setActivity(null); } /** * Ensures that the users data is correctly reflected in their edit profile. * Also tests to make sure the transition to the profile menu works on back * pressed and that the data is still consistent. * */ public void testOnUserInfoUpdate() { assertNotNull(this.mActivity); this.mInstrumentation.waitForIdleSync(); mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU); mInstrumentation.invokeMenuActionSync(mActivity, R.id.option_edit_profile, 0); this.mInstrumentation.waitForIdleSync(); View v = this.mActivity.findViewById(R.id.label_profile_name_edit); assertNotNull(v); TextView tv = (TextView) v; assertEquals(this.dineOnUser.getName(), tv.getText()); assertEquals(this.dineOnUser.getUserInfo().getName(),tv.getText()); v = this.mActivity.findViewById(R.id.button_save_changes); assertNotNull(v); Button save = (Button) v; final Button B = save; this.mActivity.runOnUiThread(new Runnable(){ @Override public void run() { assertTrue(B.performClick()); } }); this.mInstrumentation.waitForIdleSync(); mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); v = this.mActivity.findViewById(R.id.label_profile_name); assertNotNull(v); assertTrue(v instanceof TextView); tv = (TextView) v; assertEquals(this.dineOnUser.getName(),tv.getText()); assertEquals(this.dineOnUser.getUserInfo().getName(),tv.getText()); v = this.mActivity.findViewById(R.id.user_email_display); assertNotNull(v); assertTrue(v instanceof TextView); tv = (TextView) v; assertEquals(this.dineOnUser.getUserInfo().getEmail(),tv.getText()); v = this.mActivity.findViewById(R.id.user_phone_display); assertNotNull(v); assertTrue(v instanceof TextView); tv = (TextView) v; assertEquals(this.dineOnUser.getUserInfo().getPhone(),tv.getText()); } }
package com.guideviewlibrary.bean; import android.graphics.RectF; /** * Created by Roy * Date: 16/8/10 */ public class ViewPosInfo { /* 被指引控件的Rectf */ public RectF rectF; /* 被指引控件的介绍View */ // public View introView; public int introViewId; /* 介绍View的位置分布 */ public MarginInfo mMarginInfo; public ViewPosInfo() { } public ViewPosInfo(RectF rectF, int introViewId, MarginInfo marginInfo) { this.rectF = rectF; this.introViewId = introViewId; this.mMarginInfo = marginInfo; } }
package com.tencent.mm.plugin.sns.ui.widget; import android.util.DisplayMetrics; import android.view.WindowManager; import com.tencent.mm.kiss.widget.textview.a.a; import com.tencent.mm.kiss.widget.textview.a.b; import com.tencent.mm.plugin.sns.i.c; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.x; public final class d { private static d one = new d(); public int ona = 0; private a onf = null; private a ong = null; public static d bEY() { return one; } public final a getTextViewConfig() { int fromDPToPix = com.tencent.mm.bp.a.fromDPToPix(ad.getContext(), (int) (16.0f * com.tencent.mm.bp.a.fe(ad.getContext()))); if (this.onf == null || ((int) this.onf.duz) != fromDPToPix) { this.onf = b.Fe().gM(8388627).gN(ad.getContext().getResources().getColor(c.normal_text_color)).V((float) fromDPToPix).duk; } return this.onf; } public final a bEZ() { int fromDPToPix = com.tencent.mm.bp.a.fromDPToPix(ad.getContext(), (int) (16.0f * com.tencent.mm.bp.a.fe(ad.getContext()))); if (this.ong == null || ((int) this.ong.duz) != fromDPToPix) { b V = b.Fe().gM(8388627).gN(ad.getContext().getResources().getColor(c.normal_text_color)).V((float) fromDPToPix); V.duk.maxLines = 6; this.ong = V.duk; } return this.ong; } public final int getViewWidth() { if (this.ona <= 0) { DisplayMetrics displayMetrics = new DisplayMetrics(); ((WindowManager) ad.getContext().getSystemService("window")).getDefaultDisplay().getMetrics(displayMetrics); int i = displayMetrics.widthPixels; int dimension = (int) (ad.getResources().getDimension(com.tencent.mm.plugin.sns.i.d.NormalPadding) + ad.getResources().getDimension(com.tencent.mm.plugin.sns.i.d.NormalPadding)); int dimension2 = (int) ad.getResources().getDimension(com.tencent.mm.plugin.sns.i.d.sns_timeilne_margin_left); int dimension3 = (int) ad.getResources().getDimension(com.tencent.mm.plugin.sns.i.d.NormalPadding); this.ona = (i - dimension2) - dimension; x.i("MicroMsg.SnsPostDescPreloadTextViewConfig", "screenWidth " + i + " textViewWidth " + this.ona + " padding: " + dimension + " marginLeft: " + dimension2 + " thisviewPadding: " + dimension3); } return this.ona; } public static float getTextSize() { return (float) com.tencent.mm.bp.a.fromDPToPix(ad.getContext(), (int) (16.0f * com.tencent.mm.bp.a.fe(ad.getContext()))); } }
package wjtoth.cyclicstablematching; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.event.ListSelectionEvent; /** * Utility class of static methods for * creating permutations * @author wjtoth * */ public class Permutations { //compute permutations of [0,...,n-1] //ArrayList has one element public static ArrayList<PermutationArray> permutations(int n) { return permutations(array(n)); } //compute permutations of all subsets of [0,...,n-1] //each subset has permutationArray in its own position in List public static Set<PermutationArray> permutationsOfAllSubsets(int n) { return permutationsOfAllSubsets(array(n)); } //compute array [0,...,n-1] public static int[] array(int n) { int[] retval = new int[n]; for(int i = 0; i<n;++i) { retval[i] = i; } return retval; } //helper of permutationsOfAllSubsets(int n) //alternatively can be used to compute all permutation of all subsets //of elements in array public static Set<PermutationArray> permutationsOfAllSubsets(int[] array) { int subsets = (int)Math.pow(2, array.length); int[] indices = new int[array.length]; Set<PermutationArray> retval = new HashSet<>(); for(int k = 1; k<subsets; ++k) { int[] subset = new int[array.length]; for(int i = 0; i<indices.length;++i) { int include = (k >> i) % 2; if(include == 1) { subset[i] = array[i]; } else{ subset[i] = -1; } } retval.addAll(permutations(subset)); } return retval; } //compute all permutations of elements of array //helper to permutations(int n) public static ArrayList<PermutationArray> permutations(int[] array) { ArrayList<PermutationArray> retval = new ArrayList<>(); if (array.length == 1) { retval.add(new PermutationArray(array)); } else if (array.length > 1) { int lastIndex = array.length - 1; int last = array[lastIndex]; int[] rest = new int[array.length-1]; for(int i = 0; i<rest.length; ++i) { rest[i] = array[i]; } retval = merge(permutations(rest), last); } return retval; } //append each permutationArray with addend and return results public static ArrayList<PermutationArray> merge (ArrayList<PermutationArray> list, int addend) { ArrayList<PermutationArray> retval = new ArrayList<>(); for(PermutationArray prev : list) { for(int i = 0; i<prev.getArray().length+1; ++i) { int[] next = new int[prev.getArray().length+1]; for(int j = 0; j<i; ++j) { next[j] = prev.getArray()[j]; } next[i] = addend; for(int j = i+1; j<next.length; ++j) { next[j] = prev.getArray()[j-1]; } retval.add(new PermutationArray(next)); } } return retval; } }
package arun.problems.ds.arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Stack; public class FindRepeatedNumbersInArray { public static void main(String a[] ) { Scanner sc = new Scanner(System.in); sc.next(); sc.close(); String[] values = {"{[}]"}; Braces(values); } static String[] Braces(String[] values) { if(values == null || values.length == 0) return null; final String[] resultArray = new String[values.length]; final Map<Character, Character> braceMap = new HashMap<Character, Character>(); braceMap.put('(', ')'); braceMap.put('[', ']'); braceMap.put('{', '}'); for(int i = 0; i < values.length; i++) { if(isBraceVStringValid(values[i], braceMap)) { resultArray[i] = "YES"; } else { resultArray[i] = "NO"; } } return resultArray; } static boolean isBraceVStringValid(final String value, final Map<Character, Character> braceMap) { boolean result = false; final Stack usageStack = new Stack(); char[] characters = value.toCharArray(); for(char character : characters) { if(usageStack.isEmpty()) { usageStack.push(character); } else { if (braceMap.get(usageStack.peek()) == character) { usageStack.pop(); } else { usageStack.push(character); } } } if(usageStack.isEmpty()) { result = true; } return result; } }
package com.example.administrator.androidtemplet.http; import com.example.administrator.androidtemplet.MyApp; import java.io.File; /** * 作者 : LiLei * 时间 : 2018/4/8 0008. * 邮箱 :416587959@qq.com * http配置 */ public class HttpConfig { /** * 是否是测试阶段,请到GlobalConfig修改配置 */ public static boolean isTest = true; public static final String PATH_DATA = MyApp.getContext().getCacheDir().getAbsolutePath() + File.separator + "data"; /** * 缓存路径,缓存大小 */ public static final String PATH_CACHE = PATH_DATA + "/NetCache"; public static final int EACHE_SIZE = 1024 * 1024 * 50; /** * 本地网络错误 */ public static final String HTTP_NET_ERROR_MESSAGE = "网络无法连接,请稍后重试"; /** * 解析错误 */ public static final String HTTP_PARSE_ERROR_MESSAGE = "服务器数据有误,请稍后重试"; /** * 服务器应答httpcode错误 */ public static final String HTTP_RESPONSE_ERROR_MESSAGE = "网络无法连接,请稍后重试"; /** * 代码抛异常 */ public static final String HTTP_CODE_ERRDR_MESSAGE= "代码异常"; }
package knn; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; /** * Implementation of K Nearest Neighbors * @author ngadzheva */ public class Classifier { private final int TEST_SET_LENGTH; private final int ATTRIBUTES_COUNT; private List<Instance> instances; private List<Instance> testSet; private List<Instance> trainingSet; public Classifier() { this.TEST_SET_LENGTH = 20; this.ATTRIBUTES_COUNT = 4; this.instances = new ArrayList<>(); this.testSet = new ArrayList<>(); this.trainingSet = new ArrayList<>(); initializeData(); } /** * Read data from file iris.data.txt and create test set and training set * The test set is 20 randomly chosen instances from the data set * The other instances are put in the training set */ private void initializeData(){ try { BufferedReader reader = new BufferedReader(new FileReader("iris.data.txt")); String line; while ((line = reader.readLine()) != null){ String[] lineInfo = line.split(","); Instance instance = new Instance(lineInfo); instances.add(instance); line = reader.readLine(); }; } catch (FileNotFoundException ex) { Logger.getLogger(Classifier.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Classifier.class.getName()).log(Level.SEVERE, null, ex); } Collections.shuffle(instances); for (int i = 0; i < TEST_SET_LENGTH; i++) { testSet.add(instances.get(i)); } int size = instances.size(); for (int i = TEST_SET_LENGTH; i < size; i++) { trainingSet.add(instances.get(i)); } } /** * Implementation of KNN * For every instance in the test set * get its k nearest neighbors * classify it * check whether the predicted class is correct * print the predicted class and the real class * Finally, calculate the accuracy of the algorithm and print it * * @param k - the number of neighbors */ public void solve(int k){ int correctPredictions = 0; for (Instance instance : testSet) { List<Instance> neighbours = getNeighbours(trainingSet, instance, k); String className = classify(neighbours); if(className.equals(instance.getClassName())){ correctPredictions++; } System.out.printf("Prediction: %s Expected: %s%n", className, instance.getClassName()); } System.out.println("Accuracy: " + getAccuracy(correctPredictions) + "%"); } /** * Find k nearest neighbors of the current instance from the test set * For every instance from the training set * calculate the Euclidean distance between the current instance from the * training set and the current instance from the test set * put the calculated distance in the distances list * put the calculated distance and the current instance from the training * set in the dictionary * Then sort the calculated distances * Put the first k instances with min distance from the dictionary to the * list of neighbors of the current instance from the test set * * @param trainingSet * @param testInstance * @param k - the number of neighbors to find * * @return list with the k nearest neighbors */ private List<Instance> getNeighbours(List<Instance> trainingSet, Instance testInstance, int k){ List<Instance> neighbours = new ArrayList<>(); List<Double> distances = new ArrayList<>(); HashMap<Double, Instance> dictionary = new HashMap<>(); int size = trainingSet.size(); for (int i = 0; i < size; i++) { double distance = getEuclideanDistance(testInstance, trainingSet.get(i)); distances.add(distance); dictionary.put(distance, trainingSet.get(i)); } Collections.sort(distances); for (int i = 0; i < k; i++) { neighbours.add(dictionary.get(distances.get(i))); } return neighbours; } /** * Compute Euclidean distance between two instances * * @param instance1 * @param instance2 * @return the Euclidean distance */ private double getEuclideanDistance(Instance instance1, Instance instance2){ double distance = 0.0; for (int i = 0; i < ATTRIBUTES_COUNT; i++) { distance += Math.pow((instance1.getAttributes()[i] - instance2.getAttributes()[i]), 2); } return Math.sqrt(distance); } /** * Get the most common class in the k shorter distances * For every neighbor * get its class and increment the number of predictions for this class * Find the class with the greatest predictions count * Return its name * * @param neighbours * @return the class name */ private String classify(List<Instance> neighbours){ HashMap<String, Integer> predictions = new HashMap<>(); for (Instance neighbour : neighbours) { Integer currentCount = predictions.get(neighbour.getClassName()); predictions.put(neighbour.getClassName(), (currentCount == null) ? 1 : currentCount++); } int max = 0; Collection<Integer> predictionsCount = predictions.values(); for (Integer prediction : predictionsCount) { if(prediction > max){ max = prediction; } } for (Entry<String, Integer> prediction : predictions.entrySet()) { String className = prediction.getKey(); Integer classVotes = prediction.getValue(); if(classVotes == max){ return className; } } return ""; } /** * Calculate the accuracy of the algorithm * * @param predictionsCount * @return the accuracy */ private double getAccuracy(double predictionsCount){ return ((predictionsCount * 1.0) / (double) TEST_SET_LENGTH) * 100.0; } }
/** * */ package valida; import java.io.Serializable; import exception.IndiceInvalidoException; /** * @author nicolly * */ public class verificaConsultaTransacoes implements Serializable { private static final long serialVersionUID = 1L; /** * Metodo que verifica se o indice eh valido * @param indice * @throws IndiceInvalidoException */ public static void verificaIndiceInvalido(int indice) throws IndiceInvalidoException{ if(indice < 0){ throw new IndiceInvalidoException(""); } } }
package day46_collections_Part2; import java.util.*; public class LoopArrayList { public static void main(String[] args) { List<Integer> nums = new ArrayList<>(); nums.add(50); nums.add(540); nums.add(5115); nums.add(550); nums.add(90); nums.add(30); nums.add(20); nums.add(10); //Loop using for each loop for( int n: nums) { System.out.print(n+ "|"); } System.out.println(); for(int i=0; i<nums.size(); i++) { System.out.print(nums.get(i)+ "|"); } System.out.println(); //loop using forEach method. //Lambda Expression. nums.forEach(n -> System.out.print(n+ "|")); // Everthing is the same only easier way. System.out.println(); nums.removeIf(n -> n<500); nums.forEach(n -> System.out.print(n+"|")); } }
package com.tencent.mm.plugin.backup.backuppcui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.plugin.backup.backuppcmodel.b; import com.tencent.mm.plugin.backup.backuppcui.BackupPcUI.3.3; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.platformtools.x; class BackupPcUI$3$3$1 implements OnClickListener { final /* synthetic */ 3 gXp; BackupPcUI$3$3$1(3 3) { this.gXp = 3; } public final void onClick(DialogInterface dialogInterface, int i) { x.i("MicroMsg.BackupPcUI", "user click close. stop backup."); h.mEJ.a(400, 10, 1, false); b.arV().arX().mG(4); b.arV().arw().stop(); b.arV().arX().an(true); b.arV().aqP().gRC = -100; BackupPcUI.l(this.gXp.gXm.gXl); } }
package com.smxknife.java2.io.input; import java.io.*; /** * @author smxknife * 2018/11/19 */ public class DataInputStreamWithDataOutputStreamDemo { public static void main(String[] args) throws IOException { String content = "hello"; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream); dataOutputStream.writeUTF(content); dataOutputStream.flush(); // 从这个输出可以看到前面会插入两个字符 // for (int i = 0; i < byteArrayOutputStream.toByteArray().length; i++) { // System.out.println((char) byteArrayOutputStream.toByteArray()[i]); // } ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream); System.out.println(dataInputStream.readUTF()); } }
package unalcol.clone; import unalcol.service.ServiceCore; /** * <p>Service for cloning objects</p> * <p> * <p>Copyright: Copyright (c) 2010</p> * * @author Jonatan Gomez Perdomo * @version 1.0 */ public abstract class Clone<T> { public static Clone<?> get(Object owner) { if (ServiceCore.get(Object.class, Clone.class) == null) set(Object.class, new CloneWrapper()); return (Clone<?>) ServiceCore.get(owner, Clone.class); } public static boolean set(Object owner, Clone<?> service) { return ServiceCore.set(owner, Clone.class, service); } /** * Creates a clone of a given object * * @param obj Object to be cloned * @return A clone of the object, if a cloning service is available for the given object, <i>null</i> otherwise */ @SuppressWarnings("unchecked") public static Object create(Object obj) { return ((Clone<Object>) get(obj)).clone(obj); } /** * Creates a clone of a given object * * @param toClone Object to be cloned * @return A clone of the object */ public abstract T clone(T toClone); }
package com.thanhviet.userlistarchvm; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MediatorLiveData; import android.arch.lifecycle.Observer; import android.support.annotation.Nullable; import com.thanhviet.userlistarchvm.db.UserRoomDB; import com.thanhviet.userlistarchvm.db.entity.UserEntity; import java.util.List; /** * Created by FRAMGIA\bui.dinh.viet on 19/07/18. */ public class UserRepository { private static UserRepository sInstance; private final UserRoomDB mDatabase; private MediatorLiveData<List<UserEntity>> mObservableUsers; public static UserRepository getInstance(final UserRoomDB database) { if (sInstance == null) { synchronized (UserRepository.class) { if (sInstance == null) { sInstance = new UserRepository(database); } } } return sInstance; } private UserRepository(final UserRoomDB database) { mDatabase = database; mObservableUsers = new MediatorLiveData<>(); mObservableUsers.addSource(mDatabase.mUserDao().loadAllUsers(), new Observer<List<UserEntity>>() { @Override public void onChanged(@Nullable List<UserEntity> userEntities) { if (mDatabase.getDatabaseCreated().getValue() != null) { mObservableUsers.postValue(userEntities); } } }); } /** * Get all user entity data from mObservableUsers */ public LiveData<List<UserEntity>> getUserEntity() { return mObservableUsers; } /** * Get user detail from id */ public LiveData<UserEntity> getUserDetail(int userId) { return mDatabase.mUserDao().loadUser(userId); } }
package com.audioservice.audios; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.audioservice.jeffchien.audios.rest.layouts.SimpleResult; import retrofit.Callback; import retrofit.Response; import retrofit.Retrofit; public class LoginFragment extends Fragment { private final static String TAG = LoginFragment.class.getName(); private TextView mTextStatus; public LoginFragment() { // Required empty public constructor } public static LoginFragment newInstance() { Bundle args = new Bundle(); LoginFragment fragment = new LoginFragment(); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View fragmentView = inflater.inflate(R.layout.fragment_login, container, false); setUpViews(fragmentView); return fragmentView; } private void setUpViews(View rootView){ mTextStatus = (TextView)rootView.findViewById(R.id.text_login_status_msg); final EditText editEmail = (EditText)rootView.findViewById(R.id.edit_email); final EditText editPassword = (EditText)rootView.findViewById(R.id.edit_password); Button loginButton = (Button)rootView.findViewById(R.id.but_login); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mTextStatus.setTextColor(Color.BLACK); mTextStatus.setText(R.string.processing); String email = editEmail.getText().toString(); String password = editPassword.getText().toString(); Public.AudioS.userLogin(email, password).enqueue(mLoginCallback); } }); } private final Callback<SimpleResult> mLoginCallback = new Callback<SimpleResult>() { @Override public void onResponse(Response<SimpleResult> response, Retrofit retrofit) { int code = response.code(); if(code == 200){ Intent intent = new Intent(getActivity(), EntryActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); }else if(code >= 500 && code < 600){ //Internal error Log.e(TAG, "Login receive internal error: " + response.message()); }else{ mTextStatus.setTextColor(Color.RED); mTextStatus.setText(R.string.login_failed); } } @Override public void onFailure(Throwable t) { mTextStatus.setTextColor(Color.RED); mTextStatus.setText(R.string.login_failed); t.printStackTrace(); } }; }
package lap3bai1; import java.util.Scanner; public class Lap3bai1 { public static void main(String[] args) { int a; boolean kiemTra=true; Scanner chiLinh = new Scanner(System.in); System.out.println("Nhập vào một số nguyên :"); a= chiLinh.nextInt(); for(int i=2 ;i<a-1;i++ ){ if (a % i == 0) { kiemTra=false; break; } } if (kiemTra==false) { System.out.println("Số bạn vừa nhập không phải là số nguyên tố !"); } else System.out.println("Số bạn vừa nhập là số nguyên tố !"); { } } }
package sortAlgorithm; public class StraightInsertionSortDemo { }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package vpl.math; /** * * @author kppx */ public class Triple { private double x,y,z; public Triple() { this.x=0; this.y=0; this.z=0; } public Triple(double a,double b, double c) { this.x=a; this.y=b; this.z=c; } public double getX() { return x; } public double getLength() { double l; l=Math.pow(x, 2)+Math.pow(y,2) + Math.pow(z,2);//, l) l= Math.sqrt(l); return l; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getZ() { return z; } public void setZ(double z) { this.z = z; } public Triple getDistance(Triple a, Triple b) { Triple t = new Triple(); return t; } Matrix toMatrix() { Matrix mat = new Matrix(3,1); mat.setValueAt(0, 0, getX()); mat.setValueAt(1, 0, getY()); mat.setValueAt(2, 0, getZ()); return mat; } }
package com.bsa.bsa_giphy; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class BsaGiphyApplicationTests { @Test void contextLoads() { } }
package tuan2; import java.awt.Color; import java.awt.Font; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class bai3 extends JFrame{ public bai3(){ super("Demo Windows"); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { bai3 JPanel= new bai3(); JPanel.setSize(400,300); JPanel.setLocationRelativeTo(null); JPanel.setVisible(true); JPanel pnBox =new JPanel(); pnBox.setLayout(new BoxLayout(pnBox, BoxLayout.X_AXIS)); JButton btn1 =new JButton("BoxLayout"); btn1.setForeground(Color.red); Font font = new Font("Arial",Font.BOLD | Font.ITALIC,25); btn1.setFont(font);pnBox.add(btn1); JButton btn2=new JButton("X_AXIS"); btn2.setForeground(Color.BLUE); btn2.setFont(font);pnBox.add(btn2); JButton btn3=new JButton("Y_AXIS"); btn3.setForeground(Color.ORANGE); btn3.setFont(font);pnBox.add(btn3); JPanel.add(pnBox); } }
package leetcode; /** * @author kangkang lou */ public class Main_162 { public int findPeakElement(int[] nums) { if (nums.length == 2) { return nums[0] > nums[1] ? 0 : 1; } for (int i = 1; i < nums.length - 1; i++) { if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) { return i; } if (i == nums.length - 2 && nums[i + 1] > nums[i]) { return nums.length - 1; } } return 0; } public int findPeakElement0(int[] num) { return helper(num, 0, num.length - 1); } public int helper(int[] num, int start, int end) { if (start == end) { return start; } else if (start + 1 == end) { if (num[start] > num[end]) return start; return end; } else { int m = (start + end) / 2; if (num[m] > num[m - 1] && num[m] > num[m + 1]) { return m; } else if (num[m - 1] > num[m] && num[m] > num[m + 1]) { return helper(num, start, m - 1); } else { return helper(num, m + 1, end); } } } public static void main(String[] args) { } }
package com.library.bexam.common.util; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; /** * 执行sql文件工具 * * @auther yuk * @Time 2017/9/16 14:08 */ public class SQLExecuteUtils { /** * 连接信息 */ private static String url = ""; private static String userName = ""; private static String password = ""; private static String[] params = new String[0]; private SQLExecuteUtils() { } /** * 获取sql执行工具 * 通过配置文件读取数据库url,用户名,密码信息 * * @return */ public static SQLExecuteUtils geInstance(String[] param) { loadProperties(); params = param; return new SQLExecuteUtils(); } private static void loadProperties() { Properties pro = new Properties(); try { pro.load(new FileInputStream(PathUtil.getPath(PathUtil.PathType.CONFIG) + "application.properties")); //数据库连接地址 url = pro.getProperty("spring.datasource.url"); //数据库用户名 userName = pro.getProperty("spring.datasource.username"); //数据库密码 password = pro.getProperty("spring.datasource.password"); } catch (IOException e) { e.printStackTrace(); } } /** * 获取sql执行工具 * 通过配置文件读取数据库url,用户名,密码信息 * * @return */ public static SQLExecuteUtils getInstance() { loadProperties(); return new SQLExecuteUtils(); } /** * 执行sql * * @param sqlContent * @param dbName * @param sqlDelimiter */ public boolean executeUserSQLFile(String sqlContent, String dbName, String sqlDelimiter) { SQLExecutor sqlExecutor; String temp = ""; if (params != null && params.length > 0) { StringBuilder stringBuilder = new StringBuilder(); for (String str : params) { stringBuilder.append(str + "&"); } temp = stringBuilder.toString().substring(0, stringBuilder.length() - 1); } sqlExecutor = new SQLExecutor("com.mysql.jdbc.Driver", url.split("\\?")[0].replaceAll(dbName, "") + "?" + temp + "useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true", userName, password, sqlDelimiter); try { sqlExecutor.importFile(sqlContent); } catch (Exception e) { e.printStackTrace(); return false; } return true; } }
package com.anonymous.emojiproject.Presenters; import android.content.Context; import android.content.DialogInterface; import android.preference.PreferenceManager; import android.support.v7.app.AlertDialog; import com.anonymous.emojiproject.Models.AsyncContainer; import com.anonymous.emojiproject.Models.EmojiModel; import com.anonymous.emojiproject.R; import com.anonymous.emojiproject.Utils.ExtraUtils; import com.anonymous.emojiproject.Utils.FetchData; import com.anonymous.emojiproject.Utils.TranslateTask; import com.anonymous.emojiproject.Views.EmojiView; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; public class EmojiPresenter { private EmojiView emojiView; private List<EmojiModel> emojiModelList; private TranslateTask translateTask; public EmojiPresenter(EmojiView emojiView){ this.emojiView = emojiView; } public void loadEmoji(final Context context){ if (ExtraUtils.isConnected(context)) { try { String json = new FetchData().execute().get(); emojiModelList = ExtraUtils.parseJSON(json); PreferenceManager.getDefaultSharedPreferences(context).edit() .putString("theJson",json).apply(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } else { String json = PreferenceManager. getDefaultSharedPreferences(context).getString("theJson", ""); emojiModelList = ExtraUtils.parseJSON(json); } } public void parseEmojiSentence(String string) throws ExecutionException, InterruptedException { translateTask = new TranslateTask(); emojiView.displayEmoji(translateTask.execute(new AsyncContainer(string,(ArrayList) emojiModelList)).get()); } public void checkFirstOpen(Context context){ if (ExtraUtils.isFirstOpen(context) && !ExtraUtils.isConnected(context)) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.network_unavailable_title); builder.setMessage(R.string.network_unavailabl_content); String positiveText = context.getString(android.R.string.ok); builder.setPositiveButton(positiveText, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { emojiView.finishActivity(); } }); AlertDialog dialog = builder.create(); dialog.show(); } else loadEmoji(context); } public ArrayList<EmojiModel> getEmojiList(){ return (ArrayList<EmojiModel>) emojiModelList; } public void share(String string) { emojiView.shareEmoji(string); } }
package com.goldgov.portal.studyreviews.service; import com.goldgov.gtiles.core.service.Query; public class StudyReviewsQuery extends Query<StudyReviews> { private String searchUserId; private String searchPartyOrgID; private String searchReviewsTitle; private String searchUserName; private String createTimeSort; private String searchIndex; private Integer searchReviewsType; public Integer getSearchReviewsType() { return searchReviewsType; } public void setSearchReviewsType(Integer searchReviewsType) { this.searchReviewsType = searchReviewsType; } public String getSearchUserId() { return searchUserId; } public void setSearchUserId(String searchUserId) { this.searchUserId = searchUserId; } public String getSearchPartyOrgID() { return searchPartyOrgID; } public void setSearchPartyOrgID(String searchPartyOrgID) { this.searchPartyOrgID = searchPartyOrgID; } public String getSearchReviewsTitle() { return searchReviewsTitle; } public void setSearchReviewsTitle(String searchReviewsTitle) { this.searchReviewsTitle = searchReviewsTitle; } public String getSearchUserName() { return searchUserName; } public void setSearchUserName(String searchUserName) { this.searchUserName = searchUserName; } public String getCreateTimeSort() { return createTimeSort; } public void setCreateTimeSort(String createTimeSort) { this.createTimeSort = createTimeSort; } public String getSearchIndex() { return searchIndex; } public void setSearchIndex(String searchIndex) { this.searchIndex = searchIndex; } }
package Puzzles.Heritage; import java.io.IOException; import java.util.Scanner; /** * Created by skyll on 24.05.2016. */ public class HeritageRunner { public static void main(String[] args) { final int count = 100; Case[] cases = new Case[count]; initCases(cases); printCases(cases); for (int i = 0; i < cases.length; i++) { for (int j = 0; j < cases.length; j++) { if ((j+1)%(i+1) == 0) { cases[j].changeStatus(); } } //printCases(cases); //new Scanner(System.in).next(); } printCases(cases); } public static void printCases(Case[] cases) { int i = 0; for (Case aCase : cases) { if (i < 10) System.out.print("0"); System.out.print(++i + ": " +aCase.isOpened() + "\t"); if (i%5 == 0) System.out.println("\t"); if (i%10 == 0) System.out.println("\n"); } } public static void initCases(Case[] cases) { int i = 0; for (Case aCase : cases) { cases[i++] = new Case(); } } }