hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
809f0ba9e9401f5e313bf6bd9bf5396328043e0a
601
package org.innovateuk.ifs.invite.resource; import org.innovateuk.ifs.commons.resource.PageResource; import java.util.List; /** * Resource encapsulating a pageable list of {@link AssessorCreatedInviteResource}s. */ public class AssessorCreatedInvitePageResource extends PageResource<AssessorCreatedInviteResource> { public AssessorCreatedInvitePageResource() { } public AssessorCreatedInvitePageResource(long totalElements, int totalPages, List<AssessorCreatedInviteResource> content, int number, int size) { super(totalElements, totalPages, content, number, size); } }
31.631579
149
0.790349
3dbb11bddd0f754883b2b4be4a09a5b63f6592fa
1,918
/* * Copyright 2009 Denys Pavlov, Igor Azarnyi * * 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.yes.cart.domain.entity; /** * Attribute group interface. * <p/> * User: Igor Azarny [email protected] * Date: 07-May-2011 * Time: 11:12:54 */ public interface AttributeGroup extends Auditable, Codable { /** * Get primary key. * * @return primary key. */ long getAttributegroupId(); /** * Set primary key. * * @param attributegroupId pk value */ void setAttributegroupId(long attributegroupId); /** * Get attribute group code. * * @return attribute group code. */ @Override String getCode(); /** * Set code value * * @param code code value. */ @Override void setCode(String code); /** * Get attribute group name. * * @return name */ String getName(); /** * Set name. * * @param name name value. */ void setName(String name); /** * Get attribute group description. * * @return description */ String getDescription(); /** * Set description. * * @param description description value. */ void setDescription(String description); }
21.076923
79
0.576121
12884f37ab06971b44fbe1ed27766a6730ac23f8
2,734
package net.minecraft.src; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; public class McRegionChunkLoader implements IChunkLoader { private final File worldFolder; public McRegionChunkLoader(File var1) { this.worldFolder = var1; } public Chunk loadChunk(World var1, int var2, int var3) throws IOException { DataInputStream var4 = RegionFileCache.func_22124_c(this.worldFolder, var2, var3); if (var4 != null) { NBTTagCompound var5 = CompressedStreamTools.func_774_a(var4); if (!var5.hasKey("Level")) { System.out.println("Chunk file at " + var2 + "," + var3 + " is missing level data, skipping"); return null; } else if (!var5.getCompoundTag("Level").hasKey("Blocks")) { System.out.println("Chunk file at " + var2 + "," + var3 + " is missing block data, skipping"); return null; } else { Chunk var6 = ChunkLoader.loadChunkIntoWorldFromCompound(var1, var5.getCompoundTag("Level")); if (!var6.isAtLocation(var2, var3)) { System.out.println("Chunk file at " + var2 + "," + var3 + " is in the wrong location; relocating. (Expected " + var2 + ", " + var3 + ", got " + var6.xPosition + ", " + var6.zPosition + ")"); var5.setInteger("xPos", var2); var5.setInteger("zPos", var3); var6 = ChunkLoader.loadChunkIntoWorldFromCompound(var1, var5.getCompoundTag("Level")); } var6.func_25083_h(); return var6; } } else { return null; } } public void saveChunk(World var1, Chunk var2) throws IOException { var1.checkSessionLock(); try { DataOutputStream var3 = RegionFileCache.func_22120_d(this.worldFolder, var2.xPosition, var2.zPosition); NBTTagCompound var4 = new NBTTagCompound(); NBTTagCompound var5 = new NBTTagCompound(); var4.setTag("Level", var5); ChunkLoader.storeChunkInCompound(var2, var1, var5); CompressedStreamTools.func_771_a(var4, var3); var3.close(); WorldInfo var6 = var1.getWorldInfo(); var6.setSizeOnDisk(var6.getSizeOnDisk() + (long)RegionFileCache.func_22121_b(this.worldFolder, var2.xPosition, var2.zPosition)); } catch (Exception var7) { var7.printStackTrace(); } } public void saveExtraChunkData(World var1, Chunk var2) throws IOException { } public void func_661_a() { } public void saveExtraData() { } }
39.057143
210
0.598025
d8c178252031ff6936c0f840595a70555ff6e5e5
785
package ua.com.nc.nctrainingproject.persistance.dao.postgre.queries; public class AdminRightsQuery { public static final String TABLE_NAME = "adminrights"; public static final String ADMIN_ID = "admin_id"; public static final String RIGHT_ID = "right_id"; public static final String GET_ADMIN_ID_BY_RIGHT_ID = "SELECT " + ADMIN_ID + " FROM " + TABLE_NAME + " WHERE " + RIGHT_ID + " =(?);"; public static final String GET_RIGHT_ID_BY_ADMIN_ID = "SELECT " + RIGHT_ID + " FROM " + TABLE_NAME + " WHERE " + ADMIN_ID + " =(?);"; public static final String DELETE_BY_ADMIN_ID = "DELETE FROM " + TABLE_NAME + " WHERE " + ADMIN_ID + " =(?);"; public static final String CREATE_PAIR = "INSERT INTO " + TABLE_NAME + " (" + ADMIN_ID + "," + RIGHT_ID + ")" + " VALUES(?,?)"; }
43.611111
111
0.680255
ec0458a7bf89ca25eb6bbc78cb3d3e09a0c2fbb2
151
package edu.slu.parks.healthwatch.history; /** * Created by okori on 14-Nov-16. */ public enum ViewType { DAY, WEEK, MONTH, YEAR }
11.615385
42
0.615894
ae10a778c1a4fad32ca9cb6646e7afa1e898cd4a
1,737
package com.logicaldoc.enterprise.webservice.soap.endpoint; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; import com.logicaldoc.ws.ObjectFactory; import com.logicaldoc.ws.WSCriterion; import com.logicaldoc.ws.WSDocument; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.2 * */ @WebService(name = "EnterpriseSearch", targetNamespace = "http://ws.logicaldoc.com") @XmlSeeAlso({ ObjectFactory.class }) public interface EnterpriseSearch { /** * * @param criteria * @param maxResults * @param templateId * @param sid * @return * returns java.util.List<com.logicaldoc.ws.WSDocument> * @throws Exception */ @WebMethod @WebResult(name = "hit", targetNamespace = "") @RequestWrapper(localName = "findByParameters", targetNamespace = "http://ws.logicaldoc.com", className = "com.logicaldoc.ws.FindByParameters") @ResponseWrapper(localName = "findByParametersResponse", targetNamespace = "http://ws.logicaldoc.com", className = "com.logicaldoc.ws.FindByParametersResponse") public List<WSDocument> findByParameters( @WebParam(name = "sid", targetNamespace = "") String sid, @WebParam(name = "templateId", targetNamespace = "") Long templateId, @WebParam(name = "criteria", targetNamespace = "") List<WSCriterion> criteria, @WebParam(name = "maxResults", targetNamespace = "") int maxResults) throws Exception ; }
30.473684
164
0.694876
29829782a51cef5e3cf35491fb1726bf8743c683
840
package com.joe.nio.buffer; import java.nio.ByteBuffer; /** * ByteBuffer 支持类型化的 put 和 get * put 放入的是什么数据类型,get 就应该使用相应的数据类型来取出,否则可能有 BufferUnderflowException 异常 * * @author ckh * @create 10/22/20 2:53 PM */ public class NIOByteBufferPutGet { public static void main(String[] args) { ByteBuffer byteBuffer = ByteBuffer.allocate(64); byteBuffer.putInt(100); byteBuffer.putLong(200); byteBuffer.putChar('嵩'); byteBuffer.putShort((short) 4); byteBuffer.flip(); System.out.println(byteBuffer.getInt()); System.out.println(byteBuffer.getLong()); System.out.println(byteBuffer.getChar()); System.out.println(byteBuffer.getShort()); // System.out.println(byteBuffer.getLong()); // 如果没有按照put 的类型获取时, 可能抛出 BufferUnderflowException } }
26.25
71
0.665476
56a49b68612484d0c5e251607d8ebc65e34c46d6
853
package pubsub.subscriber; import pubsub.service.PubSubService; /** * SubscriberImpl class extends Subscriber and implements the abstract methods mentioned above. * @author luiz * */ public class SubscriberImpl extends Subscriber { //Add subscriber with PubSubService for a topic @Override public void addSubscriber(String topic, PubSubService pubSubService) { pubSubService.addSubscriber(topic, this); } //Unsubscribe subscriber with PubSubService for a topic @Override public void unSubscribe(String topic, PubSubService pubSubService) { pubSubService.removeSubscriber(topic, this); } //Request specifically for messages related to topic from PubSubService @Override public void getMessagesForSubscriberOfTopic(String topic, PubSubService pubSubService) { pubSubService.getMessagesForSubscriberOfTopic(topic, this); } }
25.088235
95
0.798359
99b1c431002e8b92429f7de93ecc510b6922611c
2,027
package eu.fox7.rexp.isc.cnfa.core; import eu.fox7.rexp.data.Symbol; import eu.fox7.rexp.isc.cnfa.guard.Guard; import eu.fox7.rexp.isc.cnfa.update.Update; import eu.fox7.rexp.tree.nfa.lw.NfaState; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; public class CnfaTransitionMap implements Serializable { private static final long serialVersionUID = 1L; protected Map<NfaState, Set<CnfaTransition>> srcMap; protected Map<NfaState, Set<CnfaTransition>> tgtMap; protected Map<Symbol, Set<CnfaTransition>> symbolMap; public CnfaTransitionMap() { srcMap = new LinkedHashMap<NfaState, Set<CnfaTransition>>(); tgtMap = new LinkedHashMap<NfaState, Set<CnfaTransition>>(); symbolMap = new LinkedHashMap<Symbol, Set<CnfaTransition>>(); } public void addTransition(NfaState source, Symbol symbol, NfaState target, Guard guard, Update update) { CnfaTransition transition = new CnfaTransition(source, symbol, target, guard, update); updateMap(srcMap, source, transition); updateMap(tgtMap, target, transition); updateMap(symbolMap, symbol, transition); } private <K, V> void updateMap(Map<K, Set<V>> map, K key, V value) { if (map.containsKey(key)) { Set<V> set = map.get(key); set.add(value); } else { Set<V> set = new LinkedHashSet<V>(); set.add(value); map.put(key, set); } } public Set<CnfaTransition> entrySet() { Set<CnfaTransition> set = new LinkedHashSet<CnfaTransition>(); for (Set<CnfaTransition> s : srcMap.values()) { set.addAll(s); } return set; } public Set<CnfaTransition> findBySource(NfaState source) { return srcMap.get(source); } public Set<CnfaTransition> findByTarget(NfaState target) { return tgtMap.get(target); } public Set<CnfaTransition> findBySymbol(Symbol symbol) { Set<CnfaTransition> s = symbolMap.get(symbol); return s != null ? s : new LinkedHashSet<CnfaTransition>(); } }
30.712121
106
0.710903
4eef55adbf873ae6ab9fc4bd1036521460a16443
12,344
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.springframework.security.config.annotation.web.configurers; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.access.vote.AuthenticatedVoter; import org.springframework.security.access.vote.RoleVoter; import org.springframework.security.config.annotation.ObjectPostProcessor; import org.springframework.security.config.annotation.web.HttpSecurityBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** * Adds URL based authorization using * {@link DefaultFilterInvocationSecurityMetadataSource}. At least one * {@link org.springframework.web.bind.annotation.RequestMapping} needs to be * mapped to {@link ConfigAttribute}'s for this * {@link SecurityContextConfigurer} to have meaning. <h2>Security Filters</h2> * * <p> * Usage includes applying the {@link UrlAuthorizationConfigurer} and then * modifying the StandardInterceptUrlRegistry. For example: * </p> * * <pre> * protected void configure(HttpSecurity http) throws Exception { * http * .apply(new UrlAuthorizationConfigurer<HttpSecurity>()).getRegistry() * .antMatchers("/users**","/sessions/**").hasRole("USER") * .antMatchers("/signup").hasRole("ANONYMOUS") * .anyRequest().hasRole("USER"); * } * </pre> * * The following Filters are populated * * <ul> * <li> * {@link org.springframework.security.web.access.intercept.FilterSecurityInterceptor} * </li> * </ul> * * <h2>Shared Objects Created</h2> * * The following shared objects are populated to allow other * {@link org.springframework.security.config.annotation.SecurityConfigurer}'s * to customize: * <ul> * <li> * {@link org.springframework.security.web.access.intercept.FilterSecurityInterceptor} * </li> * </ul> * * <h2>Shared Objects Used</h2> * * The following shared objects are used: * * <ul> * <li> * {@link org.springframework.security.config.annotation.web.builders.HttpSecurity#getAuthenticationManager()} * </li> * </ul> * * @param <H> * the type of {@link HttpSecurityBuilder} that is being configured * @param <C> * the type of object that is being chained * * @author Rob Winch * @since 3.2 * @see ExpressionUrlAuthorizationConfigurer */ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>> extends AbstractInterceptUrlConfigurer<UrlAuthorizationConfigurer<H>,H> { private final StandardInterceptUrlRegistry REGISTRY = new StandardInterceptUrlRegistry(); /** * The StandardInterceptUrlRegistry is what users will interact with after * applying the {@link UrlAuthorizationConfigurer}. * * @return */ public StandardInterceptUrlRegistry getRegistry() { return REGISTRY; } /** * Adds an {@link ObjectPostProcessor} for this class. * * @param objectPostProcessor * @return the {@link UrlAuthorizationConfigurer} for further customizations */ public UrlAuthorizationConfigurer<H> withObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) { addObjectPostProcessor(objectPostProcessor); return this; } public class StandardInterceptUrlRegistry extends ExpressionUrlAuthorizationConfigurer<H>.AbstractInterceptUrlRegistry<StandardInterceptUrlRegistry,AuthorizedUrl> { @Override protected final AuthorizedUrl chainRequestMatchersInternal(List<RequestMatcher> requestMatchers) { return new AuthorizedUrl(requestMatchers); } /** * Adds an {@link ObjectPostProcessor} for this class. * * @param objectPostProcessor * @return the {@link ExpressionUrlAuthorizationConfigurer} for further customizations */ public StandardInterceptUrlRegistry withObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) { addObjectPostProcessor(objectPostProcessor); return this; } public H and() { return UrlAuthorizationConfigurer.this.and(); } } /** * Creates the default {@link AccessDecisionVoter} instances used if an * {@link AccessDecisionManager} was not specified using * {@link #accessDecisionManager(AccessDecisionManager)}. * * @param http the builder to use */ @Override @SuppressWarnings("rawtypes") final List<AccessDecisionVoter> getDecisionVoters(H http) { List<AccessDecisionVoter> decisionVoters = new ArrayList<AccessDecisionVoter>(); decisionVoters.add(new RoleVoter()); decisionVoters.add(new AuthenticatedVoter()); return decisionVoters; } /** * Creates the {@link FilterInvocationSecurityMetadataSource} to use. The * implementation is a {@link DefaultFilterInvocationSecurityMetadataSource}. * * @param http the builder to use */ @Override FilterInvocationSecurityMetadataSource createMetadataSource(H http) { return new DefaultFilterInvocationSecurityMetadataSource(REGISTRY.createRequestMap()); } /** * Adds a mapping of the {@link RequestMatcher} instances to the {@link ConfigAttribute} instances. * @param requestMatchers the {@link RequestMatcher} instances that should map to the provided {@link ConfigAttribute} instances * @param configAttributes the {@link ConfigAttribute} instances that should be mapped by the {@link RequestMatcher} instances * @return the {@link UrlAuthorizationConfigurer} for further customizations */ private StandardInterceptUrlRegistry addMapping(Iterable<? extends RequestMatcher> requestMatchers, Collection<ConfigAttribute> configAttributes) { for(RequestMatcher requestMatcher : requestMatchers) { REGISTRY.addMapping(new AbstractConfigAttributeRequestMatcherRegistry.UrlMapping(requestMatcher, configAttributes)); } return REGISTRY; } /** * Creates a String for specifying a user requires a role. * * @param role * the role that should be required which is prepended with ROLE_ * automatically (i.e. USER, ADMIN, etc). It should not start * with ROLE_ * @return the {@link ConfigAttribute} expressed as a String */ private static String hasRole(String role) { Assert.isTrue( !role.startsWith("ROLE_"), role + " should not start with ROLE_ since ROLE_ is automatically prepended when using hasRole. Consider using hasAuthority or access instead."); return "ROLE_" + role; } /** * Creates a String for specifying that a user requires one of many roles. * * @param roles * the roles that the user should have at least one of (i.e. * ADMIN, USER, etc). Each role should not start with ROLE_ since * it is automatically prepended already. * @return the {@link ConfigAttribute} expressed as a String */ private static String[] hasAnyRole(String... roles) { for(int i=0;i<roles.length;i++) { roles[i] = "ROLE_" + roles[i]; } return roles; } /** * Creates a String for specifying that a user requires one of many authorities * @param authorities the authorities that the user should have at least one of (i.e. ROLE_USER, ROLE_ADMIN, etc). * @return the {@link ConfigAttribute} expressed as a String. */ private static String[] hasAnyAuthority(String... authorities) { return authorities; } /** * Maps the specified {@link RequestMatcher} instances to {@link ConfigAttribute} instances. * * @author Rob Winch * @since 3.2 */ public final class AuthorizedUrl { private final List<RequestMatcher> requestMatchers; /** * Creates a new instance * @param requestMatchers the {@link RequestMatcher} instances to map to some {@link ConfigAttribute} instances. * @see UrlAuthorizationConfigurer#chainRequestMatchers(List) */ private AuthorizedUrl(List<RequestMatcher> requestMatchers) { Assert.notEmpty(requestMatchers, "requestMatchers must contain at least one value"); this.requestMatchers = requestMatchers; } /** * Specifies a user requires a role. * * @param role * the role that should be required which is prepended with ROLE_ * automatically (i.e. USER, ADMIN, etc). It should not start * with ROLE_ * the {@link UrlAuthorizationConfigurer} for further customization */ public StandardInterceptUrlRegistry hasRole(String role) { return access(UrlAuthorizationConfigurer.hasRole(role)); } /** * Specifies that a user requires one of many roles. * * @param roles * the roles that the user should have at least one of (i.e. * ADMIN, USER, etc). Each role should not start with ROLE_ since * it is automatically prepended already. * @return the {@link UrlAuthorizationConfigurer} for further customization */ public StandardInterceptUrlRegistry hasAnyRole(String... roles) { return access(UrlAuthorizationConfigurer.hasAnyRole(roles)); } /** * Specifies a user requires an authority. * * @param authority * the authority that should be required * @return the {@link UrlAuthorizationConfigurer} for further customization */ public StandardInterceptUrlRegistry hasAuthority(String authority) { return access(authority); } /** * Specifies that a user requires one of many authorities * @param authorities the authorities that the user should have at least one of (i.e. ROLE_USER, ROLE_ADMIN, etc). * @return the {@link UrlAuthorizationConfigurer} for further customization */ public StandardInterceptUrlRegistry hasAnyAuthority(String... authorities) { return access(UrlAuthorizationConfigurer.hasAnyAuthority(authorities)); } /** * Specifies that an anonymous user is allowed access * @return the {@link UrlAuthorizationConfigurer} for further customization */ public StandardInterceptUrlRegistry anonymous() { return hasRole("ROLE_ANONYMOUS"); } /** * Specifies that the user must have the specified {@link ConfigAttribute}'s * @param attributes the {@link ConfigAttribute}'s that restrict access to a URL * @return the {@link UrlAuthorizationConfigurer} for further customization */ public StandardInterceptUrlRegistry access(String... attributes) { addMapping(requestMatchers, SecurityConfig.createList(attributes)); return UrlAuthorizationConfigurer.this.REGISTRY; } } }
39.819355
168
0.683571
ed1f84aff9d91bcf9aafb00d99dc5f1e10738134
20,303
/* * Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: ResourcePanel.java,v 1.1.1.1 2001/05/22 08:13:01 jstrachan Exp $ */ package org.dom4j.visdom.util; import org.dom4j.visdom.util.Log; import org.dom4j.visdom.util.SystemExitManager; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.*; import java.net.URL; import java.net.MalformedURLException; import java.util.*; import javax.swing.*; /** * Base class for a panel which implements general resource * finding methods plus specific helper methods for menus and toolBars */ public class ResourcePanel extends JPanel { public ResourcePanel() { super(true); } public ResourcePanel(ResourceBundle resources) { super(true); this.resources = resources; } //------------------------------------------------------------------------- // getters and setters //------------------------------------------------------------------------- public ResourceBundle getResources() { return resources; } public void setResources(ResourceBundle resources) { this.resources = resources; } /** * Fetch the menu item that was created for the given * command. * @param cmd Name of the action. * @returns item created for the given command or null * if one wasn't created. */ protected JMenuItem getMenuItem(String cmd) { return (JMenuItem) menuItems.get(cmd); } /** * get an Action object by the Action.NAME attribute * */ public Action getAction(String cmd) { // install the command table via lazy construction // rather than in the constructor if ( commands == null ) { commands = new Hashtable(); Action[] actions = getActions(); for (int i = 0; i < actions.length; i++) { Action a = actions[i]; commands.put(a.getValue(Action.NAME), a); } } return (Action) commands.get(cmd); } /** * Fetch the list of actions supported by this * editor. It is implemented to return the list * of actions supported by the embedded JTextComponent * augmented with the actions defined locally. */ public Action[] getActions() { return new Action[0]; } /** * Returns the status bar for this component * if one has been created. May return null. * * @return the statusBar for this component; may be null * if one hasn't been created */ public Container getStatusBar() { return statusBar; } //------------------------------------------------------------------------- // public make methods: adorn existing toolBar/menuBars //------------------------------------------------------------------------- /** * adds component specific menu items to the given menuBar * */ public void makeMenuBar(JMenuBar menuBar) { JMenuItem mi; String temp = getResourceString("menubar"); if ( temp != null ) { String[] menuKeys = tokenize(temp); for (int i = 0; i < menuKeys.length; i++) { JMenu m = createMenu(menuKeys[i]); if (m != null) { menuBar.add(m); } } } } /** * adds component specific buttons to the given toolBar * */ public void makeToolBar(JToolBar toolBar) { String temp = getResourceString("toolbar"); if ( temp != null ) { String[] toolKeys = tokenize(temp); for (int i = 0; i < toolKeys.length; i++) { if (toolKeys[i].equals("-")) { toolBar.add(Box.createHorizontalStrut(5)); } else { toolBar.add(createTool(toolKeys[i])); } } toolBar.add(Box.createHorizontalGlue()); } } //------------------------------------------------------------------------- // factory methods //------------------------------------------------------------------------- /** * Create the menuBar for the app. By default this pulls the * definition of the menu from the associated resource file. */ public JMenuBar createMenuBar() { JMenuBar mb = new JMenuBar(); mb.setName( "MenuBar" ); makeMenuBar(mb); return mb; } /** * Create the toolBar. By default this reads the * resource file for the definition of the toolBar. */ public Component createToolBar() { JToolBar toolBar = new JToolBar(); toolBar.setName( "ToolBar" ); makeToolBar(toolBar); return toolBar; } /** * Create a status bar */ public Component createStatusBar() { // need to do something reasonable here statusBar = new StatusBar(); statusBar.setName( "StatusBar" ); return statusBar; } /** * To shutdown when run as an application. This is a * fairly lame implementation. A more self-respecting * implementation would at least check to see if a save * was needed. */ public static WindowAdapter createApplicationCloser() { return new WindowAdapter() { public void windowClosing(WindowEvent e) { SystemExitManager.exit(0); } }; } //------------------------------------------------------------------------- // menu implmentation methods //------------------------------------------------------------------------- /** * Create a menu for the app. By default this pulls the * definition of the menu from the associated resource file. */ protected JMenu createMenu(String key) { /* if ( key.equals( GoMenuFactory.GO_MENU_KEY ) ) { GoMenuFactory factory = new GoMenuFactory( getResources() ); return factory.createMenu(); } */ String label = getResourceString(key + LABEL_SUFFIX); JMenu menu = new JMenu( label ); makeMenu(menu, key); return menu; } protected void makeMenu(JMenu menu, String key) { menu.setName( key ); String temp = getResourceString(key); if ( temp != null ) { String[] itemKeys = tokenize(temp); for (int i = 0; i < itemKeys.length; i++) { if (itemKeys[i].equals("-")) { menu.addSeparator(); } else { JMenuItem mi = createMenuItem(itemKeys[i]); menu.add(mi); } } } } /** * This is the hook through which all menu items are * created. It registers the result with the menuitem * hashtable so that it can be fetched with getMenuItem(). * @see #getMenuItem */ protected JMenuItem createMenuItem(String cmd) { String label = getLabelString(cmd ); final JMenuItem mi = new JMenuItem( label ); mi.setName( cmd ); Icon icon = getResourceIcon(cmd); //URL url = getResource(cmd + IMAGE_SUFFIX); //if (url != null) if ( icon != null ) { mi.setHorizontalTextPosition(JButton.RIGHT); mi.setIcon(icon); //mi.setIcon(new ImageIcon(url)); } String astr = getResourceString(cmd + ACTION_SUFFIX); if (astr == null) { astr = cmd; } mi.setActionCommand(astr); Action a = getAction(astr); if (a != null) { mi.addActionListener(a); // #### swing should do this but I'll add it anyway if ( ! a.isEnabled() ) { mi.setEnabled(false); } a.addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { String name = evt.getPropertyName(); Object value = evt.getNewValue(); if ( name.equals( ACTION_ENABLED ) && value instanceof Boolean ) { mi.setEnabled( ((Boolean)value).booleanValue() ); } } } ); } else { mi.setEnabled(false); } menuItems.put(cmd, mi); return mi; } // #### should be protected public JMenuItem createActionMenuItem(Action action) { String cmd = (String) action.getValue(Action.NAME); final JMenuItem mi = new JMenuItem( getLabelString(cmd )); mi.setName( cmd ); Icon icon = getResourceIcon(cmd); //URL url = getResource(cmd + IMAGE_SUFFIX); //if (url != null) if ( icon != null ) { mi.setHorizontalTextPosition(JButton.RIGHT); mi.setIcon(icon); //mi.setIcon(new ImageIcon(url)); } String astr = getResourceString(cmd + ACTION_SUFFIX); if (astr == null) { astr = cmd; } mi.setActionCommand(astr); mi.addActionListener(action); // #### swing should do this but I'll add it anyway if ( ! action.isEnabled() ) { mi.setEnabled(false); } action.addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { String name = evt.getPropertyName(); Object value = evt.getNewValue(); if ( name.equals( ACTION_ENABLED ) && value instanceof Boolean ) { mi.setEnabled( ((Boolean)value).booleanValue() ); } } } ); menuItems.put(cmd, mi); return mi; } //------------------------------------------------------------------------- // toolBar implmentation methods //------------------------------------------------------------------------- /** * Hook through which every toolBar item is created. */ protected Component createTool(String key) { return createToolBarButton(key); } /** * Create a button to go inside of the toolBar. By default this * will load an image resource. The image filename is relative to * the classpath (including the '.' directory if its a part of the * classpath), and may either be in a JAR file or a separate file. * * @param key The key in the resource file to serve as the basis * of lookups. */ protected JButton createToolBarButton(String key) { final JButton b = new JButton(getResourceIcon(key)); b.setName( key ); /* //URL url = getResource(key + IMAGE_SUFFIX); //JButton b = new JButton(new ImageIcon(url)) { public float getAlignmentY() { return 0.5f; } }; */ b.setRequestFocusEnabled(false); b.setMargin(new Insets(1,1,1,1)); String astr = getResourceString(key + ACTION_SUFFIX); if (astr == null) { astr = key; } Action a = getAction(astr); if (a != null) { b.setActionCommand(astr); b.addActionListener(a); // #### swing should do this but I'll add it anyway if ( ! a.isEnabled() ) { b.setEnabled(false); } a.addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { String name = evt.getPropertyName(); Object value = evt.getNewValue(); if ( name.equals( ACTION_ENABLED ) && value instanceof Boolean ) { b.setEnabled( ((Boolean)value).booleanValue() ); } } } ); } else { b.setEnabled(false); } String tip = getResourceString(key + TOOLTIP_SUFFIX); if (tip != null) { b.setToolTipText(tip); } return b; } //------------------------------------------------------------------------- // Resource fetching methods //------------------------------------------------------------------------- protected String getResourceString(String nm) { String str; try { str = getResources().getString(nm); } catch (MissingResourceException mre) { str = null; } catch (NullPointerException e) { str = null; } return str; } protected String getLabelString(String cmd) { String answer = getResourceString(cmd + LABEL_SUFFIX); if ( answer == null ) return cmd; return answer; } protected Icon getResourceIcon(String key) { String s = getResourceString(key + IMAGE_SUFFIX); if ( s != null ) { String name = getResourceString(key + IMAGE_SUFFIX); URL url = ClassLoader.getSystemResource( name ); if ( url != null ) { return new ImageIcon(url); } else { Log.info( "Could not load system resource: " + name ); } /* try { String name = getResourceString(key + IMAGE_SUFFIX); URL url = ClassLoader.getSystemResource( name ); //URL url = new URL(name); if ( url != null ) { return new ImageIcon(url); } catch (MalformedURLException e) { Log.exception(e); } //return new ImageIcon(getResourceString(key + IMAGE_SUFFIX)); */ } return null; } protected URL getResource(String key) { String name = getResourceString(key); if (name != null) { URL url = this.getClass().getResource(name); System.out.println( "Resource for key: " + key + " is name: " + name + " and URL: " + url ); return url; } return null; } /** * Take the given string and chop it up into a series * of strings on whitespace boundries. This is useful * for trying to get an array of strings out of the * resource file. */ protected String[] tokenize(String input) { Vector v = new Vector(); StringTokenizer t = new StringTokenizer(input); String cmd[]; while (t.hasMoreTokens()) v.addElement(t.nextToken()); cmd = new String[v.size()]; for (int i = 0; i < cmd.length; i++) cmd[i] = (String) v.elementAt(i); return cmd; } //------------------------------------------------------------------------- // StatusBar //------------------------------------------------------------------------- /** * #### FIXME - I'm not very useful yet */ class StatusBar extends Container { public StatusBar() { super(); setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); } public void paint(Graphics g) { super.paint(g); } } //------------------------------------------------------------------------- // Attributes //------------------------------------------------------------------------- private Hashtable menuItems = new Hashtable(); private ResourceBundle resources; private Hashtable commands; private JMenuBar menuBar; private JToolBar toolBar; private Container statusBar; /** * Suffix applied to the key used in resource file * lookups for an image. */ public static final String IMAGE_SUFFIX = ".image"; /** * Suffix applied to the key used in resource file * lookups for a label. */ public static final String LABEL_SUFFIX = ".label"; /** * Suffix applied to the key used in resource file * lookups for an action. */ public static final String ACTION_SUFFIX = ".action"; /** * Suffix applied to the key used in resource file * lookups for tooltip text. */ public static final String TOOLTIP_SUFFIX = ".tooltip"; // #### should be moved into Swing public static final String ACTION_ENABLED = "enabled"; } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided * that the following conditions are met: * * 1. Redistributions of source code must retain copyright * statements and notices. Redistributions must also contain a * copy of this document. * * 2. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote * products derived from this Software without prior written * permission of MetaStuff, Ltd. For written permission, * please contact [email protected]. * * 4. Products derived from this Software may not be called "DOM4J" * nor may "DOM4J" appear in their names without prior written * permission of MetaStuff, Ltd. DOM4J is a registered * trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project * (http://dom4j.org/). * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: ResourcePanel.java,v 1.1.1.1 2001/05/22 08:13:01 jstrachan Exp $ */
29.901325
80
0.490174
4beacf8ee3fc80c0d81b3baaaee6cdbb21197dc7
8,597
/** * Created by Y1475945. */ import java.util.ArrayList; public abstract class Lifeform extends Env_Entity { private static ArrayList<Env_Entity> worldInhabitants = new ArrayList<>(); protected static ArrayList<Lifeform> deadBirds = new ArrayList<>(); private ArrayList<Env_Entity> myNeighbours = new ArrayList<>(); private CartesianVector velocity; private double repulsion_distance; private double view_distance; private double view_angle; private double speed; private static boolean neighbourLines = false; private static final boolean viewArc = false; /************************************************************************************ * Instantiation Functions ************************************************************************************/ public Lifeform(Canvas canvas) { super(canvas); this.velocity = new CartesianVector((Math.random() * 2) -1, (Math.random() * 2) - 1).normalise(1); this.view_angle = Math.toRadians(360); } public Lifeform(Canvas canvas, CartesianDouble pos) { super(canvas, pos); this.velocity = new CartesianVector((Math.random() * 2) -1, (Math.random() * 2) - 1).normalise(1); this.view_angle = Math.toRadians(360); } /************************************************************************************ * Geometric Calculation Functions ************************************************************************************/ /** * Finds all entities that are in sight and adds them to the internal list of neighbours. */ protected void findNeighbours() { this.myNeighbours.clear(); if (worldInhabitants.size() > 0) { for (Env_Entity entity : worldInhabitants) { if (isInSight(entity) && entity != this) { this.myNeighbours.add(entity); } } } } /** * Determines whether the given entity is within sight of the object. * @param entity Any entity within the environment. * @return boolean */ public boolean isInSight(Env_Entity entity) { boolean inFront = this.isInFront(entity); boolean closeEnough = this.distanceTo(entity) <= this.getView_Distance(); inFront = true; return (inFront && closeEnough); } public boolean isInFront(Env_Entity entity) { CartesianVector vecBetween = this.getCurrentPosition().vecTo(entity.getCurrentPosition()); double theta = this.getVelocity().angleBetween(vecBetween); double lowerBearing = this.getMyBearing() - this.getView_angle()/2; double upperBearing = this.getMyBearing() + this.getView_angle()/2; if(lowerBearing < 0) { lowerBearing += Math.toRadians(360); } if(upperBearing > Math.toRadians(360)) { upperBearing -= Math.toRadians(360); } return (theta >= lowerBearing) || (theta <= upperBearing); } public boolean isTooClose(Env_Entity entity) { return this.distanceTo(entity) <= this.getRepulsion_distance(); } /** * Updates the position co-ordinates of the object according to its velocity in the given timeframe. * @param timePassed Time passed in milliseconds. */ public void updatePos(double timePassed) { CartesianDouble nextPos; double localVelMag = this.getVelocity().magnitude(); double localBearing = Math.toDegrees(this.getMyBearing()); nextPos = this.calculateEndPoint(this.getCurrentPosition(), (localVelMag * (timePassed / 1000)), localBearing); double nextX = nextPos.getX(); double nextY = nextPos.getY(); int width = this.getEnvironment().getWidth(); int height = this.getEnvironment().getHeight(); if(nextX >= width) { nextX -= width; } if(nextX <= 0) { nextX += width; } if(nextY >= height) { nextY -= height; } if (nextY <= 0) { nextY += height; } this.setPosition(new CartesianDouble(nextX, nextY)); } protected void detectFatalCollision(Env_Entity entity) { if(entity instanceof Terrain && this.distanceTo(entity) <= entity.getSize()) { deadBirds.add(this); } } protected void draw() { double localBearing = Math.toDegrees(this.getMyBearing()); CartesianDouble localPosition = this.getCurrentPosition(), nextPosition; // array holding angles and distances to draw a turtle // Lower section credited to Chris Harte from Java Lab 3 double[][] polarArray = new double[][] { { 150.0, 120.0, 120.0 }, {this.getSize(), this.getSize(),this.getSize()} }; for(int i=0; i<3 ; i++) { // update local bearing localBearing += polarArray[0][i]; // calculate new position given local bearing and distance nextPosition = this.calculateEndPoint(localPosition, polarArray[1][i], (int)Math.round(localBearing)); // draw a line between local position and new position this.getEnvironment().drawLineBetweenPoints(localPosition, nextPosition, this.getColour()); // update local position reference to point at new position localPosition = nextPosition; } if(viewArc) { this.getEnvironment().drawArc (this.getCurrentPosition(), this.getView_Distance(), -Math.toDegrees(this.getMyBearing() + (this.view_angle / 2.0)), Math.toDegrees(this.getView_angle()), "Red" ); // this.getEnvironment().drawCircle(this.getCurrentPosition(), this.getView_Distance(), this.getColour()); } if(neighbourLines) { for (Env_Entity thing : this.getMyNeighbours()) { if(this.distanceTo(thing) <= this.getView_Distance()) { this.getEnvironment().drawLineBetweenPoints(localPosition, thing.getCurrentPosition(), "Orange"); } } } } public static void cleanUpDead() { for(Lifeform lifeform : deadBirds) { worldInhabitants.remove(lifeform); } } /************************************************************************************ * Getter Functions ************************************************************************************/ public double getRepulsion_distance() { return this.repulsion_distance; } public double getView_Distance() { return view_distance; } public double getView_angle() { return this.view_angle; } public CartesianVector getVelocity() { return this.velocity; } public ArrayList<Env_Entity> getMyNeighbours() { return this.myNeighbours; } public double getMyBearing() { return Math.atan2(this.getVelocity().getY(),this.getVelocity().getX()); } public double getSpeed() { return speed; } public static ArrayList<Env_Entity> getWorldInhabitants() { return worldInhabitants; } /************************************************************************************ * Setter Functions ************************************************************************************/ protected void setVelocity(CartesianVector newVel) { this.velocity = new CartesianVector(newVel.getX(), newVel.getY()); } public static void setWorldInhabitants(ArrayList<Env_Entity> worldInhabitants) { Lifeform.worldInhabitants = worldInhabitants; } public void setView_distance(double view_distance) { this.view_distance = view_distance; } public void setView_angle(double view_angle) { this.view_angle = view_angle; } public void setRepulsion_distance(double repulsion_distance) { this.repulsion_distance = repulsion_distance; } public void setSpeed(double speed) { this.speed = speed; } public static void setNeighbourLines(Boolean val) { neighbourLines = val; } }
28.279605
119
0.543096
7245e9bfccdba079e286d3d613067369febae1d5
821
package io.nixer.nixerplugin.core.detection.events.elastic; import io.searchbox.client.JestClient; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties({ElasticIndexProperties.class}) @ConditionalOnProperty(prefix = "nixer.events.elastic", name = "enabled", havingValue = "true") public class ElasticLoggingAutoConfiguration { @Bean public ElasticIndexer elasticEventsIndexer(JestClient jestClient, ElasticIndexProperties elasticProps) { return new ElasticIndexer(jestClient, elasticProps.getIndex(), elasticProps.getType()); } }
41.05
108
0.828258
0aaadaad08d61605fbe2a08bd849e062f39709da
3,136
/* * This file is part of the L2JServer project. * * 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.l2jserver.gameserver.engines; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.l2jserver.Config; import org.l2jserver.gameserver.datatables.SkillTable; import org.l2jserver.gameserver.model.Skill; import org.l2jserver.gameserver.model.items.Item; /** * @author mkizub */ public class DocumentEngine { protected static final Logger LOGGER = Logger.getLogger(DocumentEngine.class.getName()); private final List<File> _itemFiles = new ArrayList<>(); private final List<File> _skillFiles = new ArrayList<>(); public static DocumentEngine getInstance() { return SingletonHolder.INSTANCE; } private DocumentEngine() { hashFiles("data/stats/items", _itemFiles); hashFiles("data/stats/skills", _skillFiles); } private void hashFiles(String dirname, List<File> hash) { final File dir = new File(Config.DATAPACK_ROOT, dirname); if (!dir.exists()) { LOGGER.info("Dir " + dir.getAbsolutePath() + " not exists"); return; } final File[] files = dir.listFiles(); for (File f : files) { if (f.getName().endsWith(".xml") && !f.getName().startsWith("custom")) { hash.add(f); } } final File customfile = new File(Config.DATAPACK_ROOT, dirname + "/custom.xml"); if (customfile.exists()) { hash.add(customfile); } } public List<Skill> loadSkills(File file) { if (file == null) { LOGGER.warning("Skill file not found."); return null; } final DocumentSkill doc = new DocumentSkill(file); doc.parse(); return doc.getSkills(); } public void loadAllSkills(Map<Integer, Skill> allSkills) { int count = 0; for (File file : _skillFiles) { final List<Skill> s = loadSkills(file); if (s == null) { continue; } for (Skill skill : s) { allSkills.put(SkillTable.getSkillHashCode(skill), skill); count++; } } LOGGER.info("SkillsEngine: Loaded " + count + " skill templates."); } /** * Return created items * @return List of {@link Item} */ public List<Item> loadItems() { final List<Item> list = new ArrayList<>(); for (File f : _itemFiles) { final DocumentItem document = new DocumentItem(f); document.parse(); list.addAll(document.getItemList()); } return list; } private static class SingletonHolder { protected static final DocumentEngine INSTANCE = new DocumentEngine(); } }
24.888889
89
0.69324
8a925b66664209c34131cbc37ea3d9dc714c564a
3,188
/*Copyright (C) 2018 Roland Hauser, <[email protected]> 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 ch.sourcepond.io.fssync.common.lib; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import java.io.Serializable; import java.util.Collection; import java.util.function.Consumer; import static java.util.Arrays.asList; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ServiceListenerRegistrarTest { private final BundleContext context = mock(BundleContext.class); private final Serializable service = mock(Serializable.class); private final Consumer<Serializable> registration = mock(Consumer.class); private final Runnable unregistration = mock(Runnable.class); private final ServiceReference<Object> reference = mock(ServiceReference.class); private final Collection<ServiceReference<Object>> references = asList(reference); private final ServiceListenerRegistrar registrar = new ServiceListenerRegistrar(); @Before public void setup() throws Exception { when(context.getService(reference)).thenReturn(service); when(context.getServiceReferences(Serializable.class, null)).thenReturn((Collection) references); } @Test public void registerListener() throws Exception { registrar.registerListener(context, registration, unregistration, Serializable.class); final InOrder order = inOrder(context, registration); order.verify(context).addServiceListener(argThat(inv -> ServiceListenerImpl.class.equals(inv.getClass())), eq("(objectClass=java.io.Serializable)")); order.verify(registration).accept(service); } @Test public void invalidSyntaxException() throws Exception { final InvalidSyntaxException expected = new InvalidSyntaxException("", ""); doThrow(expected).when(context).addServiceListener(any(), anyString()); try { registrar.registerListener(context, registration, unregistration, Serializable.class); fail("Exception expected here"); } catch (final IllegalStateException e) { assertSame(expected, e.getCause()); } } }
43.081081
157
0.764743
44399e6c6dd2fe5a699cebbdc21cca83196b887a
863
import java.util.Scanner; public class P6_Combinations_with_Repetition { public static String[] elements; public static String[] kSlots; public static int k; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); elements = scanner.nextLine().split("\\s+"); k = Integer.parseInt(scanner.nextLine()); kSlots = new String[k]; combinations(0, 0); } private static void combinations(int index, int start) { if (index == k){ print(kSlots); }else { for (int i = start; i < elements.length; i++) { kSlots[index] = elements[i]; combinations(index + 1, i); } } } private static void print(String[] elements) { System.out.println(String.join(" ", elements)); } }
26.151515
60
0.563152
92cf5cfbf634d78c9406ae1fcc6c8de71227bfaa
358
import no.ssb.rawdata.api.RawdataClientInitializer; module no.ssb.lds.server { requires no.ssb.lds.core; requires no.ssb.config; requires org.slf4j; requires org.apache.commons.logging; // needed to use the solr search provider requires no.ssb.rawdata.api; requires no.ssb.service.provider.api; uses RawdataClientInitializer; }
27.538462
82
0.740223
84ff6cf6225ddf397eee5cc6698c4078ff332574
4,446
/* Copyright 2020-2021. Huawei Technologies Co., Ltd. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.huawei.hms.rn.ml.imagerelatedservices; import android.app.Activity; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.huawei.hms.mlplugin.productvisionsearch.MLProductVisionSearchCapture; import com.huawei.hms.mlsdk.common.MLFrame; import com.huawei.hms.mlsdk.productvisionsearch.cloud.MLRemoteProductVisionSearchAnalyzer; import com.huawei.hms.rn.ml.HMSBase; import com.huawei.hms.rn.ml.helpers.creators.HMSObjectCreator; import com.huawei.hms.rn.ml.helpers.creators.HMSResultCreator; import static com.huawei.hms.rn.ml.helpers.constants.HMSConstants.PRODUCT_VISION_CONSTANTS; import static com.huawei.hms.rn.ml.helpers.constants.HMSResults.CURRENT_ACTIVITY_NULL; import static com.huawei.hms.rn.ml.helpers.constants.HMSResults.FRAME_NULL; import static com.huawei.hms.rn.ml.helpers.constants.HMSResults.SUCCESS; public class HMSProductVisionSearch extends HMSBase { /** * Initializes module * * @param context app context */ public HMSProductVisionSearch(ReactApplicationContext context) { super(context, HMSProductVisionSearch.class.getSimpleName(), PRODUCT_VISION_CONSTANTS); Fresco.initialize(context); } /** * Asynchronous product search * Resolve : Result Object * * @param isStop Releases resources for analyzer. Recommended to use on latest frame * @param frameConfiguration Frame configuration to obtain frame * @param analyzerSetting Setting for creating analyzer */ @ReactMethod public void asyncAnalyzeFrame(boolean isStop, ReadableMap frameConfiguration, ReadableMap analyzerSetting, final Promise promise) { startMethodExecTimer("asyncAnalyzeFrame"); MLFrame frame = HMSObjectCreator.getInstance().createFrame(frameConfiguration, getContext()); if (frame == null) { handleResult("asyncAnalyzeFrame", FRAME_NULL, promise); return; } MLRemoteProductVisionSearchAnalyzer remoteProductVisionSearchAnalyzer = HMSObjectCreator.getInstance().createProductVisionSearchAnalyzer(analyzerSetting); remoteProductVisionSearchAnalyzer.asyncAnalyseFrame(frame) .addOnSuccessListener(mlProductVisionSearches -> { if (isStop) remoteProductVisionSearchAnalyzer.stop(); handleResult("asyncAnalyzeFrame", HMSResultCreator.getInstance().getProductVisionSearchResult(mlProductVisionSearches), promise); }) .addOnFailureListener(e -> { if (isStop) remoteProductVisionSearchAnalyzer.stop(); handleResult("asyncAnalyzeFrame", e, promise); }); } /** * Start product vision search plugin * Resolve : Result Object * * @param pluginConfiguration plugin configuration */ @ReactMethod public void startProductVisionSearchCapturePlugin(ReadableMap pluginConfiguration, final Promise promise) { startMethodExecTimer("startProductVisionSearchCapturePlugin"); Activity currentActivity = getCurrentActivity(); if (currentActivity == null) { handleResult("startProductVisionSearchCapturePlugin", CURRENT_ACTIVITY_NULL, promise); return; } MLProductVisionSearchCapture capture = HMSObjectCreator.getInstance().createProductVisionSearchCapture(pluginConfiguration, getContext()); capture.startCapture(currentActivity); handleResult("startProductVisionSearchCapturePlugin", SUCCESS, promise); } }
42.75
162
0.728295
3f8fcf1cee6c4e0db2e5ec3c09498bc1a3b5795d
2,901
package ch.zhaw.securitylab.DIMBA.networking; import ch.zhaw.securitylab.DIMBA.DIMBA; import ch.zhaw.securitylab.DIMBA.data.metasettings.Metasettings; import ch.zhaw.securitylab.DIMBA.networking.listeners.ConnectionListener; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.Response.Listener; import com.android.volley.toolbox.HttpHeaderParser; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; /** * The Request object holding the data and storing the response listener for making https requests with volley. */ public class InRequest extends Request<InResponse> { // -------------------------------------------- // // FIELDS // -------------------------------------------- // private final Object mLock = new Object(); private Listener<InResponse> listener; private Map<String, String> data; // -------------------------------------------- // // CONSTRUCT // -------------------------------------------- // public InRequest(int method, String url, ConnectionListener connectionListener, Map<String, String> data) { super(method, getBaseUrl() + url, connectionListener); int timeout = DIMBA.get().getMetasettingsDao().getSettings().getTimeout(); this.listener = connectionListener; this.data = data; this.setRetryPolicy(new DefaultRetryPolicy( timeout, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT )); } private static String getBaseUrl() { Metasettings metasettings = DIMBA.get().getMetasettingsDao().getSettings(); return "https://" + metasettings.getIp() + ":8443"; } // -------------------------------------------- // // OVERRIDE // -------------------------------------------- // @Override public Map<String, String> getHeaders() { Map<String, String> params = new HashMap<String, String>(); String jwt = DIMBA.get().getJwt(); if (jwt != null) { params.put("Authorization", "Bearer: " + jwt); } return params; } @Override protected Map<String, String> getParams() { return data; } @Override protected Response<InResponse> parseNetworkResponse(NetworkResponse networkResponse) { String message; try { message = new String(networkResponse.data, HttpHeaderParser.parseCharset(networkResponse.headers)); } catch (UnsupportedEncodingException e) { message = new String(networkResponse.data); } InResponse response = new InResponse(message, networkResponse.statusCode); return Response.success(response, HttpHeaderParser.parseCacheHeaders(networkResponse)); } @Override protected void deliverResponse(InResponse response) { Response.Listener<InResponse> listener; synchronized (mLock) { listener = this.listener; } if (listener != null) { listener.onResponse(response); } } }
27.367925
111
0.669769
7de56e842761df1676010e451b0b69694df3d621
494
package dev.jlarsen.authserverdemo.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * Throw and render a view with error locally, since there is an issue with the redirect_uri */ @ResponseStatus(value= HttpStatus.BAD_REQUEST) public class RedirectUriException extends RuntimeException { public RedirectUriException() { super("invalid_request - invalid parameter, or otherwise invalid request"); } }
30.875
92
0.785425
a3a59d2f4c72f13c11cfe95c1e93236c73af2192
1,966
package me.mckoxu.mckrtp.listeners; import me.mckoxu.mckrtp.MCKRTp; import me.mckoxu.mckrtp.utils.CoordinateUtil; import me.mckoxu.mckrtp.utils.RandomUtil; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; public class PlayerInteractListener implements Listener { public static ConfigurationSection config = MCKRTp.getInst().getConfig(); @EventHandler public void onInteract(PlayerInteractEvent e){ Player p = e.getPlayer(); Action a = e.getAction(); if(a == Action.RIGHT_CLICK_BLOCK){ Block b = e.getClickedBlock(); Location l = b.getLocation(); if(b.getType() == Material.STONE_BUTTON){ if(!MCKRTp.locations.isEmpty()) { for (Location loc : MCKRTp.locations) { if (CoordinateUtil.sameCords(l, loc)) { double x = RandomUtil.getRandom(MCKRTp.minx, MCKRTp.maxx); double z = RandomUtil.getRandom(MCKRTp.minz, MCKRTp.maxz); Location teleport = new Location(loc.getWorld(), x, loc.getWorld().getHighestBlockYAt((int) x, (int) z), z); p.teleport(teleport); p.sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("info.teleport").replace("{WORLD}", teleport.getWorld().getName()).replace("{X}", String.valueOf(teleport.getX())).replace("{Y}", String.valueOf(teleport.getY())).replace("{Z}", String.valueOf(teleport.getZ())))); return; } } } } } } }
43.688889
316
0.618515
8be5f3a65a627ec68de4347fb9cde84fae61272d
4,151
package com.sngur.learnkhasi.roomdb; import android.content.Context; import com.sngur.learnkhasi.model.room.Editors; import com.sngur.learnkhasi.model.room.FavoriteWord; import com.sngur.learnkhasi.model.room.StoredEnglishWord; import com.sngur.learnkhasi.model.room.StoredKhasiWord; import com.sngur.learnkhasi.model.room.StoredSentence; import com.sngur.learnkhasi.model.room.UserSentenceReported; import com.sngur.learnkhasi.model.room.UserSentenceVotes; import com.sngur.learnkhasi.model.room.UserWordReported; import com.sngur.learnkhasi.model.room.UserWordVoted; import com.sngur.learnkhasi.roomdb.dao.EditorsDao; import com.sngur.learnkhasi.roomdb.dao.FavoriteWordDao; import com.sngur.learnkhasi.roomdb.dao.StoredEnglishWordDao; import com.sngur.learnkhasi.roomdb.dao.StoredKhasiWordDao; import com.sngur.learnkhasi.roomdb.dao.StoredSentenceDao; import com.sngur.learnkhasi.roomdb.dao.UserSentenceReportedDao; import com.sngur.learnkhasi.roomdb.dao.UserSentenceVotesDao; import com.sngur.learnkhasi.roomdb.dao.UserWordReportedDao; import com.sngur.learnkhasi.roomdb.dao.UserWordVotesDao; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import androidx.annotation.NonNull; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.room.migration.Migration; import androidx.sqlite.db.SupportSQLiteDatabase; @Database(entities = {UserSentenceVotes.class, UserSentenceReported.class, StoredSentence.class,UserWordReported.class,UserWordVoted.class, FavoriteWord.class, StoredKhasiWord.class, StoredEnglishWord.class, Editors.class}, version = 1, exportSchema = false) public abstract class LearnKhasiDatabase extends RoomDatabase { private static volatile LearnKhasiDatabase INSTANCE; private static final int NUMBER_OF_THREADS = 4; public static final ExecutorService databaseWriteExecutor = Executors.newFixedThreadPool(NUMBER_OF_THREADS); public abstract UserSentenceVotesDao userSentenceVotesDao(); public abstract UserSentenceReportedDao userSentenceReportedDao(); public abstract StoredSentenceDao storedSentenceDao(); public abstract UserWordVotesDao userWordVotesDao(); public abstract UserWordReportedDao userWordReportedDao(); public abstract FavoriteWordDao favoriteWordDao(); public abstract StoredEnglishWordDao storedEnglishWordDao(); public abstract StoredKhasiWordDao storedKhasiWordDao(); public abstract EditorsDao editorsDao(); //Migration // static final Migration MIGRATION_1_2 = new Migration(1, 2) { // @Override // public void migrate(SupportSQLiteDatabase database) { // // Since we didn't alter the table, there's nothing else to do here. // database.execSQL("CREATE TABLE user_sentence_reported (fromLanguage TEXT, sentenceId TEXT NOT NULL, reported INTEGER NOT NULL, PRIMARY KEY(sentenceId))"); // } // }; // // static final Migration MIGRATION_2_3 = new Migration(2, 3) { // @Override // public void migrate(SupportSQLiteDatabase database) { // //database.execSQL("ALTER TABLE user_sentence_reported RENAME COLUMN vote TO reported"); // } // }; //getDatabase returns the singleton. public static LearnKhasiDatabase getDatabase(final Context context) { if (INSTANCE == null) { synchronized (LearnKhasiDatabase.class) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.getApplicationContext(), LearnKhasiDatabase.class, "learnkhasi") //.addCallback(sRoomDatabaseCallback) //.addMigrations(MIGRATION_1_2,MIGRATION_2_3) .fallbackToDestructiveMigration() .build(); } } } return INSTANCE; } private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() { @Override public void onOpen(@NonNull SupportSQLiteDatabase db) { super.onOpen(db); } }; }
44.634409
258
0.738376
3188b8523fd596634c43858908e34405e7322263
120
package dne.eiim.xjam; public class SystemOut extends PrintStreamOut { public SystemOut() { super(System.out); } }
15
47
0.733333
28647cd8373d80f53341106753d92f0b557288e8
1,652
package net.zephyrizing.http_server; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; import java.util.Map; import net.zephyrizing.http_server.HttpRequest.Method; public class RequestBuilder { private static final String CONTENT_LENGTH_HEADER = "Content-Length"; private Method m; private String p; private String q; private ByteBuffer buff; private Headers headers = new HeadersMap(); public RequestBuilder method(Method m) { this.m = m; return this; } public RequestBuilder path(String p) { this.p = p; return this; } public RequestBuilder query(String q) { this.q = q; return this; } public RequestBuilder header(String key, String value) { this.headers.put(key, value); return this; } public boolean hasContentHeader() { return this.headers.containsKey(CONTENT_LENGTH_HEADER); } public long contentLength() { return Integer.parseInt(this.headers.get(CONTENT_LENGTH_HEADER)); } public RequestBuilder body(ByteBuffer buff) { this.buff = buff; return this; } public HttpRequest build() { assertNotNull(this.m, "Request method must be set"); assertNotNull(this.p, "Request path must be set"); return new HttpRequest(this.m, this.p, this.q, this.headers, this.buff); } private void assertNotNull(Object o, String message) { if (o == null) { throw new IllegalArgumentException(String.format("%s before calling build.", message)); } } }
24.656716
99
0.637409
4b9baec742835f2e2949cc45eab281300d2394b2
2,612
package org.conqueror.drone.task; import akka.actor.ActorRef; import akka.actor.Cancellable; import akka.event.LoggingAdapter; import org.conqueror.common.utils.file.FileUtils; import org.conqueror.drone.config.CrawlConfig; import org.conqueror.drone.data.url.URLInfo; import org.conqueror.drone.selenium.webdriver.WebBrowser; import org.json.simple.JSONObject; import org.openqa.selenium.WebElement; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class PageToFileCrawler extends PageCrawler { public PageToFileCrawler(int number, Cancellable beforeSchedule, WebBrowser browser, LoggingAdapter logger, URLInfo urlInfo, CrawlConfig config, ActorRef taskManager, ActorRef taskWorker) { super(number, beforeSchedule, browser, logger, urlInfo, config, taskManager, taskWorker); } @Override protected void savePageSource(URLInfo urlInfo) { if (getConfig().getRootDirectory() == null) return; int numberOfPages = getConfig().getNumberOfPages(); // String pageSource = getBrowser().getPageSource().trim(); // if (pageSource.isEmpty()) return; WebElement title = getBrowser().findElementByXPath("//*[@id=\"articleTitle\"]", 3); if (title == null) return; WebElement postDate = getBrowser().findElementByXPath("//*[@id=\"main_content\"]/div[1]/div[3]/div/span[2]", 3); if (postDate == null) return; WebElement body = getBrowser().findElementByXPath("//*[@id=\"articleBodyContents\"]", 3); if (body == null) return; try { int fileNumber = urlInfo.getId() / numberOfPages; FileUtils.createDirectory(getConfig().getRootDirectory(), urlInfo.getDomain()); Path filePath = Paths.get(getConfig().getRootDirectory(), urlInfo.getDomain(), String.valueOf(fileNumber)); JSONObject jsonObject = new JSONObject(); jsonObject.put("id", urlInfo.getId()); jsonObject.put("depth", urlInfo.getDepth()); jsonObject.put("url", urlInfo.getUrl()); jsonObject.put("title", title.getText()); jsonObject.put("postDate", postDate.getText()); jsonObject.put("body", body.getText()); FileUtils.writeContent(filePath, jsonObject.toString(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); FileUtils.writeContent(filePath, "\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND); } catch (IOException e) { log().error(e, "failed to save page source"); } } }
42.819672
193
0.686064
e462daeb2f6ab44be3a05c97ddeece30487a09a9
15,490
/** * Copyright 2015 , University of Rochester Medical Center * * * 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. * * @author png ([email protected]) */ package edu.rochester.urmc.util; import java.text.DecimalFormat; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; public class AggregateFx { public Object aggrVFIRST( HashMap[] in , HashMap control){ Object ans = ""; for( HashMap i : in ){ ans = ""+i.get("DATA"); i.put("RATIONALE", "First Value"); break; } return ans; } public static Double val( Object x ){ Double answer = null; if( x instanceof Number ){ answer = new Double(((Number) x).doubleValue()); } else if( !isKindOfNull( x ) ){ try{ answer = new Double( "" + x ); }catch (Exception ex){} } return answer; } public static boolean isKindOfNull( Object in ){ boolean ans = false; ans |= in == null; //boolean temp =( in == null ); //boolean temp3 =(".".equals(in.toString().trim())) ); //.... //answer = temp || temp2 || .......; ans |= (in != null && "".equals(in.toString().trim())); ans |= (in != null && ".".equals(in.toString().trim())); ans |= (in != null && ":".equals(in.toString().trim())); ans |= (in != null && "/".equals(in.toString().trim())); ans |= (in != null && "N".equals(in.toString().trim())); ans |= (in != null && "N.".equals(in.toString().trim())); ans |= (in != null && ".N".equals(in.toString().trim())); ans |= (in != null && "-".equals(in.toString().trim())); //ans |= (in != null && "0".equals(in.toString().trim())); return ans; } public Object aggrVMIN( HashMap[] in , HashMap control){ Object ans = ""; Double minsofar = Double.MAX_VALUE; for( HashMap i : in ){ Double test = val(i.get("DATA")); if( test != null && minsofar.compareTo(test) > 0 ){ minsofar = test; i.put("RATIONALE", " current min.."); } } return ""+(Double.MAX_VALUE == minsofar?"":minsofar); } public Object aggrD2ND( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( HashMap i : in ){ count++; i.put("RATIONALE", "#" + count ); if( count >= 2 ){ ans = ""+ i.get("START_DATE"); break; } } return ans; } public Object aggrDE2ND( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( int iter = in.length-1; in != null && iter > 0; iter-- ){ count++; in[iter].put("RATIONALE", "#" + count ); if( count >= 2 ){ ans = ""+ in[iter].get("START_DATE"); break; } } return ans; } public Object aggrDE3RD( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( int iter = in.length-1; in != null && iter > 0; iter-- ){ count++; in[iter].put("RATIONALE", "#" + count ); if( count >= 3 ){ ans = ""+ in[iter].get("START_DATE"); break; } } return ans; } public Object aggrDE4TH( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( int iter = in.length-1; in != null && iter > 0; iter-- ){ count++; in[iter].put("RATIONALE", "#" + count ); if( count >= 4 ){ ans = ""+ in[iter].get("START_DATE"); break; } } return ans; } public Object aggrDE5TH( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( int iter = in.length-1; in != null && iter > 0; iter-- ){ count++; in[iter].put("RATIONALE", "#" + count ); if( count >= 5 ){ ans = ""+ in[iter].get("START_DATE"); break; } } return ans; } public Object aggrD3RD( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( HashMap i : in ){ count++; i.put("RATIONALE", "#" + count ); if( count >= 3 ){ ans = ""+ i.get("START_DATE"); break; } } return ans; } public Object aggrD4TH( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( HashMap i : in ){ count++; i.put("RATIONALE", "#" + count ); if( count >= 4 ){ ans = ""+ i.get("START_DATE"); break; } } return ans; } public Object aggrD5TH( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( HashMap i : in ){ count++; i.put("RATIONALE", "#" + count ); if( count >= 5 ){ ans = ""+ i.get("START_DATE"); break; } } return ans; } public Object aggrV2ND( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( HashMap i : in ){ count++; i.put("RATIONALE", "#" + count ); if( count >= 2 ){ ans = ""+ i.get("DATA"); break; } } return ans; } public Object aggrVE2ND( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( int iter = in.length-1; in != null && iter > 0; iter-- ){ count++; in[iter].put("RATIONALE", "#" + count ); if( count >= 2 ){ ans = ""+ in[iter].get("DATA"); break; } } return ans; } public Object aggrVE3RD( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( int iter = in.length-1; in != null && iter > 0; iter-- ){ count++; in[iter].put("RATIONALE", "#" + count ); if( count >= 3 ){ ans = ""+ in[iter].get("DATA"); break; } } return ans; } public Object aggrVE4TH( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( int iter = in.length-1; in != null && iter > 0; iter-- ){ count++; in[iter].put("RATIONALE", "#" + count ); if( count >= 5 ){ ans = ""+ in[iter].get("DATA"); break; } } return ans; } public Object aggrVE5TH( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( int iter = in.length-1; in != null && iter > 0; iter-- ){ count++; in[iter].put("RATIONALE", "#" + count ); if( count >= 5 ){ ans = ""+ in[iter].get("DATA"); break; } } return ans; } public Object aggrV3RD( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( HashMap i : in ){ count++; i.put("RATIONALE", "#" + count ); if( count >= 3 ){ ans = ""+ i.get("DATA"); break; } } return ans; } public Object aggrV4TH( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( HashMap i : in ){ count++; i.put("RATIONALE", "#" + count ); if( count >= 4 ){ ans = ""+ i.get("DATA"); break; } } return ans; } public Object aggrV5TH( HashMap[] in , HashMap control){ Object ans = ""; String test; int count = 0; for( HashMap i : in ){ count++; i.put("RATIONALE", "#" + count ); if( count >= 5 ){ ans = ""+ i.get("DATA"); break; } } return ans; } public Object aggrDMIN( HashMap[] in , HashMap control){ Object ans = ""; Double minsofar = Double.MAX_VALUE; for( HashMap i : in ){ Double test = val(i.get("DATA")); if( test != null && minsofar.compareTo(test) > 0 ){ minsofar = test; ans = i.get("START_DATE"); i.put("RATIONALE", " current min.."); } } return ans; } public Object aggrVAVG( HashMap[] in , HashMap control){ Object ans = ""; double sum = new Double(0); double count = 0; for( HashMap i : in ){ Double test = val(i.get("DATA")); if( test != null ){ sum += test.doubleValue(); ; i.put("RATIONALE", ""+new DecimalFormat("0.000").format(sum) +"/"+ (++count) ); } } return "" + (count == 0? "" : new DecimalFormat("0.00000").format(sum/count) ); } public Object aggrVMAX( HashMap[] in , HashMap control){ Object ans = ""; Double minsofar = Double.MIN_VALUE; for( HashMap i : in ){ Double test = val(i.get("DATA")); if( test != null && minsofar.compareTo(test) < 0 ){ minsofar = test; i.put("RATIONALE", " current max.."); } } return ""+(Double.MIN_VALUE == minsofar?"":minsofar); } public Object aggrDMAX( HashMap[] in , HashMap control){ Object ans = ""; Double minsofar = Double.MIN_VALUE; for( HashMap i : in ){ Double test = val(i.get("DATA")); if( test != null && minsofar.compareTo(test) < 0 ){ minsofar = test; ans = i.get("START_DATE"); i.put("RATIONALE", " current max.."); } } return ans; } public Object aggrCOUNT( HashMap[] in , HashMap control){ int count =0; for( HashMap i : in ){ i.put("RATIONALE", ""+(++count)); } return in.length == 0 ? "" : (""+in.length); } public Object aggrVMODE( HashMap[] in , HashMap control){ Object ans = ""; Arrays.sort(in,new Comparator<HashMap>(){ public int compare(HashMap a, HashMap b) { return ((Comparable)a.get("DATA")).compareTo(((Comparable)b.get("DATA"))); } }); Object sofar = ""; Object curr = ""; int maxsofar = 0; int currcount = 0; for( HashMap i : in ){ if( !curr.equals(i.get("DATA")) ){ currcount = 0; curr = i.get("DATA"); } currcount ++; if( currcount > maxsofar ){ sofar = curr; maxsofar = currcount; i.put("RATIONALE", ""+currcount+ " current mode.."); } else { i.put("RATIONALE", ""+currcount); } } return ""+sofar; } public Object aggrPRESENCE( HashMap[] in , HashMap control){ return in.length > 0 ? "1" : "0"; } public Object aggrVLAST( HashMap[] in , HashMap control){ Object ans = ""; if( in.length > 0 ){ HashMap i = in[ in.length -1 ]; ans = ""+i.get("DATA"); i.put("RATIONALE", "Last Value"); } return ans; } public Object aggrDFIRST( HashMap[] in , HashMap control){ Object ans = ""; for( HashMap i : in ){ i.put("RATIONALE", "First Date"); ans = i.get("START_DATE"); break; } return ans; } public Object aggrDLAST( HashMap[] in , HashMap control){ Object ans = ""; if( in.length > 0 ){ HashMap i = in[ in.length -1 ]; i.put("RATIONALE", "Last Date"); ans = i.get("START_DATE"); } return ans; } public Object aggrAGGR_STR( HashMap[] in , HashMap control){ String ans = ""; int counter = 0; for( HashMap i : in ){ counter ++; i.put("RATIONALE", "adding"); String addition = (""+i.get("DATA")).replace(';', ',') + ";\n"; if( ans.length() + 50 >= 4000 ){ ans += ";\n*** TRUNCATED, " + (in.length - counter) + " ITEMS REMAINING ***"; break; } else { ans += addition; } } return ans; } public Object aggrAGGR_STR_N_DATE( HashMap[] in , HashMap control){ String ans = ""; int counter = 0; for( HashMap i : in ){ i.put("RATIONALE", "adding"); String addition = REDCapFormatter.format(i.get("START_DATE"),"datetime")+"-"+(""+i.get("DATA")).replace(';', ',') + ";\n"; if( ans.length() + 50 >= 4000 ){ ans += ";\n*** TRUNCATED, " + (in.length - counter) + " ITEMS REMAINING ***"; break; } else { ans += addition; } } return ans; } public Object aggrAGGR_HISTOGRAM( HashMap[] in , HashMap control){ String ans = ""; HashMap< String, Integer > db = new HashMap(); int counter = 0; for( HashMap i : in ){ i.put("RATIONALE", "adding"); String addition = (""+i.get("DATA")).replace(';', ',') ; if( !db.containsKey(addition) ){ db.put(addition, 0); } db.put(addition,db.get(addition) + 1); } for( String key : db.keySet() ){ String addition = key.replace(';', ',')+" - (" + db.get(key) + " items );\n"; if( ans.length() + 50 >= 4000 ){ ans += ";\n*** TRUNCATED, " + (in.length - counter) + " ITEMS REMAINING ***"; break; } else { ans += addition; } } return ans; } public Object format( Object ans, HashMap control ){ return "" + ans; } }
31.104418
134
0.436862
c8096e8af514a1ed04899988a279653b849b093d
750
package Builder; /** * Created by wlp on 2018/5/22. * 商品 */ public class Computer { private String cpu; private String amr; private String sd; @Override public String toString() { return "Computer{" + "cpu='" + cpu + '\'' + ", amr='" + amr + '\'' + ", sd='" + sd + '\'' + '}'; } public String getCpu() { return cpu; } public void setCpu(String cpu) { this.cpu = cpu; } public String getAmr() { return amr; } public void setAmr(String amr) { this.amr = amr; } public String getSd() { return sd; } public void setSd(String sd) { this.sd = sd; } }
16.304348
40
0.454667
d5267bb6bcd222d729ba9ca299b351a35c7789b6
1,957
package com.puresoltechnologies.javafx.charts.dialogs; import java.util.List; import com.puresoltechnologies.javafx.charts.ChartView; import com.puresoltechnologies.javafx.charts.plots.Plot; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.DialogPane; import javafx.scene.control.Label; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.layout.BorderPane; /** * This class provides the chart properties dialog to configure the chart which * was provided in the constructor. * * @author Rick-Rainer Ludwig * */ public class ChartPropertiesDialog extends Dialog<Void> { private final ChartView chartView; private final TreeView<String> chartElements = new TreeView<>(); private final List<Plot<?, ?, ?>> plots; public ChartPropertiesDialog(ChartView chartView, List<Plot<?, ?, ?>> plots) { super(); this.chartView = chartView; this.plots = plots; setTitle(chartView.getTitle() + " Chart Properties"); setHeaderText("Configure the chart, its axes and plots."); setResizable(true); DialogPane dialogPane = getDialogPane(); dialogPane.getButtonTypes().addAll(ButtonType.CLOSE); BorderPane borderPane = new BorderPane(); borderPane.setLeft(chartElements); borderPane.setCenter(new Label("Select a chart element to configure.")); dialogPane.setContent(borderPane); createTree(); } private void createTree() { TreeItem<String> rootItem = new TreeItem<>("Chart"); rootItem.setExpanded(true); TreeItem<String> axesItem = new TreeItem<>("Axes"); axesItem.setExpanded(true); TreeItem<String> plotsItem = new TreeItem<>("Plots"); plotsItem.setExpanded(true); for (Plot<?, ?, ?> plot : plots) { TreeItem<String> plotItem = new TreeItem<>(plot.getTitle()); plotsItem.getChildren().add(plotItem); } rootItem.getChildren().addAll(axesItem, plotsItem); chartElements.setRoot(rootItem); } }
27.957143
82
0.746551
d1f9fa60780c75a71d7fb5a051d2be94da6f4133
605
package com.generator.dao; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 公共DAO接口 * @param <T> */ public interface AbstrctDao <T>{ void insert(T t)throws Exception; void update(T t)throws Exception; void delete(@Param("key") String ukfield, @Param("value")Object value)throws Exception; T select(@Param("key") String ukfield, @Param("value")Object value)throws Exception; boolean exsits(@Param("key")String ukfield,@Param("value")Object value)throws Exception; List<T> selectLike(@Param("key")String key)throws Exception ; }
31.842105
96
0.690909
5acc61a32d98aa478c766d47747ea1e8c613e52c
10,231
/** * created by ozkh on 10/11/2015. * acknowledgements to below: * http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/ * http://www.tutorialspoint.com/java/java_sending_email.htm * https://www.youtube.com/watch?v=glewfpkid74 * and any other online source that i have missed out (hopefully not). */ import javax.mail.Message; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; // The main menu (a Viewer of the MVC pattern) public class MainFrame extends JFrame { private Color green = new Color(0,100,0); private final static String SENDPANEL = "Send Mail"; private final static String RECEPANEL = "Receive Mail"; private final static String TITLEFRAME = "Othman Empire Mail"; private final static String SENDBUTTON = "Send Demonic Mail"; private final static String NEXTBUTTON = "Next Demonic Mail"; private final static String PREVBUTTON = "Previous Demonic Mail"; private final static String FROMFIELD = "[email protected]"; private final static String TOFIELD = "[email protected]"; private final static String SUBJECTFIELD = "Lack of Confidence"; private final static String BODYFIELD = "Dear Mr.Evil,\n\n" + "Am I a poor programmer if I can't figure out the bubble sort algorithm?\n\nRegards,\nTheDiabolic"; private Border emptyBorder = BorderFactory.createEmptyBorder(10, 10, 10, 10); private Border greenBorder = BorderFactory.createLineBorder(green); private JFrame frame; private JTabbedPane tabbedPane; private JPanel card1, card2, sendButtonPanel, recvButtonPanel, messagePanel, subjectPanel, fromPanel, toPanel; private JButton sendMailButton, nextMailButton, prevMailButton; private JLabel subjectLabel, fromLabel, toLabel; private JTextField subjectField, fromField, toField; private JTextArea bodyText, recvText; private JScrollPane recvPanel, bodyPanel; private Container contentPane; private MailController mailController; private MailModel mailModel; // To be accessed through mailController private int messageNum = 0; public MainFrame(MailController mc) { mailController = mc; mailModel = mailController.getMailModel(); // Create the frame and adjust settings frame = new JFrame(TITLEFRAME); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(700, 700); // Main pane where tabs will be added contentPane = frame.getContentPane(); // Tabbed pane where 'cards' will be added tabbedPane = new JTabbedPane(); // Add components to the 'card' for the first tab card1 = new JPanel(); card1.setLayout(new BoxLayout(card1, BoxLayout.PAGE_AXIS)); // Add components to the 'card' for the second tab card2 = new JPanel(); card2.setLayout(new BoxLayout(card2, BoxLayout.PAGE_AXIS)); // Create the panel for the receiving buttons (previous and next buttons) recvButtonPanel = new JPanel(); recvButtonPanel.setLayout((new BoxLayout(recvButtonPanel, BoxLayout.LINE_AXIS))); sendButtonPanel = new JPanel(); sendButtonPanel.setLayout((new BoxLayout(sendButtonPanel, BoxLayout.LINE_AXIS))); // Create the panel for where the email is typed up messagePanel = new JPanel(); messagePanel.setLayout((new BoxLayout(messagePanel, BoxLayout.PAGE_AXIS))); messagePanel.setBorder(emptyBorder); // Create the panel and text field where emails are typed up for card1 bodyText = new JTextArea(BODYFIELD); bodyText.setBorder(BorderFactory.createCompoundBorder(greenBorder, emptyBorder)); bodyPanel = new JScrollPane(bodyText, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); bodyPanel.setBorder(BorderFactory.createCompoundBorder(new EtchedBorder(), emptyBorder)); // Create the panel and text field where received emails could be displayed for card2 recvText = new JTextArea(); recvText.setEditable(false); recvText.setBorder(BorderFactory.createCompoundBorder(greenBorder, emptyBorder)); recvPanel = new JScrollPane(recvText, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); recvPanel.setBorder(new TitledBorder( BorderFactory.createCompoundBorder(new EtchedBorder(), emptyBorder), "Received Email: ")); // Create the "subject" mail field panel subjectPanel = new JPanel(); subjectPanel.setLayout(new BoxLayout(subjectPanel, BoxLayout.LINE_AXIS)); subjectPanel.setMaximumSize(new Dimension((int) frame.getMaximumSize().getWidth(), 0)); // Create the "sent from" mail field panel fromPanel = new JPanel(); fromPanel.setLayout(new BoxLayout(fromPanel, BoxLayout.LINE_AXIS)); fromPanel.setMaximumSize(new Dimension((int) frame.getMaximumSize().getWidth(), 0)); // Create the "sent to" mail field panel toPanel = new JPanel(); toPanel.setLayout(new BoxLayout(toPanel, BoxLayout.LINE_AXIS)); toPanel.setMaximumSize(new Dimension((int) frame.getMaximumSize().getWidth(), 0)); // Create the send and and receive (next and prev) mail buttons sendMailButton = new JButton(SENDBUTTON); nextMailButton = new JButton(NEXTBUTTON); nextMailButton.setMinimumSize(new Dimension(180, 25)); nextMailButton.setMaximumSize(nextMailButton.getMinimumSize()); prevMailButton = new JButton(PREVBUTTON); prevMailButton.setMinimumSize(new Dimension(180, 25)); prevMailButton.setMaximumSize(prevMailButton.getMinimumSize()); // Create labels corresponding to email detail fields subjectLabel = new JLabel("Subject"); fromLabel = new JLabel("From"); toLabel = new JLabel("To"); // Create fields to enter email details for card1 subjectField = new JTextField(SUBJECTFIELD); subjectField.setBorder(greenBorder); fromField = new JTextField(FROMFIELD); fromField.setBorder(greenBorder); fromField.setEditable(false); toField = new JTextField(TOFIELD); toField.setBorder(greenBorder); card1.add(Box.createRigidArea(new Dimension(10, 0))); card1.add(messagePanel); card2.add(Box.createRigidArea(new Dimension(0, 10))); card2.add(recvPanel); card2.add(Box.createRigidArea(new Dimension(0, 10))); card2.add(recvButtonPanel); card2.add(Box.createRigidArea(new Dimension(0, 10))); tabbedPane.addTab(SENDPANEL, card1); tabbedPane.addTab(RECEPANEL, card2); messagePanel.add(fromPanel); messagePanel.add(Box.createRigidArea(new Dimension(0, 10))); messagePanel.add(toPanel); messagePanel.add(Box.createRigidArea(new Dimension(0, 10))); messagePanel.add(subjectPanel); messagePanel.add(Box.createRigidArea(new Dimension(0, 10))); messagePanel.add(bodyPanel); messagePanel.add(Box.createRigidArea(new Dimension(0, 10))); messagePanel.add(sendButtonPanel); sendButtonPanel.add(sendMailButton); recvButtonPanel.add(prevMailButton); recvButtonPanel.add(Box.createRigidArea(new Dimension(30, 0))); recvButtonPanel.add(nextMailButton); subjectPanel.add(subjectLabel); subjectPanel.add(Box.createRigidArea(new Dimension(10, 0))); subjectPanel.add(subjectField); fromPanel.add(fromLabel); fromPanel.add(Box.createRigidArea(new Dimension(25, 0))); fromPanel.add(fromField); toPanel.add(toLabel); toPanel.add(Box.createRigidArea(new Dimension(40, 0))); toPanel.add(toField); contentPane.add(tabbedPane, BorderLayout.CENTER); frame.pack(); // Adding event listeners sendMailButton.addActionListener(new SendButtonListener()); RecvButtonListener recvHandler = new RecvButtonListener(); nextMailButton.addActionListener(recvHandler); prevMailButton.addActionListener(recvHandler); addWindowListener(new ExitListener()); } public JFrame getFrame() { return frame;} public void setUsername(String from) { fromField.setText(from); } // Sends an email whenever the button is pressed private class SendButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { mailModel.sendMail(fromField.getText(), toField.getText(), subjectField.getText(), bodyText.getText()); } } // Reads the next or previous email from inbox private class RecvButtonListener implements ActionListener { Message message = null; public void actionPerformed(ActionEvent event) { if(event.getSource() == nextMailButton) { messageNum += 1; } if(event.getSource() == prevMailButton) { messageNum -= 1; } mailModel.openInbox(); message = mailModel.fetchInboxMail(messageNum); recvText.setText(mailModel.readMail(message)); } } // Listener to ensure that all connections are closed // (courtesy from an online source that I no longer have access to) private class ExitListener implements WindowListener { public void windowClosing(WindowEvent arg0) { mailController.getMailModel().closeConnections(); System.exit(0); } public void windowOpened(WindowEvent arg0) {} public void windowClosed(WindowEvent arg0) {} public void windowIconified(WindowEvent arg0) {} public void windowDeiconified(WindowEvent arg0) {} public void windowActivated(WindowEvent arg0) {} public void windowDeactivated(WindowEvent arg0) {} } }
43.53617
115
0.69309
072d91aaa13d9a8e73251f4d2eed98e391d794cb
1,359
package packt.java9.by.example.mybusiness.productinformation; import java.net.URI; public class ProductInformation { private String id; private String title; private String description; private final double size[] = new double[3]; private double weight; public void setId(String id) { this.id = id; } public void setTitle(String title) { this.title = title; } public void setDescription(String description) { this.description = description; } public void setWeight(double weight) { this.weight = weight; } public String getId() { return id; } public String getTitle() { return title; } public String getDescription() { return description; } public double[] getSize() { return size; } public double getWeight() { return weight; } public static final ProductInformation emptyProductInformation = new ProductInformation(); static { emptyProductInformation.setTitle(""); emptyProductInformation.setDescription(""); emptyProductInformation.setId(""); emptyProductInformation.setWeight(0); emptyProductInformation.getSize()[0] = 0; emptyProductInformation.getSize()[1] = 0; emptyProductInformation.getSize()[2] = 0; } }
22.65
94
0.637233
71a8c641934984f7baa3686ce221938c6ff4460c
896
package com.mm.tnxrs.common.model.base; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.IBean; /** * Generated by JFinal, do not modify this file. */ @SuppressWarnings("serial") public abstract class BaseAuthCode<M extends BaseAuthCode<M>> extends Model<M> implements IBean { public void setId(java.lang.String id) { set("id", id); } public java.lang.String getId() { return get("id"); } public void setAccountId(java.lang.Integer accountId) { set("accountId", accountId); } public java.lang.Integer getAccountId() { return get("accountId"); } public void setExpireAt(java.lang.Long expireAt) { set("expireAt", expireAt); } public java.lang.Long getExpireAt() { return get("expireAt"); } public void setType(java.lang.Integer type) { set("type", type); } public java.lang.Integer getType() { return get("type"); } }
19.911111
97
0.705357
16a3fdcdb0f00dc7559a2790864162318ef15333
784
package useful; import common.Util; import us.codecraft.webmagic.selector.Html; public class TraceHTMLTag { public static void main(final String[] args) { final String s = "<span class=\"titleLabel\" style=\"line-height: 16px\"> 企业年报信息 </span></div> </td> </tr> </table> </div> <div> <table class=\"tableInfo\" cellspacing=\"0\"> <tr class=\"trTitleText\"> <td>序号</td> <td>报送年度</td> <td>公示日期</td> <td>详情</td> </tr> <tr class=\"tablebodytext\"> <td class=\"nothing\" colspan=\"4\">暂无数据</td> </tr> </table>asdasd2312 asd"; final String a = "<table" + Util.parseRegex(s, "企业年报信息[\\s\\S]*?<table([\\s\\S]*?)/table>") + "/table>"; final Html html = new Html(a); System.out.println(html); System.out.println("116".matches("^(\\-|\\+?)\\d+\\.?\\d*")); } }
43.555556
369
0.605867
dbd1ed0240d8e938dc15077b7400b60fb3da1c6f
972
package com.desertkun.brainout.content; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; import com.desertkun.brainout.content.effect.EffectSet; import com.desertkun.brainout.reflection.Reflect; import com.desertkun.brainout.reflection.ReflectAlias; @Reflect("content.Effect") public class Effect extends Content { private EffectSet set; private JsonValue setValue; public Effect() { set = new EffectSet(); } @Override public void read(Json json, JsonValue jsonData) { super.read(json, jsonData); setValue = jsonData.get("set"); } @Override public void completeLoad(AssetManager assetManager) { super.completeLoad(assetManager); if (setValue != null) { set.read(setValue); setValue = null; } } public EffectSet getSet() { return set; } }
20.680851
55
0.657407
603295579725d935f4a9aa0153c9e6ff8f8c27a5
1,395
package it.progess.core.pojo; import it.progess.core.vo.Ivo; import it.progess.core.vo.PaymentSolution; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="tblpaymentsolution") public class TblPaymentSolution implements Itbl{ @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="idpaymentsolution") private int idPaymentSolution; @Column(name="name") private String name; @Column(name="online") private boolean online; @Column(name="code") private String code; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public boolean isOnline() { return online; } public void setOnline(boolean online) { this.online = online; } public int getIdPaymentSolution() { return idPaymentSolution; } public void setIdPaymentSolution(int idPaymentSolution) { this.idPaymentSolution = idPaymentSolution; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void convertToTable(Ivo obj){ PaymentSolution ps = (PaymentSolution)obj; this.idPaymentSolution = ps.getIdPaymentSolution(); this.name = ps.getName(); this.online = ps.isOnline(); this.code = ps.getCode(); } }
24.051724
58
0.754122
d467e5bc99d3129b381c654e414fe9b7118b4b49
3,413
/* * Copyright (C) 2017 - present Instructure, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.instructure.canvasapi2.apis; import com.instructure.canvasapi2.StatusCallback; import com.instructure.canvasapi2.builders.RestBuilder; import com.instructure.canvasapi2.builders.RestParams; import com.instructure.canvasapi2.models.PollResponse; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Response; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Path; import retrofit2.http.Query; public class PollsAPI { interface PollsInterface { @GET("polls") Call<PollResponse> getPollsList(); @GET("{next}") Call<PollResponse> next(@Path(value = "next", encoded = false) String nextURL); @GET("polls/{pollId}") Call<PollResponse> getSinglePoll(@Path("pollId") long pollId); @POST("polls") Call<PollResponse> createPoll(@Query("polls[][question]") String pollTitle, @Body String body); @PUT("polls/{pollId}") Call<PollResponse> updatePoll(@Path("pollId") long pollId, @Query("polls[][question]") String pollTitle, @Body String body); @DELETE("polls/{pollId}") Call<ResponseBody> deletePoll(@Path("pollId") long pollId); } public static void getFirstPagePolls(RestBuilder adapter, RestParams params, StatusCallback<PollResponse> callback) { callback.addCall(adapter.build(PollsInterface.class, params).getPollsList()).enqueue(callback); } public static void getNextPagePolls(String nextURL, RestBuilder adapter, RestParams params, StatusCallback<PollResponse> callback){ callback.addCall(adapter.build(PollsInterface.class, params).next(nextURL)).enqueue(callback); } public static void getSinglePoll(long pollId, RestBuilder adapter, RestParams params, StatusCallback<PollResponse> callback) { callback.addCall(adapter.build(PollsInterface.class, params).getSinglePoll(pollId)).enqueue(callback); } public static void createPoll(String title, RestBuilder adapter, RestParams params, StatusCallback<PollResponse> callback) { callback.addCall(adapter.build(PollsInterface.class, params).createPoll(title, "")).enqueue(callback); } public static void updatePoll(long pollId, String title, RestBuilder adapter, RestParams params, StatusCallback<PollResponse> callback) { callback.addCall(adapter.build(PollsInterface.class, params).updatePoll(pollId, title, "")).enqueue(callback); } public static void deletePoll(long pollId, RestBuilder adapter, RestParams params, StatusCallback<ResponseBody> callback) { callback.addCall(adapter.build(PollsInterface.class, params).deletePoll(pollId)).enqueue(callback); } }
41.621951
141
0.733372
7cb2c82b17295798c3730b3f26f4db29e57aacdb
31,363
/** * JUunit tests for the Scanner for the class project in COP5556 Programming Language Principles * at the University of Florida, Spring 2018. * <p> * This software is solely for the educational benefit of students * enrolled in the course during the Spring 2018 semester. * <p> * This software, and any software derived from it, may not be shared with others or posted to public web sites, * either during the course or afterwards. * * @Beverly A. Sanders, 2018 */ package cop5556sp18; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import cop5556sp18.Scanner.LexicalException; import cop5556sp18.Scanner.Token; import static cop5556sp18.Scanner.Kind.*; public class ScannerTest { //set Junit to be able to catch exceptions @Rule public ExpectedException thrown = ExpectedException.none(); //To make it easy to print objects and turn this output on and off static boolean doPrint = true; private void show(Object input) { if (doPrint) { System.out.println(input.toString()); } } /** * Retrieves the next token and checks that it is an EOF token. * Also checks that this was the last token. * * @param scanner * @return the Token that was retrieved */ Token checkNextIsEOF(Scanner scanner) { Scanner.Token token = scanner.nextToken(); assertEquals(Scanner.Kind.EOF, token.kind); assertFalse(scanner.hasTokens()); return token; } /** * Retrieves the next token and checks that its kind, position, length, line, and position in line * match the given parameters. * * @param scanner * @param kind * @param pos * @param length * @param line * @param pos_in_line * @return the Token that was retrieved */ Token checkNext(Scanner scanner, Scanner.Kind kind, int pos, int length, int line, int pos_in_line) { Token t = scanner.nextToken(); assertEquals(kind, t.kind); assertEquals(pos, t.pos); assertEquals(length, t.length); assertEquals(line, t.line()); assertEquals(pos_in_line, t.posInLine()); return t; } /** * Retrieves the next token and checks that its kind and length match the given * parameters. The position, line, and position in line are ignored. * * @param scanner * @param kind * @param length * @return the Token that was retrieved */ Token checkNext(Scanner scanner, Scanner.Kind kind, int length) { Token t = scanner.nextToken(); assertEquals(kind, t.kind); assertEquals(length, t.length); return t; } /** * Simple test case with an empty program. The only Token will be the EOF Token. * * @throws LexicalException */ @Test public void testEmpty() throws LexicalException { String input = ""; //The input is the empty string. This is legal show(input); //Display the input Scanner scanner = new Scanner(input).scan(); //Create a Scanner and initialize it show(scanner); //Display the Scanner checkNextIsEOF(scanner); //Check that the only token is the EOF token. } /** * Test illustrating how to put a new line in the input program and how to * check content of tokens. * <p> * Because we are using a Java String literal for input, we use \n for the * end of line character. (We should also be able to handle \n, \r, and \r\n * properly.) * <p> * Note that if we were reading the input from a file, the end of line * character would be inserted by the text editor. * Showing the input will let you check your input is * what you think it is. * * @throws LexicalException */ @Test public void testSemi() throws LexicalException { String input = ";;\n;;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 0, 1, 1, 1); checkNext(scanner, SEMI, 1, 1, 1, 2); checkNext(scanner, SEMI, 3, 1, 2, 1); checkNext(scanner, SEMI, 4, 1, 2, 2); checkNextIsEOF(scanner); } /** * This example shows how to test that your scanner is behaving when the * input is illegal. In this case, we are giving it an illegal character '~' in position 2 * <p> * The example shows catching the exception that is thrown by the scanner, * looking at it, and checking its contents before rethrowing it. If caught * but not rethrown, then JUnit won't get the exception and the test will fail. * <p> * The test will work without putting the try-catch block around * new Scanner(input).scan(); but then you won't be able to check * or display the thrown exception. * * @throws LexicalException */ @Test public void failIllegalChar() throws LexicalException { String input = ";;~"; show(input); thrown.expect(LexicalException.class); //Tell JUnit to expect a LexicalException try { new Scanner(input).scan(); } catch (LexicalException e) { //Catch the exception show(e); //Display it assertEquals(2, e.getPos()); //Check that it occurred in the expected position throw e; //Rethrow exception so JUnit will see it } } @Test public void testParens() throws LexicalException { String input = "()"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, LPAREN, 0, 1, 1, 1); checkNext(scanner, RPAREN, 1, 1, 1, 2); checkNextIsEOF(scanner); } /* ----------------- NEW TEST CASES START --------------------- */ @Test public void testSpace() throws LexicalException { String input = " "; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNextIsEOF(scanner); } @Test public void testLessThan() throws LexicalException { String input = ";<;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 0, 1, 1, 1); checkNext(scanner, OP_LT, 1, 1, 1, 2); checkNext(scanner, SEMI, 2, 1, 1, 3); checkNextIsEOF(scanner); } @Test public void testLessThanEq() throws LexicalException { String input = ";<=;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 0, 1, 1, 1); checkNext(scanner, OP_LE, 1, 2, 1, 2); checkNext(scanner, SEMI, 3, 1, 1, 4); checkNextIsEOF(scanner); } @Test public void testLeftPixel() throws LexicalException { String input = ";<<;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 0, 1, 1, 1); checkNext(scanner, LPIXEL, 1, 2, 1, 2); checkNext(scanner, SEMI, 3, 1, 1, 4); checkNextIsEOF(scanner); } @Test public void testGreaterThan() throws LexicalException { String input = ";>;>"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 0, 1, 1, 1); checkNext(scanner, OP_GT, 1, 1, 1, 2); checkNext(scanner, SEMI, 2, 1, 1, 3); checkNext(scanner, OP_GT, 3, 1, 1, 4); checkNextIsEOF(scanner); } @Test public void testGreaterThanEq() throws LexicalException { String input = ";>=;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 0, 1, 1, 1); checkNext(scanner, OP_GE, 1, 2, 1, 2); checkNext(scanner, SEMI, 3, 1, 1, 4); checkNextIsEOF(scanner); } @Test public void testRightPixel() throws LexicalException { String input = ";>>;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 0, 1, 1, 1); checkNext(scanner, RPIXEL, 1, 2, 1, 2); checkNext(scanner, SEMI, 3, 1, 1, 4); checkNextIsEOF(scanner); } @Test public void testNextLineAtStart() throws LexicalException { String input = "\n;<;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 1, 1, 2, 1); checkNext(scanner, OP_LT, 2, 1, 2, 2); checkNext(scanner, SEMI, 3, 1, 2, 3); checkNextIsEOF(scanner); } @Test public void testColon() throws LexicalException { String input = ";::;:"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 0, 1, 1, 1); checkNext(scanner, OP_COLON, 1, 1, 1, 2); checkNext(scanner, OP_COLON, 2, 1, 1, 3); checkNext(scanner, SEMI, 3, 1, 1, 4); checkNext(scanner, OP_COLON, 4, 1, 1, 5); checkNextIsEOF(scanner); } @Test public void testAssign() throws LexicalException { String input = ";:=;:"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 0, 1, 1, 1); checkNext(scanner, OP_ASSIGN, 1, 2, 1, 2); checkNext(scanner, SEMI, 3, 1, 1, 4); checkNext(scanner, OP_COLON, 4, 1, 1, 5); checkNextIsEOF(scanner); } @Test public void testEqual() throws LexicalException { String input = ";==;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 0, 1, 1, 1); checkNext(scanner, OP_EQ, 1, 2, 1, 2); checkNext(scanner, SEMI, 3, 1, 1, 4); checkNextIsEOF(scanner); } @Test public void testFailSingleEqualChar() throws LexicalException { String input = ";=:;:"; show(input); thrown.expect(LexicalException.class); try { new Scanner(input).scan(); } catch (LexicalException e) { show(e); assertEquals(1, e.getPos()); throw e; } } @Test public void testExclamation() throws LexicalException { String input = ";!:;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 0, 1, 1, 1); checkNext(scanner, OP_EXCLAMATION, 1, 1, 1, 2); checkNext(scanner, OP_COLON, 2, 1, 1, 3); checkNext(scanner, SEMI, 3, 1, 1, 4); checkNextIsEOF(scanner); } @Test public void testNotEqual() throws LexicalException { String input = ";!=;:"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 0, 1, 1, 1); checkNext(scanner, OP_NEQ, 1, 2, 1, 2); checkNext(scanner, SEMI, 3, 1, 1, 4); checkNext(scanner, OP_COLON, 4, 1, 1, 5); checkNextIsEOF(scanner); } @Test public void testEqNotEqual() throws LexicalException { String input = ";!===;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, SEMI, 0, 1, 1, 1); checkNext(scanner, OP_NEQ, 1, 2, 1, 2); checkNext(scanner, OP_EQ, 3, 2, 1, 4); checkNext(scanner, SEMI, 5, 1, 1, 6); checkNextIsEOF(scanner); } @Test public void testBraces() throws LexicalException { String input = "{}"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, LBRACE, 0, 1, 1, 1); checkNext(scanner, RBRACE, 1, 1, 1, 2); checkNextIsEOF(scanner); } @Test public void testSquareBraces() throws LexicalException { String input = "[]"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, LSQUARE, 0, 1, 1, 1); checkNext(scanner, RSQUARE, 1, 1, 1, 2); checkNextIsEOF(scanner); } @Test public void testComma() throws LexicalException { String input = ",;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, COMMA, 0, 1, 1, 1); checkNext(scanner, SEMI, 1, 1, 1, 2); checkNextIsEOF(scanner); } @Test public void testQuestion() throws LexicalException { String input = "?;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, OP_QUESTION, 0, 1, 1, 1); checkNext(scanner, SEMI, 1, 1, 1, 2); checkNextIsEOF(scanner); } @Test public void testAnd() throws LexicalException { String input = "&;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, OP_AND, 0, 1, 1, 1); checkNext(scanner, SEMI, 1, 1, 1, 2); checkNextIsEOF(scanner); } @Test public void testOr() throws LexicalException { String input = "|;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, OP_OR, 0, 1, 1, 1); checkNext(scanner, SEMI, 1, 1, 1, 2); checkNextIsEOF(scanner); } @Test public void testPlus() throws LexicalException { String input = "+;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, OP_PLUS, 0, 1, 1, 1); checkNext(scanner, SEMI, 1, 1, 1, 2); checkNextIsEOF(scanner); } @Test public void testMinus() throws LexicalException { String input = "-;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, OP_MINUS, 0, 1, 1, 1); checkNext(scanner, SEMI, 1, 1, 1, 2); checkNextIsEOF(scanner); } @Test public void testMod() throws LexicalException { String input = "%;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, OP_MOD, 0, 1, 1, 1); checkNext(scanner, SEMI, 1, 1, 1, 2); checkNextIsEOF(scanner); } @Test public void testAt() throws LexicalException { String input = "@;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, OP_AT, 0, 1, 1, 1); checkNext(scanner, SEMI, 1, 1, 1, 2); checkNextIsEOF(scanner); } @Test public void testZero() throws LexicalException { String input = "0;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, INTEGER_LITERAL, 0, 1, 1, 1); checkNext(scanner, SEMI, 1, 1, 1, 2); checkNextIsEOF(scanner); } @Test public void testNonZero() throws LexicalException { String input = "1234;"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, INTEGER_LITERAL, 0, 4, 1, 1); checkNext(scanner, SEMI, 4, 1, 1, 5); checkNextIsEOF(scanner); } @Test public void testDigits() throws LexicalException { String input = "01230"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, INTEGER_LITERAL, 0, 1, 1, 1); checkNext(scanner, INTEGER_LITERAL, 1, 4, 1, 2); checkNextIsEOF(scanner); } @Test public void testIntegerLiteralOutOfRange() throws LexicalException { String input = "4294967296"; show(input); thrown.expect(LexicalException.class); try { new Scanner(input).scan(); } catch (LexicalException e) { show(e); assertEquals(0, e.getPos()); throw e; } } @Test public void testMultipleZeros() throws LexicalException { String input = "00"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, INTEGER_LITERAL, 0, 1, 1, 1); checkNext(scanner, INTEGER_LITERAL, 1, 1, 1, 2); checkNextIsEOF(scanner); } @Test public void testSingleAlphabet() throws LexicalException { String input = "a"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, IDENTIFIER, 0, 1, 1, 1); checkNextIsEOF(scanner); } @Test public void testAlphabets() throws LexicalException { String input = "meh meh booo0"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, IDENTIFIER, 0, 3, 1, 1); checkNext(scanner, IDENTIFIER, 4, 3, 1, 5); checkNext(scanner, IDENTIFIER, 8, 5, 1, 9); checkNextIsEOF(scanner); } @Test public void testInvalidIdentifier() throws LexicalException { String input = "$abc"; show(input); thrown.expect(LexicalException.class); try { new Scanner(input).scan(); } catch (LexicalException e) { show(e); assertEquals(0, e.getPos()); throw e; } } @Test public void testInvalidIdentifierStart() throws LexicalException { String input = "_123"; show(input); thrown.expect(LexicalException.class); try { new Scanner(input).scan(); } catch (LexicalException e) { show(e); assertEquals(0, e.getPos()); throw e; } } @Test public void testInvalidIdentifierStartDollar() throws LexicalException { String input = "$123"; show(input); thrown.expect(LexicalException.class); try { new Scanner(input).scan(); } catch (LexicalException e) { show(e); assertEquals(0, e.getPos()); throw e; } } @Test public void testInvalidIdentifierUnderscore() throws LexicalException { String input = "123_"; show(input); thrown.expect(LexicalException.class); try { new Scanner(input).scan(); } catch (LexicalException e) { show(e); assertEquals(3, e.getPos()); throw e; } } @Test public void testInvalidIdentifierDollar() throws LexicalException { String input = "123$"; show(input); thrown.expect(LexicalException.class); try { new Scanner(input).scan(); } catch (LexicalException e) { show(e); assertEquals(3, e.getPos()); throw e; } } @Test public void testInvalidIdentUnderscoreMid() throws LexicalException { String input = "123_a"; show(input); thrown.expect(LexicalException.class); try { new Scanner(input).scan(); } catch (LexicalException e) { show(e); assertEquals(3, e.getPos()); throw e; } } @Test public void testInvalidIdentDollarMid() throws LexicalException { String input = "123$a"; show(input); thrown.expect(LexicalException.class); try { new Scanner(input).scan(); } catch (LexicalException e) { show(e); assertEquals(3, e.getPos()); throw e; } } @Test public void testValidIdentifier() throws LexicalException { String input = "meh_meh booo0"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, IDENTIFIER, 0, 7, 1, 1); checkNext(scanner, IDENTIFIER, 8, 5, 1, 9); checkNextIsEOF(scanner); } @Test public void testValidIdentifierDollar() throws LexicalException { String input = "meh$meh booo0"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, IDENTIFIER, 0, 7, 1, 1); checkNext(scanner, IDENTIFIER, 8, 5, 1, 9); checkNextIsEOF(scanner); } @Test public void testLiteralIdentifier() throws LexicalException { String input = "123booo0"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, INTEGER_LITERAL, 0, 3, 1, 1); checkNext(scanner, IDENTIFIER, 3, 5, 1, 4); checkNextIsEOF(scanner); } @Test public void testIdentifier() throws LexicalException { String input = "booo01256ab"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, IDENTIFIER, 0, 11, 1, 1); checkNextIsEOF(scanner); } @Test public void testIdentifierLiteral() throws LexicalException { String input = "0123booo"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, INTEGER_LITERAL, 0, 1, 1, 1); checkNext(scanner, INTEGER_LITERAL, 1, 3, 1, 2); checkNext(scanner, IDENTIFIER, 4, 4, 1, 5); checkNextIsEOF(scanner); } @Test public void testKeyword() throws LexicalException { String input = "0123while"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, INTEGER_LITERAL, 0, 1, 1, 1); checkNext(scanner, INTEGER_LITERAL, 1, 3, 1, 2); checkNext(scanner, KW_while, 4, 5, 1, 5); checkNextIsEOF(scanner); } @Test public void testKeywordIdent() throws LexicalException { String input = "0123whiletrue"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, INTEGER_LITERAL, 0, 1, 1, 1); checkNext(scanner, INTEGER_LITERAL, 1, 3, 1, 2); checkNext(scanner, IDENTIFIER, 4, 9, 1, 5); checkNextIsEOF(scanner); } @Test public void testBooleanLiteral() throws LexicalException { String input = "0123true"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, INTEGER_LITERAL, 0, 1, 1, 1); checkNext(scanner, INTEGER_LITERAL, 1, 3, 1, 2); checkNext(scanner, BOOLEAN_LITERAL, 4, 4, 1, 5); checkNextIsEOF(scanner); } @Test public void testBooleanIdent() throws LexicalException { String input = "0123trueif"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, INTEGER_LITERAL, 0, 1, 1, 1); checkNext(scanner, INTEGER_LITERAL, 1, 3, 1, 2); checkNext(scanner, IDENTIFIER, 4, 6, 1, 5); checkNextIsEOF(scanner); } @Test public void testDot() throws LexicalException { String input = "."; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, DOT, 0, 1, 1, 1); checkNextIsEOF(scanner); } @Test public void testFloatZeroBefore() throws LexicalException { String input = "0."; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, FLOAT_LITERAL, 0, 2, 1, 1); checkNextIsEOF(scanner); } @Test public void testFloatZeroAfter() throws LexicalException { String input = ".0"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, FLOAT_LITERAL, 0, 2, 1, 1); checkNextIsEOF(scanner); } @Test public void testFloatZero() throws LexicalException { String input = "0.0"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, FLOAT_LITERAL, 0, 3, 1, 1); checkNextIsEOF(scanner); } @Test public void testFloatNonZeroBefore() throws LexicalException { String input = "8."; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, FLOAT_LITERAL, 0, 2, 1, 1); checkNextIsEOF(scanner); } @Test public void testFloatNonZeroAfter() throws LexicalException { String input = ".8"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, FLOAT_LITERAL, 0, 2, 1, 1); checkNextIsEOF(scanner); } @Test public void testFloatNonZero() throws LexicalException { String input = "19.0"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, FLOAT_LITERAL, 0, 4, 1, 1); checkNextIsEOF(scanner); } @Test public void testLiteralAndNonZeroFloat() throws LexicalException { String input = "01.23"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, INTEGER_LITERAL, 0, 1, 1, 1); checkNext(scanner, FLOAT_LITERAL, 1, 4, 1, 2); checkNextIsEOF(scanner); } @Test public void testLiteralZeroFloat() throws LexicalException { String input = "00."; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, INTEGER_LITERAL, 0, 1, 1, 1); checkNext(scanner, FLOAT_LITERAL, 1, 2, 1, 2); checkNextIsEOF(scanner); } @Test public void testLiteralFloat() throws LexicalException { String input = "01."; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, INTEGER_LITERAL, 0, 1, 1, 1); checkNext(scanner, FLOAT_LITERAL, 1, 2, 1, 2); checkNextIsEOF(scanner); } @Test public void testFloatDot() throws LexicalException { String input = ".333."; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, FLOAT_LITERAL, 0, 4, 1, 1); checkNext(scanner, DOT, 4, 1, 1, 5); checkNextIsEOF(scanner); } @Test public void testFloatOutOfRange() throws LexicalException { String input = "999999999999999999999999999999999999999999999999999.999990000"; show(input); thrown.expect(LexicalException.class); try { new Scanner(input).scan(); } catch (LexicalException e) { show(e); assertEquals(0, e.getPos()); throw e; } } @Test public void testTimesPower() throws LexicalException { String input = "***"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, OP_POWER, 0, 2, 1, 1); checkNext(scanner, OP_TIMES, 2, 1, 1, 3); checkNextIsEOF(scanner); } @Test public void testTimesDiv() throws LexicalException { String input = "***/"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, OP_POWER, 0, 2, 1, 1); checkNext(scanner, OP_TIMES, 2, 1, 1, 3); checkNext(scanner, OP_DIV, 3, 1, 1, 4); checkNextIsEOF(scanner); } @Test public void testEmptyComment() throws LexicalException { String input = "/**/"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNextIsEOF(scanner); } @Test public void testInvalidComment() throws LexicalException { String input = "/*/*"; show(input); thrown.expect(LexicalException.class); try { new Scanner(input).scan(); } catch (LexicalException e) { show(e); assertEquals(0, e.getPos()); throw e; } } @Test public void testValidComment() throws LexicalException { String input = "/*ABC*def/****/"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNextIsEOF(scanner); } @Test public void testCommentWithStar() throws LexicalException { String input = "/***/"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNextIsEOF(scanner); } @Test public void testCommentWithNextLine() throws LexicalException { String input = "/**\n*/*abc"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, OP_TIMES, 6, 1, 2, 3); checkNext(scanner, IDENTIFIER, 7, 3, 2, 4); checkNextIsEOF(scanner); } @Test public void testNestedComment() throws LexicalException { String input = "/*/**/*/"; Scanner scanner = new Scanner(input).scan(); show(input); show(scanner); checkNext(scanner, OP_TIMES, 6, 1, 1, 7); checkNext(scanner, OP_DIV, 7, 1, 1, 8); checkNextIsEOF(scanner); } @Test public void testNestedComment2() throws LexicalException { String input = "/**/**/*/"; show(input); thrown.expect(LexicalException.class); try { new Scanner(input).scan(); } catch (LexicalException e) { show(e); assertEquals(6, e.getPos()); throw e; } } }
31.175944
114
0.556962
90a36eb558fc2bb200446fad71c215edb9b9209f
389
package nl.vs.fuse.demo.configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.Configuration; /** * This empty class only loads the imported bean configuration file into the application context */ @Configuration @ImportResource("classpath:spring/util-observability.xml") public class ObservabilityConfiguration{ };
27.785714
97
0.822622
14fe1de43394bdd4339b874467e622eac19f01ca
823
package de.unipaderborn.visuflow.debug.handlers; import java.util.Collections; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.osgi.service.event.Event; import org.osgi.service.event.EventAdmin; import de.unipaderborn.visuflow.VisuflowConstants; import de.unipaderborn.visuflow.util.ServiceUtil; public class DebugStepBackHandler extends org.eclipse.core.commands.AbstractHandler implements VisuflowConstants { @Override public Object execute(ExecutionEvent event) throws ExecutionException { EventAdmin ea = ServiceUtil.getService(EventAdmin.class); Event stepOver = new Event(EA_TOPIC_DEBUGGING_ACTION_STEP_BACK, Collections.emptyMap()); ea.sendEvent(stepOver); // has to be null (see javadoc) return null; } }
31.653846
115
0.793439
9922656bc22f33c5ffa24b1f676e39ff416cb101
1,962
/* * 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.beam.runners.flink.translation.utils; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; import org.apache.beam.runners.core.metrics.DistributionCell; /** Helpers for reporting checkpoint durations. */ public class CheckpointStats { /** Checkpoint id => Checkpoint start (System.currentTimeMillis()). */ private final Map<Long, Long> checkpointDurations = new HashMap<>(); /** Distribution cell for reporting checkpoint durations. */ private final Supplier<DistributionCell> distributionCellSupplier; public CheckpointStats(Supplier<DistributionCell> distributionCellSupplier) { this.distributionCellSupplier = distributionCellSupplier; } public void snapshotStart(long checkpointId) { checkpointDurations.put(checkpointId, System.currentTimeMillis()); } public void reportCheckpointDuration(long checkpointId) { Long checkpointStart = checkpointDurations.remove(checkpointId); if (checkpointStart != null) { long checkpointDuration = System.currentTimeMillis() - checkpointStart; distributionCellSupplier.get().update(checkpointDuration); } } }
40.040816
79
0.766565
c409ecfdf9fd6841454989db14217a43248023bb
512
package com.livebet.domain.operation; @Deprecated public class ChangeQuotesResponse implements GenericResponse { /** * */ private static final long serialVersionUID = -3660256240475168010L; private boolean result; private String cause; public boolean isResult() { return result; } public void setResult(boolean result) { this.result = result; } public String getCause() { return cause; } public void setCause(String cause) { this.cause = cause; } }
16.516129
69
0.681641
fd2488378d3d62c7e1e828b77ecde0b6de4d368d
4,466
package edu.ucdenver.ccp.datasource.fileparsers.obo; /* * #%L * Colorado Computational Pharmacology's common module * %% * Copyright (C) 2012 - 2015 Regents of the University of Colorado * %% * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * #L% */ import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import edu.ucdenver.ccp.common.reflection.ConstructorUtil; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.MolecularInteractionOntologyTermID; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Some databases used MI:0000 as a placeholder and attach a specific term name * to it, e.g. in IRefWeb there is both MI:0000(BIND_Translation) and * MI:0000(unspecified). This record allows for the ID and term name to be * paired. * * @author Center for Computational Pharmacology, UC Denver; * [email protected] * */ // @Record(dataSource = DataSource.MI_ONTOLOGY) @EqualsAndHashCode @ToString public abstract class MiOntologyIdTermPair { private static final Logger logger = Logger.getLogger(MiOntologyIdTermPair.class); private final MolecularInteractionOntologyTermID id; private final String termName; /** * @param id * @param termName */ public MiOntologyIdTermPair(MolecularInteractionOntologyTermID id, String termName) { super(); this.id = id; this.termName = termName; } public MiOntologyIdTermPair(MolecularInteractionOntologyTermID id) { super(); this.id = id; this.termName = null; } /** * @return the id */ protected MolecularInteractionOntologyTermID getId() { return id; } /** * @return the termName */ protected String getTermName() { return termName; } /** * @param input * @return parses Strings of the form "MI:0326(protein)" and returns a * {@link MiOntologyIdTermPair} */ public static <T extends MiOntologyIdTermPair> T parseString(Class<T> miIdTermPairClass, String input) { Pattern methodIDPattern = Pattern.compile("(MI:\\d+),?\\((.*?)\\)"); Matcher m = methodIDPattern.matcher(input); if (m.find()) { return (T) ConstructorUtil.invokeConstructor(miIdTermPairClass.getName(), new MolecularInteractionOntologyTermID(m.group(1)), m.group(2)); // return new MiOntologyIdTermPair(new // MolecularInteractionOntologyTermID(m.group(1)), // m.group(2)); } methodIDPattern = Pattern.compile("psi-mi:\"(MI:\\d+)\",?\\((.*?)\\)"); m = methodIDPattern.matcher(input); if (m.find()) { String miId = m.group(1); String name = (m.group(2).equals("-")) ? null : m.group(2); if (name != null) { return (T) ConstructorUtil.invokeConstructor(miIdTermPairClass.getName(), new MolecularInteractionOntologyTermID(miId), name); } return (T) ConstructorUtil.invokeConstructor(miIdTermPairClass.getName(), new MolecularInteractionOntologyTermID(miId)); } logger.warn("Unable to extract MiOntologyIdTermPair from: " + input); return null; } }
34.620155
105
0.734438
2ed69acf1de2cdc7539dd75d42a85ef61a138e85
557
package mat; /** * Created by Mateusz on 21.05.2017. */ enum Direction { UP { @Override Direction opposite() { return DOWN; } }, DOWN { @Override Direction opposite() { return UP; } }, LEFT { @Override Direction opposite() { return RIGHT; } }, RIGHT { @Override Direction opposite() { return LEFT; } }; abstract Direction opposite(); }
15.472222
37
0.409336
f15dda8b03166255b1f70429defa73a3c303b069
6,710
/* PROJECT GOALS -Use Parse to set up a backend that will allow users to authenticate -Utilize Parse server to store user data and post data in a database -Develop an app that will allow users to (1) create new account, (2) log in/out (3) create a post -Use the camera API to allow users to take/upload photos with their device BRAINSTORM -LoginActivity, SignUpActivity??, MainActivity, PostActivity -Gotta setup layout of menu and/or bottom bar -Get IG resources imported and setup -Handle basic logic to facilitate posting */ package com.example.instagramemulator; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.FileProvider; import androidx.fragment.app.FragmentManager; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.Menu; import android.widget.Toast; import com.google.android.material.bottomnavigation.BottomNavigationView; import java.io.ByteArrayOutputStream; import java.io.File; public class MainActivity extends AppCompatActivity { public static final String TAG = "MAIN_ACTIVITY"; public static final int CAMERA_REQUEST_CODE = 666; BottomNavigationView bottomNavigation; FragmentManager fragmentManager = getSupportFragmentManager(); String photoFileName = "photo.jpg"; File photoFile; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setLogo(R.drawable.instagram_logo); //Add the TimelineFragment to the activity upon first startup if(savedInstanceState == null) { fragmentManager.beginTransaction() .setReorderingAllowed(true) .add(R.id.fragmentPrimary, TimelineFragment.class, null) .commit(); } bottomNavigation = findViewById(R.id.btmNavigation); bottomNavigation.getMenu().getItem(0).setIcon(R.drawable.ic_home_filled); bottomNavigation.setOnNavigationItemSelectedListener(item -> { switch (item.getItemId()) { case R.id.icHome: fragmentManager.beginTransaction() .setReorderingAllowed(true) .replace(R.id.fragmentPrimary, TimelineFragment.class, null) .commit(); bottomNavigation.getMenu().getItem(0).setIcon(R.drawable.ic_home_filled); bottomNavigation.getMenu().getItem(1).setIcon(R.drawable.ic_post_outline); bottomNavigation.getMenu().getItem(2).setIcon(R.drawable.ic_profile_outline); break; case R.id.icPost: if(R.id.icPost != bottomNavigation.getSelectedItemId()) { Log.i(TAG, "Post icon selected; opening camera"); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); photoFile = getPhotoFileUri(photoFileName); Uri fileProvider = FileProvider.getUriForFile(MainActivity.this, "com.codepath.fileprovider", photoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider); if(intent.resolveActivity(getPackageManager()) != null) { try { startActivityForResult(intent, CAMERA_REQUEST_CODE); } catch (Exception e) { e.printStackTrace(); } } } break; case R.id.icProfile: if(R.id.icProfile != bottomNavigation.getSelectedItemId()) { Log.i(TAG, "Profile icon selected; switching to ProfileFragment"); fragmentManager.beginTransaction() .setReorderingAllowed(true) .replace(R.id.fragmentPrimary, ProfileFragment.class, null) .commit(); bottomNavigation.getMenu().getItem(0).setIcon(R.drawable.ic_home_outline); bottomNavigation.getMenu().getItem(1).setIcon(R.drawable.ic_post_outline); bottomNavigation.getMenu().getItem(2).setIcon(R.drawable.ic_profile_filled); } break; } return true; }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == CAMERA_REQUEST_CODE) { if(resultCode == RESULT_OK) { Bitmap takenImage = BitmapFactory.decodeFile(photoFile.getAbsolutePath()); takenImage = BitmapScaler.scaleToFitWidth(takenImage, 800); ByteArrayOutputStream bs = new ByteArrayOutputStream(); takenImage.compress(Bitmap.CompressFormat.JPEG, 50, bs); try { Log.i(TAG, "Have picture; starting PostFragment"); Bundle bundle = new Bundle(); bundle.putByteArray("photo", bs.toByteArray()); bundle.putString("photoFilePath", photoFile.getAbsolutePath()); fragmentManager.beginTransaction() .replace(R.id.fragmentPrimary, PostFragment.class, bundle) .setReorderingAllowed(true) .commit(); } catch (Exception e) { e.printStackTrace(); } } else { Toast.makeText(this, "Error taking photo", Toast.LENGTH_SHORT).show(); } } } public File getPhotoFileUri(String fileName) { File mediaStorageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), TAG); if(!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) Log.e(TAG, "Failed to create directory"); File file = new File(mediaStorageDir.getPath() + File.separator + fileName); return file; } }
43.290323
129
0.604769
e2e3bbcf04415acb6f3d8987b47f82a11dddbf44
1,476
package com.github.vanroy.springdata.jest.mapper; import com.github.vanroy.springdata.jest.exception.JestElasticsearchException; import com.google.gson.JsonPrimitive; import io.searchbox.action.Action; import io.searchbox.client.JestResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Default implementation for ErrorMapper. * * @author Julien Roy */ public class DefaultErrorMapper implements ErrorMapper { private static final Logger logger = LoggerFactory.getLogger(DefaultErrorMapper.class); @Override public void mapError(Action action, JestResult result, boolean acceptNotFound) { if (!result.isSucceeded()) { String errorMessage = String.format("Cannot execute jest action , response code : %s , error : %s , message : %s", result.getResponseCode(), result.getErrorMessage(), getMessage(result)); if (acceptNotFound && isSuccessfulResponse(result.getResponseCode())) { logger.debug(errorMessage); } else { logger.error(errorMessage); throw new JestElasticsearchException(errorMessage, result); } } } private static <T extends JestResult> String getMessage(T result) { if (result.getJsonObject() == null) { return null; } JsonPrimitive message = result.getJsonObject().getAsJsonPrimitive("message"); if (message == null) { return null; } return message.getAsString(); } private static boolean isSuccessfulResponse(int statusCode) { return statusCode < 300 || statusCode == 404; } }
29.52
190
0.747967
9204f5ddbb22d7e06dca0ad3671c8bd9d8f638dd
1,309
/* * 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 br.senac.tads4.dsw.servletjsp.servlet; import br.senac.tads4.dsw.servletjsp.modelo.Pessoa; import br.senac.tads4.dsw.servletjsp.service.PessoaService; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Fernando */ @WebServlet(name = "ListaPessoasServlet", urlPatterns = {"/lista-pessoas"}) public class ListaPessoasServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PessoaService service = new PessoaService(); // Lista todas as pessoas cadastradas List<Pessoa> lista = service.listar(); request.setAttribute("listaAtrib", lista); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/lista.jsp"); dispatcher.forward(request, response); } }
34.447368
91
0.75783
ee058881c3d4c60eb8457d78da37bca1ed05068f
982
Check if a LinkedList is palindrome or not. Given the head of a singly linked list, return true if it is a palindrome. /* Example 1: Input: head = [1,2,2,1] Output: true Example 2: Input: head = [1,2] Output: false */ Method 1: Brute Force Time Complexity : O(n) Space Complexity: O(n) Code: static boolean isPalindrome(Node head) { Node slow = head; boolean ispalin = true; Stack<Integer> stack = new Stack<Integer>(); while (slow != null) { stack.push(slow.data); slow = slow.ptr; } while (head != null) { int i = stack.pop(); if (head.data == i) { ispalin = true; } else { ispalin = false; break; } head = head.ptr; } return ispalin; } Method 2: Better approach https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
19.64
86
0.53666
4aaed2d9456de9de36e976483c06a99f367aaec8
6,093
package edu.kit.exp.server.structure; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.sql.SQLException; import edu.kit.exp.server.communication.ClientDataPropertiesMessage; import edu.kit.exp.server.communication.ClientDataTransmissionMessage; import edu.kit.exp.server.jpa.DataManagementException; import edu.kit.exp.server.jpa.dao.MeasurementDataDAO; import edu.kit.exp.server.jpa.entity.MeasurementData; import edu.kit.exp.server.run.LoggedQueue; import edu.kit.exp.server.run.QueueManager; import edu.kit.exp.server.run.RunStateLogEntry; import edu.kit.exp.server.run.RunStateLogger; import edu.kit.exp.common.Constants; /** * Handels receipt of a data transmission by popping messages from the * DataTransmissionQueue * * @author Tonda */ public class ServerDataTransmissionManagement { private static final String DATABASE_OUTPUT_MESSAGE = "Write to Database"; private static final String CLIENT_AND_FILE_NUMBER_FORMAT = "%1$s (%2$s/%3$s)"; private static ServerDataTransmissionManagement instance = null; private LoggedQueue<ClientDataPropertiesMessage> dataPropertiesQueue = QueueManager.getClientDataPropertiesQueueInstance(); private LoggedQueue<ClientDataTransmissionMessage> dataMessageQueue = QueueManager.getDataTransmissionQueueInstance(); private RunStateLogger runStateLogger = RunStateLogger.getInstance(); private MeasurementDataDAO measurementDataDao = new MeasurementDataDAO(); private FileOutputStream fileOutputStream; private TransmissionLogger logger; private String clientId; private long totalBytesRead; private long fileSizeInBytes; private int fileIndex; private int totalNumberOfFiles; private ServerDataTransmissionManagement() { } /** * return Singleton instance */ public static ServerDataTransmissionManagement getInstance() { if (instance == null) { instance = new ServerDataTransmissionManagement(); } return instance; } /** * Starts the receipt of messages before saving it to the database * * @throws DataManagementException * @throws IOException * @throws SQLException */ public void receive(String clientId, String subjectId) throws DataManagementException, IOException, SQLException { this.clientId = clientId; ClientDataPropertiesMessage properties = receiveDataProperties(); String[] fileNames = properties.getFileNames(); totalNumberOfFiles = fileNames.length; for (fileIndex = 0; fileIndex < totalNumberOfFiles; fileIndex++) { calculateInitialValues(properties); long startTimeStamp = properties.getStartTimeStamps()[fileIndex]; long stopTimeStamp = properties.getStopTimeStamps()[fileIndex]; receiveSingleFile(fileNames[fileIndex]); saveFileToDatabase(subjectId, fileNames[fileIndex], startTimeStamp, stopTimeStamp); } } private ClientDataPropertiesMessage receiveDataProperties() { ClientDataPropertiesMessage properties = null; while (properties == null) { properties = dataPropertiesQueue.pop(); } return properties; } private void saveFileToDatabase(String subjectId, String fileName, long startTimeStamp, long stopTimeStamp) throws DataManagementException, IOException, SQLException { RunStateLogEntry logEntry = new RunStateLogEntry(clientId, DATABASE_OUTPUT_MESSAGE, String.format(CLIENT_AND_FILE_NUMBER_FORMAT, shortenFileName(fileName), fileIndex + 1, totalNumberOfFiles), "In Progress"); runStateLogger.createOutputMessage(logEntry); measurementDataDao.createMeasurementData(createMeasurementDataObject(fileName, subjectId, startTimeStamp, stopTimeStamp), createFileInputStream(fileName)); logEntry = new RunStateLogEntry(clientId, DATABASE_OUTPUT_MESSAGE, String.format(CLIENT_AND_FILE_NUMBER_FORMAT, shortenFileName(fileName), fileIndex + 1, totalNumberOfFiles), "Finished"); logEntry.setOverwriteLatestEntry(true); runStateLogger.createOutputMessage(logEntry); } public static String shortenFileName(String fileName) { if (fileName.length() >= 10) { fileName = fileName.substring(0, 7) + "..."; } return fileName; } private MeasurementData createMeasurementDataObject(String fileName, String subjectId, long startTimeStamp, long stopTimeStamp) { return new MeasurementData(fileName, clientId, subjectId, startTimeStamp, stopTimeStamp); } private FileInputStream createFileInputStream(String fileName) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(new File(Constants.FILE_PREFIX_SERVER + fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } return fileInputStream; } private void receiveSingleFile(String fileName) throws IOException { logger = new TransmissionLogger(this, fileName); logger.start(); int packageNumber = 1; boolean isLast = false; while (isLast == false) { ClientDataTransmissionMessage message = dataMessageQueue.pop(); if (message.getPackageNumber() == -1) { writeBytesToFile(message.getData()); isLast = true; } else if (message.getFileNumber() == (fileIndex + 1) && message.getPackageNumber() == packageNumber) { writeBytesToFile(message.getData()); packageNumber++; } } fileOutputStream.flush(); fileOutputStream.close(); logger.end(); } private void calculateInitialValues(ClientDataPropertiesMessage properties) throws FileNotFoundException { fileSizeInBytes = properties.getFileSizes()[fileIndex]; String fileName = properties.getFileNames()[fileIndex]; fileOutputStream = new FileOutputStream(new File(Constants.FILE_PREFIX_SERVER + fileName)); } private void writeBytesToFile(byte[] data) throws IOException { totalBytesRead += data.length; fileOutputStream.write(data); fileOutputStream.flush(); } public long getTotalBytesRead() { return totalBytesRead; } public long getFileSizeInBytes() { return fileSizeInBytes; } public String getClientId() { return clientId; } public int getFileNumber() { return fileIndex; } public int getTotalNumberOfFiles() { return totalNumberOfFiles; } }
35.017241
209
0.787133
5ade0ceb13037823185e1fc6de3d2fdea380914b
1,434
package com.coinninja.coinkeeper.service.client.model; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class CNDeviceTest { @Test public void convert_string_to_DevicePlatform_enum_for_android_test() { CNDevice cnDevice = new CNDevice(); cnDevice.devicePlatform = "android"; CNDevice.DevicePlatform platForm = cnDevice.getPlatform(); assertThat(platForm, equalTo(CNDevice.DevicePlatform.ANDROID)); } @Test public void convert_string_to_DevicePlatform_enum_for_ios_test() { CNDevice cnDevice = new CNDevice(); cnDevice.devicePlatform = "ios"; CNDevice.DevicePlatform platForm = cnDevice.getPlatform(); assertThat(platForm, equalTo(CNDevice.DevicePlatform.IOS)); } @Test public void when_device_platform_string_is_null_return_null() { CNDevice cnDevice = new CNDevice(); cnDevice.devicePlatform = null; CNDevice.DevicePlatform platForm = cnDevice.getPlatform(); assertThat(platForm, equalTo(null)); } @Test public void when_device_platform_string_is_of_unknown_type_return_null() { CNDevice cnDevice = new CNDevice(); cnDevice.devicePlatform = "windows phone"; CNDevice.DevicePlatform platForm = cnDevice.getPlatform(); assertThat(platForm, equalTo(null)); } }
28.117647
78
0.711994
37491c42add288fcb26b0e785fd612fe257f3d76
483
public VanillaTaxes implements FriendlyIRS { public double taxPerson(Person p) {return 1;} public double taxCompany(Company c){ double total = 0; for (int i = 0; i < c.getSize(); i++) total += c.getEmployee(i).accept(this); return total; } public double taxRegion(Region r){ double total = 0; for (int i = 0; i < r.getSize(); i++) total += r.getCompany(i).accept(this); return total; } }
25.421053
51
0.556936
a45b7a55c1a2ac51e1f1f0430e68743975632ac6
157
package com.test.dynamic_proxy_hook.static_proxy; /** * Created by wzc on 2017/6/12. */ public interface Shopping { String doShopping(long money); }
15.7
49
0.719745
05bbaf38d79724ec1b7cda8ba62c754c69606966
2,286
package timing.ukulele.service.auth.token; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import timing.ukulele.common.util.JsonUtils; import timing.ukulele.data.user.view.UserVO; import timing.ukulele.service.auth.BaseUserDetail; import timing.ukulele.service.auth.Constant; import java.util.Map; /** * 自定义JwtAccessToken转换器 * @author fengxici */ public class JwtAccessToken extends JwtAccessTokenConverter { /** * 生成token * * @param accessToken * @param authentication * @return */ @Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { DefaultOAuth2AccessToken defaultOAuth2AccessToken = new DefaultOAuth2AccessToken(accessToken); //客户端模式不包含用户信息 if (authentication.getPrincipal() instanceof BaseUserDetail) { // 设置额外用户信息 UserVO baseUser = ((BaseUserDetail) authentication.getPrincipal()).getBaseUser(); baseUser.setPassword(null); // 将用户信息添加到token额外信息中 defaultOAuth2AccessToken.getAdditionalInformation().put(Constant.USER_INFO, baseUser); } return super.enhance(defaultOAuth2AccessToken, authentication); } /** * 解析token * * @param value * @param map * @return */ @Override public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) { OAuth2AccessToken oauth2AccessToken = super.extractAccessToken(value, map); convertData(oauth2AccessToken, oauth2AccessToken.getAdditionalInformation()); return oauth2AccessToken; } private void convertData(OAuth2AccessToken accessToken, Map<String, ?> map) { accessToken.getAdditionalInformation().put(Constant.USER_INFO, convertUserData(map.get(Constant.USER_INFO))); } private UserVO convertUserData(Object map) { String json = JsonUtils.deserializer(map); UserVO user = JsonUtils.serializable(json, UserVO.class); return user; } }
34.636364
117
0.725722
cb78f6e1d21cd75a9afd9e899ee97aee28eba49f
644
package com.github.thomasfischl.eurydome.backend.dal; import org.springframework.stereotype.Service; import com.github.thomasfischl.eurydome.backend.model.DOService; import com.mongodb.BasicDBObject; @Service public class ServiceDataStore extends AbstractDataStore<DOService> { @Override protected String getCollectionName() { return "service"; } @Override protected DOService createEmptyDomainObject() { DOService service = new DOService(); service.setStatus(DOService.STOPPED); return service; } @Override protected DOService createDomainObject(BasicDBObject obj) { return new DOService(obj); } }
22.206897
68
0.768634
862fbfec516f3237318063bad729ee35826811b7
224
package com.systemmeltdown.robotlib.sensors; import edu.wpi.first.wpilibj.Sendable; /** * Base Sensor Class * * This is the base class for all kinds of sensors */ public abstract class Sensor implements Sendable { }
17.230769
50
0.745536
344585259e38e067bdcf5f96d036a6fdf6445f56
2,512
package biggerfish.ai; import cage.core.scene.Node; import cage.core.scene.SceneManager; import cage.core.scene.SceneNode; import org.joml.Random; import org.joml.Vector3f; import org.joml.Vector3fc; public class AISchoolNode extends SceneNode { private Vector3f origin; private float originRadius; private Vector3f[] offset; private float offsetRadius; private int fishCount; private int type; private float tickTime; private float maxTickTime; public AISchoolNode(SceneManager sceneManager, Node parent, int type, Vector3fc origin, float originRadius, int fishCount, float offsetRadius, Random random) { super(sceneManager, parent); this.origin = new Vector3f(origin); this.originRadius = originRadius; this.offsetRadius = offsetRadius; this.fishCount = fishCount; this.type = type; this.tickTime = 0.0f; this.maxTickTime = 0.0f; this.offset = new Vector3f[fishCount]; for(int i=0; i<fishCount; ++i) { this.offset[i] = new Vector3f(random.nextFloat(), random.nextFloat(), random.nextFloat()).mul(2.0f).sub(1.0f, 1.0f, 1.0f).mul(offsetRadius, offsetRadius, offsetRadius); } } public Vector3fc getOffset(int index) { return offset[index]; } public Vector3fc getOrigin() { return origin; } public void setOrigin(Vector3fc origin) { this.origin.set(origin); } public float getOriginRadius() { return originRadius; } public void setOriginRadius(float originRadius) { this.originRadius = originRadius; } public float getOffsetRadius() { return offsetRadius; } public void setOffsetRadius(float offsetRadius) { this.offsetRadius = offsetRadius; } public int getFishType() { return type; } public void setFishType(int type) { this.type = type; } public float getTickTime() { return tickTime; } public void setTickTime(float tickTime) { this.tickTime = tickTime; } public float getMaxTickTime() { return maxTickTime; } public void setMaxTickTime(float maxTickTime) { this.maxTickTime = maxTickTime; } public int getFishCount() { return fishCount; } public void setFishCount(int fishCount) { this.fishCount = fishCount; } }
25.896907
181
0.625796
99aba4053af8e0f1a40c9f7b00670c38e6af0156
539
package io.verticle.kubernetes.authgateway.route; import org.springframework.cloud.gateway.route.Route; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; @Component public class RuntimeRouteLocator implements RouteLocator { private Flux<Route> routes = Flux.empty(); @Override public Flux<Route> getRoutes() { return routes; } public void setRoutes(Flux<Route> routes) { this.routes = routes; } }
23.434783
60
0.74397
0b9b37ae12bc0bec6132d7e831223533f53799bc
999
package it.univpm.mobile_programming_project.utils.picker; import androidx.annotation.NonNull; import androidx.fragment.app.DialogFragment; import android.app.Dialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.text.format.DateFormat; import java.util.Calendar; import it.univpm.mobile_programming_project.R; public class TimePickerFragment extends DialogFragment { private final TimePickerDialog.OnTimeSetListener timeSetListener; public TimePickerFragment (TimePickerDialog.OnTimeSetListener timeSetListener) { this.timeSetListener = timeSetListener; } @NonNull public Dialog onCreateDialog (Bundle savedIstance) { final Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); return new TimePickerDialog(getActivity(), R.style.Theme_Widget_Dialog, this.timeSetListener, hour, minute, DateFormat.is24HourFormat(getActivity())); } }
31.21875
158
0.775776
f45bd6652d2c4a43a4653977af25997920a9cac6
15,720
/* * Copyright 2018 Google 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloudsearch.samples; // [START cloud_search_content_sdk_imports] import com.google.api.client.http.ByteArrayContent; import com.google.api.services.cloudsearch.v1.model.Item; import com.google.api.services.cloudsearch.v1.model.PushItem; import com.google.common.primitives.Longs; import com.google.enterprise.cloudsearch.sdk.CheckpointCloseableIterable; import com.google.enterprise.cloudsearch.sdk.CheckpointCloseableIterableImpl; import com.google.enterprise.cloudsearch.sdk.config.Configuration; import com.google.enterprise.cloudsearch.sdk.indexing.*; import com.google.enterprise.cloudsearch.sdk.indexing.template.*; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.logging.Logger; // [END cloud_search_content_sdk_imports] /** * A sample connector using the Cloud Search SDK. * * <p>This is a simplified sample connector that takes advantage of the * Cloud Search SDK. It illustrates using the listing connector template and * queues to detect changes and more efficiently indexing content vs. the * full traversal strategy. While the full set of documents are traversed * and queued, document content is only transmitted for new or modified * documents. * * <p>You must provide a configuration file for the connector. This * configuration file (for example: sample-config.properties) is supplied to * the connector via a command line argument: * * <pre>java com.google.cloudsearch.samples.ListTraversalSample \ * -Dconfig=sample-config.properties * </pre> * * <p>Sample properties file: * * <pre> * # Required properties for accessing data source * # (These values are created by the admin before running the connector) * api.sourceId=1234567890abcdef * api.serviceAccountPrivateKeyFile=./PrivateKey.json * * # This simple sample only needs to run one time and exit * connector.runOnce=true * * # These are used to schedule the traversals at fixed intervals * # For this sample, full traversals every 2 minutes * schedule.traversalIntervalSecs=120 * schedule.performTraversalOnStart=true * * # Number of synthetic documents to create * sample.documentCount=10 * </pre> */ public class ListTraversalSample { // [START cloud_search_content_sdk_main] /** * This sample connector uses the Cloud Search SDK template class for a * list traversal connector. * * @param args program command line arguments * @throws InterruptedException thrown if an abort is issued during initialization */ public static void main(String[] args) throws InterruptedException { Repository repository = new SampleRepository(); IndexingConnector connector = new ListingConnector(repository); IndexingApplication application = new IndexingApplication.Builder(connector, args).build(); application.start(); } // [END cloud_search_content_sdk_main] /** * Sample repository that indexes a set of synthetic documents. * <p> * By using the SDK provided connector templates, the only code required * from the connector developer are the methods from the {@link Repository} * class. These are used to perform the actual access of the data for * uploading via the API. */ public static class SampleRepository implements Repository { /** * Log output */ Logger log = Logger.getLogger(SampleRepository.class.getName()); /** * Number of synthetic documents to index. */ private int numberOfDocuments; /** * Tracks the state of synthetic documents between traversals. Maps the * document ID to a timestamp which is mutated between traversals and * used to dervive content hashes and document versions. */ private Map<Integer, Long> documents = new HashMap<>(); /** * High water mark for document IDs, used when generating additional * docs during mutations. */ private int lastDocumentId = 0; SampleRepository() { } /** * Performs any data repository initializations here. * * @param context the {@link RepositoryContext}, not used here */ @Override public void init(RepositoryContext context) { log.info("Initializing repository"); numberOfDocuments = Configuration.getInteger("sample.documentCount", 10).get(); } /** * Performs any data repository shut down code here. */ @Override public void close() { log.info("Closing repository"); } /** * Gets all of the existing document IDs from the data repository. * * <p>This method is called by {@link ListingConnector#traverse()} during * <em>full traversals</em>. Every document ID and metadata hash value in * the <em>repository</em> is pushed to the Cloud Search queue. Each pushed * document is later polled and processed in the {@link #getDoc(Item)} method. * <p> * The metadata hash values are pushed to aid document change detection. The * queue sets the document status depending on the hash comparison. If the * pushed ID doesn't yet exist in Cloud Search, the document's status is * set to <em>new</em>. If the ID exists but has a mismatched hash value, * its status is set to <em>modified</em>. If the ID exists and matches * the hash value, its status is unchanged. * * <p>In every case, the pushed content hash value is only used for * comparison. The hash value is only set in the queue during an * update (see {@link #getDoc(Item)}). * * @param checkpoint value defined and maintained by this connector * @return this is typically a {@link PushItems} instance */ @Override public CheckpointCloseableIterable<ApiOperation> getIds(byte[] checkpoint) { log.info("Pushing documents to index"); // prepare the data repository for the next simulated traversal mutate(); // [START cloud_search_content_sdk_push_ids] PushItems.Builder allIds = new PushItems.Builder(); for (Map.Entry<Integer, Long> entry : this.documents.entrySet()) { String documentId = Integer.toString(entry.getKey()); String hash = this.calculateMetadataHash(entry.getKey()); PushItem item = new PushItem().setMetadataHash(hash); log.info("Pushing " + documentId); allIds.addPushItem(documentId, item); } // [END cloud_search_content_sdk_push_ids] // [START cloud_search_content_sdk_checkpoint_iterator] ApiOperation pushOperation = allIds.build(); CheckpointCloseableIterable<ApiOperation> iterator = new CheckpointCloseableIterableImpl.Builder<>( Collections.singletonList(pushOperation)) .build(); return iterator; // [END cloud_search_content_sdk_checkpoint_iterator] } /** * Gets a single data repository document. * * <p>This method is called by the {@link ListingConnector} during a poll * of the Cloud Search queue. Each queued document is processed * individually depending on its state in the data repository: * * <ul> * <li>Missing: The document is no longer in the data repository, so it * is deleted from Cloud Search.</li> * <li>Unmodified: The document is already indexed and it has not changed, * so re-push with an unmodified status.</li> * <li>New or modified: The document is brand new, or has been modified * since it was indexed, so re-index it.</li> * </ul> * * <p>The metadata hash is sent during all <em>new</em> or <em>modified</em> * status document updates. This hash value is stored with the document * in the Cloud Search API queue for future comparisons of pushed * document IDs (see {@link #getIds(byte[])}). * * @param item the data repository document to retrieve * @return the document's state determines which type of * {@link ApiOperation} is returned: * {@link RepositoryDoc}, {@link DeleteItem}, or {@link PushItem} */ @Override public ApiOperation getDoc(Item item) { log.info(() -> String.format("Checking document %s", item.getName())); // [START cloud_search_content_sdk_deleted_item] String resourceName = item.getName(); int documentId = Integer.parseInt(resourceName); if (!documents.containsKey(documentId)) { // Document no longer exists -- delete it log.info(() -> String.format("Deleting document %s", item.getName())); return ApiOperations.deleteItem(resourceName); } // [END cloud_search_content_sdk_deleted_item] // [START cloud_search_content_sdk_unchanged_item] String currentHash = this.calculateMetadataHash(documentId); if (this.canSkipIndexing(item, currentHash)) { // Document neither modified nor deleted, ack the push log.info(() -> String.format("Document %s not modified", item.getName())); PushItem pushItem = new PushItem().setType("NOT_MODIFIED"); return new PushItems.Builder().addPushItem(resourceName, pushItem).build(); } // [END cloud_search_content_sdk_unchanged_item] // New or modified document, index it. log.info(() -> String.format("Updating document %s", item.getName())); return buildDocument(documentId); } /** * Creates a document for indexing. * <p> * For this connector sample, the created document is domain public * searchable. The content is a simple text string. * * @param documentId unique local id for the document * @return the fully formed document ready for indexing */ private ApiOperation buildDocument(int documentId) { // [START cloud_search_content_sdk_domain_acl] // Make the document publicly readable within the domain Acl acl = new Acl.Builder() .setReaders(Collections.singletonList(Acl.getCustomerPrincipal())) .build(); // [END cloud_search_content_sdk_domain_acl] // [START cloud_search_content_sdk_build_item] // Url is required. Use google.com as a placeholder for this sample. String viewUrl = "https://www.google.com"; // Version is required, set to current timestamp. byte[] version = Longs.toByteArray(System.currentTimeMillis()); // Set metadata hash so queue can detect changes String metadataHash = this.calculateMetadataHash(documentId); // Using the SDK item builder class to create the document with // appropriate attributes. This can be expanded to include metadata // fields etc. Item item = IndexingItemBuilder.fromConfiguration(Integer.toString(documentId)) .setItemType(IndexingItemBuilder.ItemType.CONTENT_ITEM) .setAcl(acl) .setSourceRepositoryUrl(IndexingItemBuilder.FieldOrValue.withValue(viewUrl)) .setVersion(version) .setHash(metadataHash) .build(); // [END cloud_search_content_sdk_build_item] // [START cloud_search_content_sdk_build_repository_doc] // For this sample, content is just plain text String content = String.format("Hello world from sample doc %d", documentId); ByteArrayContent byteContent = ByteArrayContent.fromString("text/plain", content); // Create the fully formed document RepositoryDoc doc = new RepositoryDoc.Builder() .setItem(item) .setContent(byteContent, IndexingService.ContentFormat.TEXT) .build(); // [END cloud_search_content_sdk_build_repository_doc] return doc; } // The following method is not used in this simple full traversal sample // connector, but could be implemented if the data repository supports // a way to detect changes. /** * {@inheritDoc} * * <p>This method is not required by the FullTraversalConnector and is * unimplemented. */ @Override public CheckpointCloseableIterable<ApiOperation> getChanges(byte[] checkpoint) { return null; } // The following methods are not used in the full traversal connector, but // might be used in the template and/or custom listing traversal connector // implementations. /** * {@inheritDoc} * * <p>This method is not required by the FullTraversalConnector and is * unimplemented. */ @Override public CheckpointCloseableIterable<ApiOperation> getAllDocs(byte[] checkpoint) { return null; } /** * {@inheritDoc} * * <p>This method is not required by the FullTraversalConnector and is * unimplemented. */ @Override public boolean exists(Item item) { return false; } /** * Returns a hash of the item's metadata. For the generated documents, a * timestamp is used to generate a hash. In production implementation, * a cryptographic hash of the actual content should be used. * * @param documentId document to get hash value of * @return Hash value of the document */ private String calculateMetadataHash(int documentId) { long timestamp = this.documents.get(documentId); return Long.toHexString(timestamp); } // [START cloud_search_content_sdk_skip_indexing] /** * Checks to see if an item is already up to date * * @param previousItem Polled item * @param currentHash Metadata hash of the current github object * @return PushItem operation */ private boolean canSkipIndexing(Item previousItem, String currentHash) { if (previousItem.getStatus() == null || previousItem.getMetadata() == null) { return false; } String status = previousItem.getStatus().getCode(); String previousHash = previousItem.getMetadata().getHash(); return "ACCEPTED".equals(status) && previousHash != null && previousHash.equals(currentHash); } // [END cloud_search_content_sdk_skip_indexing] /** * Simulate changes to the repository by randomly mutate the documents. A * subset of documents will be either deleted or modified during traversals * and new documents created. */ private void mutate() { log.info("Mutating repository."); Random r = new Random(); Map<Integer, Long> newDocuments = new HashMap<>(); for (int key : this.documents.keySet()) { switch (r.nextInt(3)) { case 0: // Leave document unchanged. newDocuments.put(key, this.documents.get(key)); break; case 1: // Mark it as modified newDocuments.put(key, System.currentTimeMillis()); break; default: // Delete the document (omit from map) } } // Create new documents int newDocumentCount = this.numberOfDocuments - newDocuments.size(); for (int i = 0; i < newDocumentCount; ++i) { int id = ++lastDocumentId; newDocuments.put(id, System.currentTimeMillis()); } // Swap out document set this.documents = newDocuments; } } }
37.879518
95
0.685433
5ec273453b21a138337a6bed23ea7d7cc7299942
1,841
package airhacks; import software.constructs.Construct; import java.util.Map; import software.amazon.awscdk.CfnOutput; import software.amazon.awscdk.Duration; import software.amazon.awscdk.Stack; import software.amazon.awscdk.StackProps; import software.amazon.awscdk.services.lambda.Code; import software.amazon.awscdk.services.lambda.Function; import software.amazon.awscdk.services.lambda.Runtime; public class CDKStack extends Stack { static Map<String, String> configuration = Map.of("message", "hello,duke"); static String functionName = "airhacks_lambda_greetings_boundary_Greetings"; static String lambdaHandler = "airhacks.lambda.greetings.boundary.Greetings::onEvent"; static int memory = 128; static int timeout = 10; static int maxConcurrency = 2; public CDKStack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); var function = createUserListenerFunction(functionName, lambdaHandler, configuration, memory, maxConcurrency, timeout); CfnOutput.Builder.create(this, "function-output").value(function.getFunctionArn()).build(); } Function createUserListenerFunction(String functionName,String functionHandler, Map<String,String> configuration, int memory, int maximumConcurrentExecution, int timeout) { return Function.Builder.create(this, functionName) .runtime(Runtime.JAVA_11) .code(Code.fromAsset("../target/function.jar")) .handler(functionHandler) .memorySize(memory) .functionName(functionName) .environment(configuration) .timeout(Duration.seconds(timeout)) .reservedConcurrentExecutions(maximumConcurrentExecution) .build(); } }
39.170213
176
0.708311
ac4fc8a229fae01555f5d4b8b8443c8e3002ae49
282
package de.maikmerten.spitools; /** * * @author maik */ public interface SPIConnection { public void select(); public void deselect(); public void sendByte(int b); public int receiveByte(); public int sendReceiveByte(int b); public void receiveBytes(byte[] buf); }
14.842105
38
0.702128
99f46696803274210ff25ba573ad310782e9758a
2,282
package br.com.application.name.mobile.bean.enums; import java.io.IOException; import java.util.Scanner; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; import br.com.application.name.mobile.interfaces.WebMobileApplication; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.remote.MobileCapabilityType; import io.appium.java_client.remote.MobilePlatform; /** * * @author Ronaldo Silva * */ public enum WebView implements WebMobileApplication { WEBVIEW { @Override public AndroidDriver<WebElement> getDriver() { // TODO Auto-generated method stub return getDriver("chrome"); } }; private AndroidDriver<WebElement> webViewDriver; /** * Retorna {@code AndroidDriver} para o aplicativo. * * @param appPackage * @return {@link AndroidDriver} */ public AndroidDriver<WebElement> getDriver(String browser) { try { Thread.sleep(100); webViewDriver = new AndroidDriver<WebElement>(getCapabilities(browser)); webViewDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); } catch (IOException | InterruptedException e) { e.printStackTrace(); } return webViewDriver; } /** * Retorna {@code DesiredCapabilities} * * @param appPackage * @return {@link DesiredCapabilities} * @throws IOException */ private DesiredCapabilities getCapabilities(String browser) throws IOException { Scanner scanner = null; scanner = new Scanner(Runtime.getRuntime().exec(new String[] { "/bin/bash", "-l", "-c", "adb get-serialno" }) .getInputStream()); String deviceSerialNumver = (scanner != null && scanner.hasNext()) ? scanner.next() : ""; scanner.close(); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("deviceName", "Galaxy"); capabilities.setCapability("platformName", MobilePlatform.ANDROID); capabilities.setCapability("device", "Android"); capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, browser); capabilities.setCapability("udid", deviceSerialNumver); capabilities.setCapability("appActivity", "MainActivity_"); capabilities.setCapability("appPackage", "com.android.settings"); return capabilities; } }
28.17284
111
0.746713
2659fed31b979019d9760c8010b2ddfc29a01ec3
34,222
package nl.pim16aap2.armoredElytra.util; /* * The MIT License (MIT) * * Copyright (c) 2018 Hex_27 * Copyright (c) 2020 Crypto Morin * * 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. */ import com.google.common.base.Enums; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableSet; import lombok.NonNull; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.apache.commons.lang.WordUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; /** * <b>XMaterial</b> - Data Values/Pre-flattening<br> * 1.13 and above as priority. * <p> * This class is mainly designed to support ItemStacks. If you want to use it on blocks you'll have to use <a * href="https://github.com/CryptoMorin/XSeries/blob/master/XBlock.java">XBlock</a> * <p> * Pre-flattening: https://minecraft.gamepedia.com/Java_Edition_data_values/Pre-flattening Materials: * https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Material.html Materials (1.12): * https://helpch.at/docs/1.12.2/index.html?org/bukkit/Material.html Material IDs: * https://minecraft-ids.grahamedgecombe.com/ Material Source Code: * <p> * https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/browse/src/main/java/org/bukkit/Material.java XMaterial * v1: https://www.spigotmc.org/threads/329630/ * * @author Crypto Morin * @version 5.0.0 * @see Material * @see ItemStack */ public enum XMaterial { CHAINMAIL_CHESTPLATE, DIAMOND_CHESTPLATE, GOLDEN_CHESTPLATE("GOLD_CHESTPLATE"), IRON_CHESTPLATE, LEATHER_CHESTPLATE, NETHERITE_CHESTPLATE("1.16"), PHANTOM_MEMBRANE("1.13"), AIR, NETHERITE_INGOT("1.16"), ; /** * An immutable cached set of {@link XMaterial#values()} to avoid allocating memory for calling the method every * time. * * @since 2.0.0 */ public static final EnumSet<XMaterial> VALUES = EnumSet.allOf(XMaterial.class); /** * A set of material names that can be damaged. * <p> * Most of the names are not complete as this list is intended to be checked with {@link String#contains} for memory * usage. * * @since 1.0.0 */ private static final ImmutableSet<String> DAMAGEABLE = ImmutableSet.of( "HELMET", "CHESTPLATE", "LEGGINGS", "BOOTS", "SWORD", "AXE", "PICKAXE", "SHOVEL", "HOE", "ELYTRA", "TRIDENT", "HORSE_ARMOR", "BARDING", "SHEARS", "FLINT_AND_STEEL", "BOW", "FISHING_ROD", "CARROT_ON_A_STICK", "CARROT_STICK", "SPADE", "SHIELD" ); /* * A set of all the legacy names without duplicates. * <p> * It'll help to free up a lot of memory if it's not used. * Add it back if you need it. * * @see #containsLegacy(String) * @since 2.2.0 * private static final ImmutableSet<String> LEGACY_VALUES = VALUES.stream().map(XMaterial::getLegacy) .flatMap(Arrays::stream) .filter(m -> m.charAt(1) == '.') .collect(Collectors.collectingAndThen(Collectors.toSet(), ImmutableSet::copyOf)); */ /** * Guava (Google Core Libraries for Java)'s cache for performance and timed caches. For strings that match a certain * XMaterial. Mostly cached for configs. * * @since 1.0.0 */ private static final Cache<String, XMaterial> NAME_CACHE = CacheBuilder.newBuilder() .softValues() .expireAfterAccess(15, TimeUnit.MINUTES) .build(); /** * Guava (Google Core Libraries for Java)'s cache for performance and timed caches. For XMaterials that are already * parsed once. * * @since 3.0.0 */ private static final Cache<XMaterial, Optional<Material>> PARSED_CACHE = CacheBuilder.newBuilder() .softValues() .expireAfterAccess(10, TimeUnit.MINUTES) .concurrencyLevel(Runtime.getRuntime().availableProcessors()) .build(); /** * Pre-compiled RegEx pattern. Include both replacements to avoid recreating string multiple times with multiple * RegEx checks. * * @since 3.0.0 */ private static final Pattern FORMAT_PATTERN = Pattern.compile("\\W+"); /** * The current version of the server in the a form of a major version. * * @since 1.0.0 */ private static final int VERSION = Integer.parseInt(getMajorVersion(Bukkit.getVersion()).substring(2)); /** * Cached result if the server version is after the v1.13 flattening update. Please don't mistake this with * flat-chested people. It happened. * * @since 3.0.0 */ private static final boolean ISFLAT = supports(13); /** * The data value of this material https://minecraft.gamepedia.com/Java_Edition_data_values/Pre-flattening * * @see #getData() */ private final byte data; /** * A list of material names that was being used for older verions. * * @see #getLegacy() */ private final String[] legacy; XMaterial(int data, String... legacy) { this.data = (byte) data; this.legacy = legacy; } XMaterial() { this(0); } XMaterial(String... legacy) { this(0, legacy); } /** * Checks if the version is 1.13 Aquatic Update or higher. An invocation of this method yields the cached result * from the expression: * <p> * <blockquote> * {@link #supports(int) 13}} * </blockquote> * * @return true if 1.13 or higher. * * @see #getVersion() * @see #supports(int) * @since 1.0.0 */ public static boolean isNewVersion() { return ISFLAT; } /** * This is just an extra method that method that can be used for many cases. It can be used in {@link * org.bukkit.event.player.PlayerInteractEvent} or when accessing {@link org.bukkit.entity.Player#getMainHand()}, or * other compatibility related methods. * <p> * An invocation of this method yields exactly the same result as the expression: * <p> * <blockquote> * {@link #getVersion()} == 1.8 * </blockquote> * * @since 2.0.0 */ public static boolean isOneEight() { return !supports(9); } /** * The current version of the server. * * @return the current server version or 0.0 if unknown. * * @see #isNewVersion() * @since 2.0.0 */ public static double getVersion() { return VERSION; } /** * When using newer versions of Minecraft ({@link #isNewVersion()}), helps to find the old material name with its * data value using a cached search for optimization. * * @see #matchDefinedXMaterial(String, byte) * @since 1.0.0 */ @Nullable private static XMaterial requestOldXMaterial(@NonNull String name, byte data) { String holder = name + data; XMaterial cache = NAME_CACHE.getIfPresent(holder); if (cache != null) return cache; for (XMaterial material : VALUES) { // Not using material.name().equals(name) check is intended. if ((data == -1 || data == material.data) && material.anyMatchLegacy(name)) { NAME_CACHE.put(holder, material); return material; } } return null; } /** * Checks if XMaterial enum contains a material with the given name. * <p> * You should use {@link #matchXMaterial(String)} instead if you're going to get the XMaterial object after checking * if it's available in the list by doing a simple {@link Optional#isPresent()} check. This is just to avoid * multiple loops for maximum performance. * * @param name * name of the material. * * @return true if XMaterial enum has this material. * * @since 1.0.0 */ public static boolean contains(@NonNull String name) { Validate.notEmpty(name, "Cannot check for null or empty material name"); name = format(name); for (XMaterial materials : VALUES) if (materials.name().equals(name)) return true; return false; } /** * Parses the given material name as an XMaterial with unspecified data value. * * @see #matchXMaterialWithData(String) * @since 2.0.0 */ @NonNull public static Optional<XMaterial> matchXMaterial(@NonNull String name) { Validate.notEmpty(name, "Cannot match a material with null or empty material name"); Optional<XMaterial> oldMatch = matchXMaterialWithData(name); if (oldMatch.isPresent()) return oldMatch; return matchDefinedXMaterial(format(name), (byte) -1); } /** * Parses material name and data value from the specified string. The seperators are: <b>, or :</b> Spaces are * allowed. Mostly used when getting materials from config for old school minecrafters. * <p> * <b>Examples</b> * <p><pre> * {@code INK_SACK:1 -> RED_DYE} * {@code WOOL, 14 -> RED_WOOL} * </pre> * * @param name * the material string that consists of the material name, data and separator character. * * @return the parsed XMaterial. * * @see #matchXMaterial(String) * @since 3.0.0 */ private static Optional<XMaterial> matchXMaterialWithData(String name) { for (char separator : new char[]{',', ':'}) { int index = name.indexOf(separator); if (index == -1) continue; String mat = format(name.substring(0, index)); byte data = Byte.parseByte(StringUtils.deleteWhitespace(name.substring(index + 1))); return matchDefinedXMaterial(mat, data); } return Optional.empty(); } /** * Parses the given material as an XMaterial. * * @throws IllegalArgumentException * may be thrown as an unexpected exception. * @see #matchDefinedXMaterial(String, byte) * @see #matchXMaterial(ItemStack) * @since 2.0.0 */ @NonNull public static XMaterial matchXMaterial(@NonNull Material material) { Objects.requireNonNull(material, "Cannot match null material"); return matchDefinedXMaterial(material.name(), (byte) -1) .orElseThrow(() -> new IllegalArgumentException("Unsupported Material With No Bytes: " + material.name())); } /** * Parses the given item as an XMaterial using its material and data value (durability). * * @param item * the ItemStack to match. * * @return an XMaterial if matched any. * * @throws IllegalArgumentException * may be thrown as an unexpected exception. * @see #matchDefinedXMaterial(String, byte) * @since 2.0.0 */ @NonNull @SuppressWarnings("deprecation") public static XMaterial matchXMaterial(@NonNull ItemStack item) { Objects.requireNonNull(item, "Cannot match null ItemStack"); String material = item.getType().name(); byte data = (byte) (ISFLAT || isDamageable(material) ? 0 : item.getDurability()); return matchDefinedXMaterial(material, data) .orElseThrow(() -> new IllegalArgumentException("Unsupported Material: " + material + " (" + data + ')')); } /** * Parses the given material name and data value as an XMaterial. All the values passed to this method will not be * null or empty and are formatted correctly. * * @param name * the formatted name of the material. * @param data * the data value of the material. * * @return an XMaterial (with the same data value if specified) * * @see #matchXMaterial(Material) * @see #matchXMaterial(int, byte) * @see #matchXMaterial(ItemStack) * @since 3.0.0 */ @NonNull private static Optional<XMaterial> matchDefinedXMaterial(@NonNull String name, byte data) { boolean duplicated = isDuplicated(name); // Do basic number and boolean checks before accessing more complex enum stuff. // Maybe we can simplify (ISFLAT || !duplicated) with the (!ISFLAT && duplicated) // under it to save a few nanoseconds? // if (!Boolean.valueOf(Boolean.getBoolean(Boolean.TRUE.toString())).equals(Boolean.FALSE.booleanValue())) // return null; if (data <= 0 && !duplicated) { // Apparently the transform method is more efficient than toJavaUtil() // toJavaUtil isn't even supported in older versions. Optional<XMaterial> xMat = Enums.getIfPresent(XMaterial.class, name).transform(Optional::of).or(Optional.empty()); if (xMat.isPresent()) return xMat; } // XMaterial Paradox (Duplication Check) // I've concluded that this is just an infinite loop that keeps // going around the Singular Form and the Plural Form materials. A waste of brain cells and a waste of time. // This solution works just fine anyway. XMaterial xMat = requestOldXMaterial(name, data); if (xMat == null) return Optional.empty(); if (!ISFLAT && duplicated && xMat.name().charAt(xMat.name().length() - 1) == 'S') { // A solution for XMaterial Paradox. // Manually parses the duplicated materials to find the exact material based on the server version. // If ends with "S" -> Plural Form Material return Enums.getIfPresent(XMaterial.class, name).transform(Optional::of).or(Optional.empty()); } return Optional.ofNullable(xMat); } /** * <b>XMaterial Paradox (Duplication Check)</b> * Checks if the material has any duplicates. * <p> * <b>Example:</b> * <p>{@code MELON, CARROT, POTATO, BEETROOT -> true} * * @param name * the name of the material to check. * * @return true if there's a duplicated material for this material, otherwise false. * * @see #isDuplicated() * @since 2.0.0 */ private static boolean isDuplicated(@NonNull String name) { return false; } /** * Gets the XMaterial based on the material's ID (Magic Value) and data value.<br> You should avoid using this for * performance issues. * * @param id * the ID (Magic value) of the material. * @param data * the data value of the material. * * @return a parsed XMaterial with the same ID and data value. * * @see #matchXMaterial(ItemStack) * @since 2.0.0 */ @NonNull public static Optional<XMaterial> matchXMaterial(int id, byte data) { if (id < 0 || data < 0) return Optional.empty(); // Looping through Material.values() will take longer. for (XMaterial materials : VALUES) if (materials.data == data && materials.getId() == id) return Optional.of(materials); return Optional.empty(); } /** * Attempts to build the string like an enum name. Removes all the spaces, numbers and extra non-English characters. * Also removes some config/in-game based strings. * * @param name * the material name to modify. * * @return a Material enum name. * * @since 2.0.0 */ @NonNull private static String format(@NonNull String name) { return FORMAT_PATTERN.matcher( name.trim().replace('-', '_').replace(' ', '_')).replaceAll("").toUpperCase(Locale.ENGLISH); } /** * Checks if the specified version is the same version or higher than the current server version. * * @param version * the major version to be checked. "1." is ignored. E.g. 1.12 = 12 | 1.9 = 9 * * @return true of the version is equal or higher than the current version. * * @since 2.0.0 */ public static boolean supports(int version) { return VERSION >= version; } /** * Converts the enum names to a more friendly and readable string. * * @return a formatted string. * * @see #toWord(String) * @since 2.1.0 */ @NonNull public static String toWord(@NonNull Material material) { Objects.requireNonNull(material, "Cannot translate a null material to a word"); return toWord(material.name()); } /** * Parses an enum name to a normal word. Normal names have underlines removed and each word capitalized. * <p> * <b>Examples:</b> * <pre> * EMERALD -> Emerald * EMERALD_BLOCK -> Emerald Block * ENCHANTED_GOLDEN_APPLE -> Enchanted Golden Apple * </pre> * * @param name * the name of the enum. * * @return a cleaned more readable enum name. * * @since 2.1.0 */ @NonNull private static String toWord(@NonNull String name) { return WordUtils.capitalize(name.replace('_', ' ').toLowerCase(Locale.ENGLISH)); } /** * Gets the exact major version (..., 1.9, 1.10, ..., 1.14) * * @param version * Supports {@link Bukkit#getVersion()}, {@link Bukkit#getBukkitVersion()} and normal formats such as * "1.14" * * @return the exact major version. * * @since 2.0.0 */ @NonNull public static String getMajorVersion(@NonNull String version) { Validate.notEmpty(version, "Cannot get major Minecraft version from null or empty string"); // getVersion() int index = version.lastIndexOf("MC:"); if (index != -1) version = version.substring(index + 4, version.length() - 1); else if (version.endsWith("SNAPSHOT")) { // getBukkitVersion() index = version.indexOf('-'); version = version.substring(0, index); } // 1.13.2, 1.14.4, etc... int lastDot = version.lastIndexOf('.'); if (version.indexOf('.') != lastDot) version = version.substring(0, lastDot); return version; } /** * Checks if the material can be damaged by using it. Names going through this method are not formatted. * * @param name * the name of the material. * * @return true of the material can be damaged. * * @see #isDamageable() * @since 1.0.0 */ public static boolean isDamageable(@NonNull String name) { Objects.requireNonNull(name, "Material name cannot be null"); for (String damageable : DAMAGEABLE) if (name.contains(damageable)) return true; return false; } /** * Checks if the list of given material names matches the given base material. Mostly used for configs. * <p> * Supports {@link String#contains} {@code CONTAINS:NAME} and Regular Expression {@code REGEX:PATTERN} formats. * <p> * <b>Example:</b> * <blockquote><pre> * XMaterial material = {@link #matchXMaterial(ItemStack)}; * if (material.isOneOf(plugin.getConfig().getStringList("disabled-items")) return; * </pre></blockquote> * <br> * <b>{@code CONTAINS} Examples:</b> * <pre> * {@code "CONTAINS:CHEST" -> CHEST, ENDERCHEST, TRAPPED_CHEST -> true} * {@code "cOnTaINS:dYe" -> GREEN_DYE, YELLOW_DYE, BLUE_DYE, INK_SACK -> true} * </pre> * <p> * <b>{@code REGEX} Examples</b> * <pre> * {@code "REGEX:^.+_.+_.+$" -> Every Material with 3 underlines or more: SHULKER_SPAWN_EGG, * SILVERFISH_SPAWN_EGG, SKELETON_HORSE_SPAWN_EGG} * {@code "REGEX:^.{1,3}$" -> Material names that have 3 letters only: BED, MAP, AIR} * </pre> * <p> * The reason that there are tags for {@code CONTAINS} and {@code REGEX} is for the performance. Please avoid using * the {@code REGEX} tag if you can use the {@code CONTAINS} tag. It'll have a huge impact on performance. Please * avoid using {@code (capturing groups)} there's no use for them in this case. If you want to use groups, use * {@code (?: non-capturing groups)}. It's faster. * <p> * You can make a cache for pre-compiled RegEx patterns from your config. It's better, but not much faster since * these patterns are not that complex. * <p> * Want to learn RegEx? You can mess around in <a href="https://regexr.com/">RegExr</a> website. * * @param material * the base material to match other materials with. * @param materials * the material names to check base material on. * * @return true if one of the given material names is similar to the base material. * * @since 3.1.1 */ public static boolean isOneOf(@NonNull Material material, @Nullable List<String> materials) { if (materials == null || materials.isEmpty()) return false; Objects.requireNonNull(material, "Cannot match materials with a null material"); String name = material.name(); for (String comp : materials) { comp = comp.toUpperCase(); if (comp.startsWith("CONTAINS:")) { comp = format(comp.substring(9)); if (name.contains(comp)) return true; continue; } if (comp.startsWith("REGEX:")) { comp = comp.substring(6); if (name.matches(comp)) return true; continue; } // Direct Object Equals Optional<XMaterial> mat = matchXMaterial(comp); if (mat.isPresent() && mat.get().parseMaterial() == material) return true; } return false; } /** * Gets the version which this material was added in. If the material doesn't have a version it'll return 0; * * @return the Minecraft version which tihs material was added in. * * @since 3.0.0 */ public int getMaterialVersion() { if (this.legacy.length == 0) return 0; String version = this.legacy[0]; if (version.charAt(1) != '.') return 0; return Integer.parseInt(version.substring(2)); } /** * Sets the {@link Material} (and data value on older versions) of an item. Damageable materials will not have their * durability changed. * <p> * Use {@link #parseItem()} instead when creating new ItemStacks. * * @param item * the item to change its type. * * @see #parseItem() * @since 3.0.0 */ @NonNull @SuppressWarnings("deprecation") public ItemStack setType(@NonNull ItemStack item) { Objects.requireNonNull(item, "Cannot set material for null ItemStack"); item.setType(this.parseMaterial()); if (!ISFLAT && !this.isDamageable()) item.setDurability(this.data); return item; } /** * Checks if the list of given material names matches the given base material. Mostly used for configs. * * @param materials * the material names to check base material on. * * @return true if one of the given material names is similar to the base material. * * @see #isOneOf(Material, List) * @since 3.0.0 */ public boolean isOneOf(@Nullable List<String> materials) { Material material = this.parseMaterial(); if (material == null) return false; return isOneOf(material, materials); } /** * Checks if the given string matches any of this material's legacy material names. All the values passed to this * method will not be null or empty and are formatted correctly. * * @param name * the name to check * * @return true if it's one of the legacy names. * * @since 2.0.0 */ private boolean anyMatchLegacy(@NonNull String name) { for (String legacy : this.legacy) { if (legacy.isEmpty()) // Left-side suggestion list break; if (name.equals(legacy)) return true; } return false; } /** * User-friendly readable name for this material In most cases you should be using {@link #name()} instead. * * @return string of this object. * * @see #toWord(String) * @since 3.0.0 */ @Override public String toString() { return toWord(this.name()); } /** * Gets the ID (Magic value) of the material. * * @return the ID of the material or <b>-1</b> if it's a new block or the material is not supported. * * @see #matchXMaterial(int, byte) * @since 2.2.0 */ @SuppressWarnings("deprecation") public int getId() { if (this.data != 0 || (this.legacy.length != 0 && Integer.parseInt(this.legacy[0].substring(2)) >= 13)) return -1; Material material = this.parseMaterial(); return material == null ? -1 : material.getId(); } /** * Checks if the material has any duplicates. * * @return true if there is a duplicated name for this material, otherwise false. * * @see #isDuplicated(String) * @since 2.0.0 */ public boolean isDuplicated() { return false; } /** * Checks if the material can be damaged by using it. Names going through this method are not formatted. * * @return true if the item can be damaged (have its durability changed), otherwise false. * * @see #isDamageable(String) * @since 1.0.0 */ public boolean isDamageable() { return isDamageable(this.name()); } /** * The data value of this material * <a href="https://minecraft.gamepedia.com/Java_Edition_data_values/Pre-flattening">pre-flattening</a>. * <p> * Can be accessed with {@link ItemStack#getData()} then {@code MaterialData#getData()} or {@link * ItemStack#getDurability()} if not damageable. * * @return data of this material, or 0 if none. * * @since 1.0.0 */ @SuppressWarnings("deprecation") public byte getData() { return data; } /** * Get a list of materials names that was previously used by older versions. If the material was added in a new * version {@link #isNewVersion()}, then the first element will indicate which version the material was added in. * * @return a list of legacy material names and the first element as the version the material was added in if new. * * @since 1.0.0 */ @NonNull public String[] getLegacy() { return legacy; } /** * Parses an item from this XMaterial. Uses data values on older versions. * * @return an ItemStack with the same material (and data value if in older versions.) * * @see #parseItem(boolean) * @see #setType(ItemStack) * @since 1.0.0 */ @Nullable public ItemStack parseItem() { return parseItem(false); } /** * Parses an item from this XMaterial. Uses data values on older versions. * * @param suggest * if true {@link #parseMaterial(boolean)} true will be used. * * @return an ItemStack with the same material (and data value if in older versions.) * * @see #setType(ItemStack) * @since 2.0.0 */ @Nullable @SuppressWarnings("deprecation") public ItemStack parseItem(boolean suggest) { Material material = this.parseMaterial(suggest); if (material == null) return null; return ISFLAT ? new ItemStack(material) : new ItemStack(material, 1, this.data); } /** * Parses the material of this XMaterial. * * @return the material related to this XMaterial based on the server version. * * @see #parseMaterial(boolean) * @since 1.0.0 */ @Nullable public Material parseMaterial() { return parseMaterial(false); } /** * Parses the material of this XMaterial and accepts suggestions. * * @param suggest * use a suggested material (from older materials) if the material is added in a later version of * Minecraft. * * @return the material related to this XMaterial based on the server version. * * @since 2.0.0 */ @SuppressWarnings("OptionalAssignedToNull") @Nullable public Material parseMaterial(boolean suggest) { Optional<Material> cache = PARSED_CACHE.getIfPresent(this); if (cache != null) return cache.orElse(null); Material mat; if (!ISFLAT && this.isDuplicated()) mat = requestOldMaterial(suggest); else { mat = Material.getMaterial(this.name()); if (mat == null) mat = requestOldMaterial(suggest); } if (mat != null) PARSED_CACHE.put(this, Optional.ofNullable(mat)); return mat; } /** * Parses a material for older versions of Minecraft. Accepts suggestions if specified. * * @param suggest * if true suggested materials will be considered for old versions. * * @return a parsed material suitable for the current Minecraft version. * * @see #parseMaterial(boolean) * @since 2.0.0 */ @Nullable private Material requestOldMaterial(boolean suggest) { for (int i = this.legacy.length - 1; i >= 0; i--) { String legacy = this.legacy[i]; // Check if we've reached the end and the last string is our // material version. if (i == 0 && legacy.charAt(1) == '.') return null; // According to the suggestion list format, all the other names continuing // from here are considered as a "suggestion" // The empty string is an indicator for suggestion list on the left side. if (legacy.isEmpty()) { if (suggest) continue; break; } Material material = Material.getMaterial(legacy); if (material != null) return material; } return null; } /** * Checks if an item has the same material (and data value on older versions). * * @param item * item to check. * * @return true if the material is the same as the item's material (and data value if on older versions), otherwise * false. * * @since 1.0.0 */ @SuppressWarnings("deprecation") public boolean isSimilar(@NonNull ItemStack item) { Objects.requireNonNull(item, "Cannot compare with null ItemStack"); if (item.getType() != this.parseMaterial()) return false; return ISFLAT || this.isDamageable() || item.getDurability() == this.data; } /** * Gets the suggested material names that can be used if the material is not supported in the current version. * * @return a list of suggested material names. * * @see #parseMaterial(boolean) * @since 2.0.0 */ @NonNull public List<String> getSuggestions() { if (this.legacy.length == 0 || this.legacy[0].charAt(1) != '.') return new ArrayList<>(); List<String> suggestions = new ArrayList<>(); for (String legacy : this.legacy) { if (legacy.isEmpty()) break; suggestions.add(legacy); } return suggestions; } /** * Checks if this material is supported in the current version. Suggested materials will be ignored. * <p> * Note that you should use {@link #parseMaterial()} and check if it's null if you're going to parse and use the * material later. * * @return true if the material exists in {@link Material} list. * * @since 2.0.0 */ public boolean isSupported() { int version = this.getMaterialVersion(); if (version != 0) return supports(version); Material material = Material.getMaterial(this.name()); if (material != null) return true; return requestOldMaterial(false) != null; } /** * Checks if the material is newly added after the 1.13 Aquatic Update. * * @return true if the material was newly added, otherwise false. * * @see #getMaterialVersion() * @since 2.0.0 */ public boolean isFromNewSystem() { return this.legacy.length != 0 && Integer.parseInt(this.legacy[0].substring(2)) > 13; } }
33.984111
123
0.603501
ceac4a446ba7196e6b5b85f552baf4ee7853b2c2
5,863
package com.example.zqf.store.Activity_Home; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.zqf.store.Bean.Good; import com.example.zqf.store.Bean.Order; import com.example.zqf.store.Bean.User; import com.example.zqf.store.Good_detailActivity; import com.example.zqf.store.R; import com.example.zqf.store.SumActivity; import java.io.File; import java.util.ArrayList; import java.util.List; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.BmobUser; import cn.bmob.v3.datatype.BmobFile; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.DownloadFileListener; import cn.bmob.v3.listener.QueryListener; import cn.bmob.v3.listener.UpdateListener; /** * Created by admin on 2018/3/23. */ public class Brand_DetailActivity extends AppCompatActivity { TextView tx51,tx54,tx58,tx61,tx65,tx63,tx81; Button button; ImageView imageView; Good good=new Good(); List<Good> goods=new ArrayList<>(); String path; ActionBar bar; User user= BmobUser.getCurrentUser(User.class); int state; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reuse_form); bar = getSupportActionBar(); bar.setDisplayHomeAsUpEnabled(true); Intent intent=getIntent(); good=(Good) intent.getSerializableExtra("good"); state=intent.getIntExtra("state",-1); goods=user.getGoods(); path="/data/user/0/com.example.zqf.store/cache/bmob/"+good.getName()+".jpg"; BmobQuery<Good> query = new BmobQuery<>(); query.getObject(good.getObjectId(), new QueryListener<Good>() { @Override public void done(Good good, BmobException e) { if(e==null){ download(good.getPicGood()); } } }); tx51=findViewById(R.id.textView51); tx51.setText(good.getMasterneme()); tx54=findViewById(R.id.textView54); tx54.setText(good.getMasterQQ()); tx58=findViewById(R.id.textView58); tx58.setText(good.getMasterphone()); tx61=findViewById(R.id.textView61); tx61.setText(good.getName()); tx65=findViewById(R.id.textView65); tx65.setText(good.getDescribe()); tx65.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(Brand_DetailActivity.this, Good_detailActivity.class); intent.putExtra("keygood",good); startActivity(intent); } }); tx63=findViewById(R.id.textView63); tx63.setText(good.getPrice()+""); tx81=findViewById(R.id.textView81); tx81.setText(good.getMasterClass()); imageView=findViewById(R.id.imageView3); Bitmap bt= BitmapFactory.decodeFile(path); imageView.setImageBitmap(bt); button=findViewById(R.id.button21); button.setVisibility(View.INVISIBLE); } public boolean onCreateOptionsMenu(Menu menu){ getMenuInflater().inflate(R.menu.like,menu); return super.onCreateOptionsMenu(menu); } public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()){ case android.R.id.home: this.finish(); return false; case R.id.like: if(item.getTitle().toString().equals("收藏")){ goods.add(good); user.setGoods(goods); user.update(new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ toast("已收藏"); }else{ toast(e.getMessage()); } } }); item.setTitle("已收藏"); }else if(item.getTitle().toString().equals("已收藏")){ goods.remove(good); user.setGoods(goods); user.update(new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ toast("已取消"); }else{ toast(e.getMessage()); } } }); item.setTitle("收藏"); } return true; default: return super.onOptionsItemSelected(item); } } public void download(BmobFile picUser) { picUser.download(new DownloadFileListener() { @Override public void done(String s, BmobException e) { if(e==null){ //Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show(); } else Toast.makeText(getApplicationContext(),"失败!", Toast.LENGTH_LONG).show(); } @Override public void onProgress(Integer integer, long l) { } }); } public void toast(String toast) { //Toast便捷使用方法 Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_LONG).show(); } }
34.28655
95
0.571892
a8ebf2a115f97d6dbbe5d59abc88917ae8d4c250
4,690
package uk.gov.pay.connector.gateway.epdq; import com.google.common.collect.ImmutableMap; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import uk.gov.pay.connector.refund.model.domain.RefundStatus; import java.util.Optional; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static uk.gov.pay.connector.charge.model.domain.ChargeStatus.CAPTURED; import static uk.gov.pay.connector.gateway.PaymentGatewayName.EPDQ; import static uk.gov.pay.connector.gateway.epdq.EpdqNotification.StatusCode.EPDQ_PAYMENT_REQUESTED; import static uk.gov.pay.connector.gateway.epdq.EpdqNotification.StatusCode.EPDQ_REFUND; import static uk.gov.pay.connector.gatewayaccount.model.GatewayAccount.CREDENTIALS_SHA_OUT_PASSPHRASE; @RunWith(MockitoJUnitRunner.class) public class EpdqNotificationServiceTest extends BaseEpdqNotificationServiceTest { @Before public void setup() { super.setup(); } @Test public void givenAChargeCapturedNotification_chargeNotificationProcessorInvokedWithNotificationAndCharge() { final String payload = notificationPayloadForTransaction( payId, EPDQ_PAYMENT_REQUESTED); notificationService.handleNotificationFor(payload); verify(mockRefundNotificationProcessor, never()).invoke(any(), any(), any(), any()); verify(mockChargeNotificationProcessor).invoke(payId, mockCharge, CAPTURED, null); } @Test public void givenARefundNotification_refundNotificationProcessorInvokedWithNotificationAndCharge() { final String payload = notificationPayloadForTransaction( payId, EPDQ_REFUND); notificationService.handleNotificationFor(payload); verify(mockChargeNotificationProcessor, never()).invoke(any(), any(), any(), any()); verify(mockRefundNotificationProcessor).invoke(EPDQ, RefundStatus.REFUNDED, payId + "/" + payIdSub, payId); } @Test public void ifChargeNotFound_shouldNotInvokeChargeOrRefundNotificationProcessor() { final String payload = notificationPayloadForTransaction( payId, EPDQ_REFUND); when(mockChargeDao.findByProviderAndTransactionId(EPDQ.getName(), payId)).thenReturn(Optional.empty()); notificationService.handleNotificationFor(payload); verify(mockChargeNotificationProcessor, never()).invoke(any(), any(), any(), any()); verify(mockRefundNotificationProcessor, never()).invoke(any(), any(), any(), any()); } @Test public void ifTransactionIdEmpty_shouldNotInvokeChargeOrRefundNotificationProcessor() { final String payload = notificationPayloadForTransaction( null, EPDQ_REFUND); notificationService.handleNotificationFor(payload); verify(mockChargeNotificationProcessor, never()).invoke(anyString(), any(), any(), any()); verify(mockRefundNotificationProcessor, never()).invoke(any(), any(), any(), any()); } @Test public void ifPayloadNotValidXml_shouldIgnoreNotification() { String payload = "not_valid"; notificationService.handleNotificationFor(payload); verify(mockChargeNotificationProcessor, never()).invoke(any(), any(), any(), any()); verify(mockRefundNotificationProcessor, never()).invoke(any(), any(), any(), any()); } @Test public void shouldIgnoreNotificationWhenStatusIsUnknown() { final String payload = notificationPayloadForTransaction( payId, EpdqNotification.StatusCode.UNKNOWN); notificationService.handleNotificationFor(payload); verify(mockChargeNotificationProcessor, never()).invoke(anyString(), any(), any(), any()); verify(mockRefundNotificationProcessor, never()).invoke(any(), any(), any(), any()); } @Test public void shouldNotUpdateIfShaPhraseExpectedIsIncorrect() { when(mockGatewayAccountEntity.getCredentials()) .thenReturn(ImmutableMap.of(CREDENTIALS_SHA_OUT_PASSPHRASE, "sha-phrase-out-expected")); final String payload = notificationPayloadForTransaction(payId, EPDQ_PAYMENT_REQUESTED); notificationService.handleNotificationFor(payload); verify(mockChargeNotificationProcessor, never()).invoke(anyString(), any(), any(), any()); verify(mockRefundNotificationProcessor, never()).invoke(any(), any(), any(), any()); } }
39.411765
115
0.724307
029d7e2a5c502831169143af67b844619edb06c3
307
package com.github.tony19.example.customappender; /** * Sample configuration that takes an integer capacity setting */ public class Config { private int capacity; public void setCapacity(int capacity) { this.capacity = capacity; } public int getCapacity() { return this.capacity; } }
18.058824
62
0.716612
1871a4112bf7f2fa11775bdf6b956547eec3e136
1,674
package protomoto.ast; import org.jparsec.Parser; import org.jparsec.Parsers; import org.jparsec.Scanners; import org.jparsec.Terminals; public class ASTParser<T> { private static final Terminals OPERATORS = Terminals.operators("(", ")"); private static final Parser<Void> IGNORED = Parsers.or(Scanners.JAVA_LINE_COMMENT, Scanners.JAVA_BLOCK_COMMENT, Scanners.WHITESPACES).skipMany(); private static final Parser<?> TOKENIZER = Parsers.or(Terminals.IntegerLiteral.TOKENIZER, Terminals.StringLiteral.SINGLE_QUOTE_TOKENIZER, Terminals.Identifier.TOKENIZER, OPERATORS.tokenizer()); /*private static Parser<?> term(String... names) { return OPERATORS.token(names); }*/ public static <T> Parser<T> create1(ASTFactory<T> factory, Terminals operators) { Parser<T> INTEGER = Terminals.IntegerLiteral.PARSER.map((java.lang.String str) -> factory.createInt(Integer.parseInt(str))); Parser<T> STRING = Terminals.StringLiteral.PARSER.map((java.lang.String str) -> factory.createString(str)); Parser<T> SYMBOL = Terminals.Identifier.PARSER.map((java.lang.String str) -> factory.createString(str)); Parser<T> atom = INTEGER.or(STRING).or(SYMBOL); Parser.Reference<T> ref = Parser.newReference(); Parser<T> unit = ref.lazy().between(operators.token("("), operators.token(")")).or(atom); Parser<T> parser = unit.many().map((java.util.List<T> x) -> (T) factory.createList(x)); ref.set(parser); return ref.lazy(); } public static <T> Parser<T> create(ASTFactory<T> factory) { return create1(factory, OPERATORS).from(TOKENIZER, IGNORED); } }
47.828571
197
0.693548
6f830caf1ef14e5757c71dbd47c1efe27e00d1df
24,610
package com.vitco.app.layout.content.mainview; import com.jidesoft.action.CommandMenuBar; import com.threed.jpct.Config; import com.threed.jpct.Object3D; import com.threed.jpct.SimpleVector; import com.threed.jpct.util.Light; import com.vitco.app.core.CameraChangeListener; import com.vitco.app.core.EngineInteractionPrototype; import com.vitco.app.core.data.container.Voxel; import com.vitco.app.core.world.WorldManager; import com.vitco.app.manager.action.types.StateActionPrototype; import com.vitco.app.manager.action.types.SwitchActionPrototype; import com.vitco.app.manager.async.AsyncAction; import com.vitco.app.manager.pref.PrefChangeListener; import com.vitco.app.manager.thread.LifeTimeThread; import com.vitco.app.manager.thread.ThreadManagerInterface; import com.vitco.app.settings.VitcoSettings; import org.springframework.beans.factory.annotation.Autowired; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.util.Random; /** * Creates the main view instance and attaches the specific user interaction. */ public class MainView extends EngineInteractionPrototype implements MainViewInterface { private ThreadManagerInterface threadManager; // set the action handler @Autowired public final void setThreadManager(ThreadManagerInterface threadManager) { this.threadManager = threadManager; } protected MainView() { super(-1); } // -------------- // we don't have an ghost overlay to draw @Override protected SimpleVector[][] getGhostOverlay() { return new SimpleVector[0][]; } @Override protected boolean updateGhostOverlay() { return false; } // ----------------------- @Override protected Voxel[] getVoxels() { return data.getVisibleLayerVoxel(); } @Override protected Voxel[][] getChangedVoxels() { return data.getNewVisibleLayerVoxel("main_view"); } @Override protected Voxel[][] getChangedSelectedVoxels() { return data.getNewSelectedVoxel("main_view"); } // true if the "grid mode is on" private boolean gridModeOn = true; // true if the "light is on" private boolean staticLightOn = false; private void moveLightBehindCamera(Light light) { SimpleVector direction = camera.getPosition().normalize(); direction.scalarMul(2000000f); light.setPosition(direction); } // true if using "bounding box" private boolean useBoundingBox = true; @Override public final JPanel build() { // make sure we can see into the distance world.setClippingPlanes(Config.nearPlane, VitcoSettings.MAIN_VIEW_ZOOM_OUT_LIMIT * 2); selectedVoxelsWorld.setClippingPlanes(Config.nearPlane,VitcoSettings.MAIN_VIEW_ZOOM_OUT_LIMIT*2); // toggle shader // enable/disable shader actionManager.registerAction("toggle_shader_enabled", new AbstractAction() { private boolean enabled = false; @Override public void actionPerformed(ActionEvent e) { enabled = !enabled; container.enableShader(enabled); if (enabled) { console.addLine("Shader is enabled."); } else { console.addLine("Shader is disabled."); } forceRepaint(); } }); // start/stop test mode (rapid camera rotation) actionManager.registerAction("toggle_rapid_camera_testing",new AbstractAction() { private boolean active = false; private final Random rand = new Random(); private LifeTimeThread thread; private float dirx = 0f; private float diry = 0f; private final float maxSpeed = 1f; private final float speedChange = 0.1f; @Override public void actionPerformed(ActionEvent e) { active = !active; if (active) { thread = new LifeTimeThread() { @Override public void loop() throws InterruptedException { asyncActionManager.addAsyncAction(new AsyncAction() { @Override public void performAction() { dirx = Math.min(maxSpeed, Math.max(-maxSpeed, dirx + (rand.nextFloat() - 0.5f)*speedChange)); diry = Math.min(maxSpeed, Math.max(-maxSpeed, diry + (rand.nextFloat() - 0.5f)*speedChange)); camera.rotate(dirx, diry); forceRepaint(); } }); synchronized (this) { thread.wait(50); } } }; threadManager.manage(thread); console.addLine("Test activated."); } else { threadManager.remove(thread); console.addLine("Test deactivated."); } } }); // lighting final Light dark_light = WorldManager.addLight(world, SimpleVector.ORIGIN, -10); final Light light1 = WorldManager.addLight(world, new SimpleVector(-1500000, -2000000, -1000000), 3); final Light light2 = WorldManager.addLight(world, new SimpleVector(1500000, 2000000, 1000000), 3); camera.addCameraChangeListener(new CameraChangeListener() { @Override public void onCameraChange() { if (!staticLightOn) { moveLightBehindCamera(dark_light); } } }); if (!preferences.contains("light_mode_active")) { preferences.storeBoolean("light_mode_active", staticLightOn); } // react to changes on the light status preferences.addPrefChangeListener("light_mode_active", new PrefChangeListener() { @Override public void onPrefChange(Object o) { staticLightOn = (Boolean) o; if (staticLightOn) { dark_light.disable(); light1.enable(); light2.enable(); world.setAmbientLight(0, 0, 0); } else { dark_light.enable(); light1.disable(); light2.disable(); world.setAmbientLight(60, 60, 60); } moveLightBehindCamera(dark_light); forceRepaint(); } }); // react to changes on the light status preferences.addPrefChangeListener("light_mode_active", new PrefChangeListener() { @Override public void onPrefChange(Object o) { staticLightOn = (Boolean) o; if (staticLightOn) { dark_light.disable(); light1.enable(); light2.enable(); world.setAmbientLight(0, 0, 0); } else { dark_light.enable(); light1.disable(); light2.disable(); world.setAmbientLight(60, 60, 60); } moveLightBehindCamera(dark_light); forceRepaint(); } }); // register the toggle light mode action (always possible) actionManager.registerAction("toggle_light_mode", new StateActionPrototype() { @Override public void action(ActionEvent actionEvent) { preferences.storeBoolean("light_mode_active", !staticLightOn); } @Override public boolean getStatus() { return !staticLightOn; } }); if (!preferences.contains("grid_mode_active")) { preferences.storeBoolean("grid_mode_active", gridModeOn); } // react to changes on the grid status preferences.addPrefChangeListener("grid_mode_active", new PrefChangeListener() { @Override public void onPrefChange(Object o) { gridModeOn = (Boolean) o; world.setBorder(gridModeOn); forceRepaint(); } }); // register the toggle grid mode action (always possible) actionManager.registerAction("toggle_grid_mode", new StateActionPrototype() { @Override public void action(ActionEvent actionEvent) { preferences.storeBoolean("grid_mode_active", !gridModeOn); } @Override public boolean getStatus() { return gridModeOn; } }); // camera settings camera.setFOVLimits(VitcoSettings.MAIN_VIEW_ZOOM_FOV,VitcoSettings.MAIN_VIEW_ZOOM_FOV); camera.setFOV(VitcoSettings.MAIN_VIEW_ZOOM_FOV); camera.setZoomLimits(VitcoSettings.MAIN_VIEW_ZOOM_IN_LIMIT, VitcoSettings.MAIN_VIEW_ZOOM_OUT_LIMIT); camera.setView(VitcoSettings.MAIN_VIEW_CAMERA_POSITION); // camera initial position // =============== BOUNDING BOX // add the bounding box (texture) final Object3D[] boundingBox = {WorldManager.getGridPlane()}; final int[] boundingBoxId = {world.addObject(boundingBox[0])}; // listen to bounding box size changes and change texture object (only in main view) // Note: This doesn't need a repaint since that is done in a more general listener preferences.addPrefChangeListener("bounding_box_size", new PrefChangeListener() { @Override public void onPrefChange(Object newValue) { // generate new bounding box boundingBox[0] = WorldManager.getGridPlane(); boundingBox[0].setVisibility(useBoundingBox); // remove old bounding box world.removeObject(boundingBoxId[0]); // add new bounding box boundingBoxId[0] = world.addObject(boundingBox[0]); } }); // listen to bounding box visibility changes preferences.addPrefChangeListener("use_bounding_box", new PrefChangeListener() { @Override public void onPrefChange(Object o) { useBoundingBox = (Boolean)o; container.setDrawBoundingBox(useBoundingBox); // overlay part boundingBox[0].setVisibility(useBoundingBox); // texture part // redraw container container.doNotSkipNextWorldRender(); forceRepaint(); } }); // make sure the preference is set if (!preferences.contains("use_bounding_box")) { preferences.storeBoolean("use_bounding_box", useBoundingBox); } actionManager.registerAction("toggle_bounding_box", new StateActionPrototype() { @Override public void action(ActionEvent actionEvent) { preferences.storeBoolean("use_bounding_box", !useBoundingBox); } @Override public boolean getStatus() { return useBoundingBox; } }); // =============== // user mouse input - change camera position MouseAdapter mouseAdapter = new MouseAdapter() { @Override public void mouseWheelMoved(final MouseWheelEvent e) { // scroll = zoom in and out asyncActionManager.addAsyncAction(new AsyncAction() { @Override public void performAction() { int rotation = e.getWheelRotation(); if (rotation < 0) { camera.zoomIn(Math.abs(rotation) * VitcoSettings.MAIN_VIEW_ZOOM_SPEED_SLOW); } else { camera.zoomOut(rotation * VitcoSettings.MAIN_VIEW_ZOOM_SPEED_SLOW); } voxelAdapter.replayHover(); container.doNotSkipNextWorldRender(); forceRepaint(); } }); } // left, middle, right private Point[] mouseDown = new Point[] {null, null, null}; private String[] mouseAction = new String[] {null, null, null}; { preferences.addPrefChangeListener("mbutton1", newValue -> mouseAction[0] = (String) newValue); preferences.addPrefChangeListener("mbutton2", newValue -> mouseAction[1] = (String) newValue); preferences.addPrefChangeListener("mbutton3", newValue -> mouseAction[2] = (String) newValue); } @Override public void mousePressed(final MouseEvent e) { asyncActionManager.addAsyncAction(new AsyncAction() { @Override public void performAction() { switch (e.getModifiers() & (MouseEvent.BUTTON1_MASK | MouseEvent.BUTTON2_MASK | MouseEvent.BUTTON3_MASK)) { case MouseEvent.BUTTON1_MASK: mouseDown[0] = e.getPoint(); break; case MouseEvent.BUTTON2_MASK: mouseDown[1] = e.getPoint(); break; case MouseEvent.BUTTON3_MASK: mouseDown[2] = e.getPoint(); break; default: break; } } }); } @Override public void mouseReleased(final MouseEvent e) { asyncActionManager.addAsyncAction(new AsyncAction() { @Override public void performAction() { switch (e.getModifiers() & (MouseEvent.BUTTON1_MASK | MouseEvent.BUTTON2_MASK | MouseEvent.BUTTON3_MASK)) { case MouseEvent.BUTTON1_MASK: mouseDown[0] = null; break; case MouseEvent.BUTTON2_MASK: mouseDown[1] = null; break; case MouseEvent.BUTTON3_MASK: mouseDown[2] = null; break; default: break; } } }); } @Override public void mouseDragged(final MouseEvent e) { asyncActionManager.addAsyncAction(new AsyncAction() { @Override public void performAction() { Point rotateMouseButton = null; Point truckMouseButton = null; for (int i = 0; i < 3; i++) { switch (mouseAction[i]) { case "rotate": if (rotateMouseButton == null) { rotateMouseButton = mouseDown[i]; } break; case "truck": if (truckMouseButton == null) { truckMouseButton = mouseDown[i]; } break; } } if (rotateMouseButton != null) { camera.rotate(e.getX() - rotateMouseButton.x, e.getY() - rotateMouseButton.y); rotateMouseButton.x = e.getX(); rotateMouseButton.y = e.getY(); container.doNotSkipNextWorldRender(); forceRepaint(); } else if (truckMouseButton != null) { camera.shift(e.getX() - truckMouseButton.x, e.getY() - truckMouseButton.y, VitcoSettings.MAIN_VIEW_SIDE_MOVE_FACTOR); truckMouseButton.x = e.getX(); truckMouseButton.y = e.getY(); container.doNotSkipNextWorldRender(); forceRepaint(); } } }); } }; container.addMouseWheelListener(mouseAdapter); container.addMouseMotionListener(mouseAdapter); container.addMouseListener(mouseAdapter); abstract class CameraAction extends SwitchActionPrototype { protected abstract void step(); private LifeTimeThread thread = null; @Override public void switchOn() { if (thread == null) { thread = new LifeTimeThread() { @Override public void loop() throws InterruptedException { asyncActionManager.addAsyncAction(new AsyncAction() { @Override public void performAction() { step(); voxelAdapter.replayHover(); forceRepaint(); } }); synchronized (this) { thread.wait(25); } } }; threadManager.manage(thread); } } @Override public void switchOff() { if (thread != null) { threadManager.remove(thread); thread = null; } } } // register zoom buttons actionManager.registerAction("mainview_zoom_in", new CameraAction() { @Override protected void step() { camera.zoomIn(VitcoSettings.MAIN_VIEW_BUTTON_ZOOM_SPEED); } }); actionManager.registerAction("mainview_zoom_out", new CameraAction() { @Override protected void step() { camera.zoomOut(VitcoSettings.MAIN_VIEW_BUTTON_ZOOM_SPEED); } }); // register rotate buttons actionManager.registerAction("mainview_rotate_left", new CameraAction() { @Override protected void step() { camera.rotate(VitcoSettings.MAIN_VIEW_BUTTON_ROTATE_SIDEWAYS_SPEED, 0); } }); actionManager.registerAction("mainview_rotate_right", new CameraAction() { @Override protected void step() { camera.rotate(-VitcoSettings.MAIN_VIEW_BUTTON_ROTATE_SIDEWAYS_SPEED, 0); } }); actionManager.registerAction("mainview_rotate_up", new CameraAction() { @Override protected void step() { camera.rotate(0, VitcoSettings.MAIN_VIEW_BUTTON_ROTATE_OVER_SPEED); } }); actionManager.registerAction("mainview_rotate_down", new CameraAction() { @Override protected void step() { camera.rotate(0, -VitcoSettings.MAIN_VIEW_BUTTON_ROTATE_OVER_SPEED); } }); // register move buttons actionManager.registerAction("mainview_move_left", new CameraAction() { @Override protected void step() { camera.shift(1, 0, VitcoSettings.MAIN_VIEW_BUTTON_MOVE_SIDEWAYS_SPEED); } }); actionManager.registerAction("mainview_move_right", new CameraAction() { @Override protected void step() { camera.shift(-1, 0, VitcoSettings.MAIN_VIEW_BUTTON_MOVE_SIDEWAYS_SPEED); } }); actionManager.registerAction("mainview_move_up", new CameraAction() { @Override protected void step() { camera.shift(0, 1, VitcoSettings.MAIN_VIEW_BUTTON_MOVE_OVER_SPEED); } }); actionManager.registerAction("mainview_move_down", new CameraAction() { @Override protected void step() { camera.shift(0, -1, VitcoSettings.MAIN_VIEW_BUTTON_MOVE_OVER_SPEED); } }); // register reset action actionManager.registerAction("reset_main_view_camera", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { camera.setView(VitcoSettings.MAIN_VIEW_CAMERA_POSITION); container.doNotSkipNextWorldRender(); forceRepaint(); } }); actionManager.registerAction("center_main_view_camera", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { camera.setCenterShift(new SimpleVector( -preferences.loadInteger("currentplane_sideview3") * VitcoSettings.VOXEL_SIZE, -preferences.loadInteger("currentplane_sideview2") * VitcoSettings.VOXEL_SIZE, -preferences.loadInteger("currentplane_sideview1") * VitcoSettings.VOXEL_SIZE )); container.doNotSkipNextWorldRender(); forceRepaint(); } }); // register "align view to side plane" actions actionManager.registerAction("align_main_to_sideview1", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { SimpleVector pos = new SimpleVector(VitcoSettings.SIDE_VIEW1_CAMERA_POSITION); pos.makeEqualLength(camera.getPosition()); camera.setView(pos); forceRepaint(); } }); actionManager.registerAction("align_main_to_sideview2", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { SimpleVector pos = new SimpleVector(VitcoSettings.SIDE_VIEW2_CAMERA_POSITION); pos.makeEqualLength(camera.getPosition()); camera.setView(pos); forceRepaint(); } }); actionManager.registerAction("align_main_to_sideview3", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { SimpleVector pos = new SimpleVector(VitcoSettings.SIDE_VIEW3_CAMERA_POSITION); pos.makeEqualLength(camera.getPosition()); camera.setView(pos); forceRepaint(); } }); // register button action for wireframe toggle actionManager.registerAction("main_window_toggle_wireframe", new StateActionPrototype() { private boolean useWireFrame = false; // always false on startup @Override public void action(ActionEvent actionEvent) { useWireFrame = !useWireFrame; container.useWireFrame(useWireFrame); forceRepaint(); } @Override public boolean getStatus() { return useWireFrame; } }); // holds menu and render area (container) final JPanel wrapper = new JPanel(); wrapper.setLayout(new BorderLayout()); // prevent "flickering" when swapping windows preferences.addPrefChangeListener("engine_view_bg_color", new PrefChangeListener() { @Override public void onPrefChange(Object o) { wrapper.setBackground((Color) o); } }); // create menu CommandMenuBar menuPanel = new CommandMenuBar(); //menuPanel.setOrientation(1); // top down orientation menuPanel.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); menuGenerator.buildMenuFromXML(menuPanel, "com/vitco/app/layout/content/mainview/toolbar.xml"); // so the background doesn't show menuPanel.setOpaque(true); // add to wrapper wrapper.add(menuPanel, BorderLayout.SOUTH); wrapper.add(container, BorderLayout.CENTER); return wrapper; } }
40.476974
145
0.543072
71be827cbf27991e99b512c30500430b25eeafc2
593
package com.createchance.imageeditor.drawers; import com.createchance.imageeditor.shaders.DirectionalWarpTransShader; /** * Directional warp transition drawer. * * @author createchance * @date 2018/12/31 */ public class DirectionalWarpTransDrawer extends AbstractTransDrawer { @Override protected void getTransitionShader() { mTransitionShader = new DirectionalWarpTransShader(); } public void setDirectional(float directionalX, float directionalY) { ((DirectionalWarpTransShader) mTransitionShader).setUDirectional(directionalX, directionalY); } }
28.238095
101
0.767285
98b2bb24776388913273b82cc0cde443d79cfb55
3,432
/* * 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.sling.replication.queue.impl.jobhandling; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.sling.event.jobs.Job; import org.apache.sling.replication.queue.ReplicationQueueItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JobHandlingUtils { private static final String PATHS = "replication.package.paths"; public static final String ID = "replication.package.id"; private static final String TYPE = "replication.package.type"; protected static final String ACTION = "replication.package.action"; public static ReplicationQueueItem getPackage(final Job job) { return new ReplicationQueueItem((String) job.getProperty(ID), (String[]) job.getProperty(PATHS), String.valueOf(job.getProperty(ACTION)), String.valueOf(job.getProperty(TYPE))); } public static Map<String, Object> createFullPropertiesFromPackage( ReplicationQueueItem replicationPackage) { Map<String, Object> properties = new HashMap<String, Object>(); properties.put(ID, replicationPackage.getId()); properties.put(PATHS, replicationPackage.getPaths()); properties.put(ACTION, replicationPackage.getAction()); properties.put(TYPE, replicationPackage.getType()); return properties; } public static Map<String, Object> createIdPropertiesFromPackage( ReplicationQueueItem replicationPackage) { Map<String, Object> properties = new HashMap<String, Object>(); properties.put(ID, replicationPackage.getId()); return properties; } public static Byte[] box(byte[] bytes) { if (bytes == null) return null; Byte[] result = new Byte[bytes.length]; for (int i = 0; i < bytes.length; i++) { result[i] = bytes[i]; } return result; } public static byte[] unBox(Byte[] bytes) { if (bytes == null) return null; byte[] result = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) { result[i] = bytes[i]; } return result; } public static String getQueueName(Job job) { String topic = job.getTopic(); if (topic == null || !topic.startsWith(JobHandlingReplicationQueue.REPLICATION_QUEUE_TOPIC)) return null; String queue = topic.substring(JobHandlingReplicationQueue.REPLICATION_QUEUE_TOPIC.length() + 1); int idx = queue.indexOf("/"); if (idx < 0) return ""; return queue.substring(idx + 1); } }
35.381443
113
0.678904
1406a49bffe1f4d63f69e10fe4e5c16bce4209fb
4,786
/* * @(#)ObjectKey.java * Copyright © 2021 The authors and contributors of JHotDraw. MIT License. */ package org.jhotdraw8.collection; import org.jhotdraw8.annotation.NonNull; import org.jhotdraw8.annotation.Nullable; import org.jhotdraw8.reflect.TypeToken; import java.lang.reflect.Type; import java.util.Objects; /** * A <em>name</em> which provides typesafe access to a map entry. * <p> * A Key has a name, a type and a default value. * <p> * The following code example shows how to set and get a value from a map. * <pre> * {@code * String value = "Werner"; * Key<String> stringKey = new Key("name",String.class,null); * Map<Key<?>,Object> map = new HashMap<>(); * stringKey.put(map, value); * } * </pre> * <p> * Note that {@code Key} is not a value type. Thus using two distinct instances * of a Key will result in two distinct entries in the hash map, even if both * keys have the same name. * * @author Werner Randelshofer */ public abstract class AbstractKey<T> implements Key<T> { private static final long serialVersionUID = 1L; private final int ordinal; /** * Holds a String representation of the name. */ private final @NonNull String name; /** * Holds the default value. */ private final @Nullable T initialValue; /** * This variable is used as a "type token" so that we can check for * assignability of attribute values at runtime. */ private final @NonNull Type type; /** * Whether the value may be set to null. */ private final boolean isNullable; private final boolean isTransient; /** * Creates a new instance with the specified name, type token class, default * value null, and allowing null values. * * @param name The name of the key. * @param clazz The type of the value. */ public AbstractKey(@NonNull String name, @NonNull Type clazz) { this(name, clazz, null); } public AbstractKey(@NonNull String name, @NonNull TypeToken<T> clazz, T initialValue) { this(name, clazz.getType(), initialValue); } /** * Creates a new instance with the specified name, type token class, default * value, and allowing or disallowing null values. * * @param name The name of the key. * @param clazz The type of the value. * @param initialValue The default value. */ public AbstractKey(@NonNull String name, @NonNull Type clazz, @Nullable T initialValue) { this(name, clazz, true, initialValue); } /** * Creates a new instance with the specified name, type token class, default * value, and allowing or disallowing null values. * * @param name The name of the key. * @param clazz The type of the value. * @param isNullable Whether the value may be set to null * @param initialValue The default value. */ public AbstractKey(@NonNull String name, @NonNull Type clazz, boolean isNullable, @Nullable T initialValue) { this(name, clazz, isNullable, false, initialValue); } public AbstractKey(@NonNull String name, @NonNull Type clazz, @Nullable Class<?>[] typeParameters, boolean isNullable, @Nullable T initialValue) { this(name, clazz, isNullable, false, initialValue); } public AbstractKey(@Nullable String name, @NonNull Type clazz, boolean isNullable, boolean isTransient, @Nullable T initialValue) { Objects.requireNonNull(name, "name"); Objects.requireNonNull(clazz, "clazz"); if (!isNullable && initialValue == null) { throw new IllegalArgumentException("defaultValue may not be null if isNullable==false"); } this.name = name; this.type = clazz; this.isNullable = isNullable; this.isTransient = isTransient; this.initialValue = initialValue; this.ordinal = Key.createNextOrdinal(); } /** * Returns the name string. * * @return name string. */ @Override public @NonNull String getName() { return name; } @Override public @NonNull Type getValueType() { return type; } @Override public @Nullable T getDefaultValue() { return initialValue; } @Override public boolean isNullable() { return isNullable; } public boolean isTransient() { return isTransient; } /** * Returns the name string. */ @Override public @NonNull String toString() { String keyClass = getClass().getName(); return keyClass.substring(keyClass.lastIndexOf('.') + 1) + "@" + System.identityHashCode(this) + " {\"" + name + "\"}"; } public int ordinal() { return ordinal; } }
29.54321
150
0.637484
54fd9e7cd004189c2c9d7f0ff0b874ac32f9220e
10,783
package algebra.curves.barreto_naehrig; import algebra.fields.*; import java.math.BigInteger; public interface BNFields { /* Scalar field Fr */ public abstract class BNFr<BNFrT extends BNFr<BNFrT>> extends AbstractFieldElementExpanded<BNFrT> { public abstract Fp element(); public abstract BNFrT zero(); public abstract BNFrT one(); public abstract BNFrT multiplicativeGenerator(); public abstract BNFrT construct(final Fp element); public abstract String toString(); public BNFrT add(final BNFrT other) { return this.construct(this.element().add(other.element())); } public BNFrT sub(final BNFrT other) { return this.construct(this.element().sub(other.element())); } public BNFrT mul(final BNFrT other) { return this.construct(this.element().mul(other.element())); } public boolean isZero() { return this.equals(this.zero()); } public boolean isSpecial() { return this.isZero(); } public boolean isOne() { return this.equals(this.one()); } public BNFrT random(final Long seed, final byte[] secureSeed) { return this.construct(this.element().random(seed, secureSeed)); } public BNFrT negate() { return this.construct(this.element().negate()); } public BNFrT inverse() { return this.construct(this.element().inverse()); } public BNFrT square() { return this.construct(this.element().square()); } public BNFrT rootOfUnity(final long size) { return this.construct(this.element().rootOfUnity(size)); } public int bitSize() { return this.element().bitSize(); } public BigInteger toBigInteger() { return this.element().toBigInteger(); } public boolean equals(final BNFrT other) { if (other == null) { return false; } return this.element().equals(other.element()); } } /* Base field Fq */ public abstract class BNFq<BNFqT extends BNFq<BNFqT>> extends AbstractFieldElementExpanded<BNFqT> { public abstract Fp element(); public abstract BNFqT zero(); public abstract BNFqT one(); public abstract BNFqT multiplicativeGenerator(); public abstract BNFqT construct(final long element); public abstract BNFqT construct(final Fp element); public abstract String toString(); public BNFqT add(final BNFqT other) { return this.construct(this.element().add(other.element())); } public BNFqT sub(final BNFqT other) { return this.construct(this.element().sub(other.element())); } public BNFqT mul(final BNFqT other) { return this.construct(this.element().mul(other.element())); } public BNFqT mul(final Fp other) { return this.construct(this.element().mul(other)); } public boolean isZero() { return this.equals(this.zero()); } public boolean isSpecial() { return this.isZero(); } public boolean isOne() { return this.equals(this.one()); } public BNFqT random(final Long seed, final byte[] secureSeed) { return this.construct(this.element().random(seed, secureSeed)); } public BNFqT negate() { return this.construct(this.element().negate()); } public BNFqT inverse() { return this.construct(this.element().inverse()); } public BNFqT square() { return this.construct(this.element().square()); } public BNFqT rootOfUnity(final long size) { return this.construct(this.element().rootOfUnity(size)); } public int bitSize() { return this.element().bitSize(); } public BigInteger toBigInteger() { return this.element().toBigInteger(); } public boolean equals(final BNFqT other) { if (other == null) { return false; } return this.element().equals(other.element()); } } /* Twist field Fq2 */ public abstract class BNFq2<BNFqT extends BNFq<BNFqT>, BNFq2T extends BNFq2<BNFqT, BNFq2T>> extends AbstractFieldElement<BNFq2T> { public abstract Fp2 element(); public abstract BNFq2T zero(); public abstract BNFq2T one(); public abstract BNFq2T construct(final Fp2 element); public abstract String toString(); public BNFq2T add(final BNFq2T other) { return this.construct(this.element().add(other.element())); } public BNFq2T sub(final BNFq2T other) { return this.construct(this.element().sub(other.element())); } public BNFq2T mul(final BNFq2T other) { return this.construct(this.element().mul(other.element())); } public BNFq2T mul(final BNFqT other) { return this.construct(this.element().mul(other.element())); } public boolean isZero() { return this.equals(this.zero()); } public boolean isOne() { return this.equals(this.one()); } public BNFq2T random(final Long seed, final byte[] secureSeed) { return this.construct(this.element().random(seed, secureSeed)); } public BNFq2T negate() { return this.construct(this.element().negate()); } public BNFq2T inverse() { return this.construct(this.element().inverse()); } public BNFq2T square() { return this.construct(this.element().square()); } public BNFq2T FrobeniusMap(long power) { return this.construct(this.element().FrobeniusMap(power)); } public int bitSize() { return this.element().bitSize(); } public boolean equals(final BNFq2T other) { if (other == null) { return false; } return this.element().equals(other.element()); } } /* Field Fq6 */ public abstract class BNFq6< BNFqT extends BNFq<BNFqT>, BNFq2T extends BNFq2<BNFqT, BNFq2T>, BNFq6T extends BNFq6<BNFqT, BNFq2T, BNFq6T>> extends AbstractFieldElement<BNFq6T> { public abstract Fp6_3Over2 element(); public abstract BNFq6T zero(); public abstract BNFq6T one(); public abstract Fp2 mulByNonResidue(final Fp2 other); public abstract BNFq6T construct(final Fp6_3Over2 element); public abstract String toString(); public BNFq6T add(final BNFq6T other) { return this.construct(this.element().add(other.element())); } public BNFq6T sub(final BNFq6T other) { return this.construct(this.element().sub(other.element())); } public BNFq6T mul(final BNFqT other) { return this.construct(this.element().mul(other.element())); } public BNFq6T mul(final BNFq2T other) { return this.construct(this.element().mul(other.element())); } public BNFq6T mul(final BNFq6T other) { return this.construct(this.element().mul(other.element())); } public boolean isZero() { return this.equals(this.zero()); } public boolean isOne() { return this.equals(this.one()); } public BNFq6T random(final Long seed, final byte[] secureSeed) { return this.construct(this.element().random(seed, secureSeed)); } public BNFq6T negate() { return this.construct(this.element().negate()); } public BNFq6T square() { return this.construct(this.element().square()); } public BNFq6T inverse() { return this.construct(this.element().inverse()); } public BNFq6T FrobeniusMap(long power) { return this.construct(this.element().FrobeniusMap(power)); } public int bitSize() { return this.element().bitSize(); } public boolean equals(final BNFq6T other) { if (other == null) { return false; } return this.element().equals(other.element()); } } /* Field Fq12 */ public abstract class BNFq12< BNFqT extends BNFq<BNFqT>, BNFq2T extends BNFq2<BNFqT, BNFq2T>, BNFq6T extends BNFq6<BNFqT, BNFq2T, BNFq6T>, BNFq12T extends BNFq12<BNFqT, BNFq2T, BNFq6T, BNFq12T>> extends AbstractFieldElement<BNFq12T> { public abstract Fp12_2Over3Over2 element(); public abstract BNFq12T zero(); public abstract BNFq12T one(); public abstract BNFq12T construct(final Fp12_2Over3Over2 element); public abstract String toString(); public BNFq12T add(final BNFq12T other) { return this.construct(this.element().add(other.element())); } public BNFq12T sub(final BNFq12T other) { return this.construct(this.element().sub(other.element())); } public BNFq12T mul(final BNFqT other) { return this.construct(this.element().mul(other.element())); } public BNFq12T mul(final BNFq2T other) { return this.construct(this.element().mul(other.element())); } public BNFq12T mul(final BNFq6T other) { return this.construct(this.element().mul(other.element())); } // public Fp6_3Over2 mulByNonResidue(final Fp6_3Over2 other) { // return other.construct(Fq12Parameters.nonresidue().mul(other.c2), other.c0, // other.c1); // } public BNFq12T mul(final BNFq12T other) { return this.construct(this.element().mul(other.element())); } public BNFq12T pow(final BigInteger other) { return this.construct(this.element().pow(other)); } public boolean isZero() { return this.equals(this.zero()); } public boolean isOne() { return this.equals(this.one()); } public BNFq12T random(final Long seed, final byte[] secureSeed) { return this.construct(this.element().random(seed, secureSeed)); } public BNFq12T negate() { return this.construct(this.element().negate()); } public BNFq12T square() { return this.construct(this.element().square()); } public BNFq12T inverse() { return this.construct(this.element().inverse()); } public BNFq12T FrobeniusMap(long power) { return this.construct(this.element().FrobeniusMap(power)); } public BNFq12T unitaryInverse() { return this.construct(this.element().unitaryInverse()); } public BNFq12T cyclotomicSquared() { return this.construct(this.element().cyclotomicSquared()); } public BNFq12T mulBy024(final BNFq2T ell0, final BNFq2T ellVW, final BNFq2T ellVV) { return this.construct( this.element().mulBy024(ell0.element(), ellVW.element(), ellVV.element())); } public BNFq12T cyclotomicExponentiation(final BigInteger exponent) { return this.construct(this.element().cyclotomicExponentiation(exponent)); } public int bitSize() { return this.element().bitSize(); } public boolean equals(final BNFq12T other) { if (other == null) { return false; } return this.element().equals(other.element()); } } }
25.431604
93
0.642215
cbd355925aa68e8003dcb096bae41ed87e7dd182
1,363
package designpattern.creational; import java.util.*; import designpattern.util.BasedPattern; public class Prototype implements BasedPattern { @Override public void TestPattern() { Car bmw = new Car(); Car benz = new Car(); Cars cars = new Cars(); cars.addPrototype("BMW", bmw); cars.addPrototype("BENS", benz); try { @SuppressWarnings("unused") Car bmwPrototype = cars.getPrototype("BMW"); } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } class Wheel implements Cloneable { protected Object clone() throws CloneNotSupportedException { return super.clone(); } } class Car implements Cloneable { private Wheel[] wheels = { new Wheel(), new Wheel(), new Wheel(), new Wheel() }; protected Object clone() throws CloneNotSupportedException { Car copy = (Car) super.clone(); copy.wheels = (Wheel[]) this.wheels.clone(); for (int i = 0; i < this.wheels.length; i++) { copy.wheels[i] = (Wheel) this.wheels[i].clone(); } return copy; } } class Cars { private Map<String, Car> prototypes = new HashMap<String, Car>(); void addPrototype(String brand, Car prototype) { prototypes.put(brand, prototype); } Car getPrototype(String brand) throws CloneNotSupportedException { return (Car) prototypes.get(brand).clone(); } } }
23.101695
68
0.680117
dc29561d84e8881d276245e1821e6c0f553d2e53
3,621
package com.phoenix.phoenixtales.rise.client.screen; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; import com.phoenix.phoenixtales.core.PhoenixTales; import com.phoenix.phoenixtales.rise.block.blocks.alloyfactory.AlloyContainer; import com.phoenix.phoenixtales.rise.block.blocks.alloyfactory.AlloyTile; import net.minecraft.client.gui.screen.inventory.ContainerScreen; import net.minecraft.client.world.ClientWorld; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; public class AlloyScreen extends ContainerScreen<AlloyContainer> { private static final ResourceLocation TEXTURE = new ResourceLocation(PhoenixTales.MOD_ID, "textures/gui/alloy_gui.png"); private AlloyTile tile = null; public AlloyScreen(AlloyContainer screenContainer, PlayerInventory inv, ITextComponent titleIn) { super(screenContainer, inv, titleIn); } @Override protected void init() { super.init(); this.tile = this.getTileEntity(); } @Override public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) { this.renderBackground(matrixStack); super.render(matrixStack, mouseX, mouseY, partialTicks); this.renderHoveredTooltip(matrixStack, mouseX, mouseY); } @SuppressWarnings("deprecation") @Override protected void drawGuiContainerBackgroundLayer(MatrixStack matrixStack, float partialTicks, int x, int y) { RenderSystem.color4f(1f, 1f, 1f, 1f); this.minecraft.getTextureManager().bindTexture(TEXTURE); int i = this.guiLeft; int j = this.guiTop; this.blit(matrixStack, i, j, 0, 0, this.xSize, this.ySize); double percent = (double) (this.tile.getProgressPercent()) / 100d; if (percent < 0.4285d) { double p1 = 0.4285d * percent; this.blit(matrixStack, i + 64, j + 26, 199, 0, (int) (p1 * 24d), 3); this.blit(matrixStack, i + 88, j + 26, 223, 0, 24 - (int) (p1 * 24d), 3); } else { double p2 = 0.5715d * percent; this.blit(matrixStack, i + 64, j + 26, 199, 0, 24, 3); this.blit(matrixStack, i + 88, j + 26, 223, 0, 0, 3); this.blit(matrixStack, i + 84, j + 28, 219, 2, 8, (int) (p2 * 32d)); } double energyP = (double) (this.tile.getEnergyPercent()) / 100d; this.blit(matrixStack, i + 167, j + 5, 194, 1, 3, 75 - ((int) (energyP * 75d))); // if (container.getProgress() > 0) { // this.playerInventory.player.sendMessage(new StringTextComponent("progress = " + this.getProgress() + " and total = " + this.getTotal()), playerInventory.player.getUniqueID()); // int i1 = this.getContainer().getProgressScaled(23); // this.blit(matrixStack, i + 84, j + 33, 192, 0, 8, i1 + 23); // } // int k = this.container.getCookProgressionScaled(); // this.blit(matrixStack, /*k*/i + 84, /*k*/j + 33, /*k*/192, /*k*/0, 8, k + 1); // if (container.isValid()) { // this.blit(matrixStack, i + 82, j + 9, 176, 0, 13, 17); // } } private AlloyTile getTileEntity() { ClientWorld world = this.getMinecraft().world; if (world != null) { TileEntity tile = world.getTileEntity(this.getContainer().getPos()); if (tile instanceof AlloyTile) { return (AlloyTile) tile; } } return null; } }
38.521277
189
0.639602
a64e6a5a3c9370c4c2e575b53915b01c930f90a1
2,025
package by.andd3dfx.configs; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.converter.MappingJackson2MessageConverter; import org.springframework.messaging.converter.MessageConverter; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Autowired private ObjectMapper objectMapper; @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic") .setTaskScheduler(heartBeatScheduler()); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws-client") .setAllowedOrigins("*") .withSockJS(); } @Override public boolean configureMessageConverters(List<MessageConverter> messageConverters) { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); converter.setObjectMapper(objectMapper); messageConverters.add(converter); // Don't add default converters. return false; } @Bean public TaskScheduler heartBeatScheduler() { return new ThreadPoolTaskScheduler(); } }
38.207547
91
0.766914
c580efee7e245fb75f4d9653330b2337c3754cd8
1,961
/** * Copyright (C) 2002 Mike Hummel ([email protected]) * * 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.summerclouds.common.core.operation; import org.summerclouds.common.core.log.Log; public class DefaultMonitor implements Monitor { private long steps; private long step; private StringBuilder lineBuffer = new StringBuilder(); private Log log = null; public DefaultMonitor(Class<?> owner) { log = Log.getLog(owner); } public long getSteps() { return steps; } @Override public void setSteps(long steps) { this.steps = steps; } @Override public long getStep() { return step; } @Override public void setStep(long step) { this.step = step; } @Override public Log log() { return log; } @Override public void println() { synchronized (lineBuffer) { log().i("STDOUT", lineBuffer); lineBuffer = new StringBuilder(); } } @Override public void println(Object... out) { print(out); println(); } @Override public void print(Object... out) { synchronized (lineBuffer) { for (Object o : out) { if (o instanceof Throwable) log.i(null, o); else lineBuffer.append(o); } } } @Override public void incrementStep() { step++; } }
23.345238
75
0.607853
e15c8060a031e69ad4f0f5f088d43565ae4e1ae4
786
package org.develop.algorithm; /** * Hello world! * @author */ public class App { public boolean isPalindrome(String args){ if(null==args || args.length()==0){ return true; } StringBuilder newStr = new StringBuilder(); char[] charStr = args.toCharArray(); for (int i = 0; i < charStr.length; i++) { if(Character.isLetterOrDigit(charStr[i])){ newStr.append(charStr[i]); } } char[] newChar = newStr.toString().toLowerCase().toCharArray(); int i=0, j= newChar.length - 1; while(i < j){ if(newChar[i] != newChar[j]){ return false; } ++ i; -- j; } return true; } }
24.5625
71
0.477099
f31aaedfcef1a0e117d21417950ef571c01d262f
5,137
package me.miles.matthew.SolitaireAnim; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.io.InputStream; import java.util.Random; import javax.imageio.ImageIO; public class Card { private Point2D.Double position; private Point2D.Double velocity; private Point2D.Double acceleration; private Dimension size; private Double coRest; private BufferedImage texture; private static final String[] Cards = { "2_of_clubs.png", "2_of_diamonds.png", "2_of_hearts.png", "2_of_spades.png", "3_of_clubs.png", "3_of_diamonds.png", "3_of_hearts.png", "3_of_spades.png", "4_of_clubs.png", "4_of_diamonds.png", "4_of_hearts.png", "4_of_spades.png", "5_of_clubs.png", "5_of_diamonds.png", "5_of_hearts.png", "5_of_spades.png", "queen_of_clubs.png", "queen_of_diamonds.png", "queen_of_hearts.png", "queen_of_spades.png", "red_joker.png" }; public Card(double x, double y, Dimension size, double coefficientOfRestitution) { position = new Point2D.Double(x, y); velocity = new Point2D.Double(0, 0); acceleration = new Point2D.Double(0, 0); this.size = size; this.coRest = coefficientOfRestitution; this.texture = getRandomImage(); } public static BufferedImage getRandomImage() { // returns a random image from the Images folder Random rand = new Random(); //URL res = Card.class.getResource("Images"); // located in /src/.../Images //File f = new File(res.getFile()); // File f = null; try { //f = new File(Card.class.getProtectionDomain().getCodeSource().getLocation().toURI()); InputStream iconstream = Card.class.getResourceAsStream("res/Images/"+Cards[rand.nextInt(Cards.length)]); BufferedImage img = ImageIO.read(iconstream); return img; } catch (Exception e) { e.printStackTrace(); BufferedImage img = new BufferedImage(2, 2, BufferedImage.TYPE_INT_RGB); img.setRGB(0, 1, 0xFF00FF); img.setRGB(1, 0, 0xFF00FF); return img; } // if (f == null || !f.exists()) { // return new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); // } // File[] files = f.listFiles(); // int random = rand.nextInt(files.length); // BufferedImage img = null; // try { // img = ImageIO.read(files[random]); // } catch (IOException e) { // e.printStackTrace(); // } // return img; } /** * Updates the card's physical state. * @param timePassed The time passed since the last frame in seconds. * @param boundaries The boundaries of the panel. */ public void update(Double timePassed, Dimension boundaries) { velocity.x += acceleration.x*timePassed; velocity.y += acceleration.y*timePassed; position.x += velocity.x*timePassed; position.y += velocity.y*timePassed; // if (position.x - size.width/2 < 0) { // position.x = size.width/2; // velocity.x *= -1; // } // if (position.x + size.width/2 > boundaries.width) { // position.x = boundaries.width - size.width/2; // velocity.x *= -1; // } if (position.y - size.height/2 < 0) { position.y = size.height/2; velocity.y *= -coRest; } if (position.y + size.height/2 > boundaries.height) { position.y = boundaries.height - size.height/2; velocity.y *= -coRest; } if (velocity.x == 0) { velocity.x = 0.5; } // this.texture = getRandomImage(); } public void applyForce(Point2D.Double force) { acceleration.x += force.x; acceleration.y += force.y; } public void addVelocity(Point2D.Double velocity) { this.velocity.x = velocity.x; this.velocity.y = velocity.y; } public double getX() { return position.x; } public double getY() { return position.y; } public int getWidth() { return size.width; } public int getHeight() { return size.height; } public void draw(Graphics2D g2) { int xOrigin = (int) Math.round(position.x-(size.getWidth()/2)); int yOrigin = (int) Math.round(position.y-(size.getHeight()/2)); // g2.setColor(Color.BLACK); // g2.fillRect(xOrigin, yOrigin, size.width, size.height); // g2.setColor(Color.WHITE); // g2.fillRect(xOrigin+1, yOrigin+1, size.width-2, size.height-2); g2.drawImage(texture.getScaledInstance(size.width, size.height, 0), xOrigin, yOrigin, null); } }
32.308176
118
0.559471
92089e43c98247148eeaa226d1abed1bd061b2f6
4,786
/* * Copyright 2017 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.blaze.base.run.producers; import com.google.idea.blaze.base.command.BlazeCommandName; import com.google.idea.blaze.base.command.BlazeFlags; import com.google.idea.blaze.base.model.primitives.TargetExpression; import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; import com.google.idea.blaze.base.run.BlazeCommandRunConfigurationType; import com.google.idea.blaze.base.run.smrunner.BlazeTestEventsHandler; import com.google.idea.blaze.base.run.smrunner.SmRunnerUtils; import com.google.idea.blaze.base.run.state.BlazeCommandRunConfigurationCommonState; import com.intellij.execution.Location; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.annotation.Nullable; /** * Handles the specific case where the user creates a run configuration by selecting test suites / * classes / methods from the test UI tree. * * <p>In this special case we already know the blaze target string, and only need to apply a filter * to the existing configuration. Delegates language-specific filter calculation to {@link * BlazeTestEventsHandler}. */ public class BlazeFilterExistingRunConfigurationProducer extends BlazeRunConfigurationProducer<BlazeCommandRunConfiguration> { public BlazeFilterExistingRunConfigurationProducer() { super(BlazeCommandRunConfigurationType.getInstance()); } @Override protected boolean doSetupConfigFromContext( BlazeCommandRunConfiguration configuration, ConfigurationContext context, Ref<PsiElement> sourceElement) { String testFilter = getTestFilter(context); if (testFilter == null) { return false; } BlazeCommandRunConfigurationCommonState handlerState = configuration.getHandlerStateIfType(BlazeCommandRunConfigurationCommonState.class); if (handlerState == null || !BlazeCommandName.TEST.equals(handlerState.getCommandState().getCommand())) { return false; } // replace old test filter flag if present List<String> flags = new ArrayList<>(handlerState.getBlazeFlagsState().getRawFlags()); flags.removeIf((flag) -> flag.startsWith(BlazeFlags.TEST_FILTER)); flags.add(testFilter); if (SmRunnerUtils.countSelectedTestCases(context) == 1 && !flags.contains(BlazeFlags.DISABLE_TEST_SHARDING)) { flags.add(BlazeFlags.DISABLE_TEST_SHARDING); } handlerState.getBlazeFlagsState().setRawFlags(flags); configuration.setName(configuration.getName() + " (filtered)"); configuration.setNameChangedByUser(true); return true; } @Override protected boolean doIsConfigFromContext( BlazeCommandRunConfiguration configuration, ConfigurationContext context) { String testFilter = getTestFilter(context); if (testFilter == null) { return false; } BlazeCommandRunConfigurationCommonState handlerState = configuration.getHandlerStateIfType(BlazeCommandRunConfigurationCommonState.class); return handlerState != null && Objects.equals(handlerState.getCommandState().getCommand(), BlazeCommandName.TEST) && Objects.equals(testFilter, handlerState.getTestFilterFlag()); } @Nullable private static String getTestFilter(ConfigurationContext context) { RunConfiguration base = context.getOriginalConfiguration(null); if (!(base instanceof BlazeCommandRunConfiguration)) { return null; } TargetExpression target = ((BlazeCommandRunConfiguration) base).getTarget(); if (target == null) { return null; } BlazeTestEventsHandler testEventsHandler = BlazeTestEventsHandler.getHandlerForTarget(context.getProject(), target); if (testEventsHandler == null) { return null; } List<Location<?>> selectedElements = SmRunnerUtils.getSelectedSmRunnerTreeElements(context); if (selectedElements.isEmpty()) { return null; } return testEventsHandler.getTestFilter(context.getProject(), selectedElements); } }
40.559322
99
0.763477
da0e577efc791adde0e0d122aded4c08ec44c894
1,236
package sketch.util.fcns; import java.util.Vector; /** * map values from one iterator to another. * * @author gatoatigrado (nicholas tung) [email: ntung at ntung] * @license This file is licensed under BSD license, available at * http://creativecommons.org/licenses/BSD/. While not required, if you make * changes, please consider contributing back! */ public class VectorMap { public static <INTYPE, OUTTYPE> Vector<OUTTYPE> vecmap(Iterable<INTYPE> inarr, VectorMapFcn<INTYPE, OUTTYPE> map) { Vector<OUTTYPE> result = new Vector<OUTTYPE>(); for (INTYPE elt : inarr) { result.add(map.map(elt)); } return result; } public static <INTYPE, OUTTYPE> Vector<OUTTYPE> vecmap_nonnull( Iterable<INTYPE> inarr, VectorMapFcn<INTYPE, OUTTYPE> map) { Vector<OUTTYPE> result = new Vector<OUTTYPE>(); for (INTYPE elt : inarr) { final OUTTYPE next = map.map(elt); if (next != null) { result.add(next); } } return result; } public static abstract class VectorMapFcn<INTYPE, OUTTYPE> { public abstract OUTTYPE map(INTYPE arg); } }
30.146341
85
0.610032
c02aa3f513caab2fed1a22fd9bed1e5cc392ec8a
1,975
package org.rcsb.cif.binary.data; import org.rcsb.cif.binary.encoding.ByteArrayEncoding; import org.rcsb.cif.binary.encoding.Encoding; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; /** * An array of floating point numbers using 32 bit to store each value. */ public class Float32Array extends AbstractEncodedData<double[]> implements FloatArray { private static final int NUMBER_OF_BYTES = 4; private static final int TYPE = 32; public Float32Array(double[] data) { this(data, new ArrayDeque<>()); } public Float32Array(double[] data, Deque<Encoding<?, ?>> encoding) { super(data, encoding); } public Float32Array(ByteArray array) { super(formArray(array.getData()), array.getEncoding()); } private static double[] formArray(byte[] array) { double[] doubles = new double[array.length / NUMBER_OF_BYTES]; ByteBuffer byteBuffer = ByteBuffer.wrap(array).order(ByteOrder.LITTLE_ENDIAN); for (int i = 0; i < doubles.length; i++) { doubles[i] = byteBuffer.getFloat(); } return doubles; } @Override public double[] getData() { return (double[]) data; } @Override public byte[] toByteArray() { ByteBuffer buffer = ByteBuffer.allocate(length() * NUMBER_OF_BYTES); buffer.order(ByteOrder.LITTLE_ENDIAN); for (double d : getData()) { buffer.putFloat((float) d); } return buffer.array(); } @Override public int getNumberOfBytes() { return NUMBER_OF_BYTES; } @Override public int getType() { return TYPE; } @Override public ByteArray encode() { return ByteArrayEncoding.FLOAT32.encode(this); } @Override public String toString() { return getClass().getSimpleName() + ": " + Arrays.toString(getData()); } }
26.333333
87
0.639494
ecb26eb480abe0163c3b922a5787adbe0bec8e0a
290
package br.com.eng_software.loja.dao; import org.springframework.data.repository.CrudRepository; import br.com.eng_software.loja.model.Usuario; public interface UsuarioDAO extends CrudRepository<Usuario, Integer> { public Usuario findByUsernameOrEmail(String username, String email); }
29
70
0.831034
8b61d3cdfe7dfa41d2f63c4b4b85e3a10ca21891
3,714
package com.qh.system.controller; import com.github.pagehelper.PageInfo; import com.qh.common.annotation.OperationLog; import com.qh.common.util.PageResultBean; import com.qh.common.util.ResultBean; import com.qh.common.validate.groups.Create; import com.qh.system.model.User; import com.qh.system.service.RoleService; import com.qh.system.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.validation.Valid; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @Resource private UserService userService; @Resource private RoleService roleService; @GetMapping("/index") public String index() { return "user/user-list"; } @OperationLog("获取用户列表") @GetMapping("/list") @ResponseBody public PageResultBean<User> getList(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "10") int limit, User userQuery) { List<User> users = userService.selectAllWithDept(page, limit, userQuery); PageInfo<User> userPageInfo = new PageInfo<>(users); return new PageResultBean<>(userPageInfo.getTotal(), userPageInfo.getList()); } @GetMapping public String add(Model model) { model.addAttribute("roles", roleService.selectAll()); return "user/user-add"; } @GetMapping("/{userId}") public String update(@PathVariable("userId") Integer userId, Model model) { model.addAttribute("roleIds", userService.selectRoleIdsById(userId)); model.addAttribute("user", userService.selectOne(userId)); model.addAttribute("roles", roleService.selectAll()); return "user/user-add"; } @OperationLog("编辑角色") @PutMapping @ResponseBody public ResultBean update(@Valid User user, @RequestParam(value = "role[]", required = false) Integer[] roleIds) { userService.update(user, roleIds); return ResultBean.success(); } @OperationLog("新增用户") @PostMapping @ResponseBody public ResultBean add(@Validated(Create.class) User user, @RequestParam(value = "role[]", required = false) Integer[] roleIds) { return ResultBean.success(userService.add(user, roleIds)); } @OperationLog("禁用账号") @PostMapping("/{userId:\\d+}/disable") @ResponseBody public ResultBean disable(@PathVariable("userId") Integer userId) { return ResultBean.success(userService.disableUserByID(userId)); } @OperationLog("激活账号") @PostMapping("/{userId}/enable") @ResponseBody public ResultBean enable(@PathVariable("userId") Integer userId) { return ResultBean.success(userService.enableUserByID(userId)); } @OperationLog("删除账号") @DeleteMapping("/{userId}") @ResponseBody public ResultBean delete(@PathVariable("userId") Integer userId) { userService.delete(userId); return ResultBean.success(); } @GetMapping("/{userId}/reset") public String resetPassword(@PathVariable("userId") Integer userId, Model model) { model.addAttribute("userId", userId); return "user/user-reset-pwd"; } @OperationLog("重置密码") @PostMapping("/{userId}/reset") @ResponseBody public ResultBean resetPassword(@PathVariable("userId") Integer userId, String password) { userService.updatePasswordByUserId(userId, password); return ResultBean.success(); } }
33.763636
132
0.683091
324686eca9586a6c3e4bb0f3c2d78846ad249302
1,169
package ratelimit; /** * 平滑突发 * * @author zhaoxuyang */ public class SmoothBursty extends SmoothRateLimiter { /** * 在RateLimiter未使用时,最多存储几秒的令牌 */ final double maxBurstSeconds; /** * @param stopwatch guava中的一个时钟类实例,会通过这个来计算时间及令牌 * @param maxBurstSeconds 在ReteLimiter未使用时,最多保存几秒的令牌,默认是1 */ SmoothBursty(SleepingStopwatch stopwatch, double maxBurstSeconds) { super(stopwatch); this.maxBurstSeconds = maxBurstSeconds; } @Override void doSetRate(double permitsPerSecond, double stableIntervalMicros) { double oldMaxPermits = this.maxPermits; maxPermits = maxBurstSeconds * permitsPerSecond; if (oldMaxPermits == Double.POSITIVE_INFINITY) { storedPermits = maxPermits; } else { storedPermits = (oldMaxPermits == 0.0) ? 0.0 : storedPermits * maxPermits / oldMaxPermits; } } @Override long storedPermitsToWaitTime(double storedPermits, double permitsToTake) { return 0L; } @Override double coolDownIntervalMicros() { return stableIntervalMicros; } }
24.87234
78
0.639863
13350315d50b0b8179639b1a8e86c0cc14593f64
3,038
package ru.otus.appcontainer; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import ru.otus.appcontainer.api.AppComponent; import ru.otus.appcontainer.api.AppComponentsContainer; import ru.otus.appcontainer.api.AppComponentsContainerConfig; import java.lang.reflect.InvocationTargetException; import java.util.*; @Slf4j public class AppComponentsContainerImpl implements AppComponentsContainer { private final List<Object> appComponents = new ArrayList<>(); private final Map<String, Object> appComponentsByName = new HashMap<>(); public AppComponentsContainerImpl(Class<?> initialConfigClass) { processConfig(initialConfigClass); } private void processConfig(Class<?> configClass) { checkConfigClass(configClass); parseConfig(configClass); } @SneakyThrows private void parseConfig(Class<?> configClass) { Object config = configClass.getDeclaredConstructor().newInstance(); Arrays.stream(configClass.getDeclaredMethods()) .filter(method -> method.isAnnotationPresent(AppComponent.class)) .sorted(Comparator.comparingInt(method -> method.getAnnotation(AppComponent.class).order())) .forEach(method -> { method.setAccessible(true); Class<?>[] parameters = method.getParameterTypes(); Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { args[i] = getAppComponent(parameters[i]); } Object component; try { component = method.invoke(config, args); } catch (IllegalAccessException | InvocationTargetException e) { log.error(e.getMessage(), e); throw new RuntimeException(e); } String name = method.getAnnotation(AppComponent.class).name(); appComponentsByName.put(name, component); appComponents.add(component); }); } private void checkConfigClass(Class<?> configClass) { if (!configClass.isAnnotationPresent(AppComponentsContainerConfig.class)) { throw new IllegalArgumentException(String.format("Given class is not config %s", configClass.getName())); } } @Override public <C> C getAppComponent(Class<C> componentClass) { return (C) appComponents.stream() .filter(c -> componentClass.isAssignableFrom(c.getClass())) .findFirst() .orElseThrow(() -> new NoSuchBeanDefinitionException(componentClass.getName())); } @Override public <C> C getAppComponent(String componentName) { C component = (C) appComponentsByName.get(componentName); if (component == null) { throw new NoSuchBeanDefinitionException(componentName); } return component; } }
38.948718
117
0.623766
76594c7bbb98a926b97e5ff82202bca845f943d5
2,355
package com.exasol.adapter.document.documentfetcher.files.segmentation; import static com.exasol.adapter.document.documentfetcher.files.segmentation.FileSegmentDescription.ENTIRE_FILE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.List; import org.junit.jupiter.api.Test; import com.exasol.adapter.document.documentfetcher.files.RemoteFile; class ExplicitSegmentMatcherTest { @Test void testMatchWholeFile() { final RemoteFile remoteFile = getRemoteFileForName("test.txt"); final FileSegment segment = new FileSegment(remoteFile, ENTIRE_FILE); final ExplicitSegmentDescription segmentDescription = new ExplicitSegmentDescription(List.of(segment)); final List<FileSegment> result = new ExplicitSegmentMatcher(segmentDescription) .getMatchingSegmentsFor(remoteFile); assertThat(result, contains(segment)); } @Test void testMatchSegmentsFile() { final RemoteFile remoteFile = getRemoteFileForName("test.txt"); final FileSegment segment1 = new FileSegment(remoteFile, new FileSegmentDescription(3, 0)); final FileSegment segment2 = new FileSegment(remoteFile, new FileSegmentDescription(3, 1)); final ExplicitSegmentDescription segmentDescription = new ExplicitSegmentDescription( List.of(segment1, segment2)); final List<FileSegment> result = new ExplicitSegmentMatcher(segmentDescription) .getMatchingSegmentsFor(remoteFile); assertThat(result, containsInAnyOrder(segment1, segment2)); } @Test void testMismatch() { final ExplicitSegmentDescription segmentDescription = new ExplicitSegmentDescription( List.of(new FileSegment(getRemoteFileForName("test.txt"), ENTIRE_FILE))); final List<FileSegment> result = new ExplicitSegmentMatcher(segmentDescription) .getMatchingSegmentsFor(getRemoteFileForName("other.txt")); assertThat(result, empty()); } private RemoteFile getRemoteFileForName(final String fileName) { final RemoteFile remoteFile = mock(RemoteFile.class); when(remoteFile.getResourceName()).thenReturn(fileName); return remoteFile; } }
44.433962
112
0.740552
bf7eb4e15706015d45f0516338cdf23415ea270d
1,045
package projects.displaynet.nodes.messages; import projects.defaultProject.nodes.nodeImplementations.BinarySearchTreeLayer; import sinalgo.nodes.messages.Message; /** * RPCMessage */ public class RPCMessage extends Message { private String command; private BinarySearchTreeLayer node; private int value; public RPCMessage(String command, BinarySearchTreeLayer node) { this.command = command; this.node = node; this.value = -1; } public RPCMessage(String command, int value) { this.command = command; this.node = null; this.value = value; } public String getCommand() { return this.command; } public BinarySearchTreeLayer getNode() { return this.node; } public int getValue() { return this.value; } public void setCommand(String cmd) { this.command = cmd; } public void setNode(BinarySearchTreeLayer node) { this.node = node; } public void setValue(int value) { this.value = value; } @Override public Message clone() { return this; } }
18.660714
79
0.691866
2e7824cc4d9ceeeb44027568c99f73d95cf32f2d
810
package team.fjut.cf.pojo.po; import lombok.Data; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import java.util.Date; /** * @author axiang [2020/4/29] */ @Data @Table(name = "t_spider_get_problem_info") public class SpiderGetProblemInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "JDBC") Integer id; String spiderName; String spiderJob; Date insertTime; String fromWebsite; String problemUrl; String problemId; String problemTitle; String problemTimeLimit; String problemMemoryLimit; String problemDescription; String problemInput; String problemOutput; String problemSampleInput; String problemSampleOutput; }
22.5
75
0.744444
3e7375c6d35cde9d71e2ece12947c05513cca8ec
270
package org.snomed.heathanalytics.store; import org.snomed.heathanalytics.domain.Patient; import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository; public interface PatientRepository extends ElasticsearchCrudRepository<Patient, String> { }
33.75
89
0.866667
90aa838ef1645f27408c9a97975b3a261cc890bb
3,654
package nl.uva.larissa.json.model; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.ValidationException; import javax.validation.Validator; import org.apache.abdera.i18n.iri.IRI; public class StatementBuilder { public static StatementBuilder statement() { StatementBuilder result = new StatementBuilder(); return result; } final Validator validator = Validation.buildDefaultValidatorFactory() .getValidator(); private String id; private String email; private String verbId; private String referenceId; private String activityId; private String registration; private String instructor; private List<String> parentContextActivities = new ArrayList<>(0); private StatementBuilder() { } public StatementBuilder id(String id) { this.id = id; return this; } public StatementBuilder actor(String email) { this.email = email; return this; } public StatementBuilder verb(String id) { this.verbId = id; return this; } public StatementBuilder statementRef(String id) { this.referenceId = id; return this; } public Statement build() { Statement result = new Statement(); result.setAuthority(createAgentWithEmail("[email protected]")); result.setId(id); Verb verb = new Verb(); verb.setId(new IRI(verbId)); result.setVerb(verb); result.setActor(createAgentWithEmail(email)); if (referenceId != null) { StatementRef ref = new StatementRef(); ref.setId(referenceId); result.setStatementObject(ref); } else if (activityId != null) { result.setStatementObject(createActivityWithId(activityId)); } Context context = null; if (registration != null) { context = new Context(); context.setRegistration(registration); } if (instructor != null) { if (context == null) { context = new Context(); } context.setInstructor(createAgentWithEmail(instructor)); } if (!parentContextActivities.isEmpty()) { if (context == null) { context = new Context(); } ContextActivities contextActivities = new ContextActivities(); ArrayList<Activity> activities = new ArrayList<>( parentContextActivities.size()); for (String activityId : parentContextActivities) { activities.add(createActivityWithId(activityId)); } contextActivities.setParent(activities); context.setContextActivities(contextActivities); } if (context != null) { result.setContext(context); } Set<ConstraintViolation<Statement>> violations = validator .validate(result); if (!violations.isEmpty()) { throw new ValidationException(violations.iterator().next() .getMessage()); } return result; } private Activity createActivityWithId(String id) { Activity result = new Activity(); result.setId(new IRI(id)); return result; } private Agent createAgentWithEmail(String email) { Agent result = new Agent(); IFI ifi = new IFI(); ifi.setMbox(new IRI("mailto:" + email)); result.setIdentifier(ifi); return result; } public StatementBuilder randomId() { this.id = UUID.randomUUID().toString(); return this; } public StatementBuilder activity(String string) { this.activityId = string; return this; } public StatementBuilder contextWithRegistration(String registration) { this.registration = registration; return this; } public StatementBuilder instructor(String string) { this.instructor = string; return this; } public StatementBuilder parentContextActivity(String string) { parentContextActivities.add(string); return this; } }
23.273885
71
0.72879
d72aac3d361f22e5873e959287083dcf273045d7
3,503
package com.test; import javax.imageio.ImageIO; import javax.servlet.ServletException; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Base64; import java.util.Random; /** * @author zhangbo */ public class ValidationCode { /** * 验证码图片的宽度 */ private int width = 76; /** * 验证码图片的高度 */ private int height = 34; /** * 验证码字符个数 */ private int codeCount = 4; /** * xx */ private int xx = width / (codeCount + 2); //生成随机数的水平距离 /** * 字体高度 */ private int fontHeight = height - 12; //生成随机数的数字高度 /** * codeY */ private int codeY = height - 8; //生成随机数的垂直距离 /** * codeSequence */ private String[] codeSequence = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "Q", "W", "E", "R", "T", "Y", "U", "I", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M"}; public void verificationCode() throws ServletException, IOException { // 定义图像buffer BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D gd = buffImg.createGraphics(); // 创建一个随机数生成器类 Random random = new Random(); // 将图像填充为白色 gd.setColor(Color.WHITE); gd.fillRect(0, 0, width, height); // 创建字体,字体的大小应该根据图片的高度来定 Font font = new Font("Fixedsys", Font.PLAIN, fontHeight); // 设置字体 gd.setFont(font); // 画边框 gd.setColor(Color.BLACK); gd.drawRect(0, 0, width - 1, height - 1); // 随机产生4条干扰线,使图象中的认证码不易被其它程序探测到 gd.setColor(Color.BLACK); for (int i = 0; i < 4; i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); gd.drawLine(x, y, x + xl, y + yl); } // randomCode用于保存随机产生的验证码,以便用户登录后进行验证 StringBuilder randomCode = new StringBuilder(); int red = 0, green = 0, blue = 0; // 随机产生codeCount数字的验证码 for (int i = 0; i < codeCount; i++) { // 得到随机产生的验证码数字 String strRand = String.valueOf(codeSequence[random.nextInt(27)]); // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同 red = random.nextInt(125); green = random.nextInt(255); blue = random.nextInt(200); // 用随机产生的颜色将验证码绘制到图像中。 gd.setColor(new Color(red, green, blue)); gd.drawString(strRand, (i + 1) * xx, codeY); // 将产生的四个随机数组合在一起 randomCode.append(strRand); } System.out.println(randomCode); // 将验证码保存到Session中 // session.setAttribute(SessionConstants.VERIFICATION_CODE, randomCode.toString()); // 禁止图像缓存 // resp.setHeader("Pragma", "no-cache"); // resp.setHeader("Cache-Control", "no-cache"); // resp.setDateHeader("Expires", 0); // // resp.setContentType("image/jpeg"); // // // 将图像输出到Servlet输出流中 // ServletOutputStream sos = resp.getOutputStream(); // ImageIO.write(buffImg, "jpeg", sos); // sos.close(); // 转Base64 ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(buffImg, "jpg", baos); Base64.getEncoder().encodeToString(baos.toByteArray()); } }
26.141791
93
0.544391
9051c1a4afd6674b832db020dadd9529cdb65ef8
3,636
/* * Copyright (C) 2019 - 2020 Rabobank Nederland * * 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.rabobank.argos.test; import static java.util.concurrent.TimeUnit.MINUTES; import static org.awaitility.Awaitility.await; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.Arrays; import org.apache.commons.io.IOUtils; import lombok.extern.slf4j.Slf4j; @Slf4j public class XLDeployHelper { private static Properties properties = Properties.getInstance(); public static void waitForXLDeployToStart() { log.info("Waiting for xldeploy start"); HttpClient client = HttpClient.newBuilder().authenticator(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(properties.getXlDeployUser(), properties.getXlDeployPassword().toCharArray()); } }).build(); await().atMost(1, MINUTES).until(() -> { try { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(properties.getXlDeployBaseUrl()+"/server/state")) .build(); HttpResponse<String> send = client.send(request, HttpResponse.BodyHandlers.ofString()); return 200 == send.statusCode(); } catch (IOException e) { //ignore return false; } }); log.info("xldeploy started"); } public static void initXLDeploy() { log.info("Initializing xldeploy"); StringWriter writer = new StringWriter(); try { IOUtils.copy(XLDeployHelper.class.getResourceAsStream("/xldeploy/init-cis.json"), writer); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } String json = writer.toString(); HttpClient client = HttpClient.newBuilder().authenticator(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(properties.getXlDeployUser(), properties.getXlDeployPassword().toCharArray()); } }).build(); try { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(properties.getXlDeployBaseUrl() + "/repository/cis")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(json)).build(); HttpResponse<String> send = client.send(request, HttpResponse.BodyHandlers.ofString()); } catch (IOException | InterruptedException e) { // ignore } log.info("xldeploy initialized"); } }
37.484536
103
0.638339
21225711aa73988682a1a7656062f12ef6575f48
3,062
/* * Copyright (c) 2015-2022, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tribuo.classification.evaluation; import org.tribuo.ImmutableOutputInfo; import org.tribuo.Prediction; import org.tribuo.classification.Label; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.tribuo.classification.Utils.label; import static org.tribuo.classification.Utils.mkDomain; import static org.tribuo.classification.Utils.mkPrediction; import static org.junit.jupiter.api.Assertions.assertEquals; public class LabelConfusionMatrixTest { @Test public void testMulticlass() { List<Prediction<Label>> predictions = Arrays.asList( mkPrediction("a", "a"), mkPrediction("c", "b"), mkPrediction("b", "b"), mkPrediction("b", "c") ); ImmutableOutputInfo<Label> domain = mkDomain(predictions); LabelConfusionMatrix cm = new LabelConfusionMatrix(domain, predictions); Label a = label("a"); Label b = label("b"); Label c = label("c"); assertEquals(1, cm.confusion(a, a)); assertEquals(1, cm.confusion(b, c)); assertEquals(1, cm.confusion(c, b)); assertEquals(1, cm.tp(a)); assertEquals(0, cm.fp(a)); assertEquals(3, cm.tn(a)); assertEquals(0, cm.fn(a)); assertEquals(1, cm.support(a)); assertEquals(1, cm.tp(b)); assertEquals(1, cm.fp(b)); assertEquals(1, cm.tn(b)); assertEquals(1, cm.fn(b)); assertEquals(2, cm.support(b)); assertEquals(0, cm.tp(c)); assertEquals(1, cm.fp(c)); assertEquals(2, cm.tn(c)); assertEquals(1, cm.fn(c)); assertEquals(1, cm.support(c)); assertEquals(4, cm.support()); List<Label> lblOrder = new ArrayList<>(); lblOrder.add(a); lblOrder.add(b); lblOrder.add(c); cm.setLabelOrder(lblOrder); String cmToString = cm.toString(); assertEquals(" a b c\n" + "a 1 0 0\n" + "b 0 1 1\n" + "c 0 1 0\n", cmToString); lblOrder.clear(); lblOrder.add(c); lblOrder.add(a); cm.setLabelOrder(lblOrder); cmToString = cm.toString(); assertEquals(" c a\n" + "c 0 0\n" + "a 0 1\n", cmToString); } }
30.62
80
0.60516
9a05c847b25880838cbfbb0044e09e61c0a5581b
661
/* * 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 lk.ijse.gymmanagementsystem.business.custom; import java.util.ArrayList; import lk.ijse.gymmanagementsystem.business.SuperBO; import lk.ijse.gymmanagementsystem.model.CustomDTO; import lk.ijse.gymmanagementsystem.model.MeasurementDTO; /** * * @author jamith */ public interface MeasurementBO extends SuperBO{ public boolean addMeasurent(MeasurementDTO measurementDTO) throws Exception; public ArrayList<CustomDTO> getAllMeasurements() throws Exception; }
31.47619
80
0.795764
275c5f1e506ffb357c9749526add20e4dd2b1196
2,624
package com.notably.model.userpref; import static java.util.Objects.requireNonNull; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Objects; import com.notably.commons.GuiSettings; /** * Represents User's preferences. */ public class UserPrefModelImpl implements UserPrefModel { private GuiSettings guiSettings = new GuiSettings(); private Path blockDataFilePath = Paths.get("data" , "blockdata.json"); /** * Creates a {@code UserPrefs} with default values. */ public UserPrefModelImpl() {} /** * Creates a {@code UserPrefs} with the prefs in {@code userPrefs}. * * @param userPrefs {@code UserPrefs} data */ public UserPrefModelImpl(ReadOnlyUserPrefModel userPrefs) { this(); resetUserPrefModel(userPrefs); } @Override public void setUserPrefModel(ReadOnlyUserPrefModel userPrefModel) { resetUserPrefModel(userPrefModel); } @Override public ReadOnlyUserPrefModel getUserPrefModel() { return this; } @Override public void resetUserPrefModel(ReadOnlyUserPrefModel newUserPrefModel) { requireNonNull(newUserPrefModel); setGuiSettings(newUserPrefModel.getGuiSettings()); setBlockDataFilePath(newUserPrefModel.getBlockDataFilePath()); } @Override public GuiSettings getGuiSettings() { return guiSettings; } @Override public void setGuiSettings(GuiSettings guiSettings) { requireNonNull(guiSettings); this.guiSettings = guiSettings; } @Override public Path getBlockDataFilePath() { return blockDataFilePath; } @Override public void setBlockDataFilePath(Path blockDataFilePath) { requireNonNull(blockDataFilePath); this.blockDataFilePath = blockDataFilePath; } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof UserPrefModel)) { //this handles null as well. return false; } UserPrefModel o = (UserPrefModel) other; return guiSettings.equals(o.getGuiSettings()) && blockDataFilePath.equals(o.getBlockDataFilePath()); } @Override public int hashCode() { return Objects.hash(guiSettings, blockDataFilePath); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Gui Settings : " + guiSettings); sb.append("\nLocal data file location : " + blockDataFilePath); return sb.toString(); } }
25.980198
77
0.661585
2076845b5a74a200c0629218d4d76e7f187dbec4
795
package tpsql.test.junit.mysql; import org.junit.Before; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import tpsql.sql.config.IDbConfig; import tpsql.sql.config.IDbConfigFactory; import tpsql.test.util.DbConfigUtil; import tpsql.core.spring.SpringContext; import tpsql.test.spring.*; public class MySqlSupport { @Before public void init(){ new AnnotationConfigApplicationContext(SpringConfig.class); IDbConfigFactory dbConfigFactory = (IDbConfigFactory)SpringContext.instance().get(IDbConfigFactory.class); IDbConfig dbConfig = DbConfigUtil.getDbConfig("mysql"); dbConfig.setDefault(true); dbConfigFactory.add(dbConfig); } }
31.8
114
0.783648
53a7168cfa85778e0a8acf52db04e0bce5ebc94e
2,894
package org.spincast.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.List; import java.util.Map; import org.junit.Test; import org.spincast.core.exchange.DefaultRequestContext; import org.spincast.core.routing.Handler; import org.spincast.plugins.httpclient.HttpResponse; import org.spincast.shaded.org.apache.http.HttpStatus; import org.spincast.testing.defaults.NoAppStartHttpServerTestingBase; public class RequestPathParamsAndQueryStringParamsTest extends NoAppStartHttpServerTestingBase { @Test public void paramsAndQueryStringParams() throws Exception { getRouter().GET("/${param1}/two/${param2}/four/*{param3}").handle(new Handler<DefaultRequestContext>() { @Override public void handle(DefaultRequestContext context) { String val = context.request().getPathParam("param1"); assertEquals("one", val); val = context.request().getPathParam("param2"); assertEquals("three", val); val = context.request().getPathParam("param3"); assertEquals("five/six", val); val = context.request().getPathParam("nope"); assertNull(val); Map<String, List<String>> querystringParams = context.request().getQueryStringParams(); assertEquals(2, querystringParams.size()); List<String> key1Values = context.request().getQueryStringParam("key1"); assertNotNull(key1Values); assertEquals(1, key1Values.size()); assertEquals("val1", key1Values.get(0)); List<String> key2Values = context.request().getQueryStringParam("key2"); assertNotNull(key2Values); assertEquals(2, key2Values.size()); assertEquals("vala", key2Values.get(0)); assertEquals("valb", key2Values.get(1)); List<String> nopeValues = context.request().getQueryStringParam("nope"); assertNotNull(nopeValues); assertEquals(0, nopeValues.size()); String key1FirstValue = context.request().getQueryStringParamFirst("key1"); assertEquals("val1", key1FirstValue); String key2FirstValue = context.request().getQueryStringParamFirst("key2"); assertEquals("vala", key2FirstValue); String nopeFirstValue = context.request().getQueryStringParamFirst("nope"); assertNull(nopeFirstValue); } }); String url = createTestUrl("/one/two/three/four/five/six/") + "?key1=val1&key2=vala&key2=valb"; HttpResponse response = GET(url, true).send(); assertEquals(HttpStatus.SC_OK, response.getStatus()); } }
38.586667
112
0.638563
0866b4e61e7e72e56bb096ded1d2020a600f8d2c
6,139
/* * 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.hop.beam.core.fn; import org.apache.beam.sdk.metrics.Counter; import org.apache.beam.sdk.metrics.Metrics; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.values.KV; import org.apache.hop.beam.core.BeamHop; import org.apache.hop.beam.core.HopRow; import org.apache.hop.beam.core.util.JsonRowMeta; import org.apache.hop.core.exception.HopException; import org.apache.hop.core.row.RowDataUtil; import org.apache.hop.core.row.IRowMeta; import org.apache.hop.pipeline.Pipeline; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; // Split a Hop row into key and values parts // public class HopKeyValueFn extends DoFn<HopRow, KV<HopRow, HopRow>> { private String inputRowMetaJson; private List<String> transformPluginClasses; private List<String> xpPluginClasses; private String[] keyFields; private String[] valueFields; private String counterName; private static final Logger LOG = LoggerFactory.getLogger( HopKeyValueFn.class ); private transient IRowMeta inputRowMeta; private transient int[] keyIndexes; private transient int[] valueIndexes; private transient Counter initCounter; private transient Counter readCounter; private transient Counter errorCounter; public HopKeyValueFn() { } public HopKeyValueFn( String inputRowMetaJson, List<String> transformPluginClasses, List<String> xpPluginClasses, String[] keyFields, String[] valueFields, String counterName) { this.inputRowMetaJson = inputRowMetaJson; this.transformPluginClasses = transformPluginClasses; this.xpPluginClasses = xpPluginClasses; this.keyFields = keyFields; this.valueFields = valueFields; this.counterName = counterName; } @Setup public void setUp() { try { readCounter = Metrics.counter( Pipeline.METRIC_NAME_READ, counterName ); errorCounter = Metrics.counter( Pipeline.METRIC_NAME_ERROR, counterName ); // Initialize Hop Beam // BeamHop.init(transformPluginClasses, xpPluginClasses); inputRowMeta = JsonRowMeta.fromJson( inputRowMetaJson ); // Calculate key indexes // if ( keyFields.length==0) { throw new HopException( "There are no group fields" ); } keyIndexes = new int[ keyFields.length]; for ( int i = 0; i< keyFields.length; i++) { keyIndexes[i]=inputRowMeta.indexOfValue( keyFields[i] ); if ( keyIndexes[i]<0) { throw new HopException( "Unable to find group by field '"+ keyFields[i]+"' in input "+inputRowMeta.toString() ); } } // Calculate the value indexes // valueIndexes =new int[ valueFields.length]; for ( int i = 0; i< valueFields.length; i++) { valueIndexes[i] = inputRowMeta.indexOfValue( valueFields[i] ); if ( valueIndexes[i]<0) { throw new HopException( "Unable to find subject by field '"+ valueFields[i]+"' in input "+inputRowMeta.toString() ); } } // Now that we know everything, we can split the row... // Metrics.counter( Pipeline.METRIC_NAME_INIT, counterName ).inc(); } catch(Exception e) { errorCounter.inc(); LOG.error("Error setup of splitting row into key and value", e); throw new RuntimeException( "Unable to setup of split row into key and value", e ); } } @ProcessElement public void processElement( ProcessContext processContext ) { try { // Get an input row // HopRow inputHopRow = processContext.element(); readCounter.inc(); Object[] inputRow = inputHopRow.getRow(); // Copy over the data... // Object[] keyRow = RowDataUtil.allocateRowData( keyIndexes.length ); for ( int i = 0; i< keyIndexes.length; i++) { keyRow[i] = inputRow[ keyIndexes[i]]; } // Copy over the values... // Object[] valueRow = RowDataUtil.allocateRowData( valueIndexes.length ); for ( int i = 0; i< valueIndexes.length; i++) { valueRow[i] = inputRow[ valueIndexes[i]]; } KV<HopRow, HopRow> keyValue = KV.of( new HopRow(keyRow), new HopRow( valueRow ) ); processContext.output( keyValue ); } catch(Exception e) { errorCounter.inc(); LOG.error("Error splitting row into key and value", e); throw new RuntimeException( "Unable to split row into key and value", e ); } } /** * Gets inputRowMetaJson * * @return value of inputRowMetaJson */ public String getInputRowMetaJson() { return inputRowMetaJson; } /** * @param inputRowMetaJson The inputRowMetaJson to set */ public void setInputRowMetaJson( String inputRowMetaJson ) { this.inputRowMetaJson = inputRowMetaJson; } /** * Gets keyFields * * @return value of keyFields */ public String[] getKeyFields() { return keyFields; } /** * @param keyFields The keyFields to set */ public void setKeyFields( String[] keyFields ) { this.keyFields = keyFields; } /** * Gets valueFields * * @return value of valueFields */ public String[] getValueFields() { return valueFields; } /** * @param valueFields The valueFields to set */ public void setValueFields( String[] valueFields ) { this.valueFields = valueFields; } }
30.391089
126
0.68187
a85d770f3dc2413a5dbc7357e89448d82ff483a8
4,148
package webservice.client.IPGU02; import com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl; import exception.ElkServiceException; import org.apache.log4j.Logger; import org.junit.BeforeClass; import org.junit.Test; import webservice.MyServiceLogHandler; import webservice.client.IPGUElkSubscribeService.SubscriberServiceTest; import webservice.objects.elk.*; import javax.xml.namespace.QName; import javax.xml.ws.BindingProvider; import javax.xml.ws.Service; import javax.xml.ws.handler.Handler; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; public class ServiceSendingDataToELKTest { private static Logger logger = Logger.getLogger(SubscriberServiceTest.class); private static ServiceSendingDataToELK sendingDataToELK; @BeforeClass public static void init() { try { //тестовая среда URL url = new URL("http://smev-mvf.test.gosuslugi.ru:7777/gateway/services/SID0004763/wsdl"); QName qname = new QName("http://gosuslugi.ru/epguapi/ws/v25/", "CreateOrderService"); Service service = Service.create(url, qname); CreateOrderService createOrderService = service.getPort(CreateOrderService.class); /* BindingProvider bindingProvider = (BindingProvider) createOrderService; java.util.List<Handler> handlers = bindingProvider.getBinding().getHandlerChain(); handlers.add(new MyServiceLogHandler()); bindingProvider.getBinding().setHandlerChain(handlers);*/ ServiceSendingDataToELKImpl serviceSendingDataToELK = new ServiceSendingDataToELKImpl(); serviceSendingDataToELK.setService(createOrderService); serviceSendingDataToELK.setArchiveUtil(new ArchiveUtil()); serviceSendingDataToELK.setObjectFactoryArchive(new webservice.objects.archive.ObjectFactory()); serviceSendingDataToELK.setObjectFactoryElk(new ObjectFactory()); serviceSendingDataToELK.setObjectFactorySmev(new webservice.objects.smev.ObjectFactory()); sendingDataToELK = serviceSendingDataToELK; } catch (MalformedURLException e) { logger.error(e); } } @Test public void sendOrders() { List<Order> list = new ArrayList<>(); Order order = new Order(); order.setUserId("22"); order.setOrderNumber("1"); order.setEServiceCode("1"); order.setRequestDate(new XMLGregorianCalendarImpl()); list.add(order); try { sendingDataToELK.sendOrders(list); } catch (ElkServiceException e) { logger.error(e); } } @Test public void deleteOrders() { List<String> list = Arrays.asList("12", "2313", "2131"); try { sendingDataToELK.deleteOrders(list); } catch (ElkServiceException e) { logger.error(e); } } @Test public void updateOrders() { List<UpdateOrder> orders = new ArrayList<>(); UpdateOrder updateOrder = new UpdateOrder(); updateOrder.setElkOrderNumber("12"); StatusHistoryList statusHistoryList = new StatusHistoryList(); StatusHistory statusHistory = new StatusHistory(); statusHistory.setStatus("Ok"); statusHistory.setStatusName("statusOk"); statusHistory.setStatusExtId("0"); statusHistory.setStatusDate(new XMLGregorianCalendarImpl()); statusHistoryList.getStatusHistory().add(statusHistory); updateOrder.getStatusHistoryList().add(statusHistoryList); orders.add(updateOrder); try { sendingDataToELK.updateOrders(orders); } catch (ElkServiceException e) { logger.error(e); } } @Test public void sendFilesByOrders() { List<String> fileNames = new ArrayList<>(); try { sendingDataToELK.sendFilesByOrders(fileNames, "12", "0"); } catch (ElkServiceException e) { logger.error(e); } } }
37.035714
108
0.676471
093478c46912a15dab9b8aa2325d3e89ec27ae7e
770
package com.flair.bi.domain.value; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import com.fasterxml.jackson.annotation.JsonTypeName; @Entity @DiscriminatorValue(value = "DECIMAL") @JsonTypeName(value = "DECIMAL") public class DecimalValue extends Value { @Column(name = "decimal_value") private double value; public DecimalValue() { this.setType("DECIMAL"); } public double getValue() { return value; } public void setValue(double value) { this.value = value; } @Override public boolean equalValue(Value value) { if (value instanceof DecimalValue) { DecimalValue decimalValue = (DecimalValue) value; return decimalValue.getValue() == this.value; } return false; } }
20.263158
53
0.745455
6148012c4fea8c8581c544676fbf539698068c7b
288
package in.techware.lataxidriverapp.listeners; /** * Created by Jemsheer K D on 29 November, 2016. * Package com.company.sample.listeners * Project Telugu Catholic Matrimony */ public interface ProgressListener { void update(long bytesRead, long contentLength, boolean done); }
24
66
0.763889