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
de08f2fa755ee338ab3246a1194c5231349f43e4
1,519
package io.github.jackson.introspector; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; import org.codehaus.jackson.map.AnnotationIntrospector; import org.codehaus.jackson.map.MapperConfig; import org.codehaus.jackson.map.introspect.AnnotatedClass; import org.codehaus.jackson.map.introspect.AnnotatedMember; import org.codehaus.jackson.map.jsontype.NamedType; import org.codehaus.jackson.map.jsontype.SubtypeResolver; /** * This class acts just as an holder for registered sub-types.<br/> * It does not perform any logic since it ignores any annotation mechanism. * * @author rveloso * */ public class SimpleSubTypeResolver extends SubtypeResolver { protected Set<NamedType> subtypes = new LinkedHashSet<>(); @Override public void registerSubtypes(NamedType... types) { for (NamedType type : types) { subtypes.add(type); } } @Override public void registerSubtypes(Class<?>... classes) { NamedType[] types = new NamedType[classes.length]; for (int i = 0; i < types.length; i++) { types[i] = new NamedType(classes[i]); } registerSubtypes(types); } @Override public Collection<NamedType> collectAndResolveSubtypes(AnnotatedMember property, MapperConfig<?> config, AnnotationIntrospector ai) { return subtypes; } @Override public Collection<NamedType> collectAndResolveSubtypes(AnnotatedClass basetype, MapperConfig<?> config, AnnotationIntrospector ai) { return subtypes; } }
28.12963
106
0.736669
931fd291cb6ba9346312964964493e4c36938895
3,964
package net.twasi.core.database; import net.twasi.core.database.models.TwitchAccount; import net.twasi.core.database.models.User; import net.twasi.core.database.models.permissions.PermissionEntity; import net.twasi.core.database.models.permissions.PermissionEntityType; import net.twasi.core.database.models.permissions.PermissionGroups; import net.twasi.core.database.models.permissions.Permissions; import org.junit.Assert; import org.junit.BeforeClass; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class PermissionsTest { // botDeveloper is Viewer and Subscriber. He has TwitchID 1. private static TwitchAccount botDeveloper = new TwitchAccount( "BotDeveloper", null, null, "1", Arrays.asList( PermissionGroups.VIEWER, PermissionGroups.SUBSCRIBERS ) ); // moderator is a moderator. He has TwitchID 2. private static TwitchAccount moderator = new TwitchAccount( "MyCoolModerator", null, null, "2", Arrays.asList( PermissionGroups.VIEWER, PermissionGroups.SUBSCRIBERS, PermissionGroups.MODERATOR ) ); // viewer is just a viewer with TwitchID 3. private static TwitchAccount viewer = new TwitchAccount( "MyKindViewer", null, null, "3", Collections.singletonList(PermissionGroups.VIEWER) ); private static List<Permissions> examplePermissions = new ArrayList<>(); private static User user; @BeforeClass public static void setUp() { Permissions permission = new Permissions( Arrays.asList( new PermissionEntity( PermissionEntityType.GROUP, PermissionGroups.MODERATOR, null ), new PermissionEntity( PermissionEntityType.SINGLE, null, botDeveloper ) ), Arrays.asList("commands.mod.*", "commands.user.execute"), "commands" ); examplePermissions.add(permission); user = new User(); user.setPermissions(examplePermissions); } // @Test public void grantsPermissionByGroup() { checkForUser(moderator); } // @Test public void grantsPermissionByAccount() { checkForUser(botDeveloper); } private void checkForUser(TwitchAccount moderator) { Boolean hasAddPermission = user.hasPermission(moderator, "commands.mod.add"); Boolean hasEditPermission = user.hasPermission(moderator, "commands.mod.edit"); Boolean hasDeletePermission = user.hasPermission(moderator, "commands.mod.delete"); Boolean hasUnknownPermission = user.hasPermission(moderator, "commands.unknown.doNothing"); Assert.assertTrue(hasAddPermission); Assert.assertTrue(hasEditPermission); Assert.assertTrue(hasDeletePermission); Assert.assertFalse(hasUnknownPermission); } // @Test public void revokesPermission() { Boolean hasAddPermission = user.hasPermission(viewer, "commands.add"); Boolean hasEditPermission = user.hasPermission(viewer, "commands.edit"); Boolean hasDeletePermission = user.hasPermission(viewer, "commands.delete"); Boolean hasUnknownPermission = user.hasPermission(moderator, "commands.unknown.doNothing"); Assert.assertFalse(hasAddPermission); Assert.assertFalse(hasEditPermission); Assert.assertFalse(hasDeletePermission); Assert.assertFalse(hasUnknownPermission); } }
34.77193
99
0.618063
90dd8b3ea00d3b0409f3346f6280fb8ade560815
313
package com.mt.access.application.user.representation; import com.mt.access.domain.model.user.User; import lombok.Data; @Data public class UserPublicCardRepresentation { private String id; public UserPublicCardRepresentation(User bizUser) { this.id = bizUser.getUserId().getDomainId(); } }
22.357143
55
0.750799
1dfc781b5d77885ba0f62ebe0ca5d34bfc82ffce
963
package com.barmpas.asthma.data; import android.net.Uri; import android.provider.BaseColumns; /* * The contract class for the local SQLite Database class where the user stores the session. */ public final class SessionContract { public static final String CONTENT_AUTHORITY = "com.barmpas.asthma"; public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); public static final String PATH_SESSION = "session"; private SessionContract() { } public static final class SessionEntry implements BaseColumns { public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_SESSION); public final static String TABLE_NAME = "sessions"; public final static String _ID = BaseColumns._ID; public final static String COLUMN_BREATHES_IN = "bin"; public final static String COLUMN_ERROR = "ain"; public final static String COLUMN_ID = "id"; } }
35.666667
99
0.727934
c296742ce1cdb7235b27f6ec1e2b3be59bda4f83
128
package com.astronautlabs.mc.rezolve.common; public interface IMachineInventory { void outputSlotActivated(int index); }
21.333333
45
0.789063
fef1eac382609ea9c4667eb3c33c1c96e1c8dd69
2,908
/* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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.neo4j.driver.internal.handlers; import org.neo4j.driver.Statement; import org.neo4j.driver.internal.BookmarksHolder; import org.neo4j.driver.internal.async.ExplicitTransaction; import org.neo4j.driver.internal.handlers.pulln.BasicPullResponseHandler; import org.neo4j.driver.internal.handlers.pulln.SessionPullResponseHandler; import org.neo4j.driver.internal.handlers.pulln.TransactionPullResponseHandler; import org.neo4j.driver.internal.messaging.v1.BoltProtocolV1; import org.neo4j.driver.internal.messaging.v3.BoltProtocolV3; import org.neo4j.driver.internal.spi.Connection; public class PullHandlers { public static AbstractPullAllResponseHandler newBoltV1PullAllHandler( Statement statement, RunResponseHandler runHandler, Connection connection, ExplicitTransaction tx ) { if ( tx != null ) { return new TransactionPullAllResponseHandler( statement, runHandler, connection, tx, BoltProtocolV1.METADATA_EXTRACTOR ); } return new SessionPullAllResponseHandler( statement, runHandler, connection, BookmarksHolder.NO_OP, BoltProtocolV1.METADATA_EXTRACTOR ); } public static AbstractPullAllResponseHandler newBoltV3PullAllHandler( Statement statement, RunResponseHandler runHandler, Connection connection, BookmarksHolder bookmarksHolder, ExplicitTransaction tx ) { if ( tx != null ) { return new TransactionPullAllResponseHandler( statement, runHandler, connection, tx, BoltProtocolV3.METADATA_EXTRACTOR ); } return new SessionPullAllResponseHandler( statement, runHandler, connection, bookmarksHolder, BoltProtocolV3.METADATA_EXTRACTOR ); } public static BasicPullResponseHandler newBoltV4PullHandler( Statement statement, RunResponseHandler runHandler, Connection connection, BookmarksHolder bookmarksHolder, ExplicitTransaction tx ) { if ( tx != null ) { return new TransactionPullResponseHandler( statement, runHandler, connection, tx, BoltProtocolV3.METADATA_EXTRACTOR ); } return new SessionPullResponseHandler( statement, runHandler, connection, bookmarksHolder, BoltProtocolV3.METADATA_EXTRACTOR ); } }
45.4375
148
0.758597
e163da453931c7b2db3d663692bf8db883c54567
2,079
package fr.nantes.cta.test; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import fr.nantes.cta.Airway; import fr.nantes.cta.CompassDirection; import fr.nantes.cta.one.AirwayImpl; import fr.nantes.cta.one.LatitudeImpl; import fr.nantes.cta.one.LongitudeImpl; import fr.nantes.cta.one.PositionImpl; import fr.nantes.cta.one.TakenAirwayImpl; import fr.nantes.cta.one.VORImpl; public class TakenAirwayImplTest { private TakenAirwayImpl instance; private Airway air1; private int alt1; private CompassDirection cd1; @Before public void setUp() throws Exception { VORImpl v = new VORImpl("test1", new PositionImpl(new LatitudeImpl(45, 10, 10, CompassDirection.NORTH), new LongitudeImpl(45, 10, 10, CompassDirection.EAST))); VORImpl o = new VORImpl("test2", new PositionImpl(new LatitudeImpl(40, 10, 10, CompassDirection.NORTH), new LongitudeImpl(40, 10, 10, CompassDirection.EAST))); VORImpl r = new VORImpl(null, new PositionImpl(new LatitudeImpl(40, 10, 10, CompassDirection.NORTH), new LongitudeImpl(40, 10, 10, CompassDirection.EAST))); air1 = new AirwayImpl(v,o); cd1 = CompassDirection.NORTH; //air2 = new Air } @After public void tearDown() throws Exception { } @Test public void testTakenAirwayImpl() { TakenAirwayImpl tai1 = new TakenAirwayImpl(air1, 1000, cd1); assertNotNull(tai1); } @Test public void testDistance() { TakenAirwayImpl tai1 = new TakenAirwayImpl(air1, 1000, cd1); assertEquals(tai1.distance(), air1.getDistance(),0); } @Test public void testGetAirway() { TakenAirwayImpl tai1 = new TakenAirwayImpl(air1, 1000, cd1); assertEquals(tai1.getAirway(), air1); } @Test public void testGetAltitude() { TakenAirwayImpl tai1 = new TakenAirwayImpl(air1, 1000, cd1); assertEquals(tai1.getAltitude(), 1000, 0); } @Test public void testGetSense() { TakenAirwayImpl tai1 = new TakenAirwayImpl(air1, 1000, cd1); assertEquals(tai1.getSense(), cd1); } }
28.479452
162
0.714286
5393e3eafb6f8c7bf5684000255c0258d5e42533
1,302
package com.uDash.DesktopApp.Controllers; import com.uDash.DesktopApp.Dto.WidgetDto; import com.uDash.DesktopApp.Services.WidgetService; import com.uDash.Utils.Bussines.Widget; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; import static org.springframework.web.bind.annotation.RequestMethod.DELETE; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; @RestController @RequestMapping("/api/widgets") public class WidgetsController { @Autowired WidgetService widgetService; @RequestMapping(method = POST, value = "") public ResponseEntity addWitdget(@RequestBody @Valid WidgetDto widget) { widgetService.addWidget(widget); return ResponseEntity.ok(null); } @RequestMapping(method = GET, value = "") public List<WidgetDto> getWitdgets() { return widgetService.getWidgets(); } }
32.55
76
0.791859
6198d523f3967dc73c2ea79f1bb1cfeec9c27cd1
522
package com.easy.popkart.domain.dao; import lombok.*; import java.sql.Timestamp; import java.util.List; @Data @EqualsAndHashCode(callSuper = true) @NoArgsConstructor @ToString public class UserInfoDAO extends BaseDAO { private String id; private String userName; private String account; private String password; private boolean valid; private String createBy; private Timestamp createDt; private String updateBy; private Timestamp updateDt; private List<RoleInfoDAO> userRoles; }
22.695652
42
0.754789
afcc35217816106deb9f9edf144e12beceb4371e
644
package org.zstack.sdk; public class PciDeviceMetaDataEntry { public java.lang.String key; public void setKey(java.lang.String key) { this.key = key; } public java.lang.String getKey() { return this.key; } public PciDeviceMetaDataOperator op; public void setOp(PciDeviceMetaDataOperator op) { this.op = op; } public PciDeviceMetaDataOperator getOp() { return this.op; } public java.lang.String value; public void setValue(java.lang.String value) { this.value = value; } public java.lang.String getValue() { return this.value; } }
21.466667
53
0.631988
ba958969d09d71ec6b65391fb319dfa4dc640716
381
/* * 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 de.codekings.common.Enumerators; /** * * @author Jan */ public enum ClassType { T_FILM, T_DVD, T_KUNDE, T_MITARBEITER, T_PUBLICKEY, T_COVER, T_GENRE, T_RESERVIERUNG, T_AUSLEIHE; }
25.4
101
0.734908
0f718c1ccf2f284c0b36464648bcdae852ccbea5
14,319
// Copyright 2000-2021 Nokia // // Licensed under the Apache License 2.0 // SPDX-License-Identifier: Apache-2.0 // package com.alcatel.as.util.serviceloader; // Jdk import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; import org.apache.felix.dm.annotation.api.Component; import org.apache.felix.dm.annotation.api.Inject; import org.apache.log4j.Logger; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; /** * Helper class used to load a service from the OSGi service registry. This class has two * purpose: * <p> * <ul> * <li>Used to load a service within an OSGi environment. this method simply looks up a service * from the OSGi registry. However, it will return null if the service is not available, you a * slightly better way to get services is to use a dependency injection framework (like * SCR/DM/Spring/iPOJO, etc ...) * <li>Used to load a service outside OSGi. The services are tracked by looking for * META-INF/services files from the classpath. * </ul> * * <p> This class is a component in order to get injected with a bundle context. If it used before * it is activated, then we'll do a best effort and use low level OSGi API in order to get a bundle context. */ @Component(provides=ServiceLoader.class) public class ServiceLoader { /** Automatically injected by dependency manager, or manually retrieved using low level osgi API. */ @Inject private static volatile BundleContext _bc; /** List of already loaded services (non OSGi mode) */ private final static Map<String, Object> _services = new ConcurrentHashMap<String, Object>(); /** lock internally used for thread safety. */ private final static ReentrantLock _lock = new ReentrantLock(); /** Our logger */ private final static Logger _logger = Logger.getLogger(ServiceLoader.class); /** * Returns the service associated to the given class. If the service is not ready, then this * method returns null. Application may track for the service availability, using any OSGi * dependency injection framework (like DM, SCR, iPOJO, Spring, ...) * * @param c The service interface name * @return the Service, or null if the service is not yet started */ @SuppressWarnings("unchecked") public static <T> T getService(Class<T> c) { return (T) getService(c.getName(), null); } /** * Returns the service associated to the given class. If the service is not ready, then this * method returns null. Application may track for the service availability, using any OSGi * dependency injection framework (like DM, SCR, iPOJO, Spring, ...) * * @param c The service interface name * @param filter the OSGi filter used to lookup the correct service * @return the Service, or null if the service is not yet started */ @SuppressWarnings("unchecked") public static <T> T getService(Class<T> c, String filter) { return (T) getService(c.getName(), filter); } /** * Returns an implementation object implementing the interface provided in arguments. * * @param serviceInterface the interface of the service to load * @return null if the service implementation is not found */ @SuppressWarnings("unchecked") public static <T> T getService(String serviceInterface) { return (T) getService(serviceInterface, null); } /** * Loads a class from the classpath, outside OSGi. This method is only meant to be used * outside OSGi, in junit autotests, for instance, which are not running inside an OSGi * container. This method will lookup the specified class name from all jars found in the * classpath. When a jar contains a meta file (META-INF/services/clazz) which corresponds to * the clazz parameter, then the content of this file will be loaded in order to retrieve the * service implementation. The service meta file can also contains some specific service * properties (comma separated) which can also be specified in the filter parameter. * * @param clazz the class to load * @param filter an OSGi filter matching some keys from the SPI META-INF/services file. * SPI implementation classes can be appended with some specific service properties * (key=value pairs, comma separated). Example: com.foo.bar.MyInterfaceImpl;foo=bar;foo2=bar2 * @param paramObjects objects to be passed to the constructor of the service implementation * @param paramClasses classes of objects passed to the constructor of the service implementation * @return a service loaded from the classpath */ @SuppressWarnings("unchecked") public static <T> T loadClass(Class<?> clazz, String filter, Object[] paramObjects, Class<?>[] paramClasses) { T service = (T) loadFromClassPath(clazz.getName(), filter, paramObjects, paramClasses); if (service != null) { // Register the service in our map, so we can return it from our getService methods _lock.lock(); try { String serviceKey = clazz.getName() + ((filter == null) ? "" : filter); _services.put(serviceKey, service); } finally { _lock.unlock(); } } return service; } /** * Returns the service associated to the given class. If the service is not ready, then this * method returns null. Application may track for the ervice availability, using any OSGi * dependency injection framework (like DM, SCR, iPOJO, Spring, ...) * * @param serviceInterface The interface of the service to load * @param filter an optional OSGi filter * @return the service, or null if the service has bot been found. */ @SuppressWarnings("unchecked") public static <T> T getService(String serviceInterface, String filter) { String serviceKey = serviceInterface + ((filter == null) ? "" : filter); initBundleContext(); if (_bc == null) { // It looks like we are not running inside an OSGi framework: try to load an // implementation from the classpath. // First, see if we have already loaded the service in our cache. Object service = (T) _services.get(serviceKey); if (service != null) { return (T) service; } // The service has not yet been loaded from the classpath, load it. _lock.lock(); try { Object s = _services.get(serviceKey); if (s != null) { return (T) s; } service = loadFromClassPath(serviceInterface, filter, new Object[0], new Class[0]); if (service != null) { _services.put(serviceKey, service); } return (T) service; } finally { _lock.unlock(); } } // Try to load the service from the OSGi registry ... ServiceReference<?>[] refs; try { refs = _bc.getServiceReferences(serviceInterface, filter); } catch (InvalidSyntaxException e) { throw new IllegalArgumentException("Invalid OSGi service filter: " + filter, e); } if (refs != null) { return (T) _bc.getService(refs[0]); } return null; } private static void initBundleContext() { if (_bc == null) { try { Bundle b = FrameworkUtil.getBundle(ServiceLoader.class); if (b != null) { b.start(); _bc = b.getBundleContext(); } } catch (Throwable t) { // we are probably running outside osgi. } } } private static Object loadFromClassPath(String serviceInterface, String filter, Object[] paramObjects, Class<?>[] paramClasses) { String[] filterKeyVal = parseFilter(filter); String factoryClassName = null; try { URL[] urls = getResources("META-INF/services/" + serviceInterface, new ClassLoader[] { Thread.currentThread().getContextClassLoader(), ServiceLoader.class.getClassLoader(), ClassLoader.getSystemClassLoader(), }); if (urls.length == 0) { return null; } for (URL u : urls) { if ((factoryClassName = lookForFactory(u, filterKeyVal)) != null) { break; } } if (factoryClassName == null) { return null; } Class<?> clazz = getClass(factoryClassName, new ClassLoader[] { Thread.currentThread().getContextClassLoader(), ServiceLoader.class.getClassLoader(), ClassLoader.getSystemClassLoader() }); return instantiate(clazz, paramObjects, paramClasses); } catch (Throwable t) { Throwable lastCause = t; while (lastCause.getCause() != null) { lastCause = lastCause.getCause(); } throw new RuntimeException("Can not load service " + serviceInterface + ": " + lastCause.toString(), t); } } private static String[] parseFilter(String filter) { String original = filter; if (filter == null) { return null; } filter = filter.trim(); if (!filter.startsWith("(") && !filter.endsWith(")")) { throw new IllegalArgumentException("invalid osgi filter: " + filter); } filter = filter.substring(1, filter.length() - 1); if (filter.indexOf("(") != -1 || filter.indexOf(")") != -1) { throw new IllegalArgumentException("complex OSGi filter not currently supported: " + original); } String[] keyval = filter.split("="); if (keyval == null || keyval.length != 2) { throw new IllegalArgumentException("invalid osgi filter: " + original); } keyval[0] = keyval[0].trim(); keyval[1] = keyval[1].trim(); return keyval; } /** * Parse a factory class name from inside a SPI file, and check if it matches the * ldap filter provided by the application. * The SPI file may contain either a fully qualified java class file, optionally followed * by some optiona osgi service properties. * Example: * * com.alcatel.as.service.concurrent.impl.jdkTimerServiceImplStandalone;strict=true * com.alcatel.as.service.concurrent.impl.WheelTimerServiceImplStandalone;strict=false * * @param u the URL of the SPI file containing a given factory class * @param filterKeyVal an array of strings (array[0]=filter key name, array[1]=filter key val), * or null if no filters are specified. * * @return the factory class name, or null if the filter does not match. */ private static String lookForFactory(URL u, String[] filterKeyVal) throws IOException { InputStream in = null; try { String factoryClassName; in = u.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8")); while ((factoryClassName = br.readLine()) != null) { factoryClassName = factoryClassName.trim(); if (factoryClassName.startsWith("#")) { continue; } // Check OSGi service properties, if any. int semiColumn = factoryClassName.indexOf(";"); String[] factoryClassNameProps = null; if (semiColumn != -1) { factoryClassNameProps = factoryClassName.substring(semiColumn + 1).trim().split(";"); if (factoryClassNameProps.length == 0) { _logger.warn("Found invalid properties in file " + u + ": " + Arrays.toString(factoryClassNameProps)); continue; } factoryClassName = factoryClassName.substring(0, semiColumn); } // Check if the user has specified a filter. if (filterKeyVal != null) { if (semiColumn == -1) { // Ignore the factory if it does contain any properties continue; } // The factory class name contains some properties: check if they match our filter. Properties factoryProps = new Properties(); for (int i = 0; i < factoryClassNameProps.length; i++) { String[] keyval = factoryClassNameProps[i].trim().split("="); factoryProps.put(keyval[0].trim(), keyval[1].trim()); } if (!filterKeyVal[1].equals(factoryProps.get(filterKeyVal[0]))) { continue; } return factoryClassName; } else { // The user did not provide any service filters: return the parsed factory class name. return factoryClassName; } } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } return null; } private static URL[] getResources(String resource, ClassLoader[] loaders) { List<URL> urls = new ArrayList<URL>(); URL u; for (ClassLoader cl : loaders) { if (cl != null) { if ((u = cl.getResource(resource)) != null) { urls.add(u); } } } return urls.toArray(new URL[urls.size()]); } private static Class<?> getClass(String factoryClassName, ClassLoader[] loaders) throws ClassNotFoundException { for (ClassLoader cl : loaders) { try { if (cl != null) { return cl.loadClass(factoryClassName); } } catch (ClassNotFoundException e) { } } throw new ClassNotFoundException(factoryClassName); } private static Object instantiate(Class<?> clazz, Object[] paramObjects, Class<?>[] paramClasses) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { if (paramObjects == null || paramObjects.length == 0) { return clazz.newInstance(); } Constructor<?> constr = clazz.getConstructor(paramClasses); return (constr.newInstance(paramObjects)); } }
37.192208
113
0.652979
3092e9cb6e85eed4706460c6415ad259f2a3e43c
4,145
package com.ycombinator.news.dto; import android.annotation.SuppressLint; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.ycombinator.news.service.HackerNewsMapper; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import org.junit.Before; import org.junit.Test; import static org.fest.assertions.api.Assertions.assertThat; public class ItemDTOTest { private ObjectMapper mapper; @Before public void setUp() { this.mapper = HackerNewsMapper.createHackerNewsMapper(); } @Test(expected = JsonParseException.class) public void testFailsOnMissingRequiredType() throws IOException { mapper.readValue(getClass().getResourceAsStream("comment_dto_1_no_type.json"), ItemDTO.class); } @Test public void testFallsBackOnUnknownRequiredType() throws IOException { ItemDTO itemDTO = mapper.readValue(getClass().getResourceAsStream("comment_dto_1_unknown_type.json"), ItemDTO.class); assertThat(itemDTO).isExactlyInstanceOf(ItemDTO.class); assertThat(itemDTO.getId()).isEqualTo(new ItemId(2921983)); assertThat(itemDTO.getBy()).isEqualTo(new UserId("norvig")); @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); assertThat(dateFormat.format(itemDTO.getTime())).isEqualTo("2011-08-25 02:38:47"); } @Test(expected = JsonMappingException.class) public void testFailsOnMissingRequiredItemId() throws IOException { mapper.readValue(getClass().getResourceAsStream("comment_dto_1_no_id.json"), ItemDTO.class); } @Test(expected = JsonMappingException.class) public void testFailsOnMissingRequiredBy() throws IOException { mapper.readValue(getClass().getResourceAsStream("job_dto_1_no_by.json"), ItemDTO.class); } @Test(expected = JsonMappingException.class) public void testFailsOnMissingRequiredTime() throws IOException { mapper.readValue(getClass().getResourceAsStream("comment_dto_1_no_time.json"), ItemDTO.class); } @Test public void testUrlCorrect() throws IOException { ItemDTO itemDTO = mapper.readValue(getClass().getResourceAsStream("comment_dto_1.json"), ItemDTO.class); assertThat(itemDTO.getOwnUrl()).isEqualTo("https://news.ycombinator.com/item?id=2921983"); } @Test public void testOnMissingByAndDeleted() throws IOException { ItemDTO itemDTO = mapper.readValue(getClass().getResourceAsStream("comment_dto_1_no_by_deleted.json"), ItemDTO.class); assertThat(itemDTO).isInstanceOf(CommentDTO.class); CommentDTO commentDTO = (CommentDTO) itemDTO; assertThat(commentDTO.getId()).isEqualTo(new ItemId(2921983)); assertThat(commentDTO.getBy()).isEqualTo(new UserId("deleted")); assertThat(commentDTO.getParent()).isEqualTo(new ItemId(2921506)); assertThat(commentDTO.getKids().size()).isEqualTo(7); assertThat(commentDTO.getKids().get(3)).isEqualTo(new ItemId(2922709)); assertThat(commentDTO.getText()).isEqualTo("Aw shucks, guys ... you make me blush with your compliments.<p>Tell you what, Ill make a deal: I'll keep writing if you keep reading. K?"); @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); assertThat(dateFormat.format(commentDTO.getTime())).isEqualTo("2011-08-25 02:38:47"); } @Test public void testCanDeserialiseSerialised() throws IOException { ItemDTO original = new ItemDTO(new ItemId(78), new UserId("amf"), new Date(115, 1, 17, 1, 2, 3).getTime() / 1000, false); ItemDTO transformed = mapper.readValue(mapper.writeValueAsString(original), ItemDTO.class); assertThat(transformed.getId()).isEqualTo(new ItemId(78)); assertThat(transformed.getBy()).isEqualTo(new UserId("amf")); assertThat(transformed.getTime()).isEqualTo(new Date(115, 1, 17, 1, 2, 3)); } }
43.177083
191
0.725452
cae7d077d31dc609604cdec14ae925d2f4fb57de
9,593
package org.linlinjava.litemall.admin.web; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.github.pagehelper.PageInfo; import com.google.gson.JsonObject; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.linlinjava.litemall.admin.config.webSocket.WebSocketUtil; import org.linlinjava.litemall.core.util.JacksonUtil; import org.linlinjava.litemall.db.domain.Item; import org.linlinjava.litemall.db.domain.LitemallAdmin; import org.linlinjava.litemall.db.domain.Task; import org.linlinjava.litemall.db.service.ScreenService; import org.linlinjava.litemall.db.util.ResponseUtil; import org.linlinjava.litemall.db.util.Constant; import org.linlinjava.litemall.db.service.TaskService; import org.linlinjava.litemall.db.util.StringUtilsXD; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(value = "/admin/screen/task") public class TaskController { @Autowired private TaskService taskService; @Autowired private ScreenService screenService; private static Logger logger = LoggerFactory.getLogger(TaskController.class); /** * @param page 开始页数 * @param limit 每页条数 * @Description: 获取任务列表 * @title selectTaskPage * @auther IngaWu * @currentdate:2020年9月2日 */ @ApiOperation(value = "获取任务列表") @GetMapping("/selectTaskPage") public ResponseUtil selectTaskPage(String name, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "limit", required = false) Integer limit) { ResponseUtil responseUtil = new ResponseUtil(); Task task = new Task(); task.setName(name); logger.info("selectTaskPage and task={},page={},limit={}", JSON.toJSONString(task), page, limit); try { PageInfo<Task> pageList = taskService.selectTaskPage(task, StringUtilsXD.checkPageNumParam(page), StringUtilsXD.checkPageSizeParam(limit)); return responseUtil.succeedPage(pageList); } catch (Exception e) { logger.error("selectTaskPage and task={},page={},limit={}", JSON.toJSONString(task), page, limit, e); } return responseUtil; } /** * @param taskId 任务id * @Description: 通过任务id查看任务详情 * @Title: selectTaskById * @auther IngaWu * @currentdate:2020年9月2日 */ @ApiOperation(value = "通过任务id查看任务详情") @GetMapping(value = "/selectTaskById") public ResponseUtil<Task> selectTaskById(@RequestParam(value = "taskId") String taskId) { logger.info("selectTaskById and taskId={}", taskId); ResponseUtil<Task> responseUtil = new ResponseUtil<>(); if (StringUtilsXD.isBlank(taskId)) { return responseUtil.initCodeAndMsg(Constant.STATUS_SYS_02, Constant.RTNINFO_SYS_02); } try { Task task = taskService.selectTaskById(taskId); responseUtil.setData(task); responseUtil.initCodeAndMsg(Constant.STATUS_SYS_00, Constant.RTNINFO_SYS_00); } catch (Exception e) { logger.error("selectTaskById and taskId={}", taskId, e); } return responseUtil; } /** * @Description: 添加任务 * @Title: insertTask * @auther IngaWu * @currentdate:2020年9月2日 */ @ApiOperation(value = "添加任务") @PostMapping(value = "/insertTask") public ResponseUtil<Task> insertTask(@RequestBody Task task) { logger.info("insertTask and task:{}", JSON.toJSONString(task)); ResponseUtil<Task> responseUtil = new ResponseUtil<>(); try { Subject currentUser = SecurityUtils.getSubject(); LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal(); task.setUserid(admin.getId()); int n = taskService.insertTask(task); if (n == 1) { responseUtil.initCodeAndMsg(Constant.STATUS_SYS_00, Constant.RTNINFO_SYS_00); } } catch (Exception e) { logger.error("insertTask and task:{}", JSON.toJSONString(task), e); } return responseUtil; } /** * @Description: 编辑任务 * @title updateTaskById * @author IngaWu * @currentdate:2020年9月2日 */ @ApiOperation(value = "编辑任务") @PostMapping(value = "/updateTaskById") public ResponseUtil<Task> updateTaskById(@RequestBody Task task) { logger.info("updateTaskById and task:{}", JSON.toJSONString(task)); ResponseUtil<Task> responseUtil = new ResponseUtil<>(); if (StringUtilsXD.isBlank(task.get_id())) { return responseUtil.initCodeAndMsg(Constant.STATUS_SYS_02, Constant.RTNINFO_SYS_02); } try { int n = taskService.updateTaskById(task); if (n == 1) { responseUtil.initCodeAndMsg(Constant.STATUS_SYS_00, Constant.RTNINFO_SYS_00); } } catch (Exception e) { logger.error("updateTaskById and task:{}", JSON.toJSONString(task), e); } return responseUtil; } @ApiOperation(value = "编辑完整任务") @PostMapping(value = "/updateTaskTotalById") public ResponseUtil<Task> updateTaskTotalById(@RequestBody Task task) { logger.info("updateTaskTotalById and task:{}", JSON.toJSONString(task)); ResponseUtil<Task> responseUtil = new ResponseUtil<>(); if (StringUtilsXD.isBlank(task.get_id())) { return responseUtil.initCodeAndMsg(Constant.STATUS_SYS_02, Constant.RTNINFO_SYS_02); } try { int n = taskService.updateTaskTotalById(task); if (n == 1) { responseUtil.initCodeAndMsg(Constant.STATUS_SYS_00, Constant.RTNINFO_SYS_00); } } catch (Exception e) { logger.error("updateTaskTotalById and task:{}", JSON.toJSONString(task), e); } return responseUtil; } /** * @param id 任务id * @Description: 删除任务 * @Title: deleteById * @auther IngaWu * @currentdate:2020年9月2日 */ @ApiOperation(value = "删除任务") @PostMapping(value = "/deleteById") public ResponseUtil<Task> deleteById(@RequestParam(value = "id") String id) { logger.info("deleteById and id={}", JSON.toJSONString(id)); ResponseUtil<Task> responseUtil = new ResponseUtil<>(); try { int n = taskService.deleteById(id); if (n == 1) { responseUtil.initCodeAndMsg(Constant.STATUS_SYS_00, Constant.RTNINFO_SYS_00); } } catch (Exception e) { logger.error("deleteById and id={}", JSON.toJSONString(id), e); } return responseUtil; } /** * @Description: 播放任务 * @Title: playTask * @auther IngaWu * @currentdate:2020年9月22日 */ @ApiOperation(value = "播放任务") @PostMapping(value = "/playTask") public ResponseUtil<Object> playTask(@RequestBody String body) { String id = JacksonUtil.parseString(body, "id"); List<String> selectCardIds = JacksonUtil.parseStringList(body, "selectCardIds"); logger.info("playTask and id ={},selectCardIds={}", id,JSON.toJSONString(selectCardIds)); if (null == selectCardIds || selectCardIds.size() < 1) { ResponseUtil<Object> responseUtil = new ResponseUtil<>(); return responseUtil.initCodeAndMsg(Constant.STATUS_SYS_03, Constant.RTNINFO_SYS_03); } return screenService.playXixunTask(id, selectCardIds); } /** * @Description: 快速创建任务 * @Title: insertQuickTask * @auther IngaWu * @currentdate:2020年9月22日 */ @ApiOperation(value = "快速创建任务") @PostMapping(value = "/insertQuickTask") public ResponseUtil<Task> insertQuickTask(@RequestParam(value = "programName") String programName, @RequestParam(value = "programId") String programId) { logger.info("insertQuickTask and programId:{}", programId); ResponseUtil<Task> responseUtil = new ResponseUtil<>(); try { String taskName = programName + "_Task"; Task existTask = taskService.selectTaskByName(taskName); if (null != existTask) { responseUtil.initCodeAndMsg(Constant.STATUS_SYS_04, Constant.RTNINFO_SYS_04); return responseUtil; } Subject currentUser = SecurityUtils.getSubject(); LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal(); Integer userId = admin.getId(); int n = taskService.insertQuickTask(taskName, programId, userId); if (n == 1) { responseUtil.initCodeAndMsg(Constant.STATUS_SYS_00, Constant.RTNINFO_SYS_00); } } catch (Exception e) { logger.error("insertQuickTask and programId:{}", programId, e); } return responseUtil; } @ApiOperation(value = "任务进度") @RequestMapping(value = "/nocice",method = RequestMethod.POST,produces = "application/json;charset=UTF-8") public Object demo(@RequestBody JSONObject json) throws Exception{ try { System.out.println("输出:"+json); System.out.println("输出2:"+json.toJSONString()); WebSocketUtil.sendInfo(json.toJSONString()); }catch (Exception e){ e.printStackTrace(); } return ResponseUtil.ok(json); } }
39.315574
179
0.644011
add4a8cc48d4cda98f5b98c1ce84e17cdfd04218
1,421
package com.helloingob.bluefever; import org.junit.Assert; import org.junit.Test; import com.helloingob.bluefever.command.encoder.PasswordEncoder; public class PasswordEncoderTests { @Test public void test_datecoder() { int pin = 123; Assert.assertTrue(PasswordEncoder.encode(pin).equals(encodePasswordOriginal(String.valueOf(pin)))); pin = 000000000; Assert.assertTrue(PasswordEncoder.encode(pin).equals(encodePasswordOriginal(String.valueOf(pin)))); pin = 999999999; Assert.assertTrue(PasswordEncoder.encode(pin).equals(encodePasswordOriginal(String.valueOf(pin)))); } private static String encodePasswordOriginal(String pin) { if (pin == null || pin.isEmpty()) { pin = "981723"; } String pinData = Integer.toHexString(Integer.parseInt(pin)); while (pinData.length() < 8) { pinData = "0" + pinData; } return LSBfirstWithHexString(pinData); } public static String LSBfirstWithHexString(String string) { int i; String[] splitData = new String[(string.length() / 2)]; for (i = 0; i < splitData.length; i++) { splitData[i] = string.substring(i * 2, (i * 2) + 2); } string = ""; for (i = splitData.length - 1; i >= 0; i--) { string = string + splitData[i]; } return string; } }
29.604167
107
0.612245
0158ab4749bea9a9c841e8b514d2dc69e8d7943a
1,416
package sneckomod.relics; import basemod.abstracts.CustomRelic; import com.badlogic.gdx.graphics.Texture; import com.megacrit.cardcrawl.actions.common.DrawCardAction; import com.megacrit.cardcrawl.actions.common.GainEnergyAction; import com.megacrit.cardcrawl.actions.utility.UseCardAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import sneckomod.SneckoMod; import downfall.util.TextureLoader; public class SneckoSoul extends CustomRelic { public static final String ID = SneckoMod.makeID("SneckoSoul"); private static final Texture IMG = TextureLoader.getTexture(SneckoMod.makeRelicPath("SneckoSoul.png")); private static final Texture OUTLINE = TextureLoader.getTexture(SneckoMod.makeRelicOutlinePath("SneckoSoul.png")); public SneckoSoul() { super(ID, IMG, OUTLINE, RelicTier.STARTER, LandingSound.MAGICAL); } public void atBattleStart() { this.grayscale = false; } public void onVictory() { grayscale = false; } public void onUseCard(AbstractCard c, UseCardAction action) { if (!grayscale && c.color != AbstractDungeon.player.getCardColor()) { addToBot(new DrawCardAction(1)); addToBot(new GainEnergyAction(1)); grayscale = true; } } public String getUpdatedDescription() { return DESCRIPTIONS[0]; } }
33.714286
118
0.728814
0fffd0df1f4e389722dc052ac2908bf3521dc3ff
3,220
package com.jdon.util; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * Creates instance of any object, given its full qualified class name is given * and it has a public accessable constructor. This class is a static class it * can not be instantiated * * @author Nadia Nashi */ public final class ObjectCreator { /** * Private constructor. This class can not be instantiated */ private ObjectCreator() { } /** * Instantaite an Object from a given class name * * @param className * full qualified name of the class * @return the instantaited Object * @exception java.lang.Exception * if instantiation failed */ public static Object createObject(String className) throws Exception { return createObject(Class.forName(className)); } /** * Instantaite an Object instance * * @param classObject * Class object representing the object type to be instantiated * @return the instantaied Object * @exception java.lang.Exception * if instantiation failed */ public static Object createObject(Class classObject) throws Exception { return classObject.newInstance(); } /** * Instantaite an Object instance, requires a constructor with parameters * * @param className * full qualified name of the class * @param params * an array including the required parameters to instantaite the * object * @return the instantaited Object * @exception java.lang.Exception * if instantiation failed */ public static Object createObject(String className, Object[] params) throws Exception { return createObject(Class.forName(className), params); } /** * Instantaite an Object instance, requires a constractor with parameters * * @param classObject * , Class object representing the object type to be instantiated * @param params * an array including the required parameters to instantaite the * object * @return the instantaied Object * @exception java.lang.Exception * if instantiation failed */ public static Object createObject(Class classObject, Object[] params) throws Exception { Constructor[] constructors = classObject.getConstructors(); Object object = null; for (int counter = 0; counter < constructors.length; counter++) { try { object = constructors[counter].newInstance(params); } catch (Exception e) { if (e instanceof InvocationTargetException) ((InvocationTargetException) e).getTargetException().printStackTrace(); // do nothing, try the next constructor } } if (object == null) throw new InstantiationException(); return object; } public static Class createClass(String className) { Class classService = null; try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); classService = classLoader.loadClass(className); } catch (Exception ex) { System.err.print("[JdonFramework] createClass error:" + ex); } return classService; } }
31.568627
90
0.673913
e8d0067866ea5c899d62e556a4e33c911033b40e
21,761
package com.thefuntasty.infinity; import android.os.Looper; import android.support.annotation.IntRange; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; @SuppressWarnings({"UnusedParameters", "unused"}) public abstract class InfinityAdapter<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> implements InfinityEventInterface { private static final int HEADER_VIEW_TYPE_OFFSET = 100001; private static final int FOOTER = -1; private @InfinityConstant.Status int loadingStatus = InfinityConstant.IDLE; private List<T> content = new ArrayList<>(); private InfinityFillerImpl<T> filler; private InfinityEventListener eventListener; private int limit = 20; private int offset = 0; private int visibleThreshold = 5; private boolean footerVisible = false; private boolean pullToRefresh = false; private boolean startCalled = false; private boolean initialContent = false; private boolean isRestarted = false; private RecyclerView.OnScrollListener onScrollListener; private RecyclerView recyclerView; @SuppressWarnings("unchecked") @Override public final VH onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType > HEADER_VIEW_TYPE_OFFSET) { return (VH) onCreateHeaderViewHolder(parent, viewType - HEADER_VIEW_TYPE_OFFSET); } else if (viewType == FOOTER) { return (VH) onCreateFooterViewHolder(parent); } else { return onCreateContentViewHolder(parent, viewType); } } @Override public final void onBindViewHolder(VH holder, int position) { int viewType = getItemViewType(position); if (viewType > HEADER_VIEW_TYPE_OFFSET) { onBindHeaderViewHolder(holder, position); } else if (viewType == FOOTER) { onBindFooterViewHolder(holder); } else { onBindContentViewHolder(holder, position - getHeaderCount()); } } @Override public void onBindViewHolder(VH holder, int position, List<Object> payloads) { int viewType = getItemViewType(position); if (viewType > HEADER_VIEW_TYPE_OFFSET) { if (payloads.isEmpty()) { onBindHeaderViewHolder(holder, position); } else { onBindHeaderViewHolder(holder, position, payloads); } } else if (viewType == FOOTER) { onBindFooterViewHolder(holder); } else { if (payloads.isEmpty()) { onBindContentViewHolder(holder, position - getHeaderCount()); } else { onBindContentViewHolder(holder, position - getHeaderCount(), payloads); } } } /** * Return total item count in adapter including headers and loading/refresh footer * * @return number of items in adapter */ @Override public final int getItemCount() { return getHeaderCount() + (content != null ? content.size() : 0) + (footerVisible ? 1 : 0); } /** * Returns content (!) items count. Do not include headers and loading/refresh footer * * @return number of content items */ public final int getContentItemCount() { return content.size(); } @Override public final int getItemViewType(int position) { if (position < getHeaderCount()) { return getHeaderItemViewType(position) + HEADER_VIEW_TYPE_OFFSET; } else if (position < getHeaderCount() + content.size()) { return getContentItemViewType(position); } else { return FOOTER; } } /** * Sets initial collection what should be show before loading has been started * * @param initialCollection reference to initial collection */ public void setInitialContent(List<T> initialCollection) { initialContent = true; content.clear(); content.addAll(initialCollection); notifyDataSetChanged(); } /** * Get number of headers * * @return number of headers */ public int getHeaderCount() { return 0; } /** * Gets header view type at specified position. Must not be negative value. Must not collide with * content view types * * @param position item position * @return header header(!) item view type */ public @IntRange(from = 50, to = 100) int getHeaderItemViewType(int position) { return 50; } /** * Create ViewHolder for header item * * @param parent ViewHolder's parent * @return created header item's ViewHolder */ public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup parent, int viewType) { return null; } /** * Bind header with provided ViewHolder at specified position * * @param holder header's view holder * @param position header's position */ public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int position) { } /** * Bind header with provided ViewHolder at specified position * * @param holder header's view holder * @param position header's position * @param payloads custom update payloads */ public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int position, List<Object> payloads) { onBindHeaderViewHolder(holder, position); } /** * Provides FooterViewHolder after onBind action * * @param footerViewHolder footer's view holder */ protected void onUpdateFooterViewHolder(FooterViewHolder footerViewHolder) { } /** * Create ViewHolder for content item * * @param parent ViewHolder's parent * @return created content item's ViewHolder */ public abstract VH onCreateContentViewHolder(ViewGroup parent, int viewType); /** * Bind content with provided ViewHolder at specified position * * @param holder header's view holder * @param position header's position */ public abstract void onBindContentViewHolder(VH holder, int position); /** * Bind content with provided ViewHolder at specified position * * @param holder header's view holder * @param position header's position * @param payloads custom update payloads */ public void onBindContentViewHolder(VH holder, int position, List<Object> payloads) { onBindContentViewHolder(holder, position); } /** * Gets item view type at specified position. Must not be negative value. Must not collide with * headers' view types * * @param position item position * @return content item view type */ public @IntRange(from = 0, to = 49) int getContentItemViewType(int position) { return 0; } /** * Provides content ViewHolder before it gets recycled * * @param holder content ViewHolder */ protected void onContentViewRecycled(VH holder) { } /** * Provides footer ViewHolder before it gets recycled * * @param holder footer ViewHolder */ protected void onFooterViewRecycled(FooterViewHolder holder) { } /** * Provides footer ViewHolder when it gets attached to window * * @param holder footer ViewHolder */ protected void onFooterViewAttachedToWindow(FooterViewHolder holder) { } /** * Provides content ViewHolder when it gets attached to window * * @param holder content ViewHolder */ protected void onContentViewAttachedToWindow(VH holder) { } /** * Provides footer ViewHolder when it gets detached from window * * @param holder footer ViewHolder */ protected void onFooterViewDetachedFromWindow(FooterViewHolder holder) { } /** * Provides content ViewHolder when it gets detached from window * * @param holder contentViewHolder */ protected void onContentViewDetachedFromWindow(VH holder) { } @Override public void onViewRecycled(VH holder) { if (holder instanceof FooterViewHolder) { onFooterViewRecycled((FooterViewHolder) holder); } else { onContentViewRecycled(holder); } super.onViewRecycled(holder); } @Override public void onViewAttachedToWindow(VH holder) { super.onViewAttachedToWindow(holder); if (holder instanceof FooterViewHolder) { onFooterViewAttachedToWindow((FooterViewHolder) holder); } else { onContentViewAttachedToWindow(holder); } } @Override public void onViewDetachedFromWindow(VH holder) { super.onViewDetachedFromWindow(holder); if (holder instanceof FooterViewHolder) { onFooterViewDetachedFromWindow((FooterViewHolder) holder); } else { onContentViewDetachedFromWindow(holder); } } private RecyclerView.ViewHolder onCreateFooterViewHolder(ViewGroup parent) { View footer = LayoutInflater.from(parent.getContext()).inflate(getFooterLayout(), parent, false); footer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (loadingStatus == InfinityConstant.ERROR) { tryAgain(); } } }); return new FooterViewHolder(footer); } private void onBindFooterViewHolder(RecyclerView.ViewHolder holder) { if (holder instanceof FooterViewHolder) { FooterViewHolder footerViewHolder = (FooterViewHolder) holder; onBindFooterViewHolder(footerViewHolder); } } private void onBindFooterViewHolder(FooterViewHolder footerViewHolder) { if (loadingStatus == InfinityConstant.ERROR) { footerViewHolder.loading.setVisibility(View.GONE); footerViewHolder.retry.setVisibility(View.VISIBLE); } else { footerViewHolder.loading.setVisibility(View.VISIBLE); footerViewHolder.retry.setVisibility(View.GONE); } if (recyclerView != null && recyclerView.getLayoutManager() instanceof StaggeredGridLayoutManager) { StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) footerViewHolder.itemView.getLayoutParams(); layoutParams.setFullSpan(true); } onUpdateFooterViewHolder(footerViewHolder); } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { this.recyclerView = recyclerView; RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { onAttachedGridLayoutManager(recyclerView); } else if (layoutManager instanceof LinearLayoutManager) { onAttachedLinearLayoutManager(recyclerView); } else if (layoutManager instanceof StaggeredGridLayoutManager) { onAttachedStaggeredGridManager(recyclerView); } } private void onAttachedStaggeredGridManager(RecyclerView recyclerView) { final StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager(); onScrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { int visibleItemCount = recyclerView.getChildCount(); int totalItemCount = staggeredGridLayoutManager.getItemCount(); int[] positions = new int[staggeredGridLayoutManager.getSpanCount()]; staggeredGridLayoutManager.findLastVisibleItemPositions(positions); int lastVisibleItem = findMax(positions); staggeredGridLayoutManager.findFirstVisibleItemPositions(positions); int firstVisibleItem = findMin(positions); if (!initialContent && loadingStatus == InfinityConstant.IDLE && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) { footerVisible = true; requestNextPostponed(recyclerView); } } }; recyclerView.addOnScrollListener(onScrollListener); } private void onAttachedGridLayoutManager(final RecyclerView recyclerView) { final GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager(); gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { int viewType = getItemViewType(position); if (viewType > HEADER_VIEW_TYPE_OFFSET || viewType == FOOTER) { return gridLayoutManager.getSpanCount(); } else { return 1; } } }); onScrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { int firstVisibleItem = gridLayoutManager.findFirstVisibleItemPosition(); int visibleItemCount = recyclerView.getChildCount(); int totalItemCount = gridLayoutManager.getItemCount(); if (!initialContent && loadingStatus == InfinityConstant.IDLE && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) { footerVisible = true; requestNextPostponed(recyclerView); } } }; recyclerView.addOnScrollListener(onScrollListener); } private void onAttachedLinearLayoutManager(RecyclerView recyclerView) { final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); onScrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { int firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition(); int visibleItemCount = recyclerView.getChildCount(); int totalItemCount = linearLayoutManager.getItemCount(); if (!initialContent && loadingStatus == InfinityConstant.IDLE && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) { footerVisible = true; requestNextPostponed(recyclerView); } } }; recyclerView.addOnScrollListener(onScrollListener); } @Override public void onDetachedFromRecyclerView(RecyclerView recyclerView) { recyclerView.removeOnScrollListener(onScrollListener); } private void requestFirst() { offset = 0; setLoading(InfinityConstant.FIRST_PAGE); onPreLoad(InfinityConstant.FIRST_PAGE); refreshFooter(); filler.resetCallbacks(getFirstPageCallback(), getNextPageCallback()); filler.onLoad(limit, offset, filler.getFirstPageCallback()); } private void requestNextPostponed(RecyclerView recyclerView) { setLoading(InfinityConstant.NEXT_PAGE); recyclerView.post(new Runnable() { @Override public void run() { refreshFooter(); onPreLoad(InfinityConstant.NEXT_PAGE); filler.onLoad(limit, offset, filler.getNextPageCallback()); } }); } @NonNull private InfinityFiller.Callback<T> getFirstPageCallback() { return new InfinityFiller.Callback<T>() { @Override public void onData(List<T> list) { if (!interrupted) { if (isRestarted) { content.clear(); notifyDataSetChanged(); } addDataAndResolveState(list, InfinityConstant.FIRST_PAGE); } } @Override public void onError(Throwable error) { if (!interrupted) { setError(); refreshFooter(); onFirstUnavailable(error, pullToRefresh); } } }; } @NonNull private InfinityFiller.Callback<T> getNextPageCallback() { return new InfinityFiller.Callback<T>() { @Override public void onData(List<T> list) { if (!interrupted) { addDataAndResolveState(list, InfinityConstant.NEXT_PAGE); } } @Override public void onError(Throwable error) { if (!interrupted) { setError(); refreshFooter(); onNextUnavailable(error); } } }; } public boolean isStarted() { return startCalled; } public void start() { if (!startCalled) { requestFirst(); startCalled = true; } else { throw new IllegalStateException("start() can be called only once. Use restart instead"); } } public void restart() { restart(false); } public void restart(boolean pullToRefresh) { footerVisible = false; this.pullToRefresh = pullToRefresh; this.isRestarted = true; requestFirst(); } /** * Method to define threshold indicating if next page should be loaded. If you want to increase * amount of invisible items, increase this value. * * @param visibleThreshold threshold size. Default value = 5 */ public void setVisibleThreshold(int visibleThreshold) { this.visibleThreshold = visibleThreshold; } /** * Sets limit value. If limit is not exceeded after data load, infinity expects there is no more * data and onFinished() is called * * @param limit limit value */ public void setLimit(int limit) { this.limit = limit; } /** * Sets event listener what provides info during data load * * @param eventListener instance of */ public void setEventListener(InfinityEventListener eventListener) { this.eventListener = eventListener; } /** * Sets data filler * * @param filler filler from what data are obtained */ public void setFiller(@NonNull InfinityFiller<T> filler) { this.filler = new InfinityFillerImpl<>(filler); } /** * Gets content item at particular position. * * @param position index of returned item * @return content item */ public T getContentItem(int position) { return content.get(position); } /** * Gets all content items * * @return list of current content items */ public List<T> getContentItems() { return content; } /** * Add item to content at specific position. If restart is called, item is removed with rest of the content. * * @param pos position where item will be added. If position is bigger than content size, item will be added to the end of the content. * @param item item which will be added to the content */ public void addItem(int pos, T item) { if (pos >= content.size()) { content.add(item); notifyItemInserted(getHeaderCount() + content.size() - 1); } else { content.add(pos, item); notifyItemInserted(getHeaderCount() + pos); } offset += 1; } /** * Add items to content at specific position. If restart is called, items are removed with rest of the content. * * @param pos position where items will be added. If position is bigger than content size, items will be added to the end of the content. * @param items items what will be added to the content */ public void addItems(int pos, List<T> items) { if (pos >= content.size()) { content.addAll(items); notifyItemInserted(getHeaderCount() + content.size() - 1); } else { content.addAll(pos, items); notifyItemInserted(getHeaderCount() + pos); } offset += items.size(); } /** * Retrieves current status of item load * * @return one of the statuses: ERROR, IDLE, LOADING, FINISHED */ public @InfinityConstant.Status int getCurrentLoadingStatus() { return loadingStatus; } private void addDataAndResolveState(@NonNull List<T> data, @InfinityConstant.Part int part) { if (Looper.myLooper() != Looper.getMainLooper()) { throw new InfinityException("Callback methods onData() & onError() must be called from UI Thread"); } content.addAll(data); initialContent = false; setIdle(); refreshFooter(); notifyItemRangeInserted(offset + getHeaderCount(), data.size()); offset += data.size(); if (part == InfinityConstant.FIRST_PAGE && data.size() == 0) { // no data onFirstEmpty(pullToRefresh); setFinished(); removeFooter(); } else { // we have some data onLoad(part); if (data.size() < limit) { setFinished(); removeFooter(); } else { // notify scroller about possibility loading next parts onScrollListener.onScrolled(recyclerView, recyclerView.getScrollX(), recyclerView.getScrollY()); } } } private void refreshFooter() { if (!footerVisible) { // add footer footerVisible = true; notifyItemInserted(getItemCount()); } else { // refresh content notifyItemChanged(getItemCount() - 1); } } private void removeFooter() { if (footerVisible) { footerVisible = false; notifyItemRemoved(getItemCount()); } } private void setError() { loadingStatus = InfinityConstant.ERROR; } private void setIdle() { loadingStatus = InfinityConstant.IDLE; } private void setLoading(@InfinityConstant.Part int part) { loadingStatus = InfinityConstant.LOADING; } private void setFinished() { loadingStatus = InfinityConstant.FINISHED; onFinished(); } private void onLoad(@InfinityConstant.Part int part) { if (part == InfinityConstant.FIRST_PAGE) { recyclerView.scrollToPosition(0); onFirstLoaded(pullToRefresh); } else { onNextLoaded(); } } private void onPreLoad(@InfinityConstant.Part int part) { if (part == InfinityConstant.FIRST_PAGE) { onPreLoadFirst(pullToRefresh); } else { onPreLoadNext(); } } private void tryAgain() { requestNextPostponed(recyclerView); } public @LayoutRes int getFooterLayout() { return R.layout.footer_layout; } public final void onPreLoadFirst(boolean pullToRefresh) { if (eventListener != null) { eventListener.onPreLoadFirst(pullToRefresh); } } @Override public final void onPreLoadNext() { if (eventListener != null) { eventListener.onPreLoadNext(); } } @Override public final void onFirstLoaded(boolean pullToRefresh) { if (eventListener != null) { eventListener.onFirstLoaded(pullToRefresh); } } @Override public final void onNextLoaded() { if (eventListener != null) { eventListener.onNextLoaded(); } } @Override public final void onFirstUnavailable(Throwable error, boolean pullToRefresh) { if (eventListener != null) { eventListener.onFirstUnavailable(error, pullToRefresh); } } @Override public final void onFirstEmpty(boolean pullToRefresh) { if (eventListener != null) { eventListener.onFirstEmpty(pullToRefresh); } } @Override public final void onNextUnavailable(Throwable error) { if (eventListener != null) { eventListener.onNextUnavailable(error); } } @Override public final void onFinished() { if (eventListener != null) { eventListener.onFinished(); } } private int findMax(int[] lastPositions) { int max = Integer.MIN_VALUE; for (int value : lastPositions) { if (value > max) { max = value; } } return max; } private int findMin(int[] lastPositions) { int min = Integer.MAX_VALUE; for (int value : lastPositions) { if (value != RecyclerView.NO_POSITION && value < min) { min = value; } } return min; } }
28.445752
148
0.731446
0f22c726caaa93f266471a78fd0d5766bd2f6604
539
import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.WebDriverWait; public class RequestTourPage extends BaseActions { public RequestTourPage(WebDriver driver, WebDriverWait wait) { super(driver, wait); } String currentTourRequest; public String RequestTourSection(){ driver.findElement(Locators.LINK_REQUEST_TOUR).click(); currentTourRequest = driver.getCurrentUrl(); System.out.println(currentTourRequest); return currentTourRequest; } }
31.705882
68
0.714286
ff3c81e518420365d235e3e33a9e2cdbdc1bfa44
480
package com.robert.java.unioviscope.model; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue("ADMIN") public class Admin extends User { private static final long serialVersionUID = -3901544609521291065L; Admin() { } public Admin(String userName) { super(userName); } @Override public String toString() { return "Admin [userName=" + getUserName() + ", role=" + getRole() + "]"; } }
19.2
75
0.6875
f716c9d28307c7e9af149c9d81e3df55e9bb30df
7,012
/* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``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 THE APACHE SOFTWARE FOUNDATION 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.tigris.subversion.svnant.conditions; import org.tigris.subversion.svnclientadapter.ISVNClientAdapter; import org.tigris.subversion.svnclientadapter.ISVNInfo; import org.tigris.subversion.svnclientadapter.SVNClientException; import org.tigris.subversion.svnclientadapter.SVNNodeKind; import org.tigris.subversion.svnclientadapter.SVNRevision; import org.tigris.subversion.svnclientadapter.SVNUrl; import org.tigris.subversion.svnant.SvnFacade; import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import java.io.File; import java.net.MalformedURLException; /** * This condition works similar to the generally known <code>available</code> task shipped * with the ant distribution. The only difference is it's * * @author Daniel Kasmeroglu <a href="mailto:daniel.kasmeroglu">daniel.kasmeroglu@kasisoft.net</a> */ public class Available extends SvnCondition { private String target = null; private FileDir type = null; /** * {@inheritDoc} */ protected void preconditions() throws BuildException { if( target == null ) { throw new BuildException( "Missing attribute 'target'." ); } } /** * {@inheritDoc} */ protected boolean internalEval() { ISVNClientAdapter client = SvnFacade.getClientAdapter( this ); // Retrieve info for the requested element ISVNInfo info = null; try { File asfile = new File( Project.translatePath( target ) ); if( asfile.exists() ) { // Since the target exists locally, assume it's not a URL. info = client.getInfo( asfile ); } else { try { SVNUrl url = new SVNUrl( target ); info = client.getInfo( url ); } catch( MalformedURLException ex ) { throw new BuildException( "The url '" + target + "' is not valid.", ex ); } } } catch( SVNClientException ex ) { // assume that it is not existant return false; } // No info -> not in repository if( null == info ) { return false; } // No revision -> not in repository if( (info.getRevision() == null) || (SVNRevision.INVALID_REVISION.equals( info.getRevision() )) ) { return false; } if( type != null ) { if( type.isDir() ) { return info.getNodeKind() == SVNNodeKind.DIR; } else /* if ( type.isFile() ) */{ return info.getNodeKind() == SVNNodeKind.FILE; } } // Assume it is... return true; } /** * Changes the current target to be tested. * * @param newtarget The new target to be set. */ public void setTarget( String newtarget ) { target = newtarget; if( (target != null) && (target.length() == 0) ) { target = null; } } /** * Sets the type if a specific type is desired. * * @param newtype The type that has to be used. */ public void setType( FileDir newtype ) { type = newtype; } /** * EnumeratedAttribute covering the file types to be checked for, either * file or dir. */ public static class FileDir extends EnumeratedAttribute { private static final String[] VALUES = { "file", "dir" }; /** * {@inheritDoc} */ public String[] getValues() { return VALUES; } /** * Indicate if the value specifies a directory. * * @return true if the value specifies a directory. */ public boolean isDir() { return "dir".equalsIgnoreCase( getValue() ); } /** * Indicate if the value specifies a file. * * @return true if the value specifies a file. */ public boolean isFile() { return "file".equalsIgnoreCase( getValue() ); } } }
34.712871
108
0.605819
86c1fecb2e3679849b7b909893683d72705d46d5
3,110
/** * Copyright 2013 Netflix, 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 rx.operators; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import rx.Notification; import rx.Observer; import rx.Scheduler; import rx.util.functions.Action0; /* package */class ScheduledObserver<T> implements Observer<T> { private final Observer<T> underlying; private final Scheduler scheduler; private final ConcurrentLinkedQueue<Notification<T>> queue = new ConcurrentLinkedQueue<Notification<T>>(); private final AtomicInteger counter = new AtomicInteger(0); public ScheduledObserver(Observer<T> underlying, Scheduler scheduler) { this.underlying = underlying; this.scheduler = scheduler; } @Override public void onCompleted() { enqueue(new Notification<T>()); } @Override public void onError(final Exception e) { enqueue(new Notification<T>(e)); } @Override public void onNext(final T args) { enqueue(new Notification<T>(args)); } private void enqueue(Notification<T> notification) { // this must happen before 'counter' is used to provide synchronization between threads queue.offer(notification); // we now use counter to atomically determine if we need to start processing or not // it will be 0 if it's the first notification or the scheduler has finished processing work // and we need to start doing it again if (counter.getAndIncrement() == 0) { processQueue(); } } private void processQueue() { scheduler.schedule(new Action0() { @Override public void call() { Notification<T> not = queue.poll(); switch (not.getKind()) { case OnNext: underlying.onNext(not.getValue()); break; case OnError: underlying.onError(not.getException()); break; case OnCompleted: underlying.onCompleted(); break; default: throw new IllegalStateException("Unknown kind of notification " + not); } // decrement count and if we still have work to do // recursively schedule ourselves to process again if (counter.decrementAndGet() > 0) { scheduler.schedule(this); } } }); } }
32.395833
110
0.620579
facf8d2dfc177f43317201f3e1d04aabcac2bd15
3,953
package ghost.framework.web.mvc.nginx.ui.plugin.controller; import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.RuntimeUtil; import cn.hutool.core.util.StrUtil; import ghost.framework.beans.annotation.injection.Autowired; import ghost.framework.web.angular1x.context.controller.ControllerBase; import ghost.framework.web.context.bind.annotation.RequestMapping; import ghost.framework.web.context.http.responseContent.DataResponse; import ghost.framework.web.mvc.context.ModelAndView; import ghost.framework.web.mvc.context.bind.annotation.Controller; import ghost.framework.web.mvc.context.bind.annotation.ResponseBody; import ghost.framework.web.mvc.nginx.ui.plugin.model.MonitorInfo; import ghost.framework.web.mvc.nginx.ui.plugin.service.MonitorService; import ghost.framework.web.mvc.nginx.ui.plugin.service.SettingService; import ghost.framework.web.mvc.nginx.ui.plugin.utils.SystemTool; import javax.servlet.http.HttpSession; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; //@RequestMapping("/adminPage/monitor") @Controller("/api") public class MonitorController extends ControllerBase { @Autowired MonitorService monitorService; @Autowired SettingService settingService; @RequestMapping("") public ModelAndView index(HttpSession httpSession, ModelAndView modelAndView) { List<Map<String, String>> list = new ArrayList<>(); if (SystemTool.isWindows()) { File[] roots = File.listRoots();// 获取磁盘分区列表 for (File file : roots) { Map<String, String> map = new HashMap<String, String>(); long freeSpace = file.getFreeSpace(); long totalSpace = file.getTotalSpace(); long usableSpace = totalSpace - freeSpace; map.put("path", file.getPath()); map.put("freeSpace", freeSpace / 1024 / 1024 / 1024 + "G");// 空闲空间 map.put("usableSpace", usableSpace / 1024 / 1024 / 1024 + "G");// 已用空间 map.put("totalSpace", totalSpace / 1024 / 1024 / 1024 + "G");// 总空间 map.put("percent", NumberUtil.decimalFormat("#.##%", (double) usableSpace / (double) totalSpace));// 总空间 list.add(map); } } else { try { List<String> lines = RuntimeUtil.execForLines("df -h"); for (int i = 1; i < lines.size(); i++) { String line = lines.get(i); if (line.startsWith(File.separator)) { while (line.contains(" ")) { line = line.replace(" ", " "); } Map<String, String> map = new HashMap<String, String>(); String[] names = line.split(" "); map.put("path", names[0]); map.put("freeSpace", names[3]);// 空闲空间 map.put("usableSpace", names[2]);// 已用空间 map.put("totalSpace", names[1]);// 总空间 map.put("percent", names[4]);// 总空间 list.add(map); } } } catch (Exception e) { e.printStackTrace(); } } modelAndView.addObject("list", list); String nginxPath = settingService.get("nginxPath"); String nginxExe = settingService.get("nginxExe"); String nginxDir = settingService.get("nginxDir"); Boolean isInit = StrUtil.isNotEmpty(nginxExe) || StrUtil.isNotEmpty(nginxPath); if (StrUtil.isEmpty(nginxExe)) { nginxExe = "nginx"; } modelAndView.addObject("nginxDir", nginxDir); modelAndView.addObject("nginxExe", nginxExe); modelAndView.addObject("nginxPath", nginxPath); modelAndView.addObject("isInit", isInit.toString()); modelAndView.setViewName("/adminPage/monitor/index"); return modelAndView; } @RequestMapping("check") @ResponseBody public DataResponse check() { MonitorInfo monitorInfo = monitorService.getMonitorInfo(); return DataResponse.success(monitorInfo); } @RequestMapping("addNginxGiudeOver") @ResponseBody public DataResponse addNginxGiudeOver(String nginxDir, String nginxExe, String nginxPath) { settingService.set("nginxDir", nginxDir); settingService.set("nginxExe", nginxExe); settingService.set("nginxPath", nginxPath); return DataResponse.success(); } }
33.5
108
0.715406
fdb994d3187d1d5444351352ebc843bcc44eeddf
7,281
// Copyright 2017 The Nomulus 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 google.registry.batch; import static com.google.common.base.Preconditions.checkArgument; import static google.registry.util.DateTimeUtils.isBeforeOrAt; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import com.google.appengine.api.taskqueue.TransientFailureException; import com.google.common.base.Joiner; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Multimap; import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.Config; import google.registry.model.EppResource; import google.registry.model.eppcommon.Trid; import google.registry.model.host.HostResource; import google.registry.persistence.VKey; import google.registry.request.Action.Service; import google.registry.util.CloudTasksUtils; import google.registry.util.Retrier; import javax.inject.Inject; import javax.inject.Named; import org.joda.time.DateTime; import org.joda.time.Duration; /** Helper class to enqueue tasks for handling asynchronous operations in flows. */ public final class AsyncTaskEnqueuer { /** The HTTP parameter names used by async flows. */ public static final String PARAM_RESOURCE_KEY = "resourceKey"; public static final String PARAM_REQUESTING_CLIENT_ID = "requestingClientId"; public static final String PARAM_CLIENT_TRANSACTION_ID = "clientTransactionId"; public static final String PARAM_SERVER_TRANSACTION_ID = "serverTransactionId"; public static final String PARAM_IS_SUPERUSER = "isSuperuser"; public static final String PARAM_HOST_KEY = "hostKey"; public static final String PARAM_REQUESTED_TIME = "requestedTime"; public static final String PARAM_RESAVE_TIMES = "resaveTimes"; /** The task queue names used by async flows. */ public static final String QUEUE_ASYNC_ACTIONS = "async-actions"; public static final String QUEUE_ASYNC_DELETE = "async-delete-pull"; public static final String QUEUE_ASYNC_HOST_RENAME = "async-host-rename-pull"; private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final Duration MAX_ASYNC_ETA = Duration.standardDays(30); private final Duration asyncDeleteDelay; private final Queue asyncDeletePullQueue; private final Queue asyncDnsRefreshPullQueue; private final Retrier retrier; private CloudTasksUtils cloudTasksUtils; @Inject public AsyncTaskEnqueuer( @Named(QUEUE_ASYNC_DELETE) Queue asyncDeletePullQueue, @Named(QUEUE_ASYNC_HOST_RENAME) Queue asyncDnsRefreshPullQueue, @Config("asyncDeleteFlowMapreduceDelay") Duration asyncDeleteDelay, CloudTasksUtils cloudTasksUtils, Retrier retrier) { this.asyncDeletePullQueue = asyncDeletePullQueue; this.asyncDnsRefreshPullQueue = asyncDnsRefreshPullQueue; this.asyncDeleteDelay = asyncDeleteDelay; this.cloudTasksUtils = cloudTasksUtils; this.retrier = retrier; } /** Enqueues a task to asynchronously re-save an entity at some point in the future. */ public void enqueueAsyncResave(VKey<?> entityToResave, DateTime now, DateTime whenToResave) { enqueueAsyncResave(entityToResave, now, ImmutableSortedSet.of(whenToResave)); } /** * Enqueues a task to asynchronously re-save an entity at some point(s) in the future. * * <p>Multiple re-save times are chained one after the other, i.e. any given run will re-enqueue * itself to run at the next time if there are remaining re-saves scheduled. */ public void enqueueAsyncResave( VKey<?> entityKey, DateTime now, ImmutableSortedSet<DateTime> whenToResave) { DateTime firstResave = whenToResave.first(); checkArgument(isBeforeOrAt(now, firstResave), "Can't enqueue a resave to run in the past"); Duration etaDuration = new Duration(now, firstResave); if (etaDuration.isLongerThan(MAX_ASYNC_ETA)) { logger.atInfo().log( "Ignoring async re-save of %s; %s is past the ETA threshold of %s.", entityKey, firstResave, MAX_ASYNC_ETA); return; } Multimap<String, String> params = ArrayListMultimap.create(); params.put(PARAM_RESOURCE_KEY, entityKey.stringify()); params.put(PARAM_REQUESTED_TIME, now.toString()); if (whenToResave.size() > 1) { params.put(PARAM_RESAVE_TIMES, Joiner.on(',').join(whenToResave.tailSet(firstResave, false))); } logger.atInfo().log("Enqueuing async re-save of %s to run at %s.", entityKey, whenToResave); cloudTasksUtils.enqueue( QUEUE_ASYNC_ACTIONS, cloudTasksUtils.createPostTaskWithDelay( ResaveEntityAction.PATH, Service.BACKEND.toString(), params, etaDuration)); } /** Enqueues a task to asynchronously delete a contact or host, by key. */ public void enqueueAsyncDelete( EppResource resourceToDelete, DateTime now, String requestingRegistrarId, Trid trid, boolean isSuperuser) { logger.atInfo().log( "Enqueuing async deletion of %s on behalf of registrar %s.", resourceToDelete.getRepoId(), requestingRegistrarId); TaskOptions task = TaskOptions.Builder.withMethod(Method.PULL) .countdownMillis(asyncDeleteDelay.getMillis()) .param(PARAM_RESOURCE_KEY, resourceToDelete.createVKey().stringify()) .param(PARAM_REQUESTING_CLIENT_ID, requestingRegistrarId) .param(PARAM_SERVER_TRANSACTION_ID, trid.getServerTransactionId()) .param(PARAM_IS_SUPERUSER, Boolean.toString(isSuperuser)) .param(PARAM_REQUESTED_TIME, now.toString()); trid.getClientTransactionId() .ifPresent(clTrid -> task.param(PARAM_CLIENT_TRANSACTION_ID, clTrid)); addTaskToQueueWithRetry(asyncDeletePullQueue, task); } /** Enqueues a task to asynchronously refresh DNS for a renamed host. */ public void enqueueAsyncDnsRefresh(HostResource host, DateTime now) { VKey<HostResource> hostKey = host.createVKey(); logger.atInfo().log("Enqueuing async DNS refresh for renamed host %s.", hostKey); addTaskToQueueWithRetry( asyncDnsRefreshPullQueue, TaskOptions.Builder.withMethod(Method.PULL) .param(PARAM_HOST_KEY, hostKey.stringify()) .param(PARAM_REQUESTED_TIME, now.toString())); } /** * Adds a task to a queue with retrying, to avoid aborting the entire flow over a transient issue * enqueuing a task. */ private void addTaskToQueueWithRetry(final Queue queue, final TaskOptions task) { retrier.callWithRetry(() -> queue.add(task), TransientFailureException.class); } }
45.223602
100
0.754429
86910724708d442ea05a7c61a6fa82a360c9c917
1,208
package mcjty.lib.varia; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.network.play.server.SPlaySoundEffectPacket; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class SoundTools { // Server side: play a sound to all nearby players public static void playSound(World worldObj, SoundEvent soundName, double x, double y, double z, double volume, double pitch) { SPlaySoundEffectPacket soundEffect = new SPlaySoundEffectPacket(soundName, SoundCategory.BLOCKS, x, y, z, (float) volume, (float) pitch); for (int j = 0; j < worldObj.players().size(); ++j) { ServerPlayerEntity player = (ServerPlayerEntity)worldObj.players().get(j); BlockPos chunkcoordinates = player.blockPosition(); double d7 = x - chunkcoordinates.getX(); double d8 = y - chunkcoordinates.getY(); double d9 = z - chunkcoordinates.getZ(); double d10 = d7 * d7 + d8 * d8 + d9 * d9; if (d10 <= 256.0D) { player.connection.send(soundEffect); } } } }
38.967742
145
0.667219
4a0c2fa6ed92d64983015eb459f7fa0e1b1469ac
1,436
package com.pulu.robot.service; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import com.pulu.robot.om.EM; import com.pulu.robot.om.Experience; @SuppressWarnings("resource") public class EMService { public static EM em = new EM(); private final static String EM_PATH = "data//em.txt"; static { FileInputStream fis; try { fis = new FileInputStream(EM_PATH); ObjectInputStream ois = new ObjectInputStream(fis); em = (EM) ois.readObject(); if (em == null) em = new EM(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void serializeToFile() { File file = new File(EM_PATH); try { file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(em); oos.flush(); oos.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println(em.getExperience().getName()); } public static void addE(Experience e) { em.setExperience(e); } }
24.758621
56
0.707521
baa4852b9bd6bb867f0935140a11d9ad63ad7fd5
6,126
/* * 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 com.github.sgoeschl.freemarker.cli.tools.commonscsv; import com.github.sgoeschl.freemarker.cli.impl.DocumentFactory; import com.github.sgoeschl.freemarker.cli.model.Document; import com.github.sgoeschl.freemarker.cli.model.Settings; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.CSVRecord; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.List; import java.util.Map; import java.util.Properties; import static java.nio.charset.StandardCharsets.UTF_8; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertNotNull; import static junit.framework.TestCase.assertTrue; import static org.apache.commons.csv.CSVFormat.DEFAULT; import static org.apache.commons.csv.CSVFormat.EXCEL; public class CommonsCSVToolTest { private static final String ANY_KEY = "C71"; private static final String ANY_TEMPLATE = "info.ftl"; private static final String CONTRACT_ID = "contract_id"; private static final int CONTRACT_ID_IDX = 0; private static final File BOM_CSV = new File("./site/sample/csv/excel-export-utf8.csv"); private static final File TEST_CSV = new File("./site/sample/csv/contract.csv"); @Test public void shallParseCvsFile() throws IOException { try (CSVParser parser = commonsCsvTool().parse(document(), DEFAULT.withHeader())) { assertNotNull(parser); assertEquals(32, parser.getHeaderMap().size()); assertEquals(22, parser.getRecords().size()); } } @Test public void shallParseCvsString() throws IOException { try (CSVParser parser = commonsCsvTool().parse(document().getText(), DEFAULT.withHeader())) { assertNotNull(parser); assertEquals(32, parser.getHeaderMap().size()); assertEquals(22, parser.getRecords().size()); } } @Test public void shallGetKeysFromCsvRecords() throws IOException { final CommonsCSVTool commonsCsvTool = commonsCsvTool(); final List<String> keys; try (CSVParser parser = commonsCsvTool.parse(document(), DEFAULT.withHeader())) { keys = commonsCsvTool.toKeys(parser.getRecords(), CONTRACT_ID); } assertEquals(7, keys.size()); assertEquals(7, keys.size()); assertEquals("C71", keys.get(0)); assertEquals("C72", keys.get(1)); assertEquals("C73", keys.get(2)); assertEquals("C74", keys.get(3)); assertEquals("C75", keys.get(4)); assertEquals("C76", keys.get(5)); assertEquals("C78", keys.get(6)); } @Test public void shallCreateMapFromCsvRecords() throws IOException { final CommonsCSVTool commonsCsvTool = commonsCsvTool(); final Map<String, CSVRecord> map; try (CSVParser parser = commonsCsvTool.parse(document(), DEFAULT.withHeader())) { map = commonsCsvTool.toMap(parser.getRecords(), CONTRACT_ID); } assertEquals(7, map.size()); assertEquals(ANY_KEY, map.get(ANY_KEY).get(CONTRACT_ID_IDX)); } @Test public void shallCreateMultiMapFromCsvRecords() throws IOException { final CommonsCSVTool commonsCsvTool = commonsCsvTool(); final Map<String, List<CSVRecord>> map; try (CSVParser parser = commonsCsvTool.parse(document(), DEFAULT.withHeader())) { map = commonsCsvTool.toMultiMap(parser.getRecords(), CONTRACT_ID); } assertEquals(7, map.size()); assertEquals(ANY_KEY, map.get(ANY_KEY).get(0).get(CONTRACT_ID_IDX)); } @Test public void shallPrintCsvRecords() throws IOException { final CommonsCSVTool commonsCsvTool = commonsCsvTool(); final CSVFormat cvsFormat = DEFAULT.withHeader(); try (CSVParser parser = commonsCsvTool.parse(document(), cvsFormat)) { try (CSVPrinter printer = commonsCsvTool.printer(cvsFormat)) { printer.printRecord(parser.getHeaderMap()); } } assertTrue(commonsCsvTool.getWriter().toString().contains(CONTRACT_ID)); } @Test public void shallStripBomFromCsvFile() throws IOException { try (CSVParser parser = commonsCsvTool().parse(document(BOM_CSV), EXCEL.withHeader().withDelimiter(';'))) { assertEquals("Text", parser.getHeaderNames().get(0)); } } @Test public void shallConvertToCsvDelimiter() { assertEquals(' ', commonsCsvTool().toDelimiter("space")); assertEquals(' ', commonsCsvTool().toDelimiter("SPACE")); assertEquals('^', commonsCsvTool().toDelimiter("^")); } private Document document() { return document(TEST_CSV); } private Document document(File file) { return DocumentFactory.create(file, UTF_8); } private CommonsCSVTool commonsCsvTool() { return new CommonsCSVTool(settings()); } private Map<String, Object> settings() { return Settings.builder() .setTemplateName(ANY_TEMPLATE) .setConfiguration(new Properties()) .setWriter(new StringWriter()) .build() .toMap(); } }
37.353659
115
0.679889
d64462e86eea69836741d3df50334baa9ef9f1b2
1,793
/* * Copyright 2013 Robotoworks Limited * 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.specapi.android.net; import java.io.IOException; import java.util.List; import org.specapi.android.internal.util.JsonWriter; /** * <p>Uses the JsonWriter to write (serialize) the given entity T.</p> * * @param <T> */ public abstract class JsonEntityWriter<T> { private JsonEntityWriterProvider mProvider; /** * <p>A writer provider which provides other writers * that may be needed when writing entities that the entity for this * writer references, for example in object graphs.</p> */ public JsonEntityWriterProvider getProvider() { return mProvider; } public JsonEntityWriter(JsonEntityWriterProvider provider) { mProvider = provider; } /** * <p>Writes the given entity to the writer</p> * @param writer The writer to write the entity to * @param entity The entity to write to the writer */ public abstract void write(JsonWriter writer, T entity) throws IOException; /** * <p>Writes the given list of entities to the writer</p> * @param writer The writer to write the entities to * @param entities The entities to write to the writer */ public abstract void writeList(JsonWriter writer, List<T> entities) throws IOException; }
31.45614
88
0.737869
20002601d610c0776858e0aec6483853a871e543
2,591
package org.im97mori.rbt.ble.advertising; import android.os.Parcel; import android.os.Parcelable; import androidx.annotation.NonNull; import org.im97mori.ble.BLEUtils; import org.im97mori.ble.ByteArrayCreater; import org.im97mori.ble.advertising.ManufacturerSpecificData; import org.im97mori.rbt.RbtConstants; /** * 3.5 Serial number */ public class SerialNumber implements RbtPacket, Parcelable { /** * @see ByteArrayCreater */ public static final ByteArrayCreater<SerialNumber> CREATOR = new ByteArrayCreater<SerialNumber>() { /** * {@inheritDoc} */ @Override @NonNull public SerialNumber createFromParcel(@NonNull Parcel in) { return new SerialNumber(in); } /** * {@inheritDoc} */ @Override @NonNull public SerialNumber[] newArray(int size) { return new SerialNumber[size]; } /** * {@inheritDoc} */ @NonNull @Override public SerialNumber createFromByteArray(@NonNull byte[] values) { return new SerialNumber(values); } }; /** * Serial number */ private final String mSerialNumber; /** * Memory index (Latest) */ private final long mMemoryIndex; /** * Constructor for SerialNumber * * @param data byte array from {@link ManufacturerSpecificData#getManufacturerSpecificData()} */ public SerialNumber(@NonNull byte[] data) { mSerialNumber = new String(data, 1, 10); mMemoryIndex = BLEUtils.createUInt32(data, 11); } /** * Constructor from {@link Parcel} * * @param in Parcel */ private SerialNumber(@NonNull Parcel in) { mSerialNumber = in.readString(); mMemoryIndex = in.readLong(); } /** * {@inheritDoc} */ @Override public int describeContents() { return 0; } /** * {@inheritDoc} */ @Override public void writeToParcel(@NonNull Parcel dest, int flags) { dest.writeString(mSerialNumber); dest.writeLong(mMemoryIndex); } /** * {@inheritDoc} */ @Override public int getDataType() { return RbtConstants.RbtAdvertisingDataType.DATA_TYPE_SERIAL_NUMBER; } /** * @return Serial number */ public String getSerialNumber() { return mSerialNumber; } /** * @return Memory index (Latest) */ public long getMemoryIndex() { return mMemoryIndex; } }
21.237705
103
0.588962
fcffe516545e249f53642efa18d11caed8400a87
994
package questions.leetcode113; import questions.dataStructure.TreeNode; import java.util.ArrayList; import java.util.List; public class PathSum2 { private List<List<Integer>> res; public List<List<Integer>> pathSum(TreeNode root, int sum) { res = new ArrayList<>(); if (root == null) return res; List<Integer> path = new ArrayList<>(); buildPath(path, sum, 0, root); return res; } private void buildPath(List<Integer> path, int sum, int curr, TreeNode node){ curr += node.val; path.add(node.val); if (node.left == null && node.right == null){ if (sum == curr) res.add(new ArrayList<>(path)); } if (node.left != null){ buildPath(path, sum, curr, node.left); } if (node.right != null){ buildPath(path, sum, curr, node.right); } path.remove(path.size()-1); curr -= node.val; return; } }
24.85
81
0.55332
ec52eba1556161bca751649a5c6053aa929f1d75
19,588
/* -*- mode: Java; c-basic-offset: 2; indent-tabs-mode: nil; coding: utf-8-unix -*- * * Copyright © 2019 microBean™. * * 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.microbean.jaxrs.cdi; import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import javax.enterprise.context.ContextNotActiveException; import javax.enterprise.context.Dependent; import javax.enterprise.context.spi.AlterableContext; import javax.enterprise.context.spi.Context; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.event.Observes; import javax.enterprise.inject.Any; import javax.enterprise.inject.spi.AfterBeanDiscovery; import javax.enterprise.inject.spi.AnnotatedMethod; import javax.enterprise.inject.spi.AnnotatedType; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanAttributes; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.Extension; import javax.enterprise.inject.spi.ProcessAnnotatedType; import javax.enterprise.inject.spi.ProcessBeanAttributes; import javax.enterprise.inject.spi.WithAnnotations; import javax.enterprise.inject.spi.configurator.BeanConfigurator; import javax.enterprise.util.AnnotationLiteral; import javax.inject.Qualifier; import javax.inject.Singleton; import javax.ws.rs.HttpMethod; import javax.ws.rs.Path; import javax.ws.rs.core.Application; import javax.ws.rs.ApplicationPath; /** * An {@link Extension} that makes {@link Application}s and resource * classes available as CDI beans. * * @author <a href="https://about.me/lairdnelson" * target="_parent">Laird Nelson</a> */ public class JaxRsExtension implements Extension { private final Set<Class<?>> potentialResourceClasses; private final Set<Class<?>> potentialProviderClasses; private final Map<Class<?>, BeanAttributes<?>> resourceBeans; private final Map<Class<?>, BeanAttributes<?>> providerBeans; private final Set<Set<Annotation>> qualifiers; /** * Creates a new {@link JaxRsExtension}. */ public JaxRsExtension() { super(); this.potentialResourceClasses = new HashSet<>(); this.potentialProviderClasses = new HashSet<>(); this.resourceBeans = new HashMap<>(); this.providerBeans = new HashMap<>(); this.qualifiers = new HashSet<>(); } private final <T> void discoverRootResourceClasses(@Observes @WithAnnotations({ Path.class }) final ProcessAnnotatedType<T> event) { Objects.requireNonNull(event); final AnnotatedType<T> annotatedType = event.getAnnotatedType(); if (annotatedType != null && isRootResourceClass(annotatedType)) { final Class<T> javaClass = annotatedType.getJavaClass(); if (javaClass != null) { this.potentialResourceClasses.add(javaClass); } } } private final <T> void discoverProviderClasses(@Observes @WithAnnotations({ javax.ws.rs.ext.Provider.class }) final ProcessAnnotatedType<T> event) { Objects.requireNonNull(event); final AnnotatedType<T> annotatedType = event.getAnnotatedType(); if (annotatedType != null) { final Class<T> javaClass = annotatedType.getJavaClass(); if (javaClass != null) { this.potentialProviderClasses.add(javaClass); } } } private final <T> void forAllBeanAttributes(@Observes final ProcessBeanAttributes<T> event) { Objects.requireNonNull(event); final BeanAttributes<T> beanAttributes = event.getBeanAttributes(); if (beanAttributes != null) { final Set<Type> beanTypes = beanAttributes.getTypes(); if (beanTypes != null && !beanTypes.isEmpty()) { for (final Type beanType : beanTypes) { final Class<?> beanTypeClass; if (beanType instanceof Class) { beanTypeClass = (Class<?>)beanType; } else if (beanType instanceof ParameterizedType) { final Object rawBeanType = ((ParameterizedType)beanType).getRawType(); if (rawBeanType instanceof Class) { beanTypeClass = (Class<?>) rawBeanType; } else { beanTypeClass = null; } } else { beanTypeClass = null; } if (beanTypeClass != null) { if (Application.class.isAssignableFrom(beanTypeClass)) { this.qualifiers.add(beanAttributes.getQualifiers()); // yes, add the set as an element, not the set's elements } // Edge case: it could be an application whose methods are // annotated with @Path, so it could still be a resource // class. That's why this isn't an else if. if (this.potentialResourceClasses.remove(beanTypeClass)) { // This bean has a beanType that we previously // identified as a JAX-RS resource. event.configureBeanAttributes().addQualifiers(ResourceClass.Literal.INSTANCE); this.resourceBeans.put(beanTypeClass, beanAttributes); } if (this.potentialProviderClasses.remove(beanTypeClass)) { // This bean has a beanType that we previously // identified as a Provider class. this.providerBeans.put(beanTypeClass, beanAttributes); } } } } } } /** * Returns an {@linkplain Collections#unmodifiableSet(Set) * unmodifiable <code>Set</code>} of {@link Set}s of {@linkplain * Qualifier qualifier annotations} that have been found annotating * {@link Application}s. * * <p>This method never returns {@code null}.</p> * * @return a non-{@code null}, {@linkplain Collections#unmodifiableSet(Set) * unmodifiable <code>Set</code>} of {@link Set}s of {@linkplain * Qualifier qualifier annotations} that have been found annotating * {@link Application}s */ public final Set<Set<Annotation>> getAllApplicationQualifiers() { return Collections.unmodifiableSet(this.qualifiers); } private final void afterNonSyntheticBeansAreEnabled(@Observes final AfterBeanDiscovery event, final BeanManager beanManager) { Objects.requireNonNull(event); Objects.requireNonNull(beanManager); final Set<Bean<?>> applicationBeans = beanManager.getBeans(Application.class, Any.Literal.INSTANCE); if (applicationBeans != null && !applicationBeans.isEmpty()) { for (final Bean<?> bean : applicationBeans) { @SuppressWarnings("unchecked") final Bean<Application> applicationBean = (Bean<Application>)bean; final CreationalContext<Application> cc = beanManager.createCreationalContext(applicationBean); final Class<? extends Annotation> applicationScope = applicationBean.getScope(); assert applicationScope != null; final Context context = beanManager.getContext(applicationScope); assert context != null; final AlterableContext alterableContext = context instanceof AlterableContext ? (AlterableContext)context : null; Application application = null; try { if (alterableContext == null) { application = applicationBean.create(cc); } else { try { application = alterableContext.get(applicationBean, cc); } catch (final ContextNotActiveException ok) { application = applicationBean.create(cc); } } if (application != null) { final Set<Annotation> applicationQualifiers = applicationBean.getQualifiers(); final ApplicationPath applicationPath = application.getClass().getAnnotation(ApplicationPath.class); if (applicationPath != null) { event.addBean() .types(ApplicationPath.class) .scope(Singleton.class) .qualifiers(applicationQualifiers) .createWith(ignored -> applicationPath); } final Set<Class<?>> classes = application.getClasses(); if (classes != null && !classes.isEmpty()) { for (final Class<?> cls : classes) { final Object resourceBean = this.resourceBeans.remove(cls); final Object providerBean = this.providerBeans.remove(cls); if (resourceBean == null && providerBean == null) { final BeanConfigurator<?> bc = event.addBean() .scope(Dependent.class) // by default; possibly overridden by read() .read(beanManager.createAnnotatedType(cls)) .addQualifiers(applicationQualifiers) .addQualifiers(ResourceClass.Literal.INSTANCE); } } } // Deliberately don't try to deal with getSingletons(). } } finally { try { if (application != null) { if (alterableContext == null) { applicationBean.destroy(application, cc); } else { try { alterableContext.destroy(applicationBean); } catch (final UnsupportedOperationException ok) { } } } } finally { cc.release(); } } } } // Any potentialResourceClasses left over here are annotated // types we discovered, but for whatever reason were not made // into beans. Maybe they were vetoed. this.potentialResourceClasses.clear(); // Any potentialProviderClasses left over here are annotated // types we discovered, but for whatever reason were not made // into beans. Maybe they were vetoed. this.potentialProviderClasses.clear(); // OK, when we get here, if there are any resource beans left // lying around they went "unclaimed". Build a synthetic // Application for them. if (!this.resourceBeans.isEmpty()) { final Set<Entry<Class<?>, BeanAttributes<?>>> resourceBeansEntrySet = this.resourceBeans.entrySet(); assert resourceBeansEntrySet != null; assert !resourceBeansEntrySet.isEmpty(); final Map<Set<Annotation>, Set<Class<?>>> resourceClassesByQualifiers = new HashMap<>(); for (final Entry<Class<?>, BeanAttributes<?>> entry : resourceBeansEntrySet) { assert entry != null; final Set<Annotation> qualifiers = entry.getValue().getQualifiers(); Set<Class<?>> resourceClasses = resourceClassesByQualifiers.get(qualifiers); if (resourceClasses == null) { resourceClasses = new HashSet<>(); resourceClassesByQualifiers.put(qualifiers, resourceClasses); } resourceClasses.add(entry.getKey()); } final Set<Entry<Set<Annotation>, Set<Class<?>>>> entrySet = resourceClassesByQualifiers.entrySet(); assert entrySet != null; assert !entrySet.isEmpty(); for (final Entry<Set<Annotation>, Set<Class<?>>> entry : entrySet) { assert entry != null; final Set<Annotation> resourceBeanQualifiers = entry.getKey(); final Set<Class<?>> resourceClasses = entry.getValue(); assert resourceClasses != null; assert !resourceClasses.isEmpty(); final Set<Class<?>> allClasses; if (this.providerBeans.isEmpty()) { allClasses = resourceClasses; } else { allClasses = new HashSet<>(resourceClasses); final Set<Entry<Class<?>, BeanAttributes<?>>> providerBeansEntrySet = this.providerBeans.entrySet(); assert providerBeansEntrySet != null; assert !providerBeansEntrySet.isEmpty(); final Iterator<Entry<Class<?>, BeanAttributes<?>>> providerBeansIterator = providerBeansEntrySet.iterator(); assert providerBeansIterator != null; while (providerBeansIterator.hasNext()) { final Entry<Class<?>, BeanAttributes<?>> providerBeansEntry = providerBeansIterator.next(); assert providerBeansEntry != null; final Set<Annotation> providerBeanQualifiers = providerBeansEntry.getValue().getQualifiers(); boolean match = false; if (resourceBeanQualifiers == null) { if (providerBeanQualifiers == null) { match = true; } } else if (resourceBeanQualifiers.equals(providerBeanQualifiers)) { match = true; } if (match) { allClasses.add(providerBeansEntry.getKey()); providerBeansIterator.remove(); } } } assert resourceBeanQualifiers != null; assert !resourceBeanQualifiers.isEmpty(); final Set<Annotation> syntheticApplicationQualifiers = new HashSet<>(resourceBeanQualifiers); syntheticApplicationQualifiers.remove(ResourceClass.Literal.INSTANCE); event.addBean() .addTransitiveTypeClosure(SyntheticApplication.class) .scope(Singleton.class) .addQualifiers(syntheticApplicationQualifiers) .createWith(cc -> new SyntheticApplication(allClasses)); this.qualifiers.add(syntheticApplicationQualifiers); } this.resourceBeans.clear(); } if (!this.providerBeans.isEmpty()) { // TODO: we found some provider class beans but never associated // them with any application. This would only happen if they // were not qualified with qualifiers that also qualified // unclaimed resource beans. That would be odd. Either we // should throw a deployment error or just ignore them. } this.providerBeans.clear(); } private static final <T> boolean isRootResourceClass(final AnnotatedType<T> type) { return type != null && type.isAnnotationPresent(Path.class); } private static final <T> boolean isResourceClass(final AnnotatedType<T> type) { // Section 3.1: "Resource classes are POJOs that have at least one // method annotated with @Path or a request method designator." // // Not sure whether POJO here means "concrete class" or not. boolean returnValue = false; if (type != null) { final Class<?> javaClass = type.getJavaClass(); if (javaClass != null && !javaClass.isInterface() && !Modifier.isAbstract(javaClass.getModifiers())) { final Set<AnnotatedMethod<? super T>> methods = type.getMethods(); if (methods != null && !methods.isEmpty()) { METHOD_LOOP: for (final AnnotatedMethod<? super T> method : methods) { final Set<Annotation> annotations = method.getAnnotations(); if (annotations != null && !annotations.isEmpty()) { for (final Annotation annotation : annotations) { if (annotation != null) { final Class<?> annotationType = annotation.annotationType(); if (Path.class.isAssignableFrom(annotationType)) { returnValue = true; break METHOD_LOOP; } else { final Annotation[] metaAnnotations = annotationType.getAnnotations(); if (metaAnnotations != null && metaAnnotations.length > 0) { for (final Annotation metaAnnotation : metaAnnotations) { if (metaAnnotation != null) { final Class<?> metaAnnotationType = metaAnnotation.annotationType(); if (HttpMethod.class.isAssignableFrom(metaAnnotationType)) { returnValue = true; break METHOD_LOOP; } } } } } } } } } } } } return returnValue; } /** * An {@link Application} that has been synthesized out of resource * classes found on the classpath that have not otherwise been * {@linkplain Application#getClasses() claimed} by other {@link * Application} instances. * * @author <a href="https://about.me/lairdnelson" * target="_parent">Laird Nelson</a> * * @see Application */ public static final class SyntheticApplication extends Application { private final Set<Class<?>> classes; SyntheticApplication(final Set<Class<?>> classes) { super(); if (classes == null || classes.isEmpty()) { this.classes = Collections.emptySet(); } else { this.classes = Collections.unmodifiableSet(classes); } } /** * Returns an {@linkplain Collections#unmodifiableSet(Set) * unmodifiable <code>Set</code>} of resource and provider * classes. * * <p>This method never returns {@code null}.</p> * * @return a non-{@code null}, {@linkplain * Collections#unmodifiableSet(Set) unmodifiable <code>Set</code>} * of resource and provider classes. */ @Override public final Set<Class<?>> getClasses() { return this.classes; } } /** * A {@link Qualifier} annotation indicating that a {@link * BeanAttributes} implementation is a JAX-RS resource class. * * <p>This annotation cannot be applied manually to any Java element * but can be used as an input to the {@link * BeanManager#getBeans(Type, Annotation...)} method.</p> * * @author <a href="https://about.me/lairdnelson" * target="_parent">Laird Nelson</a> */ @Documented @Inherited @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ }) public @interface ResourceClass { /** * A {@link ResourceClass} implementation. * * @author <a href="https://about.me/lairdnelson" * target="_parent">Laird Nelson</a> * * @see #INSTANCE */ public static final class Literal extends AnnotationLiteral<ResourceClass> implements ResourceClass { private static final long serialVersionUID = 1L; /** * The sole instance of this class. * * <p>This field is never {@code null}.</p> */ public static final ResourceClass INSTANCE = new Literal(); } } }
39.651822
124
0.629926
ddf893acd6541cfb0153c2769d303715aea1264f
3,606
package com.huaweicloud.sdk.bcs.v2.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Consumer; /** DmsKafkaInfo */ public class DmsKafkaInfo { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "addr") private List<String> addr = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "order_fade_enable") private Boolean orderFadeEnable; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "order_fade_cache") private Long orderFadeCache; public DmsKafkaInfo withAddr(List<String> addr) { this.addr = addr; return this; } public DmsKafkaInfo addAddrItem(String addrItem) { if (this.addr == null) { this.addr = new ArrayList<>(); } this.addr.add(addrItem); return this; } public DmsKafkaInfo withAddr(Consumer<List<String>> addrSetter) { if (this.addr == null) { this.addr = new ArrayList<>(); } addrSetter.accept(this.addr); return this; } /** Kafka连接地址 * * @return addr */ public List<String> getAddr() { return addr; } public void setAddr(List<String> addr) { this.addr = addr; } public DmsKafkaInfo withOrderFadeEnable(Boolean orderFadeEnable) { this.orderFadeEnable = orderFadeEnable; return this; } /** Kafka模式下,是否开启共识节点老化 * * @return orderFadeEnable */ public Boolean getOrderFadeEnable() { return orderFadeEnable; } public void setOrderFadeEnable(Boolean orderFadeEnable) { this.orderFadeEnable = orderFadeEnable; } public DmsKafkaInfo withOrderFadeCache(Long orderFadeCache) { this.orderFadeCache = orderFadeCache; return this; } /** Kafka模式下,开启共识节点后的老化阈值 * * @return orderFadeCache */ public Long getOrderFadeCache() { return orderFadeCache; } public void setOrderFadeCache(Long orderFadeCache) { this.orderFadeCache = orderFadeCache; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DmsKafkaInfo dmsKafkaInfo = (DmsKafkaInfo) o; return Objects.equals(this.addr, dmsKafkaInfo.addr) && Objects.equals(this.orderFadeEnable, dmsKafkaInfo.orderFadeEnable) && Objects.equals(this.orderFadeCache, dmsKafkaInfo.orderFadeCache); } @Override public int hashCode() { return Objects.hash(addr, orderFadeEnable, orderFadeCache); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DmsKafkaInfo {\n"); sb.append(" addr: ").append(toIndentedString(addr)).append("\n"); sb.append(" orderFadeEnable: ").append(toIndentedString(orderFadeEnable)).append("\n"); sb.append(" orderFadeCache: ").append(toIndentedString(orderFadeCache)).append("\n"); sb.append("}"); return sb.toString(); } /** Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
27.318182
106
0.628674
ddb53ed489f463d635b45fc1b1794cd113851234
1,557
/* * Copyright 2021-2022 Aklivity Inc * * Licensed under the Aklivity Community License (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.aklivity.io/aklivity-community-license/ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package io.aklivity.zilla.runtime.binding.http.kafka.internal.config; import java.util.List; import org.agrona.DirectBuffer; import io.aklivity.zilla.runtime.binding.http.kafka.internal.types.KafkaFilterFW; public final class HttpKafkaWithFetchFilterResult { public final DirectBuffer key; public final List<HttpKafkaWithFetchFilterHeaderResult> headers; HttpKafkaWithFetchFilterResult( DirectBuffer key, List<HttpKafkaWithFetchFilterHeaderResult> headers) { this.key = key; this.headers = headers; } public void filter( KafkaFilterFW.Builder builder) { if (key != null) { builder.conditionsItem(c -> c.key(k -> k.length(key.capacity()) .value(key, 0, key.capacity()))); } if (headers != null) { headers.forEach(h -> builder.conditionsItem(h::condition)); } } }
30.529412
85
0.669878
882008899b6cc326d061e4600f988f1f08c9d3fa
2,039
package org.apache.http.message; import java.io.Serializable; import org.apache.http.FormattedHeader; import org.apache.http.HeaderElement; import org.apache.http.ParseException; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.util.Args; import org.apache.http.util.CharArrayBuffer; @NotThreadSafe public class BufferedHeader implements FormattedHeader, Cloneable, Serializable { private static final long serialVersionUID = -2768352615787625448L; private final CharArrayBuffer buffer; private final String name; private final int valuePos; public BufferedHeader(CharArrayBuffer charArrayBuffer) throws ParseException { Args.notNull(charArrayBuffer, "Char array buffer"); int indexOf = charArrayBuffer.indexOf(58); if (indexOf == -1) { throw new ParseException("Invalid header: " + charArrayBuffer.toString()); } String substringTrimmed = charArrayBuffer.substringTrimmed(0, indexOf); if (substringTrimmed.length() == 0) { throw new ParseException("Invalid header: " + charArrayBuffer.toString()); } this.buffer = charArrayBuffer; this.name = substringTrimmed; this.valuePos = indexOf + 1; } public Object clone() throws CloneNotSupportedException { return super.clone(); } public CharArrayBuffer getBuffer() { return this.buffer; } public HeaderElement[] getElements() throws ParseException { ParserCursor parserCursor = new ParserCursor(0, this.buffer.length()); parserCursor.updatePos(this.valuePos); return BasicHeaderValueParser.INSTANCE.parseElements(this.buffer, parserCursor); } public String getName() { return this.name; } public String getValue() { return this.buffer.substringTrimmed(this.valuePos, this.buffer.length()); } public int getValuePos() { return this.valuePos; } public String toString() { return this.buffer.toString(); } }
32.365079
88
0.695929
4be9d6b50438501264fdb802de39fce7268b9f0c
216
package net.fabricmc.example; import net.fabricmc.example.items.FabricItem; import net.minecraft.item.BlockItem; public class Items { public static FabricItem FABRIC_ITEM; public static BlockItem BARREL; }
21.6
45
0.791667
421cdb8714e0651525ca95f3261cc9bce920fd4f
628
package com.java.study.answer.zuo.emiddle.class08; public class Code01_Self_Crossing { public static boolean isSelfCrossing(int[] x) { if (x == null || x.length < 4) { return false; } if ((x.length > 3 && x[2] <= x[0] && x[3] >= x[1]) || (x.length > 4 && ((x[3] <= x[1] && x[4] >= x[2]) || (x[3] == x[1] && x[0] + x[4] == x[2])))) { return true; } for (int i = 5; i < x.length; i++) { if (x[i - 1] <= x[i - 3] && ((x[i] >= x[i - 2]) || (x[i - 2] >= x[i - 4] && x[i - 5] + x[i - 1] >= x[i - 3] && x[i - 4] + x[i] >= x[i - 2]))) { return true; } } return false; } }
24.153846
80
0.420382
fa71eeee59cb3777b6b0f89f97a17751ccaa3783
2,174
package tlb.twist; import tlb.factory.TlbFactory; import tlb.service.Server; import tlb.utils.SystemEnvironment; import tlb.utils.XmlUtil; import tlb.utils.FileUtil; import org.apache.tools.ant.Task; import org.apache.tools.ant.BuildException; import org.apache.commons.io.FileUtils; import org.dom4j.Element; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; /** * @understands task to publish the time taken to execute scenarios */ public class PublishScenarioExecutionTime extends Task { private String reportsDir; private Server server; private static final String XML_REPORT_PATH = "/xml"; public PublishScenarioExecutionTime(Server server) { this.server = server; } public PublishScenarioExecutionTime() { this(new SystemEnvironment()); } public PublishScenarioExecutionTime(SystemEnvironment systemEnvironment) { this(TlbFactory.getTalkToService(systemEnvironment)); } public void setReportsDir(String reportsDir) { this.reportsDir = reportsDir; } @Override public String getTaskName() { return "publishTestTime"; } @Override @SuppressWarnings("unchecked") public void execute() throws BuildException { Iterator<File> reports = FileUtils.iterateFiles(new File(reportsDir + XML_REPORT_PATH), null, false); List<File> reportFiles = FileUtil.toFileList(reports); server.publishSubsetSize(reportFiles.size()); for (File report : reportFiles) { try { Element element = XmlUtil.domFor(FileUtils.readFileToString(report)); Element testCase = (Element) element.selectSingleNode("//testcase"); server.testClassTime(testCase.attribute("name").getText(), toSecond(testCase)); } catch (IOException e) { throw new RuntimeException("Could not read the twist report: " + report.getName(), e); } } } private long toSecond(Element testCase) { double time = Double.parseDouble(testCase.attribute("time").getText()); return (long)(time * 1000); } }
31.507246
109
0.687213
03b8bc38e3ff50b7240e45350cdd7aebca66dcac
2,208
package mcjty.rftoolsbase.modules.worldgen; import mcjty.rftoolsbase.RFToolsBase; import mcjty.rftoolsbase.modules.worldgen.blocks.DimensionalShardBlock; import mcjty.rftoolsbase.modules.worldgen.blocks.DimensionalShardBlock.OreType; import net.minecraft.block.Block; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import static mcjty.rftoolsbase.RFToolsBase.MODID; public class WorldGenSetup { public static final DeferredRegister<Item> ITEMS = new DeferredRegister<>(ForgeRegistries.ITEMS, MODID); public static final DeferredRegister<Block> BLOCKS = new DeferredRegister<>(ForgeRegistries.BLOCKS, MODID); public static void register() { BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus()); ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus()); } public static final RegistryObject<Block> DIMENSIONAL_SHARD_OVERWORLD = BLOCKS.register("dimensionalshard_overworld", () -> new DimensionalShardBlock(OreType.ORE_OVERWORLD)); public static final RegistryObject<Item> DIMENSIONAL_SHARD_OVERWORLD_ITEM = ITEMS.register("dimensionalshard_overworld", () -> new BlockItem(DIMENSIONAL_SHARD_OVERWORLD.get(), RFToolsBase.createStandardProperties())); public static final RegistryObject<Block> DIMENSIONAL_SHARD_NETHER = BLOCKS.register("dimensionalshard_nether", () -> new DimensionalShardBlock(OreType.ORE_NETHER)); public static final RegistryObject<Item> DIMENSIONAL_SHARD_NETHER_ITEM = ITEMS.register("dimensionalshard_nether", () -> new BlockItem(DIMENSIONAL_SHARD_NETHER.get(), RFToolsBase.createStandardProperties())); public static final RegistryObject<Block> DIMENSIONAL_SHARD_END = BLOCKS.register("dimensionalshard_end", () -> new DimensionalShardBlock(OreType.ORE_END)); public static final RegistryObject<Item> DIMENSIONAL_SHARD_END_ITEM = ITEMS.register("dimensionalshard_end", () -> new BlockItem(DIMENSIONAL_SHARD_END.get(), RFToolsBase.createStandardProperties())); }
63.085714
221
0.815217
33c19f74d5bb704d3b13103d93f109b000439e9f
346
package de.cxp.ocs.smartsuggest.spi; public class DummySuggestDataProvider implements SuggestDataProvider { @Override public boolean hasData(String indexName) { return false; } @Override public long getLastDataModTime(String indexName) { return -1; } @Override public SuggestData loadData(String indexName) { return null; } }
16.47619
70
0.763006
da689944025e8418503013953de70571b02f19b1
710
package cn.zhoujianfeng.baidumap; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Set extends Activity { private Button bt_back; @Override public void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.set); bt_back = findViewById(R.id.bt_back); bt_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Set.this,Search.class); startActivity(intent); } }); } }
25.357143
66
0.653521
e79856d3eeedab912f1a837c989d8809637eef4e
368
package com.platform.aix.cmd.biz.baseconf.cmd40910; import lombok.Data; import java.util.Date; /** * 角色组功能关联 * * @author: Advance * @date: 2018/8/1 * @description: */ @Data public class Cmd40910Resp { private String rolegrpid; private String functionidlist; private Integer sysflag; private Date createdtime; private Date modifiedtime; }
16
51
0.706522
878499157a2602997e9c9862becbb3d3f32c2ed4
965
package model; /** * TtTask (Time triggered Task) represents an infinite set of time triggered jobs. */ public class TtTask extends Task { private final int releaseTime; private final int executionTime; /** * See Task class for other parameters * @param releaseTime job release time relative to the period * @param executionTime execution time of each job */ public TtTask(int id, int period, int deadline, int releaseTime, int executionTime) { super(id, period, deadline); this.releaseTime = releaseTime; this.executionTime = executionTime; } public TtJob getNthRepetition(int n) { return new TtJob(getId(), n, this.getPeriod(), getDeadline() + n*getPeriod(), getReleaseTime() + n*getPeriod(), getExecutionTime()); } public int getReleaseTime() { return releaseTime; } public int getExecutionTime() { return executionTime; } }
26.805556
89
0.653886
dbaa9b80db7f7050047ccdcd8c54d635ac26a36d
1,191
package com.moringa.gohire; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ @BindView(R.id.viewAvailableCarsButton) Button mViewAvailableCarsButton; @BindView(R.id.textViewHeader) TextView mTextViewHeader; @BindView(R.id.nameEditText) EditText mNameEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); mViewAvailableCarsButton.setOnClickListener(this); } @Override public void onClick(View v) { if(v==mViewAvailableCarsButton){ String name = mNameEditText.getText().toString(); Intent intent= new Intent(MainActivity.this,AvailableCar_activity.class); intent.putExtra("name",name); startActivity(intent); } } }
31.342105
85
0.738875
4746d7441f97c3d80c946b21f443721698c79370
276
package io.github.yexiaoxiaogo.DAOSelect; import java.util.List; public interface WebsitesDao { public List<Websites> getAllWebsties(); public Websites getWebsites(int id); public void updateWebsites(Websites websites); public void deleteWebsites(Websites websites); }
23
47
0.804348
86b2aced7301e821fe4700f008f0491e54c65e0e
3,572
/* * Copyright 2011-2017 Amazon.com, Inc. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.codegen.emitters.tasks; import com.amazonaws.codegen.emitters.CodeWriter; import com.amazonaws.codegen.emitters.FreemarkerGeneratorTask; import com.amazonaws.codegen.emitters.GeneratorTask; import com.amazonaws.codegen.emitters.GeneratorTaskParams; import com.amazonaws.codegen.internal.Utils; import com.amazonaws.codegen.model.config.customization.AuthPolicyActions; import com.amazonaws.codegen.model.intermediate.Metadata; import com.amazonaws.util.ImmutableMapParameter; import java.util.Collections; import java.util.List; import java.util.Map; public class PolicyActionEnumGeneratorTasks extends BaseGeneratorTasks { private final String policyEnumClassDir; private final AuthPolicyActions policyActions; private final Metadata metadata; public PolicyActionEnumGeneratorTasks(GeneratorTaskParams dependencies) { super(dependencies); this.policyEnumClassDir = dependencies.getPathProvider().getPolicyEnumDirectory(); this.policyActions = model.getCustomizationConfig().getAuthPolicyActions(); this.metadata = model.getMetadata(); } @Override protected boolean hasTasks() { final AuthPolicyActions policyActions = model.getCustomizationConfig().getAuthPolicyActions(); return policyActions == null || !policyActions.isSkip(); } @Override protected List<GeneratorTask> createTasks() throws Exception { info("Emitting policy action enum class"); String serviceName = getPolicyActionServiceName(); String actionPrefix = getEnumActionPrefix(); Map<String, Object> dataModel = ImmutableMapParameter.of( "fileHeader", model.getFileHeader(), "operations", model.getOperations().keySet(), "metadata", model.getMetadata(), "serviceName", serviceName, "actionPrefix", actionPrefix); return Collections.singletonList( new FreemarkerGeneratorTask(new CodeWriter(policyEnumClassDir, serviceName + "Actions"), freemarker.getPolicyActionClassTemplate(), dataModel)); } private String getPolicyActionServiceName() { // This is to support the file naming for exiting/legacy clients. // The files don't follow the standard naming conventions. // To avoid breaking changes, the fileNamePrefix contains the name of // the file to be used. if (policyActions != null && policyActions.getFileNamePrefix() != null) { return Utils.capitialize(policyActions.getFileNamePrefix()); } return Utils.capitialize(metadata.getEndpointPrefix()); } private String getEnumActionPrefix() { if (policyActions != null && policyActions.getActionPrefix() != null) { return policyActions.getActionPrefix(); } return metadata.getEndpointPrefix(); } }
39.252747
104
0.702128
4397fc393efe7f946228b2ed5b69466d75f6f296
376
package com.zyj.spring.importTest; import org.springframework.context.annotation.ImportSelector; import org.springframework.core.type.AnnotationMetadata; public class ImportSelectorTest implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { System.out.println("ImportSelectorTest"); return new String[0]; } }
28.923077
75
0.824468
1bcbfb57df2cd9fb7db0c008c8dac5cb89eed89b
2,314
/** * * Copyright (c) 2018 Fractus IT d.o.o. <http://fractus.io> * */ package io.fractus.osgi.tutorial.service.listener; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; /** * This class implements a simple bundle that utilizes the OSGi * framework's event mechanism to listen for service events. Upon * receiving a service event, it prints out the event's details. **/ public class Activator implements BundleActivator, ServiceListener { /** * Implements BundleActivator.start(). * @param context the framework context for the bundle. **/ public void start(BundleContext bundleContex) throws Exception { bundleContex.addServiceListener(this); System.out.println("Activator " + Activator.class.getName() + " started"); } /** * Implements BundleActivator.stop(). * @param context the framework context for the bundle. **/ public void stop(BundleContext bundleContext) throws Exception { bundleContext.removeServiceListener(this); System.out.println("Activator " + Activator.class.getName() + " stoped"); } /** * Implements ServiceListener.serviceChanged(). * Prints the details of any service event from the framework. * @param serviceEvent the fired service event. **/ public void serviceChanged(ServiceEvent serviceEvent) { System.out.println(Activator.class.getName() + ": serviceEvent: " + serviceEvent); String[] objectClass = (String[])serviceEvent.getServiceReference().getProperty("objectClass"); if (serviceEvent.getType() == ServiceEvent.REGISTERED){ System.out.println("ServiceListener: Service of type " + objectClass[0] + " registered."); }else if (serviceEvent.getType() == ServiceEvent.UNREGISTERING){ System.out.println("ServiceListener: Service of type " + objectClass[0] + " unregistered."); }else if (serviceEvent.getType() == ServiceEvent.MODIFIED){ System.out.println("ServiceListener: Service of type " + objectClass[0] + " modified."); } } }
32.138889
105
0.65471
38e97a3d5e3782986689e8f3fc5d992fa8543354
785
package com.winfun.controller; import com.winfun.entity.pojo.ApiResult; import com.winfun.service.DubboServiceOne; import org.apache.dubbo.config.annotation.DubboReference; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; /** * 测试本地存根 * @author winfun * @date 2021/2/1 10:26 上午 **/ //@RestController public class TestStubController { @DubboReference(lazy = true,check = false,stub = "com.winfun.demo.stub.DubboServiceOneStub") private DubboServiceOne dubboServiceOne; @GetMapping("/stub/{name}") public ApiResult<String> testStub(@PathVariable("name") String name){ return this.dubboServiceOne.sayHello(name); } }
29.074074
96
0.766879
95b03e56e3335373b70a1c766005e592118c0507
80
package incendius.game.players.content.misc; public class WildernessDitch { }
13.333333
44
0.8
3f491bc534151b06920c55c3d411f5cda8e70b0a
434
import java.util.HashMap; public class E10 { public static void main(String args[]) { // create hash map HashMap<Integer, String> newmap = new HashMap<>(); // populate hash map newmap.put(1, "tutorials"); newmap.put(2, "point"); newmap.put(3, "is best"); // checking collection view of the map System.out.println("Collection view is: "+ newmap.values()); } }
25.529412
68
0.582949
a7c55ebd52fb4aaeec752622fc67dec1ffc96fc6
3,580
package com.boringbalcomb.YelpApiCacher.BusinessDetails.model; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "address1", "address2", "address3", "city", "zip_code", "country", "state", "display_address", "cross_streets" }) public class BusinessDetailsLocation { @JsonProperty("address1") private String address1; @JsonProperty("address2") private String address2; @JsonProperty("address3") private String address3; @JsonProperty("city") private String city; @JsonProperty("zip_code") private String zipCode; @JsonProperty("country") private String country; @JsonProperty("state") private String state; @JsonProperty("display_address") private List<String> displayAddress = null; @JsonProperty("cross_streets") private String crossStreets; @JsonProperty("address1") public String getAddress1() { return address1; } @JsonProperty("address1") public void setAddress1(String address1) { this.address1 = address1; } @JsonProperty("address2") public String getAddress2() { return address2; } @JsonProperty("address2") public void setAddress2(String address2) { this.address2 = address2; } @JsonProperty("address3") public String getAddress3() { return address3; } @JsonProperty("address3") public void setAddress3(String address3) { this.address3 = address3; } @JsonProperty("city") public String getCity() { return city; } @JsonProperty("city") public void setCity(String city) { this.city = city; } @JsonProperty("zip_code") public String getZipCode() { return zipCode; } @JsonProperty("zip_code") public void setZipCode(String zipCode) { this.zipCode = zipCode; } @JsonProperty("country") public String getCountry() { return country; } @JsonProperty("country") public void setCountry(String country) { this.country = country; } @JsonProperty("state") public String getState() { return state; } @JsonProperty("state") public void setState(String state) { this.state = state; } @JsonProperty("display_address") public List<String> getDisplayAddress() { return displayAddress; } @JsonProperty("display_address") public void setDisplayAddress(List<String> displayAddress) { this.displayAddress = displayAddress; } @JsonProperty("cross_streets") public String getCrossStreets() { return crossStreets; } @JsonProperty("cross_streets") public void setCrossStreets(String crossStreets) { this.crossStreets = crossStreets; } @Override public String toString() { return "BusinessDetailsLocation{" + "address1='" + address1 + '\'' + ", address2='" + address2 + '\'' + ", address3='" + address3 + '\'' + ", city='" + city + '\'' + ", zipCode='" + zipCode + '\'' + ", country='" + country + '\'' + ", state='" + state + '\'' + ", displayAddress=" + displayAddress + ", crossStreets='" + crossStreets + '\'' + '}'; } }
24.353741
64
0.60838
a49166a050565a23955058dc333d8e775f325e0f
13,657
package com.github.chrisblutz.networking.exceptions; import com.github.chrisblutz.networking.Listenable; import com.github.chrisblutz.networking.properties.Localization; /** * A utility class for creating {@code Exceptions} based on localizations */ public class Errors { public static void threadErrored(String threadName, Listenable listenable, Throwable parent) { NetworkException ex = getThreadErrored(threadName, parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void threadErrored(String threadName, Throwable parent) { threadErrored(threadName, null); } public static NetworkException getThreadErrored(String threadName, Throwable parent) { NetworkException exception = new NetworkException(Localization.getMessage(Localization.THREAD_HAS_ERRORED, threadName) + (parent != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } public static void serverTimedOut(Listenable listenable, Throwable parent) { NetworkException ex = getServerTimedOut(parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void serverTimedOut(Throwable parent) { serverTimedOut(null, parent); } public static NetworkException getServerTimedOut(Throwable parent) { NetworkException exception = new NetworkException(Localization.getMessage(Localization.SERVER_TIMEOUT) + (parent != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } public static void invalidPacketConstructor(Listenable listenable, Throwable parent) { NetworkException ex = getInvalidPacketConstructor(parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void invalidPacketConstructor(Throwable parent) { invalidPacketConstructor(null, parent); } public static NetworkException getInvalidPacketConstructor(Throwable parent) { NetworkException exception = new NetworkException(Localization.getMessage(Localization.PACKET_CONSTRUCTOR) + (parent != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } public static void unreadableData(Listenable listenable, Throwable parent) { NetworkException ex = getUnreadableData(parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void unreadableData(Throwable parent) { unreadableData(null, parent); } public static NetworkException getUnreadableData(Throwable parent) { NetworkException exception = new NetworkException(Localization.getMessage(Localization.UNREADABLE_DATA) + (parent != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } public static void encryptionFailed(Listenable listenable, String type, Throwable parent) { NetworkException ex = getEncryptionFailed(type, parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void encryptionFailed(String type, Throwable parent) { encryptionFailed(null, type, parent); } public static NetworkException getEncryptionFailed(String type, Throwable parent) { NetworkException exception = new NetworkException(Localization.getMessage(Localization.ENCRYPTION_FAILED, type) + (parent != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } public static void decryptionFailed(Listenable listenable, String type, Throwable parent) { NetworkException ex = getDecryptionFailed(type, parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void decryptionFailed(String type, Throwable parent) { decryptionFailed(null, type, parent); } public static NetworkException getDecryptionFailed(String type, Throwable parent) { NetworkException exception = new NetworkException( Localization.getMessage(Localization.DECRYPTION_FAILED, type) + (parent != null && parent.getMessage() != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } public static void disallowedForcedStateChange(Listenable listenable, Throwable parent) { NetworkException ex = getDisallowedForcedStateChange(parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void disallowedForcedStateChange(Throwable parent) { disallowedForcedStateChange(null, parent); } public static NetworkException getDisallowedForcedStateChange(Throwable parent) { NetworkException exception = new NetworkException(Localization.getMessage(Localization.DISALLOWED_FORCED_STATE_CHANGE) + (parent != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } public static void missingDataType(Listenable listenable, String type, String name, Throwable parent) { NullPointerException ex = getMissingDataType(type, name, parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void missingDataType(String type, String name, Throwable parent) { missingDataType(null, type, name, parent); } public static NullPointerException getMissingDataType(String type, String name, Throwable parent) { NullPointerException exception = new NullPointerException(Localization.getMessage(Localization.MISSING_DATA_TYPE, type, name) + (parent != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } public static void noResponseExpected(Listenable listenable, String type, Throwable parent) { NetworkException ex = getNoResponseExpected(type, parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void noResponseExpected(String type, Throwable parent) { noResponseExpected(null, type, parent); } public static NetworkException getNoResponseExpected(String type, Throwable parent) { NetworkException exception = new NetworkException(Localization.getMessage(Localization.NO_RESPONSE_EXPECTED, type) + (parent != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } public static void responseTimedOut(Listenable listenable, String type, Throwable parent) { NetworkException ex = getResponseTimedOut(type, parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void responseTimedOut(String type, Throwable parent) { responseTimedOut(null, type, parent); } public static NetworkException getResponseTimedOut(String type, Throwable parent) { NetworkException exception = new NetworkException(Localization.getMessage(Localization.RESPONSE_TIMED_OUT, type) + (parent != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } public static void malformedQuery(Listenable listenable, String id, String type, Throwable parent) { NetworkException ex = getMalformedQuery(id, type, parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void malformedQuery(String id, String type, Throwable parent) { malformedQuery(null, id, type, parent); } public static NetworkException getMalformedQuery(String id, String type, Throwable parent) { NetworkException exception = new NetworkException(Localization.getMessage(Localization.MALFORMED_QUERY, id, type) + (parent != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } public static void genericFatalConnection(Listenable listenable, String ip, int port, Throwable parent) { NetworkException ex = getGenericFatalConnection(ip, port, parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void genericFatalConnection(String ip, int port, Throwable parent) { genericFatalConnection(null, ip, port, parent); } public static NetworkException getGenericFatalConnection(String ip, int port, Throwable parent) { NetworkException exception = new NetworkException(Localization.getMessage(Localization.GENERIC_FATAL_CONNECTION, ip, Integer.toString(port)) + (parent != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } public static void branchingNotServerSide(Listenable listenable, Throwable parent) { NetworkException ex = getBranchingNotServerSide(parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void branchingNotServerSide(Throwable parent) { branchingNotServerSide(null, parent); } public static NetworkException getBranchingNotServerSide(Throwable parent) { NetworkException exception = new NetworkException(Localization.getMessage(Localization.BRANCHING_NOT_SERVER_SIDE) + (parent != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } public static void branchingFailed(Listenable listenable, Throwable parent) { NetworkException ex = getBranchingFailed(parent); if (listenable != null) { listenable.report(ex); } else { throw ex; } } public static void branchingFailed(Throwable parent) { branchingFailed(null, parent); } public static NetworkException getBranchingFailed(Throwable parent) { NetworkException exception = new NetworkException(Localization.getMessage(Localization.BRANCHING_FAILED) + (parent != null && !parent.getMessage().equals("") ? " (" + Localization.getMessage(Localization.CAUSED_BY, parent.getClass().getName(), parent.getMessage()) + ")" : "")); if (parent != null) { exception.setStackTrace(parent.getStackTrace()); } return exception; } }
30.281596
322
0.642821
184d9d65ed97ae842561ea5b08b03419a0e7d0a4
3,178
/* * Copyright 2000-2014 Vaadin Ltd. * * 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.customweb.sass.internal.visitor; import java.util.Collection; import java.util.Collections; import com.customweb.sass.internal.Scope; import com.customweb.sass.internal.ScssContext; import com.customweb.sass.internal.handler.SCSSErrorHandler; import com.customweb.sass.internal.parser.ParseException; import com.customweb.sass.internal.parser.Variable; import com.customweb.sass.internal.tree.MixinDefNode; import com.customweb.sass.internal.tree.MixinNode; import com.customweb.sass.internal.tree.Node; import com.customweb.sass.internal.tree.controldirective.TemporaryNode; public class MixinNodeHandler { public static Collection<Node> traverse(ScssContext context, MixinNode node) { return replaceMixins(context, node); } private static Collection<Node> replaceMixins(ScssContext context, MixinNode node) { MixinDefNode mixinDef = context.getMixinDefinition(node.getName()); if (mixinDef == null) { SCSSErrorHandler.get().traverseError( "Mixin Definition: " + node.getName() + " not found"); return Collections.emptyList(); } return replaceMixinNode(context, node, mixinDef); } private static Collection<Node> replaceMixinNode(ScssContext context, MixinNode mixinNode, MixinDefNode mixinDef) { MixinDefNode defClone = mixinDef.copy(); defClone.replaceContentDirective(mixinNode); if (!mixinDef.getArglist().isEmpty()) { defClone.replacePossibleArguments(mixinNode.getArglist()); defClone.replaceVariables(context); } // parameters have been evaluated in parent scope, rest should be // in the scope where the mixin was defined Scope previousScope = context.openVariableScope(defClone .getDefinitionScope()); try { // add variables from argList for (Variable var : defClone.getArglist().getArguments()) { Variable evaluated = new Variable(var.getName(), var.getExpr() .evaluateFunctionsAndExpressions(context, true)); context.addVariable(evaluated); } // traverse child nodes in this scope // use correct parent with intermediate TemporaryNode Node tempParent = new TemporaryNode(mixinNode.getParentNode(), defClone.getChildren()); return tempParent.traverse(context); } finally { context.closeVariableScope(previousScope); } } }
39.234568
82
0.685651
d0e5245d87a6fe7a194899b93f734485e934181a
780
package threads; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; public class UserStorageTest { @Test public void test() { UserStorage storage = new UserStorage(); User user1 = new User(1, 100); User user2 = new User(2, 200); assertThat(storage.add(user1), is(true)); assertThat(storage.add(user2), is(true)); assertThat(storage.add(new User(3, 300)), is(true)); assertThat(storage.add(new User(1, 150)), is(false)); assertThat(storage.update(new User(1, 111)), is(true)); storage.transfer(user1.getId(), user2.getId(), 50); assertThat(user1.getAmount(), is(61)); assertThat(user2.getAmount(), is(250)); } }
30
63
0.635897
cbc7f7152cf6b5da8d667eb091455932f6a00d64
403
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package u.aly; public final class cu { public final byte a; public final int b; public cu() { this((byte)0, 0); } public cu(byte byte0, int i) { a = byte0; b = i; } }
16.12
62
0.593052
968b17abe0f341e22628082ddbd9df75c2fb990d
3,646
package cn.wendong.admin.core.shiro.session; import java.util.Collection; import java.util.Date; import org.apache.shiro.session.InvalidSessionException; import org.apache.shiro.session.Session; import org.apache.shiro.session.UnknownSessionException; import org.apache.shiro.session.mgt.SessionContext; import org.apache.shiro.session.mgt.SessionKey; import org.apache.shiro.session.mgt.SimpleSession; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; /** * session管理 * @author MB yangtdo@qq.com * @date 2018-12-14 */ public class SessionManager extends DefaultWebSessionManager { public void validateSessions() { super.validateSessions(); } protected Session retrieveSession(SessionKey sessionKey) { try { return super.retrieveSession(sessionKey); } catch (UnknownSessionException e) { } return null; } public Date getStartTimestamp(SessionKey key) { try { return super.getStartTimestamp(key); } catch (InvalidSessionException e) { } return null; } public Date getLastAccessTime(SessionKey key) { try { return super.getLastAccessTime(key); } catch (InvalidSessionException e) { } return null; } public long getTimeout(SessionKey key) { try { return super.getTimeout(key); } catch (InvalidSessionException e) { } return 0L; } public void setTimeout(SessionKey key, long maxIdleTimeInMillis) { try { super.setTimeout(key, maxIdleTimeInMillis); } catch (InvalidSessionException localInvalidSessionException) { } } public void touch(SessionKey key) { try { super.touch(key); } catch (InvalidSessionException localInvalidSessionException) { } } public String getHost(SessionKey key) { try { return super.getHost(key); } catch (InvalidSessionException e) { } return null; } public Collection<Object> getAttributeKeys(SessionKey key) { try { return super.getAttributeKeys(key); } catch (InvalidSessionException e) { } return null; } public Object getAttribute(SessionKey sessionKey, Object attributeKey) { try { return super.getAttribute(sessionKey, attributeKey); } catch (InvalidSessionException e) { } return null; } public void setAttribute(SessionKey sessionKey, Object attributeKey, Object value) { try { super.setAttribute(sessionKey, attributeKey, value); } catch (InvalidSessionException localInvalidSessionException) { } } public Object removeAttribute(SessionKey sessionKey, Object attributeKey) { try { return super.removeAttribute(sessionKey, attributeKey); } catch (InvalidSessionException e) { } return null; } public void stop(SessionKey key) { try { super.stop(key); } catch (InvalidSessionException localInvalidSessionException) { } } public void checkValid(SessionKey key) { try { super.checkValid(key); } catch (InvalidSessionException localInvalidSessionException) { } } protected Session doCreateSession(SessionContext context) { try { return super.doCreateSession(context); } catch (IllegalStateException e) { } return null; } protected Session newSessionInstance(SessionContext context) { Session session = super.newSessionInstance(context); session.setTimeout(getGlobalSessionTimeout()); return session; } public Session start(SessionContext context) { SimpleSession session; try { return super.start(context); } catch (NullPointerException e) { session = new SimpleSession(); session.setId(Integer.valueOf(0)); } return session; } }
24.635135
86
0.71311
f077f18904fd0709eb313beed3625a78c9d4bfa4
5,928
package com.mcjty.smalltales.modules.story.client; import com.mcjty.smalltales.modules.story.blocks.StoryAnchorTile; import com.mcjty.smalltales.modules.story.network.PacketUpdateKnowledge; import com.mcjty.smalltales.setup.Messages; import com.mojang.blaze3d.matrix.MatrixStack; import mcjty.lib.gui.*; import mcjty.lib.gui.widgets.*; import net.minecraft.client.Minecraft; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import static mcjty.lib.gui.widgets.Widgets.*; public class GuiConfigurator extends GuiItemScreen implements IKeyReceiver { public static final int WIDTH = 340; public static final int HEIGHT = 200; private final BlockPos pos; private TextField chapterTextField; private TextField messageTextField; private Slider rangeSlider; private ScrollableLabel range; private ToggleButton onActivateButton; public GuiConfigurator(BlockPos pos) { super(Messages.INSTANCE, WIDTH, HEIGHT, ManualEntry.EMPTY); this.pos = pos; } @Override public void init() { super.init(); chapterTextField = textfield(70, 10, WIDTH-80, 20).event(this::update).addTextEnterEvent(this::updateAndExit); messageTextField = textfield(70, 32, WIDTH-80, 20).event(this::update).addTextEnterEvent(this::updateAndExit); range = new ScrollableLabel().hint(70, 54, 30, 20).event(i -> update("")).realMinimum(1).realMaximum(50).name("range"); rangeSlider = slider(105, 54, WIDTH-80-35, 20).horizontal().scrollableName("range"); onActivateButton = new ToggleButton().hint(70, 76, WIDTH-80, 20).event(() -> update("")).checkMarker(true); TileEntity be = Minecraft.getInstance().level.getBlockEntity(pos); if (be instanceof StoryAnchorTile) { StoryAnchorTile tile = (StoryAnchorTile) be; tile.getChapter().ifPresent(c -> chapterTextField.text(c)); tile.getMessage().ifPresent(c -> messageTextField.text(c)); range.setGenericValue(tile.getRange()); onActivateButton.pressed(tile.isOnActivate()); } Panel toplevel = positional().filledRectThickness(2).children( label(10, 10, 55, 20, "Chapter:"), chapterTextField, label(10, 32, 55, 20, "Message:"), messageTextField, label(10, 54, 55, 20, "Range:"), range, rangeSlider, label(10, 76, 55, 20, "Activate:"), onActivateButton ); int x = (this.width - xSize) / 2; int y = (this.height - ySize) / 2; toplevel.bounds(x, y, xSize, ySize); window = new Window(this, toplevel); minecraft.keyboardHandler.setSendRepeatsToGui(true); } private void updateAndExit(String c) { update(c); onClose(); } private void update(String _) { if (range == null || onActivateButton == null) { return; } Messages.INSTANCE.sendToServer(new PacketUpdateKnowledge(pos, chapterTextField.getText(), messageTextField.getText(), range.getRealValue(), onActivateButton.isPressed())); } @Override public void mouseMoved(double xx, double yy) { // If not initialized yet we do nothing if (window == null) { return; } window.mouseDragged(xx, yy, 0); // @todo 1.14 is this right? What button? } @Override public boolean mouseClicked(double x, double y, int button) { // If not initialized yet we do nothing if (window == null) { return false; } return super.mouseClicked(x, y, button); } @Override public boolean mouseReleased(double mouseX, double mouseY, int button) { // If not initialized yet we do nothing if (window == null) { return false; } return super.mouseReleased(mouseX, mouseY, button); } @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { // If not initialized yet we do nothing if (window == null) { return false; } boolean rc = false; if (!window.keyTyped(keyCode, scanCode)) { rc = super.keyPressed(keyCode, scanCode, modifiers); } return rc; } @Override public Window getWindow() { return window; } @Override public void keyTypedFromEvent(int keyCode, int scanCode) { if (window != null) { if (window.keyTyped(keyCode, scanCode)) { super.keyPressed(keyCode, scanCode, 0); // @todo 1.14: modifiers? } } } @Override public void charTypedFromEvent(char codePoint) { if (window != null) { if (window.charTyped(codePoint)) { super.charTyped(codePoint, 0); // @todo 1.14: modifiers? } } } @Override public boolean mouseClickedFromEvent(double x, double y, int button) { WindowManager manager = getWindow().getWindowManager(); // manager.mouseClicked(x, y, button); return true; } @Override public boolean mouseReleasedFromEvent(double x, double y, int button) { WindowManager manager = getWindow().getWindowManager(); // manager.mouseReleased(x, y, button); return true; } @Override public boolean mouseScrolledFromEvent(double x, double y, double amount) { WindowManager manager = getWindow().getWindowManager(); manager.mouseScrolled(x, y, amount); return true; } @Override public void render(MatrixStack matrixStack, int mouseX, int mouseY, float par3) { super.render(matrixStack, mouseX, mouseY, par3); drawWindow(matrixStack); } public static void open(BlockPos pos) { Minecraft.getInstance().setScreen(new GuiConfigurator(pos)); } }
33.874286
127
0.628543
1fe55566d82ec35e22ac16e4ab1fc0498e5933a2
321
package io.jutil.jdo.internal.core.reflect2; import java.util.Set; /** * @author Jin Zheng * @since 2022-05-01 */ public class RefelctConst { public static final Set<String> IGNORE_METHOD_SET = Set.of("wait", "equals", "toString", "hashCode", "getClass", "notify", "notifyAll"); private RefelctConst() { } }
18.882353
113
0.685358
4675cca91e3e531128b511444e5ec69bf34a795a
68,434
/* * Copyright (C) 2021 Alberto Irurueta Carro (alberto@irurueta.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.irurueta.navigation.inertial.calibration; import com.irurueta.algebra.AlgebraException; import com.irurueta.algebra.Matrix; import com.irurueta.algebra.WrongSizeException; import com.irurueta.navigation.inertial.BodyKinematics; import com.irurueta.statistics.UniformRandomizer; import com.irurueta.units.Acceleration; import com.irurueta.units.AccelerationUnit; import com.irurueta.units.AngularSpeed; import com.irurueta.units.AngularSpeedUnit; import org.junit.Test; import java.util.Random; import static org.junit.Assert.*; public class BodyKinematicsFixerTest { private static final double TIME_INTERVAL_SECONDS = 0.02; private static final double MIN_ACCELEROMETER_VALUE = -2.0 * 9.81; private static final double MAX_ACCELEROMETER_VALUE = 2.0 * 9.81; private static final double MIN_GYRO_VALUE = -2.0; private static final double MAX_GYRO_VALUE = 2.0; private static final double MICRO_G_TO_METERS_PER_SECOND_SQUARED = 9.80665E-6; private static final double DEG_TO_RAD = 0.01745329252; private static final double ABSOLUTE_ERROR = 1e-12; @Test public void testConstructor() throws WrongSizeException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values assertEquals(fixer.getAccelerationBias(), new Matrix(3, 1)); final Matrix ba = new Matrix(3, 1); fixer.getAccelerationBias(ba); assertEquals(ba, new Matrix(3, 1)); assertArrayEquals(fixer.getAccelerationBiasArray(), new double[3], 0.0); final double[] ba2 = new double[3]; fixer.getAccelerationBiasArray(ba2); assertArrayEquals(ba2, new double[3], 0.0); assertEquals(fixer.getAccelerationBiasX(), 0.0, 0.0); assertEquals(fixer.getAccelerationBiasY(), 0.0, 0.0); assertEquals(fixer.getAccelerationBiasZ(), 0.0, 0.0); final AccelerationTriad accelerationTriad1 = fixer.getAccelerationBiasAsTriad(); assertEquals(accelerationTriad1.getValueX(), 0.0, 0.0); assertEquals(accelerationTriad1.getValueY(), 0.0, 0.0); assertEquals(accelerationTriad1.getValueZ(), 0.0, 0.0); assertEquals(AccelerationUnit.METERS_PER_SQUARED_SECOND, accelerationTriad1.getUnit()); final AccelerationTriad accelerationTriad2 = new AccelerationTriad(); fixer.getAccelerationBiasAsTriad(accelerationTriad2); assertEquals(accelerationTriad1, accelerationTriad2); assertEquals(fixer.getAccelerationCrossCouplingErrors(), new Matrix(3, 3)); final Matrix ma = new Matrix(3, 3); fixer.getAccelerationCrossCouplingErrors(ma); assertEquals(ma, new Matrix(3, 3)); final Acceleration bax1 = fixer.getAccelerationBiasXAsAcceleration(); assertEquals(bax1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AccelerationUnit.METERS_PER_SQUARED_SECOND, bax1.getUnit()); final Acceleration bax2 = new Acceleration( 1.0, AccelerationUnit.FEET_PER_SQUARED_SECOND); fixer.getAccelerationBiasXAsAcceleration(bax2); assertEquals(bax1, bax2); final Acceleration bay1 = fixer.getAccelerationBiasYAsAcceleration(); assertEquals(bay1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AccelerationUnit.METERS_PER_SQUARED_SECOND, bay1.getUnit()); final Acceleration bay2 = new Acceleration( 1.0, AccelerationUnit.FEET_PER_SQUARED_SECOND); fixer.getAccelerationBiasYAsAcceleration(bay2); assertEquals(bay1, bay2); final Acceleration baz1 = fixer.getAccelerationBiasZAsAcceleration(); assertEquals(baz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AccelerationUnit.METERS_PER_SQUARED_SECOND, baz1.getUnit()); final Acceleration baz2 = new Acceleration( 1.0, AccelerationUnit.FEET_PER_SQUARED_SECOND); fixer.getAccelerationBiasZAsAcceleration(baz2); assertEquals(baz1, baz2); assertEquals(fixer.getAccelerationSx(), 0.0, 0.0); assertEquals(fixer.getAccelerationSy(), 0.0, 0.0); assertEquals(fixer.getAccelerationSz(), 0.0, 0.0); assertEquals(fixer.getAccelerationMxy(), 0.0, 0.0); assertEquals(fixer.getAccelerationMxz(), 0.0, 0.0); assertEquals(fixer.getAccelerationMyx(), 0.0, 0.0); assertEquals(fixer.getAccelerationMyz(), 0.0, 0.0); assertEquals(fixer.getAccelerationMzx(), 0.0, 0.0); assertEquals(fixer.getAccelerationMzy(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedBias(), new Matrix(3, 1)); final Matrix bg = new Matrix(3, 1); fixer.getAngularSpeedBias(bg); assertEquals(bg, new Matrix(3, 1)); assertArrayEquals(fixer.getAngularSpeedBiasArray(), new double[3], 0.0); final double[] bg2 = new double[3]; fixer.getAngularSpeedBiasArray(bg2); assertArrayEquals(bg2, new double[3], 0.0); final AngularSpeedTriad angularSpeedTriad1 = fixer.getAngularSpeedBiasAsTriad(); assertEquals(angularSpeedTriad1.getValueX(), 0.0, 0.0); assertEquals(angularSpeedTriad1.getValueY(), 0.0, 0.0); assertEquals(angularSpeedTriad1.getValueZ(), 0.0, 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, angularSpeedTriad1.getUnit()); final AngularSpeedTriad angularSpeedTriad2 = new AngularSpeedTriad(); fixer.getAngularSpeedBiasAsTriad(angularSpeedTriad2); assertEquals(angularSpeedTriad1, angularSpeedTriad2); assertEquals(fixer.getAngularSpeedBiasX(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedBiasY(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = fixer.getAngularSpeedBiasXAsAngularSpeed(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, bgx1.getUnit()); final AngularSpeed bgx2 = new AngularSpeed( 1.0, AngularSpeedUnit.DEGREES_PER_SECOND); fixer.getAngularSpeedBiasXAsAngularSpeed(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = fixer.getAngularSpeedBiasYAsAngularSpeed(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, bgy1.getUnit()); final AngularSpeed bgy2 = new AngularSpeed( 1.0, AngularSpeedUnit.DEGREES_PER_SECOND); fixer.getAngularSpeedBiasYAsAngularSpeed(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = fixer.getAngularSpeedBiasZAsAngularSpeed(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, bgz1.getUnit()); final AngularSpeed bgz2 = new AngularSpeed( 1.0, AngularSpeedUnit.DEGREES_PER_SECOND); fixer.getAngularSpeedBiasZAsAngularSpeed(bgz2); assertEquals(bgz1, bgz2); assertEquals(fixer.getAngularSpeedCrossCouplingErrors(), new Matrix(3, 3)); final Matrix mg = new Matrix(3, 3); fixer.getAngularSpeedCrossCouplingErrors(mg); assertEquals(mg, new Matrix(3, 3)); assertEquals(fixer.getAngularSpeedSx(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedSy(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedSz(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMxy(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMxz(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMyx(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMyz(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMzx(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMzy(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedGDependantCrossBias(), new Matrix(3, 3)); final Matrix gg = new Matrix(3, 3); fixer.getAngularSpeedGDependantCrossBias(gg); assertEquals(gg, new Matrix(3, 3)); } @Test public void testGetSetAccelerationBias() throws WrongSizeException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value final Matrix b1 = fixer.getAccelerationBias(); final Matrix b2 = new Matrix(1, 1); fixer.getAccelerationBias(b2); assertEquals(b1, new Matrix(3, 1)); assertEquals(b1, b2); // set new value final Matrix b3 = generateBa(); fixer.setAccelerationBias(b3); // check final Matrix b4 = fixer.getAccelerationBias(); final Matrix b5 = new Matrix(3, 1); fixer.getAccelerationBias(b5); assertEquals(b3, b4); assertEquals(b3, b5); // Force IllegalArgumentException try { fixer.setAccelerationBias(new Matrix(1, 1)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { fixer.setAccelerationBias(new Matrix(3, 3)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testGetSetAccelerationBiasArray() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value final double[] b1 = fixer.getAccelerationBiasArray(); final double[] b2 = new double[3]; fixer.getAccelerationBiasArray(b2); assertArrayEquals(b1, new double[3], 0.0); assertArrayEquals(b1, b2, 0.0); // set new value final double[] b3 = generateBa().getBuffer(); fixer.setAccelerationBias(b3); // check final double[] b4 = fixer.getAccelerationBiasArray(); final double[] b5 = new double[3]; fixer.getAccelerationBiasArray(b5); assertArrayEquals(b3, b4, 0.0); assertArrayEquals(b3, b5, 0.0); // Force IllegalArgumentException try { fixer.getAccelerationBiasArray(new double[1]); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { fixer.setAccelerationBias(new double[1]); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testGetSetAccelerationBiasTriad() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value final AccelerationTriad triad1 = fixer.getAccelerationBiasAsTriad(); assertEquals(triad1.getValueX(), 0.0, 0.0); assertEquals(triad1.getValueY(), 0.0, 0.0); assertEquals(triad1.getValueZ(), 0.0, 0.0); assertEquals(AccelerationUnit.METERS_PER_SQUARED_SECOND, triad1.getUnit()); // set new value final AccelerationTriad triad2 = new AccelerationTriad(); triad2.setValueCoordinates(generateBa()); fixer.setAccelerationBias(triad2); // check final AccelerationTriad triad3 = fixer.getAccelerationBiasAsTriad(); final AccelerationTriad triad4 = new AccelerationTriad(); fixer.getAccelerationBiasAsTriad(triad4); assertEquals(triad2, triad3); assertEquals(triad2, triad4); } @Test public void testGetSetAccelerationBiasX() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAccelerationBiasX(), 0.0, 0.0); // set new value final Matrix b = generateBa(); final double bx = b.getElementAtIndex(0); fixer.setAccelerationBiasX(bx); // check assertEquals(bx, fixer.getAccelerationBiasX(), 0.0); } @Test public void testGetSetAccelerationBiasY() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAccelerationBiasY(), 0.0, 0.0); // set new value final Matrix b = generateBa(); final double by = b.getElementAtIndex(1); fixer.setAccelerationBiasY(by); // check assertEquals(by, fixer.getAccelerationBiasY(), 0.0); } @Test public void testGetSetAccelerationBiasZ() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAccelerationBiasZ(), 0.0, 0.0); // set new value final Matrix b = generateBa(); final double bz = b.getElementAtIndex(2); fixer.setAccelerationBiasZ(bz); // check assertEquals(bz, fixer.getAccelerationBiasZ(), 0.0); } @Test public void testSetAccelerationBias1() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values assertEquals(fixer.getAccelerationBiasX(), 0.0, 0.0); assertEquals(fixer.getAccelerationBiasY(), 0.0, 0.0); assertEquals(fixer.getAccelerationBiasZ(), 0.0, 0.0); // set new values final Matrix b = generateBa(); final double bx = b.getElementAtIndex(0); final double by = b.getElementAtIndex(1); final double bz = b.getElementAtIndex(2); fixer.setAccelerationBias(bx, by, bz); // check assertEquals(bx, fixer.getAccelerationBiasX(), 0.0); assertEquals(by, fixer.getAccelerationBiasY(), 0.0); assertEquals(bz, fixer.getAccelerationBiasZ(), 0.0); } @Test public void testGetSetAccelerationBiasXAsAcceleration() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value final Acceleration bx1 = fixer.getAccelerationBiasXAsAcceleration(); assertEquals(bx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AccelerationUnit.METERS_PER_SQUARED_SECOND, bx1.getUnit()); // set new value final Matrix b = generateBa(); final double bx = b.getElementAtIndex(0); final Acceleration bx2 = new Acceleration( bx, AccelerationUnit.METERS_PER_SQUARED_SECOND); fixer.setAccelerationBiasX(bx2); // check final Acceleration bx3 = fixer.getAccelerationBiasXAsAcceleration(); final Acceleration bx4 = new Acceleration( 1.0, AccelerationUnit.FEET_PER_SQUARED_SECOND); fixer.getAccelerationBiasXAsAcceleration(bx4); assertEquals(bx2, bx3); assertEquals(bx2, bx4); } @Test public void testGetSetAccelerationBiasYAsAcceleration() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value final Acceleration by1 = fixer.getAccelerationBiasYAsAcceleration(); assertEquals(by1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AccelerationUnit.METERS_PER_SQUARED_SECOND, by1.getUnit()); // set new value final Matrix b = generateBa(); final double by = b.getElementAtIndex(1); final Acceleration by2 = new Acceleration( by, AccelerationUnit.METERS_PER_SQUARED_SECOND); fixer.setAccelerationBiasY(by2); // check final Acceleration by3 = fixer.getAccelerationBiasYAsAcceleration(); final Acceleration by4 = new Acceleration( 1.0, AccelerationUnit.FEET_PER_SQUARED_SECOND); fixer.getAccelerationBiasYAsAcceleration(by4); assertEquals(by2, by3); assertEquals(by2, by4); } @Test public void testGetSetAccelerationBiasZAsAcceleration() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value final Acceleration bz1 = fixer.getAccelerationBiasZAsAcceleration(); assertEquals(bz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AccelerationUnit.METERS_PER_SQUARED_SECOND, bz1.getUnit()); // set new value final Matrix b = generateBa(); final double bz = b.getElementAtIndex(2); final Acceleration bz2 = new Acceleration( bz, AccelerationUnit.METERS_PER_SQUARED_SECOND); fixer.setAccelerationBiasZ(bz2); // check final Acceleration bz3 = fixer.getAccelerationBiasZAsAcceleration(); final Acceleration bz4 = new Acceleration( 1.0, AccelerationUnit.FEET_PER_SQUARED_SECOND); fixer.getAccelerationBiasZAsAcceleration(bz4); assertEquals(bz2, bz3); assertEquals(bz2, bz4); } @Test public void testGetSetBias2() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values final Acceleration bx1 = fixer.getAccelerationBiasXAsAcceleration(); assertEquals(bx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AccelerationUnit.METERS_PER_SQUARED_SECOND, bx1.getUnit()); final Acceleration by1 = fixer.getAccelerationBiasYAsAcceleration(); assertEquals(by1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AccelerationUnit.METERS_PER_SQUARED_SECOND, by1.getUnit()); final Acceleration bz1 = fixer.getAccelerationBiasZAsAcceleration(); assertEquals(bz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AccelerationUnit.METERS_PER_SQUARED_SECOND, bz1.getUnit()); // set new values final Matrix b = generateBa(); final double bx = b.getElementAtIndex(0); final double by = b.getElementAtIndex(1); final double bz = b.getElementAtIndex(2); final Acceleration bx2 = new Acceleration( bx, AccelerationUnit.METERS_PER_SQUARED_SECOND); final Acceleration by2 = new Acceleration( by, AccelerationUnit.METERS_PER_SQUARED_SECOND); final Acceleration bz2 = new Acceleration( bz, AccelerationUnit.METERS_PER_SQUARED_SECOND); fixer.setAccelerationBias(bx2, by2, bz2); // check final Acceleration bx3 = fixer.getAccelerationBiasXAsAcceleration(); final Acceleration by3 = fixer.getAccelerationBiasYAsAcceleration(); final Acceleration bz3 = fixer.getAccelerationBiasZAsAcceleration(); assertEquals(bx2, bx3); assertEquals(by2, by3); assertEquals(bz2, bz3); } @Test public void testGetSetAccelerationCrossCouplingErrors() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values final Matrix m1 = fixer.getAccelerationCrossCouplingErrors(); final Matrix m2 = new Matrix(1, 1); fixer.getAccelerationCrossCouplingErrors(m2); assertEquals(m1, new Matrix(3, 3)); assertEquals(m1, m2); // set new values final Matrix m3 = generateMa(); final double sx = m3.getElementAt(0, 0); final double sy = m3.getElementAt(1, 1); final double sz = m3.getElementAt(2, 2); final double mxy = m3.getElementAt(0, 1); final double mxz = m3.getElementAt(0, 2); final double myx = m3.getElementAt(1, 0); final double myz = m3.getElementAt(1, 2); final double mzx = m3.getElementAt(2, 0); final double mzy = m3.getElementAt(2, 1); fixer.setAccelerationCrossCouplingErrors(m3); // check final Matrix m4 = fixer.getAccelerationCrossCouplingErrors(); final Matrix m5 = new Matrix(3, 3); fixer.getAccelerationCrossCouplingErrors(m5); assertEquals(m3, m4); assertEquals(m3, m5); assertEquals(sx, fixer.getAccelerationSx(), 0.0); assertEquals(sy, fixer.getAccelerationSy(), 0.0); assertEquals(sz, fixer.getAccelerationSz(), 0.0); assertEquals(mxy, fixer.getAccelerationMxy(), 0.0); assertEquals(mxz, fixer.getAccelerationMxz(), 0.0); assertEquals(myx, fixer.getAccelerationMyx(), 0.0); assertEquals(myz, fixer.getAccelerationMyz(), 0.0); assertEquals(mzx, fixer.getAccelerationMzx(), 0.0); assertEquals(mzy, fixer.getAccelerationMzy(), 0.0); // Force IllegalArgumentException try { fixer.setAccelerationCrossCouplingErrors( new Matrix(1, 3)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { fixer.setAccelerationCrossCouplingErrors( new Matrix(3, 1)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } // Force AlgebraException try { final Matrix wrong = Matrix.identity(3, 3); wrong.multiplyByScalar(-1.0); fixer.setAccelerationCrossCouplingErrors(wrong); fail("AlgebraException expected but not thrown"); } catch (final AlgebraException ignore) { } } @Test public void testGetSetAccelerationSx() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAccelerationSx(), 0.0, 0.0); // set new value final Matrix m = generateMa(); final double sx = m.getElementAt(0, 0); fixer.setAccelerationSx(sx); // check assertEquals(sx, fixer.getAccelerationSx(), 0.0); } @Test public void testGetSetAccelerationSy() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAccelerationSy(), 0.0, 0.0); // set new value final Matrix m = generateMa(); final double sy = m.getElementAt(1, 1); fixer.setAccelerationSy(sy); // check assertEquals(sy, fixer.getAccelerationSy(), 0.0); } @Test public void testGetSetAccelerationSz() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAccelerationSz(), 0.0, 0.0); // set new value final Matrix m = generateMa(); final double sz = m.getElementAt(2, 2); fixer.setAccelerationSz(sz); // check assertEquals(sz, fixer.getAccelerationSz(), 0.0); } @Test public void testGetSetAccelerationMxy() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAccelerationMxy(), 0.0, 0.0); // set new value final Matrix m = generateMa(); final double mxy = m.getElementAt(0, 1); fixer.setAccelerationMxy(mxy); // check assertEquals(mxy, fixer.getAccelerationMxy(), 0.0); } @Test public void testGetSetAccelerationMxz() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAccelerationMxz(), 0.0, 0.0); // set new value final Matrix m = generateMa(); final double mxz = m.getElementAt(0, 2); fixer.setAccelerationMxz(mxz); // check assertEquals(mxz, fixer.getAccelerationMxz(), 0.0); } @Test public void testGetSetAccelerationMyx() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAccelerationMyx(), 0.0, 0.0); // set new value final Matrix m = generateMa(); final double myx = m.getElementAt(1, 0); fixer.setAccelerationMyx(myx); // check assertEquals(myx, fixer.getAccelerationMyx(), 0.0); } @Test public void testGetSetAccelerationMyz() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAccelerationMyz(), 0.0, 0.0); // set new value final Matrix m = generateMa(); final double myz = m.getElementAt(1, 2); fixer.setAccelerationMyz(myz); // check assertEquals(myz, fixer.getAccelerationMyz(), 0.0); } @Test public void testGetSetAccelerationMzx() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAccelerationMzx(), 0.0, 0.0); // set new value final Matrix m = generateMa(); final double mzx = m.getElementAt(2, 0); fixer.setAccelerationMzx(mzx); // check assertEquals(mzx, fixer.getAccelerationMzx(), 0.0); } @Test public void testGetSetAccelerationMzy() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAccelerationMzy(), 0.0, 0.0); // set new value final Matrix m = generateMa(); final double mzy = m.getElementAt(2, 1); fixer.setAccelerationMzy(mzy); // check assertEquals(mzy, fixer.getAccelerationMzy(), 0.0); } @Test public void testSetAccelerationScalingFactors() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values assertEquals(fixer.getAccelerationSx(), 0.0, 0.0); assertEquals(fixer.getAccelerationSy(), 0.0, 0.0); assertEquals(fixer.getAccelerationSz(), 0.0, 0.0); // set new values final Matrix m = generateMa(); final double sx = m.getElementAt(0, 0); final double sy = m.getElementAt(1, 1); final double sz = m.getElementAt(2, 2); fixer.setAccelerationScalingFactors(sx, sy, sz); // check assertEquals(fixer.getAccelerationSx(), sx, 0.0); assertEquals(fixer.getAccelerationSy(), sy, 0.0); assertEquals(fixer.getAccelerationSz(), sz, 0.0); } @Test public void testSetAccelerationCrossCouplingErrors() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values assertEquals(fixer.getAccelerationMxy(), 0.0, 0.0); assertEquals(fixer.getAccelerationMxz(), 0.0, 0.0); assertEquals(fixer.getAccelerationMyx(), 0.0, 0.0); assertEquals(fixer.getAccelerationMyz(), 0.0, 0.0); assertEquals(fixer.getAccelerationMzx(), 0.0, 0.0); assertEquals(fixer.getAccelerationMzy(), 0.0, 0.0); // set new values final Matrix m = generateMa(); final double mxy = m.getElementAt(0, 1); final double mxz = m.getElementAt(0, 2); final double myx = m.getElementAt(1, 0); final double myz = m.getElementAt(1, 2); final double mzx = m.getElementAt(2, 0); final double mzy = m.getElementAt(2, 1); fixer.setAccelerationCrossCouplingErrors(mxy, mxz, myx, myz, mzx, mzy); // check assertEquals(mxy, fixer.getAccelerationMxy(), 0.0); assertEquals(mxz, fixer.getAccelerationMxz(), 0.0); assertEquals(myx, fixer.getAccelerationMyx(), 0.0); assertEquals(myz, fixer.getAccelerationMyz(), 0.0); assertEquals(mzx, fixer.getAccelerationMzx(), 0.0); assertEquals(mzy, fixer.getAccelerationMzy(), 0.0); } @Test public void testSetAccelerationScalingFactorsAndCrossCouplingErrors() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values assertEquals(fixer.getAccelerationSx(), 0.0, 0.0); assertEquals(fixer.getAccelerationSy(), 0.0, 0.0); assertEquals(fixer.getAccelerationSz(), 0.0, 0.0); assertEquals(fixer.getAccelerationMxy(), 0.0, 0.0); assertEquals(fixer.getAccelerationMxz(), 0.0, 0.0); assertEquals(fixer.getAccelerationMyx(), 0.0, 0.0); assertEquals(fixer.getAccelerationMyz(), 0.0, 0.0); assertEquals(fixer.getAccelerationMzx(), 0.0, 0.0); assertEquals(fixer.getAccelerationMzy(), 0.0, 0.0); // set new values final Matrix m = generateMa(); final double sx = m.getElementAt(0, 0); final double sy = m.getElementAt(1, 1); final double sz = m.getElementAt(2, 2); final double mxy = m.getElementAt(0, 1); final double mxz = m.getElementAt(0, 2); final double myx = m.getElementAt(1, 0); final double myz = m.getElementAt(1, 2); final double mzx = m.getElementAt(2, 0); final double mzy = m.getElementAt(2, 1); fixer.setAccelerationScalingFactorsAndCrossCouplingErrors(sx, sy, sz, mxy, mxz, myx, myz, mzx, mzy); // check assertEquals(fixer.getAccelerationSx(), sx, 0.0); assertEquals(fixer.getAccelerationSy(), sy, 0.0); assertEquals(fixer.getAccelerationSz(), sz, 0.0); assertEquals(mxy, fixer.getAccelerationMxy(), 0.0); assertEquals(mxz, fixer.getAccelerationMxz(), 0.0); assertEquals(myx, fixer.getAccelerationMyx(), 0.0); assertEquals(myz, fixer.getAccelerationMyz(), 0.0); assertEquals(mzx, fixer.getAccelerationMzx(), 0.0); assertEquals(mzy, fixer.getAccelerationMzy(), 0.0); } @Test public void testGetSetAngularSpeedBias() throws WrongSizeException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value final Matrix b1 = fixer.getAngularSpeedBias(); final Matrix b2 = new Matrix(1, 1); fixer.getAngularSpeedBias(b2); assertEquals(b1, new Matrix(3, 1)); assertEquals(b1, b2); // set new value final Matrix b3 = generateBg(); fixer.setAngularSpeedBias(b3); // check final Matrix b4 = fixer.getAngularSpeedBias(); final Matrix b5 = new Matrix(3, 1); fixer.getAngularSpeedBias(b5); assertEquals(b3, b4); assertEquals(b3, b5); // Force IllegalArgumentException try { fixer.setAngularSpeedBias(new Matrix(1, 1)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { fixer.setAngularSpeedBias(new Matrix(3, 3)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testGetSetAngularSpeedBiasArray() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value final double[] b1 = fixer.getAngularSpeedBiasArray(); final double[] b2 = new double[3]; fixer.getAngularSpeedBiasArray(b2); assertArrayEquals(b1, new double[3], 0.0); assertArrayEquals(b1, b2, 0.0); // set new value final double[] b3 = generateBg().getBuffer(); fixer.setAngularSpeedBias(b3); // check final double[] b4 = fixer.getAngularSpeedBiasArray(); final double[] b5 = new double[3]; fixer.getAngularSpeedBiasArray(b5); assertArrayEquals(b3, b4, 0.0); assertArrayEquals(b3, b5, 0.0); // Force IllegalArgumentException try { fixer.getAngularSpeedBiasArray(new double[1]); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { fixer.setAngularSpeedBias(new double[1]); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testGetSetAngularSpeedBiasTriad() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value final AngularSpeedTriad triad1 = fixer.getAngularSpeedBiasAsTriad(); assertEquals(triad1.getValueX(), 0.0, 0.0); assertEquals(triad1.getValueY(), 0.0, 0.0); assertEquals(triad1.getValueZ(), 0.0, 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, triad1.getUnit()); // set new value final AngularSpeedTriad triad2 = new AngularSpeedTriad(); triad2.setValueCoordinates(generateBg()); fixer.setAngularSpeedBias(triad2); // check final AngularSpeedTriad triad3 = fixer.getAngularSpeedBiasAsTriad(); final AngularSpeedTriad triad4 = new AngularSpeedTriad(); fixer.getAngularSpeedBiasAsTriad(triad4); assertEquals(triad2, triad3); assertEquals(triad2, triad4); } @Test public void testGetSetAngularSpeedBiasX() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAngularSpeedBiasX(), 0.0, 0.0); // set new value final Matrix b = generateBg(); final double bx = b.getElementAtIndex(0); fixer.setAngularSpeedBiasX(bx); // check assertEquals(bx, fixer.getAngularSpeedBiasX(), 0.0); } @Test public void testGetSetAngularSpeedBiasY() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAngularSpeedBiasY(), 0.0, 0.0); // set new value final Matrix b = generateBg(); final double by = b.getElementAtIndex(1); fixer.setAngularSpeedBiasY(by); // check assertEquals(by, fixer.getAngularSpeedBiasY(), 0.0); } @Test public void testGetSetAngularSpeedBiasZ() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAngularSpeedBiasZ(), 0.0, 0.0); // set new value final Matrix b = generateBg(); final double bz = b.getElementAtIndex(2); fixer.setAngularSpeedBiasZ(bz); // check assertEquals(bz, fixer.getAngularSpeedBiasZ(), 0.0); } @Test public void testSetAngularSpeedBias1() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values assertEquals(fixer.getAngularSpeedBiasX(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedBiasY(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedBiasZ(), 0.0, 0.0); // set new values final Matrix b = generateBg(); final double bx = b.getElementAtIndex(0); final double by = b.getElementAtIndex(1); final double bz = b.getElementAtIndex(2); fixer.setAngularSpeedBias(bx, by, bz); // check assertEquals(bx, fixer.getAngularSpeedBiasX(), 0.0); assertEquals(by, fixer.getAngularSpeedBiasY(), 0.0); assertEquals(bz, fixer.getAngularSpeedBiasZ(), 0.0); } @Test public void testGetSetAngularSpeedBiasXAsAngularSpeed() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value final AngularSpeed bx1 = fixer.getAngularSpeedBiasXAsAngularSpeed(); assertEquals(bx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, bx1.getUnit()); // set new value final Matrix b = generateBg(); final double bx = b.getElementAtIndex(0); final AngularSpeed bx2 = new AngularSpeed( bx, AngularSpeedUnit.RADIANS_PER_SECOND); fixer.setAngularSpeedBiasX(bx2); // check final AngularSpeed bx3 = fixer.getAngularSpeedBiasXAsAngularSpeed(); final AngularSpeed bx4 = new AngularSpeed( 1.0, AngularSpeedUnit.DEGREES_PER_SECOND); fixer.getAngularSpeedBiasXAsAngularSpeed(bx4); assertEquals(bx2, bx3); assertEquals(bx2, bx4); } @Test public void testGetSetAngularSpeedBiasYAsAngularSpeed() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value final AngularSpeed by1 = fixer.getAngularSpeedBiasYAsAngularSpeed(); assertEquals(by1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, by1.getUnit()); // set new value final Matrix b = generateBg(); final double by = b.getElementAtIndex(1); final AngularSpeed by2 = new AngularSpeed( by, AngularSpeedUnit.RADIANS_PER_SECOND); fixer.setAngularSpeedBiasY(by2); // check final AngularSpeed by3 = fixer.getAngularSpeedBiasYAsAngularSpeed(); final AngularSpeed by4 = new AngularSpeed( 1.0, AngularSpeedUnit.DEGREES_PER_SECOND); fixer.getAngularSpeedBiasYAsAngularSpeed(by4); assertEquals(by2, by3); assertEquals(by2, by4); } @Test public void testGetSetAngularSpeedBiasZAsAngularSpeed() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value final AngularSpeed bz1 = fixer.getAngularSpeedBiasZAsAngularSpeed(); assertEquals(bz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, bz1.getUnit()); // set new value final Matrix b = generateBg(); final double bz = b.getElementAtIndex(2); final AngularSpeed bz2 = new AngularSpeed( bz, AngularSpeedUnit.RADIANS_PER_SECOND); fixer.setAngularSpeedBiasZ(bz2); // check final AngularSpeed bz3 = fixer.getAngularSpeedBiasZAsAngularSpeed(); final AngularSpeed bz4 = new AngularSpeed( 1.0, AngularSpeedUnit.DEGREES_PER_SECOND); fixer.getAngularSpeedBiasZAsAngularSpeed(bz4); assertEquals(bz2, bz3); assertEquals(bz2, bz4); } @Test public void testGetSetAngularSpeedBias2() { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values final AngularSpeed bx1 = fixer.getAngularSpeedBiasXAsAngularSpeed(); assertEquals(bx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, bx1.getUnit()); final AngularSpeed by1 = fixer.getAngularSpeedBiasYAsAngularSpeed(); assertEquals(by1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, by1.getUnit()); final AngularSpeed bz1 = fixer.getAngularSpeedBiasZAsAngularSpeed(); assertEquals(bz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, bz1.getUnit()); // set new values final Matrix b = generateBg(); final double bx = b.getElementAtIndex(0); final double by = b.getElementAtIndex(1); final double bz = b.getElementAtIndex(2); final AngularSpeed bx2 = new AngularSpeed( bx, AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed by2 = new AngularSpeed( by, AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bz2 = new AngularSpeed( bz, AngularSpeedUnit.RADIANS_PER_SECOND); fixer.setAngularSpeedBias(bx2, by2, bz2); // check final AngularSpeed bx3 = fixer.getAngularSpeedBiasXAsAngularSpeed(); final AngularSpeed by3 = fixer.getAngularSpeedBiasYAsAngularSpeed(); final AngularSpeed bz3 = fixer.getAngularSpeedBiasZAsAngularSpeed(); assertEquals(bx2, bx3); assertEquals(by2, by3); assertEquals(bz2, bz3); } @Test public void testGetSetAngularSpeedCrossCouplingErrors() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values final Matrix m1 = fixer.getAngularSpeedCrossCouplingErrors(); final Matrix m2 = new Matrix(1, 1); fixer.getAngularSpeedCrossCouplingErrors(m2); assertEquals(m1, new Matrix(3, 3)); assertEquals(m1, m2); // set new values final Matrix m3 = generateMg(); final double sx = m3.getElementAt(0, 0); final double sy = m3.getElementAt(1, 1); final double sz = m3.getElementAt(2, 2); final double mxy = m3.getElementAt(0, 1); final double mxz = m3.getElementAt(0, 2); final double myx = m3.getElementAt(1, 0); final double myz = m3.getElementAt(1, 2); final double mzx = m3.getElementAt(2, 0); final double mzy = m3.getElementAt(2, 1); fixer.setAngularSpeedCrossCouplingErrors(m3); // check final Matrix m4 = fixer.getAngularSpeedCrossCouplingErrors(); final Matrix m5 = new Matrix(3, 3); fixer.getAngularSpeedCrossCouplingErrors(m5); assertEquals(m3, m4); assertEquals(m3, m5); assertEquals(sx, fixer.getAngularSpeedSx(), 0.0); assertEquals(sy, fixer.getAngularSpeedSy(), 0.0); assertEquals(sz, fixer.getAngularSpeedSz(), 0.0); assertEquals(mxy, fixer.getAngularSpeedMxy(), 0.0); assertEquals(mxz, fixer.getAngularSpeedMxz(), 0.0); assertEquals(myx, fixer.getAngularSpeedMyx(), 0.0); assertEquals(myz, fixer.getAngularSpeedMyz(), 0.0); assertEquals(mzx, fixer.getAngularSpeedMzx(), 0.0); assertEquals(mzy, fixer.getAngularSpeedMzy(), 0.0); // Force IllegalArgumentException try { fixer.setAngularSpeedCrossCouplingErrors( new Matrix(1, 3)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { fixer.setAngularSpeedCrossCouplingErrors(new Matrix(3, 1)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } // Force AlgebraException try { final Matrix wrong = Matrix.identity(3, 3); wrong.multiplyByScalar(-1.0); fixer.setAngularSpeedCrossCouplingErrors(wrong); fail("AlgebraException expected but not thrown"); } catch (final AlgebraException ignore) { } } @Test public void testGetSetAngularSpeedSx() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAngularSpeedSx(), 0.0, 0.0); // set new value final Matrix m = generateMg(); final double sx = m.getElementAt(0, 0); fixer.setAngularSpeedSx(sx); // check assertEquals(sx, fixer.getAngularSpeedSx(), 0.0); } @Test public void testGetSetAngularSpeedSy() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAngularSpeedSy(), 0.0, 0.0); // set new value final Matrix m = generateMg(); final double sy = m.getElementAt(1, 1); fixer.setAngularSpeedSy(sy); // check assertEquals(sy, fixer.getAngularSpeedSy(), 0.0); } @Test public void testGetSetAngularSpeedSz() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAngularSpeedSz(), 0.0, 0.0); // set new value final Matrix m = generateMg(); final double sz = m.getElementAt(2, 2); fixer.setAngularSpeedSz(sz); // check assertEquals(sz, fixer.getAngularSpeedSz(), 0.0); } @Test public void testGetSetAngularSpeedMxy() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAngularSpeedMxy(), 0.0, 0.0); // set new value final Matrix m = generateMg(); final double mxy = m.getElementAt(0, 1); fixer.setAngularSpeedMxy(mxy); // check assertEquals(mxy, fixer.getAngularSpeedMxy(), 0.0); } @Test public void testGetSetAngularSpeedMxz() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAngularSpeedMxz(), 0.0, 0.0); // set new value final Matrix m = generateMg(); final double mxz = m.getElementAt(0, 2); fixer.setAngularSpeedMxz(mxz); // check assertEquals(mxz, fixer.getAngularSpeedMxz(), 0.0); } @Test public void testGetSetAngularSpeedMyx() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAngularSpeedMyx(), 0.0, 0.0); // set new value final Matrix m = generateMg(); final double myx = m.getElementAt(1, 0); fixer.setAngularSpeedMyx(myx); // check assertEquals(myx, fixer.getAngularSpeedMyx(), 0.0); } @Test public void testGetSetAngularSpeedMyz() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAngularSpeedMyz(), 0.0, 0.0); // set new value final Matrix m = generateMg(); final double myz = m.getElementAt(1, 2); fixer.setAngularSpeedMyz(myz); // check assertEquals(myz, fixer.getAngularSpeedMyz(), 0.0); } @Test public void testGetSetAngularSpeedMzx() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAngularSpeedMzx(), 0.0, 0.0); // set new value final Matrix m = generateMg(); final double mzx = m.getElementAt(2, 0); fixer.setAngularSpeedMzx(mzx); // check assertEquals(mzx, fixer.getAngularSpeedMzx(), 0.0); } @Test public void testGetSetAngularSpeedMzy() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default value assertEquals(fixer.getAngularSpeedMzy(), 0.0, 0.0); // set new value final Matrix m = generateMg(); final double mzy = m.getElementAt(2, 1); fixer.setAngularSpeedMzy(mzy); // check assertEquals(mzy, fixer.getAngularSpeedMzy(), 0.0); } @Test public void testSetAngularSpeedScalingFactors() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values assertEquals(fixer.getAngularSpeedSx(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedSy(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedSz(), 0.0, 0.0); // set new values final Matrix m = generateMg(); final double sx = m.getElementAt(0, 0); final double sy = m.getElementAt(1, 1); final double sz = m.getElementAt(2, 2); fixer.setAngularSpeedScalingFactors(sx, sy, sz); // check assertEquals(fixer.getAngularSpeedSx(), sx, 0.0); assertEquals(fixer.getAngularSpeedSy(), sy, 0.0); assertEquals(fixer.getAngularSpeedSz(), sz, 0.0); } @Test public void testSetAngularSpeedCrossCouplingErrors() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values assertEquals(fixer.getAngularSpeedMxy(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMxz(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMyx(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMyz(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMzx(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMzy(), 0.0, 0.0); // set new values final Matrix m = generateMg(); final double mxy = m.getElementAt(0, 1); final double mxz = m.getElementAt(0, 2); final double myx = m.getElementAt(1, 0); final double myz = m.getElementAt(1, 2); final double mzx = m.getElementAt(2, 0); final double mzy = m.getElementAt(2, 1); fixer.setAngularSpeedCrossCouplingErrors(mxy, mxz, myx, myz, mzx, mzy); // check assertEquals(mxy, fixer.getAngularSpeedMxy(), 0.0); assertEquals(mxz, fixer.getAngularSpeedMxz(), 0.0); assertEquals(myx, fixer.getAngularSpeedMyx(), 0.0); assertEquals(myz, fixer.getAngularSpeedMyz(), 0.0); assertEquals(mzx, fixer.getAngularSpeedMzx(), 0.0); assertEquals(mzy, fixer.getAngularSpeedMzy(), 0.0); } @Test public void testSetAngularSpeedScalingFactorsAndCrossCouplingErrors() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values assertEquals(fixer.getAngularSpeedSx(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedSy(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedSz(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMxy(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMxz(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMyx(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMyz(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMzx(), 0.0, 0.0); assertEquals(fixer.getAngularSpeedMzy(), 0.0, 0.0); // set new values final Matrix m = generateMg(); final double sx = m.getElementAt(0, 0); final double sy = m.getElementAt(1, 1); final double sz = m.getElementAt(2, 2); final double mxy = m.getElementAt(0, 1); final double mxz = m.getElementAt(0, 2); final double myx = m.getElementAt(1, 0); final double myz = m.getElementAt(1, 2); final double mzx = m.getElementAt(2, 0); final double mzy = m.getElementAt(2, 1); fixer.setAngularSpeedScalingFactorsAndCrossCouplingErrors(sx, sy, sz, mxy, mxz, myx, myz, mzx, mzy); // check assertEquals(fixer.getAngularSpeedSx(), sx, 0.0); assertEquals(fixer.getAngularSpeedSy(), sy, 0.0); assertEquals(fixer.getAngularSpeedSz(), sz, 0.0); assertEquals(mxy, fixer.getAngularSpeedMxy(), 0.0); assertEquals(mxz, fixer.getAngularSpeedMxz(), 0.0); assertEquals(myx, fixer.getAngularSpeedMyx(), 0.0); assertEquals(myz, fixer.getAngularSpeedMyz(), 0.0); assertEquals(mzx, fixer.getAngularSpeedMzx(), 0.0); assertEquals(mzy, fixer.getAngularSpeedMzy(), 0.0); } @Test public void testGetSetAngularSpeedGDependantCrossBias() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); // check default values final Matrix g1 = fixer.getAngularSpeedGDependantCrossBias(); final Matrix g2 = new Matrix(1, 1); fixer.getAngularSpeedGDependantCrossBias(g2); assertEquals(g1, new Matrix(3, 3)); assertEquals(g1, g2); // set new values final Matrix g3 = generateGg(); fixer.setAngularSpeedGDependantCrossBias(g3); // check final Matrix g4 = fixer.getAngularSpeedGDependantCrossBias(); final Matrix g5 = new Matrix(3, 3); fixer.getAngularSpeedGDependantCrossBias(g5); assertEquals(g3, g4); assertEquals(g3, g5); // Force IllegalArgumentException try { fixer.setAngularSpeedGDependantCrossBias( new Matrix(1, 3)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { fixer.setAngularSpeedGDependantCrossBias( new Matrix(3, 1)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testFix1() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); final Matrix ba = generateBa(); final Matrix bg = generateBg(); final Matrix ma = generateMa(); final Matrix mg = generateMg(); final Matrix gg = generateGg(); final double accelNoiseRootPSD = 0.0; final double gyroNoiseRootPSD = 0.0; final double accelQuantLevel = 0.0; final double gyroQuantLevel = 0.0; fixer.setAccelerationBias(ba); fixer.setAccelerationCrossCouplingErrors(ma); fixer.setAngularSpeedBias(bg); fixer.setAngularSpeedCrossCouplingErrors(mg); fixer.setAngularSpeedGDependantCrossBias(gg); final IMUErrors errors = new IMUErrors(ba, bg, ma, mg, gg, accelNoiseRootPSD, gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double fx = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double fy = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double fz = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double omegaX = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final double omegaY = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final double omegaZ = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final BodyKinematics trueKinematics = new BodyKinematics(fx, fy, fz, omegaX, omegaY, omegaZ); final BodyKinematics measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errors, new Random()); final BodyKinematics result = new BodyKinematics(); fixer.fix(measuredKinematics, result); // check assertTrue(result.equals(trueKinematics, ABSOLUTE_ERROR)); } @Test public void testFix2() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); final Matrix ba = generateBa(); final Matrix bg = generateBg(); final Matrix ma = generateMa(); final Matrix mg = generateMg(); final Matrix gg = generateGg(); final double accelNoiseRootPSD = 0.0; final double gyroNoiseRootPSD = 0.0; final double accelQuantLevel = 0.0; final double gyroQuantLevel = 0.0; fixer.setAccelerationBias(ba); fixer.setAccelerationCrossCouplingErrors(ma); fixer.setAngularSpeedBias(bg); fixer.setAngularSpeedCrossCouplingErrors(mg); fixer.setAngularSpeedGDependantCrossBias(gg); final IMUErrors errors = new IMUErrors(ba, bg, ma, mg, gg, accelNoiseRootPSD, gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double fx = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double fy = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double fz = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double omegaX = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final double omegaY = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final double omegaZ = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final BodyKinematics trueKinematics = new BodyKinematics(fx, fy, fz, omegaX, omegaY, omegaZ); final AccelerationTriad trueF = trueKinematics.getSpecificForceTriad(); final AngularSpeedTriad trueAngularSpeed = trueKinematics .getAngularRateTriad(); final BodyKinematics measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errors, new Random()); final AccelerationTriad measuredF = measuredKinematics .getSpecificForceTriad(); final AngularSpeedTriad measuredAngularSpeed = measuredKinematics .getAngularRateTriad(); final AccelerationTriad fixedF = new AccelerationTriad(); final AngularSpeedTriad fixedAngularSpeed = new AngularSpeedTriad(); fixer.fix(measuredF, measuredAngularSpeed, fixedF, fixedAngularSpeed); // check assertTrue(fixedF.equals(trueF, ABSOLUTE_ERROR)); assertTrue(fixedAngularSpeed.equals(trueAngularSpeed, ABSOLUTE_ERROR)); } @Test public void testFix3() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); final Matrix ba = generateBa(); final Matrix bg = generateBg(); final Matrix ma = generateMa(); final Matrix mg = generateMg(); final Matrix gg = generateGg(); final double accelNoiseRootPSD = 0.0; final double gyroNoiseRootPSD = 0.0; final double accelQuantLevel = 0.0; final double gyroQuantLevel = 0.0; fixer.setAccelerationBias(ba); fixer.setAccelerationCrossCouplingErrors(ma); fixer.setAngularSpeedBias(bg); fixer.setAngularSpeedCrossCouplingErrors(mg); fixer.setAngularSpeedGDependantCrossBias(gg); final IMUErrors errors = new IMUErrors(ba, bg, ma, mg, gg, accelNoiseRootPSD, gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double fx = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double fy = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double fz = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double omegaX = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final double omegaY = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final double omegaZ = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final BodyKinematics trueKinematics = new BodyKinematics(fx, fy, fz, omegaX, omegaY, omegaZ); final AccelerationTriad trueF = trueKinematics.getSpecificForceTriad(); final AngularSpeedTriad trueAngularSpeed = trueKinematics .getAngularRateTriad(); final BodyKinematics measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errors, new Random()); final AccelerationTriad fixedF = new AccelerationTriad(); final AngularSpeedTriad fixedAngularSpeed = new AngularSpeedTriad(); fixer.fix(measuredKinematics, fixedF, fixedAngularSpeed); // check assertTrue(fixedF.equals(trueF, ABSOLUTE_ERROR)); assertTrue(fixedAngularSpeed.equals(trueAngularSpeed, ABSOLUTE_ERROR)); } @Test public void testFix4() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); final Matrix ba = generateBa(); final Matrix bg = generateBg(); final Matrix ma = generateMa(); final Matrix mg = generateMg(); final Matrix gg = generateGg(); final double accelNoiseRootPSD = 0.0; final double gyroNoiseRootPSD = 0.0; final double accelQuantLevel = 0.0; final double gyroQuantLevel = 0.0; fixer.setAccelerationBias(ba); fixer.setAccelerationCrossCouplingErrors(ma); fixer.setAngularSpeedBias(bg); fixer.setAngularSpeedCrossCouplingErrors(mg); fixer.setAngularSpeedGDependantCrossBias(gg); final IMUErrors errors = new IMUErrors(ba, bg, ma, mg, gg, accelNoiseRootPSD, gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double fx = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double fy = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double fz = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double omegaX = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final double omegaY = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final double omegaZ = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final BodyKinematics trueKinematics = new BodyKinematics(fx, fy, fz, omegaX, omegaY, omegaZ); final BodyKinematics measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errors, new Random()); final AccelerationTriad measuredF = measuredKinematics .getSpecificForceTriad(); final AngularSpeedTriad measuredAngularSpeed = measuredKinematics .getAngularRateTriad(); final BodyKinematics result = new BodyKinematics(); fixer.fix(measuredF, measuredAngularSpeed, result); // check assertTrue(result.equals(trueKinematics, ABSOLUTE_ERROR)); } @Test public void fixAndReturnNew1() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); final Matrix ba = generateBa(); final Matrix bg = generateBg(); final Matrix ma = generateMa(); final Matrix mg = generateMg(); final Matrix gg = generateGg(); final double accelNoiseRootPSD = 0.0; final double gyroNoiseRootPSD = 0.0; final double accelQuantLevel = 0.0; final double gyroQuantLevel = 0.0; fixer.setAccelerationBias(ba); fixer.setAccelerationCrossCouplingErrors(ma); fixer.setAngularSpeedBias(bg); fixer.setAngularSpeedCrossCouplingErrors(mg); fixer.setAngularSpeedGDependantCrossBias(gg); final IMUErrors errors = new IMUErrors(ba, bg, ma, mg, gg, accelNoiseRootPSD, gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double fx = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double fy = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double fz = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double omegaX = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final double omegaY = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final double omegaZ = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final BodyKinematics trueKinematics = new BodyKinematics(fx, fy, fz, omegaX, omegaY, omegaZ); final BodyKinematics measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errors, new Random()); final BodyKinematics result = fixer.fixAndReturnNew(measuredKinematics); // check assertTrue(result.equals(trueKinematics, ABSOLUTE_ERROR)); } @Test public void fixAndReturnNew2() throws AlgebraException { final BodyKinematicsFixer fixer = new BodyKinematicsFixer(); final Matrix ba = generateBa(); final Matrix bg = generateBg(); final Matrix ma = generateMa(); final Matrix mg = generateMg(); final Matrix gg = generateGg(); final double accelNoiseRootPSD = 0.0; final double gyroNoiseRootPSD = 0.0; final double accelQuantLevel = 0.0; final double gyroQuantLevel = 0.0; fixer.setAccelerationBias(ba); fixer.setAccelerationCrossCouplingErrors(ma); fixer.setAngularSpeedBias(bg); fixer.setAngularSpeedCrossCouplingErrors(mg); fixer.setAngularSpeedGDependantCrossBias(gg); final IMUErrors errors = new IMUErrors(ba, bg, ma, mg, gg, accelNoiseRootPSD, gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double fx = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double fy = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double fz = randomizer.nextDouble(MIN_ACCELEROMETER_VALUE, MAX_ACCELEROMETER_VALUE); final double omegaX = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final double omegaY = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final double omegaZ = randomizer.nextDouble(MIN_GYRO_VALUE, MAX_GYRO_VALUE); final BodyKinematics trueKinematics = new BodyKinematics(fx, fy, fz, omegaX, omegaY, omegaZ); final BodyKinematics measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errors, new Random()); final AccelerationTriad measuredF = measuredKinematics .getSpecificForceTriad(); final AngularSpeedTriad measuredAngularSpeed = measuredKinematics .getAngularRateTriad(); final BodyKinematics result = fixer.fixAndReturnNew( measuredF, measuredAngularSpeed); // check assertTrue(result.equals(trueKinematics, ABSOLUTE_ERROR)); } private Matrix generateBa() { return Matrix.newFromArray(new double[]{ 900 * MICRO_G_TO_METERS_PER_SECOND_SQUARED, -1300 * MICRO_G_TO_METERS_PER_SECOND_SQUARED, 800 * MICRO_G_TO_METERS_PER_SECOND_SQUARED}); } private Matrix generateBg() { return Matrix.newFromArray(new double[]{ -9 * DEG_TO_RAD / 3600.0, 13 * DEG_TO_RAD / 3600.0, -8 * DEG_TO_RAD / 3600.0}); } private Matrix generateMa() throws WrongSizeException { final Matrix result = new Matrix(3, 3); result.fromArray(new double[]{ 500e-6, -300e-6, 200e-6, -150e-6, -600e-6, 250e-6, -250e-6, 100e-6, 450e-6 }, false); return result; } private Matrix generateMg() throws WrongSizeException { final Matrix result = new Matrix(3, 3); result.fromArray(new double[]{ 400e-6, -300e-6, 250e-6, 0.0, -300e-6, -150e-6, 0.0, 0.0, -350e-6 }, false); return result; } private Matrix generateGg() throws WrongSizeException { final Matrix result = new Matrix(3, 3); final double tmp = DEG_TO_RAD / (3600 * 9.80665); result.fromArray(new double[]{ 0.9 * tmp, -1.1 * tmp, -0.6 * tmp, -0.5 * tmp, 1.9 * tmp, -1.6 * tmp, 0.3 * tmp, 1.1 * tmp, -1.3 * tmp }, false); return result; } }
37.997779
88
0.651854
3ae2fd6a6af2a8212e58c7cbd82d1637655c5f8e
12,808
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.plan; import java.io.Serializable; import java.util.Set; import org.apache.hadoop.hive.ql.hooks.ReadEntity; import org.apache.hadoop.hive.ql.hooks.WriteEntity; public class DDLWork implements Serializable { private static final long serialVersionUID = 1L; private createTableDesc createTblDesc; private createTableLikeDesc createTblLikeDesc; private createViewDesc createVwDesc; private dropTableDesc dropTblDesc; private truncateTableDesc truncTblDesc; private alterTableDesc alterTblDesc; private showTablesDesc showTblsDesc; private showProcesslistDesc showprosDesc; private killqueryDesc kqueryDesc; private showqueryDesc squeryDesc; private clearqueryDesc clearDesc; private showInfoDesc infoDesc; private showTableSizeDesc tablesizedesc; private showDatabaseSizeDesc dbsizedesc; private showRowCountDesc rowcountdesc; private showFunctionsDesc showFuncsDesc; private descFunctionDesc descFunctionDesc; private showPartitionsDesc showPartsDesc; private descTableDesc descTblDesc; private AddPartitionDesc addPartitionDesc; private MsckDesc msckDesc; private execExtSQLDesc execsqldesc; private showViewTablesDesc viewTablesDesc; private addDefaultPartitionDesc addDefaultPartDesc; private truncatePartitionDesc truncatePartDesc; private alterCommentDesc alterComDesc; private createDatabaseDesc createDbDesc; private dropDatabaseDesc dropDbDesc; private useDatabaseDesc useDbDesc; private showDBDesc showDbDesc; private showIndexDesc showIndexsDesc; private showCreateTableDesc showCT; private showVersionDesc versionDesc; private Set<ReadEntity> inputs; private Set<WriteEntity> outputs; public DDLWork() { } public DDLWork(showVersionDesc versionDesc) { super(); this.versionDesc = versionDesc; } public showVersionDesc getVersionDesc() { return versionDesc; } public DDLWork(createDatabaseDesc createDbDesc) { super(); this.createDbDesc = createDbDesc; } public DDLWork(execExtSQLDesc execExtSQLdesc) { super(); this.execsqldesc = execExtSQLdesc; } public DDLWork(showViewTablesDesc vtdesc) { super(); this.viewTablesDesc = vtdesc; } public DDLWork(showCreateTableDesc showCT) { super(); this.showCT = showCT; } public showCreateTableDesc getShowCT() { return showCT; } public void setShowCT(showCreateTableDesc showCT) { this.showCT = showCT; } public DDLWork(showDBDesc desc) { super(); this.showDbDesc = desc; } public showDBDesc getShowDbDesc() { return showDbDesc; } public void setShowDbDesc(showDBDesc showDbDesc) { this.showDbDesc = showDbDesc; } public useDatabaseDesc getUseDbDesc() { return useDbDesc; } public void setUseDbDesc(useDatabaseDesc useDbDesc) { this.useDbDesc = useDbDesc; } public DDLWork(useDatabaseDesc useDbDesc) { super(); this.useDbDesc = useDbDesc; } public createDatabaseDesc getCreateDbDesc() { return createDbDesc; } public void setCreateDbDesc(createDatabaseDesc createDbDesc) { this.createDbDesc = createDbDesc; } public dropDatabaseDesc getDropDbDesc() { return dropDbDesc; } public void setDropDbDesc(dropDatabaseDesc dropDbDesc) { this.dropDbDesc = dropDbDesc; } public DDLWork(dropDatabaseDesc dropDbDesc) { super(); this.dropDbDesc = dropDbDesc; } public DDLWork(alterTableDesc alterTblDesc) { this.alterTblDesc = alterTblDesc; } public DDLWork(truncatePartitionDesc tpd) { this.truncatePartDesc = tpd; } public truncatePartitionDesc getTruncatePartDesc() { return truncatePartDesc; } public void setTruncatePartDesc(truncatePartitionDesc truncatePartDesc) { this.truncatePartDesc = truncatePartDesc; } public DDLWork(addDefaultPartitionDesc adpd) { this.addDefaultPartDesc = adpd; } public DDLWork(createTableDesc createTblDesc) { this.createTblDesc = createTblDesc; } public DDLWork(createTableLikeDesc createTblLikeDesc) { this.createTblLikeDesc = createTblLikeDesc; } public DDLWork(alterCommentDesc acd) { this.alterComDesc = acd; } public alterCommentDesc getAlterCommentDesc() { return this.alterComDesc; } public void setAlterCommentDesc(alterCommentDesc acd) { this.alterComDesc = acd; } public DDLWork(Set<ReadEntity> inputs, Set<WriteEntity> outputs, createViewDesc createVwDesc) { this(inputs, outputs); this.createVwDesc = createVwDesc; } public execExtSQLDesc getExecsqldesc() { return execsqldesc; } public void setExecsqldesc(execExtSQLDesc execsqldesc) { this.execsqldesc = execsqldesc; } public showViewTablesDesc getViewTablesDesc() { return viewTablesDesc; } public void setViewTablesDesc(showViewTablesDesc viewTablesDesc) { this.viewTablesDesc = viewTablesDesc; } public DDLWork(dropTableDesc dropTblDesc) { this.dropTblDesc = dropTblDesc; } public DDLWork(truncateTableDesc truncTblDesc) { this.truncTblDesc = truncTblDesc; } public DDLWork(descTableDesc descTblDesc) { this.descTblDesc = descTblDesc; } public DDLWork(showTablesDesc showTblsDesc) { this.showTblsDesc = showTblsDesc; } public DDLWork(showProcesslistDesc showprosDesc) { this.showprosDesc = showprosDesc; } public DDLWork(killqueryDesc kq) { this.kqueryDesc = new killqueryDesc(kq.getQueryId()); } public DDLWork(showqueryDesc sq) { this.squeryDesc = new showqueryDesc(sq.getQueryId(), sq.getResFile()); } public DDLWork(clearqueryDesc cq) { this.clearDesc = cq; } public DDLWork(showInfoDesc info) { this.infoDesc = info; } public DDLWork(showTableSizeDesc ssize) { this.tablesizedesc = ssize; } public DDLWork(showDatabaseSizeDesc dbsize) { this.dbsizedesc = dbsize; } public DDLWork(showRowCountDesc rcount) { this.rowcountdesc = rcount; } public DDLWork(showFunctionsDesc showFuncsDesc) { this.showFuncsDesc = showFuncsDesc; } public DDLWork(descFunctionDesc descFuncDesc) { this.descFunctionDesc = descFuncDesc; } public DDLWork(showPartitionsDesc showPartsDesc) { this.showPartsDesc = showPartsDesc; } public DDLWork(AddPartitionDesc addPartitionDesc) { this.addPartitionDesc = addPartitionDesc; } public DDLWork(MsckDesc checkDesc) { this.msckDesc = checkDesc; } @explain(displayName = "Create Table Operator") public createTableDesc getCreateTblDesc() { return createTblDesc; } public void setCreateTblDesc(createTableDesc createTblDesc) { this.createTblDesc = createTblDesc; } @explain(displayName = "Create Table Operator") public createTableLikeDesc getCreateTblLikeDesc() { return createTblLikeDesc; } public void setCreateTblLikeDesc(createTableLikeDesc createTblLikeDesc) { this.createTblLikeDesc = createTblLikeDesc; } @explain(displayName = "Create View Operator") public createViewDesc getCreateViewDesc() { return createVwDesc; } public void setCreateViewDesc(createViewDesc createVwDesc) { this.createVwDesc = createVwDesc; } @explain(displayName = "Drop Table Operator") public dropTableDesc getDropTblDesc() { return dropTblDesc; } public void setDropTblDesc(dropTableDesc dropTblDesc) { this.dropTblDesc = dropTblDesc; } @explain(displayName = "Truncate Table Operator") public truncateTableDesc getTruncTblDesc() { return truncTblDesc; } public void setTruncTblDesc(truncateTableDesc truncTblDesc) { this.truncTblDesc = truncTblDesc; } @explain(displayName = "Alter Table Operator") public alterTableDesc getAlterTblDesc() { return alterTblDesc; } public void setAlterTblDesc(alterTableDesc alterTblDesc) { this.alterTblDesc = alterTblDesc; } @explain(displayName = "Show Table Operator") public showTablesDesc getShowTblsDesc() { return showTblsDesc; } public void setShowTblsDesc(showTablesDesc showTblsDesc) { this.showTblsDesc = showTblsDesc; } @explain(displayName = "Show Processlist Operator") public showProcesslistDesc getShowProcesslistDesc() { return showprosDesc; } public killqueryDesc getKillQueryDesc() { return kqueryDesc; } public showqueryDesc getShowQueryDesc() { return squeryDesc; } public clearqueryDesc getClearQueryDesc() { return clearDesc; } public showInfoDesc getShowInfoDesc() { return infoDesc; } public showTableSizeDesc getShowTableSizeDesc() { return tablesizedesc; } public showDatabaseSizeDesc getShowDatabaseSizeDesc() { return dbsizedesc; } public showRowCountDesc getShowRowCountDesc() { return rowcountdesc; } public void setShowTblsDesc(showProcesslistDesc showprosDesc) { this.showprosDesc = showprosDesc; } public void setKillQueryDesc(killqueryDesc in) { this.kqueryDesc = in; } public void setShowQueryDesc(showqueryDesc in) { this.squeryDesc = in; } public void setClearQueryDesc(clearqueryDesc in) { this.clearDesc = in; } public void setShowInfoDesc(showInfoDesc ss) { this.infoDesc = ss; } public void setShowTableSizeDesc(showTableSizeDesc ss) { this.tablesizedesc = ss; } public void setShowDatabaseSizeDesc(showDatabaseSizeDesc ss) { this.dbsizedesc = ss; } public void setShowRowCountDesc(showRowCountDesc ssss) { this.rowcountdesc = ssss; } @explain(displayName = "Show Function Operator") public showFunctionsDesc getShowFuncsDesc() { return showFuncsDesc; } @explain(displayName = "Show Function Operator") public descFunctionDesc getDescFunctionDesc() { return descFunctionDesc; } public void setShowFuncsDesc(showFunctionsDesc showFuncsDesc) { this.showFuncsDesc = showFuncsDesc; } public void setDescFuncDesc(descFunctionDesc descFuncDesc) { this.descFunctionDesc = descFuncDesc; } @explain(displayName = "Show Partitions Operator") public showPartitionsDesc getShowPartsDesc() { return showPartsDesc; } public void setShowPartsDesc(showPartitionsDesc showPartsDesc) { this.showPartsDesc = showPartsDesc; } @explain(displayName = "Describe Table Operator") public descTableDesc getDescTblDesc() { return descTblDesc; } public void setDescTblDesc(descTableDesc descTblDesc) { this.descTblDesc = descTblDesc; } public AddPartitionDesc getAddPartitionDesc() { return addPartitionDesc; } public void setAddPartitionDesc(AddPartitionDesc addPartitionDesc) { this.addPartitionDesc = addPartitionDesc; } public DDLWork(showIndexDesc showIndexsDesc) { this.showIndexsDesc = showIndexsDesc; } public DDLWork(Set<ReadEntity> inputs, Set<WriteEntity> outputs) { this.inputs = inputs; this.outputs = outputs; } public DDLWork(Set<ReadEntity> inputs, Set<WriteEntity> outputs, alterTableDesc alterTblDesc) { this(inputs, outputs); this.alterTblDesc = alterTblDesc; } public DDLWork(Set<ReadEntity> inputs, Set<WriteEntity> outputs, createTableDesc crtTblDesc) { this.inputs = inputs; this.outputs = outputs; this.createTblDesc = crtTblDesc; } public DDLWork(Set<ReadEntity> inputs, Set<WriteEntity> outputs, createTableLikeDesc crtTblLikeDesc) { this.inputs = inputs; this.outputs = outputs; this.createTblLikeDesc = crtTblLikeDesc; } public showIndexDesc getShowIndexDesc() { return showIndexsDesc; } public void setShowIndexDesc(showIndexDesc showIndexsDesc) { this.showIndexsDesc = showIndexsDesc; } public MsckDesc getMsckDesc() { return msckDesc; } public void setMsckDesc(MsckDesc msckDesc) { this.msckDesc = msckDesc; } public addDefaultPartitionDesc getAddDefaultPartDesc() { return addDefaultPartDesc; } public void setAddDefaultPartDesc(addDefaultPartitionDesc addDefaultPartDesc) { this.addDefaultPartDesc = addDefaultPartDesc; } }
24.773694
81
0.745628
26a4f9279408800d80af2f5c4987915248ef667a
183
package cn.myperf4j.base.util; /** * Created by LinShunkang on 2019/04/05 */ public interface SysProperties { String LINE_SEPARATOR = System.getProperty("line.separator"); }
16.636364
65
0.726776
50b1fb90abe9c0e992d60c55715e5c38104b8cfd
2,043
/* * Copyright 2010-2011 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 cn.lhfei.hadoop.ch08; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.SequenceFile.CompressionType; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * @version 0.1 * * @author Hefei Li * * @since May 10, 2015 */ public class SortByTemperatureUsingHashPartitioner extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Job job = JobBuilder.parseInputAndOutput(this, getConf(), args); if (job == null) { return -1; } job.setInputFormatClass(SequenceFileInputFormat.class); job.setOutputKeyClass(IntWritable.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); SequenceFileOutputFormat.setCompressOutput(job, true); SequenceFileOutputFormat.setOutputCompressorClass(job, GzipCodec.class); SequenceFileOutputFormat.setOutputCompressionType(job, CompressionType.BLOCK); return job.waitForCompletion(true) ? 0 : 1; } public static void main(String[] args) throws Exception { int exitCode = ToolRunner.run( new SortByTemperatureUsingHashPartitioner(), args); System.exit(exitCode); } }
32.428571
80
0.770436
40733c8ef0579408a829ec8a9c1e5a4172e5c10c
5,448
/* * Copyright 2018-2021 Ki11er_wolf * * 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.ki11erwolf.resynth.item; import com.ki11erwolf.resynth.block.ResynthBlocks; import com.ki11erwolf.resynth.config.ResynthConfig; import com.ki11erwolf.resynth.config.categories.MineralCrystalConfig; import com.ki11erwolf.resynth.util.CommonRKeys; import com.ki11erwolf.resynth.util.CommonTooltips; import com.ki11erwolf.resynth.util.ExpandingTooltip; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUseContext; import net.minecraft.util.ActionResultType; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import javax.annotation.Nullable; import java.util.List; /** * The item class for the Mineral Crystal item. * * <p/>This class exists mainly to provide the * "emergency" dirt/grass to Mineral Soil * conversion functionality. */ class ItemMineralCrystal extends ResynthItem<ItemMineralCrystal> { /** * Configuration settings for this item class. */ private static final MineralCrystalConfig CONFIG = ResynthConfig.GENERAL_CONFIG.getCategory(MineralCrystalConfig.class); /** * The name of the item given to its constructor. */ private final String name; /** * Constructs a new Mineral Crystal item. * * @param name the registry name of the item. */ ItemMineralCrystal(String name) { super(name); this.name = name; } /** * {@inheritDoc}. * * <br>Sets the tooltip for this item from the lang files. * Will also display a message if emergency conversion * mode is enabled from the config. */ @Override public void addInformation(ItemStack stack, @Nullable World world, List<ITextComponent> tooltip, ITooltipFlag flagIn) { new ExpandingTooltip().setCollapsedTooltip(null).setExpandedTooltip(CommonTooltips.NEW_LINE).setCondition( CONFIG.isECMEnabled() && CommonRKeys.SHIFT.rKey.query() ).write(tooltip); if(CONFIG.isECMEnabled()) tooltip.add(getFormattedTooltip(name + ".ecm", TextFormatting.DARK_PURPLE)); super.addInformation(stack, world, tooltip, flagIn); } /** * Called when the item is used (right-clicked) while * targeting a block. * * <p/>This is used, when enabled, to turn dirt/grass * DIRECTLY into Mineral Soil WITHOUT ANYTHING ELSE. * That is, this method will JUST do the conversion, * without any extras that are not required to complete * the task. * * <p/>This method is used in cases where the Mineral Hoe * is broken and Mineral Soil cannot otherwise be obtained. * * <p/>Which is why it is VITAL that this method simply performs * the task at hand and does not attempt anything else. * * @param context the context in which the item was used. * @return the result of using the item (pass/fail). */ @Override public ActionResultType onItemUse(ItemUseContext context) { ActionResultType result; //Do change if can if(CONFIG.isECMEnabled()){ World world = context.getWorld(); BlockPos pos = context.getPos(); BlockState source = world.getBlockState(pos); //Do change result = doChange(world, pos, source); } else result = ActionResultType.FAIL; //If the block was replaced and the player is in survival, //shrink the item stack used to do the replace if(result == ActionResultType.SUCCESS) if(context.getPlayer() != null && !context.getPlayer().isCreative()) context.getItem().shrink(1); return result; } /** * An extremely minimal way of turning dirt or grass * into Mineral Soil. This simply does the block change * if it can, otherwise it returns. * * @param world the world. * @param pos the block position of the block to replace. * @param source the block we're replacing. * @return {@link ActionResultType#SUCCESS} if the block * was replaced, {@link ActionResultType#FAIL} if the block * was NOT replaced. */ private ActionResultType doChange(World world, BlockPos pos, BlockState source){ //If block is grass or dirt. if(source.getBlock() == Blocks.DIRT || source.getBlock() == Blocks.GRASS_BLOCK){ //Change block to mineral soil. world.setBlockState(pos, ResynthBlocks.BLOCK_MINERAL_SOIL.getDefaultState()); return ActionResultType.SUCCESS; } //Else do nothing return ActionResultType.FAIL; } }
35.376623
114
0.68025
83628a7cab02e4494092c3405d8a285c745748ca
2,758
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.v7.cardview; public final class R { public static final class attr { public static int cardBackgroundColor = 0x7f040058; public static int cardCornerRadius = 0x7f040059; public static int cardElevation = 0x7f04005a; public static int cardMaxElevation = 0x7f04005b; public static int cardPreventCornerOverlap = 0x7f04005c; public static int cardUseCompatPadding = 0x7f04005d; public static int contentPadding = 0x7f040087; public static int contentPaddingBottom = 0x7f040088; public static int contentPaddingLeft = 0x7f040089; public static int contentPaddingRight = 0x7f04008a; public static int contentPaddingTop = 0x7f04008b; } public static final class color { public static int cardview_dark_background = 0x7f06002a; public static int cardview_light_background = 0x7f06002b; public static int cardview_shadow_end_color = 0x7f06002c; public static int cardview_shadow_start_color = 0x7f06002d; } public static final class dimen { public static int cardview_compat_inset_shadow = 0x7f08004f; public static int cardview_default_elevation = 0x7f080050; public static int cardview_default_radius = 0x7f080051; } public static final class style { public static int Base_CardView = 0x7f16000a; public static int CardView = 0x7f1600a1; public static int CardView_Dark = 0x7f1600a2; public static int CardView_Light = 0x7f1600a3; } public static final class styleable { public static int[] CardView = { 0x01010140, 0x0101013f, 0x7f040058, 0x7f040059, 0x7f04005a, 0x7f04005b, 0x7f04005c, 0x7f04005d, 0x7f040087, 0x7f040088, 0x7f040089, 0x7f04008a, 0x7f04008b }; public static int CardView_android_minHeight = 0; public static int CardView_android_minWidth = 1; public static int CardView_cardBackgroundColor = 2; public static int CardView_cardCornerRadius = 3; public static int CardView_cardElevation = 4; public static int CardView_cardMaxElevation = 5; public static int CardView_cardPreventCornerOverlap = 6; public static int CardView_cardUseCompatPadding = 7; public static int CardView_contentPadding = 8; public static int CardView_contentPaddingBottom = 9; public static int CardView_contentPaddingLeft = 10; public static int CardView_contentPaddingRight = 11; public static int CardView_contentPaddingTop = 12; } }
48.385965
198
0.725163
4871b1131b6adc7ef734049abdbc98b5f114bbef
377
/** * @author: Gadigeppa Muthu * @date: 27-Apr-2020 * * Question: Given two integers, write a function that swaps them without using any temporary variables. * **/ public class SwapVariablesSolution{ public static void main(String[] args){ int a = 5; int b = 3; a = a ^ b; b = a ^ b; a = a ^ b; System.out.println("a: " + a + ", b: " + b ); } }
12.566667
103
0.578249
74b08993bfb1fdba8411060b5ada03a7cb482651
2,085
package org.opencb.opencga.storage.hadoop.variant.metadata; import org.apache.hadoop.conf.Configuration; import org.opencb.opencga.storage.core.exceptions.StorageEngineException; import org.opencb.opencga.storage.core.metadata.models.Lock; import org.opencb.opencga.storage.core.metadata.adaptors.SampleMetadataDBAdaptor; import org.opencb.opencga.storage.core.metadata.models.SampleMetadata; import org.opencb.opencga.storage.hadoop.utils.HBaseManager; import java.util.Iterator; import static org.opencb.opencga.storage.hadoop.variant.metadata.HBaseVariantMetadataUtils.*; /** * Created by jacobo on 20/01/19. */ public class HBaseSampleMetadataDBAdaptor extends AbstractHBaseDBAdaptor implements SampleMetadataDBAdaptor { public HBaseSampleMetadataDBAdaptor(HBaseManager hBaseManager, String metaTableName, Configuration configuration) { super(hBaseManager, metaTableName, configuration); } @Override public SampleMetadata getSampleMetadata(int studyId, int sampleId, Long timeStamp) { return readValue(getSampleMetadataRowKey(studyId, sampleId), SampleMetadata.class, timeStamp); } @Override public void updateSampleMetadata(int studyId, SampleMetadata sample, Long timeStamp) { putValue(getSampleNameIndexRowKey(studyId, sample.getName()), HBaseVariantMetadataUtils.Type.INDEX, sample.getId(), timeStamp); putValue(getSampleMetadataRowKey(studyId, sample.getId()), HBaseVariantMetadataUtils.Type.SAMPLE, sample, timeStamp); } @Override public Iterator<SampleMetadata> sampleMetadataIterator(int studyId) { return iterator(getSampleMetadataRowKeyPrefix(studyId), SampleMetadata.class, false); } @Override public Integer getSampleId(int studyId, String sampleName) { return readValue(getSampleNameIndexRowKey(studyId, sampleName), Integer.class, null); } @Override public Lock lock(int studyId, int id, long lockDuration, long timeout) throws StorageEngineException { return lock(getSampleMetadataRowKey(studyId, id), lockDuration, timeout); } }
42.55102
135
0.783693
94804ede76f24d5a467008f61b79dd82dc64938b
5,154
package us.ilite.robot; public class Enums { public enum EClimberMode { VELOCITY, POSITION, PERCENT_OUTPUT, BEGIN_HANG, DEFAULT } public enum ERungState { NULL, // Driver activates move to initial position GROUND, // Grab the mid bar. Operator pushes button to enter this state. //Automated go to high bar GO_TO_HIGH_BAR, TRAVEL_TILL_HIT_HIGH, GRAB_HIGH_BAR, // Operator pushes button to enter this state. // Balancing while grabbing both Mid and High. Drives the climber in reverse. BALANCING, // Automated entry. // Release double claw after we're balanced. Should be 1 cycle or so. RELEASING_MID, // Automated entry. // Go to traversal position. Keep double claw released during this time MOVE_TO_TRAVERSAL, // Automated entry. // Close double claw, stay in this state until driver pushes button GRAB_TRAVERSAL, // Driver pushes the button to enter this state. // Open single claw. RELEASE_HIGH, // Autoated entry after N seconds of RELEASE_HIGH state // Move to final traversal position. FINAL_LIFT } public enum EClampMode { NULL, CLAMPED, RELEASED } public enum EClimberAngle { //Angles at desired rung //At last test at playground //high at 104, traversal is 277, final lift is 150 NULL(0.0), MID(-90.0), HIGH(102.0), BALANCED(41.0), TRAVERSAL(277.0), FINAL_LIFT(150), SCORE(250.0); //Old traversal angle is 287.5 final double kAngle; EClimberAngle(double pAngle) { kAngle = pAngle; } public double getAngle() { return kAngle; } } // ============================ ================================================= // Limelight States // ============================================================================= // Limelight LED state // 0 - Use Pipeline LED state // 1 - Force LED off // 2 - Force LED blink // 3 - Force LED on public enum LimelightLedMode { NO_CHANGE, LED_OFF, LED_BLINK, LED_ON; } // LED control and colors public enum LEDColorMode { NULL( 0, 0, 0 ), DEFAULT( 0, 0, 0 ), PURPLE( 125, 0, 250 ), RED( 255, 0, 0 ), WHITE( 255, 255, 255 ), GREEN( 0, 255, 0 ), YELLOW( 255, 255, 0 ), BLUE( 0, 0, 255 ), ORANGE( 255, 165, 0 ); double red; double green; double blue; LEDColorMode(double pR, double pG, double pB) { red = pR; green = pG; blue = pB; } public double getRed() { return red; } public double getGreen() { return green; } public double getBlue() { return blue; } // Color clr = new Color(red, green, blue); // // public Color getColor() { // return this.clr; // } } public enum LEDState { NULL, BLINKING, SOLID; } // Limelight camera mode // 0 - Vision Processor // 1 - Driver Camera (Increases exposure, disables vision processing) public enum LimelightCamMode { VISION_PROCESSOR, DRIVER_CAMERA; } // Limelight stream mode // 0 - Standard - Side-by-side streams if a webcam is attached to Limelight // 1 - PiP Main - The secondary camera stream is placed in the lower-right corner of the primary camera stream // 2 - PiP Secondary - The primary camera stream is placed in the lower-right corner of the secondary camera stream public enum LimelightStreamMode { STANDARD, PIP_MAIN, PIP_SECONDARY; } // Limelight snapshot state // 0 - Stop taking snapshots // 1 - Take two snapshots per second public enum LimelightSnapshotMode { STOP_SNAPSHOTS, START_SNAPSHOTS; } // ============================================================================= // Drivetrain States // ============================================================================= public enum EDriveState { NULL, RESET, RESET_ODOMETRY, PATH_FOLLOWING_BASIC, PATH_FOLLOWING_RAMSETE, TARGET_ANGLE_LOCK, HOLD, VELOCITY, PERCENT_OUTPUT, POSITION, SMART_MOTION, TURN_TO, } // ============================================================================= // Intake Module States // ============================================================================= public enum ERollerState { NULL, PERCENT_OUTPUT, VELOCITY; } public enum EArmState { NULL, EXTEND, RETRACT, DEFAULT; } public enum EFeederState { NULL, PERCENT_OUTPUT, VELOCITY; } }
25.141463
119
0.496702
3c5d1b2f343c26467f2880890ed9c8071a93d81d
497
/* * Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved. */ package com.aqua.services.fixtures; import jsystem.framework.fixture.Fixture; public class ParentExampleFixture extends Fixture { public ParentExampleFixture() { } public void setUp() throws Exception { report.step(" in parent example fixture setup"); } public void tearDown() throws Exception { report.step(" in parent example fixture tearDown"); } public void failTearDown() throws Exception { } }
19.88
69
0.742455
e69b050bee2f60d6b0d6f937fb62d60276e09086
41,994
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.google.android.gms.internal.ads; import android.content.Context; import android.util.JsonWriter; import com.google.android.gms.common.util.*; import java.io.IOException; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.*; // Referenced classes of package com.google.android.gms.internal.ads: // zzane, zzand, zzamu, zzamz, // zzana, zznk, zzkb, zzni, // zzanc, zzanb public final class zzamy { public zzamy() { this(((String) (null))); // 0 0:aload_0 // 1 1:aconst_null // 2 2:invokespecial #55 <Method void zzamy(String)> // 3 5:return } public zzamy(String s) { // 0 0:aload_0 // 1 1:invokespecial #26 <Method void Object()> if(!isEnabled()) //* 2 4:invokestatic #60 <Method boolean isEnabled()> //* 3 7:ifne 21 { s = ((String) (new ArrayList())); // 4 10:new #62 <Class ArrayList> // 5 13:dup // 6 14:invokespecial #63 <Method void ArrayList()> // 7 17:astore_1 } else //* 8 18:goto 159 { String s1 = UUID.randomUUID().toString(); // 9 21:invokestatic #69 <Method UUID UUID.randomUUID()> // 10 24:invokevirtual #73 <Method String UUID.toString()> // 11 27:astore_2 if(s == null) //* 12 28:aload_1 //* 13 29:ifnonnull 79 { s = String.valueOf(((Object) (s1))); // 14 32:aload_2 // 15 33:invokestatic #77 <Method String String.valueOf(Object)> // 16 36:astore_1 if(s.length() != 0) //* 17 37:aload_1 //* 18 38:invokevirtual #81 <Method int String.length()> //* 19 41:ifeq 54 s = "network_request_".concat(s); // 20 44:ldc1 #83 <String "network_request_"> // 21 46:aload_1 // 22 47:invokevirtual #87 <Method String String.concat(String)> // 23 50:astore_1 else //* 24 51:goto 64 s = new String("network_request_"); // 25 54:new #40 <Class String> // 26 57:dup // 27 58:ldc1 #83 <String "network_request_"> // 28 60:invokespecial #88 <Method void String(String)> // 29 63:astore_1 s = ((String) (Arrays.asList(((Object []) (new String[] { s }))))); // 30 64:iconst_1 // 31 65:anewarray String[] // 32 68:dup // 33 69:iconst_0 // 34 70:aload_1 // 35 71:aastore // 36 72:invokestatic #46 <Method List Arrays.asList(Object[])> // 37 75:astore_1 } else //* 38 76:goto 159 { s = String.valueOf(((Object) (s))); // 39 79:aload_1 // 40 80:invokestatic #77 <Method String String.valueOf(Object)> // 41 83:astore_1 if(s.length() != 0) //* 42 84:aload_1 //* 43 85:invokevirtual #81 <Method int String.length()> //* 44 88:ifeq 101 s = "ad_request_".concat(s); // 45 91:ldc1 #90 <String "ad_request_"> // 46 93:aload_1 // 47 94:invokevirtual #87 <Method String String.concat(String)> // 48 97:astore_1 else //* 49 98:goto 111 s = new String("ad_request_"); // 50 101:new #40 <Class String> // 51 104:dup // 52 105:ldc1 #90 <String "ad_request_"> // 53 107:invokespecial #88 <Method void String(String)> // 54 110:astore_1 s1 = String.valueOf(((Object) (s1))); // 55 111:aload_2 // 56 112:invokestatic #77 <Method String String.valueOf(Object)> // 57 115:astore_2 if(s1.length() != 0) //* 58 116:aload_2 //* 59 117:invokevirtual #81 <Method int String.length()> //* 60 120:ifeq 133 s1 = "network_request_".concat(s1); // 61 123:ldc1 #83 <String "network_request_"> // 62 125:aload_2 // 63 126:invokevirtual #87 <Method String String.concat(String)> // 64 129:astore_2 else //* 65 130:goto 143 s1 = new String("network_request_"); // 66 133:new #40 <Class String> // 67 136:dup // 68 137:ldc1 #83 <String "network_request_"> // 69 139:invokespecial #88 <Method void String(String)> // 70 142:astore_2 s = ((String) (Arrays.asList(((Object []) (new String[] { s, s1 }))))); // 71 143:iconst_2 // 72 144:anewarray String[] // 73 147:dup // 74 148:iconst_0 // 75 149:aload_1 // 76 150:aastore // 77 151:dup // 78 152:iconst_1 // 79 153:aload_2 // 80 154:aastore // 81 155:invokestatic #46 <Method List Arrays.asList(Object[])> // 82 158:astore_1 } } zzcuz = ((List) (s)); // 83 159:aload_0 // 84 160:aload_1 // 85 161:putfield #92 <Field List zzcuz> // 86 164:return } public static boolean isEnabled() { Object obj = sLock; // 0 0:getstatic #28 <Field Object sLock> // 1 3:astore_1 obj; // 2 4:aload_1 JVM INSTR monitorenter ; // 3 5:monitorenter boolean flag; Exception exception; if(zzcuv && zzcuw) //* 4 6:getstatic #95 <Field boolean zzcuv> //* 5 9:ifeq 32 //* 6 12:getstatic #97 <Field boolean zzcuw> //* 7 15:ifeq 32 flag = true; // 8 18:iconst_1 // 9 19:istore_0 else //* 10 20:goto 23 //* 11 23:aload_1 //* 12 24:monitorexit //* 13 25:iload_0 //* 14 26:ireturn //* 15 27:astore_2 //* 16 28:aload_1 //* 17 29:monitorexit //* 18 30:aload_2 //* 19 31:athrow flag = false; // 20 32:iconst_0 // 21 33:istore_0 obj; JVM INSTR monitorexit ; return flag; exception; obj; JVM INSTR monitorexit ; throw exception; //* 22 34:goto 23 } static final void zza(int i, Map map, JsonWriter jsonwriter) throws IOException { jsonwriter.name("params").beginObject(); // 0 0:aload_2 // 1 1:ldc1 #103 <String "params"> // 2 3:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 3 6:invokevirtual #113 <Method JsonWriter JsonWriter.beginObject()> // 4 9:pop jsonwriter.name("firstline").beginObject(); // 5 10:aload_2 // 6 11:ldc1 #115 <String "firstline"> // 7 13:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 8 16:invokevirtual #113 <Method JsonWriter JsonWriter.beginObject()> // 9 19:pop jsonwriter.name("code").value(i); // 10 20:aload_2 // 11 21:ldc1 #117 <String "code"> // 12 23:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 13 26:iload_0 // 14 27:i2l // 15 28:invokevirtual #120 <Method JsonWriter JsonWriter.value(long)> // 16 31:pop jsonwriter.endObject(); // 17 32:aload_2 // 18 33:invokevirtual #123 <Method JsonWriter JsonWriter.endObject()> // 19 36:pop zza(jsonwriter, map); // 20 37:aload_2 // 21 38:aload_1 // 22 39:invokestatic #126 <Method void zza(JsonWriter, Map)> jsonwriter.endObject(); // 23 42:aload_2 // 24 43:invokevirtual #123 <Method JsonWriter JsonWriter.endObject()> // 25 46:pop // 26 47:return } private static void zza(JsonWriter jsonwriter, Map map) throws IOException { label0: { if(map == null) //* 0 0:aload_1 //* 1 1:ifnonnull 5 return; // 2 4:return jsonwriter.name("headers").beginArray(); // 3 5:aload_0 // 4 6:ldc1 #129 <String "headers"> // 5 8:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 6 11:invokevirtual #132 <Method JsonWriter JsonWriter.beginArray()> // 7 14:pop map = ((Map) (map.entrySet().iterator())); // 8 15:aload_1 // 9 16:invokeinterface #138 <Method Set Map.entrySet()> // 10 21:invokeinterface #144 <Method Iterator Set.iterator()> // 11 26:astore_1 do { String s; Object obj; do { if(!((Iterator) (map)).hasNext()) break label0; // 12 27:aload_1 // 13 28:invokeinterface #149 <Method boolean Iterator.hasNext()> // 14 33:ifeq 211 obj = ((Object) ((java.util.Map.Entry)((Iterator) (map)).next())); // 15 36:aload_1 // 16 37:invokeinterface #153 <Method Object Iterator.next()> // 17 42:checkcast #155 <Class java.util.Map$Entry> // 18 45:astore_3 s = (String)((java.util.Map.Entry) (obj)).getKey(); // 19 46:aload_3 // 20 47:invokeinterface #158 <Method Object java.util.Map$Entry.getKey()> // 21 52:checkcast #40 <Class String> // 22 55:astore_2 } while(zzcuy.contains(((Object) (s)))); // 23 56:getstatic #51 <Field Set zzcuy> // 24 59:aload_2 // 25 60:invokeinterface #162 <Method boolean Set.contains(Object)> // 26 65:ifne 27 if(((java.util.Map.Entry) (obj)).getValue() instanceof List) //* 27 68:aload_3 //* 28 69:invokeinterface #165 <Method Object java.util.Map$Entry.getValue()> //* 29 74:instanceof #167 <Class List> //* 30 77:ifeq 151 { obj = ((Object) (((List)((java.util.Map.Entry) (obj)).getValue()).iterator())); // 31 80:aload_3 // 32 81:invokeinterface #165 <Method Object java.util.Map$Entry.getValue()> // 33 86:checkcast #167 <Class List> // 34 89:invokeinterface #168 <Method Iterator List.iterator()> // 35 94:astore_3 while(((Iterator) (obj)).hasNext()) //* 36 95:aload_3 //* 37 96:invokeinterface #149 <Method boolean Iterator.hasNext()> //* 38 101:ifeq 27 { String s1 = (String)((Iterator) (obj)).next(); // 39 104:aload_3 // 40 105:invokeinterface #153 <Method Object Iterator.next()> // 41 110:checkcast #40 <Class String> // 42 113:astore 4 jsonwriter.beginObject(); // 43 115:aload_0 // 44 116:invokevirtual #113 <Method JsonWriter JsonWriter.beginObject()> // 45 119:pop jsonwriter.name("name").value(s); // 46 120:aload_0 // 47 121:ldc1 #169 <String "name"> // 48 123:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 49 126:aload_2 // 50 127:invokevirtual #171 <Method JsonWriter JsonWriter.value(String)> // 51 130:pop jsonwriter.name("value").value(s1); // 52 131:aload_0 // 53 132:ldc1 #172 <String "value"> // 54 134:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 55 137:aload 4 // 56 139:invokevirtual #171 <Method JsonWriter JsonWriter.value(String)> // 57 142:pop jsonwriter.endObject(); // 58 143:aload_0 // 59 144:invokevirtual #123 <Method JsonWriter JsonWriter.endObject()> // 60 147:pop } continue; // 61 148:goto 95 } if(!(((java.util.Map.Entry) (obj)).getValue() instanceof String)) break; // 62 151:aload_3 // 63 152:invokeinterface #165 <Method Object java.util.Map$Entry.getValue()> // 64 157:instanceof #40 <Class String> // 65 160:ifeq 206 jsonwriter.beginObject(); // 66 163:aload_0 // 67 164:invokevirtual #113 <Method JsonWriter JsonWriter.beginObject()> // 68 167:pop jsonwriter.name("name").value(s); // 69 168:aload_0 // 70 169:ldc1 #169 <String "name"> // 71 171:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 72 174:aload_2 // 73 175:invokevirtual #171 <Method JsonWriter JsonWriter.value(String)> // 74 178:pop jsonwriter.name("value").value((String)((java.util.Map.Entry) (obj)).getValue()); // 75 179:aload_0 // 76 180:ldc1 #172 <String "value"> // 77 182:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 78 185:aload_3 // 79 186:invokeinterface #165 <Method Object java.util.Map$Entry.getValue()> // 80 191:checkcast #40 <Class String> // 81 194:invokevirtual #171 <Method JsonWriter JsonWriter.value(String)> // 82 197:pop jsonwriter.endObject(); // 83 198:aload_0 // 84 199:invokevirtual #123 <Method JsonWriter JsonWriter.endObject()> // 85 202:pop } while(true); // 86 203:goto 27 zzane.e("Connection headers should be either Map<String, String> or Map<String, List<String>>"); // 87 206:ldc1 #174 <String "Connection headers should be either Map<String, String> or Map<String, List<String>>"> // 88 208:invokestatic #179 <Method void zzane.e(String)> } jsonwriter.endArray(); // 89 211:aload_0 // 90 212:invokevirtual #182 <Method JsonWriter JsonWriter.endArray()> // 91 215:pop // 92 216:return } static final void zza(String s, JsonWriter jsonwriter) throws IOException { jsonwriter.name("params").beginObject(); // 0 0:aload_1 // 1 1:ldc1 #103 <String "params"> // 2 3:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 3 6:invokevirtual #113 <Method JsonWriter JsonWriter.beginObject()> // 4 9:pop if(s != null) //* 5 10:aload_0 //* 6 11:ifnull 25 jsonwriter.name("error_description").value(s); // 7 14:aload_1 // 8 15:ldc1 #187 <String "error_description"> // 9 17:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 10 20:aload_0 // 11 21:invokevirtual #171 <Method JsonWriter JsonWriter.value(String)> // 12 24:pop jsonwriter.endObject(); // 13 25:aload_1 // 14 26:invokevirtual #123 <Method JsonWriter JsonWriter.endObject()> // 15 29:pop // 16 30:return } private final void zza(String s, zzand zzand1) { StringWriter stringwriter; JsonWriter jsonwriter; stringwriter = new StringWriter(); // 0 0:new #190 <Class StringWriter> // 1 3:dup // 2 4:invokespecial #191 <Method void StringWriter()> // 3 7:astore_3 jsonwriter = new JsonWriter(((java.io.Writer) (stringwriter))); // 4 8:new #105 <Class JsonWriter> // 5 11:dup // 6 12:aload_3 // 7 13:invokespecial #194 <Method void JsonWriter(java.io.Writer)> // 8 16:astore 4 jsonwriter.beginObject(); // 9 18:aload 4 // 10 20:invokevirtual #113 <Method JsonWriter JsonWriter.beginObject()> // 11 23:pop jsonwriter.name("timestamp").value(zzcux.currentTimeMillis()); // 12 24:aload 4 // 13 26:ldc1 #196 <String "timestamp"> // 14 28:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 15 31:getstatic #36 <Field Clock zzcux> // 16 34:invokeinterface #202 <Method long Clock.currentTimeMillis()> // 17 39:invokevirtual #120 <Method JsonWriter JsonWriter.value(long)> // 18 42:pop jsonwriter.name("event").value(s); // 19 43:aload 4 // 20 45:ldc1 #204 <String "event"> // 21 47:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 22 50:aload_1 // 23 51:invokevirtual #171 <Method JsonWriter JsonWriter.value(String)> // 24 54:pop jsonwriter.name("components").beginArray(); // 25 55:aload 4 // 26 57:ldc1 #206 <String "components"> // 27 59:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 28 62:invokevirtual #132 <Method JsonWriter JsonWriter.beginArray()> // 29 65:pop for(s = ((String) (zzcuz.iterator())); ((Iterator) (s)).hasNext(); jsonwriter.value((String)((Iterator) (s)).next())); // 30 66:aload_0 // 31 67:getfield #92 <Field List zzcuz> // 32 70:invokeinterface #168 <Method Iterator List.iterator()> // 33 75:astore_1 // 34 76:aload_1 // 35 77:invokeinterface #149 <Method boolean Iterator.hasNext()> // 36 82:ifeq 103 // 37 85:aload 4 // 38 87:aload_1 // 39 88:invokeinterface #153 <Method Object Iterator.next()> // 40 93:checkcast #40 <Class String> // 41 96:invokevirtual #171 <Method JsonWriter JsonWriter.value(String)> // 42 99:pop //* 43 100:goto 76 try { jsonwriter.endArray(); // 44 103:aload 4 // 45 105:invokevirtual #182 <Method JsonWriter JsonWriter.endArray()> // 46 108:pop zzand1.zza(jsonwriter); // 47 109:aload_2 // 48 110:aload 4 // 49 112:invokeinterface #211 <Method void zzand.zza(JsonWriter)> jsonwriter.endObject(); // 50 117:aload 4 // 51 119:invokevirtual #123 <Method JsonWriter JsonWriter.endObject()> // 52 122:pop jsonwriter.flush(); // 53 123:aload 4 // 54 125:invokevirtual #214 <Method void JsonWriter.flush()> jsonwriter.close(); // 55 128:aload 4 // 56 130:invokevirtual #217 <Method void JsonWriter.close()> } //* 57 133:goto 143 // Misplaced declaration of an exception variable catch(String s) //* 58 136:astore_1 { zzane.zzb("unable to log", ((Throwable) (s))); // 59 137:ldc1 #219 <String "unable to log"> // 60 139:aload_1 // 61 140:invokestatic #223 <Method void zzane.zzb(String, Throwable)> } zzdi(stringwriter.toString()); // 62 143:aload_3 // 63 144:invokevirtual #224 <Method String StringWriter.toString()> // 64 147:invokestatic #227 <Method void zzdi(String)> return; // 65 150:return } static final void zza(String s, String s1, Map map, byte abyte0[], JsonWriter jsonwriter) throws IOException { jsonwriter.name("params").beginObject(); // 0 0:aload 4 // 1 2:ldc1 #103 <String "params"> // 2 4:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 3 7:invokevirtual #113 <Method JsonWriter JsonWriter.beginObject()> // 4 10:pop jsonwriter.name("firstline").beginObject(); // 5 11:aload 4 // 6 13:ldc1 #115 <String "firstline"> // 7 15:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 8 18:invokevirtual #113 <Method JsonWriter JsonWriter.beginObject()> // 9 21:pop jsonwriter.name("uri").value(s); // 10 22:aload 4 // 11 24:ldc1 #230 <String "uri"> // 12 26:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 13 29:aload_0 // 14 30:invokevirtual #171 <Method JsonWriter JsonWriter.value(String)> // 15 33:pop jsonwriter.name("verb").value(s1); // 16 34:aload 4 // 17 36:ldc1 #232 <String "verb"> // 18 38:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 19 41:aload_1 // 20 42:invokevirtual #171 <Method JsonWriter JsonWriter.value(String)> // 21 45:pop jsonwriter.endObject(); // 22 46:aload 4 // 23 48:invokevirtual #123 <Method JsonWriter JsonWriter.endObject()> // 24 51:pop zza(jsonwriter, map); // 25 52:aload 4 // 26 54:aload_2 // 27 55:invokestatic #126 <Method void zza(JsonWriter, Map)> if(abyte0 != null) //* 28 58:aload_3 //* 29 59:ifnull 77 jsonwriter.name("body").value(Base64Utils.encode(abyte0)); // 30 62:aload 4 // 31 64:ldc1 #234 <String "body"> // 32 66:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 33 69:aload_3 // 34 70:invokestatic #240 <Method String Base64Utils.encode(byte[])> // 35 73:invokevirtual #171 <Method JsonWriter JsonWriter.value(String)> // 36 76:pop jsonwriter.endObject(); // 37 77:aload 4 // 38 79:invokevirtual #123 <Method JsonWriter JsonWriter.endObject()> // 39 82:pop // 40 83:return } static final void zza(byte abyte0[], JsonWriter jsonwriter) throws IOException { int i; String s; jsonwriter.name("params").beginObject(); // 0 0:aload_1 // 1 1:ldc1 #103 <String "params"> // 2 3:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 3 6:invokevirtual #113 <Method JsonWriter JsonWriter.beginObject()> // 4 9:pop i = abyte0.length; // 5 10:aload_0 // 6 11:arraylength // 7 12:istore_2 s = Base64Utils.encode(abyte0); // 8 13:aload_0 // 9 14:invokestatic #240 <Method String Base64Utils.encode(byte[])> // 10 17:astore_3 if(i >= 10000) goto _L2; else goto _L1 // 11 18:iload_2 // 12 19:sipush 10000 // 13 22:icmpge 41 _L1: abyte0 = "body"; // 14 25:ldc1 #234 <String "body"> // 15 27:astore_0 _L4: jsonwriter.name(((String) (abyte0))).value(s); // 16 28:aload_1 // 17 29:aload_0 // 18 30:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 19 33:aload_3 // 20 34:invokevirtual #171 <Method JsonWriter JsonWriter.value(String)> // 21 37:pop break; /* Loop/switch isn't completed */ // 22 38:goto 56 _L2: s = zzamu.zzde(s); // 23 41:aload_3 // 24 42:invokestatic #246 <Method String zzamu.zzde(String)> // 25 45:astore_3 if(s == null) break; /* Loop/switch isn't completed */ // 26 46:aload_3 // 27 47:ifnull 56 abyte0 = "bodydigest"; // 28 50:ldc1 #248 <String "bodydigest"> // 29 52:astore_0 if(true) goto _L4; else goto _L3 // 30 53:goto 28 _L3: jsonwriter.name("bodylength").value(i); // 31 56:aload_1 // 32 57:ldc1 #250 <String "bodylength"> // 33 59:invokevirtual #109 <Method JsonWriter JsonWriter.name(String)> // 34 62:iload_2 // 35 63:i2l // 36 64:invokevirtual #120 <Method JsonWriter JsonWriter.value(long)> // 37 67:pop jsonwriter.endObject(); // 38 68:aload_1 // 39 69:invokevirtual #123 <Method JsonWriter JsonWriter.endObject()> // 40 72:pop return; // 41 73:return } public static void zzaf(boolean flag) { synchronized(sLock) //* 0 0:getstatic #28 <Field Object sLock> //* 1 3:astore_1 //* 2 4:aload_1 //* 3 5:monitorenter { zzcuv = true; // 4 6:iconst_1 // 5 7:putstatic #95 <Field boolean zzcuv> zzcuw = flag; // 6 10:iload_0 // 7 11:putstatic #97 <Field boolean zzcuw> } // 8 14:aload_1 // 9 15:monitorexit return; // 10 16:return exception; // 11 17:astore_2 obj; // 12 18:aload_1 JVM INSTR monitorexit ; // 13 19:monitorexit throw exception; // 14 20:aload_2 // 15 21:athrow } private final void zzb(String s, String s1, Map map, byte abyte0[]) { zza("onNetworkRequest", ((zzand) (new zzamz(s, s1, map, abyte0)))); // 0 0:aload_0 // 1 1:ldc1 #255 <String "onNetworkRequest"> // 2 3:new #257 <Class zzamz> // 3 6:dup // 4 7:aload_1 // 5 8:aload_2 // 6 9:aload_3 // 7 10:aload 4 // 8 12:invokespecial #259 <Method void zzamz(String, String, Map, byte[])> // 9 15:invokespecial #261 <Method void zza(String, zzand)> // 10 18:return } private final void zzb(Map map, int i) { zza("onNetworkResponse", ((zzand) (new zzana(i, map)))); // 0 0:aload_0 // 1 1:ldc2 #265 <String "onNetworkResponse"> // 2 4:new #267 <Class zzana> // 3 7:dup // 4 8:iload_2 // 5 9:aload_1 // 6 10:invokespecial #270 <Method void zzana(int, Map)> // 7 13:invokespecial #261 <Method void zza(String, zzand)> // 8 16:return } public static boolean zzbl(Context context) { if(android.os.Build.VERSION.SDK_INT < 17) //* 0 0:getstatic #281 <Field int android.os.Build$VERSION.SDK_INT> //* 1 3:bipush 17 //* 2 5:icmpge 10 return false; // 3 8:iconst_0 // 4 9:ireturn zzna zzna = zznk.zzazm; // 5 10:getstatic #287 <Field zzna zznk.zzazm> // 6 13:astore_2 if(!((Boolean)zzkb.zzik().zzd(zzna)).booleanValue()) //* 7 14:invokestatic #293 <Method zzni zzkb.zzik()> //* 8 17:aload_2 //* 9 18:invokevirtual #299 <Method Object zzni.zzd(zzna)> //* 10 21:checkcast #301 <Class Boolean> //* 11 24:invokevirtual #304 <Method boolean Boolean.booleanValue()> //* 12 27:ifne 32 return false; // 13 30:iconst_0 // 14 31:ireturn int i; try { i = android.provider.Settings.Global.getInt(context.getContentResolver(), "development_settings_enabled", 0); // 15 32:aload_0 // 16 33:invokevirtual #310 <Method android.content.ContentResolver Context.getContentResolver()> // 17 36:ldc2 #312 <String "development_settings_enabled"> // 18 39:iconst_0 // 19 40:invokestatic #318 <Method int android.provider.Settings$Global.getInt(android.content.ContentResolver, String, int)> // 20 43:istore_1 } //* 21 44:iload_1 //* 22 45:ifeq 50 //* 23 48:iconst_1 //* 24 49:ireturn //* 25 50:iconst_0 //* 26 51:ireturn // Misplaced declaration of an exception variable catch(Context context) //* 27 52:astore_0 { zzane.zzc("Fail to determine debug setting.", ((Throwable) (context))); // 28 53:ldc2 #320 <String "Fail to determine debug setting."> // 29 56:aload_0 // 30 57:invokestatic #323 <Method void zzane.zzc(String, Throwable)> return false; // 31 60:iconst_0 // 32 61:ireturn } return i != 0; } private final void zzdh(String s) { zza("onNetworkRequestError", ((zzand) (new zzanc(s)))); // 0 0:aload_0 // 1 1:ldc2 #326 <String "onNetworkRequestError"> // 2 4:new #328 <Class zzanc> // 3 7:dup // 4 8:aload_1 // 5 9:invokespecial #329 <Method void zzanc(String)> // 6 12:invokespecial #261 <Method void zza(String, zzand)> // 7 15:return } private static void zzdi(String s) { com/google/android/gms/internal/ads/zzamy; // 0 0:ldc1 #2 <Class zzamy> JVM INSTR monitorenter ; // 1 2:monitorenter zzane.zzdj("GMA Debug BEGIN"); // 2 3:ldc2 #331 <String "GMA Debug BEGIN"> // 3 6:invokestatic #334 <Method void zzane.zzdj(String)> int i = 0; // 4 9:iconst_0 // 5 10:istore_1 _L2: if(i >= s.length()) break; /* Loop/switch isn't completed */ // 6 11:iload_1 // 7 12:aload_0 // 8 13:invokevirtual #81 <Method int String.length()> // 9 16:icmpge 80 int j = i + 4000; // 10 19:iload_1 // 11 20:sipush 4000 // 12 23:iadd // 13 24:istore_2 String s1; s1 = String.valueOf(((Object) (s.substring(i, Math.min(j, s.length()))))); // 14 25:aload_0 // 15 26:iload_1 // 16 27:iload_2 // 17 28:aload_0 // 18 29:invokevirtual #81 <Method int String.length()> // 19 32:invokestatic #340 <Method int Math.min(int, int)> // 20 35:invokevirtual #344 <Method String String.substring(int, int)> // 21 38:invokestatic #77 <Method String String.valueOf(Object)> // 22 41:astore_3 if(s1.length() != 0) //* 23 42:aload_3 //* 24 43:invokevirtual #81 <Method int String.length()> //* 25 46:ifeq 60 { s1 = "GMA Debug CONTENT ".concat(s1); // 26 49:ldc2 #346 <String "GMA Debug CONTENT "> // 27 52:aload_3 // 28 53:invokevirtual #87 <Method String String.concat(String)> // 29 56:astore_3 break MISSING_BLOCK_LABEL_71; // 30 57:goto 71 } s1 = new String("GMA Debug CONTENT "); // 31 60:new #40 <Class String> // 32 63:dup // 33 64:ldc2 #346 <String "GMA Debug CONTENT "> // 34 67:invokespecial #88 <Method void String(String)> // 35 70:astore_3 zzane.zzdj(s1); // 36 71:aload_3 // 37 72:invokestatic #334 <Method void zzane.zzdj(String)> i = j; // 38 75:iload_2 // 39 76:istore_1 if(true) goto _L2; else goto _L1 // 40 77:goto 11 _L1: zzane.zzdj("GMA Debug FINISH"); // 41 80:ldc2 #348 <String "GMA Debug FINISH"> // 42 83:invokestatic #334 <Method void zzane.zzdj(String)> com/google/android/gms/internal/ads/zzamy; // 43 86:ldc1 #2 <Class zzamy> JVM INSTR monitorexit ; // 44 88:monitorexit return; // 45 89:return s; // 46 90:astore_0 //* 47 91:ldc1 #2 <Class zzamy> throw s; // 48 93:monitorexit // 49 94:aload_0 // 50 95:athrow } public static void zzsj() { synchronized(sLock) //* 0 0:getstatic #28 <Field Object sLock> //* 1 3:astore_0 //* 2 4:aload_0 //* 3 5:monitorenter { zzcuv = false; // 4 6:iconst_0 // 5 7:putstatic #95 <Field boolean zzcuv> zzcuw = false; // 6 10:iconst_0 // 7 11:putstatic #97 <Field boolean zzcuw> zzane.zzdk("Ad debug logging enablement is out of date."); // 8 14:ldc2 #351 <String "Ad debug logging enablement is out of date."> // 9 17:invokestatic #354 <Method void zzane.zzdk(String)> } // 10 20:aload_0 // 11 21:monitorexit return; // 12 22:return exception; // 13 23:astore_1 obj; // 14 24:aload_0 JVM INSTR monitorexit ; // 15 25:monitorexit throw exception; // 16 26:aload_1 // 17 27:athrow } public static boolean zzsk() { boolean flag; synchronized(sLock) //* 0 0:getstatic #28 <Field Object sLock> //* 1 3:astore_1 //* 2 4:aload_1 //* 3 5:monitorenter { flag = zzcuv; // 4 6:getstatic #95 <Field boolean zzcuv> // 5 9:istore_0 } // 6 10:aload_1 // 7 11:monitorexit return flag; // 8 12:iload_0 // 9 13:ireturn exception; // 10 14:astore_2 obj; // 11 15:aload_1 JVM INSTR monitorexit ; // 12 16:monitorexit throw exception; // 13 17:aload_2 // 14 18:athrow } public final void zza(String s, String s1, Map map, byte abyte0[]) { if(!isEnabled()) //* 0 0:invokestatic #60 <Method boolean isEnabled()> //* 1 3:ifne 7 { return; // 2 6:return } else { zzb(s, s1, map, abyte0); // 3 7:aload_0 // 4 8:aload_1 // 5 9:aload_2 // 6 10:aload_3 // 7 11:aload 4 // 8 13:invokespecial #357 <Method void zzb(String, String, Map, byte[])> return; // 9 16:return } } public final void zza(HttpURLConnection httpurlconnection, int i) { if(!isEnabled()) //* 0 0:invokestatic #60 <Method boolean isEnabled()> //* 1 3:ifne 7 return; // 2 6:return HashMap hashmap; if(httpurlconnection.getHeaderFields() == null) //* 3 7:aload_1 //* 4 8:invokevirtual #364 <Method Map HttpURLConnection.getHeaderFields()> //* 5 11:ifnonnull 19 hashmap = null; // 6 14:aconst_null // 7 15:astore_3 else //* 8 16:goto 31 hashmap = new HashMap(httpurlconnection.getHeaderFields()); // 9 19:new #366 <Class HashMap> // 10 22:dup // 11 23:aload_1 // 12 24:invokevirtual #364 <Method Map HttpURLConnection.getHeaderFields()> // 13 27:invokespecial #369 <Method void HashMap(Map)> // 14 30:astore_3 zzb(((Map) (hashmap)), i); // 15 31:aload_0 // 16 32:aload_3 // 17 33:iload_2 // 18 34:invokespecial #371 <Method void zzb(Map, int)> if(i < 200 || i >= 300) //* 19 37:iload_2 //* 20 38:sipush 200 //* 21 41:icmplt 51 //* 22 44:iload_2 //* 23 45:sipush 300 //* 24 48:icmplt 108 { try { httpurlconnection = ((HttpURLConnection) (httpurlconnection.getResponseMessage())); // 25 51:aload_1 // 26 52:invokevirtual #374 <Method String HttpURLConnection.getResponseMessage()> // 27 55:astore_1 } //* 28 56:goto 103 // Misplaced declaration of an exception variable catch(HttpURLConnection httpurlconnection) //* 29 59:astore_1 { httpurlconnection = ((HttpURLConnection) (String.valueOf(((Object) (((IOException) (httpurlconnection)).getMessage()))))); // 30 60:aload_1 // 31 61:invokevirtual #377 <Method String IOException.getMessage()> // 32 64:invokestatic #77 <Method String String.valueOf(Object)> // 33 67:astore_1 if(((String) (httpurlconnection)).length() != 0) //* 34 68:aload_1 //* 35 69:invokevirtual #81 <Method int String.length()> //* 36 72:ifeq 86 httpurlconnection = ((HttpURLConnection) ("Can not get error message from error HttpURLConnection\n".concat(((String) (httpurlconnection))))); // 37 75:ldc2 #379 <String "Can not get error message from error HttpURLConnection\n"> // 38 78:aload_1 // 39 79:invokevirtual #87 <Method String String.concat(String)> // 40 82:astore_1 else //* 41 83:goto 97 httpurlconnection = ((HttpURLConnection) (new String("Can not get error message from error HttpURLConnection\n"))); // 42 86:new #40 <Class String> // 43 89:dup // 44 90:ldc2 #379 <String "Can not get error message from error HttpURLConnection\n"> // 45 93:invokespecial #88 <Method void String(String)> // 46 96:astore_1 zzane.zzdk(((String) (httpurlconnection))); // 47 97:aload_1 // 48 98:invokestatic #354 <Method void zzane.zzdk(String)> httpurlconnection = null; // 49 101:aconst_null // 50 102:astore_1 } zzdh(((String) (httpurlconnection))); // 51 103:aload_0 // 52 104:aload_1 // 53 105:invokespecial #381 <Method void zzdh(String)> } // 54 108:return } public final void zza(HttpURLConnection httpurlconnection, byte abyte0[]) { if(!isEnabled()) //* 0 0:invokestatic #60 <Method boolean isEnabled()> //* 1 3:ifne 7 return; // 2 6:return HashMap hashmap; if(httpurlconnection.getRequestProperties() == null) //* 3 7:aload_1 //* 4 8:invokevirtual #385 <Method Map HttpURLConnection.getRequestProperties()> //* 5 11:ifnonnull 19 hashmap = null; // 6 14:aconst_null // 7 15:astore_3 else //* 8 16:goto 31 hashmap = new HashMap(httpurlconnection.getRequestProperties()); // 9 19:new #366 <Class HashMap> // 10 22:dup // 11 23:aload_1 // 12 24:invokevirtual #385 <Method Map HttpURLConnection.getRequestProperties()> // 13 27:invokespecial #369 <Method void HashMap(Map)> // 14 30:astore_3 zzb(new String(httpurlconnection.getURL().toString()), new String(httpurlconnection.getRequestMethod()), ((Map) (hashmap)), abyte0); // 15 31:aload_0 // 16 32:new #40 <Class String> // 17 35:dup // 18 36:aload_1 // 19 37:invokevirtual #389 <Method URL HttpURLConnection.getURL()> // 20 40:invokevirtual #392 <Method String URL.toString()> // 21 43:invokespecial #88 <Method void String(String)> // 22 46:new #40 <Class String> // 23 49:dup // 24 50:aload_1 // 25 51:invokevirtual #395 <Method String HttpURLConnection.getRequestMethod()> // 26 54:invokespecial #88 <Method void String(String)> // 27 57:aload_3 // 28 58:aload_2 // 29 59:invokespecial #357 <Method void zzb(String, String, Map, byte[])> // 30 62:return } public final void zza(Map map, int i) { if(!isEnabled()) //* 0 0:invokestatic #60 <Method boolean isEnabled()> //* 1 3:ifne 7 return; // 2 6:return zzb(map, i); // 3 7:aload_0 // 4 8:aload_1 // 5 9:iload_2 // 6 10:invokespecial #371 <Method void zzb(Map, int)> if(i < 200 || i >= 300) //* 7 13:iload_2 //* 8 14:sipush 200 //* 9 17:icmplt 27 //* 10 20:iload_2 //* 11 21:sipush 300 //* 12 24:icmplt 32 zzdh(((String) (null))); // 13 27:aload_0 // 14 28:aconst_null // 15 29:invokespecial #381 <Method void zzdh(String)> // 16 32:return } public final void zzdg(String s) { if(!isEnabled()) //* 0 0:invokestatic #60 <Method boolean isEnabled()> //* 1 3:ifne 7 return; // 2 6:return if(s == null) //* 3 7:aload_1 //* 4 8:ifnonnull 12 { return; // 5 11:return } else { zzf(s.getBytes()); // 6 12:aload_0 // 7 13:aload_1 // 8 14:invokevirtual #400 <Method byte[] String.getBytes()> // 9 17:invokevirtual #404 <Method void zzf(byte[])> return; // 10 20:return } } public final void zzf(byte abyte0[]) { zza("onNetworkResponseBody", ((zzand) (new zzanb(abyte0)))); // 0 0:aload_0 // 1 1:ldc2 #406 <String "onNetworkResponseBody"> // 2 4:new #408 <Class zzanb> // 3 7:dup // 4 8:aload_1 // 5 9:invokespecial #410 <Method void zzanb(byte[])> // 6 12:invokespecial #261 <Method void zza(String, zzand)> // 7 15:return } private static Object sLock = new Object(); private static boolean zzcuv = false; private static boolean zzcuw = false; private static Clock zzcux = DefaultClock.getInstance(); private static final Set zzcuy = new HashSet(((java.util.Collection) (Arrays.asList(((Object []) (new String[0])))))); private final List zzcuz; static { // 0 0:new #4 <Class Object> // 1 3:dup // 2 4:invokespecial #26 <Method void Object()> // 3 7:putstatic #28 <Field Object sLock> // 4 10:invokestatic #34 <Method Clock DefaultClock.getInstance()> // 5 13:putstatic #36 <Field Clock zzcux> // 6 16:new #38 <Class HashSet> // 7 19:dup // 8 20:iconst_0 // 9 21:anewarray String[] // 10 24:invokestatic #46 <Method List Arrays.asList(Object[])> // 11 27:invokespecial #49 <Method void HashSet(java.util.Collection)> // 12 30:putstatic #51 <Field Set zzcuy> //* 13 33:return } }
37.162832
147
0.532028
f77d18e95cacc3eb87eb4349cb527bc3f9e5d70d
1,552
package frogger.service; import java.util.ArrayList; import frogger.model.actor.staticActor.Digit; /** * <h2>ScoreBoardUpdater</h2> * * <p>The {@link ScoreBoardUpdater} class is an singleton class of utility to update the {@link Digit} created in map * when the {@link frogger.model.Score} changed * * <p><strong>Note:</strong> this class is implemented as an {@link Enum} thus to be a singleton class. * * <p><strong>Main Functionality:</strong> * * <pre> * ScoreBoardUpdater.INSTANCE.updateScore(n, scoreBoard); * </pre> * * <p><strong>Use:</strong> * * <pre> * ScoreBoardUpdater.INSTANCE.{METHOD}() * </pre> * * @author Wenzheng Shan * @version 1.0 * @since 1.0 * @see frogger.controller.ScoreListController * @see Digit * */ public enum ScoreBoardUpdater { /** The shared instance for global use for whole project */ INSTANCE; /** * <p> Update the {@link Digit} image based on the given input points * * <p> Each time get the single figure of input n and update corresponding digit to this single figure * * @param n The current point of game (passed from {@link frogger.controller.GameController}) * @param scoreBoard The {@link ArrayList} with three single {@link Digit} as scoreBoard being updated (generated in {@link frogger.model.Map}) */ public void updateScore(int n, ArrayList<Digit> scoreBoard) { for (Digit digit: scoreBoard) { int d = n / 10; int k = n - d * 10; n = d; digit.changeScore(k); } } }
27.714286
145
0.653995
82fac4fd76553529c0f2cdb94d281607a3e0090e
1,318
package com.jagrosh.jmusicbot.interactions; import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.CommandClient; import com.jagrosh.jmusicbot.utils.CommandConverter; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.hooks.EventListener; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class InteractionManager { private final CommandClient client; public InteractionManager(CommandClient client) { this.client = client; } public CommandListUpdateAction registerCommands(Guild guild) { CommandListUpdateAction updateCommands = guild.updateCommands(); List<CommandData> commands = new ArrayList<>(); for (Command command : this.getClient().getCommands()) { Optional<CommandData> slashCommand = CommandConverter.toSlashCommand(command); slashCommand.ifPresent(commands::add); } return updateCommands.addCommands(commands); } public EventListener getListener() { return new InteractionListener(this); } public CommandClient getClient() { return client; } }
31.380952
90
0.743551
0966d414cad8829116bb71a43bb802d30b89a059
994
package se.atg.sam.ui.dropwizard.db; import org.bson.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.health.HealthCheck; import com.mongodb.MongoClientException; import com.mongodb.client.MongoDatabase; public class MongoDatabaseHealthCheck extends HealthCheck { private static final Logger logger = LoggerFactory.getLogger(MongoDatabaseHealthCheck.class); private final MongoDatabase mongoDatabase; public MongoDatabaseHealthCheck(MongoDatabase database) { this.mongoDatabase = database; } /** * Checks if the system database, available in all MongoDB instances can be * reached. */ @Override protected Result check() throws Exception { try { final Document result = mongoDatabase.runCommand(new Document("dbStats", 1)); return Result.healthy(result.toJson()); } catch (MongoClientException exc) { logger.warn("Unhealthy database", exc); return Result.unhealthy(exc); } } }
27.611111
95
0.748491
7a3d07c9ac4c71ab4e983461366386670fe986c4
15,833
/* * Copyright 2017 Austin Lehman * * 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.cali.ast; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import com.cali.CallStack; import com.cali.Environment; import com.cali.types.*; import com.cali.types.CaliException.exType; public class astFunctDef extends astNode implements astNodeInt { private astFunctDefArgsList argList = new astFunctDefArgsList(); private astStatementList instructionList = new astStatementList(); private boolean isExtern = false; public astFunctDef() { this.setType(astNodeType.FUNCTDEF); } public astFunctDef(String Name) { this.setType(astNodeType.FUNCTDEF); this.setName(Name); } public astFunctDefArgsList getArgList() { return argList; } public void setArgList(astFunctDefArgsList argList) { this.argList = argList; } public astStatementList getInstructionList() { return instructionList; } public void setInstructionList(astStatementList InstructionList) { this.instructionList = InstructionList; } public void setExtern(boolean extern) { this.isExtern = extern; } public boolean getExtern() { return this.isExtern; } @Override public CaliType evalImpl(Environment env, boolean getref) throws caliException { throw new caliException(this, "INTERNAL [astFunctDef.evalImpl] Not implemented.", env.stackTraceToString()); } @Override public String toString(int Level) { String rstr = ""; rstr += getTabs(Level) + "{\n"; rstr += this.getNodeStr(Level + 1) + ",\n"; if(this.argList != null) { rstr += getTabs(Level + 1) + "\"argumentList\":\n"; rstr += this.argList.toString(Level + 1) + ",\n"; } if(this.instructionList != null) { rstr += getTabs(Level + 1) + "\"statementList\":\n"; rstr += this.instructionList.toString(Level + 1) + ",\n"; } rstr += getTabs(Level) + "}"; return rstr; } public CaliType initArgs(Environment env, CaliList args) throws caliException { CaliType ret = new CaliNull(); if (this.argList != null) { int i = 0; for (astNode adef : this.argList.getArgs()) { // Data type in funct def specified, check that passed data // is valid. if (i < args.getValue().size()) { if (adef.getType() != astNodeType.UNDEF) { if ( (adef.getType() == astNodeType.BOOL && args.getValue().get(i).getType() != cType.cBool) || (adef.getType() == astNodeType.INT && args.getValue().get(i).getType() != cType.cInt) || (adef.getType() == astNodeType.DOUBLE && args.getValue().get(i).getType() != cType.cDouble) || (adef.getType() == astNodeType.STRING && args.getValue().get(i).getType() != cType.cString) || (adef.getType() == astNodeType.LIST && args.getValue().get(i).getType() != cType.cList) || (adef.getType() == astNodeType.MAP && args.getValue().get(i).getType() != cType.cMap) || (adef.getType() == astNodeType.OBJ && args.getValue().get(i).getType() != cType.cObject) ) { CaliException e = new CaliException(exType.exRuntime); e.setException(this.getLineNum(), "INVALID_DATA_TYPE", "Function '" + this.getName() + "' definition at position " + (i + 1) + " is expected to be of type '" + adef.getType().name() + "' but found '" + args.getValue().get(i).getType().name() + "' instead.", env.getCallStack().getStackTrace()); return e; } else if (adef.getType() == astNodeType.VAR && adef.getPrimType() != cType.cUndef && adef.getPrimType() != args.getValue().get(i).getType()) { CaliException e = new CaliException(exType.exRuntime); e.setException(this.getLineNum(), "INVALID_DATA_TYPE", "Function '" + this.getName() + "' definition at position " + (i + 1) + " is expected to be of type '" + adef.getPrimType().name() + "' but found '" + args.getValue().get(i).getType().name() + "' instead.", env.getCallStack().getStackTrace()); return e; } } if (adef.getType() == astNodeType.ETCETERA) { CaliList etcList = new CaliList(); for (int j = i; j < args.getValue().size(); j++) { etcList.add(args.getValue().get(j)); } env.getLocals().add("etc", etcList); break; } else { env.getLocals().add(adef.getName(), args.getValue().get(i)); } } else if (adef.getType() == astNodeType.ETCETERA) { CaliList etcList = new CaliList(); env.getLocals().add("etc", etcList); break; } else if (adef.getType() != astNodeType.VAR) { // Not a var, so it is a defalut value. env.getLocals().add(adef.getName(), adef.eval(env, false)); } else { CaliException e = new CaliException(exType.exRuntime); e.setException(this.getLineNum(), "ARGUMENT_NUMBER", "Number of arguments provided does not match the number in definition.", "Number of arguments provided does not match the number in definition.", env.getCallStack().getStackTrace()); ret = e; } i++; } } else if (this.argList.getArgs().size() > 0) { CaliException e = new CaliException(exType.exRuntime); e.setException(this.getLineNum(), "ARGUMENT_NUMBER", "Number of arguments provided does not match the number in definition.", "Number of arguments provided does not match the number in definition.", env.getCallStack().getStackTrace()); ret = e; } if(ret.isNull()) { ret = new CaliBool(true); } return ret; } public CaliType call (Environment env, boolean getRef, CaliList args, String FileName) throws caliException { CaliType ret = new CaliNull(); boolean retFound = false; CaliType tnode = this.initArgs(env, args); CallStack cst = new CallStack(FileName, this.getLineNum(), env.getClassInstance().getClassDef().getName(), this.getName(), "Defined."); cst.setParent(env.getCallStack()); // Itterate statement list of function if(!tnode.isEx()) { if(this.instructionList != null) { for(int i = 0; (i < this.instructionList.getStatements().size())&&(!ret.isEx()); i++) { astNode statement = this.instructionList.getStatements().get(i); CaliType tmp = null; if(statement != null) { Environment tenv = new Environment(env.getEngine()); tenv.setEnvironment(env.getClassInstance(), env.getLocals(), cst); tmp = statement.eval(tenv, getRef); if(tmp.isReturn()) { ret = ((CaliReturn)tmp).getValue(); retFound = true; break; } else if(tmp.isEx()) { ret = tmp; break; } } else { CaliException e = new CaliException(exType.exInternal); e.setException(this.getLineNum(), "NULL_PTR", "Null pointer for statement. (aFunctDef::call)", "Null pointer for statement.", env.getCallStack().getStackTrace()); ret = e; break; } } } else { CaliException e = new CaliException(exType.exInternal); e.setException(this.getLineNum(), "NULL_PTR", "Null pointer for slist. (aFunctDef::call)", "Null pointer for slist.", env.getCallStack().getStackTrace()); ret = e; } } else ret = tnode; if(ret == null) { if(retFound) { CaliException e = new CaliException(exType.exInternal); e.setException(this.getLineNum(), "NULL_PTR", "Null pointer returned. (aFunctDef::call)", "Null pointer returned.", env.getCallStack().getStackTrace()); ret = e; } else { // No return statement, create new astNode of aUndef and return. ret = new CaliNull(); } } return ret; } public CaliType callExtern(Environment env, CaliList args) throws caliException { CaliType ret = new CaliNull(); CaliObject callingObj = env.getClassInstance(); Object o = callingObj.getExternObject(); if(o != null) { ArrayList<CaliType> fargs = this.getExternArgs(env, args); try { Class<?> aclass = callingObj.getClassDef().getExternClass(); if (aclass == null) { System.out.println("aclass null"); } Method meth = aclass.getMethod(this.getName(), Environment.class, ArrayList.class); CaliType tmp = (CaliType)meth.invoke(o, env, fargs); if((tmp != null)&&(tmp instanceof CaliType)) ret = tmp; else throw new caliException(this, "Return value found from calling '" + this.getName() + "' is null or not of type CaliType.", env.stackTraceToString()); } catch (NoSuchMethodException e) { CaliException ex = new CaliException(exType.exRuntime); ex.setException(this.getLineNum(), "EXTERN_NO_SUCH_METHOD", "External call, no such method '" + this.getName() + "'.", env.getCallStack().getStackTrace()); return ex; } catch (SecurityException e) { CaliException ex = new CaliException(exType.exRuntime); ex.setException(this.getLineNum(), "EXTERN_SECURITY_EXCEPTION", "External call, security exception for method '" + this.getName() + "'.", env.getCallStack().getStackTrace()); return ex; } catch (IllegalAccessException e) { CaliException ex = new CaliException(exType.exRuntime); ex.setException(this.getLineNum(), "EXTERN_ILLEGAL_ACCESS", "External call, illegal access exception for method '" + this.getName() + "'.", env.getCallStack().getStackTrace()); return ex; } catch (IllegalArgumentException e) { CaliException ex = new CaliException(exType.exRuntime); ex.setException(this.getLineNum(), "EXTERN_ILLEGAL_ARGUMENT", "External call, illegal argument exception for method '" + this.getName() + "'.", env.getCallStack().getStackTrace()); return ex; } catch(StackOverflowError e) { CaliException ex = new CaliException(exType.exRuntime); ex.setException(this.getLineNum(), "EXTERN_STACK_OVERFLOW", "External call, stack overflow exception for method '" + this.getName() + "'. Infinite recursion perhaps?", env.getCallStack().getStackTrace()); return ex; } catch (InvocationTargetException e) { CaliException ex = new CaliException(exType.exRuntime); ex.setException(this.getLineNum(), "EXTERN_INVOCATION_TARGET_EXCEPTION", "External call, invocation target exception for method '" + this.getName() + "', the external method threw an uncaught exception: " + e.getTargetException().toString(), env.getCallStack().getStackTrace()); return ex; } catch (caliException e) { CaliException ex = new CaliException(exType.exRuntime); ex.setException(this.getLineNum(), "EXTERN_EXCEPTION", e.getMessage(), env.getCallStack().getStackTrace()); return ex; } catch (Exception e) { e.printStackTrace(); } } else { CaliException ex = new CaliException(exType.exRuntime); ex.setException(this.getLineNum(), "EXTERN_OBJECT_NOT_FOUND", "External object not found when calling '" + this.getName() + "'.", env.getCallStack().getStackTrace()); return ex; } return ret; } private ArrayList<CaliType> getExternArgs(Environment env, CaliList eargs) throws caliException { ArrayList<CaliType> args = new ArrayList<CaliType>(); boolean etcFound = false; CaliList etcList = new CaliList(); cType etype = cType.cUndef; for(int i = 0; (i < this.argList.getArgs().size())||(i < eargs.size()); i++) { if((i < this.argList.getArgs().size())&&(this.argList.getArgs().get(i).getType() == astNodeType.ETCETERA)) { if(!etcFound) { etype = ((astEtcetera)this.argList.getArgs().get(i)).getPrimType(); etcFound = true; } else throw new caliException(this, "Already found a etcetera (...) definition in this function definition.", env.stackTraceToString()); } if(etcFound) { if(i < eargs.size()) { if(etype != cType.cUndef) { if(eargs.getValue().get(i).getType() == etype) { etcList.add(eargs.getValue().get(i)); } else throw new caliException(this, "Etcetera (...) list is expecting type '" + etype.name() + " but found type '" + eargs.getValue().get(i).getType().name() + "'.", env.stackTraceToString()); } else etcList.add(eargs.getValue().get(i)); } } else { if(etcFound) { throw new caliException(this, "Cannot have arguments in function definition after etcetera (...).", env.stackTraceToString()); } else { if(this.argList.getArgs().size() > i) { astNode v = this.argList.getArgs().get(i); if(i < eargs.size()) { if((v.getPrimType() == cType.cUndef)||(v.getPrimType() == eargs.getValue().get(i).getType())||(eargs.getValue().get(i).isNull())) { args.add(eargs.getValue().get(i)); } else if((v.getPrimType() == cType.cInt)&&(eargs.getValue().get(i).getType() == cType.cDouble)){ CaliInt ai = new CaliInt((int)((CaliDouble)eargs.getValue().get(i)).getValue()); args.add(ai); } else if((v.getPrimType() == cType.cDouble)&&(eargs.getValue().get(i).getType() == cType.cInt)) { CaliDouble ad = new CaliDouble((double)((CaliInt)eargs.getValue().get(i)).getValue()); args.add(ad); } else { throw new caliException(this, "Expecting type '" + v.getPrimType().name() + " but found type '" + eargs.getValue().get(i).getType().name() + "'.", env.stackTraceToString()); } } else { args.add(this.argList.getArgs().get(i).eval(env)); } } else { throw new caliException(this, "Incorrect number of arguments provided to function '" + this.getName() + "'. Provided " + String.valueOf(eargs.size()) + " but expecting " + String.valueOf(this.argList.getArgs().size()) + ".", env.stackTraceToString()); } } } } if(etcFound) { args.add(etcList); } return args; } public CaliType getCalidoc() { CaliMap ret = new CaliMap(); ret.put("name", new CaliString(this.getName())); List<astNode> args = this.argList.getArgs(); CaliList cargs = new CaliList(); for (astNode arg : args) { astNodeInt targ = (astNodeInt)arg; CaliMap am = new CaliMap(); am.put("type", new CaliString(targ.getType().name().toLowerCase())); if (targ.getType() != astNodeType.ETCETERA) { am.put("name", new CaliString(targ.getName())); am.put("specifiedType", new CaliString(arg.getPrimType().name().substring(1).toLowerCase())); if (targ.getType() != astNodeType.VAR) { am.put("valueType", new CaliString(arg.getPrimType().name().substring(1).toLowerCase())); if (targ.getType() == astNodeType.STRING) { am.put("value", new CaliString(((astString) arg).getValueString())); } else if (targ.getType() == astNodeType.BOOL) { am.put("value", new CaliBool(((astBool) arg).getValueBool())); } else if (targ.getType() == astNodeType.INT) { am.put("value", new CaliInt(((astInt) arg).getValueInt())); } else if (targ.getType() == astNodeType.DOUBLE) { am.put("value", new CaliDouble(((astDouble) arg).getValueDouble())); } else if (targ.getType() == astNodeType.NULL) { am.put("value", new CaliNull()); } } } cargs.add(am); } ret.put("args", cargs); if (this.docNode != null) { ret.put("caliDoc", this.docNode.getCalidoc()); } return ret; } }
41.997347
306
0.641256
10e2b9c8d546259973e7ed40e261568d7aded98e
2,805
package com.lambdaschool.watermyplant.controllers; import com.lambdaschool.watermyplant.models.Plant; import com.lambdaschool.watermyplant.models.User; import com.lambdaschool.watermyplant.services.PlantService; import com.lambdaschool.watermyplant.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; @RestController @RequestMapping("/plants") public class PlantController { @Autowired PlantService plantService; @Autowired UserService userService; // get list of plants by id @GetMapping(value = "/{userId}", produces = {"application/json"}) public ResponseEntity<?> getAllPlantsByUserId( @PathVariable long userId ) { List<Plant> plantList = plantService.findPlantByUserId(userId); return new ResponseEntity<>(plantList, HttpStatus.OK); } // creating new plant @PostMapping(value = "/newplant", consumes = "application/json") public ResponseEntity<?> createNewPlant(@Valid @RequestBody Plant newplant) throws URISyntaxException { newplant.setPlantId(0); String username = SecurityContextHolder.getContext().getAuthentication().getName(); User currentUser = userService.findByName(username); newplant.setUser(currentUser); newplant = plantService.save(newplant); // set the location header for the newly created resource HttpHeaders responseHeaders = new HttpHeaders(); URI newUserURI = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{plantid}") .buildAndExpand(newplant.getPlantId()) .toUri(); responseHeaders.setLocation(newUserURI); return new ResponseEntity<>(newplant, responseHeaders, HttpStatus.OK); } // edit plant by id @PatchMapping(value = "/plant/{plantId}", consumes = "application/json") public ResponseEntity<?> editPlantById(@PathVariable long plantId, @RequestBody Plant editPlant) { plantService.update(editPlant, plantId); return new ResponseEntity<>(editPlant,HttpStatus.OK); } // delete plant by id @DeleteMapping("/plant/{plantId}") public ResponseEntity<?> deletePlantById(@PathVariable long plantId) { plantService.delete(plantId); return new ResponseEntity<>(HttpStatus.OK); } }
34.62963
105
0.723351
0b1cc7c27468365a3f38384a6b6afb4c5f010cd4
280
/* SPDX-License-Identifier: Apache 2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.repositoryservices.connectors.stores.archivestore; public class MockOpenMetadataArchiveStoreProvider extends OpenMetadataArchiveStoreProviderBase { }
35
94
0.835714
1c2349143555485447846dbe337d2a480facbdae
3,865
package mage.cards.b; import mage.MageObjectReference; import mage.abilities.Ability; import mage.abilities.DelayedTriggeredAbility; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.CreateTokenEffect; import mage.abilities.effects.common.continuous.BoostTargetEffect; import mage.abilities.effects.common.continuous.GainAbilityTargetEffect; import mage.abilities.keyword.LifelinkAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.events.ZoneChangeEvent; import mage.game.permanent.Permanent; import mage.game.permanent.token.SpiritWhiteToken; import mage.target.common.TargetControlledCreaturePermanent; import java.util.UUID; /** * @author ciaccona007 */ public class BlessedDefiance extends CardImpl { public BlessedDefiance(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "W"); // Target creature you control gets +2/+0 and gains lifelink until end of turn. When that creature dies this turn, create a 1/1 white Spirit creature token with flying. this.getSpellAbility().addEffect(new BoostTargetEffect(2, 0) .setText("Target creature you control gets +2/+0")); this.getSpellAbility().addEffect(new GainAbilityTargetEffect(LifelinkAbility.getInstance(), Duration.EndOfTurn) .setText("and gains lifelink until end of turn")); this.getSpellAbility().addEffect(new BlessedDefianceEffect()); this.getSpellAbility().addTarget(new TargetControlledCreaturePermanent()); } private BlessedDefiance(final BlessedDefiance card) { super(card); } @Override public BlessedDefiance copy() { return new BlessedDefiance(this); } } class BlessedDefianceEffect extends OneShotEffect { BlessedDefianceEffect() { super(Outcome.Benefit); staticText = "When that creature dies this turn, create a 1/1 white Spirit creature token with flying."; } private BlessedDefianceEffect(final BlessedDefianceEffect effect) { super(effect); } @Override public BlessedDefianceEffect copy() { return new BlessedDefianceEffect(this); } @Override public boolean apply(Game game, Ability source) { Permanent permanent = game.getPermanent(source.getFirstTarget()); if (permanent == null) { return false; } game.addDelayedTriggeredAbility(new BlessedDefianceDelayedTriggeredAbility(permanent, game), source); return true; } } class BlessedDefianceDelayedTriggeredAbility extends DelayedTriggeredAbility { private final MageObjectReference mor; BlessedDefianceDelayedTriggeredAbility(Permanent permanent, Game game) { super(new CreateTokenEffect(new SpiritWhiteToken()), Duration.EndOfTurn, false, false); this.mor = new MageObjectReference(permanent, game); } private BlessedDefianceDelayedTriggeredAbility(final BlessedDefianceDelayedTriggeredAbility ability) { super(ability); this.mor = ability.mor; } @Override public boolean checkEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.ZONE_CHANGE; } @Override public boolean checkTrigger(GameEvent event, Game game) { return mor.refersTo(((ZoneChangeEvent) event).getTarget(), game); } @Override public BlessedDefianceDelayedTriggeredAbility copy() { return new BlessedDefianceDelayedTriggeredAbility(this); } @Override public String getRule() { return "When that creature dies this turn, create a 1/1 white Spirit creature token with flying."; } }
33.903509
176
0.732471
63fbe6a0e5598cd12f48a09640a75dc5a52bdf28
72
public class AB extends B { public AB(String s) { super(s); } }
12
27
0.583333
de0c1262ce8a202063977bc46255918e4144d770
563
package com.mini_pfe.Config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; @Configuration public class ConfigCors extends WebMvcConfigurationSupport { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/*") .allowedOrigins("http://localhost:4200") .allowedMethods("GET", "POST", "OPTIONS", "PUT"); } }
29.631579
84
0.738899
76b98d61cd59ad466e832290c04b8e1fa20b1302
1,823
/* * * 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.geode.tools.pulse.internal.service; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; /** * Class PulseServiceFactory * * @since GemFire version 7.5 */ @Component @Scope("singleton") public class PulseServiceFactory implements ApplicationContextAware { static final long serialVersionUID = 02L; ApplicationContext applicationContext = null; public PulseService getPulseServiceInstance(final String servicename) { if (applicationContext != null && applicationContext.containsBean(servicename)) { return (PulseService) applicationContext.getBean(servicename); } return null; } @Override public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
34.396226
100
0.781679
0a169d2fa6c343fa4829001b75be75c18f755d92
4,326
/** * MIT License * <p> * Copyright (c) 2019-2020 nerve.network * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package network.nerve.converter.heterogeneouschain.eth.storage.impl; import io.nuls.core.core.annotation.Component; import io.nuls.core.rockdb.service.RocksDBService; import network.nerve.converter.heterogeneouschain.eth.constant.EthDBConstant; import network.nerve.converter.heterogeneouschain.eth.model.EthAccount; import network.nerve.converter.heterogeneouschain.eth.storage.EthAccountStorageService; import network.nerve.converter.model.bo.HeterogeneousAccount; import network.nerve.converter.model.po.StringSetPo; import network.nerve.converter.utils.ConverterDBUtil; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static network.nerve.converter.utils.ConverterDBUtil.stringToBytes; /** * @author: Mimi * @date: 2020-02-20 */ @Component public class EthAccountStorageServiceImpl implements EthAccountStorageService { private final String baseArea = EthDBConstant.DB_ETH; private final String KEY_PREFIX = "ACCOUNT-"; private final byte[] ACCOUNT_ALL_KEY = stringToBytes("ACCOUNT-ALL"); @Override public int save(EthAccount po) throws Exception { if (po == null) { return 0; } boolean result = ConverterDBUtil.putModel(baseArea, stringToBytes(KEY_PREFIX + po.getAddress()), po); if (result) { StringSetPo accountSetPo = ConverterDBUtil.getModel(baseArea, ACCOUNT_ALL_KEY, StringSetPo.class); if (accountSetPo == null) { accountSetPo = new StringSetPo(); Set<String> set = new HashSet<>(); set.add(po.getAddress()); accountSetPo.setCollection(set); result = ConverterDBUtil.putModel(baseArea, ACCOUNT_ALL_KEY, accountSetPo); } else { accountSetPo.getCollection().add(po.getAddress()); result = ConverterDBUtil.putModel(baseArea, ACCOUNT_ALL_KEY, accountSetPo); } } return result ? 1 : 0; } @Override public EthAccount findByAddress(String address) { return ConverterDBUtil.getModel(baseArea, stringToBytes(KEY_PREFIX + address), EthAccount.class); } @Override public void deleteByAddress(String address) throws Exception { RocksDBService.delete(baseArea, stringToBytes(KEY_PREFIX + address)); StringSetPo accountSetPo = ConverterDBUtil.getModel(baseArea, ACCOUNT_ALL_KEY, StringSetPo.class); if(accountSetPo != null) { accountSetPo.getCollection().remove(address); ConverterDBUtil.putModel(baseArea, ACCOUNT_ALL_KEY, accountSetPo); } } @Override public List<HeterogeneousAccount> findAll() { StringSetPo accountSetPo = ConverterDBUtil.getModel(baseArea, ACCOUNT_ALL_KEY, StringSetPo.class); if (accountSetPo == null) { return null; } Set<String> ethAccountSet = accountSetPo.getCollection(); List<HeterogeneousAccount> resultList = new ArrayList<>(); for (String address : ethAccountSet) { resultList.add(this.findByAddress(address)); } return resultList; } }
41.2
110
0.709663
0a2cf26dc4f1e122192ae8b5882d5d698a2d2931
2,297
package com.github.amarcinkowski.metro.command; import com.google.common.base.Splitter; import lombok.extern.slf4j.Slf4j; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Vector; import java.util.concurrent.TimeUnit; @Slf4j public class SystemCommand extends Command { public SystemCommand(Vector<String> args, HashMap<String, String> typedArgs) { super(args, typedArgs); } private String[] getCommand() { String command = getTypedArgs().get("command"); String commandArgs = getTypedArgs().get("commandArgs"); log.debug("EXEC system: " + command + " arg: " + commandArgs); Splitter splitter = Splitter.on('\n').omitEmptyStrings().trimResults(); List<String> commandLineList = new ArrayList<>(); commandLineList.add(command); try { commandLineList.addAll(splitter.splitToList(commandArgs)); } catch (Exception e) { } log.trace("Command " + commandLineList); return commandLineList.toArray(new String[]{}); } @Override public String execute() { String timeoutString = getTypedArgs().get("timeout"); StringBuffer output = new StringBuffer(); Process p; try { p = Runtime.getRuntime().exec(getCommand()); Integer timeout = Integer.parseInt(timeoutString); if (timeout == 0) { return "NO-OUTPUT"; } if (!p.waitFor(timeout, TimeUnit.SECONDS)) { //timeout - kill the process. p.destroy(); // consider using destroyForcibly instead } else { // p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { System.out.println(">" + line); output.append(line + "\n"); } } } catch (Exception e) { e.printStackTrace(); } log.debug("EXEC system output: " + output.toString()); return output.toString(); } }
32.814286
86
0.58337
e318bf00c40dc4585a9b84758a5ae27fdf921610
5,321
/** * Copyright 5AM Solutions Inc, ESAC, ScenPro & SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caintegrator/LICENSE.txt for details. */ package gov.nih.nci.caintegrator.file; import edu.wustl.icr.asrv1.segment.SampleWithChromosomalSegmentSet; import gov.nih.nci.caintegrator.application.analysis.GctDataset; import gov.nih.nci.caintegrator.application.analysis.SampleClassificationParameterValue; import gov.nih.nci.caintegrator.application.study.StudyConfiguration; import gov.nih.nci.caintegrator.domain.application.AbstractPersistedAnalysisJob; import gov.nih.nci.caintegrator.domain.application.ResultsZipFile; import gov.nih.nci.caintegrator.domain.application.StudySubscription; import gov.nih.nci.caintegrator.domain.translational.Study; import java.io.File; import java.io.IOException; import org.genepattern.gistic.Marker; /** * Provides file storage and retrieval functionality. */ public interface FileManager { /** * Persists a file in caIntegrator 2. This allows temp files to be copied into permanent storage associated * with a study. * * @param sourceFile the contents to be stored. The source file may be deleted after the completion of this method. * @param filename the filename to use for the file (may be different from sourceFile.getName()). * @param studyConfiguration file is associated with this studyConfiguration. * @return the permanent file. * @throws IOException if the file couldn't be copied to its destination. */ File storeStudyFile(File sourceFile, String filename, StudyConfiguration studyConfiguration) throws IOException; /** * Deletes the storage directory for the given study. * @param studyConfiguration for the directory to delete. */ void deleteStudyDirectory(StudyConfiguration studyConfiguration); /** * Returns the storage directory for the given study. * * @param study get directory for this study. * @return the directory. */ File getStudyDirectory(Study study); /** * Creates a temporary directory to use based on the given directory name. * @param dirName temporary directory name to use (just name, not path). * @return the directory. */ File getNewTemporaryDirectory(String dirName); /** * Gets temporary director. * @return temporary directory. */ String getTempDirectory(); /** * Retrieves the directory for the study subscription's user. * @param studySubscription to get username from. * @return the directory. */ File getUserDirectory(StudySubscription studySubscription); /** * Creates a file (with given name) in the study directory. * @param studySubscription to get directory for user. * @param filename of file to return. * @return newly created file. */ File createNewStudySubscriptionFile(StudySubscription studySubscription, String filename); /** * Creates a classification file (.cls) for the given sampleClassifications. * @param studySubscription to store file to user directory. * @param sampleClassifications for classifying samples. * @param clsFilename name of file. * @return .cls file. */ File createClassificationFile(StudySubscription studySubscription, SampleClassificationParameterValue sampleClassifications, String clsFilename); /** * Creates a GCT file based on the gctDataset. * @param studySubscription to store file to study folder. * @param gctDataset for genomic data to be written to file. * @param filename name of file. * @return .gct file. */ File createGctFile(StudySubscription studySubscription, GctDataset gctDataset, String filename); /** * Creates samples file for GISTIC input. * @param studySubscription to store file to study folder. * @param samples to write to file. * @return gistic input sample segment file. * @throws IOException if unable to write file. */ File createSamplesFile(StudySubscription studySubscription, SampleWithChromosomalSegmentSet[] samples) throws IOException; /** * Creates markers file for GISTIC input. * @param studySubscription to store file to study folder. * @param markers to write to file * @return gistic input markers file. * @throws IOException if unable to write file. */ File createMarkersFile(StudySubscription studySubscription, Marker[] markers) throws IOException; /** * Renames the cnvFile so it can be used by GISTIC grid service. * @param cnvFile to rename. * @return new cnvFile * @throws IOException if unable to rename. */ File renameCnvFile(File cnvFile) throws IOException; /** * Creates the input zip file for a given job. * @param studySubscription to store file to study folder. * @param job analysis job. * @param filename of the zip file to be created. * @param files set of input files. * @return input zip file. */ ResultsZipFile createInputZipFile(StudySubscription studySubscription, AbstractPersistedAnalysisJob job, String filename, File... files); }
37.737589
119
0.710017
5f766153fc2c7aedda6380534ad2aa99f2f38153
6,147
package eu.socialsensor.clustering; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ExecutionException; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import eu.socialsensor.graphdatabases.GraphDatabase; /** * Cache implementation for the temporary storage of required information of the * graph databases in order to execute the Louvain Method * * @author sotbeis * @email sotbeis@iti.gr */ public class Cache { LoadingCache<Integer, Set<Integer>> nodeCommunitiesMap; // key=nodeCommunity // value=nodeIds // contained in // nodeCommunityC LoadingCache<Integer, Set<Integer>> communitiesMap; // key=community // value=nodeIds // contained in // community LoadingCache<Integer, Integer> nodeCommunitiesToCommunities; // key=nodeCommunity // value=community LoadingCache<Integer, Set<Integer>> nodeNeighbours; // key=nodeId // value=nodeId // neighbors LoadingCache<Integer, Integer> nodeToCommunityMap; // key=nodeId // value=communityId public Cache(final GraphDatabase<?,?,?,?> graphDatabase, int cacheSize) throws ExecutionException { nodeNeighbours = CacheBuilder.newBuilder().maximumSize(cacheSize) .build(new CacheLoader<Integer, Set<Integer>>() { public Set<Integer> load(Integer nodeId) { return graphDatabase.getNeighborsIds(nodeId); } }); nodeCommunitiesMap = CacheBuilder.newBuilder().maximumSize(cacheSize) .build(new CacheLoader<Integer, Set<Integer>>() { public Set<Integer> load(Integer nodeCommunityId) { return graphDatabase.getNodesFromNodeCommunity(nodeCommunityId); } }); communitiesMap = CacheBuilder.newBuilder().maximumSize(cacheSize) .build(new CacheLoader<Integer, Set<Integer>>() { public Set<Integer> load(Integer communityId) { return graphDatabase.getNodesFromCommunity(communityId); } }); nodeToCommunityMap = CacheBuilder.newBuilder().maximumSize(cacheSize) .build(new CacheLoader<Integer, Integer>() { public Integer load(Integer nodeId) { return graphDatabase.getCommunityFromNode(nodeId); } }); nodeCommunitiesToCommunities = CacheBuilder.newBuilder().maximumSize(cacheSize) .build(new CacheLoader<Integer, Integer>() { public Integer load(Integer nodeCommunity) { return graphDatabase.getCommunity(nodeCommunity); } }); } public Set<Integer> getCommunitiesConnectedToNodeCommunities(int nodeCommunity) throws ExecutionException { Set<Integer> nodesFromNodeCommunity = nodeCommunitiesMap.get(nodeCommunity); Set<Integer> communities = new HashSet<Integer>(); for (int nodeFromNodeCommunity : nodesFromNodeCommunity) { Set<Integer> neighbors = nodeNeighbours.get(nodeFromNodeCommunity); for (int neighbor : neighbors) { communities.add(nodeToCommunityMap.get(neighbor)); } } return communities; } public void moveNodeCommunity(int nodeCommunity, int toCommunity) throws ExecutionException { int fromCommunity = nodeCommunitiesToCommunities.get(nodeCommunity); nodeCommunitiesToCommunities.put(nodeCommunity, toCommunity); Set<Integer> nodesFromCommunity = communitiesMap.get(fromCommunity); communitiesMap.invalidate(fromCommunity); communitiesMap.get(toCommunity).addAll(nodesFromCommunity); Set<Integer> nodesFromNodeCommunity = nodeCommunitiesMap.get(nodeCommunity); for (int nodeFromCommunity : nodesFromNodeCommunity) { nodeToCommunityMap.put(nodeFromCommunity, toCommunity); } } public double getNodeCommunityWeight(int nodeCommunity) throws ExecutionException { Set<Integer> nodes = nodeCommunitiesMap.get(nodeCommunity); double weight = 0; for (int node : nodes) { weight += nodeNeighbours.get(node).size(); } return weight; } public int getCommunity(int community) throws ExecutionException { return nodeCommunitiesToCommunities.get(community); } public int getCommunitySize(int community) throws ExecutionException { return communitiesMap.get(community).size(); } public double getEdgesInsideCommunity(int nodeCommunity, int community) throws ExecutionException { Set<Integer> nodeCommunityNodes = nodeCommunitiesMap.get(nodeCommunity); Set<Integer> communityNodes = communitiesMap.get(community); double edges = 0; for (int nodeCommunityNode : nodeCommunityNodes) { for (int communityNode : communityNodes) { if (nodeNeighbours.get(nodeCommunityNode).contains(communityNode)) { edges++; } } } return edges; } public void reInitializeCommunities() { nodeCommunitiesMap.invalidateAll(); communitiesMap.invalidateAll(); nodeToCommunityMap.invalidateAll(); nodeCommunitiesToCommunities.invalidateAll(); } }
38.660377
109
0.589231
e8f6fbfb32393feab33a83bc639b798ac1227172
3,009
package moze_intel.projecte.gameObjs.blocks; import javax.annotation.Nonnull; import javax.annotation.Nullable; import moze_intel.projecte.gameObjs.EnumRelayTier; import moze_intel.projecte.gameObjs.tiles.RelayMK1Tile; import moze_intel.projecte.gameObjs.tiles.RelayMK2Tile; import moze_intel.projecte.gameObjs.tiles.RelayMK3Tile; import moze_intel.projecte.utils.MathUtils; import moze_intel.projecte.utils.WorldHelper; import net.minecraft.block.BlockState; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ActionResultType; import net.minecraft.util.Direction; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.world.IBlockReader; import net.minecraft.world.World; import net.minecraftforge.fml.network.NetworkHooks; import net.minecraftforge.items.CapabilityItemHandler; public class Relay extends BlockDirection { private final EnumRelayTier tier; public Relay(EnumRelayTier tier, Properties props) { super(props); this.tier = tier; } public EnumRelayTier getTier() { return tier; } @Nonnull @Override @Deprecated public ActionResultType onBlockActivated(@Nonnull BlockState state, World world, @Nonnull BlockPos pos, @Nonnull PlayerEntity player, @Nonnull Hand hand, @Nonnull BlockRayTraceResult rtr) { if (!world.isRemote) { TileEntity te = world.getTileEntity(pos); if (te instanceof RelayMK1Tile) { NetworkHooks.openGui((ServerPlayerEntity) player, (RelayMK1Tile) te, pos); } } return ActionResultType.SUCCESS; } @Override public boolean hasTileEntity(BlockState state) { return true; } @Nullable @Override public TileEntity createTileEntity(@Nonnull BlockState state, @Nonnull IBlockReader world) { switch (tier) { case MK1: return new RelayMK1Tile(); case MK2: return new RelayMK2Tile(); case MK3: return new RelayMK3Tile(); default: return null; } } @Override @Deprecated public boolean hasComparatorInputOverride(@Nonnull BlockState state) { return true; } @Override @Deprecated public int getComparatorInputOverride(@Nonnull BlockState state, World world, @Nonnull BlockPos pos) { TileEntity te = world.getTileEntity(pos); if (te instanceof RelayMK1Tile) { RelayMK1Tile relay = (RelayMK1Tile) te; return MathUtils.scaleToRedstone(relay.getStoredEmc(), relay.getMaximumEmc()); } return 0; } @Override public void onReplaced(BlockState state, World world, @Nonnull BlockPos pos, @Nonnull BlockState newState, boolean isMoving) { if (state.getBlock() != newState.getBlock()) { TileEntity te = world.getTileEntity(pos); if (te != null) { te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, Direction.DOWN).ifPresent(inv -> WorldHelper.dropInventory(inv, world, pos)); } super.onReplaced(state, world, pos, newState, isMoving); } } }
30.704082
190
0.775673
7416c0c35b222d2a4908c0381130592e255d1681
815
package pbuf; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import pbuf.App.BiobtreeGetRequest; import pbuf.App.BiobtreeGetResponse; import pbuf.BiobtreeServiceGrpc.BiobtreeServiceBlockingStub; public class Client { public static void main(String args[]) { ManagedChannelBuilder chan = ManagedChannelBuilder.forAddress("localhost", 7777).usePlaintext(); ManagedChannel ch= chan.build(); BiobtreeServiceBlockingStub b= BiobtreeServiceGrpc.newBlockingStub(ch); // now make the request BiobtreeGetRequest request=BiobtreeGetRequest.newBuilder().addKeywords("tpi1").build(); BiobtreeGetResponse res= b.get(request); System.out.println("Number of results for tpi1 ->"+res.getResultsList().size()); } }
29.107143
102
0.721472
59aeb23e4fbed0324235cd2ec498bcbe79535807
735
package com.aidanwhiteley.books.repository.dtos; import com.aidanwhiteley.books.domain.Book; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; class BooksByRatingTest { @Test void testEqualsHashcode() { BooksByRating by = new BooksByRating(Book.Rating.POOR, 1); assertNotEquals(by, new BooksByRating(Book.Rating.POOR, 2)); assertEquals(by, new BooksByRating(Book.Rating.POOR, 1)); assertNotEquals(by.hashCode(), new BooksByRating(Book.Rating.POOR, 2).hashCode()); assertEquals(by.hashCode(), new BooksByRating(Book.Rating.POOR, 1).hashCode()); } }
35
91
0.715646
c48284bc4774c185d20624e0183c21ae2a373ee7
1,260
package web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.UserDAO; import entity.User; public class AddUserServlet extends HttpServlet{ public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{ request.setCharacterEncoding("utf-8"); response.setContentType( "text/html;charset=utf-8"); PrintWriter out = response.getWriter(); /* * 读取用户信息 */ String username = request.getParameter("uname"); String pwd = request.getParameter("pwd"); String phone = request.getParameter("phone"); System.out.println("username:" + username + " pwd:" + pwd + " phone:" + phone); /* * 服务器端应该对用户提交的数据进行合法性检查, * 比如,检查用户名是否为空等,此处暂时不考虑。 */ /* * 使用DAO将用户信息插入到数据库 */ UserDAO dao = new UserDAO(); User user = new User(); user.setUsername(username); user.setPwd(pwd); user.setPhone(phone); try{ dao.save(user); out.println("添加成功"); }catch(Exception e){ e.printStackTrace(); out.println("系统繁忙,稍后重试"); } } }
18.80597
48
0.684921
008059fda9e770924cf33132880eb06c8d3b125d
11,042
/* * Copyright 2001-present Stephen Colebourne * * 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.joda.beans.test; import static org.junit.Assert.assertEquals; import org.joda.beans.sample.Address; import org.joda.beans.sample.ImmTolerance; import org.joda.beans.sample.Person; import org.junit.Before; import org.junit.Test; /** * Test BeanAssert. */ public class TestBeanAssert { private Person person1; private Person person2; @Before public void setUp() { person1 = new Person(); person1.setForename("Vince"); person1.setSurname("Cable"); person1.setNumberOfCars(1); person1.getAddressList().add(new Address()); person1.getAddressList().get(0).setNumber(12); person1.getAddressList().get(0).setStreet("Play Street"); person1.getAddressList().get(0).setCity("Toytown"); person1.getAddressList().get(0).setOwner(new Person()); person1.getAddressList().get(0).getOwner().setForename("Nick"); person1.getAddressList().get(0).getOwner().setSurname("Clegg"); person1.setMainAddress(new Address()); person1.getMainAddress().setStreet("Party Road"); person1.getMainAddress().setCity("Gamesville"); person1.getMainAddress().setOwner(new Person()); person1.getMainAddress().getOwner().setForename("Simon"); person1.getMainAddress().getOwner().setForename("Hughes"); person1.getOtherAddressMap().put("Home", new Address()); person1.getOtherAddressMap().get("Home").setNumber(999); person1.getOtherAddressMap().get("Home").setStreet("Upper Lane"); person1.getOtherAddressMap().get("Home").setCity("Skyton"); person2 = new Person(); person2.setForename("Vince"); person2.setSurname("Cable"); person2.setNumberOfCars(1); person2.getAddressList().add(new Address()); person2.getAddressList().get(0).setNumber(12); person2.getAddressList().get(0).setStreet("Play Street"); person2.getAddressList().get(0).setCity("Toytown"); person2.getAddressList().get(0).setOwner(new Person()); person2.getAddressList().get(0).getOwner().setForename("Nick"); person2.getAddressList().get(0).getOwner().setSurname("Clegg"); person2.setMainAddress(new Address()); person2.getMainAddress().setStreet("Party Road"); person2.getMainAddress().setCity("Gamesville"); person2.getMainAddress().setOwner(new Person()); person2.getMainAddress().getOwner().setForename("Simon"); person2.getMainAddress().getOwner().setForename("Hughes"); person2.getOtherAddressMap().put("Home", new Address()); person2.getOtherAddressMap().get("Home").setNumber(999); person2.getOtherAddressMap().get("Home").setStreet("Upper Lane"); person2.getOtherAddressMap().get("Home").setCity("Skyton"); } @Test public void test_same() { BeanAssert.assertBeanEquals(person1, person1); } @Test public void test_equal() { BeanAssert.assertBeanEquals(person1, person2); } @Test public void test_bean_oneField() { person2.setForename("Bug1"); try { BeanAssert.assertBeanEquals(person1, person2); } catch (BeanComparisonError ex) { assertEquals("Bean did not equal expected. Differences:\n.forename: Content differs, expected String <Vince> but was <Bug1>", ex.getMessage()); System.out.println(ex.getMessage()); } } @Test public void test_bean_twoFields() { person2.setForename("Bug1"); person2.setSurname("Bug2"); try { BeanAssert.assertBeanEquals(person1, person2); } catch (BeanComparisonError ex) { assertEquals("Bean did not equal expected. Differences:\n.forename: Content differs, expected String <Vince> but was <Bug1>\n.surname: Content differs, expected String <Cable> but was <Bug2>", ex.getMessage()); System.out.println(ex.getMessage()); } } @Test public void test_bean_bug_embedded() { person2.getAddressList().get(0).setNumber(234); person2.getMainAddress().setCity("Bug3"); try { BeanAssert.assertBeanEquals(person1, person2); } catch (BeanComparisonError ex) { assertEquals("Bean did not equal expected. Differences:\n.addressList[0].number: Content differs, expected Integer <12> but was <234>\n.mainAddress.city: Content differs, expected String <Gamesville> but was <Bug3>", ex.getMessage()); System.out.println(ex.getMessage()); } } @Test public void test_bean_sizes() { Address address = new Address(); address.setCity("Nowhere"); person2.getOtherAddressMap().put("Bug", address); person2.getAddressList().clear(); try { BeanAssert.assertBeanEquals(person1, person2); } catch (BeanComparisonError ex) { assertEquals("Bean did not equal expected. Differences:\n.addressList: List size differs, expected 1 but was 0\n.otherAddressMap: Map size differs, expected 1 but was 2", ex.getMessage()); System.out.println(ex.getMessage()); } } @Test public void test_bean_map() { person2.getOtherAddressMap().get("Home").setCity("Bug"); person2.getOtherAddressMap().get("Home").setOwner(new Person()); try { BeanAssert.assertBeanEquals(person1, person2); } catch (BeanComparisonError ex) { assertEquals("Bean did not equal expected. Differences:\n.otherAddressMap[Home].city: Content differs, expected String <Skyton> but was <Bug>\n.otherAddressMap[Home].owner: Expected null, but was Person <Person{forename=null, surname=null, numberOfCars=0, addre...>", ex.getMessage()); System.out.println(ex.getMessage()); } } @Test public void test_beanFullDetail_twoFields() { person2.setForename("Bug1"); person2.setSurname("Bug2"); try { BeanAssert.assertBeanEqualsFullDetail(person1, person2); } catch (BeanComparisonError ex) { assertEquals("Bean did not equal expected. Differences:\n.forename: Content differs, expected String <Vince> but was <Bug1>\n.surname: Content differs, expected String <Cable> but was <Bug2>", ex.getMessage()); System.out.println(ex.getMessage()); } } //----------------------------------------------------------------------- @Test public void test_bean_oneField_double() { ImmTolerance t1 = ImmTolerance.builder().value(0.015d).build(); ImmTolerance t2 = ImmTolerance.builder().value(0.016d).build(); try { BeanAssert.assertBeanEquals(t1, t2); } catch (BeanComparisonError ex) { assertEquals("Bean did not equal expected. Differences:\n.value: Content differs, expected Double <0.015> but was <0.016>", ex.getMessage()); System.out.println(ex.getMessage()); } } @Test public void test_bean_oneField_double_withinToleranceUp() { ImmTolerance t1 = ImmTolerance.builder().value(0.015d).build(); ImmTolerance t2 = ImmTolerance.builder().value(0.0151d).build(); BeanAssert.assertBeanEquals(t1, t2, 0.0002d); } @Test public void test_bean_oneField_double_withinToleranceDown() { ImmTolerance t1 = ImmTolerance.builder().value(0.015d).build(); ImmTolerance t2 = ImmTolerance.builder().value(0.0149d).build(); BeanAssert.assertBeanEquals(t1, t2, 0.0002d); } @Test public void test_bean_oneField_double_notInTolerance() { ImmTolerance t1 = ImmTolerance.builder().value(0.015d).build(); ImmTolerance t2 = ImmTolerance.builder().value(0.0153d).build(); try { BeanAssert.assertBeanEquals(t1, t2, 0.0002d); } catch (BeanComparisonError ex) { assertEquals("Bean did not equal expected. Differences:\n.value: Double values differ by more than allowed tolerance, expected Double <0.015> but was <0.0153>", ex.getMessage()); System.out.println(ex.getMessage()); } } //----------------------------------------------------------------------- @Test public void test_bean_oneField_doubleArray() { ImmTolerance t1 = ImmTolerance.builder().array(new double[] {0.015d, 0.015d}).build(); ImmTolerance t2 = ImmTolerance.builder().array(new double[] {0.015d, 0.016d}).build(); try { BeanAssert.assertBeanEquals(t1, t2); } catch (BeanComparisonError ex) { assertEquals("Bean did not equal expected. Differences:\n.array: Content differs, expected " + "double[] <[0.015, 0.015]> but was <[0.015, 0.016]>", ex.getMessage()); System.out.println(ex.getMessage()); } } @Test public void test_bean_oneField_doubleArray_withinToleranceUp() { ImmTolerance t1 = ImmTolerance.builder().array(new double[] {0.015d, 0.015d}).build(); ImmTolerance t2 = ImmTolerance.builder().array(new double[] {0.015d, 0.0151d}).build(); BeanAssert.assertBeanEquals(t1, t2, 0.0002d); } @Test public void test_bean_oneField_doubleArray_withinToleranceDown() { ImmTolerance t1 = ImmTolerance.builder().array(new double[] {0.015d, 0.015d}).build(); ImmTolerance t2 = ImmTolerance.builder().array(new double[] {0.015d, 0.0149d}).build(); BeanAssert.assertBeanEquals(t1, t2, 0.0002d); } @Test public void test_bean_oneField_doubleArray_notInTolerance() { ImmTolerance t1 = ImmTolerance.builder().array(new double[] {0.015d, 0.015d}).build(); ImmTolerance t2 = ImmTolerance.builder().array(new double[] {0.015d, 0.0153d}).build(); try { BeanAssert.assertBeanEquals(t1, t2, 0.0002d); } catch (BeanComparisonError ex) { assertEquals("Bean did not equal expected. Differences:\n.array: Double arrays differ by " + "more than allowed tolerance, expected double[] <[0.015, 0.015]> but was <[0.015, 0.0153]>", ex.getMessage()); System.out.println(ex.getMessage()); } } }
45.069388
298
0.62869
9424c0f0923d4bd37f66e7dc3422b8b8205f0a0b
3,327
package com.dargoz.jetpack.ui.movie; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.dargoz.jetpack.R; import com.dargoz.jetpack.data.source.local.entity.MovieEntity; import com.dargoz.jetpack.viewmodel.ViewModelFactory; import java.util.List; import static com.dargoz.jetpack.utils.Constants.Category.URL_MOVIES; public class MovieFragment extends Fragment implements MovieViewModel.ErrorListener { private View root; private RecyclerView movieRecyclerView; private Button reloadButton; private ProgressBar progressBar; public MovieFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment root = inflater.inflate(R.layout.fragment_movie, container, false); return root; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); reloadButton = root.findViewById(R.id.movie_reload_button); progressBar = root.findViewById(R.id.movie_progress_bar); movieRecyclerView = root.findViewById(R.id.movie_recycler_view); movieRecyclerView.setLayoutManager(new GridLayoutManager(view.getContext(),2)); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if(getActivity() != null){ MovieViewModel viewModel = obtainViewModel(getActivity()); viewModel.setErrorCallbackListener(this); viewModel.setMovieEntities(); viewModel.getMovieList().observe(this, getMovies); reloadButton.setOnClickListener(viewButton -> { progressBar.setVisibility(View.VISIBLE); reloadButton.setVisibility(View.GONE); obtainViewModel(getActivity()); viewModel.setMovieEntities(); }); } } private static MovieViewModel obtainViewModel(FragmentActivity activity){ ViewModelFactory factory = ViewModelFactory.getInstance(activity.getApplication(), URL_MOVIES); return ViewModelProviders.of(activity, factory).get(MovieViewModel.class); } private final Observer<List<MovieEntity>> getMovies = movieEntities -> { progressBar.setVisibility(View.GONE); MovieRecyclerViewAdapter adapter = new MovieRecyclerViewAdapter(); adapter.setMovieEntities(movieEntities); movieRecyclerView.setAdapter(adapter); }; @Override public void onResponseError() { reloadButton.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); } }
36.56044
88
0.724376
8bc2c9f50691e4293af392e269ef231bfbbb6258
1,209
package com.napier.gp2; //A parent class of city with attributes public class City { // city name private String name; // country of city private String country; // district of city private String district; // population of city private int population; // set city name public void setName(String cname){ name = cname; } //get name of city to be able to access by another class public String getName(){ return name; } //set country name public void setCountry(String ccountry){ country = ccountry; } //get name of city to be able to access by another class public String getCountry(){ return country; } //set district name public void setDistrict(String cdistrict){ district = cdistrict; } //get name of city to be able to access by another class public String getDistrict(){ return district; } //set population of city public void setPopulation(int cpopulation){ population = cpopulation; } //get population of city to be able to access by another class public int getPopulation(){ return population; } }
20.844828
66
0.635236
ca10e999ce4b2bb33212bb9fffc2bf35140a8803
1,630
/** * Copyright 2005-2016 Restlet * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or or EPL 1.0 (the "Licenses"). You can * select the license that you prefer but you may not use this file except in * compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.security; import org.restlet.message.Request; import org.restlet.message.Response; /** * Authorizer allowing only confidential calls. Confidential calls typically * come through HTTPS server connectors. * * @author Jerome Louvel */ public class ConfidentialAuthorizer extends Authorizer { /** * Authorizes the request only if its method is one of the authorized * methods. * * @param request * The request sent. * @param response * The response to update. * @return True if the authorization succeeded. */ @Override public boolean authorize(Request request, Response response) { return request.isConfidential(); } }
30.185185
77
0.704294
8584aa424740e5122ab2ae6cf4ef8f080b246f15
883
package it.andreafailli.remindme.common.models; public class Subscription extends BaseEntity { private String userId; public Subscription() {} public Subscription(String id) { super(id); } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((userId == null) ? 0 : userId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof Subscription)) return false; Subscription other = (Subscription) obj; if (userId == null) { if (other.userId != null) return false; } else if (!userId.equals(other.userId)) return false; return true; } }
18.787234
71
0.667044
65c8fe37e5b7e19d80d6bd205f119bed7dad26b1
8,365
package common.ejb; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import junit.framework.TestCase; import org.aries.Handler; import org.aries.Processor; import org.aries.ejb.EJBClientImpl; import org.aries.ejb.EJBEndpointContext; import org.aries.ejb.EJBServiceImpl; import org.aries.jndi.JndiContext; import org.aries.jndi.JndiProxy; import org.aries.nam.model.old.OperationDefinition; import org.aries.nam.model.old.OperationDescripter; import org.aries.nam.model.old.ParameterDefinition; import org.aries.nam.model.old.ResultDefinition; import org.aries.runtime.BeanContext; import org.aries.service.ServiceRepository; import org.aries.service.registry.ServiceState; import org.aries.util.IdGenerator; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class EJBClientImplTest extends TestCase { @Mock private JndiContext mockJndiContext; @Mock private EJBServiceImpl mockServerStub; private EJBEndpointContext context; private EJBClientImpl client; private EJBServiceImpl server; private String serviceId = "serviceId"; private boolean holdStrongReference = false; private boolean invokeGarbageCollector = true; private Processor<String, String> processor; @Mock private ServiceRepository serviceRepository; //private EJBService classLevelInstance = new EJBServiceImpl(); @Before public void setUp() throws Exception { initializeContext(); initializeServer(); initializeClient(); initializeRepository(); } @After public void tearDown() throws Exception { client = null; } protected void initializeContext() { mockJndiContext = mock(JndiContext.class); when(mockJndiContext.getConnectionUrl()).thenReturn("jnp://127.0.0.1:1099"); when(mockJndiContext.getContextFactory()).thenReturn("org.jnp.interfaces.NamingContextFactory"); ServiceState serviceState = createServiceStateForTest(); OperationDescripter operationDescripter = createOperationDefinitionForTest(); context = new EJBEndpointContext(); context.setServiceState(serviceState); context.setOperationDescripter(operationDescripter); context.setJndiContext(mockJndiContext); context.setJndiName("server"); } public JndiContext createJndiContext() { String url = "jnp://127.0.0.1:1099"; String factory = "org.jnp.interfaces.NamingContextFactory"; JndiContext jndiContext = createJndiContext(url, factory); return jndiContext; } public static JndiContext createJndiContext(String url, String factory) { JndiProxy jndiContext = new JndiProxy(); jndiContext.setConnectionUrl(url); jndiContext.setContextFactory(factory); return jndiContext; } public OperationDescripter createOperationDefinitionForTest() { ResultDefinition resultDescripter = new ResultDefinition(); resultDescripter.setType("org.aries.Message"); resultDescripter.setName("response"); ParameterDefinition parameterDescripter = new ParameterDefinition(); parameterDescripter.setType("org.aries.Message"); parameterDescripter.setName("request"); OperationDefinition descripter = new OperationDefinition(); descripter.setOperationName("process"); descripter.getResultDescripters().add(resultDescripter); descripter.addParameterDescripter(parameterDescripter); descripter.setTransacted(false); return descripter; } public ServiceState createServiceStateForTest() { ServiceState serviceState = new ServiceState(); serviceState.setServiceId(serviceId); return serviceState; } protected void initializeServer() throws Exception { processor = createProcessor(); mockServerStub = mock(EJBServiceImpl.class); when(mockJndiContext.lookupObject("deploy/common.rmi.EJBService/remote")).thenReturn(mockServerStub); //server.initialize(); } protected Processor<String, String> createProcessor() { return new Processor<String, String>() { public String process(String object) { return "My name is Tom"; } }; } protected void initializeClient() { client = createClient(); client.initialize(); } protected EJBClientImpl createClient() { EJBClientImpl client = new EJBClientImpl(); client.setEndpointContext(context); return client; } protected void initializeRepository() { SampleService sampleService = new SampleService(); when(serviceRepository.getServiceInstance(serviceId)).thenReturn(sampleService); BeanContext.set("org.aries.serviceRepository", serviceRepository); } @Test public void testInvokeSynch() throws Exception { String correlationId = IdGenerator.createId(); String request = new String("What is your name?"); String expectedResponse = new String("My name is Tom"); when(mockServerStub.invoke(request, serviceId, correlationId)).thenReturn(expectedResponse); String response = client.invoke(request, correlationId, 10000); assertNotNull("Response should exist", response); assertEquals("Response should be correct", response, expectedResponse); } // @Test // public void testInvokeAsynch() throws Exception { // String correlationId = IdGenerator.createId(); // String request = new String("What is your name?"); // String expectedResponse = new String("My name is Tom"); // Handler<String> handler = createHandler(); // Future<String> future = client.invoke(request, correlationId, handler); // verify(mockServerStub).invokeAsync(request, correlationId); // Handler<?> handlerRef = client.getHandlers().get(correlationId); // assertEquals("Handler should be set", handler, handlerRef); // assertNotNull("Placeholder should exist", future); // } protected Handler<String> createHandler() { return new Handler<String>() { public void handle(String message) { //do nothing } }; } class SampleService { public String process(String message) { return "Tom"; } } // @Test // @Ignore // public void testReceive() throws Exception { // final ConcurrentExecutor executor = new ConcurrentExecutorImpl(1); // Future<String> future = executor.submit(new Callable<String>() { // public String call() throws Exception { // synchronized (executor) { // executor.notify(); // } // String message = client.receive(50000); // assertNotNull("Message should exist", message); // assertEquals("Message should match", "Hello", message); // return message; // } // }); // synchronized (executor) { // executor.wait(); // } // Thread.sleep(1000); // String message = "Hello"; // server.publish(message); // Object object = future.get(); // assertNotNull("Object should exist", object); // Assert.isInstanceOf(String.class, object); // String result = (String) object; // assertEquals("Message should match", "Hello", result); // } @Test @Ignore public void testReceiveAsynch() throws Exception { //Future<String> future = client.receive(createHandler()); //String result = future.get(); } // protected RMIService getServerInstance() throws Exception { // // This reference is eligible for GC after this method returns // RMIService methodLevelInstance = new RMIServiceImpl(9345, "serviceId"); // RMIService instanceToBeStubbed = holdStrongReference ? classLevelInstance : methodLevelInstance; // Remote remote = UnicastRemoteObject.exportObject(instanceToBeStubbed, 0); // Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT); // RMIService stub = RMIServiceImpl.class.cast(remote); // registry.bind("serviceId", remote); // return stub; // } // // protected RMIClient getClientStub() throws Exception { // Registry registry = LocateRegistry.getRegistry(); // Remote remote = registry.lookup("serviceId"); // RMIClient stub = RMIServicePort.class.cast(remote); // return stub; // } protected ExecutorService createExecutor(int poolSize) { SynchronousQueue<Runnable> workQueue = new SynchronousQueue<Runnable>(); ThreadPoolExecutor executor = new ThreadPoolExecutor(1, poolSize, 1, TimeUnit.MINUTES, workQueue); executor.prestartAllCoreThreads(); return executor; } }
31.685606
103
0.756844
9b7e619a6f4568529e3fb1096eb8c765f1c187e8
2,729
package org.syftkog.web.automation.framework.test; import org.syftkog.web.test.framework.DriverFactory; import org.syftkog.web.test.framework.DesiredCapabilitiesFactory; import org.openqa.selenium.WebDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; //import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.syftkog.web.test.framework.PropertiesRetriever; import org.testng.Assert; import org.testng.annotations.Test; /** * * @author BenjaminLimb */ public class DriverFactoryTest { DriverFactory factory = new DriverFactory(); /** * */ @Test(groups = "local") public void testGetDriver() { WebDriver driver = factory.getDriver(); Assert.assertNotNull(driver); driver.quit(); } @Test(groups = "local") public void testGetDriverChrome() { DesiredCapabilities caps = DesiredCapabilitiesFactory.chrome(); WebDriver driver = factory.getDriver(caps); Assert.assertNotNull(driver); driver.quit(); } @Test(groups = "local") public void testGetPhantomJS() { // // DesiredCapabilities caps = new DesiredCapabilities(); // caps.setJavascriptEnabled(true); //if you don't set this to true you will probably be sorry //// caps.setCapability("phantomjs.page.settings.userAgent", agent); //This is for the purpose of spoofing other agents in order for some sites to works or to test IE and mobile actions coded in the web page // caps.setCapability("phantomjs.binary.path",PHANTOM_JS_DRIVER_PATH); //Path to directory on Electric Commander //// caps.setCapability("handlesAlerts", true); //Currently does not support alert boxes (Will pass OK or accept, via JavaScript, to every alert that occurs, if set to true) // WebDriver driver = new PhantomJSDriver(caps); //will be treated as any other driver from here on out //// driver.manage().window().setSize(new Dimension(320, 480)); //Set your size window if you desire (i.e. for mobile size testing and other) // // // DesiredCapabilities caps = DesiredCapabilitiesFactory.phantomJS(); // PhantomJSDriver phantomJSDriver = new PhantomJSDriver(caps); // phantomJSDriver.navigate().to("http://google.com"); // WebDriver driver = factory.getDriver(caps); Assert.assertNotNull(driver); driver.quit(); } /** * */ @Test(groups = "unit") public void testGetDriverWithCapabilitites() { DesiredCapabilities caps = DesiredCapabilitiesFactory.htmlunit(); WebDriver driver = factory.getDriver(caps); Assert.assertNotNull(driver); driver.quit(); } }
36.386667
217
0.695493
53df230bbd91c2d8a7964a5d83d7d78e69bae741
12,249
package com.andrefthompson.arcadiaquest; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import de.hdodenhof.circleimageview.CircleImageView; public class RolagemDados extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rolagem_dados); TextView txtDados = findViewById(R.id.textDados); TextView txtAtqCritico = findViewById(R.id.textAtqCritico); TextView txtAtqLonge = findViewById(R.id.textAtqLonge); TextView txtAtqProximo = findViewById(R.id.textAtqProximo); TextView txtErroDef = findViewById(R.id.textErroDef); TextView txtDefesaCritico = findViewById(R.id.textDefesaCritico); TextView txtDefesa = findViewById(R.id.textDefesa); ImageView imgDef = findViewById(R.id.imgDefesa); ImageView imgDefErro = findViewById(R.id.imgDefesaErro); ImageView imgAtqPert= findViewById(R.id.imgAtqPerto); ImageView imgAtqLong = findViewById(R.id.imgAtqLonge); CircleImageView btBriga = findViewById(R.id.btBriga); CircleImageView btMais = findViewById(R.id.btMais); CircleImageView btMenos = findViewById(R.id.btMenos); MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.som); MediaPlayer mediaPlayer2 = MediaPlayer.create(this, R.raw.som); MediaPlayer mediaPlayer3 = MediaPlayer.create(this, R.raw.som); btMais.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int valorDados = Integer.valueOf(txtDados.getText().toString()); int valorDadosoma = valorDados + 1; txtDados.setText(String.valueOf(valorDadosoma)); }}); btMenos.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int valorDados = Integer.valueOf(txtDados.getText().toString()); if (valorDados > 0){ int valorDadosoma = valorDados - 1; txtDados.setText(String.valueOf(valorDadosoma));} }}); btBriga.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mediaPlayer.isPlaying()){ mediaPlayer2.start(); }else if(mediaPlayer2.isPlaying() && mediaPlayer.isPlaying()){ mediaPlayer3.start(); }else {mediaPlayer.start();} txtAtqCritico.setText(String.valueOf(0)); txtAtqLonge.setText(String.valueOf(0)); txtAtqProximo.setText(String.valueOf(0)); txtDefesa.setText(String.valueOf(0)); txtDefesaCritico.setText(String.valueOf(0)); txtErroDef.setText(String.valueOf(0)); int valorDados = Integer.valueOf(txtDados.getText().toString()); //Ataque int valorDadosAtq = valorDados; for (int cont = 0; cont != valorDadosAtq; cont += 1) { int num = (int) (Math.random() * 6); if (num <= 2) { int atqProximo = Integer.valueOf(txtAtqProximo.getText().toString()); int soma = atqProximo + 1; txtAtqProximo.setText(String.valueOf(soma)); } else if (num == 5) { int atqCritico = Integer.valueOf(txtAtqCritico.getText().toString()); int soma = atqCritico + 1; valorDadosAtq++; txtAtqCritico.setText(String.valueOf(soma)); } else if (num==3 ^ num==4){ int atqLonge = Integer.valueOf(txtAtqLonge.getText().toString()); int soma = atqLonge + 1; txtAtqLonge.setText(String.valueOf(soma)); }} //Defesa int valorDadosDef = valorDados; for (int cont = 0; cont != valorDadosDef; cont += 1) { int num = (int) (Math.random() * 6); if (num <= 3) { int defE = Integer.valueOf(txtErroDef.getText().toString()); int soma = defE + 1; txtErroDef.setText(String.valueOf(soma)); } else if (num == 5) { int defesaCritico = Integer.valueOf(txtDefesaCritico.getText().toString()); int soma = defesaCritico + 1; valorDadosDef++; txtDefesaCritico.setText(String.valueOf(soma)); } else if (num==4){ int defesa = Integer.valueOf(txtDefesa.getText().toString()); int soma = defesa + 1; txtDefesa.setText(String.valueOf(soma)); } else{}} }}); //Rerrols imgDef.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mediaPlayer.isPlaying()){ mediaPlayer2.start(); }else if(mediaPlayer2.isPlaying() && mediaPlayer.isPlaying()){ mediaPlayer3.start(); }else {mediaPlayer.start();} int valorDef = Integer.valueOf(txtDefesa.getText().toString()); if (valorDef > 0){ int dim = valorDef - 1; txtDefesa.setText(String.valueOf(dim)); int valornv = 1; for (int cont = 0; cont != valornv; cont += 1) { int num = (int) (Math.random() * 6); if (num <= 3) { int defesaErro = Integer.valueOf(txtErroDef.getText().toString()); int soma = defesaErro + 1; txtErroDef.setText(String.valueOf(soma)); } else if (num == 5) { int defesaCritico = Integer.valueOf(txtDefesaCritico.getText().toString()); int soma = defesaCritico + 1; valornv++; txtDefesaCritico.setText(String.valueOf(soma)); } else if (num==4){ int defesa = Integer.valueOf(txtDefesa.getText().toString()); int soma = defesa + 1; txtDefesa.setText(String.valueOf(soma)); } } } } }); imgDefErro.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mediaPlayer.isPlaying()){ mediaPlayer2.start(); }else if(mediaPlayer2.isPlaying() && mediaPlayer.isPlaying()){ mediaPlayer3.start(); }else {mediaPlayer.start();} int valorDef = Integer.valueOf(txtErroDef.getText().toString()); if (valorDef > 0){ int dim = valorDef - 1; txtErroDef.setText(String.valueOf(dim)); int valornv2 = 1; for (int cont = 0; cont != valornv2; cont += 1) { int num = (int) (Math.random() * 6); if (num <= 3) { int defesaErro = Integer.valueOf(txtErroDef.getText().toString()); int soma = defesaErro + 1; txtErroDef.setText(String.valueOf(soma)); } else if (num == 5) { int defesaCritico = Integer.valueOf(txtDefesaCritico.getText().toString()); int soma = defesaCritico + 1; valornv2++; txtDefesaCritico.setText(String.valueOf(soma)); } else if (num==4){ int defesa = Integer.valueOf(txtDefesa.getText().toString()); int soma = defesa + 1; txtDefesa.setText(String.valueOf(soma)); } } } } }); imgAtqPert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mediaPlayer.isPlaying()){ mediaPlayer2.start(); }else if(mediaPlayer2.isPlaying() && mediaPlayer.isPlaying()){ mediaPlayer3.start(); }else {mediaPlayer.start();} int valorAtqP = Integer.valueOf(txtAtqProximo.getText().toString()); if (valorAtqP > 0){ int dim = valorAtqP - 1; txtAtqProximo.setText(String.valueOf(dim)); int valornv3 = 1; for (int cont = 0; cont != valornv3; cont += 1) { int num = (int) (Math.random() * 6); if (num <= 2) { int atqProximo = Integer.valueOf(txtAtqProximo.getText().toString()); int soma = atqProximo + 1; txtAtqProximo.setText(String.valueOf(soma)); } else if (num == 5) { int atqCritico = Integer.valueOf(txtAtqCritico.getText().toString()); int soma = atqCritico + 1; valornv3++; txtAtqCritico.setText(String.valueOf(soma)); } else if (num==3 ^ num==4){ int atqLonge = Integer.valueOf(txtAtqLonge.getText().toString()); int soma = atqLonge + 1; txtAtqLonge.setText(String.valueOf(soma)); }} } } }); imgAtqLong.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mediaPlayer.isPlaying()){ mediaPlayer2.start(); }else if(mediaPlayer2.isPlaying() && mediaPlayer.isPlaying()){ mediaPlayer3.start(); }else {mediaPlayer.start();} int valorAtqL = Integer.valueOf(txtAtqLonge.getText().toString()); if (valorAtqL > 0){ int dim = valorAtqL - 1; txtAtqLonge.setText(String.valueOf(dim)); int valornv4 = 1; for (int cont = 0; cont != valornv4; cont += 1) { int num = (int) (Math.random() * 6); if (num <= 2) { int atqProximo = Integer.valueOf(txtAtqProximo.getText().toString()); int soma = atqProximo + 1; txtAtqProximo.setText(String.valueOf(soma)); } else if (num == 5) { int atqCritico = Integer.valueOf(txtAtqCritico.getText().toString()); int soma = atqCritico + 1; valornv4++; txtAtqCritico.setText(String.valueOf(soma)); } else if (num==3 ^ num==4){ int atqLonge = Integer.valueOf(txtAtqLonge.getText().toString()); int soma = atqLonge + 1; txtAtqLonge.setText(String.valueOf(soma)); }} } } }); //Funcionamento CircleImageView viewReG =findViewById(R.id.viewSecreto); viewReG.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent regras = new Intent(getApplicationContext(), RegrasRolagens.class); startActivity(regras); }}); }}
50.407407
103
0.501592
fb899ca8c13b5d1b6128b090043576ca815c52e0
645
package com.drumge.kvo.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by chenrenzhan on 2018/4/29. * * 修饰观察 @KvoSource 中的指定的一个属性 */ @Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.CLASS) public @interface KvoWatch { enum Thread { DEFAULT, // 当前线程 MAIN, // UI 线程 WORK // 异步线程 } String tag() default ""; // 标识同对象不同实例 String name() default ""; // 观察属性的标识 Thread thread() default Thread.DEFAULT; }
22.241379
44
0.703876
2746069895d6dae89db723724fa0ab9ea789360a
391
package com.dadsunion.tron.service; import com.dadsunion.tron.domain.TronAddress; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; /** * 地址管理Service接口 * * @author l8oo8l * @date 2021-03-06 */ public interface ITronAddressService extends IService<TronAddress> { /** * 查询列表 */ List<TronAddress> queryList(TronAddress tronAddress); }
19.55
68
0.731458
6dbfe70e5291672fdcc3093c2505e76ed6729280
7,687
package edu.tamu.dspace.proxylicense; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.Arrays; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.util.SubmissionInfo; import org.dspace.app.util.Util; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.factory.AuthorizeServiceFactory; import org.dspace.authorize.service.AuthorizeService; import org.dspace.content.Bitstream; import org.dspace.content.BitstreamFormat; import org.dspace.content.Bundle; import org.dspace.content.Item; import org.dspace.content.LicenseUtils; import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.service.BitstreamFormatService; import org.dspace.content.service.BitstreamService; import org.dspace.content.service.ItemService; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.eperson.EPerson; import org.dspace.submit.step.LicenseStep; public class ProxyLicenseStep extends LicenseStep { // user rejected the license public static final int STATUS_LICENSE_REJECTED = 1; public static final int STATUS_BAD_PROXY_FILE = 2; protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); /** log4j logger */ private static Logger log = Logger.getLogger(LicenseStep.class); /** * Process the input from the license page * * @param context * current DSpace context * @param request * current servlet request object * @param response * current servlet response object * @param subInfo * submission info object * * @return Status or error flag which will be processed by * UI-related code! (if STATUS_COMPLETE or 0 is returned, * no errors occurred!) */ @Override public int doProcessing(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) throws ServletException, IOException, SQLException, AuthorizeException { String buttonPressed = Util.getSubmitButton(request, CANCEL_BUTTON); // For Manakin: // Add the license to the item Item item = subInfo.getSubmissionItem().getItem(); EPerson submitter = context.getCurrentUser(); // Get the full text for the actual licenses String defaultLicenseText = LicenseUtils.getLicenseText(context.getCurrentLocale(), subInfo.getSubmissionItem().getCollection(), item, submitter); String proxyLicenseText = XmluiProxyLicenseStep.loadLicense("proxy.license"); String openLicenseText = XmluiProxyLicenseStep.loadLicense("open.license");; // Accepting the license means checking one of the boxes and clicking Next String decision = request.getParameter("decision"); String licenseType = request.getParameter("license-selector"); // Load the file's path and input stream and description String filePath = (String) request.getAttribute("file-path"); InputStream fileInputStream = (InputStream) request.getAttribute("file-inputstream"); // If the user somehow clicked more than one box, or didn't click any, throw back an error if (buttonPressed.equals(NEXT_BUTTON) && (decision == null || licenseType == null || request.getParameterValues("decision").length > 1)) { return STATUS_LICENSE_REJECTED; } // This block makes the proxy statement required // else if ((buttonPressed.equals(NEXT_BUTTON) && licenseType.equalsIgnoreCase("proxy")) && // (filePath == null || fileInputStream == null)) { // return STATUS_BAD_PROXY_FILE; // } else { // Otherwise, it's accepted; it's just a matter of which one log.info(LogManager.getHeader(context, "accept_license", subInfo.getSubmissionLogInfo())); // remove any existing DSpace license (just in case the user accepted it previously) itemService.removeDSpaceLicense(context, item); } if (buttonPressed.equals(NEXT_BUTTON) && licenseType.equalsIgnoreCase("default")) { LicenseUtils.grantLicense(context, item, defaultLicenseText); context.commit(); } else if (buttonPressed.equals(NEXT_BUTTON) && licenseType.equalsIgnoreCase("proxy")) { LicenseUtils.grantLicense(context, item, proxyLicenseText); // If Proxy, create the extra file if we have one if (filePath != null && fileInputStream != null) { List<Bundle> bundles = itemService.getBundles(item,"LICENSE"); Bitstream bs = bitstreamService.create(context, bundles.get(0),fileInputStream); List<String> pieces = Arrays.asList(filePath.split("\\.")); if (pieces.size() == 1) bs.setName(context,"PERMISSION.license"); else bs.setName(context,"PERMISSION." + pieces.get(pieces.size()-1)); bs.setSource(context,filePath); bs.setDescription(context,"Proxy license"); // Identify the format BitstreamFormat bf = bitstreamFormatService.guessFormat(context, bs); bs.setFormat(context,bf); // FIXME: this does not seem to work for some reason. Maybe you can't change policies on pre-archived items? // FIXME: The previous line may or may not still be true, as we have now switched to an AuthorizeService with a different removal mechanism for 6x+ authorizeService.removePoliciesActionFilter(context, bs, Constants.READ); } context.commit(); } else if (buttonPressed.equals(NEXT_BUTTON) && licenseType.equalsIgnoreCase("open")) { LicenseUtils.grantLicense(context, item, openLicenseText); context.commit(); } return STATUS_COMPLETE; } /** * Retrieves the number of pages that this "step" extends over. This method * is used to build the progress bar. * <P> * This method may just return 1 for most steps (since most steps consist of * a single page). But, it should return a number greater than 1 for any * "step" which spans across a number of HTML pages. For example, the * configurable "Describe" step (configured using input-forms.xml) overrides * this method to return the number of pages that are defined by its * configuration file. * <P> * Steps which are non-interactive (i.e. they do not display an interface to * the user) should return a value of 1, so that they are only processed * once! * * @param request * The HTTP Request * @param subInfo * The current submission information object * * @return the number of pages in this step */ public int getNumberOfPages(HttpServletRequest request, SubmissionInfo subInfo) throws ServletException { return 1; } }
42.236264
163
0.682321
c82de52ced1b4bdcbfba7a0825bc324e788c1020
8,890
package net.cartola.emissorfiscal.api.controller; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import com.google.gson.Gson; import net.cartola.emissorfiscal.documento.DocumentoFiscal; import net.cartola.emissorfiscal.documento.DocumentoFiscalItem; import net.cartola.emissorfiscal.documento.IndicadorDeOperacao; import net.cartola.emissorfiscal.emissorfiscal.service.NcmServiceLogicTest; import net.cartola.emissorfiscal.emissorfiscal.service.TestHelper; import net.cartola.emissorfiscal.ncm.Ncm; import net.cartola.emissorfiscal.ncm.NcmService; import net.cartola.emissorfiscal.operacao.Operacao; import net.cartola.emissorfiscal.operacao.OperacaoService; import net.cartola.emissorfiscal.pessoa.Pessoa; import net.cartola.emissorfiscal.pessoa.PessoaService; import net.cartola.emissorfiscal.response.Response; /** * 3 de fev de 2020 * @author robson.costa */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class DocumentoFiscalAPIControllerTest { @Autowired private TestRestTemplate restTemplate; @Autowired private TestHelper testHelper; @Autowired private NcmService ncmService; @Autowired private OperacaoService operacaoService; @Autowired private PessoaService pessoaService; AuthorizationTestHelper<Object> auth = new AuthorizationTestHelper<Object>(); private static final BigDecimal DOCUMENTO_FISCAL_ITEM_QUANTIDADE = new BigDecimal(5); private static final BigDecimal DOCUMENTO_FISCAL_ITEM_VALOR_UNITARIO = new BigDecimal(12); // private static final int DOCUMENTO_FISCAL_ITEM_CFOP = 5655; // private static final BigDecimal DOCUMENTO_FISCAL_ITEM_ICMS_CEST = new BigDecimal(100010); private static final String PATH = "/api/v1/documento-fiscal"; private Gson gson = new Gson(); // ========= MÉTODO"auxiliar" ========= private ResponseEntity<Response<DocumentoFiscal>> buscarUmDocumentoFiscal() { DocumentoFiscal docFiscal = new DocumentoFiscal(); docFiscal.setEmitente(new Pessoa()); docFiscal.getEmitente().setCnpj(TestHelper.PESSOA_EMITENTE_CNPJ); docFiscal.setTipoOperacao(IndicadorDeOperacao.SAIDA); docFiscal.setSerie(Long.parseLong(TestHelper.DOC_FISCAL_SERIE_1)); docFiscal.setNumeroNota(Long.parseLong(TestHelper.DOC_FISCAL_NUMERO_1)); ParameterizedTypeReference<Response<DocumentoFiscal>> tipoRetorno = new ParameterizedTypeReference<Response<DocumentoFiscal>>() { }; HttpEntity<Object> httpEntity = auth.autorizar(docFiscal, restTemplate); ResponseEntity<Response<DocumentoFiscal>> response = restTemplate.exchange(PATH + "/buscar", HttpMethod.POST, httpEntity, tipoRetorno); String gsonResponse = gson.toJson(response); System.out.println("\n\nRESPONSE JSON BUSCA: " +gsonResponse); return response; } @Test public void test00_CleanUp() { testHelper.limpaBanco(); testHelper.criarEstados(); testHelper.criarPessoa(); testHelper.criarOperacoes(); testHelper.criarNcms(); testHelper.criarUsuarioRoot(); } @Test public void test01_espera404NotFoundAoBuscarUmDocFiscalInexistente() { ResponseEntity<Response<DocumentoFiscal>> response = buscarUmDocumentoFiscal(); assertEquals(HttpStatus.NOT_FOUND,response.getStatusCode()); System.out.println("\n" +this.getClass() + " test01_espera404NotFoundAoBuscarUmDocFiscalInexistente, ok"); } @Test public void test02_tentaInserirDocumentoFiscalVendaInterEstadual() { // POPULANDO OBJ Operacao operacao = operacaoService.findOperacaoByDescricao(TestHelper.OPERACAO_VENDA_INTERESTADUAL).get(); Pessoa emitente = pessoaService.findByCnpj(TestHelper.PESSOA_EMITENTE_CNPJ).get(); Pessoa destinatario = pessoaService.findByCnpj(TestHelper.PESSOA_DEST_CNPJ_SP).get(); Ncm ncm = ncmService.findNcmByNumeroAndExcecao(NcmServiceLogicTest.NCM_NUMERO_REGISTRO_1, NcmServiceLogicTest.NCM_EXCECAO_REGISTRO_1).get(); List<Ncm> listNcms = ncmService.findAll(); // CRIANDO TRIBUTACOES testHelper.criarTribEstaPorNcmsEOperDentroDeSP(listNcms, operacao); testHelper.criarTributacaoFederal(listNcms, operacao); // ITEM List<DocumentoFiscalItem> listItens = new ArrayList<>(); DocumentoFiscalItem item = new DocumentoFiscalItem(); item.setQuantidade(DOCUMENTO_FISCAL_ITEM_QUANTIDADE); item.setValorUnitario(DOCUMENTO_FISCAL_ITEM_VALOR_UNITARIO); item.setClasseFiscal(Integer.toString(ncm.getNumero())); item.setExcecao(ncm.getExcecao()); listItens.add(item); // DOCUMENTO FISCAL DocumentoFiscal docFiscal = new DocumentoFiscal(); docFiscal.setOperacao(operacao); docFiscal.setTipoOperacao(IndicadorDeOperacao.SAIDA); docFiscal.setSerie(Long.parseLong(TestHelper.DOC_FISCAL_SERIE_1)); docFiscal.setNumeroNota(Long.parseLong(TestHelper.DOC_FISCAL_NUMERO_1)); docFiscal.setEmitente(emitente); docFiscal.setDestinatario(destinatario); docFiscal.setItens(listItens); HttpEntity<Object> httpEntity = auth.autorizar(docFiscal, restTemplate); ParameterizedTypeReference<Response<DocumentoFiscal>> tipoRetorno = new ParameterizedTypeReference<Response<DocumentoFiscal>>() { }; ResponseEntity<Response<DocumentoFiscal>> response = restTemplate.exchange(PATH, HttpMethod.POST,httpEntity, tipoRetorno); String gsonResponse = gson.toJson(response); System.out.println("\n\nRESPONSE JSON SAVE: " +gsonResponse); assertEquals(HttpStatus.OK, response.getStatusCode()); docFiscal = response.getBody().getData(); assertNotNull(docFiscal); System.out.println("\n" +this.getClass() + " test02_tentaInserirDocumentoFiscalVendaInterEstadual, ok"); } @Test public void test03_buscarUmDocumentoFiscal() { ResponseEntity<Response<DocumentoFiscal>> response = buscarUmDocumentoFiscal(); assertEquals(HttpStatus.OK, response.getStatusCode()); DocumentoFiscal docFiscal = response.getBody().getData(); assertNotNull(docFiscal); assertEquals(docFiscal.getEmitente().getCnpj().toString(), TestHelper.PESSOA_EMITENTE_CNPJ); assertTrue(response.getHeaders().getContentType().equals(MediaType.APPLICATION_JSON)); System.out.println("\n" +this.getClass() + " test03_buscarUmDocumentoFiscal, ok"); } @Test public void test04_tentaEditarDocFiscalVendaInterEstadualParaVenda() { ResponseEntity<Response<DocumentoFiscal>> response = buscarUmDocumentoFiscal(); assertEquals(HttpStatus.OK, response.getStatusCode()); DocumentoFiscal docFiscal = response.getBody().getData(); assertNotNull(docFiscal); assertEquals(docFiscal.getEmitente().getCnpj().toString(), TestHelper.PESSOA_EMITENTE_CNPJ); assertTrue(response.getHeaders().getContentType().equals(MediaType.APPLICATION_JSON)); Operacao operacao = operacaoService.findOperacaoByDescricao(TestHelper.OPERACAO_VENDA).get(); docFiscal.setOperacao(operacao); // CRIANDO TRIBUTACOES testHelper.criarTribEstaPorNcmsEOperDentroDeSP(ncmService.findAll(), operacao); testHelper.criarTributacaoFederal(ncmService.findAll(), operacao); HttpEntity<Object> httpEntity = auth.autorizar(docFiscal, restTemplate); ParameterizedTypeReference<Response<DocumentoFiscal>> tipoRetorno = new ParameterizedTypeReference<Response<DocumentoFiscal>>() { }; ResponseEntity<Response<DocumentoFiscal>> responsePut = restTemplate.exchange(PATH, HttpMethod.PUT, httpEntity, tipoRetorno); String gsonResponsePut = gson.toJson(responsePut); System.out.println("\n\nRESPONSE JSON EDITAR: " +gsonResponsePut); assertEquals(HttpStatus.OK, responsePut.getStatusCode()); docFiscal = responsePut.getBody().getData(); assertNotNull(docFiscal); assertEquals(TestHelper.OPERACAO_VENDA, responsePut.getBody().getData().getOperacao().getDescricao()); System.out.println("\n" +this.getClass() + " test04_tentaEditarDocFiscalVendaParaVendaInterEstadual, ok"); } }
41.737089
143
0.786389
358d4787409c52d721aa97546280e907b9c58cb3
137
package glassmaker.testmod.proxy; public class CommonProxy implements IProxy { @Override public void registerRenderers() { } }
12.454545
44
0.744526