text
stringlengths
10
2.72M
package com.goldgov.dygl.module.partyorganization.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.goldgov.dygl.dynamicfield.DynamicField; import com.goldgov.dygl.module.partyorganization.service.PartyOrganizationQuery; import com.goldgov.gtiles.core.dao.mybatis.annotation.MybatisRepository; @MybatisRepository("IPartyOrganizationDao_ACB") public interface IPartyOrganizationDao_ACB { void addInfo(@Param("fields") DynamicField field,@Param("poACID") String poACID); void updateInfo(@Param("entityID") String entityID,@Param("fields") DynamicField field); void deleteInfo(@Param("ids") String[] entityIDs); Map<String, Object> findInfoById(@Param("id") String entityID,@Param("fields") DynamicField field); List<Map<String,Object>> findInfoListByPage(@Param("query") PartyOrganizationQuery poQuery,@Param("fields") DynamicField fields); Integer isExistMember(@Param("userId") String userId,@Param("poACID") String poACID); List<Map<String,String>> findInfoMap(@Param("ids")String[] ids); }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.frontend.client.panel.bottom; import java.util.Date; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HasAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.openkm.frontend.client.Main; import com.openkm.frontend.client.widget.UserInfo; /** * Bottom panel * * @author jllort * */ public class BottomPanel extends Composite { public static final int PANEL_HEIGHT = 30; private HorizontalPanel panel; private Label statusMsg; private SimplePanel spLeft; private SimplePanel spRight; public UserInfo userInfo; private String key = ""; private Timer removeStatus; private String aditionalErrorMsg = ""; /** * BottomPanel */ public BottomPanel() { userInfo = new UserInfo(); panel = new HorizontalPanel(); spLeft = new SimplePanel(); spRight = new SimplePanel(); statusMsg = new Label(""); statusMsg.setStyleName("okm-Input"); statusMsg.setSize("340px","15px"); statusMsg.setHorizontalAlignment(HasAlignment.ALIGN_LEFT); spLeft.setWidth("10px"); spRight.setWidth("10px"); panel.add(spLeft); panel.add(userInfo); panel.add(statusMsg); panel.add(spRight); panel.setCellWidth(spLeft,"10px"); panel.setCellWidth(spRight,"10px"); panel.setCellHorizontalAlignment(userInfo, HasAlignment.ALIGN_LEFT); panel.setCellHorizontalAlignment(statusMsg, HasAlignment.ALIGN_RIGHT); panel.setCellHorizontalAlignment(spRight, HasAlignment.ALIGN_RIGHT); panel.setCellVerticalAlignment(userInfo, HasAlignment.ALIGN_MIDDLE); panel.setCellVerticalAlignment(statusMsg, HasAlignment.ALIGN_MIDDLE); panel.setStyleName("okm-bottomPanel"); panel.addStyleName("okm-DisableSelect"); panel.setHorizontalAlignment(VerticalPanel.ALIGN_LEFT); panel.setSize("100%", "100%"); initWidget(panel); } /** * Sets the size * * @param width the width size * @param height the height size */ public void setSize(int width, int height) { panel.setSize(""+width+"px", ""+height+"px"); } /** * Sets the status * * @param key The status value * @param error Is error or not */ public void setStatus(String msg) { aditionalErrorMsg = ""; // Always we ensure remove status here might be disabled to prevent removing new status data if (removeStatus!=null) { removeStatus.cancel(); removeStatus = null; } statusMsg.removeStyleName("okm-Input-Error"); statusMsg.setText(msg); } /** * Sets the status * * @param key The status value * @param error Is error or not */ public void setStatus(String key, boolean error) { this.key = key; aditionalErrorMsg = ""; // Always we ensure remove status here might be disabled to prevent removing new status data if (removeStatus!=null) { removeStatus.cancel(); removeStatus = null; } if (error) { statusMsg.addStyleName("okm-Input-Error"); DateTimeFormat dtf = DateTimeFormat.getFormat(Main.i18n("general.hour.pattern")); aditionalErrorMsg = " - " + dtf.format(new Date()); // On error case we reset status at 2 minutes removeStatus = new Timer() { public void run() { resetStatus(); } }; removeStatus.schedule(120*1000); // 2 min } else { statusMsg.removeStyleName("okm-Input-Error"); } statusMsg.setText(" "+Main.i18n(key) + aditionalErrorMsg ); } /** * Sets the status code * * @param key The status code key * @param error Is error or not * @param errorCode The code error */ public void setStatus(String key, boolean error, int errorCode) { this.key = key; aditionalErrorMsg = ""; // Always we ensure remove status here might be disabled to prevent removing new status data if (removeStatus!=null) { removeStatus.cancel(); removeStatus = null; } if (error) { statusMsg.addStyleName("okm-Input-Error"); DateTimeFormat dtf = DateTimeFormat.getFormat(Main.i18n("general.hour.pattern")); aditionalErrorMsg = " (" + errorCode +") - " + dtf.format(new Date()); // On error case we reset status at 2 minutes removeStatus = new Timer() { public void run() { resetStatus(); } }; removeStatus.schedule(120*1000); // 2 min } else { statusMsg.removeStyleName("okm-Input-Error"); } statusMsg.setText(" "+Main.i18n(key) + aditionalErrorMsg); } /** * Resets the status value */ public void resetStatus(){ statusMsg.setText(""); statusMsg.removeStyleName("okm-Input-Error"); } /** * Lang refresh */ public void langRefresh() { statusMsg.setText(" "+Main.i18n(key) + aditionalErrorMsg); userInfo.langRefresh(); } }
/* * Created on May 19, 2004 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package com.ibm.ive.tools.japt; import java.io.Serializable; /** * @author sfoley * * A specifier specifies a class, method, field or resource item. For it to be conditional * means that it only specifies such an item if a condition is met, which is the existence in the * repository of some other item. * @param specifierString the form of this string is the following:<br> * [?][conditionIdentifier:]itemIdentifier<br> * where conditionalIdentifier has the form [[method|field]:]itemIdentifier<br> * and the optional '?' means silent, which means failure of the specifier to match an existing * class, field, method, resource or other item will not generate a warning or error message<br> * For a conditional identifier, the absence of [method|field]: means that itemIdentifier * identifies a class or interface. * <p> * Item identifiers take the standard java forms of identifying classes, fields and methods. * See the ItemIdentifier class for details. * <p> * A specifier is resolvable if all its contained identifiers are resolvable. */ public class Specifier implements Serializable { private static final char silentFail = '?'; private static final char divider = ':'; private String condition; private Identifier identifier; private String fullString; public Specifier(String specifierString) { this(specifierString, null); } public Specifier(String specifierString, String from) { this(specifierString, from, true); } public Specifier(String specifierString, boolean resolvable) { this(specifierString, null, resolvable); } public Specifier(String specifierString, String from, boolean resolvable) { fullString = specifierString; boolean isSilent = false; if(specifierString.length() > 0 && specifierString.charAt(0) == silentFail) { specifierString = specifierString.substring(1); isSilent = true; } int index = specifierString.lastIndexOf(divider); if(index > 0) { condition = specifierString.substring(0, index); specifierString = specifierString.substring(index + 1); } identifier = new Identifier(specifierString, isSilent, from, resolvable); } public Specifier(Identifier ident) { fullString = ident.toString(); identifier = ident; } public Specifier append(String string) { return new Specifier(fullString + string, identifier.getFrom()); } public String getFullString() { return fullString; } public String getCondition() { return condition; } public boolean isConditional() { return condition != null; } public Identifier getIdentifier() { return identifier; } public boolean isRule() { return identifier.isRule(); } public String toString() { return fullString; } public boolean equals(Object o) { if(!(o instanceof Specifier)) { return false; } Specifier other = (Specifier) o; return (condition == null ? (other.condition == null): condition.equals(other.condition)) && identifier.equals(other.identifier); } public void setResolvable(boolean resolvable) { identifier.setResolvable(resolvable); } public boolean conditionIsTrue(JaptRepository repository) throws InvalidIdentifierException { if(!isConditional()) { return true; } return new ConditionalInterfaceItemCollection(repository, identifier.getFrom(), identifier.isResolvable(), condition).conditionIsTrue(); } }
/* * 有关数据库的操作类 * 更新时间: * ZQW-2018-03-14 * ZQW-2018-03-15 */ package model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import viewer.ConnectInterface; public class DataBase { private DataBase() {} private static String DRIVER = "com.mysql.jdbc.Driver"; // 不同的数据库需要加载不同的参数,这里加载的是MySQL数据库的驱动 private static String USER = "root"; // MySQL配置时的用户名 private static String PASSWORD = "326623"; // MySQL配置时的密码 //反馈连接数据库状态的方法 public static boolean linkDataBase() { try { Class.forName(DRIVER);//注册驱动/加载驱动 Connection connection = DriverManager.getConnection( "jdbc:mysql://" + ConnectInterface.IP +":3306/ways", USER, PASSWORD); //建立连接对象 /连接数据库 Statement statement = connection.createStatement(); //创建Statement/PreparedStatement对象,用来执行SQL语句 statement.close(); connection.close(); return true; } catch(Exception e) { e.printStackTrace(); return false; } } //查询方法 public static String searchDataBase(String tablename, String Code, String code, String keyword, boolean which) { String data = ""; //存储字段数据 String Sql = ""; //存储SQL语句 if(which) Sql = "select * from " + tablename + " where " + Code + " = '" + code +"'"; //精准查询的SQL语句 else Sql = "select * from " + tablename + " where " + Code + " like '%" + keyword + "%' or Nickname like '%" + keyword + "%' or Birthday like '%" + keyword + "%'"; //模糊查询的SQL语句 try { Class.forName(DRIVER);//注册驱动/加载驱动 Connection connection = DriverManager.getConnection( "jdbc:mysql://" + ConnectInterface.IP +":3306/ways", USER, PASSWORD); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(Sql);//结果集 while(rs.next()) { if(which) data = rs.getString(keyword); else { data = data.concat(rs.getString("Code").concat(" - "));//通过模糊查询获得一个字段的一组数据 switch(rs.getString("Nickname").length()) {//方便管理 case 2:data = data.concat(rs.getString("Name").concat(" ;"));break; case 3:data = data.concat(rs.getString("Name").concat(" ;"));break; case 4:data = data.concat(rs.getString("Name").concat(" ;"));break; case 5:data = data.concat(rs.getString("Name").concat(" ;"));break; case 6:data = data.concat(rs.getString("Name").concat(" ;"));break; case 7:data = data.concat(rs.getString("Name").concat(" ;"));break; case 8:data = data.concat(rs.getString("Name").concat(";"));break; default:break; } } } rs.close(); statement.close(); connection.close(); } catch(Exception e) { e.printStackTrace(); data = ""; } return data; } //单个字段标准模糊查询 public static String searchProbable(String tablename, String name, String which, String keyword) { String data = ""; //存储字段数据 String Sql = "select * from " + tablename + " where " + name + " like '%" + keyword + "%'"; //模糊查询的SQL语句; try { Class.forName(DRIVER);//注册驱动/加载驱动 Connection connection = DriverManager.getConnection( "jdbc:mysql://" + ConnectInterface.IP +":3306/ways", USER, PASSWORD); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(Sql);//结果集 while(rs.next()) { data = data.concat(rs.getString(which).concat("-"));//通过模糊查询获得一个字段的一组数据 } rs.close(); statement.close(); connection.close(); } catch(Exception e) { e.printStackTrace(); data = ""; } return data; } //查询整形方法 public static int queryDataBase(String tablename, String Code, String code, String keyword) { int data = 0; //存储字段数据 String Sql = ""; //存储SQL语句 Sql = "select * from " + tablename + " where " + Code + " = '" + code +"'"; //精准查询的SQL语句 try { Class.forName(DRIVER);//注册驱动/加载驱动 Connection connection = DriverManager.getConnection( "jdbc:mysql://" + ConnectInterface.IP +":3306/ways", USER, PASSWORD); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(Sql);//结果集 while(rs.next()) { data = rs.getInt(keyword); } rs.close(); statement.close(); connection.close(); } catch(Exception e) { e.printStackTrace(); data = 0; } return data; } //修改方法 public static boolean modifyDataBase(String tablename, String Code, String code, String keyword, String updatedata) { String Sql = "update " + tablename + " set " + keyword + " = '" + updatedata + "' where " + Code + " = '" + code + "'"; try { Class.forName(DRIVER);//注册驱动/加载驱动 Connection connection = DriverManager.getConnection( "jdbc:mysql://" + ConnectInterface.IP +":3306/ways", USER, PASSWORD); Statement statement = connection.createStatement(); statement.executeUpdate(Sql);//更新数据的SQL语句执行 statement.close(); connection.close(); return true; } catch(Exception e) { e.printStackTrace(); return false; } } //增加新账号方法 public static boolean insertDataBase(String code, String password, String nickname, String mailbox) { String Sql = "insert into user (Code, Password, Nickname, Mailbox) values (?, ?, ?, ?)"; try { Class.forName(DRIVER);//注册驱动/加载驱动 Connection connection = DriverManager.getConnection( "jdbc:mysql://" + ConnectInterface.IP +":3306/ways", USER, PASSWORD); PreparedStatement statement = connection.prepareStatement(Sql); statement.setString(1, code); statement.setString(2, password); statement.setString(3, nickname); statement.setString(4, mailbox); statement.executeUpdate(); statement.close(); connection.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } //增加新房间的方法 public static boolean insertRoomToDataBase (String tablename, String code, String property) { String Sql = "insert into " + tablename + " (Code, Property) values (?, ?)"; try { Class.forName(DRIVER);//注册驱动/加载驱动 Connection connection = DriverManager.getConnection( "jdbc:mysql://" + ConnectInterface.IP +":3306/ways", USER, PASSWORD); PreparedStatement statement = connection.prepareStatement(Sql); statement.setString(1, code); statement.setString(2, property); statement.executeUpdate(); statement.close(); connection.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } }
package com.tencent.mm.plugin.emoji.ui.v2; import android.graphics.Bitmap; import android.os.Message; import com.tencent.mm.ak.a.c.i; import com.tencent.mm.sdk.platformtools.bi; class EmojiStoreV2RewardUI$7 implements i { final /* synthetic */ String dat; final /* synthetic */ EmojiStoreV2RewardUI iqC; final /* synthetic */ String iqD; EmojiStoreV2RewardUI$7(EmojiStoreV2RewardUI emojiStoreV2RewardUI, String str, String str2) { this.iqC = emojiStoreV2RewardUI; this.iqD = str; this.dat = str2; } public final void a(String str, Bitmap bitmap, Object... objArr) { if (!bi.oW(str) && str.equalsIgnoreCase(this.iqD)) { Message message = new Message(); message.what = 1001; message.obj = this.dat; EmojiStoreV2RewardUI.j(this.iqC).sendMessage(message); } } }
package com.javakg.stroistat.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Attributes extends SuperForId { private String attribute; public Attributes() { } public Attributes(String attribute) { this.attribute = attribute; } public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } }
/** * * ****************************************************************************** * MontiCAR Modeling Family, www.se-rwth.de * Copyright (c) 2017, Software Engineering Group at RWTH Aachen, * All rights reserved. * * This project is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 of the License, or (at your option) any later version. * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this project. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* */ package de.monticore.lang.monticar.cnnarch._symboltable; import de.monticore.lang.monticar.cnnarch.helper.ErrorCodes; import de.monticore.lang.monticar.cnnarch.helper.Utils; import de.monticore.lang.monticar.cnnarch.predefined.AllPredefinedLayers; import de.monticore.lang.monticar.types2._ast.ASTElementType; import de.monticore.symboltable.Scope; import de.monticore.symboltable.Symbol; import de.se_rwth.commons.logging.Log; import java.util.*; public class IOSymbol extends ArchitectureElementSymbol { private ArchSimpleExpressionSymbol arrayAccess = null; private IODeclarationSymbol definition; protected IOSymbol(String name) { super(name); } public Optional<ArchSimpleExpressionSymbol> getArrayAccess() { return Optional.ofNullable(arrayAccess); } protected void setArrayAccess(ArchSimpleExpressionSymbol arrayAccess) { this.arrayAccess = arrayAccess; } protected void setArrayAccess(int arrayAccess) { this.arrayAccess = ArchSimpleExpressionSymbol.of(arrayAccess); this.arrayAccess.putInScope(getSpannedScope()); } //returns null if IODeclaration does not exist. This is checked in coco CheckIOName. public IODeclarationSymbol getDefinition() { if (definition == null){ this.definition = getArchitecture().resolveIODeclaration(getName()); } return definition; } @Override public boolean isResolvable() { return super.isResolvable() && getDefinition() != null; } @Override public boolean isInput(){ return getDefinition().isInput(); } @Override public boolean isOutput(){ return getDefinition().isOutput(); } @Override public boolean isAtomic(){ return getResolvedThis().isPresent() && getResolvedThis().get() == this; } @Override public List<ArchitectureElementSymbol> getFirstAtomicElements() { if (getResolvedThis().isPresent() && getResolvedThis().get() != this){ return getResolvedThis().get().getFirstAtomicElements(); } else { return Collections.singletonList(this); } } @Override public List<ArchitectureElementSymbol> getLastAtomicElements() { if (getResolvedThis().isPresent() && getResolvedThis().get() != this){ return getResolvedThis().get().getLastAtomicElements(); } else { return Collections.singletonList(this); } } @Override public Set<VariableSymbol> resolve() throws ArchResolveException { if (!isResolved()) { if (isResolvable()) { resolveExpressions(); getDefinition().getType().resolve(); if (!getArrayAccess().isPresent() && getDefinition().getArrayLength() > 1){ //transform io array into parallel composite List<ArchitectureElementSymbol> parallelElements = createExpandedParallelElements(); CompositeElementSymbol composite = new CompositeElementSymbol.Builder() .parallel(true) .elements(parallelElements) .build(); getSpannedScope().getAsMutableScope().add(composite); composite.setAstNode(getAstNode().get()); for (ArchitectureElementSymbol element : parallelElements){ element.putInScope(composite.getSpannedScope()); element.setAstNode(getAstNode().get()); } if (getInputElement().isPresent()){ composite.setInputElement(getInputElement().get()); } if (getOutputElement().isPresent()){ composite.setOutputElement(getOutputElement().get()); } composite.resolveOrError(); setResolvedThis(composite); } else { //Add port to the ports stored in ArchitectureSymbol if (getDefinition().isInput()){ getArchitecture().getInputs().add(this); } else { getArchitecture().getOutputs().add(this); } setResolvedThis(this); } } } return getUnresolvableVariables(); } private List<ArchitectureElementSymbol> createExpandedParallelElements() throws ArchResolveException{ List<ArchitectureElementSymbol> parallelElements = new ArrayList<>(getDefinition().getArrayLength()); if (getDefinition().isInput()){ for (int i = 0; i < getDefinition().getArrayLength(); i++){ IOSymbol ioElement = new IOSymbol(getName()); ioElement.setArrayAccess(i); parallelElements.add(ioElement); } } else { for (int i = 0; i < getDefinition().getArrayLength(); i++){ CompositeElementSymbol serialComposite = new CompositeElementSymbol(); serialComposite.setParallel(false); IOSymbol ioElement = new IOSymbol(getName()); ioElement.setArrayAccess(i); ioElement.setAstNode(getAstNode().get()); LayerSymbol getLayer = new LayerSymbol(AllPredefinedLayers.GET_NAME); getLayer.setArguments(Collections.singletonList( new ArgumentSymbol.Builder() .parameter(AllPredefinedLayers.INDEX_NAME) .value(ArchSimpleExpressionSymbol.of(i)) .build())); getLayer.setAstNode(getAstNode().get()); serialComposite.setElements(Arrays.asList(getLayer, ioElement)); parallelElements.add(serialComposite); } } return parallelElements; } @Override protected void computeUnresolvableVariables(Set<VariableSymbol> unresolvableVariables, Set<VariableSymbol> allVariables) { if (getArrayAccess().isPresent()){ getArrayAccess().get().checkIfResolvable(allVariables); unresolvableVariables.addAll(getArrayAccess().get().getUnresolvableVariables()); } getDefinition().getType().checkIfResolvable(allVariables); unresolvableVariables.addAll(getDefinition().getType().getUnresolvableVariables()); } @Override public List<ArchTypeSymbol> computeOutputTypes() { List<ArchTypeSymbol> outputShapes; if (isAtomic()){ if (isInput()){ outputShapes = Collections.singletonList(getDefinition().getType()); } else { outputShapes = Collections.emptyList(); } } else { if (!getResolvedThis().isPresent()){ throw new IllegalStateException("The architecture resolve() method was never called"); } outputShapes = getResolvedThis().get().computeOutputTypes(); } return outputShapes; } @Override public void checkInput() { if (isAtomic()) { if (isOutput()) { String name = getName(); if (getArrayAccess().isPresent()) { name = name + "[" + getArrayAccess().get().getIntValue().get() + "]"; } if (getInputTypes().size() != 1) { Log.error("0" + ErrorCodes.INVALID_ELEMENT_INPUT_SHAPE + " Invalid number of input streams. " + "The number of input streams for the output '" + name + "' is " + getInputTypes().size() + "." , getSourcePosition()); } else { ASTElementType inputType = getInputTypes().get(0).getDomain(); if (!Utils.equals(inputType, getDefinition().getType().getDomain())) { Log.error("0" + ErrorCodes.INVALID_ELEMENT_INPUT_DOMAIN + " " + "The declared output type of '" + name + "' does not match with the actual type. " + "Declared type: " + getDefinition().getType().getDomain().getTElementType().get() + ". " + "Actual type: " + inputType.getTElementType().get() + "."); } } } } else { if (!getResolvedThis().isPresent()){ throw new IllegalStateException("The architecture resolve() method was never called"); } getResolvedThis().get().checkInput(); } } @Override public Optional<Integer> getParallelLength() { return Optional.of(getDefinition().getArrayLength()); } @Override public Optional<List<Integer>> getSerialLengths() { return Optional.of(Collections.nCopies(getParallelLength().get(), 1)); } @Override protected void putInScope(Scope scope) { Collection<Symbol> symbolsInScope = scope.getLocalSymbols().get(getName()); if (symbolsInScope == null || !symbolsInScope.contains(this)) { scope.getAsMutableScope().add(this); if (getArrayAccess().isPresent()){ getArrayAccess().get().putInScope(getSpannedScope()); } } } @Override protected void resolveExpressions() throws ArchResolveException { if (getArrayAccess().isPresent()){ getArrayAccess().get().resolveOrError(); boolean valid; valid = Constraints.INTEGER.check(getArrayAccess().get(), getSourcePosition(), getName()); valid = valid && Constraints.NON_NEGATIVE.check(getArrayAccess().get(), getSourcePosition(), getName()); if (!valid){ throw new ArchResolveException(); } } } @Override protected ArchitectureElementSymbol preResolveDeepCopy() { IOSymbol copy = new IOSymbol(getName()); if (getAstNode().isPresent()){ copy.setAstNode(getAstNode().get()); } if (getArrayAccess().isPresent()) { copy.setArrayAccess(getArrayAccess().get().preResolveDeepCopy()); } return copy; } public static class Builder{ private ArchSimpleExpressionSymbol arrayAccess = null; private IODeclarationSymbol definition; public Builder arrayAccess(ArchSimpleExpressionSymbol arrayAccess){ this.arrayAccess = arrayAccess; return this; } public Builder arrayAccess(int arrayAccess){ this.arrayAccess = ArchSimpleExpressionSymbol.of(arrayAccess); return this; } public Builder definition(IODeclarationSymbol definition){ this.definition = definition; return this; } public IOSymbol build(){ if (definition == null){ throw new IllegalStateException("Missing declaration for IOSymbol"); } IOSymbol sym = new IOSymbol(definition.getName()); sym.setArrayAccess(arrayAccess); return sym; } } }
package com.estilox.application.config; public class ConnectionProperties { }
import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * 자바 데이터를 원하는 위치의 바이트를 읽을 수 있는 Stream * @author 이대용 * */ public class BufferedInputStreamExample { public static void main(String[] args) throws IOException { String path = "src/DataInputStreamExample.java"; BufferedInputStream in = new BufferedInputStream(new FileInputStream(path)); in.mark(0); int data = in.read(); data = in.read(); System.out.println(data); in.reset(); data = in.read(); System.out.println(data); in.skip(100); data = in.read(); System.out.println(data); in.close(); } }
package com.github.agmcc.slate.ast.statement; import com.github.agmcc.slate.ast.Node; import com.github.agmcc.slate.ast.Position; import com.github.agmcc.slate.ast.expression.Expression; import com.github.agmcc.slate.bytecode.Scope; import java.util.function.Consumer; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; import org.objectweb.asm.MethodVisitor; @Getter @Setter @RequiredArgsConstructor @AllArgsConstructor @EqualsAndHashCode @ToString public class Assignment implements Statement { private final String varName; private final Expression value; private Position position; @Override public void process(Consumer<Node> operation) { operation.accept(this); value.process(operation); } @Override public void generate(MethodVisitor mv, Scope scope) { final var variable = scope.getVariable(varName); value.pushAs(mv, scope, variable.getType()); mv.visitVarInsn(variable.getType().getOpcode(ISTORE), variable.getIndex()); } }
/* * Copyright 2007 Bastian Schenke 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 nz.org.take.r2ml.util; import nz.org.take.PropertyPredicate; /** * * * @author Bastian Schenke (bastian.schenke(at)googlemail.com) * */ public class R2MLPropertyPredicate extends PropertyPredicate { /** * */ public R2MLPropertyPredicate() { super(); } // /* (non-Javadoc) // * @see nz.org.take.PropertyPredicate#getSlotTypes() // */ // @Override // public Class[] getSlotTypes() { // // TODO Auto-generated method stub // return super.getSlotTypes(); // } // // // @Override public String getName() { return "p_" + super.getName(); } }
package br.com.repository; import org.springframework.data.jpa.repository.JpaRepository; import br.com.model.Doc; public interface UploadFileRepository extends JpaRepository<Doc, Integer>{ }
/* * Copyright (C) 2011-2014 Aestas/IT * * 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.aestasit.markdown.slidery.launcher; import java.io.IOException; import com.aestasit.markdown.slidery.configuration.Configuration; import com.aestasit.markdown.slidery.configuration.SimpleConfiguration; import com.aestasit.markdown.slidery.converters.ConverterFactory; import com.lexicalscope.jewel.cli.CliFactory; /** * Command-line launcher for Slidery. * * @author Andrey Adamovich * */ public final class SlideryMain { public static void main(final String[] args) { final Configuration config = new SimpleConfiguration(); try { final SlideryOptions options = CliFactory.parseArguments(SlideryOptions.class, args); config.configuration(options); ConverterFactory.createConverter(options.getFormat()).render(config); } catch (final IOException e) { e.printStackTrace(); } } }
/* * The MIT License (MIT) * * Copyright (c) 2020 Marcelo Guimarães <ataxexe@backpackcloud.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.backpackcloud.fakeomatic.process; import io.backpackcloud.fakeomatic.spi.Config; import io.backpackcloud.fakeomatic.spi.Endpoint; import io.backpackcloud.fakeomatic.spi.EndpointResponse; import io.backpackcloud.fakeomatic.spi.EventTrigger; import io.backpackcloud.fakeomatic.spi.Events; import io.backpackcloud.fakeomatic.spi.FakeOMatic; import io.backpackcloud.fakeomatic.spi.ResponseReceivedEvent; import io.backpackcloud.zipper.UnbelievableException; import io.quarkus.runtime.QuarkusApplication; import org.jboss.logging.Logger; import javax.enterprise.context.ApplicationScoped; import java.util.function.Consumer; import java.util.function.Function; @ApplicationScoped public class Generator implements QuarkusApplication, Events { private static final Logger LOGGER = Logger.getLogger(Generator.class); private final Config config; private final FakeOMatic fakeOMatic; private final EventTrigger eventTrigger; public Generator(Config config, FakeOMatic fakeOMatic, EventTrigger eventTrigger) { this.config = config; this.fakeOMatic = fakeOMatic; this.eventTrigger = eventTrigger; } @Override public int run(String... args) { int total = config.total(); int progressLog = Math.max(total / 100, 1); Endpoint endpoint = fakeOMatic.endpoint(config.endpoint()) .orElseThrow(UnbelievableException::new); GeneratorProcessInfo info = new GeneratorProcessInfo(); LOGGER.infof("Starting process... will generate %d payloads", total); info.startNow(); for (int i = 1; i <= total; i++) { if (i % progressLog == 0) { LOGGER.infof("Sending payload %d of %d", i, total); } endpoint.call() .exceptionally(logError(i)) .thenAccept(triggerEvents(i).andThen(updateStatistics(info))); } endpoint.waitForOngoingCalls(); info.endNow(); eventTrigger.trigger(FINISHED, info.toStatistics()); return 0; } private Function<Throwable, EndpointResponse> logError(int index) { return throwable -> { LOGGER.errorv(throwable, "Error while sending payload ({0})", index) ; return null; }; } private Consumer<EndpointResponse> updateStatistics(GeneratorProcessInfo statistics) { return response -> { if (response != null) { statistics.update(response); } }; } private Consumer<EndpointResponse> triggerEvents(int index) { return response -> { if (response != null) { ResponseReceivedEvent event = new ResponseReceivedEvent(index, response); eventTrigger.trigger(RESPONSE_RECEIVED, event); } }; } }
package com.prog3; public class NotEnoughDigitsException extends Exception{ public NotEnoughDigitsException(){ System.out.println("Entered value has not enough digits!"); } }
package uml; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleFloatProperty; import javafx.beans.property.SimpleStringProperty; import uml.FXML.Attribute; import uml.FXML.Box; import uml.FXML.Operation; import uml.FXML.Relation; import java.util.ArrayList; import java.util.List; /** * Created by sander on 01/04/17. */ public class VBoxModel implements Observable { //boxes -> relations, attributes and operations private SimpleStringProperty name; private List<Attribute> attributes; private List<Relation> relations; private List<Operation> operations; private SimpleFloatProperty row; private SimpleFloatProperty col; private SimpleFloatProperty width; private SimpleDoubleProperty height; public VBoxModel(Box box) { this.name = new SimpleStringProperty(box.getName()) ; this.attributes = box.getAttributes(); this.operations = box.getOperations(); this.relations = box.getRelations(); this.row = new SimpleFloatProperty(box.getRow()); this.col = new SimpleFloatProperty(box.getCol()); this.width = new SimpleFloatProperty(box.getWidth()); } //getters and setters public String getName() { return name.get(); } public void setName(String name) { this.name = new SimpleStringProperty(name); } public List<Attribute> getAttributes() { return attributes; } public void setAttributes(List<Attribute> attributes) { this.attributes = attributes; } public List<Operation> getOperations() { return operations; } public List<Relation> getRelations() { return relations; } public void setRelations(List<Relation> relations) { this.relations = relations; } public void setOperations(List<Operation> operations) { this.operations = operations; } public double getRow() { return row.doubleValue(); } public void setRow(Float row) { this.row = new SimpleFloatProperty(row); } public double getCol() { return col.doubleValue(); } public void setCol(Float col) { this.col = new SimpleFloatProperty(col); } public Double getWidth() { return width.doubleValue(); } public void setWidth(Float width) { this.width = new SimpleFloatProperty(width); } public List<InvalidationListener> getListenerList() { return listenerList; } public void setListenerList(List<InvalidationListener> listenerList) { this.listenerList = listenerList; } /** * private Float row; //distance to the right of the Box private Float col; //width of the Box private Float width; */ /** * Lijst van geregistreerde luisteraars. */ public void setName(Box box) { this.name = new SimpleStringProperty(box.getName()); } public void setAttributes(Box box) { this.attributes = box.getAttributes(); } public void setOperations(Box box) { this.operations = box.getOperations(); } private List<InvalidationListener> listenerList = new ArrayList<>(); private void fireInvalidationEvent() { for (InvalidationListener listener : listenerList) { listener.invalidated(this); } } public Double getHeight() { return height.get(); } public void setHeight(Double height) { this.height = new SimpleDoubleProperty(height); } @Override public String toString() { return "VBoxModel{" + "name='" + name + '\'' + ", attributes=" + attributes + ", relations=" + relations + ", operations=" + operations + ", row=" + row + ", col=" + col + ", width=" + width + ", listenerList=" + listenerList + '}'; } @Override public void addListener(InvalidationListener listener) { listenerList.add(listener); } @Override public void removeListener(InvalidationListener listener) { listenerList.remove(listener); } }
package com.amoraesdev.mobify.valueobjects; /** * Value Object to represent a Notification * @author Alessandro Moraes (alessandro at amoraesdev.com) */ public class Notification { private String[] usernames; private String type; private String message; public Notification(String[] usernames, String type, String message) { super(); this.usernames = usernames; this.type = type; this.message = message; } public String[] getUsernames() { return usernames; } public void setUsernames(String... usernames) { this.usernames = usernames; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
package api.longpoll.bots.methods.impl.messages; import api.longpoll.bots.adapters.deserializers.AttachmentDeserializer; import api.longpoll.bots.http.params.BoolInt; import api.longpoll.bots.methods.AuthorizedVkApiMethod; import api.longpoll.bots.methods.VkApiProperties; import api.longpoll.bots.model.objects.media.Attachment; import api.longpoll.bots.model.response.GenericResponse; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import java.util.Arrays; import java.util.List; /** * Implements <b>messages.getHistoryAttachments</b> method. * <p> * Returns media files from the dialog or group chat. * * @see <a href="https://vk.com/dev/messages.getHistoryAttachments">https://vk.com/dev/messages.getHistoryAttachments</a> */ public class GetHistoryAttachments extends AuthorizedVkApiMethod<GetHistoryAttachments.Response> { public GetHistoryAttachments(String accessToken) { super(accessToken); } @Override protected String getUrl() { return VkApiProperties.get("messages.getHistoryAttachments"); } @Override protected Class<Response> getResponseType() { return Response.class; } public GetHistoryAttachments setPeerId(int peerId) { return addParam("peer_id", peerId); } public GetHistoryAttachments setMediaType(String mediaType) { return addParam("media_type", mediaType); } public GetHistoryAttachments setStartFrom(String startFrom) { return addParam("start_from", startFrom); } public GetHistoryAttachments setCount(int count) { return addParam("count", count); } public GetHistoryAttachments setPhotoSizes(boolean photoSizes) { return addParam("photo_sizes", new BoolInt(photoSizes)); } public GetHistoryAttachments setFields(String... fields) { return setFields(Arrays.asList(fields)); } public GetHistoryAttachments setFields(List<String> fields) { return addParam("fields", fields); } public GetHistoryAttachments setGroupId(int groupId) { return addParam("group_id", groupId); } public GetHistoryAttachments setPreserveOrder(boolean preserveOrder) { return addParam("preserve_order", new BoolInt(preserveOrder)); } public GetHistoryAttachments setMaxForwardsLevel(int maxForwardsLevel) { return addParam("max_forwards_level", maxForwardsLevel); } @Override public GetHistoryAttachments addParam(String key, Object value) { return (GetHistoryAttachments) super.addParam(key, value); } /** * Response to <b>messages.getHistoryAttachments</b> request. */ public static class Response extends GenericResponse<Response.ResponseObject> { /** * Response object. */ public static class ResponseObject { /** * List of photo, video, audio or doc. */ @SerializedName("items") private List<Item> items; /** * Offset value. */ @SerializedName("next_from") private String nextFrom; /** * Describes list item. */ public static class Item { /** * Message ID. */ @SerializedName("message_id") private Integer messageId; /** * Attachment. */ @SerializedName("attachment") @JsonAdapter(AttachmentDeserializer.class) private Attachment attachment; public Integer getMessageId() { return messageId; } public void setMessageId(Integer messageId) { this.messageId = messageId; } public Attachment getAttachment() { return attachment; } public void setAttachment(Attachment attachment) { this.attachment = attachment; } @Override public String toString() { return "Item{" + "messageId=" + messageId + ", attachment=" + attachment + '}'; } } public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } public String getNextFrom() { return nextFrom; } public void setNextFrom(String nextFrom) { this.nextFrom = nextFrom; } @Override public String toString() { return "ResponseObject{" + "items=" + items + ", nextFrom='" + nextFrom + '\'' + '}'; } } } }
package com.bijietech.model; /** * Created by Lip on 2016/8/9 0009. * 查询多个产品的详情 */ public class MultiQueryCmd extends Cmd{ private String exchangeName; public String getExchangeName() { return exchangeName; } public void setExchangeName(String exchangeName) { this.exchangeName = exchangeName; } @Override public String toString() { StringBuilder sb=new StringBuilder(); sb.append("查询命令:").append(getContent()).append("\n") .append("交易所:").append(getExchangeName()).append("\n"); return sb.toString(); } }
/* * Created on Nov 6, 2006 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package com.ibm.ive.tools.japt.testcase; /** * * @author sfoley * * This class is primarily designed to test the casting optimizations for startup performance. * * It contains various methods which normally cause the verifier to load the class SomeException but * with all the upcast optimizations this class will not be needed. * * It also contains various other methods to test the dataflow analyzer used for the casting optimizations and * for stackmap creation. */ public class TestUpcast8 { /** * these are examples that do not generate verifier class loads. They are here in the event that * in the future if they DO generate class loads, then the upcast code can be modified to account for this. */ void falseAlarms(SomeException x) { /* the verifier should not load SomeException to verify that it implements SomeInterface, which is the * target interface of the following instruction. */ x.anInterfaceMethod(); /* * the verifier should not load SomeOtherException to verify that it is a subclass of SomeException. This is done * when the aastore instruction is executed at runtime. */ SomeException exc[] = new SomeException[1]; exc[0] = new SomeOtherException(); } /** * @param args */ public static void main(String[] args) { /* * How this will work is the reduction extension and the upcast extension will combine: * Reduction will remove the SomeException class from the japt output. * This can be done by explicitly removing the class with the reduction extension. * The upcast will prevent the class from being required for the verifier to do its work. */ System.out.println("ran upcast test"); } }
package it.htm.dao; import it.htm.entity.Task; import java.util.List; /** * Created by vincenzo on 27/11/16. */ public interface TaskDao { public List<Task> retrieveTaskBySlicingId(int id); public List<Task> retrieveTasks(); public Task getTaskById(int id); public void updateState(Task t); }
package Objets; import java.io.Serializable; public class Course implements Serializable { private static final long serialVersionUID = 1L; private int CID; private String name; private int year; private boolean compulsory; private Department departement; // Constructor public Course() { } // Getters public int getCID() { return CID; } public String getName() { return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase(); } public int getYear() { return year; } public boolean isCompulsory() { return compulsory; } // Setters public void setCID(int CID) { this.CID = CID; } public void setName(String name) { this.name = name.toLowerCase(); } public void setYear(int year) { this.year = year; } public void setCompulsory(boolean compulsory) { this.compulsory = compulsory; } public Department getDepartement() { return departement; } public void setDepartement(Department departement) { this.departement = departement; } public String getNiveau() { switch(year) { case 0: return "Tous niveaux"; case 1: return "L1"; case 2: return "L2"; case 3: return "L3"; case 4: return "M1"; case 5: return "M2"; } return ""; } @Override public String toString() { return getName() + " " + getNiveau(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + CID; result = prime * result + (compulsory ? 1231 : 1237); result = prime * result + ((departement == null) ? 0 : departement.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + year; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Course other = (Course) obj; if (CID != other.CID) return false; if (compulsory != other.compulsory) return false; if (departement == null) { if (other.departement != null) return false; } else if (!departement.equals(other.departement)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (year != other.year) return false; return true; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Vector; public class PatentInfo { Vector<SearchTerm> terms = new Vector<SearchTerm>(); String urlStr; String title; String uspc; String cpc; String description; String claims; public PatentInfo(String address, Vector<String> t) { for (int i = 0; i < t.size(); i++) { terms.add(new SearchTerm(t.get(i))); } urlStr = address; try { URL url = new URL(urlStr); InputStream is = url.openStream(); // throws an IOException BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { if (line.contains("<meta name=\"title\"")) { System.out.println(line); title = line.substring(line.indexOf("content=") + 9, line.indexOf('>') - 5); } else if (line.contains("<!-- Abstract -->")) { } } is.close(); } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { // } } public void addToTermCount(String term, int count) { for (int i = 0; i < terms.size(); i++) { if (terms.get(i).getTerm() == term) terms.get(i).add(count); } } public String getURL() { return urlStr; } public int getTotalTermCount() { int count = 0; for (int i = 0; i < terms.size(); i++) { count += terms.get(i).getCount(); } return count; } public int getTermCount(String term) { int count = 0; for (int i = 0; i < terms.size(); i++) { if (terms.get(i).getTerm() == term) count = terms.get(i).getCount(); } return count; } public int getUniqueTermCount() { int count = 0; for (int i = 0; i < terms.size(); i++) { if (terms.get(i).getCount() > 0) count++; } return count; } public void sortTerms() { for (int i = 0; i < terms.size(); i++) { if (i < terms.size() - 1) { for (int i2 = i + 1; i2 < terms.size(); i2++) { if (terms.get(i).getCount() < terms.get(i2).getCount()) { Collections.swap(terms, i, i2); } } } } } public Vector<SearchTerm> getTerms() { return terms; } public int getConceptCount(Vector<Concept> concepts) { int conceptCount = 0; for (int i = 0; i < concepts.size(); i++) { for (int i2 = 0; i2 < concepts.get(i).getTerms().size(); i2++) { for (int i3 = 0; i3 < terms.size(); i3++) { if (concepts.get(i).getTerms().get(i2) == terms.get(i3).getTerm() && terms.get(i3).getCount() > 0) { //System.out.println("@@@@@@ " + concepts.get(i).getTerms().get(i2) + " : " + terms.get(i3).getTerm()); conceptCount++; i3 = terms.size(); i2 = concepts.get(i).getTerms().size(); } } } } return conceptCount; } public String getTitle() { return title; } public String getAsignee() { return title; } }
package org.codeshifts.spring.core.contextconfiguration; import org.springframework.context.annotation.Configuration; @Configuration public class BeanA { private String beanValue; public String getBeanValue() { return beanValue; } public void setBeanValue(String beanValue) { this.beanValue = beanValue; } }
class Node { Node next; int data; Node(int data) { this.data = data; } } public class SumOfLinkedList { public Node addList(Node l1, Node l2) { Node head = new Node(0); Node l3 = head; int sum = 0; while (l1 != null && l2 != null) { sum = l1.data + l2.data + sum / 10; l3.next = new Node(sum % 10); l1 = l1.next; l2 = l2.next; l3 = l3.next; } Node rest = l1 != null ? l1 : l2; while (rest != null) { sum = rest.data + sum / 10; l3.next = new Node(sum % 10); rest = rest.next; l3 = l3.next; } if (sum / 10 != 0) { l3.next = new Node(1); } return head.next; } public static Node createLinkedList(int[] arr) { Node head = new Node(0); Node p = head; for (int i = 0; i < arr.length; i++) { p.next = new Node(arr[i]); p = p.next; } return head.next; } public static void printLinkedList(Node n) { Node p = n; while (p != null) { System.out.print(p.data + "->"); p = p.next; } System.out.println("null"); } public static void main(String[] args) { SumOfLinkedList sol = new SumOfLinkedList(); int[][] arrs = { {1},{}, {1}, {9}, {1}, {2, 3}, {1, 2, 3}, {5, 6, 7}, }; int count = arrs.length / 2; for (int i = 0; i < count; i++) { System.out.println("==== Test ===="); Node l1 = createLinkedList(arrs[2*i]); Node l2 = createLinkedList(arrs[2*i+1]); Node l3 = sol.addList(l1, l2); printLinkedList(l1); printLinkedList(l2); printLinkedList(l3); } } }
package org.mge.designpatterns.decorator.decorators; import org.mge.designpatterns.decorator.components.Beverage; public class Whip implements CondimentDecorator { Beverage beverage; public Whip(Beverage beverage) { this.beverage = beverage; } @Override public String getDescription() { return beverage.getDescription() + ", Whip"; } @Override public double getCost() { return 2 + beverage.getCost(); } }
package ace.life.ina.utility; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; import org.apache.log4j.Logger; /** * @author CHAHYADIS * @since January, 27, 2014 */ public class PropertiesReader { private static Logger log = Logger.getLogger(PropertiesReader.class); /** * Read internal properties file. * <p/> * Use this method for development. * * @return {@link Properties} */ public static Properties readPropsIn() { Properties props = new Properties(); InputStream in = PropertiesReader.class.getClassLoader() .getResourceAsStream("config.properties"); try { props.load(in); } catch (Exception e) { log.error(e.getMessage()); } return props; } /** * Read content of external properties file. * <p/> * Use this method for production. * * @return {@link Properties} */ public static Properties readPropsExt() { Properties props = new Properties(); String path = PropertiesReader.class.getProtectionDomain() .getCodeSource().getLocation().toString().replace("%20", " "); System.out.println(">> " + path); int i; if (path.substring(6).indexOf(":/") > 0) { // buat windows i = 6; } else { i = 5; } int p = Utility.parseExtention(path, "/").length(); path = path.substring(i); System.out.println(">>1: " + path); path = path.substring(0, path.length() - p - 1); System.out.println(">>2: " + path); try { FileInputStream fis = new FileInputStream(new File(path + File.separator + "config.properties")); props.load(fis); fis.close(); } catch (Exception e) { log.error(e.getMessage()); } return props; } }
package org.jboss.forge.plugin.gitignore; import java.util.LinkedList; import java.util.List; public class GitIgnoreGroup { private final String name; private final List<String> templates; public GitIgnoreGroup(String name) { this(name, new LinkedList<String>()); } public GitIgnoreGroup(String name, List<String> templates) { this.name = name; this.templates = templates; } public void add(String template) { templates.add(template); } public String getName() { return name; } public List<String> getTemplates() { return templates; } }
package com.vaadin.polyglotdx; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import com.vaadin.connect.auth.server.EnableVaadinConnectOAuthServer; import com.vaadin.frontend.server.EnableVaadinFrontendServer; /** * Spring boot starter class. */ @SpringBootApplication @EnableVaadinConnectOAuthServer @EnableVaadinFrontendServer public class Application extends SpringBootServletInitializer { /** * Main method to run the application. * * @param args arguments */ public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } }
package com.hand6.health.domain.entity;/** * Created by Administrator on 2019/7/9. */ import com.fasterxml.jackson.annotation.JsonInclude; import com.hand6.health.bean.ExcelColumn; import io.choerodon.mybatis.annotation.ModifyAudit; import io.choerodon.mybatis.annotation.VersionAudit; import io.choerodon.mybatis.domain.AuditDomain; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import java.math.BigDecimal; import java.util.Date; /** * @author xxxx * @description * @date 2019/7/9 */ @ModifyAudit @VersionAudit @JsonInclude(JsonInclude.Include.NON_NULL) @Data @AllArgsConstructor @NoArgsConstructor @Table(name = "motion_summary") @Builder public class MotionSummary extends AuditDomain { @Id @GeneratedValue private Long id; private Long handUserId; @ExcelColumn(value = "工号",col = 0) private String handUserNumber; @ExcelColumn(value = "姓名",col = 1) private String handFullName; @ExcelColumn(value = "性别",col = 3) private String gender; @ExcelColumn(value = "跑步距离",col = 4) private BigDecimal runDistance; @ExcelColumn(value = "跑步配速",col = 5) private String runAvgSpeed; @ExcelColumn(value = "走路距离",col = 6) private BigDecimal walkDistance; @ExcelColumn(value = "走路配速",col = 7) private String walkAvgSpeed; @ExcelColumn(value = "骑行距离",col = 8) private BigDecimal rideDistance; @ExcelColumn(value = "骑行配速",col = 9) private String rideAvgSpeed; private BigDecimal otherDistince; private String otherAvgSpeed; @DateTimeFormat(pattern = "YYYY-MM-DD hh:mm;ss") private Date actionTime; private String status; @ExcelColumn(value = "状态",col = 2) @Transient private String statusDesc; @Transient private String startDate; @Transient private String endDate; }
package pl.edu.agh.game.logic.drawable; import com.badlogic.gdx.graphics.g2d.Animation.PlayMode; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import pl.edu.agh.game.graphics.Animation; import pl.edu.agh.game.graphics.AnimationType; import pl.edu.agh.game.logic.Direction; import pl.edu.agh.game.logic.entities.Character; import pl.edu.agh.game.logic.entities.projectiles.Weapon; import pl.edu.agh.game.logic.movement.MovementComponent; import pl.edu.agh.game.logic.stats.StatsComponent; import pl.edu.agh.game.stolen_assets.Debug; import java.util.Map; /** * @author - Lukasz Gmyrek * Created on 2015-04-16 */ public class DrawableComponent { private StatsComponent statsComponent; private MovementComponent movementComponent; private Animation animation; private Direction lastUsableDirection; private AnimationType animationType = AnimationType.STANDBY; private final Map<String, Animation> animationMap; private Character character; public DrawableComponent(Map<String, Animation> animationMap) { this.animationMap = animationMap; lastUsableDirection = Direction.SOUTH; animation = animationMap.get("south"); } public void draw(SpriteBatch batch) { float originX = animation.getOriginY() + 1; float originY = animation.getOriginX(); float x = movementComponent.getX(); float y = movementComponent.getY(); int scale = 4; batch.draw(animation.getCurrentFrame(), (int) x, (int) y, originX, originY, animation.getCurrentFrame().getRegionWidth(), animation.getCurrentFrame().getRegionHeight(), scale, scale, 0); Debug.drawDot(x, y, scale, batch); } public void update(float deltaTime) { switch (animationType) { case MOVEMENT: animation.update(deltaTime * statsComponent.getMovementSpeedMultiplier()); break; case ATTACK: animation.update(deltaTime * statsComponent.getAttackSpeedMultiplier()); break; default: animation.update(deltaTime * statsComponent.getMovementSpeedMultiplier()); } Direction direction = movementComponent.getDirection(); if (isFree()) { if (!direction.equals(Direction.LAST)) { animationType = AnimationType.MOVEMENT; lastUsableDirection = direction; animation = animationMap.get(lastUsableDirection.toString() + "-walk"); animation.setPlayMode(PlayMode.LOOP); } else if (direction.equals(Direction.LAST)) { animationType = AnimationType.STANDBY; animation = animationMap.get(lastUsableDirection.toString()); } } } public boolean isFree() { return animation.isFinished() || animation.getPlayMode().equals(PlayMode.LOOP) || animation.getPlayMode().equals(PlayMode.LOOP_PINGPONG) || animation.getPlayMode().equals(PlayMode.LOOP_RANDOM) || animation.getPlayMode().equals(PlayMode.LOOP_REVERSED); } public Direction getLastUsableDirection() { return lastUsableDirection; } public void setCharacter(Character character) { this.character = character; this.statsComponent = character.statsComponent; this.movementComponent = character.movementComponent; } /** * Check is animation is free before setting animation. * @param animationType */ public void setAnimation(AnimationType animationType) { switch (animationType) { case ATTACK: this.animationType = animationType; animation = animationMap.get(lastUsableDirection.toString() + "-attack"); animation.reset(); animation.setPlayMode(PlayMode.NORMAL); break; case CHANNELLING: this.animationType = animationType; animation = animationMap.get("channeling"); animation.reset(); animation.setPlayMode(PlayMode.NORMAL); break; } } public void setLastUsableDirection(Direction lastUsableDirection) { this.lastUsableDirection = lastUsableDirection; } public void setDrawable(Weapon weapon) { //System.out.println(animation.getOriginX()+" "+animation.getOriginY()); this.statsComponent = weapon.statsComponent; this.movementComponent = weapon.movementComponent; } }
package com.booking.hotelapi.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.booking.hotelapi.entity.RoomType; @Repository public interface RoomTypeRepository extends JpaRepository<RoomType, Long> { RoomType findByRoomTypeId(Integer id); }
package org.sang.mapper; import org.sang.bean.CompanyData; public interface CompanyDataMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table company_data * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ /** * This method was generated by MyBatis Generator. * This method corresponds to the database table company_data * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ /** * This method was generated by MyBatis Generator. * This method corresponds to the database table company_data * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ int deleteByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table company_data * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ int insert(CompanyData record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table company_data * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ int insertSelective(CompanyData record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table company_data * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ /** * This method was generated by MyBatis Generator. * This method corresponds to the database table company_data * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ CompanyData selectByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table company_data * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ /** * This method was generated by MyBatis Generator. * This method corresponds to the database table company_data * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ /** * This method was generated by MyBatis Generator. * This method corresponds to the database table company_data * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ int updateByPrimaryKeySelective(CompanyData record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table company_data * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ int updateByPrimaryKey(CompanyData record); }
package com.blackonwhite.model; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.util.ArrayList; import java.util.List; import java.util.Locale; @Entity @Getter @Setter @NoArgsConstructor @Table(name = "game_user") public class User { public enum Role { USER, MODERATOR, ADMIN } @Id private Integer chatId; private String name; private Integer roomId; private UserStatus status; private int winRate; private String blackCardId; private String blackCardMetaInf; private String whiteCardMetaInf; private Locale locale = new Locale("en"); @Enumerated(EnumType.STRING) private Role role; @OneToMany(cascade = CascadeType.REFRESH) private List<Card> cards = new ArrayList<>(); }
package com.smartwerkz.bytecode.vm; import com.smartwerkz.bytecode.primitives.JavaNullReference; public class Objects { private final VirtualMachine vm; private final Classes classes; public Objects(Classes classes, VirtualMachine vm) { this.classes = classes; this.vm = vm; } public JavaNullReference nullReference() { // Create a new NULL reference each time, so we can // back track it later if something happens. return new JavaNullReference(vm, classes); } }
package com.xiaoysec.hrm.business.document.service; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.xiaoysec.hrm.business.document.entity.Document; import com.xiaoysec.hrm.business.document.mapper.DocMapper; import com.xiaoysec.hrm.business.user.entity.User; import com.xiaoysec.hrm.common.base.Page; import com.xiaoysec.hrm.common.utils.FileUtils; @Service @Transactional(readOnly = true) public class DocService { @Autowired private DocMapper docMapper; // 分页查询 public Page<Document> findList(Page<Document> page, Map<String, Object> param) { Map<String, Object> query = new HashMap<String, Object>(); String title = (String) param.get("title"); if (StringUtils.isNotBlank(title)) { query.put("title", title); query.put("mode", "like"); } Integer start = page.getStart(); Integer size = page.getSize(); query.put("start", start); query.put("size", size); page.setList(docMapper.findList(query)); page.setCount(docMapper.getDocCount(query)); return page; } public Document getDocById(Integer id) { return docMapper.getDocById(id); } @Transactional(readOnly = false) public Map upload(Document document, HttpSession session, String hideTitle) { User user = (User) session.getAttribute("sessionUser"); Map<String, Object> result = new HashMap<String, Object>(); try { if(StringUtils.isBlank(document.getTitle())){ result.put("success", false); result.put("message", "文件名称不能为空"); return result; } if (!hideTitle.equals(document.getTitle())) { // 与原名字不相同 查重 boolean isExist = isExist(document); if(isExist){ result.put("success", false); result.put("message", "文件【"+document.getTitle()+"】已存在"); return result; } } if(document.getId() == null){ //新建 if(document.getFile() == null){ result.put("success", false); result.put("message", "请上传文件"); return result; } HashMap<String, Object> fileMap = new HashMap<String,Object>(); fileMap.put("word", 1); fileMap.put("csv", 2); fileMap.put("ppt", 3); fileMap.put("excel", 4); fileMap.put("txt", 5); //获取文件名称 int fileTypeIndex = document.getFile().getOriginalFilename().trim().split("\\.").length-1; String realType = document.getFile().getOriginalFilename().split("\\.")[fileTypeIndex].toLowerCase(); if(!fileMap.containsKey(realType)){ result.put("success", false); result.put("message", "目前只支持word,csv,ppt,excel,txt格式的文件"); return result; } String contextPath = session.getServletContext().getRealPath("/"); String dirPath = contextPath+"/file"; boolean flag = FileUtils.createDirectory(dirPath); String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())+"_"+document.getFile().getOriginalFilename().toLowerCase(); String realFileName = dirPath + "/" + fileName; File file = new File(realFileName); document.getFile().transferTo(file); document.setCreateBy(user); document.setCreateDate(new Date()); document.setFileName(fileName); docMapper.addDoc(document); }else{ //修改 document.setUpdateBy(user); document.setUpdateDate(new Date()); docMapper.updateDoc(document); } result.put("success", true); result.put("message", "文件信息保存成功"); } catch (Exception e) { if (document.getId() == null) { result.put("success", false); result.put("message", "文件上传失败"); } else { result.put("success", false); result.put("message", "文件信息修改失败"); } } return result; } private boolean isExist(Document document) { HashMap<String, Object> query = new HashMap<String,Object>(); String title = document.getTitle(); query.put("title", title); query.put("mode", "equals"); Integer docCount = docMapper.getDocCount(query); return docCount>0; } @Transactional(readOnly = false) public ResponseEntity<byte[]> download(Integer fileId,HttpServletRequest request) throws IOException { Document doc = docMapper.getDocById(fileId); String fileName = doc.getFileName(); String path = request.getSession().getServletContext().getRealPath("/")+"/file/"+fileName; File file = new File(path); HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment", fileName); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(org.apache.commons.io.FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED); } // 删除 @Transactional(readOnly = false) public void deleteDocById(Integer id) { docMapper.deleteDocById(id); } }
public class ElfoVerde extends Elfo { public ElfoVerde() { super(); } public ElfoVerde(String nome) { super(nome); } public boolean atirarFlechas() { if(this.flechas > 0) { this.experiencia += 2; this.flechas--; return true; } return false; } public void adicionarItemAoInventario(Item item) { if(item.getDescricao() == "Espada de aço valiriano" || item.getDescricao() == "Arco e Flecha de Vidro") this.inventario.adicionarItem(item); } }
package com.wipro.atm.webdriver.utils; import java.util.Date; public class Constants { private Constants() { } public static final String Browser = "chrome"; public static final String OPEN_CART = "http://10.207.182.108:81/opencart/"; public static final String TESTDATAPATH = "./ScenarioData/TestData.xls"; public static String Email; public static final String OUTLOOK_URL = "https://outlook.office.com/owa/?realm=wipro.com"; public static final int NO_OF_EXEC = 1; public static final int WAIT_TIME = 16; public static String getRandomEmail(String firstName, String lastName) { firstName = firstName.toLowerCase(); lastName = lastName.toLowerCase(); Date currDate = new Date(); long randomNumber = currDate.getTime(); String domain = "@wipro.com"; Email = firstName + lastName + randomNumber + domain; return Email; } }
public class RecoursionCountDown { int count; public static void main(String[] args) { RecoursionCountDown timer = new RecoursionCountDown(); //option with recursive case //timer.getCount(); timer.getCountIteration(); timer.showCountDown(); } public void getCount() { System.out.print("Enter a positive integer: "); java.util.Scanner input = new java.util.Scanner(System.in); count = input.nextInt(); if(count <= 0) { System.out.println("You must enter a positive number."); System.out.println("Try again!"); getCount(); } } public void getCountIteration() { do { System.out.println("Enter a positive number."); java.util.Scanner input = new java.util.Scanner(System.in); count = input.nextInt(); if(count <= 0) { System.out.println("Input must be a positive number."); System.out.println("Try again!"); } }while(count <= 0); } public void showCountDown() { System.out.println("Counting down: "); for(int i = count; i >= 0; i--) { System.out.print(i + ", "); } System.out.println("Blast off!"); } }
package com.arkaces.aces_marketplace_api.service_category; import lombok.Data; @Data public class ServiceCategory { private Long id; private String name; private Integer position; }
package com.mx.profuturo.bolsa.service.desk; import java.util.LinkedList; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.mx.profuturo.bolsa.model.desk.data.DatoCompuesto; import com.mx.profuturo.bolsa.model.desk.data.DatosCompuestosGrafica; import com.mx.profuturo.bolsa.model.desk.data.DatosGrafica; import com.mx.profuturo.bolsa.model.graphics.adapters.AreaChartAdapter; import com.mx.profuturo.bolsa.model.graphics.adapters.BarChartAdapter; import com.mx.profuturo.bolsa.model.graphics.adapters.DonutChartAdapter; import com.mx.profuturo.bolsa.model.graphics.adapters.StackedChartAdapter; @Service @Scope("request") public class DeskDataToChartServiceImpl implements DeskDataToChartService { @Override public StackedChartAdapter translateStackedChart(DatosCompuestosGrafica datos) { StackedChartAdapter adapter = new StackedChartAdapter(); if(datos != null) { adapter.setAxisX(datos.getEjeX()); adapter.setAxisY(datos.getEjeY()); LinkedList<DatoCompuesto> rows = datos.getDatos(); if(datos.getDatos() != null) { Integer max = datos.getDatos().size(); for(int i = 0; i < max; i++) { adapter.compute(rows.get(i).getPivote(),rows.get(i).getDato()); } adapter.computeBars(); } } return adapter; } @Override public BarChartAdapter translateBarChart(DatosGrafica datos) { BarChartAdapter adapter = new BarChartAdapter(); if(datos != null) { LinkedList<String> rows = datos.getDatos(); adapter.setAxisX(datos.getEjeX()); adapter.setAxisY(datos.getEjeY()); if(datos.getDatos() != null) { Integer max = rows.size(); adapter.setTotalHits(max); for(int i = 0; i < max; i++) { adapter.barChartCount(rows.get(i)); } adapter.assignBarMembers(6, "Otros"); } } return adapter ; } @Override public DonutChartAdapter translateDonutChart(DatosGrafica datos) { DonutChartAdapter adapter = new DonutChartAdapter(); if(datos != null) { adapter.setTitle(datos.getTitulo()); LinkedList<String> rows = datos.getDatos(); if(datos.getDatos() != null) { for(int i = 0; i < rows.size(); i++) { adapter.compute(rows.get(i)); } } } return adapter; } @Override public AreaChartAdapter translateAreaChart(DatosGrafica datos, LinkedList<String> labels) { AreaChartAdapter adapter = new AreaChartAdapter(); adapter.setAxisX(datos.getEjeX()); adapter.setAxisY(datos.getEjeY()); LinkedList<String> rows = datos.getDatos(); if(datos.getDatos() != null) { adapter.setLabelsOrder(labels); for(int i = 0; i < rows.size(); i++) { adapter.compute(rows.get(i)); } } return adapter; } }
package databaseManager; import java.io.File; import java.sql.Connection; public abstract class DatabaseManager { public abstract boolean createFlipBoolean(String name); public abstract boolean initDirectory(); public abstract boolean flipping(String name); public abstract void initFlipTable(); }
package cn.yami.wechat.demo.service; import cn.yami.wechat.demo.dao.DemoUserDAO; import cn.yami.wechat.demo.dto.DemoUser; import cn.yami.wechat.demo.dto.LoginInfo; import cn.yami.wechat.demo.enums.CodeMessage; import cn.yami.wechat.demo.exception.GlobalException; import cn.yami.wechat.demo.utils.MD5Util; import cn.yami.wechat.demo.utils.UUIDUtil; import cn.yami.wechat.demo.utils.redis.UserTokenPrefix; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.thymeleaf.util.StringUtils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.util.Date; @Service public class DemoUserService { public static final String COOKIE_NAME_TOKEN = "token"; @Autowired DemoUserDAO demoUserDAO; @Autowired RedisService redisService; public DemoUser getById(long id){ return demoUserDAO.getById(id); } public boolean login(HttpServletResponse response,LoginInfo loginInfo) { String mobile = loginInfo.getMobile(); String password = loginInfo.getPassword(); DemoUser demoUser = getById(Long.parseLong(mobile)); if (demoUser == null){ throw new GlobalException(CodeMessage.MOBILE_NOT_EXIST); } String encryptPass = MD5Util.getEncrypt(password,demoUser.getSalt()); if (!demoUser.getPassword().equals(encryptPass)){ throw new GlobalException(CodeMessage.PASSWORD_ERROR); } demoUserDAO.incLoginCount(Long.parseLong(mobile)); demoUserDAO.setLastLoginDate(Long.parseLong(mobile),new Date()); String token = UUIDUtil.UUID(); addCookie(response,token,demoUser); return true; } public DemoUser getByToken(HttpServletResponse response,String token) { if (StringUtils.isEmpty(token)){ return null; } //延长有效期 DemoUser user = redisService.get(UserTokenPrefix.token,token,DemoUser.class); assert user!=null; addCookie(response,token,user); return user; } private void addCookie(HttpServletResponse response,String token,DemoUser demoUser){ redisService.set(UserTokenPrefix.token,token,demoUser); Cookie cookie = new Cookie(COOKIE_NAME_TOKEN,token); cookie.setMaxAge(UserTokenPrefix.token.expireSeconds()); cookie.setPath("/"); response.addCookie(cookie); } }
package com.mideas.rpg.v2.game.spell.list; import com.mideas.rpg.v2.Sprites; import com.mideas.rpg.v2.game.spell.Spell; public class Immolation extends Spell { private int cd; public Immolation() { super(2000, 2000, 800, 0, 0, 0, 3, 0, 902); name = "Immolation"; sprite = Sprites.spell_immolation; } public void setSpellCd(int number) { cd = number; } public int getSpellCd() { return cd; } }
package mono.android.app; public class ApplicationRegistration { public static void registerApplications () { // Application and Instrumentation ACWs must be registered first. mono.android.Runtime.register ("BugTracker.Droid.Application, BugTracker.Droid, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", crc64fef93827e73f2891.Application.class, crc64fef93827e73f2891.Application.__md_methods); mono.android.Runtime.register ("Windows.UI.Xaml.NativeApplication, Uno.UI, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null", crc64122dcf5ad656876d.NativeApplication.class, crc64122dcf5ad656876d.NativeApplication.__md_methods); } }
package uk.gov.companieshouse.api.testdata.controller; import java.util.HashMap; import java.util.Map; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import uk.gov.companieshouse.api.testdata.Application; import uk.gov.companieshouse.api.testdata.exception.DataException; import uk.gov.companieshouse.api.testdata.exception.InvalidAuthCodeException; import uk.gov.companieshouse.api.testdata.exception.NoDataFoundException; import uk.gov.companieshouse.api.testdata.model.rest.CompanyData; import uk.gov.companieshouse.api.testdata.model.rest.CompanySpec; import uk.gov.companieshouse.api.testdata.model.rest.DeleteCompanyRequest; import uk.gov.companieshouse.api.testdata.service.CompanyAuthCodeService; import uk.gov.companieshouse.api.testdata.service.TestDataService; import uk.gov.companieshouse.logging.Logger; import uk.gov.companieshouse.logging.LoggerFactory; @RestController @RequestMapping(value = "${api.endpoint}", produces = MediaType.APPLICATION_JSON_VALUE) public class TestDataController { private static final Logger LOG = LoggerFactory.getLogger(Application.APPLICATION_NAME); @Autowired private TestDataService testDataService; @Autowired private CompanyAuthCodeService companyAuthCodeService; @PostMapping("/company") public ResponseEntity<CompanyData> create(@Valid @RequestBody Optional<CompanySpec> request) throws DataException { CompanySpec spec = request.orElse(new CompanySpec()); CompanyData createdCompany = testDataService.createCompanyData(spec); Map<String, Object> data = new HashMap<>(); data.put("company number", createdCompany.getCompanyNumber()); data.put("jurisdiction", spec.getJurisdiction()); LOG.info("New company created", data); return new ResponseEntity<>(createdCompany, HttpStatus.CREATED); } @DeleteMapping("/company/{companyNumber}") public ResponseEntity<Void> delete(@PathVariable("companyNumber") String companyNumber, @Valid @RequestBody DeleteCompanyRequest request) throws DataException, InvalidAuthCodeException, NoDataFoundException { if (!companyAuthCodeService.verifyAuthCode(companyNumber, request.getAuthCode())) { throw new InvalidAuthCodeException(companyNumber); } testDataService.deleteCompanyData(companyNumber); Map<String, Object> data = new HashMap<>(); data.put("company number", companyNumber); LOG.info("Company deleted", data); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } }
/******************************************************************************* * Copyright (c) 2012, All Rights Reserved. * * Generation Challenge Programme (GCP) * * * This software is licensed for use under the terms of the GNU General Public * License (http://bit.ly/8Ztv8M) and the provisions of Part F of the Generation * Challenge Programme Amended Consortium Agreement (http://bit.ly/KQX1nL) * *******************************************************************************/ package org.generationcp.browser.germplasm; import org.generationcp.browser.application.Message; import org.generationcp.browser.germplasm.containers.GermplasmIndexContainer; import org.generationcp.browser.germplasm.listeners.GermplasmButtonClickListener; import org.generationcp.browser.germplasm.listeners.GermplasmItemClickListener; import org.generationcp.browser.util.Util; import org.generationcp.commons.exceptions.InternationalizableException; import org.generationcp.commons.vaadin.spring.InternationalizableComponent; import org.generationcp.commons.vaadin.spring.SimpleResourceBundleMessageSource; import org.generationcp.middleware.pojos.GermplasmPedigreeTree; import org.generationcp.middleware.pojos.GermplasmPedigreeTreeNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import com.vaadin.ui.AbstractSelect; import com.vaadin.ui.Button; import com.vaadin.ui.Component; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Select; import com.vaadin.ui.TabSheet; import com.vaadin.ui.TabSheet.Tab; import com.vaadin.ui.Tree; import com.vaadin.ui.VerticalLayout; @Configurable public class GermplasmDerivativeNeighborhoodComponent extends VerticalLayout implements InitializingBean, InternationalizableComponent{ private static final long serialVersionUID = 1L; private GermplasmPedigreeTree germplasmDerivativeNeighborhood; private GermplasmQueries qQuery; private VerticalLayout mainLayout; private TabSheet tabSheet; private GermplasmIndexContainer dataIndexContainer; private Tree derivativeNeighborhoodTree; private int gid; private Label labelNumberOfStepsBackward; private Label labelNumberOfStepsForward; private Button btnDisplay; private HorizontalLayout hLayout; private Select selectNumberOfStepBackward; private Select selectNumberOfStepForward; public static final String DISPLAY_BUTTON_ID="Display Derivative Neighborhood"; @SuppressWarnings("unused") private final static Logger LOG = LoggerFactory.getLogger(GermplasmDerivativeNeighborhoodComponent.class); @Autowired private SimpleResourceBundleMessageSource messageSource; public GermplasmDerivativeNeighborhoodComponent(int gid, GermplasmQueries qQuery, GermplasmIndexContainer dataResultIndexContainer, VerticalLayout mainLayout, TabSheet tabSheet) throws InternationalizableException { super(); this.mainLayout = mainLayout; this.tabSheet = tabSheet; this.qQuery = qQuery; this.dataIndexContainer = dataResultIndexContainer; this.gid=gid; } private void addNode(GermplasmPedigreeTreeNode node, int level) { if (level == 1) { String name = node.getGermplasm().getPreferredName() != null ? node.getGermplasm().getPreferredName().getNval() : null; String rootNodeLabel = name + "(" + node.getGermplasm().getGid() + ")"; int rootNodeId = node.getGermplasm().getGid(); derivativeNeighborhoodTree.addItem(rootNodeId); derivativeNeighborhoodTree.setItemCaption(rootNodeId, rootNodeLabel); derivativeNeighborhoodTree.setParent(rootNodeId, rootNodeId); derivativeNeighborhoodTree.setChildrenAllowed(rootNodeId, true); derivativeNeighborhoodTree.expandItemsRecursively(rootNodeId); } for (GermplasmPedigreeTreeNode child : node.getLinkedNodes()) { String name = child.getGermplasm().getPreferredName() != null ? child.getGermplasm().getPreferredName().getNval() : null; int parentNodeId = node.getGermplasm().getGid(); String childNodeLabel = name + "(" + child.getGermplasm().getGid() + ")"; int childNodeId = child.getGermplasm().getGid(); derivativeNeighborhoodTree.addItem(childNodeId); derivativeNeighborhoodTree.setItemCaption(childNodeId, childNodeLabel); derivativeNeighborhoodTree.setParent(childNodeId, parentNodeId); derivativeNeighborhoodTree.setChildrenAllowed(childNodeId, true); derivativeNeighborhoodTree.expandItemsRecursively(childNodeId); if(child.getGermplasm().getGid()==gid){ derivativeNeighborhoodTree.setValue(childNodeId); derivativeNeighborhoodTree.setImmediate(true); } addNode(child, level + 1); } } @Override public void afterPropertiesSet() { setSpacing(true); setMargin(true); hLayout= new HorizontalLayout(); hLayout.setSpacing(true); labelNumberOfStepsBackward=new Label(); selectNumberOfStepBackward= new Select (); selectNumberOfStepBackward.setWidth("50px"); populateSelectSteps(selectNumberOfStepBackward); selectNumberOfStepBackward.setNullSelectionAllowed(false); selectNumberOfStepBackward.select("2"); labelNumberOfStepsForward= new Label(); selectNumberOfStepForward= new Select (); selectNumberOfStepForward.setWidth("50px"); populateSelectSteps(selectNumberOfStepForward); selectNumberOfStepForward.setNullSelectionAllowed(false); selectNumberOfStepForward.select("3"); btnDisplay = new Button(); btnDisplay.setData(DISPLAY_BUTTON_ID); btnDisplay.setDescription("Display Germplasm Derivative Neighborhood "); btnDisplay.addListener(new GermplasmButtonClickListener(this)); hLayout.addComponent(labelNumberOfStepsBackward); hLayout.addComponent(selectNumberOfStepBackward); hLayout.addComponent(labelNumberOfStepsForward); hLayout.addComponent(selectNumberOfStepForward); hLayout.addComponent(btnDisplay); addComponent(hLayout); derivativeNeighborhoodTree= new Tree(); addComponent(derivativeNeighborhoodTree); derivativeNeighborhoodTree.addListener(new GermplasmItemClickListener(this)); derivativeNeighborhoodTree.setItemDescriptionGenerator(new AbstractSelect.ItemDescriptionGenerator() { private static final long serialVersionUID = 3442425534732855473L; @Override public String generateDescription(Component source, Object itemId, Object propertyId) { return messageSource.getMessage(Message.CLICK_TO_VIEW_GERMPLASM_DETAILS); } }); displayButtonClickAction(); } private void populateSelectSteps(Select select) { for(int i=1;i<=10;i++){ select.addItem(String.valueOf(i)); } } @Override public void attach() { super.attach(); updateLabels(); } @Override public void updateLabels() { messageSource.setCaption(labelNumberOfStepsBackward, Message.NUMBER_OF_STEPS_BACKWARD_LABEL); messageSource.setCaption(labelNumberOfStepsForward, Message.NUMBER_OF_STEPS_FORWARD_LABEL); messageSource.setCaption(btnDisplay, Message.DISPLAY_BUTTON_LABEL); } public void displayButtonClickAction() { this.removeComponent(derivativeNeighborhoodTree); derivativeNeighborhoodTree.removeAllItems(); int numberOfStepsBackward=Integer.valueOf(selectNumberOfStepBackward.getValue().toString()); int numberOfStepsForward=Integer.valueOf(selectNumberOfStepForward.getValue().toString()); germplasmDerivativeNeighborhood = qQuery.getDerivativeNeighborhood(Integer.valueOf(gid), numberOfStepsBackward,numberOfStepsForward); // throws QueryException if (germplasmDerivativeNeighborhood != null) { addNode(germplasmDerivativeNeighborhood.getRoot(), 1); } addComponent(derivativeNeighborhoodTree); } public void displayNewGermplasmDetailTab(int gid) throws InternationalizableException { if(this.mainLayout != null && this.tabSheet != null) { VerticalLayout detailLayout = new VerticalLayout(); detailLayout.setSpacing(true); if (!Util.isTabExist(tabSheet, String.valueOf(gid))) { detailLayout.addComponent(new GermplasmDetail(gid, qQuery, dataIndexContainer, mainLayout, tabSheet, false)); Tab tab = tabSheet.addTab(detailLayout, String.valueOf(gid), null); tab.setClosable(true); tabSheet.setSelectedTab(detailLayout); mainLayout.addComponent(tabSheet); } else { Tab tab = Util.getTabAlreadyExist(tabSheet, String.valueOf(gid)); tabSheet.setSelectedTab(tab.getComponent()); } } } }
package dto; /** * Created by Esther on 2016/9/2. */ public class StudentCV { public Cv getCv() { return cv; } public void setCv(Cv cv) { this.cv = cv; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } private Cv cv; private Student student; }
package com.gdcp.weibo.exceptions; public class CollectionOperationExeption extends RuntimeException{ /** * 可以抛出异常 并把与之相关操作事物的数据失效 */ private static final long serialVersionUID = 1260432742369869569L; public CollectionOperationExeption(String msg) { super(msg); } }
/** * 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.raid; import org.junit.Test; import static org.junit.Assert.*; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.protocol.LocatedBlocks; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.RaidDFSUtil; import org.apache.hadoop.hdfs.TestRaidDfs; import org.apache.hadoop.raid.RaidNode; public class TestBlockFixerDistConcurrency extends TestBlockFixer { /** * tests that we can have 2 concurrent jobs fixing files * (dist block fixer) */ @Test public void testConcurrentJobs() throws Exception { LOG.info("Test testConcurrentJobs started."); long blockSize = 8192L; int stripeLength = 3; mySetup(stripeLength, -1); // never har Path file1 = new Path("/user/dhruba/raidtest/file1"); Path file2 = new Path("/user/dhruba/raidtest/file2"); Path destPath = new Path("/destraid/user/dhruba/raidtest"); long crc1 = TestRaidDfs.createTestFilePartialLastBlock(fileSys, file1, 1, 20, blockSize); long crc2 = TestRaidDfs.createTestFilePartialLastBlock(fileSys, file2, 1, 20, blockSize); long file1Len = fileSys.getFileStatus(file1).getLen(); long file2Len = fileSys.getFileStatus(file2).getLen(); LOG.info("Test testConcurrentJobs created test files"); // create an instance of the RaidNode Configuration localConf = new Configuration(conf); localConf.set(RaidNode.RAID_LOCATION_KEY, "/destraid"); localConf.setInt("raid.blockfix.interval", 1000); localConf.set("raid.blockfix.classname", "org.apache.hadoop.raid.DistBlockFixer"); localConf.setLong("raid.blockfix.filespertask", 2L); try { cnode = RaidNode.createRaidNode(null, localConf); TestRaidDfs.waitForFileRaided(LOG, fileSys, file1, destPath); TestRaidDfs.waitForFileRaided(LOG, fileSys, file2, destPath); cnode.stop(); cnode.join(); FileStatus file1Stat = fileSys.getFileStatus(file1); FileStatus file2Stat = fileSys.getFileStatus(file2); DistributedFileSystem dfs = (DistributedFileSystem)fileSys; LocatedBlocks file1Loc = RaidDFSUtil.getBlockLocations(dfs, file1.toUri().getPath(), 0, file1Stat.getLen()); LocatedBlocks file2Loc = RaidDFSUtil.getBlockLocations(dfs, file2.toUri().getPath(), 0, file2Stat.getLen()); String[] corruptFiles = RaidDFSUtil.getCorruptFiles(dfs); assertEquals("no corrupt files expected", 0, corruptFiles.length); assertEquals("filesFixed() should return 0 before fixing files", 0, cnode.blockFixer.filesFixed()); // corrupt file1 int[] corruptBlockIdxs = new int[]{0, 4, 6}; for (int idx: corruptBlockIdxs) corruptBlock(file1Loc.get(idx).getBlock()); reportCorruptBlocks(dfs, file1, corruptBlockIdxs, blockSize); cnode = RaidNode.createRaidNode(null, localConf); DistBlockFixer blockFixer = (DistBlockFixer) cnode.blockFixer; long start = System.currentTimeMillis(); while (blockFixer.jobsRunning() < 1 && System.currentTimeMillis() - start < 240000) { LOG.info("Test testBlockFix waiting for fixing job 1 to start"); Thread.sleep(10); } assertEquals("job 1 not running", 1, blockFixer.jobsRunning()); // corrupt file2 for (int idx: corruptBlockIdxs) corruptBlock(file2Loc.get(idx).getBlock()); reportCorruptBlocks(dfs, file2, corruptBlockIdxs, blockSize); while (blockFixer.jobsRunning() < 2 && System.currentTimeMillis() - start < 240000) { LOG.info("Test testBlockFix waiting for fixing job 2 to start"); Thread.sleep(10); } assertEquals("2 jobs not running", 2, blockFixer.jobsRunning()); while (blockFixer.filesFixed() < 2 && System.currentTimeMillis() - start < 240000) { LOG.info("Test testBlockFix waiting for files to be fixed."); Thread.sleep(10); } assertEquals("files not fixed", 2, blockFixer.filesFixed()); dfs = getDFS(conf, dfs); try { Thread.sleep(5*1000); } catch (InterruptedException ignore) { } assertTrue("file not fixed", TestRaidDfs.validateFile(dfs, file1, file1Len, crc1)); assertTrue("file not fixed", TestRaidDfs.validateFile(dfs, file2, file2Len, crc2)); } catch (Exception e) { LOG.info("Test testConcurrentJobs exception " + e + StringUtils.stringifyException(e)); throw e; } finally { myTearDown(); } } /** * tests that the distributed block fixer obeys * the limit on how many files to fix simultaneously */ @Test public void testMaxPendingFiles() throws Exception { LOG.info("Test testMaxPendingFiles started."); long blockSize = 8192L; int stripeLength = 3; mySetup(stripeLength, -1); // never har Path file1 = new Path("/user/dhruba/raidtest/file1"); Path file2 = new Path("/user/dhruba/raidtest/file2"); Path destPath = new Path("/destraid/user/dhruba/raidtest"); long crc1 = TestRaidDfs.createTestFilePartialLastBlock(fileSys, file1, 1, 20, blockSize); long crc2 = TestRaidDfs.createTestFilePartialLastBlock(fileSys, file2, 1, 20, blockSize); long file1Len = fileSys.getFileStatus(file1).getLen(); long file2Len = fileSys.getFileStatus(file2).getLen(); LOG.info("Test testMaxPendingFiles created test files"); // create an instance of the RaidNode Configuration localConf = new Configuration(conf); localConf.set(RaidNode.RAID_LOCATION_KEY, "/destraid"); localConf.setInt("raid.blockfix.interval", 1000); localConf.set("raid.blockfix.classname", "org.apache.hadoop.raid.DistBlockFixer"); localConf.setLong("raid.blockfix.filespertask", 2L); localConf.setLong("raid.blockfix.maxpendingfiles", 1L); try { cnode = RaidNode.createRaidNode(null, localConf); TestRaidDfs.waitForFileRaided(LOG, fileSys, file1, destPath); TestRaidDfs.waitForFileRaided(LOG, fileSys, file2, destPath); cnode.stop(); cnode.join(); FileStatus file1Stat = fileSys.getFileStatus(file1); FileStatus file2Stat = fileSys.getFileStatus(file2); DistributedFileSystem dfs = (DistributedFileSystem)fileSys; LocatedBlocks file1Loc = RaidDFSUtil.getBlockLocations(dfs, file1.toUri().getPath(), 0, file1Stat.getLen()); LocatedBlocks file2Loc = RaidDFSUtil.getBlockLocations(dfs, file2.toUri().getPath(), 0, file2Stat.getLen()); String[] corruptFiles = RaidDFSUtil.getCorruptFiles(dfs); assertEquals("no corrupt files expected", 0, corruptFiles.length); assertEquals("filesFixed() should return 0 before fixing files", 0, cnode.blockFixer.filesFixed()); // corrupt file1 int[] corruptBlockIdxs = new int[]{0, 4, 6}; for (int idx: corruptBlockIdxs) corruptBlock(file1Loc.get(idx).getBlock()); reportCorruptBlocks(dfs, file1, corruptBlockIdxs, blockSize); corruptFiles = RaidDFSUtil.getCorruptFiles(dfs); cnode = RaidNode.createRaidNode(null, localConf); DistBlockFixer blockFixer = (DistBlockFixer) cnode.blockFixer; long start = System.currentTimeMillis(); while (blockFixer.jobsRunning() < 1 && System.currentTimeMillis() - start < 240000) { LOG.info("Test testBlockFix waiting for fixing job 1 to start"); Thread.sleep(10); } assertEquals("job not running", 1, blockFixer.jobsRunning()); // corrupt file2 for (int idx: corruptBlockIdxs) corruptBlock(file2Loc.get(idx).getBlock()); reportCorruptBlocks(dfs, file2, corruptBlockIdxs, blockSize); corruptFiles = RaidDFSUtil.getCorruptFiles(dfs); // wait until both files are fixed while (blockFixer.filesFixed() < 2 && System.currentTimeMillis() - start < 240000) { // make sure the block fixer does not start a second job while // the first one is still running assertTrue("too many jobs running", blockFixer.jobsRunning() <= 1); Thread.sleep(10); } assertEquals("files not fixed", 2, blockFixer.filesFixed()); dfs = getDFS(conf, dfs); try { Thread.sleep(5*1000); } catch (InterruptedException ignore) { } assertTrue("file not fixed", TestRaidDfs.validateFile(dfs, file1, file1Len, crc1)); assertTrue("file not fixed", TestRaidDfs.validateFile(dfs, file2, file2Len, crc2)); } catch (Exception e) { LOG.info("Test testMaxPendingFiles exception " + e + StringUtils.stringifyException(e)); throw e; } finally { myTearDown(); } } }
package shapes; import java.awt.*; /** * Created by TAWEESOFT on 4/28/16 AD. */ public class Rectangle extends Shape { private int width,height; private Color color; public Rectangle(int x, int y, int width, int height, Color color) { this.x = x; this.y = y; this.width = width; this.height = height; this.color = color; } public void paint(Graphics g) { g.setColor(color); g.fillRect(x,y,width,height); } }
package com.puxtech.reuters.rfa.Common; import java.util.Date; public class SubNode implements Comparable<SubNode> { int index; String contractCode; Date attenBeginTime; Date changeContractTime; Date attenEndTime; int diffPricePeriod; String exchangeCode; public String getExchangeCode() { return exchangeCode; } public void setExchangeCode(String exchangeCode) { this.exchangeCode = exchangeCode; } public int getDiffPricePeriod() { return diffPricePeriod; } public void setDiffPricePeriod(int diffPricePeriod) { this.diffPricePeriod = diffPricePeriod; } public String getContractCode() { return contractCode; } public void setContractCode(String contractCode) { this.contractCode = contractCode; } public Date getAttenBeginTime() { return attenBeginTime; } public void setAttenBeginTime(Date attenBeginTime) { this.attenBeginTime = attenBeginTime; } public Date getChangeContractTime() { return changeContractTime; } public void setChangeContractTime(Date changeContractTime) { this.changeContractTime = changeContractTime; } public Date getAttenEndTime() { return attenEndTime; } public void setAttenEndTime(Date attenEndTime) { this.attenEndTime = attenEndTime; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } @Override public int compareTo(SubNode o) { return this.index - o.index; } @Override public String toString() { return "SubNode [index=" + index + ", contractCode=" + contractCode + ", attenBeginTime=" + attenBeginTime + ", changeContractTime=" + changeContractTime + ", attenEndTime=" + attenEndTime + ", diffPricePeriod=" + diffPricePeriod + ", exchangeCode=" + exchangeCode + "]"; } }
package day33_arrays; public class FopLoopWith2Variables { public static void main(String[] args) { for(int i =1, j=1; i <=4;i++,j++){ System.out.println("i = "+i+" ,j= " +j); } System.out.println("****************2 way for loop***************"); for(int i=0, j =5; j >= 0;i++,j--){ System.out.println("i = "+i+" ,j= " +j); } } }
/* * Copyright (C) 2022-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 org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.data.util.Predicates.negate; import com.google.common.collect.Range; import com.google.protobuf.BoolValue; import com.hedera.mirror.common.domain.entity.CryptoAllowance; import com.hedera.mirror.common.domain.entity.EntityId; import com.hedera.mirror.common.domain.entity.EntityTransaction; import com.hedera.mirror.common.domain.entity.EntityType; import com.hedera.mirror.common.domain.entity.NftAllowance; import com.hedera.mirror.common.domain.entity.TokenAllowance; import com.hedera.mirror.common.domain.token.Nft; import com.hedera.mirror.common.domain.transaction.RecordItem; import com.hedera.mirror.common.domain.transaction.Transaction; import com.hedera.mirror.common.util.DomainUtils; import com.hedera.mirror.importer.TestUtils; import com.hedera.mirror.importer.parser.contractresult.SyntheticContractResultService; import com.hederahashgraph.api.proto.java.AccountID; import com.hederahashgraph.api.proto.java.CryptoApproveAllowanceTransactionBody; import com.hederahashgraph.api.proto.java.TokenID; import com.hederahashgraph.api.proto.java.TransactionBody; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; class CryptoApproveAllowanceTransactionHandlerTest extends AbstractTransactionHandlerTest { @Mock protected SyntheticContractResultService syntheticContractResultService; private long consensusTimestamp; private CryptoAllowance expectedCryptoAllowance; private Nft expectedNft; private NftAllowance expectedNftAllowance; private TokenAllowance expectedTokenAllowance; private EntityId payerAccountId; @BeforeEach void beforeEach() { consensusTimestamp = DomainUtils.timestampInNanosMax(recordItemBuilder.timestamp()); payerAccountId = EntityId.of(recordItemBuilder.accountId()); var cryptoOwner = recordItemBuilder.accountId(); expectedCryptoAllowance = CryptoAllowance.builder() .amountGranted(100L) .amount(100L) .owner(cryptoOwner.getAccountNum()) .payerAccountId(payerAccountId) .spender(recordItemBuilder.accountId().getAccountNum()) .timestampRange(Range.atLeast(consensusTimestamp)) .build(); when(entityIdService.lookup(cryptoOwner)).thenReturn(Optional.of(EntityId.of(cryptoOwner))); var nftOwner = recordItemBuilder.accountId(); var nftTokenId = recordItemBuilder.tokenId().getTokenNum(); expectedNft = Nft.builder() .accountId(EntityId.of(nftOwner)) .delegatingSpender(EntityId.EMPTY) .serialNumber(1) .spender(EntityId.of(recordItemBuilder.accountId())) .timestampRange(Range.atLeast(consensusTimestamp)) .tokenId(nftTokenId) .build(); when(entityIdService.lookup(nftOwner)).thenReturn(Optional.of(expectedNft.getAccountId())); expectedNftAllowance = NftAllowance.builder() .approvedForAll(true) .owner(expectedNft.getAccountId().getId()) .payerAccountId(payerAccountId) .spender(expectedNft.getSpender().getId()) .timestampRange(Range.atLeast(consensusTimestamp)) .tokenId(nftTokenId) .build(); var tokenOwner = recordItemBuilder.accountId(); expectedTokenAllowance = TokenAllowance.builder() .amountGranted(200L) .amount(200L) .owner(tokenOwner.getAccountNum()) .payerAccountId(payerAccountId) .spender(recordItemBuilder.accountId().getAccountNum()) .timestampRange(Range.atLeast(consensusTimestamp)) .tokenId(recordItemBuilder.tokenId().getTokenNum()) .build(); when(entityIdService.lookup(tokenOwner)).thenReturn(Optional.of(EntityId.of(tokenOwner))); } @Override protected TransactionHandler getTransactionHandler() { return new CryptoApproveAllowanceTransactionHandler( entityIdService, entityListener, syntheticContractLogService, syntheticContractResultService); } @Override protected TransactionBody.Builder getDefaultTransactionBody() { return TransactionBody.newBuilder() .setCryptoApproveAllowance( CryptoApproveAllowanceTransactionBody.newBuilder().build()); } @Override protected EntityType getExpectedEntityIdType() { return null; } @Test void updateTransactionSuccessful() { var recordItem = recordItemBuilder .cryptoApproveAllowance() .transactionBody(this::customizeTransactionBody) .transactionBodyWrapper(this::setTransactionPayer) .record(r -> r.setConsensusTimestamp(TestUtils.toTimestamp(consensusTimestamp))) .build(); var transaction = domainBuilder .transaction() .customize(t -> t.consensusTimestamp(consensusTimestamp)) .get(); transactionHandler.updateTransaction(transaction, recordItem); assertAllowances(null); assertThat(recordItem.getEntityTransactions()) .containsExactlyInAnyOrderEntriesOf(getExpectedEntityTransactions(recordItem, transaction)); } @Test void updateTransactionSuccessfulWithImplicitOwner() { var recordItem = recordItemBuilder .cryptoApproveAllowance() .transactionBody(this::customizeTransactionBody) .transactionBody(b -> { b.getCryptoAllowancesBuilderList().forEach(builder -> builder.clearOwner()); b.getNftAllowancesBuilderList().forEach(builder -> builder.clearOwner()); b.getTokenAllowancesBuilderList().forEach(builder -> builder.clearOwner()); }) .transactionBodyWrapper(this::setTransactionPayer) .record(r -> r.setConsensusTimestamp(TestUtils.toTimestamp(consensusTimestamp))) .build(); var effectiveOwner = recordItem.getPayerAccountId().getId(); var transaction = domainBuilder .transaction() .customize(t -> t.consensusTimestamp(consensusTimestamp)) .get(); transactionHandler.updateTransaction(transaction, recordItem); assertAllowances(effectiveOwner); assertThat(recordItem.getEntityTransactions()) .containsExactlyInAnyOrderEntriesOf(getExpectedEntityTransactions(recordItem, transaction)); } @Test void updateTransactionWithEmptyEntityId() { var alias = DomainUtils.fromBytes(domainBuilder.key()); var recordItem = recordItemBuilder .cryptoApproveAllowance() .transactionBody(this::customizeTransactionBody) .transactionBody(b -> { b.getCryptoAllowancesBuilderList() .forEach(builder -> builder.getOwnerBuilder().setAlias(alias)); b.getNftAllowancesBuilderList() .forEach(builder -> builder.getOwnerBuilder().setAlias(alias)); b.getTokenAllowancesBuilderList() .forEach(builder -> builder.getOwnerBuilder().setAlias(alias)); }) .transactionBodyWrapper(this::setTransactionPayer) .record(r -> r.setConsensusTimestamp(TestUtils.toTimestamp(consensusTimestamp))) .build(); var transaction = domainBuilder.transaction().get(); when(entityIdService.lookup(AccountID.newBuilder().setAlias(alias).build())) .thenReturn(Optional.of(EntityId.EMPTY)); transactionHandler.updateTransaction(transaction, recordItem); // The implicit entity id is used var effectiveOwner = recordItem.getPayerAccountId().getId(); assertAllowances(effectiveOwner); assertThat(recordItem.getEntityTransactions()) .containsExactlyInAnyOrderEntriesOf(getExpectedEntityTransactions(recordItem, transaction)); } @ParameterizedTest @MethodSource("provideEntities") void updateTransactionWithEmptyOwner(EntityId entityId) { // given var alias = DomainUtils.fromBytes(domainBuilder.key()); var recordItem = recordItemBuilder .cryptoApproveAllowance() .transactionBody(b -> { b.getCryptoAllowancesBuilderList() .forEach(builder -> builder.getOwnerBuilder().clear()); b.getNftAllowancesBuilderList() .forEach(builder -> builder.getOwnerBuilder().setAlias(alias)); b.getTokenAllowancesBuilderList() .forEach(builder -> builder.getOwnerBuilder().setAlias(alias)); }) .transactionBodyWrapper(w -> w.getTransactionIDBuilder() .setAccountID(AccountID.newBuilder().setAccountNum(0))) .record(r -> r.setConsensusTimestamp(TestUtils.toTimestamp(consensusTimestamp))) .build(); var transaction = domainBuilder.transaction().get(); when(entityIdService.lookup(AccountID.newBuilder().setAlias(alias).build())) .thenReturn(Optional.ofNullable(entityId)); var expectedEntityTransactions = super.getExpectedEntityTransactions(recordItem, transaction); // when transactionHandler.updateTransaction(transaction, recordItem); // then verifyNoInteractions(entityListener); assertThat(recordItem.getEntityTransactions()).containsExactlyInAnyOrderEntriesOf(expectedEntityTransactions); } @Test void updateTransactionWithAlias() { var alias = DomainUtils.fromBytes(domainBuilder.key()); var ownerEntityId = EntityId.of(recordItemBuilder.accountId()); var recordItem = recordItemBuilder .cryptoApproveAllowance() .transactionBody(this::customizeTransactionBody) .transactionBody(b -> { b.getCryptoAllowancesBuilderList() .forEach(builder -> builder.getOwnerBuilder().setAlias(alias)); b.getNftAllowancesBuilderList() .forEach(builder -> builder.getOwnerBuilder().setAlias(alias)); b.getTokenAllowancesBuilderList() .forEach(builder -> builder.getOwnerBuilder().setAlias(alias)); }) .transactionBodyWrapper(this::setTransactionPayer) .record(r -> r.setConsensusTimestamp(TestUtils.toTimestamp(consensusTimestamp))) .build(); var timestamp = recordItem.getConsensusTimestamp(); var transaction = domainBuilder .transaction() .customize(t -> t.consensusTimestamp(timestamp)) .get(); when(entityIdService.lookup(AccountID.newBuilder().setAlias(alias).build())) .thenReturn(Optional.of(ownerEntityId)); transactionHandler.updateTransaction(transaction, recordItem); assertAllowances(ownerEntityId.getId()); assertThat(recordItem.getEntityTransactions()) .containsExactlyInAnyOrderEntriesOf(getExpectedEntityTransactions(recordItem, transaction)); } private void assertAllowances(Long effectiveOwner) { if (effectiveOwner != null) { expectedCryptoAllowance.setOwner(effectiveOwner); expectedNft.setAccountId(EntityId.of(effectiveOwner, EntityType.ACCOUNT)); expectedNftAllowance.setOwner(effectiveOwner); expectedTokenAllowance.setOwner(effectiveOwner); } verify(entityListener, times(1)).onCryptoAllowance(assertArg(t -> assertEquals(expectedCryptoAllowance, t))); verify(entityListener, times(1)).onNft(assertArg(t -> assertEquals(expectedNft, t))); verify(entityListener, times(1)).onNftAllowance(assertArg(t -> assertEquals(expectedNftAllowance, t))); verify(entityListener, times(1)).onTokenAllowance(assertArg(t -> assertEquals(expectedTokenAllowance, t))); } private void customizeTransactionBody(CryptoApproveAllowanceTransactionBody.Builder builder) { builder.clear(); // duplicate with different amount builder.addCryptoAllowances(com.hederahashgraph.api.proto.java.CryptoAllowance.newBuilder() .setAmount(expectedCryptoAllowance.getAmount() - 10) .setOwner(AccountID.newBuilder().setAccountNum(expectedCryptoAllowance.getOwner())) .setSpender(AccountID.newBuilder().setAccountNum(expectedCryptoAllowance.getSpender()))); // the last one is honored builder.addCryptoAllowances(com.hederahashgraph.api.proto.java.CryptoAllowance.newBuilder() .setAmount(expectedCryptoAllowance.getAmount()) .setOwner(AccountID.newBuilder().setAccountNum(expectedCryptoAllowance.getOwner())) .setSpender(AccountID.newBuilder().setAccountNum(expectedCryptoAllowance.getSpender()))); // duplicate nft allowance by serial builder.addNftAllowances(com.hederahashgraph.api.proto.java.NftAllowance.newBuilder() .setOwner(AccountID.newBuilder() .setAccountNum(expectedNft.getAccountId().getEntityNum())) .addSerialNumbers(expectedNft.getId().getSerialNumber()) .setSpender(AccountID.newBuilder() .setAccountNum(expectedNft.getSpender().getEntityNum() + 1)) .setTokenId(TokenID.newBuilder().setTokenNum(expectedNft.getTokenId()))); // duplicate nft approved for all allowance, approved for all flag is flipped from the last one builder.addNftAllowances(com.hederahashgraph.api.proto.java.NftAllowance.newBuilder() .setApprovedForAll(BoolValue.of(!expectedNftAllowance.isApprovedForAll())) .setOwner(AccountID.newBuilder() .setAccountNum(expectedNft.getAccountId().getEntityNum())) .addSerialNumbers(expectedNft.getId().getSerialNumber()) .setSpender(AccountID.newBuilder() .setAccountNum(expectedNft.getSpender().getEntityNum())) .setTokenId(TokenID.newBuilder().setTokenNum(expectedNft.getTokenId()))); // the last one is honored builder.addNftAllowances(com.hederahashgraph.api.proto.java.NftAllowance.newBuilder() .setApprovedForAll(BoolValue.of(expectedNftAllowance.isApprovedForAll())) .setOwner(AccountID.newBuilder() .setAccountNum(expectedNft.getAccountId().getEntityNum())) .addSerialNumbers(expectedNft.getId().getSerialNumber()) .setSpender(AccountID.newBuilder() .setAccountNum(expectedNft.getSpender().getEntityNum())) .setTokenId(TokenID.newBuilder().setTokenNum(expectedNft.getTokenId()))); // duplicate token allowance builder.addTokenAllowances(com.hederahashgraph.api.proto.java.TokenAllowance.newBuilder() .setAmount(expectedTokenAllowance.getAmount() - 10) .setOwner(AccountID.newBuilder().setAccountNum(expectedTokenAllowance.getOwner())) .setSpender(AccountID.newBuilder().setAccountNum(expectedTokenAllowance.getSpender())) .setTokenId(TokenID.newBuilder().setTokenNum(expectedTokenAllowance.getTokenId()))); // the last one is honored builder.addTokenAllowances(com.hederahashgraph.api.proto.java.TokenAllowance.newBuilder() .setAmount(expectedTokenAllowance.getAmount()) .setOwner(AccountID.newBuilder().setAccountNum(expectedTokenAllowance.getOwner())) .setSpender(AccountID.newBuilder().setAccountNum(expectedTokenAllowance.getSpender())) .setTokenId(TokenID.newBuilder().setTokenNum(expectedTokenAllowance.getTokenId()))); } private Map<Long, EntityTransaction> getExpectedEntityTransactions(RecordItem recordItem, Transaction transaction) { var entityIds = Stream.concat( Stream.of( expectedNft.getAccountId(), expectedNft.getDelegatingSpender(), expectedNft.getDelegatingSpender()), Stream.of( expectedCryptoAllowance.getOwner(), expectedCryptoAllowance.getSpender(), expectedTokenAllowance.getOwner(), expectedTokenAllowance.getSpender(), expectedTokenAllowance.getTokenId(), expectedNftAllowance.getOwner(), expectedNftAllowance.getSpender(), expectedNftAllowance.getTokenId()) .filter(negate(Objects::isNull)) .map(id -> EntityId.of(id, EntityType.ACCOUNT))); return getExpectedEntityTransactions(recordItem, transaction, entityIds.toArray(EntityId[]::new)); } private void setTransactionPayer(TransactionBody.Builder builder) { builder.getTransactionIDBuilder() .setAccountID(AccountID.newBuilder().setAccountNum(payerAccountId.getEntityNum())); } }
package cn.tedu.service; public interface UserService { void deleteUsers(String... ids); }
import edu.princeton.cs.algs4.Digraph; import edu.princeton.cs.algs4.DirectedCycle; import edu.princeton.cs.algs4.In; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class WordNet { private HashMap<String, List<Integer>> words = null; private HashMap<String, String> ids = null; private Digraph graph = null; private SAP sap = null; public WordNet(String synsets, String hypernyms) { if (null == synsets || null == hypernyms) { throw new NullPointerException("Argument is null"); } In in = new In(hypernyms); String line = null; List<String> lines = new ArrayList<String>(); int len = 0; while ((line = in.readLine()) != null) { if (line.isEmpty()) continue; lines.add(line); for (String str : line.split(",")) { int i = Integer.parseInt(str.trim()); if (i > len) len = i; } } graph = new Digraph(len + 1); String[] hypers = null; int id; for (String hyper : lines) { if (hyper.isEmpty()) continue; hypers = hyper.split(","); if (hypers.length < 2) continue; id = Integer.parseInt(hypers[0].trim()); for (int i = 1; i < hypers.length; i++) graph.addEdge(id, Integer.parseInt(hypers[i].trim())); } lines = null; DirectedCycle dag = new DirectedCycle(graph); if (dag.hasCycle()) throw new IllegalArgumentException("Graph in not a DAG"); int rootCount = 0; for (int i = 0; i < len + 1; i++) { if (!graph.adj(i).iterator().hasNext()) rootCount++; if (rootCount > 1) throw new IllegalArgumentException("Graph in not a rooted DAG"); } sap = new SAP(graph); words = new HashMap<String, List<Integer>>(); ids = new HashMap<String, String>(); in = new In(synsets); String[] info = null; String[] syns = null; while ((line = in.readLine()) != null) { if (line.isEmpty()) continue; info = line.split(","); if (info.length < 2) continue; ids.put(info[0].trim(), info[1].trim()); syns = info[1].trim().split(" "); List<Integer> idVals = null; for (int i = 0; i < syns.length; i++) { idVals = words.get(syns[i]); if (null == idVals) { idVals = new ArrayList<Integer>(); words.put(syns[i], idVals); } idVals.add(Integer.parseInt(info[0].trim())); } } } public Iterable<String> nouns() { return this.words.keySet(); } public boolean isNoun(String word) { if (null == word) { throw new NullPointerException("Argument is null"); } return this.words.containsKey(word); } public int distance(String nounA, String nounB) { if (null == nounA || null == nounB) { throw new NullPointerException("Argument is null"); } if (!isNoun(nounA)) throw new IllegalArgumentException(nounA + " is not there in word net"); if (!isNoun(nounB)) throw new IllegalArgumentException(nounB + " is not there in word net"); return sap.length(words.get(nounA), words.get(nounB)); } public String sap(String nounA, String nounB) { if (null == nounA || null == nounB) { throw new NullPointerException("Argument is null"); } if (!isNoun(nounA)) throw new IllegalArgumentException(nounA + " is not there in word net"); if (!isNoun(nounB)) throw new IllegalArgumentException(nounB + " is not there in word net"); int ancesstor = sap.ancestor(words.get(nounA), words.get(nounB)); return ids.get(String.valueOf(ancesstor)); } /** * @param args */ public static void main(String[] args) { WordNet wordNet = new WordNet("synsets100-subgraph.txt", "hypernyms100-subgraph.txt"); System.out.println(wordNet.distance("freshener", "thing")); } }
package com.base.adev.activity; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import com.ashokvarma.bottomnavigation.BottomNavigationBar; import com.ashokvarma.bottomnavigation.BottomNavigationItem; import com.base.adev.R; import java.util.ArrayList; import java.util.List; /** * 底部 Tab 的基础 Activity * 继承此 Activity 后,初始化布局、添加 addItem、initialise 两个方法,传入相关的图标及文字即可。 * 想要更换 BottomNavigationBar 风格样式,请设置 setNavBarStyle 方法。 */ public abstract class BaseTabBottomActivity extends BaseActivity implements BottomNavigationBar.OnTabSelectedListener { private FragmentManager mFragmentManager; private BottomNavigationBar mBottomNavigationBar; private final List<Fragment> fragmentList = new ArrayList<>(); /** * BottomNavigationBar 的风格,默认:MODE_DEFAULT */ private int mMode = BottomNavigationBar.MODE_DEFAULT; /** * BottomNavigationBar 的背景样式,默认:BACKGROUND_STYLE_DEFAULT */ private int mBackgroundStyle = BottomNavigationBar.BACKGROUND_STYLE_DEFAULT; @Override protected void initView() { mFragmentManager = this.getSupportFragmentManager(); mBottomNavigationBar = (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar); mBottomNavigationBar.setTabSelectedListener(this); } /** * 添加 fragment 及 BottomNavigationItem(图标和文字) * * @param fragment fragment * @param imageId 图标 ID * @param title 标题(String) * @param activeColor 选定时颜色 */ public void addItem(Fragment fragment, int imageId, String title, int activeColor) { fragmentList.add(fragment); mBottomNavigationBar .addItem(new BottomNavigationItem(imageId, title).setActiveColorResource(activeColor)); } /** * 添加 fragment 及 BottomNavigationItem(图标和文字) * * @param fragment fragment * @param imageId 图标 ID * @param title 标题(int) * @param activeColor 选定时颜色 */ public void addItem(Fragment fragment, int imageId, int title, int activeColor) { fragmentList.add(fragment); mBottomNavigationBar .addItem(new BottomNavigationItem(imageId, title).setActiveColorResource(activeColor)); } /** * 添加 fragment 及 BottomNavigationItem(仅图标) * * @param fragment fragment * @param imageId 图标 ID * @param activeColor 选定时颜色 */ public void addItem(Fragment fragment, int imageId, int activeColor) { fragmentList.add(fragment); mBottomNavigationBar .addItem(new BottomNavigationItem(imageId).setActiveColorResource(activeColor)); } /** * 设置 BottomNavigationBar 风格样式 * * @param mode 风格 * @param backgroundStyle 背景样式 */ protected void setNavBarStyle(int mode, int backgroundStyle) { mMode = mode; mBackgroundStyle = backgroundStyle; } /** * 初始化容器,添加 fragment * * @param containerViewId 容器 ID */ public void initialise(int containerViewId) { mBottomNavigationBar.setMode(mMode); mBottomNavigationBar.setBackgroundStyle(mBackgroundStyle); FragmentTransaction transaction = mFragmentManager.beginTransaction(); for (Fragment fragment : fragmentList) { transaction.add(containerViewId, fragment); } transaction.commit(); showFragment(0); mBottomNavigationBar.initialise(); } /** * 显示 fragment * * @param position 位置 */ private void showFragment(int position) { FragmentTransaction transaction = mFragmentManager.beginTransaction(); for (int i = 0; i < fragmentList.size(); i++) { if (i != position) { transaction.hide(fragmentList.get(i)); } else { transaction.show(fragmentList.get(i)); } } transaction.commit(); } @Override public void onTabSelected(int position) { showFragment(position); } @Override public void onTabUnselected(int position) { } @Override public void onTabReselected(int position) { } }
import java.util.TreeSet; /** * This program represents the prototype of the Course specification. * The basic type STUDENT is implemented as a class, Also Courses is a class. See the * class 'Student', and 'CSDepartment' for its internal details. * This program uses built in datatypes of HashSets to keep track of the sets * * Written by : Abe Gustafson * Date : April 27, 2017 */ public class CSDepartment { private TreeSet<Student> students; private TreeSet<Course> courses; /* * The constructor method that implements init */ public CSDepartment() throws Exception{ students = new TreeSet<Student>(); courses = new TreeSet<Course>(); /* create 3 required courses and 1 elective */ Course r1 = new Course("CS741",true); Course r2 = new Course("CS742",true); Course r3 = new Course("CS743",true); Course e1 = new Course("CS521",false); courses.add(r1); courses.add(r2); courses.add(r3); courses.add(e1); //test (duplicate will overwrite... //courses.add(r1); //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "Constructor", "After"); return; } /* * Method for EnrollStudentInCourse Operation * Input: Course and Student to enroll */ public void EnrollStudentInCourse(Course course, Student newStudent) throws Exception{ //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "EnrollStudentInCourse", "Before"); //Precondition: Course must be a member of Courses if(course == null || !courses.contains(course)) throw new PreconditionException ("CSDepartment", "EnrollStudentInCourse", "course isnt a member courses"); //Precondition: newStudent must be a member of Students if(newStudent == null || !students.contains(newStudent)) throw new PreconditionException ("CSDepartment", "EnrollStudentInCourse", "newStudent isnt a member students"); //PostCondition: remove the course from the courses, perform enrollment, re add course course.EnrollStudent(newStudent); courses.remove(course); //course.EnrollStudent(newStudent); courses.add(course); //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "EnrollStudentInCourse", "After"); return; } /* * Method for DropStudentFromCourse operation * Input: Course and student to drop from the course */ public void DropStudentFromCourse(Course course, Student whichStudent) throws Exception{ //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "DropStudentFromCourse", "Before"); //Precondition: Course must be a member of Courses if(course == null || !courses.contains(course)) throw new PreconditionException ("CSDepartment", "DropStudentFromCourse", "course isnt a member courses"); //Precondition: newStudent must be a member of Students if(whichStudent == null || !students.contains(whichStudent)) throw new PreconditionException ("CSDepartment", "DropStudentFromCourse", "whichStudent isnt a member students"); //remove the course from the courses, perform drop, re add course course.DropStudent(whichStudent); courses.remove(course); //course.DropStudent(whichStudent); courses.add(course); //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "dropStudentFromCourse", "After"); return; } /* * method for AddTermWorkToCourse operation * Input: Adds a termwork to the Course */ public void AddTermWorkToCourse(Course course, TermWork tw) throws Exception{ //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "AddTermWorkToCourse", "Before"); //Precondition: Course must be a member of Courses if(course == null || !courses.contains(course)) throw new PreconditionException ("CSDepartment", "AddTermWorkToCourse", "course isnt a member courses"); //PostCondition: remove the course from the courses, perform addition, re add course course.AddTermWork(tw); courses.remove(course); courses.add(course); //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "AddTermWorkToCourse", "After"); return; } /* * Method for ChangeMarkForStudentInCourse * Input: Course, Student, Mark, Termwork * Change the mark for the student for the termwork in the given course */ public void ChangeMarkForStudentInCourse(Course course, Student forWho, Mark newMark, TermWork whichTermWork) throws Exception{ //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "ChangeMarkForStudentInCourse", "Before"); //Precondition: Course must be a member of Courses if(course == null || !courses.contains(course)) throw new PreconditionException ("CSDepartment", "ChangeMarkForStudentInCourse", "course isnt a member courses"); //Precondition: forWho must be a member of students if(forWho == null || !students.contains(forWho)) throw new PreconditionException ("CSDepartment", "ChangeMarkForStudentInCourse", "forWho isnt a member students"); /*//(MY)Precondition: whichTermWork must be a term work in the course if(!course.getTermWorks().contains(whichTermWork)) throw new PreconditionException ("CSDepartment", "ChangeMarkForStudentInCourse", "which termwork is not ");*/ //Postcondition: remove the course from the courses, perform drop, re add course course.ChangeTermWork(forWho, newMark, whichTermWork); courses.remove(course); courses.add(course); //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "ChangeMarkForStudentInCourse", "After"); return; } /* * Method for ReportGradeForStudentInCourse * Input: Course, Student * Ouptut: The Grade (PASS/FAIL) for the given student in the course */ public Course.Grade ReportGradeForStudentInCourse(Course course, Student forWho) throws Exception{ //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "ReportGradeForStudentInCourse", "Before"); //Precondition: Course must be a member of Courses if(course == null || !courses.contains(course)) throw new PreconditionException ("CSDepartment", "ReportGradeForStudentInCourse", "course isnt a member courses"); //Precondition: forWho must be a member of students if(forWho == null || !students.contains(forWho)) throw new PreconditionException ("CSDepartment", "ReportGradeForStudentInCourse", "forWho isnt a member students"); //Return value; Course.Grade grade = course.ReportGrade(forWho); //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "ReportGradeForStudentInCourse", "After"); return grade; } /* * Method for TopStudentInCourse operation * input: Course * Output: Student (the top student in the course) */ public Student TopStudentInCourse(Course course) throws Exception{ //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "TopStudentInCourse", "Before"); //Precondition: Course must be a member of Courses if(course == null || !courses.contains(course)) throw new PreconditionException ("CSDepartment", "ReportGradeForStudentInCourse", "course isnt a member courses"); //Postcondition: topStudent is the top student in the course Student topStudent = course.WhoGotMaximum(); //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "TopStudentInCourse", "After"); return topStudent; } /* * Method for AddNewElective * input: Course */ public void addNewElective(Course newCourse) throws Exception{ //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "AddNewElective", "Before"); //Precondition: there does not exist a course in courses where newCourse.courseNumber == // boolean alreadyExists = false; for(Course c : courses){ //the comparison already compares the courseNumber values if(c.equals(newCourse)){ alreadyExists = true; } } if(alreadyExists) throw new PreconditionException ("CSDepartment", "AddNewElective", "courseNumber already exists in courses"); //Precondition: newCourse.type = Elective if(newCourse.Required()) throw new PreconditionException ("CSDepartment", "AddNewElective", "newCourse is not an elective"); //Precondition: newCourse.students = emptyset if(newCourse.getStudents().size() != 0) throw new PreconditionException ("CSDepartment", "AddNewElective", "newCourse.students is not the emptyset"); //Precondition: newCourse.marks = emptyset if(newCourse.getMarks().size() != 0) throw new PreconditionException ("CSDepartment", "AddNewElective", "newCourse.marks is not the emptyset"); //Precondition: newCourse.termworks = emptysequence if(newCourse.getTermWorks().size() != 0) throw new PreconditionException ("CSDepartment", "AddNewElective", "newCourse.termworks is not the empty sequence"); //Postcondition: courses' = courses + newCourse courses.add(newCourse); //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "AddNewElective", "After"); return; } /* * Method for DeleteElective * input: Course */ public void deleteElective(Course whichCourse) throws Exception{ //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "deleteElective", "Before"); //Precondition: there exists a course in courses where the coursenum == whichCourse.coursenum //and the course is an elective if(whichCourse == null || !courses.contains(whichCourse) || whichCourse.Required() ) throw new PreconditionException ("CSDepartment", "deleteElective", "whichCourse does not exist and/or is not an elective"); //Precondition: the number of elective courses is > 1 int electiveCount = 0; for(Course c: courses){ if(!c.Required()){ electiveCount++; } } if(electiveCount <= 1) throw new PreconditionException ("CSDepartment", "deleteElective", "Less than or equal to one elective in courses"); //Postcondition: set courses' = courses - whichCourse courses.remove(whichCourse); //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "deleteElective", "After"); return; } /* * Method for AddNewStudent * input: student */ public void AddNewStudent(Student newStudent) throws Exception{ //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "AddNewStudent", "Before"); //Precondition: newStudent not a member of students if(newStudent == null || students.contains(newStudent)) throw new PreconditionException ("CSDepartment", "AddNewStudent", "newStudent already exists in CSDepartment"); //PostConditoin: students' = students + newStudent students.add(newStudent); //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "AddNewStudent", "After"); return; } /* * Method for Delete Student * input: student */ public void DeleteStudent(Student whichStudent) throws Exception{ //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "DeleteStudent", "Before"); //Precondition: whichStudent is a member of students if(whichStudent == null || !students.contains(whichStudent)) throw new PreconditionException ("CSDepartment", "DeleteStudent", "whichStudent does not exist in students"); //PostCondition: students' = students - whichStudent students.remove(whichStudent); //PostCondition: courses' = (all courses without whichStudent) U // (all courses with whichStudent such that all these courses have the whichStudent // removed from their students and from their marks) TreeSet<Course> updatedCourses = new TreeSet<Course>(); for(Course c : courses){ //if the course contains the student.. if(c.getStudents().contains(whichStudent)){ //drop student from course because it already contains all of the desired operations c.DropStudent(whichStudent); } updatedCourses.add(c); } courses = updatedCourses; //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "DeleteStudent", "After"); return; } /* * Method for ReportStudentCompletingRequirements * input; student * output: boolean (if the student completed the graduation requirements or not) */ public boolean ReportStudentCompletingRequirements(Student whichStudent) throws Exception{ //State Invariant if (!stateInvariantCheck()) throw new InvariantException ("CSDepartment", "ReportStudentCompletingRequirements", "Before"); //Precondition: whichStudent is a member of students if(whichStudent == null || !students.contains(whichStudent)) throw new PreconditionException ("CSDepartment", "ReportStudentCompletingRequirements", "whichStudent does not exist in students"); //Postcondition: there exist cores and elecs(constrain by cores and elecs subset of courses AND // #cores = 3 and #elecs >= 1) SUCH THAT all of the courses (cores U elecs) have been passed int numCores = 0; boolean allPassed = true; //List of all the courses taken TreeSet<Course> coursesTaken = new TreeSet<Course>(); for(Course c : courses){ //if the student is enrolled in the course c... add c to their coursesTaken if(c.getStudents().contains(whichStudent)){ if(c.Required()) numCores ++; //if they didnt pass the course if(c.ReportGrade(whichStudent) == Course.Grade.FAIL){ allPassed = false; } coursesTaken.add(c); } } //PostCondition: there must be 3 cores and at least one elective if(numCores != 3) return false; /*throw new PostconditionException ("CSDepartment", "ReportStudentCompletingRequirements", "Hasn't taken 3 core courses");*/ //PostCondition: Must have at least one elective if( (coursesTaken.size() - numCores) < 1 ){ return false; /*throw new PostconditionException ("CSDepartment", "ReportStudentCompletingRequirements", "Hasn't taken at least 1 elective");*/ } //PostCondition: coursesTaken must be passed if(!allPassed){ return false; /*throw new PostconditionException ("CSDepartment", "ReportStudentCompletingRequirements", "Hasn't passed all courses taken");*/ } return true; } /* * Used to get the specific course by name from the Main */ public Course getCourse(String name){ for(Course c : courses){ if(c.getCourseNumber().equals(name) ){ return c; } } return null; } /* * Used to get the specific Student by name from the Main */ public Student getStudent(String name){ for(Student c : students){ if(c.getName().equals(name) ){ return c; } } return null; } /* * Used to get the courses for use in printing in Main */ public TreeSet<Course> getCourses(){ return courses; } /* * State invariant check */ private boolean stateInvariantCheck(){ boolean retValue = true; //the distributed union of all the courses students is a subset of students TreeSet<Student> studsInCourses = new TreeSet<Student>(); for(Course co : courses){ //should ignore duplicate students studsInCourses.addAll(co.getStudents()); } //if studsInCourses is not a subset of students if(!students.containsAll(studsInCourses)){ retValue = false; } //HASHSETS automatically don't allow duplicate entries. //Since Courses are comparable by name, it will handle the implication that //if c1=c2, then c1.courseNumber = c2.courseNumber. //if the number of courses is less than 4 if(courses.size() < 4){ retValue = false; } //make sure that the number of courses that are core are = 3, the rest are not core courses int coreCount = 0; for(Course co : courses){ if(co.Required()){ coreCount++; } } //Coure count must be 3 if(coreCount != 3){ retValue = false; } return retValue; } }
package com.tencent.mm.plugin.appbrand.jsapi.live; import android.os.Bundle; import com.tencent.mm.plugin.appbrand.page.p.d; import com.tencent.mm.sdk.platformtools.x; class b$3 implements d { final /* synthetic */ AppBrandLivePlayerView fRH; final /* synthetic */ b fRI; b$3(b bVar, AppBrandLivePlayerView appBrandLivePlayerView) { this.fRI = bVar; this.fRH = appBrandLivePlayerView; } public final void agK() { j tC; l lVar = this.fRH.fRA; lVar.fSb = lVar.fRX.isPlaying(); if (lVar.fSb && lVar.fSh) { if (lVar.fRE && lVar.fRY != null) { lVar.fRY.onPlayEvent(6000, new Bundle()); } tC = lVar.tC("pause"); } else { tC = new j(); } x.i("MicroMsg.AppBrandLivePlayerView", "onBackground code:%d info:%s", new Object[]{Integer.valueOf(tC.errorCode), tC.fRT}); } }
package cn.hjf.handyutils; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.support.annotation.Nullable; /** * Android Application 信息相关的工具类 * Created by huangjinfu on 2017/6/28. */ public final class AppUtil { /** * 获取应用程序名称,读取 <application> 标签中的 'android:label' 属性。 * * @param context * @return null-'android:label' 属性没有指定,或者有异常产生。否则返回 'android:label' 属性的值,有可能是 "",如果 'android:label' 属性的值为 "" 的话。 */ @Nullable public static String getAppName(Context context) { PackageManager packageManager = context.getPackageManager(); try { ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0); return packageManager.getApplicationLabel(applicationInfo).toString(); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return null; } /** * 获取应用程序版本名称 * * @param context * @return null-没有指定 versionName 属性,或者有异常产生。否则返回 versionName 的值。 */ @Nullable public static String getAppVersionName(Context context) { PackageManager packageManager = context.getPackageManager(); try { PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0); return packageInfo.versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return null; } /** * 获取应用程序 VersionCode * * @param context * @return -1-有异常产生。0-没有指定 versionCode。否则返回 versionCode 的值。 */ public static int getAppVersionCode(Context context) { PackageManager packageManager = context.getPackageManager(); try { PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return -1; } }
package Sorting; import Searching.*; public class ISSStudent implements Comparable <ISSStudent>{ private String name, address; private int id; ISSStudent(String n, String a, int i){ name = n; address = a; id = i; } public String getName(){ return name; } @Override public String toString(){ return "Name:\t" + name + "\nAddress:\t" + address + "\nID:\t" + id; } public int getID(){ return id; } @Override public int compareTo(ISSStudent stud){ //this version uses name as the sorting and comparing field //vs. student id in the other version return name.compareTo(stud.name); } }
package adapters; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.gayashan.limbcare.GalleryCard; import com.example.gayashan.limbcare.R; import java.util.List; public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.ViewHolder> { private List<GalleryCard> cardItems; private Context context; public GalleryAdapter(List<GalleryCard> cardItems, Context context) { this.cardItems = cardItems; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.gallerycard, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { GalleryCard galleryCard = cardItems.get(position); holder.Gallerytopic.setText(galleryCard.getTopic()); holder.Gallerydescription.setText(galleryCard.getDescription()); holder.Galleryyid.setText(galleryCard.getIdgallery()); byte[] foodImage = galleryCard.getImage(); Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length); holder.GalarysImagee.setImageBitmap(bitmap); } @Override public int getItemCount() { return cardItems.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public TextView Galleryyid; public TextView Gallerytopic; public TextView Gallerydescription; public ImageView GalarysImagee; public ViewHolder(View itemView) { super(itemView); Galleryyid = itemView.findViewById(R.id.Galleryyid); Gallerytopic = itemView.findViewById(R.id.topicnoteW); Gallerydescription = itemView.findViewById(R.id.descriptionnoteW); GalarysImagee= itemView.findViewById(R.id.galleryimageNEW); } } }
package com.open.proxy.aop.advisor; import com.open.proxy.aop.advice.Advice; import com.open.proxy.aop.pointcut.PointCut; /** * @author jinming.wu * @date 2014-4-7 */ public class AspectJExpressionAdvisor implements Advisor { private PointCut pointCut; private Advice advice; @Override public Advice getAdvice() { return advice; } @Override public PointCut getPointCut() { return pointCut; } public void setPointCut(PointCut pointCut) { this.pointCut = pointCut; } public void setAdvice(Advice advice) { this.advice = advice; } }
package com.rca_gps.app.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Created by wafer on 2016/12/6. */ public class HistoryInfo implements Serializable{ private List<Message> caseInfos = new ArrayList<>(); public List<Message> getCaseInfos() { return caseInfos; } public void setCaseInfos(List<Message> caseInfos) { this.caseInfos = caseInfos; } }
package manju; import java.util.Scanner; public class Arthmatic { public static void main(String[] args) { Scanner scan = new Scanner(System.in); //System.out.print("Case #" + (cases+1) + ": "); int n = scan.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) { a[i] = scan.nextInt(); } int[] dif = new int[n-1]; for(int i = 0; i < n-1; i++) { dif[i] = a[i+1] - a[i]; //System.out.println(dif[i]); } int cur = 1,ans = 1; for(int i = 1; i < n - 1; i++) { if(dif[i] == dif[i-1]){ cur++; } else{ cur = 1; } ans = Math.max(ans,cur); } //max++; System.out.println(ans+1); } }
package com.encore.board.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.encore.board.domain.BoardVO; import com.encore.board.domain.MemberVO; import com.encore.board.model.BoardService; @Controller public class BoardController { @Autowired private BoardService boardService; @RequestMapping("write.do") public String write(BoardVO bvo, HttpSession session, Model model) throws Exception{ MemberVO mvo = (MemberVO) session.getAttribute("mvo"); if(session.getAttribute("mvo")==null) { //로그인 상태가 아니다.. return "redirect:index.jsp"; } bvo.setMemberVO(mvo); model.addAttribute("bvo", bvo); boardService.write(bvo); return "board/show_content"; } @RequestMapping("list.do") public String showList(Model model) throws Exception{ List<BoardVO> list = null; try { list = boardService.getBoardList(); //System.out.println(list); model.addAttribute("list", list); return "board/list"; }catch(Exception e) { return "Error"; } } @RequestMapping("showContent.do") public String showContent(Model model, HttpServletRequest request) throws Exception{ int no = Integer.parseInt(request.getParameter("no")); BoardVO rvo = null; //System.out.println(no); try { rvo = (BoardVO) boardService.showContent(no); model.addAttribute("bvo", rvo); return "board/show_content"; }catch(Exception e) { return "Error"; } } @RequestMapping("delete.do") public String delete(Model model, HttpServletRequest request) throws Exception{ int no = Integer.parseInt(request.getParameter("no")); //System.out.println(no); try { boardService.delete(no); return "redirect:list.do"; }catch(Exception e) { return "Error"; } } @RequestMapping("updateView.do") public String update(HttpServletRequest request, Model model) throws Exception{ try { int no = Integer.parseInt(request.getParameter("no")); BoardVO rvo = boardService.showContent(no); model.addAttribute("bvo", rvo); return "board/update"; }catch(Exception e) { return "Error"; } } @RequestMapping("updateBoard.do") public String updateBoard(BoardVO bvo) throws Exception{ boardService.update(bvo); return "redirect:list.do"; } }
/* * 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 pe.gob.onpe.adan.dao.adan.impl; import java.util.List; import org.springframework.stereotype.Repository; import pe.gob.onpe.adan.dao.adan.CargaDao; import pe.gob.onpe.adan.model.adan.Uploader; /** * * @author marrisueno */ @Repository("cargaDao") public class CargaDaoImpl extends AbstractDao<Integer, Uploader> implements CargaDao{ @Override public List<Uploader> listColumns(int typeUpload) { try { List<Uploader> lstUploader = getEntityManager() .createQuery("SELECT r FROM Uploader r WHERE r.uploadType=:uploadType") .setParameter("uploadType", typeUpload) .getResultList(); return lstUploader; } catch (Exception ex) { return null; } } }
/* * UniTime 3.4 - 3.5 (University Timetabling Application) * Copyright (C) 2012 - 2013, UniTime LLC, and individual contributors * as indicated by the @authors tag. * * 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 3 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, see <http://www.gnu.org/licenses/>. * */ package org.unitime.timetable.authenticate.jaas; import java.security.Principal; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.springframework.security.authentication.jaas.AuthorityGranter; import org.springframework.security.authentication.jaas.DefaultJaasAuthenticationProvider; import org.springframework.security.authentication.jaas.JaasAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.unitime.timetable.security.context.UniTimeUserContext; /** * @author Tomas Muller */ public class JaasAuthenticationProvider extends DefaultJaasAuthenticationProvider { public JaasAuthenticationProvider() { setAuthorityGranters(new AuthorityGranter[] { new AuthorityGranter() { @Override public Set<String> grant(Principal principal) { Set<String> roles = new HashSet<String>(); if (principal instanceof HasExternalId) { roles.add(((HasExternalId)principal).getExternalId()); } else { String user = principal.getName(); if (user.indexOf('@') >= 0) user = user.substring(0, user.indexOf('@')); roles.add(user); } return roles; } } }); } public Authentication authenticate(Authentication auth) throws AuthenticationException { JaasAuthenticationToken ret = (JaasAuthenticationToken)super.authenticate(auth); for (GrantedAuthority role: ret.getAuthorities()) { UniTimeUserContext user = new UniTimeUserContext(role.getAuthority(), ret.getName(), null, null); return new JaasAuthenticationToken(user, ret.getCredentials(), new ArrayList<GrantedAuthority>(user.getAuthorities()), ret.getLoginContext()); } return null; } }
package com.zhowin.miyou.mine.activity; import android.view.View; import com.zhowin.base_library.utils.ActivityManager; import com.zhowin.miyou.R; import com.zhowin.miyou.base.BaseBindActivity; import com.zhowin.miyou.databinding.ActivityMyGuildBinding; /** * 我的公会 */ public class MyGuildActivity extends BaseBindActivity<ActivityMyGuildBinding> { @Override public int getLayoutId() { return R.layout.activity_my_guild; } @Override public void initView() { setOnClick(R.id.ivBackReturn); } @Override public void initData() { } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ivBackReturn: ActivityManager.getAppInstance().finishActivity(); break; } } }
package servlet; import bean.Order; import bean.OrderItem; import bean.User; import dao.OrderDao; import dao.OrderItemDao; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; public class OrderCreateServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); User u = (User)request.getSession().getAttribute("user"); if (null == u){ response.sendRedirect("/login.jsp"); return; } Order o = new Order(); o.setUser(u); new OrderDao().insert(o); List<OrderItem> orderItems = (List<OrderItem>) request.getSession().getAttribute("ois"); for (OrderItem oi:orderItems){ oi.setOrder(o); new OrderItemDao().insert(oi); } orderItems.clear(); response.setContentType("text/html; charset=UTF-8"); response.getWriter().println("订单创建成功"); } }
package org.quarkchain.web3j.protocol.core.response; import java.io.IOException; import java.util.List; import java.util.Optional; import org.quarkchain.web3j.protocol.ObjectMapperFactory; import org.quarkchain.web3j.protocol.core.Response; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** * networkInfo */ public class NetworkInfo extends Response<NetworkInfo.Info> { @Override @JsonDeserialize(using = NetworkInfo.ResponseDeserialiser.class) public void setResult(Info result) { super.setResult(result); } public Optional<Info> getInfo() { return Optional.ofNullable(getResult()); } public static class Info { @Override public String toString() { return "Info [networkId=" + networkId + ", chainSize=" + chainSize + ", syncing=" + syncing + ", mining=" + mining + ", shardServerCount=" + shardServerCount + ", shardSizes=" + shardSizes + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((chainSize == null) ? 0 : chainSize.hashCode()); result = prime * result + ((mining == null) ? 0 : mining.hashCode()); result = prime * result + ((networkId == null) ? 0 : networkId.hashCode()); result = prime * result + ((shardServerCount == null) ? 0 : shardServerCount.hashCode()); result = prime * result + ((shardSizes == null) ? 0 : shardSizes.hashCode()); result = prime * result + ((syncing == null) ? 0 : syncing.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Info other = (Info) obj; if (chainSize == null) { if (other.chainSize != null) return false; } else if (!chainSize.equals(other.chainSize)) return false; if (mining == null) { if (other.mining != null) return false; } else if (!mining.equals(other.mining)) return false; if (networkId == null) { if (other.networkId != null) return false; } else if (!networkId.equals(other.networkId)) return false; if (shardServerCount == null) { if (other.shardServerCount != null) return false; } else if (!shardServerCount.equals(other.shardServerCount)) return false; if (shardSizes == null) { if (other.shardSizes != null) return false; } else if (!shardSizes.equals(other.shardSizes)) return false; if (syncing == null) { if (other.syncing != null) return false; } else if (!syncing.equals(other.syncing)) return false; return true; } public String getNetworkId() { return networkId; } public void setNetworkId(String networkId) { this.networkId = networkId; } public String getChainSize() { return chainSize; } public void setChainSize(String chainSize) { this.chainSize = chainSize; } public String getSyncing() { return syncing; } public void setSyncing(String syncing) { this.syncing = syncing; } public String getMining() { return mining; } public void setMining(String mining) { this.mining = mining; } public String getShardServerCount() { return shardServerCount; } public void setShardServerCount(String shardServerCount) { this.shardServerCount = shardServerCount; } public List<String> getShardSizes() { return shardSizes; } public void setShardSizes(List<String> shardSizes) { this.shardSizes = shardSizes; } private String networkId; private String chainSize; private String syncing; private String mining; private String shardServerCount; private List<String>shardSizes; } public Info networkInfo() { return getResult(); } public static class ResponseDeserialiser extends JsonDeserializer<Info> { private ObjectReader objectReader = ObjectMapperFactory.getObjectReader(); @Override public Info deserialize( JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { if (jsonParser.getCurrentToken() != JsonToken.VALUE_NULL) { return objectReader.readValue(jsonParser, Info.class); } else { return null; // null is wrapped by Optional in above getter } } } }
package demoinclusionlibrairie; public class DemoInclusionLibrairie { public static void main(String[] args) { System.out.println("5 + 1000000 = "); System.out.println("5 - 7 = "); System.out.println("premier commit"); } }
/* * Copyright (C) 2001 - 2015 Marko Salmela, http://fuusio.org * * 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 org.fuusio.api.rest; import org.fuusio.api.util.L; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Random; public class Nonce { /** * Generates a nonce string using the given time stamp as a seed. * * @param timeStamp A time stamp as a {@link String}. * @return A nonce {@link String}. */ public String generate(final String timeStamp) { final Random random = new Random(System.currentTimeMillis()); final String message = timeStamp + Integer.toString(random.nextInt()); try { final MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(message.getBytes()); final byte[] digestBytes = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { String hex = Integer.toHexString(0xFF & digestBytes[i]); if (hex.length() == 1) { // TODO hexString.append('0'); } hexString.append(hex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { L.wtf(this, "generate", e.getMessage()); } return null; } /** * Generates a nonce string using a time stamp as a seed. * * @param timeStamp A time stamp. * @return A nonce {@link String}. */ public String generate(final long timeStamp) { final String timeStampString = Long.toString(timeStamp); final int endIndex = timeStampString.length() - 3; return generate(timeStampString.substring(0, endIndex)); } /** * Returns a string representation of a nonce. It should be noted that {@link String} value is * different for each invocation. * * @return A {@link String}. */ @Override public final String toString() { return generate(System.currentTimeMillis()); } }
package com.situ.student.service; import java.util.List; import com.situ.student.controller.BanjiSearchCondition; import com.situ.student.controller.PageBean; import com.situ.student.controller.StudentSearchCondition; import com.situ.student.entity.Banji; import com.situ.student.entity.Student; public interface IBanjiService { List<Banji> findAll(); /** * 添加学生 * @param student * @return Constant.ADD_SUCCESS=1 添加成功 * Constant.ADD_FAIL=2 添加数据库失败 * Constant.ADD_NAME_REPEAT=3 名字重复 */ int add(Banji banji); List<Banji> findByName(String name); boolean deleteById(int id); Banji findById(int id); boolean update(Banji banji); boolean deleteAll(String[] ids); PageBean getPageBean(int pageNo, int pageSize); PageBean<Banji> searchByCondition(BanjiSearchCondition banjiSearchCondition); }
package driver; public class ConfusionMatrix { private int size; private int[][] matrix; /** * Creates a zeroed confusion matrix of specified size nxn. * * @param size The width/height of the confusion matrix. */ public ConfusionMatrix(int size) { this.size = size; matrix = new int[size][size]; } /** * @return The width/height of the confusion matrix. */ public int size() { return size; } /** * Increment the specified element matrix[expected][actual] * * @param expected The expected class for the example. * @param actual The actual class returned by the classifier. */ public void increment(int expected, int actual) { this.matrix[expected][actual]++; } /** * Prints a graphical representation of the matrix to standard out. */ public void printMatrix() { System.out.println(this); } /** * Returns a graphical representation of the matrix in string format. */ public String toString() { String value = ""; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { value += String.format("%4s", this.matrix[i][j]); } value += "\n"; } return value; } }
package com.progoth.synchrochat.client.gui.controllers; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.regexp.shared.MatchResult; import com.google.gwt.regexp.shared.RegExp; import com.google.gwt.user.client.Window; import com.progoth.synchrochat.client.events.RoomJoinRequestEvent; import com.progoth.synchrochat.client.events.SynchroBus; import com.progoth.synchrochat.shared.FieldVerifier; import com.progoth.synchrochat.shared.model.ChatRoom; public class UrlController { private static final UrlController sm_instance = new UrlController(); private static final RegExp sm_room = RegExp.compile("^#/room/(.*)$"); public static UrlController get() { return sm_instance; } private UrlController() { // singleton } public void startupAction() { final MatchResult m = sm_room.exec(Window.Location.getHash()); if (m == null) return; final String room = m.getGroup(1); if (FieldVerifier.validChatRoomName(room)) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { SynchroBus.get().fireEvent(new RoomJoinRequestEvent(new ChatRoom(room))); } }); } } public void updateUrl(final ChatRoom aSelection) { String curUrl = Window.Location.getHref(); if (!Window.Location.getHash().isEmpty()) { curUrl = curUrl.replace(Window.Location.getHash(), ""); } else if (curUrl.endsWith("#")) { curUrl = curUrl.substring(0, curUrl.length() - 1); } if (aSelection != null) { Window.Location.assign(curUrl + "#/room/" + aSelection.getName()); } else { Window.Location.assign(curUrl + '#'); } } }
package com.shopify.order.popup; import lombok.Data; @Data public class Pair { private int divisor; private int divisorCount; public Pair(Integer divisor, int divisorCount) { this.divisor = divisor; this.divisorCount = divisorCount; } }
package com.shafear.notes.mvp.presenter; import android.content.Intent; import com.shafear.notes.global.G; import com.shafear.notes.mvp.model.MNotes; import com.shafear.notes.mvp.view.VNotesList; import com.shafear.notes.xnotes.XNotes; /** * Created by shafe_000 on 2015-02-08. */ public class PShowNotes { public PShowNotes(){ this.choosedShowTheNotes(); } private void choosedShowTheNotes(){ //XNotes xNotes = loadNotesData(); //showNotesListScreen(xNotes); } public XNotes loadNotesData() { MNotes mNotes = new MNotes(); return mNotes.loadNotesData(); } public void showNotesListScreen(){ Intent intent = new Intent(G.ACTIVITY.getApplicationContext(), VNotesList.class); G.ACTIVITY.startActivity(intent); } }
/** *Het scherm waar de applicatie op draait * * @Madelon * @1.0 */ import javax.swing.*; class GUIMinesweeper extends JFrame { JPanel game; int width; int height; public GUIMinesweeper(int rows, int columns) { height = rows; width = columns; setContentPane( new MyGridLayout(height, width) ); //dit is wat op het scherm komt setLayout(null); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setTitle( "Minesweeper" ); setVisible(true); //de grootte past zich aan op basis van de input. De kolommen iets meer, aangezien dat er standaard iets meer zijn setSize(columns*33, rows*35); } }
package java.awt; public abstract class Image { }
/** * Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro * Copyright: 2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ package seava.ad.domain.impl.security; import java.io.Serializable; import java.util.Collection; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.QueryHint; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; import seava.j4e.domain.impl.AbstractTypeWithCode; @NamedQueries({ @NamedQuery(name = Role.NQ_FIND_BY_CODE, query = "SELECT e FROM Role e WHERE e.clientId = :clientId and e.code = :code", hints = @QueryHint(name = QueryHints.BIND_PARAMETERS, value = HintValues.TRUE)), @NamedQuery(name = Role.NQ_FIND_BY_NAME, query = "SELECT e FROM Role e WHERE e.clientId = :clientId and e.name = :name", hints = @QueryHint(name = QueryHints.BIND_PARAMETERS, value = HintValues.TRUE))}) @Entity @Table(name = Role.TABLE_NAME, uniqueConstraints = { @UniqueConstraint(name = Role.TABLE_NAME + "_UK1", columnNames = { "CLIENTID", "CODE"}), @UniqueConstraint(name = Role.TABLE_NAME + "_UK2", columnNames = { "CLIENTID", "NAME"})}) public class Role extends AbstractTypeWithCode implements Serializable { public static final String TABLE_NAME = "AD_ROLE"; private static final long serialVersionUID = -8865917134914502125L; /** * Named query find by unique key: Code. */ public static final String NQ_FIND_BY_CODE = "Role.findByCode"; /** * Named query find by unique key: Name. */ public static final String NQ_FIND_BY_NAME = "Role.findByName"; @ManyToMany(mappedBy = "roles") private Collection<User> users; @ManyToMany @JoinTable(name = "AD_ROLE_ACL", joinColumns = {@JoinColumn(name = "ROLES_ID")}, inverseJoinColumns = {@JoinColumn(name = "ACCESSCONTROLS_ID")}) private Collection<AccessControl> accessControls; @ManyToMany @JoinTable(name = "AD_ROLE_MENU", joinColumns = {@JoinColumn(name = "ROLES_ID")}, inverseJoinColumns = {@JoinColumn(name = "MENUS_ID")}) private Collection<Menu> menus; @ManyToMany @JoinTable(name = "AD_ROLE_MENUITEM", joinColumns = {@JoinColumn(name = "ROLES_ID")}, inverseJoinColumns = {@JoinColumn(name = "MENUITEMS_ID")}) private Collection<MenuItem> menuItems; public Collection<User> getUsers() { return this.users; } public void setUsers(Collection<User> users) { this.users = users; } public Collection<AccessControl> getAccessControls() { return this.accessControls; } public void setAccessControls(Collection<AccessControl> accessControls) { this.accessControls = accessControls; } public Collection<Menu> getMenus() { return this.menus; } public void setMenus(Collection<Menu> menus) { this.menus = menus; } public Collection<MenuItem> getMenuItems() { return this.menuItems; } public void setMenuItems(Collection<MenuItem> menuItems) { this.menuItems = menuItems; } @PrePersist public void prePersist() { super.prePersist(); } @PreUpdate public void preUpdate() { super.preUpdate(); } }
package cn.bs.zjzc.ui; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.bigkoo.pickerview.OptionsPickerView; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import cn.bs.zjzc.App; import cn.bs.zjzc.R; import cn.bs.zjzc.base.BaseFilterPhotoActivity; import cn.bs.zjzc.bean.ProvinceCityListResponse; import cn.bs.zjzc.dialog.MessageTools; import cn.bs.zjzc.div.NormalPopuMenu; import cn.bs.zjzc.model.bean.RegisterOrderTakerRequestBody; import cn.bs.zjzc.model.bean.UploadFileBody; import cn.bs.zjzc.presenter.RegisterOrderTakerPresenter; import cn.bs.zjzc.ui.view.IRegisterOrderTakerView; import cn.bs.zjzc.util.MD5; /** * Created by Ming on 2016/5/31. */ public class AvRegisterOrderTaker extends BaseFilterPhotoActivity implements View.OnClickListener, IRegisterOrderTakerView { private Context mContext = this; private RegisterOrderTakerPresenter mRegisterOrderTakerPresenter; private TextView btnSelectCity; private EditText etRealName; private EditText etIdNumber; private ImageView frontPhoto; private ImageView backPhoto; private ImageView peoplePhoto; private ImageView btnAddFrontPhoto; private ImageView btnAddBackPhoto; private ImageView btnAddPeoplePhoto; private TextView btnCommit; private Map<String, UploadFileBody> photoMap; private NormalPopuMenu mNormalPopuMenu; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.av_register_order_taker); mRegisterOrderTakerPresenter = new RegisterOrderTakerPresenter(this); photoMap = new HashMap<>(); initViews(); initEvents(); //初始化图片裁剪参数 setCropConfig(600, 460, 30, 23); } private void initEvents() { btnSelectCity.setOnClickListener(this); btnAddFrontPhoto.setOnClickListener(this); btnAddBackPhoto.setOnClickListener(this); btnAddPeoplePhoto.setOnClickListener(this); btnCommit.setOnClickListener(this); } private void initViews() { btnSelectCity = ((TextView) findViewById(R.id.register_order_taker_select_city)); etRealName = ((EditText) findViewById(R.id.register_order_taker_et_real_name)); etIdNumber = ((EditText) findViewById(R.id.register_order_taker_et_id_number)); frontPhoto = ((ImageView) findViewById(R.id.register_order_taker_identification_photo1)); backPhoto = ((ImageView) findViewById(R.id.register_order_taker_identification_photo2)); peoplePhoto = ((ImageView) findViewById(R.id.register_order_taker_identification_photo3)); btnAddFrontPhoto = ((ImageView) findViewById(R.id.register_order_taker_add_identification_photo1)); btnAddBackPhoto = ((ImageView) findViewById(R.id.register_order_taker_add_identification_photo2)); btnAddPeoplePhoto = ((ImageView) findViewById(R.id.register_order_taker_add_identification_photo3)); btnCommit = ((TextView) findViewById(R.id.register_order_taker_btn_commit)); //添加标记 btnAddFrontPhoto.setTag("ID_photo"); btnAddBackPhoto.setTag("ID_back_photo"); btnAddPeoplePhoto.setTag("ID_people"); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && requestCode == CROP_PHOTO_REQUEST_CODE) { String fileName = outputUri.getLastPathSegment(); if (fileName.equals(getPhotoName((String) btnAddFrontPhoto.getTag()))) {//身份证正面照 frontPhoto.setImageBitmap(getFilterPhoto()); } else if (fileName.equals(getPhotoName((String) btnAddBackPhoto.getTag()))) {//身份证反面照 backPhoto.setImageBitmap(getFilterPhoto()); } else if (fileName.equals(getPhotoName((String) btnAddPeoplePhoto.getTag()))) {//手持身份证照 peoplePhoto.setImageBitmap(getFilterPhoto()); } } } @Override public void onClick(final View v) { switch (v.getId()) { case R.id.register_order_taker_select_city: showCityPickerView(); break; case R.id.register_order_taker_add_identification_photo1: case R.id.register_order_taker_add_identification_photo2: case R.id.register_order_taker_add_identification_photo3: showSelectPhotoPupuMenu(v); break; case R.id.register_order_taker_btn_commit: registerOrderTaker(); break; } } private void showCityPickerView() { OptionsPickerView pvOptions = new OptionsPickerView(mContext); //一级菜单(省)数组 ArrayList<ProvinceCityListResponse.DataBean> pList = new ArrayList<>(); //二级菜单(市)数组 final ArrayList<ArrayList<ProvinceCityListResponse.DataBean.CityListBean>> pcList = new ArrayList<>(); //添加省份数据到一级菜单数组 pList.addAll(App.LOGIN_USER.getProvinceCityList()); int size = pList.size(); //循环添加城市到二级菜单 for (int i = 0; i < size; i++) { ArrayList<ProvinceCityListResponse.DataBean.CityListBean> city_list = pList.get(i).city_list; //如果城市列表为空,则删除改省份 if (city_list.size() == 0) { pList.remove(i); i--; size--; continue; } pcList.add(city_list); } //设置监听 pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() { @Override public void onOptionsSelect(int options1, int option2, int options3) { String name = pcList.get(options1).get(option2).name; Log.i("onOptionsSelect", "onOptionsSelect: " + name); btnSelectCity.setText(name); } }); //设置多级联动菜单的标题 pvOptions.setTitle("选择城市"); //设置多级联动菜单的数据 pvOptions.setPicker(pList, pcList, true); //设置菜单是否循环显示 pvOptions.setCyclic(false, false, false); pvOptions.show(); } private void showSelectPhotoPupuMenu(final View v) { if (mNormalPopuMenu == null) { mNormalPopuMenu = new NormalPopuMenu(mContext); mNormalPopuMenu.setMenuGravity(Gravity.CENTER); } String[] items = getResources().getStringArray(R.array.str_array_setting_header); mNormalPopuMenu.show(v, "上传相片", items, new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position == 1) { fromAlbum(); addPhotoBody(v); } else if (position == 2) { fromTakePhoto(); addPhotoBody(v); } else if (position == 3) { mNormalPopuMenu.dismiss(); } } }); } private void addPhotoBody(View v) { UploadFileBody photoBody = new UploadFileBody(); String tag = (String) v.getTag(); photoBody.fileName = getPhotoName(tag); photoBody.file = savePhoto(photoBody.fileName); photoMap.put(tag, photoBody); mNormalPopuMenu.dismiss(); } @NonNull private String getPhotoName(String key) { return MD5.getMD5(key) + ".jpg"; } private void registerOrderTaker() { String address = btnSelectCity.getText().toString(); String realName = etRealName.getText().toString(); String idNumber = etIdNumber.getText().toString(); if (TextUtils.isEmpty(address)) { showMsg("没有选择地址"); return; } if (TextUtils.isEmpty(realName)) { showMsg("没有输入真实姓名"); return; } if (TextUtils.isEmpty(idNumber)) { showMsg("没有输入身份证号码"); return; } //身份证未验证 if(!Pattern.matches("(^\\d{15}$)|(^\\d{17}([0-9]|X|x)$)", idNumber)){ showMsg("请输入正确的身份证号码"); return; } if (!photoMap.containsKey("ID_photo")) { showMsg("请上传身份证正面照"); return; } if (!photoMap.containsKey("ID_back_photo")) { showMsg("请上传身份证反面照"); return; } if (!photoMap.containsKey("ID_people")) { showMsg("请上传手持身份证照"); return; } mRegisterOrderTakerPresenter.registerOrderTaker(new RegisterOrderTakerRequestBody(address, realName, idNumber, photoMap)); } @Override public void registOrderUserSuccess(String msg) { MessageTools.showDialog(this, "申请结果", msg, false, "我知道了", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AvRegisterOrderTaker.this.finish(); } }); } }
package com.eric.tools.file; import com.eric.tools.decode.APKTool; import com.eric.tools.time.TimeConvert; import java.time.Duration; import java.time.Instant; /** * @ClassName: FileRunnable * @Description: 实现了Runnable接口的多线程文件操作类 * @Author: Eric * @Date: 2019/3/7 0007 * @Email: xiao_cui_vip@163.com */ //该类暂时已经用不到了,如果后续确认不在需要该类时可以将其删除 /* public class FileRunnable implements Runnable { //APK文件源路径(文件夹) private String src; //反编译文件输出路径(文件夹) private String des; public FileRunnable() { } public FileRunnable(String src, String des) { this.src = src; this.des = des; } @Override public void run() { Instant start = Instant.now(); System.out.println(">>>线程:" + Thread.currentThread().getName() + "开始执行<<<"); APKTool.decode(src, des); Instant end = Instant.now(); System.out.print(">>>线程:" + Thread.currentThread().getName() + "执行完毕,耗时:"); TimeConvert.convert(Duration.between(start, end).toMillis()); } public String getSrc() { return src; } public void setSrc(String src) { this.src = src; } public String getDes() { return des; } public void setDes(String des) { this.des = des; } } */
package serverframe_listener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; import java.util.Vector; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import server_util.Table_util; import serverframe_usermanage.UserManagePanel; /**用户管理密码重置监听 * @author lisu * */ public class UserM_ModifypasswordListener implements ActionListener { /** *用户管理面板 */ private UserManagePanel managePanel; public UserM_ModifypasswordListener(UserManagePanel managePanel) { this.managePanel = managePanel; } public void actionPerformed(ActionEvent e) { int index = managePanel.getTable().getSelectedRow(); if (index < 0) { JOptionPane.showMessageDialog(null, "请选择一行后再做密码重置"); return; } else { //在文件里修改密码 String userid = String.valueOf(managePanel.getTable().getValueAt(index, 0)); String password="123456"; Table_util.modifypassword(password,userid); } //更新表格 Table_util.renew_Table(this.managePanel.getTable(), this.managePanel.getColumnVector()); managePanel.getButton_Modify().setEnabled(false); managePanel.getButton_Delete().setEnabled(false); managePanel.getButton_Modifypassword().setEnabled(false); } }
package com.prokarma.reference.architecture.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Presale { @SerializedName("startDateTime") @Expose public String startDateTime; @SerializedName("endDateTime") @Expose public String endDateTime; @SerializedName("name") @Expose public String name; @SerializedName("description") @Expose public String description; @SerializedName("url") @Expose public String url; }
package pageObject; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.RemoteWebDriver; //1st web pages's POM public class loginHome { public WebDriver driver; public loginHome(WebDriver driver) { this.driver = driver; } By loginLocate = By.linkText("Login"); By text= By.id("PHPTRAVELS"); By navbar= By.className("clearfix"); public WebElement login() { return driver.findElement(loginLocate); } public WebElement returntext() { return driver.findElement(text); } public WebElement returnnav() { return driver.findElement(navbar); } }
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; /** @author <<author name redacted >> Purpose: Homework assignment 1, sorting a table object to test its functionalities */ public class TableSorter{ static int counter = 0; public static void main (String[]args)throws IOException, Exception{ Table tableInit = Table.GetTable("matrix.txt"); sortable(tableInit); Print(tableInit); System.out.println(); System.out.println(isSorted(tableInit)); System.out.println(counter); } public static void sortable(Table t){ int row = 0; //Bubble sort is implemented to sort numbers at the row level first while (row<t.getSize()){ counter++; int n = t.getSize(); for(int i=0; i< n-1 ; i++){ counter+=2; for(int j=0; j<n-i-1; j++){ counter+=2; if(t.getTableValue(row,j) > t.getTableValue(row,j+1)){ counter++; int temp = t.getTableValue(row,j); counter++; t.setTableValue(row,j,t.getTableValue(row,j+1)); counter++; t.setTableValue(row,j+1,temp); counter++; } } } row++; counter++; } int col = 0; row = 0; counter+=2; //Bubble sort is then implemented again at the column level once rows are sorted while (col<t.getSize()){ counter++; int n = t.getSize(); counter++; for(int i=0; i< n-1 ; i++){ counter+=2; for(int j=0; j<n-i-1; j++){ counter+=2; if(t.getTableValue(j,col) > t.getTableValue(j+1,col)){ counter++; int temp = t.getTableValue(j,col); counter++; t.setTableValue(j,col,t.getTableValue(j+1,col)); counter++; t.setTableValue(j+1,col,temp); counter++; } } } col++; counter++; } } public static boolean isSorted(Table t){ for(int i=0; i<t.getSize(); i++){ for(int j=0; j<t.getSize() -1; j++){ if (t.getTableValue(i,j)>t.getTableValue(i,j+1)){ return false; } } } for(int i=0; i<t.getSize(); i++){ for(int j=0; j<t.getSize()-1; j++){ if (t.getTableValue(j,i)>t.getTableValue(j+1,i)){ return false; } } } return true; } public static void Print(Table t){ for(int i=0; i<t.getSize(); i++){ for(int j=0; j<t.getSize(); j++){ System.out.print(t.getTableValue(i,j)+" "); } System.out.println(); } } }
package edu.ssafy.root.dao; import java.util.List; import edu.ssafy.root.food.Food; import edu.ssafy.root.member.Member; import edu.ssafy.root.member.MemberDetail; import edu.ssafy.root.member.eatListDTO; public interface MemberDAO { public boolean add(Member m); public boolean modify(Member m); public void delete(String id); public Member search(String id); public int getSize(); public String getName(String id); public boolean addProduct(int fcode, int btnId, int fCnt, String userId); public List<Member> searchAll(); // 섭취 정보 public List<eatListDTO> eatList(String id); public void deleteEatFood(MemberDetail md); public double[] sumEat(String id); public List<MemberDetail> eatList(); }
package com.changhui.demo1; public enum CountryEnums { ONE(1, "韩"), TWO(2, "魏"), Three(3, "赵"), FOUR(4, "齐"), FIVE(5, "楚"), SIX(6, "燕"); private Integer retCode; private String retMsg; private CountryEnums(Integer retCode, String retMsg) { this.retCode = retCode; this.retMsg = retMsg; } public Integer getRetCode() { return retCode; } public void setRetCode(Integer retCode) { this.retCode = retCode; } public String getRetMsg() { return retMsg; } public void setRetMsg(String retMsg) { this.retMsg = retMsg; } public static CountryEnums forEachCountryEnums(int i) { for (CountryEnums countryEnums : values()) { if (countryEnums.getRetCode() == i) return countryEnums; } return null; } }
package shiro; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import java.util.Set; /** * @author malf * @description TODO * @project how2jStudy * @since 2020/11/9 */ public class DatabaseRealm extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { // 能进入到这里,表示账号已经通过验证了 String userName = (String) principalCollection.getPrimaryPrincipal(); // 通过 UserDao 获取角色和权限 UserDao userDao = new UserDao(); Set<String> roles = userDao.roles(userName); Set<String> permissions = userDao.permissions(userName); // 授权对象 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); // 把角色和权限关联进去 info.setRoles(roles); info.setStringPermissions(permissions); return info; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 获取账号密码 UsernamePasswordToken t = (UsernamePasswordToken) token; String userName = token.getPrincipal().toString(); String password = new String(t.getPassword()); // 获取数据库中的密码 UserDao userDao = new UserDao(); User user = userDao.getUser(userName); String passwordInDB = user.getPassword(); String salt = user.getSalt(); String encodedPassword = new SimpleHash("md5", password, salt, 2).toString(); if (null == user || !encodedPassword.equals(passwordInDB)) { throw new AuthenticationException(); } // 如果为空就是账号不存在,如果不相同就是密码错误,但是都抛出 AuthenticationException,而不是抛出具体错误原因,免得给破解者提供帮助信息 // if (null == passwordInDB || !passwordInDB.equals(password)){ // throw new AuthenticationException(); // } // 认证信息里存放账号密码, getName() 是当前 Realm 的继承方法,通常返回当前类名 :databaseRealm SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName, password, getName()); return info; } }
package cn.uway.config; import java.io.File; import java.util.List; /** * 配置文件读取器<br> * 主要是把配置文件中配置的bean对象读取为Map,提供对象转换器将map转换为实例对象。 * * * @ClassName: ConfigReader * @author Niow * @date: 2014-6-18 */ public interface ConfigReader{ /** * 把一个配置文件中配置的所有Bean读取到内存中<br> * * @param file 文件对象 * @return 返回一个包含bean名称和属性的列表集合 */ public List<ConfigBean> readConfigBean(File file) throws Exception; /** * 把一个配置文件中配置的所有Bean读取到内存中<br> * * @param filePath 文件路径,具体是相对路径还是绝对路径由实现类控制 * @return 返回一个包含bean名称和属性的列表集合 */ public List<ConfigBean> readConfigBean(String filePath) throws Exception; }
/** * Copyright (C) 2011-2013 BonitaSoft S.A. * BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble * * 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.0 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, see <http://www.gnu.org/licenses/>. */ package org.bonitasoft.studio.tests.pagetemplate; import org.bonitasoft.studio.form.properties.i18n.Messages; import org.bonitasoft.studio.test.swtbot.util.SWTBotTestUtil; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor; import org.eclipse.swtbot.eclipse.gef.finder.SWTBotGefTestCase; import org.eclipse.swtbot.eclipse.gef.finder.SWTGefBot; import org.eclipse.swtbot.eclipse.gef.finder.widgets.SWTBotGefEditPart; import org.eclipse.swtbot.eclipse.gef.finder.widgets.SWTBotGefEditor; import org.eclipse.swtbot.swt.finder.SWTBot; import org.eclipse.swtbot.swt.finder.junit.SWTBotJunit4ClassRunner; import org.eclipse.swtbot.swt.finder.waits.Conditions; import org.eclipse.swtbot.swt.finder.waits.DefaultCondition; import org.eclipse.swtbot.swt.finder.waits.ICondition; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; /** * @author Aurelien Pupier * */ @RunWith(SWTBotJunit4ClassRunner.class) public class TestPageTemplate extends SWTBotGefTestCase { protected String editorTextContent; @Test @Ignore("Fix me in TR") public void testUsePageTemplate(){ SWTBotGefEditor formGefEditor = addUsageOfDefaultPageTemplate(); formGefEditor.activateTool("Checkbox"); formGefEditor.click(200,200); formGefEditor.save(); formGefEditor.mainEditPart().select(); checkTextInsideHtml("<div id=\"Checkbox1\">"); /*Modify widget name*/ SWTBotGefEditPart checkboxPart = formGefEditor.getEditPart("Checkbox1").parent(); formGefEditor.select(checkboxPart); bot.viewById(SWTBotTestUtil.VIEWS_PROPERTIES_FORM_GENERAL).show(); SWTBotTestUtil.selectTabbedPropertyView(bot, "General"); bot.button("Edit...").click(); //bot.waitUntil(Conditions.shellIsActive(Messages.)) bot.text("Checkbox1").setText("CheckboxModified"); bot.button(IDialogConstants.OK_LABEL).click(); bot.activeEditor().save(); saveEditorAndWaitNoMoreDirtyState(); /*check it has opened, content and close it to come back to form editor*/ formGefEditor.mainEditPart().click(); checkTextInsideHtml("<div id=\"CheckboxModified\">");//the line should be at the end /*Check restore*/ bot.viewById(SWTBotTestUtil.VIEWS_PROPERTIES_FORM_GENERAL).show(); SWTBotTestUtil.selectTabbedPropertyView(bot, "General"); bot.button(Messages.Restore).click(); bot.waitUntil(Conditions.shellIsActive(Messages.confirm_title)); bot.button(IDialogConstants.OK_LABEL).click(); /*check it has opened, content and close it to come back to form editor*/ formGefEditor.mainEditPart().select(); checkTextInsideHtml("<div id=\"CheckboxModified\">");//the line should be better /*Add and delete a widget, check that there is a warning popup*/ formGefEditor.activateTool("Date"); formGefEditor.click(200,100); formGefEditor.save(); formGefEditor.getEditPart("Date1").parent().select(); formGefEditor.clickContextMenu("Delete"); bot.button(IDialogConstants.OK_LABEL).click(); bot.waitUntil(Conditions.shellIsActive("Warning")); bot.button(IDialogConstants.OK_LABEL).click(); saveEditorAndWaitNoMoreDirtyState(); /*check it has opened, content and close it to come back to form editor*/ formGefEditor.mainEditPart().select(); checkTextInsideHtml("<div id=\"Date1\">"); bot.viewById(SWTBotTestUtil.VIEWS_PROPERTIES_FORM_GENERAL).show(); SWTBotTestUtil.selectTabbedPropertyView(bot, "General"); bot.button(Messages.Clear).click(); bot.waitUntil(Conditions.shellIsActive(Messages.confirm_title)); bot.button(IDialogConstants.OK_LABEL).click(); saveEditorAndWaitNoMoreDirtyState(); assertFalse("Edit button is still enabled", bot.button(Messages.Edit).isEnabled()); assertFalse("Clear button is still enabled", bot.button(Messages.Clear).isEnabled()); } private SWTGefBot saveEditorAndWaitNoMoreDirtyState() { final SWTGefBot gefBot = bot; gefBot.activeEditor().save(); bot.waitUntil(new DefaultCondition() { public boolean test() throws Exception { return !gefBot.activeEditor().isDirty(); } public String getFailureMessage() { return "The editor is still dirty after the save."; } }); return gefBot; } private void checkTextInsideHtml(final String textToCheck) { bot.button(Messages.Edit).click(); bot.waitUntil(new ICondition() { public boolean test() throws Exception { editorTextContent = bot.styledText().getText(); return editorTextContent.contains(textToCheck); } public void init(SWTBot bot) { } public String getFailureMessage() { return "The generated html is not well-formed. It doesn't contain "+textToCheck+"\nCurrent text:\n"+editorTextContent; } },10000,500); bot.activeEditor().close(); } private SWTBotGefEditor addUsageOfDefaultPageTemplate() { bot.closeAllEditors(); bot.waitUntil(new ICondition() { public boolean test() throws Exception { return bot.editors().isEmpty(); } public void init(SWTBot bot) { } public String getFailureMessage() { return "Some editors has not been closed properly."; } }); SWTBotTestUtil.createNewDiagram(bot); SWTBotGefEditor gefEditor = bot.gefEditor(bot.activeEditor().getTitle()); SWTBotEditor formEditor = SWTBotTestUtil.createFormWhenOnAProcessWithStep(bot, gefEditor, "Step1"); SWTBotGefEditor formGefEditor = bot.gefEditor(formEditor.getTitle()); bot.viewById(SWTBotTestUtil.VIEWS_PROPERTIES_FORM_GENERAL).show(); SWTBotTestUtil.selectTabbedPropertyView(bot, "General"); bot.button(Messages.Restore).click(); /*There is a long-running operation before so need a waituntil*/ bot.waitUntil(Conditions.widgetIsEnabled(bot.button(Messages.Edit)),20000,100); assertTrue("Clear button is not enabled", bot.button(Messages.Clear).isEnabled()); return formGefEditor; } }
package com.ehootu.sys.service; import com.ehootu.sys.entity.ErrorDistanceSettingEntity; import java.util.List; import java.util.Map; /** * 误差距离设置 * * @author zhangyong * @email zhangyong@ehootu.com * @date 2018-03-05 14:40:03 */ public interface ErrorDistanceSettingService { ErrorDistanceSettingEntity queryObject(Integer id); List<ErrorDistanceSettingEntity> queryList(Map<String, Object> map); int queryTotal(Map<String, Object> map); void save(ErrorDistanceSettingEntity errorDistanceSetting); void update(ErrorDistanceSettingEntity errorDistanceSetting); void delete(Integer id); void deleteBatch(Integer[] ids); }
package com.top.demo.modules.service; import com.top.demo.modules.pojo.RoleDO; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 角色表 服务类 * </p> * * @author lth * @since 2019-10-17 */ public interface RoleService extends IService<RoleDO> { }
package co.usa.ciclo3.ciclo3.repository.crud; import co.usa.ciclo3.ciclo3.model.Reservation; import org.springframework.data.repository.CrudRepository; public interface ReservationCrudRepository extends CrudRepository<Reservation, Integer> { }
package com.njupt.ws_cxf_spring.ws.bean; public class Data { int dataID; String value; String type; String devKey; String saveTime; public Data() { super(); // TODO Auto-generated constructor stub } public Data(int dataID, String value, String type, String devKey, String saveTime) { super(); this.dataID = dataID; this.value = value; this.type = type; this.devKey = devKey; this.saveTime = saveTime; } public int getDataID() { return dataID; } public void setDataID(int dataID) { this.dataID = dataID; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDevKey() { return devKey; } public void setDevKey(String devKey) { this.devKey = devKey; } public String getSaveTime() { return saveTime; } public void setSaveTime(String saveTime) { this.saveTime = saveTime; } @Override public String toString() { return "Data [dataID=" + dataID + ", value=" + value + ", type=" + type + ", devKey=" + devKey + ", saveTime=" + saveTime + "]"; } }
package backjoon.sortion; import java.io.*; public class Backjoon2751 { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); private static int[] arr; private static int[] sortedArr; static int N; public static void main(String[] args) throws IOException { N = Integer.parseInt(br.readLine()); arr = new int[N]; sortedArr = new int[N]; for(int i = 0; i < N; i++){ arr[i] = Integer.parseInt(br.readLine()); } mergeSort(0, N - 1); for(int i = 0 ; i < N; i++){ bw.write(arr[i] + "\n"); } bw.close(); br.close(); } public static void mergeSort(int low, int high){ if(low < high){ int mid = low + (high - low) / 2; mergeSort(low, mid); mergeSort(mid + 1, high); merge(low, high); } } public static void merge(int low, int high){ int mid = low + (high - low) / 2; int i = low; int j = mid + 1; int k = low; while(i <= mid && j <= high){ if(arr[i] <= arr[j]){ sortedArr[k++] = arr[i++]; }else{ sortedArr[k++] = arr[j++]; } } if(i <= mid){ while(k <= high){ sortedArr[k++] = arr[i++]; } }else{ while(k <= high){ sortedArr[k++] = arr[j++]; } } k--; while(k >= low){ arr[k] = sortedArr[k]; k--; } } }
package com.example.demo.common.ExceptionHandler; public class CustomException extends RuntimeException { public String message; public Integer code; public CustomException(CustomExceptionEnum customExceptionEnum){ this.message = customExceptionEnum.message; this.code = customExceptionEnum.code; } @Override public String getMessage() { return message; } public Integer getCode() { return code; } }
/* * 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 gui.view; import bl.AppException; import bl.UserInterface; import bl.UserRepository; import bl.EntMngClass; import ejb.Users; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import javax.persistence.NoResultException; import javax.swing.JOptionPane; /** * * @author ARDIT */ public class Login extends javax.swing.JFrame { /** * Creates new form Login */ public Login() { setLayout(new BorderLayout()); setSize(452,605); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int jFramewidth=this.getSize().width; int jFrameheight=this.getSize().height; int locationx=(dim.width-jFramewidth)/2; int locationy=(dim.height-jFrameheight)/2; this.setLocation(locationx,locationy); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); usertxtf = new javax.swing.JTextField(); pass = new javax.swing.JPasswordField(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel3MouseClicked(evt); } }); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 400, 120, 30)); usertxtf.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N usertxtf.setBorder(null); jPanel1.add(usertxtf, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 235, 225, 30)); pass.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N pass.setBorder(null); pass.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { passKeyPressed(evt); } }); jPanel1.add(pass, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 335, 225, 30)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Photos/loginmda.png"))); // NOI18N jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 452, 605)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void passKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passKeyPressed if(evt.getKeyCode()==KeyEvent.VK_ENTER){ loginMethod(); } }//GEN-LAST:event_passKeyPressed private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel3MouseClicked loginMethod(); }//GEN-LAST:event_jLabel3MouseClicked public void loginMethod(){ String username=usertxtf.getText(); String password=pass.getText(); Users user; try{ EntMngClass emc=new EntMngClass(username.trim(),password.trim()); UserInterface userir=new UserRepository(emc.getEntityManager()); String salt = userir.findSalt(username); user=userir.findByUsernamePassword(username,userir.kripto(salt+password)); test t=new test(user,emc.getEntityManager()); if(user.getPozita().equals("Administrator")) t.setPriority(true); else t.setPriority(false); t.setVisible(true); dispose(); }catch (NoResultException nre){ JOptionPane.showMessageDialog(null,"Gabimm "); usertxtf.setText(""); pass.setText(""); } catch(AppException ae){ JOptionPane.showMessageDialog(null, ae.getMessage()); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Login().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPasswordField pass; private javax.swing.JTextField usertxtf; // End of variables declaration//GEN-END:variables private void close() { WindowEvent winClosing=new WindowEvent (this, WindowEvent.WINDOW_CLOSING); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosing); } }
/* * Copyright © 2018 tesshu.com (webmaster@tesshu.com) * * 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.tesshu.sonic.player.view.mediator; import com.tesshu.sonic.player.plugin.view.ViewSupplier; import com.tesshu.sonic.player.view.ICustomContainer; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.checkerframework.checker.nullness.qual.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.github.classgraph.ClassGraph; import io.github.classgraph.ScanResult; public class ViewMediator { private final Logger LOG = LoggerFactory.getLogger(ViewMediator.class); private static ViewMediator instance; private final List<ViewSupplier> suppliers; { suppliers = new ArrayList<>(); try (//@formatter:off ScanResult scanResult = new ClassGraph() .enableAllInfo() .whitelistPackages("com.tesshu.sonic.player.plugin.view") .scan()) {//@formatter:on var classInfos = scanResult .getClassesImplementing("com.tesshu.sonic.player.plugin.view.ViewSupplier"); var infos = classInfos.loadClasses(); for (var supplier : infos) { try { var constructor = supplier.getDeclaredConstructor(); constructor.setAccessible(true); ViewSupplier instance = (ViewSupplier) constructor.newInstance(); suppliers.add(instance); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { LOG.error("Error getting instances of ViewSupplier", e); } } } if (0 == suppliers.size()) { LOG.info("ViewSupplier not found at all."); } else { LOG.info("ViewSupplier found({}). ->", suppliers.size()); for (var supplier : suppliers) { LOG.info(supplier.getName()); } } } public Optional<ICustomContainer> createContainer(@NonNull String supplierName) { if (0 == suppliers.stream() .filter(supplier -> supplier.getName().equals(supplierName)).count()) { LOG.info("ViewSupplier({}) specified can not be found.", supplierName); } return suppliers.stream() .filter(s -> s.getName().equals(supplierName)).findFirst() .stream() .map(s -> s.createContainer()).findFirst(); } public static ViewMediator of() { if (null == instance) { instance = new ViewMediator(); } return instance; } }