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
26ae1bd30bb76874bb7a6f1e2b52861612f297d1
1,726
package com.accesscontrol.services.impl; import com.accesscontrol.constants.AccessControlConfigConstants; import com.accesscontrol.services.PasswordEncryptionService; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import java.util.Properties; public class DefaultPasswordEncryptionService implements PasswordEncryptionService { @Autowired @Qualifier(AccessControlConfigConstants.ACCESS_CONTROL_CONFIG) private Properties accessControlConfigProperties; @Override public String encryptPassword(String password) { String digest=accessControlConfigProperties.getProperty(AccessControlConfigConstants.PasswordEncryption.PASSWORD_DIGEST,"MD5"); String salt=accessControlConfigProperties.getProperty(AccessControlConfigConstants.PasswordEncryption.PASSWORD_SALT,""); String pepper=accessControlConfigProperties.getProperty(AccessControlConfigConstants.PasswordEncryption.PASSWORD_PEPPER,""); String encryptedFlag=accessControlConfigProperties.getProperty(AccessControlConfigConstants.PasswordEncryption.PASSWORD_ENCRYTPION_FLAG,"__IS_ENCRYPTED__"); return StringUtils.join(new String(DigestUtils.getDigest(digest).digest(StringUtils.join(salt,password,pepper).getBytes())),encryptedFlag); } @Override public Boolean isPasswordEncrypted(String password) { String encryptedFlag=accessControlConfigProperties.getProperty(AccessControlConfigConstants.PasswordEncryption.PASSWORD_ENCRYTPION_FLAG,"__IS_ENCRYPTED__"); return password.endsWith(encryptedFlag); } }
49.314286
164
0.83314
f3905d6f96b2e4d2575d17a18ffdd4485d1591bb
4,715
/* * Copyright (c) 2008 Kasper Nielsen. * * 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 packed.internal.hooks.usesite; import static java.util.Objects.requireNonNull; import java.lang.invoke.MethodHandle; import java.lang.reflect.Member; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import app.packed.base.Key; import app.packed.base.Nullable; import app.packed.hooks.BeanClass; import packed.internal.component.ComponentSetup; import packed.internal.component.bean.BeanSetup; import packed.internal.hooks.AbstractHookModel; import packed.internal.hooks.ClassHookModel; import packed.internal.inject.dependency.DependencyDescriptor; import packed.internal.inject.dependency.DependencyProducer; import packed.internal.inject.dependency.InjectionNode; /** * */ public abstract class UseSiteMemberHookModel extends JavaHookElementModel { /** Dependencies that needs to be resolved. */ public final List<DependencyDescriptor> dependencies; @Nullable public final Consumer<? super ComponentSetup> processor; public final boolean provideAsConstant; @Nullable public final Key<?> provideAskey; // Jeg tror man loeber alle parameterene igennem og ser om der // er en sidecar provide der passer dem // Saa man sidecar providen dertil. UseSiteMemberHookModel(Builder builder, List<DependencyDescriptor> dependencies) { this.dependencies = requireNonNull(dependencies); this.provideAsConstant = builder.provideAsConstant; this.provideAskey = builder.provideAsKey; this.processor = builder.processor; } public void onWire(BeanSetup css) { // Register hooks, maybe move to component setup InjectionNode i = new InjectionNode(css, this, createProviders()); css.container.injection.addNode(i); if (processor != null) { processor.accept(css); } } public abstract DependencyProducer[] createProviders(); /** * Returns the modifiers of the underlying member. * * @return the modifiers of the underlying member * * @see Member#getModifiers() */ public abstract int getModifiers(); public abstract MethodHandle methodHandle(); public static abstract class Builder extends AbstractBootstrapBuilder { @Nullable // Eneste problem er at dette ogsaa kan vaere en buildTime model.. // Maaske skal vi have en faelles klasse?? AbstractHookModel<?> buildtimeModel; /** Any extension class that manages this member. */ UseSiteClassHookModel.@Nullable Builder managedBy; @Nullable Consumer<? super ComponentSetup> processor; /** If the member is being provided as a service whether or not it is constant. */ boolean provideAsConstant; /** If the member is being provided as a service its key. */ @Nullable Key<?> provideAsKey; Builder(BootstrappedClassModel.Builder source, AbstractHookModel<?> model) { super(source); this.buildtimeModel = model; } public final Optional<Class<?>> buildType() { if (disabled) { return Optional.empty(); } else if (buildtimeModel == null) { return Optional.empty(); } return Optional.of(buildtimeModel.bootstrapImplementation()); } public void complete() {} public final void disable() { disabled = true; this.buildtimeModel = null; } @SuppressWarnings("unchecked") public final <T extends BeanClass> T manageBy(Class<T> type) { requireNonNull(type, "The specified type is null"); checkNotDisabled(); if (managedBy != null) { throw new IllegalStateException("This method can only be invoked once"); } UseSiteClassHookModel.Builder builder = managedBy = source.classes.computeIfAbsent(type, c -> new UseSiteClassHookModel.Builder(source, ClassHookModel.ofManaged(type))); return (T) builder.instance; } } }
33.678571
100
0.678473
3da46e3c3ca33a9f34756b0c67d297e08b561da9
306
import searchui.MainWindow; import sun.awt.OSInfo; /** * Created by bclaus on 2/7/17. */ public class Main { public static void main(String[] args) { System.out.printf("Hello you are running %s", OSInfo.getOSType()); javax.swing.SwingUtilities.invokeLater(new MainWindow()); } }
23.538462
74
0.669935
d06d53b6dd994aa07875de57294f16a5bc6ce184
3,950
package com.totvs.tjc.infra.json; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.totvs.tjc.carteira.Cnpj; import com.totvs.tjc.infra.json.CnpjConverter.CnpjDeserializer; import com.totvs.tjc.infra.json.CnpjConverter.CnpjSerializer; @DisplayName("Teste de serializac\u00E3o de cnpj (json)") public class CnpjConverterTest { private static Writer writer; private static JsonGenerator generator; private static SerializerProvider provider; private static DeserializationContext context; private static ObjectMapper mapper; private static CnpjSerializer serializer; private static CnpjDeserializer deserializer; private static String cnpjValido; private static String cnpjInvalido; @BeforeAll static void initAll() { mapper = new ObjectMapper(); serializer = new CnpjSerializer(); deserializer = new CnpjDeserializer(); cnpjValido = "19861350000170"; cnpjInvalido = "06305901000177"; } @BeforeEach void init() throws IOException { writer = new StringWriter(); generator = new JsonFactory().createGenerator(writer); provider = mapper.getSerializerProvider(); context = mapper.getDeserializationContext(); } @Test void cnpjSerializer() throws IOException, JsonProcessingException { serializer.serialize(Cnpj.from(cnpjValido), generator, provider); generator.flush(); assertEquals("\"" + cnpjValido + "\"", writer.toString()); } @Test void cnpjSerializerNull() throws IOException, JsonProcessingException { assertThrows(NullPointerException.class, () -> serializer.serialize(null, generator, provider)); } @Test void cnpjDeserializer() throws IOException, JsonProcessingException { String json = String.format("{\"cnpj\":%s}", "\"" + cnpjValido + "\""); JsonParser parser = mapper.getFactory().createParser(json); Cnpj actual = deserializer.deserialize(parser, context); assertNotNull(actual); assertEquals(Cnpj.from(cnpjValido), actual); } @Test void cnpjDeserializerSemNo() throws IOException, JsonProcessingException { String json = String.format("%s", "\"" + cnpjValido + "\""); JsonParser parser = mapper.getFactory().createParser(json); Cnpj actual = deserializer.deserialize(parser, context); assertNotNull(actual); assertEquals(Cnpj.from(cnpjValido), actual); } @Test void cnpjInvalidoDeserializer() throws IOException, JsonProcessingException { String json = String.format("{\"cnpj\":%s}", "\"" + cnpjInvalido + "\""); JsonParser parser = mapper.getFactory().createParser(json); assertThrows(IllegalArgumentException.class, () -> deserializer.deserialize(parser, context)); } @Test void cnpjNuloDeserializer() throws IOException, JsonProcessingException { String json = String.format("\"" + null + "\""); JsonParser parser = mapper.getFactory().createParser(json); assertThrows(IllegalArgumentException.class, () -> deserializer.deserialize(parser, context)); } }
32.916667
104
0.712658
6f01d8d6f7eab411c809a6afcab8b62540e41738
1,157
package com.twasyl.slideshowfx.snippet.executor.golo; import com.twasyl.slideshowfx.snippet.executor.ISnippetExecutorOptions; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import java.io.File; import java.io.FileNotFoundException; /** * Options that are necessary for the Java snippet executor. * * @author Thierry Wasylczenko * @version 1.0.0 * @since 1.0.0 SlideshowFX 1.0.0 */ public class GoloSnippetExecutorOptions implements ISnippetExecutorOptions { private final ObjectProperty<File> goloHome = new SimpleObjectProperty<>(); public ObjectProperty<File> goloHomeProperty() { return this.goloHome; } public File getGoloHome() { return this.goloHome.get(); } public void setGoloHome(File goloHome) throws FileNotFoundException { if(goloHome == null) throw new NullPointerException("The goloHome can not be null"); if(!goloHome.exists()) throw new FileNotFoundException("The goloHome doesn't exist"); if(!goloHome.isDirectory()) throw new IllegalArgumentException("The goloHome is not a directory"); this.goloHome.setValue(goloHome); } }
36.15625
106
0.757995
9c1f7cb4b71c0fe76103b594ad5c2c7f6751424b
177
/** * The classes for holding information about the distributed systems * * @author Jorge Calderon * */ package org.simulationsystems.csf.sim.core.api.distributedsystems;
25.285714
68
0.757062
f710c97a3906908ed31aa826e9e85bba538c5150
812
package android.support.design.internal; import android.content.Context; import android.support.annotation.RestrictTo; import android.support.p003v7.view.menu.MenuBuilder; import android.support.p003v7.view.menu.MenuItemImpl; import android.support.p003v7.view.menu.SubMenuBuilder; import android.view.SubMenu; @RestrictTo({RestrictTo.Scope.LIBRARY_GROUP}) public class NavigationMenu extends MenuBuilder { public NavigationMenu(Context context) { super(context); } public SubMenu addSubMenu(int group, int id, int categoryOrder, CharSequence title) { MenuItemImpl item = (MenuItemImpl) addInternal(group, id, categoryOrder, title); SubMenuBuilder subMenu = new NavigationSubMenu(getContext(), this, item); item.setSubMenu(subMenu); return subMenu; } }
35.304348
89
0.761084
bc88c736746a6f1353c4832d35c0c7df2179ed73
6,199
/* * 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.jackrabbit.oak.security.authorization; import java.util.List; import javax.annotation.Nullable; import javax.jcr.RepositoryException; import javax.jcr.security.AccessControlList; import javax.jcr.security.AccessControlManager; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.apache.jackrabbit.JcrConstants; import org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils; import org.apache.jackrabbit.oak.AbstractSecurityTest; import org.apache.jackrabbit.oak.api.Tree; import org.apache.jackrabbit.oak.commons.PathUtils; import org.apache.jackrabbit.oak.plugins.tree.TreeLocation; import org.apache.jackrabbit.oak.spi.security.Context; import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.AccessControlConstants; import org.apache.jackrabbit.oak.spi.security.authorization.permission.PermissionConstants; import org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal; import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConstants; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class AuthorizationContextTest extends AbstractSecurityTest { @Override public void after() throws Exception { try { root.refresh(); } finally { super.after(); } } private void createAcl(@Nullable String path, String... privilegeNames) throws RepositoryException { AccessControlManager acMgr = getAccessControlManager(root); AccessControlList acl = AccessControlUtils.getAccessControlList(acMgr, path); assertNotNull(acl); acl.addAccessControlEntry(EveryonePrincipal.getInstance(), privilegesFromNames(privilegeNames)); acMgr.setPolicy(path, acl); } /** * @see <a href="https://issues.apache.org/jira/browse/OAK-2740">OAK-2740</a> */ @Test public void testItemDefinitionsDefinesContextRoot() throws Exception { List<String> paths = Lists.newArrayList( "/jcr:system/jcr:nodeTypes/rep:AccessControllable/rep:namedChildNodeDefinitions/rep:policy", "/jcr:system/jcr:nodeTypes/rep:RepoAccessControllable/rep:namedChildNodeDefinitions/rep:repoPolicy"); for (String defPath : paths) { Tree tree = root.getTree(defPath); assertFalse(AuthorizationContext.getInstance().definesContextRoot(tree)); } } @Test public void testPolicyDefinesContextRoot() throws Exception { createAcl("/", PrivilegeConstants.JCR_READ); Tree aclTree = root.getTree("/").getChild(AccessControlConstants.REP_POLICY); assertTrue(aclTree.exists()); assertTrue(AuthorizationContext.getInstance().definesContextRoot(aclTree)); } @Test public void testRepoPolicyDefinesContextRoot() throws Exception { createAcl(null, PrivilegeConstants.JCR_NAMESPACE_MANAGEMENT); Tree aclTree = root.getTree("/").getChild(AccessControlConstants.REP_REPO_POLICY); assertTrue(aclTree.exists()); assertTrue(AuthorizationContext.getInstance().definesContextRoot(aclTree)); } @Test public void testAceDefinesContextRoot() throws Exception { createAcl("/", PrivilegeConstants.JCR_READ); Tree aclTree = root.getTree("/").getChild(AccessControlConstants.REP_POLICY); assertTrue(aclTree.exists()); for (Tree child : aclTree.getChildren()) { assertFalse(AuthorizationContext.getInstance().definesContextRoot(child)); } } @Test public void testLocation() throws Exception { createAcl("/", PrivilegeConstants.JCR_READ); Context ctx = AuthorizationContext.getInstance(); String policyPath = "/rep:policy"; assertTrue(ctx.definesLocation(TreeLocation.create(root, policyPath + "/allow"))); assertTrue(ctx.definesLocation(TreeLocation.create(root, policyPath + "/allow/" + AccessControlConstants.REP_PRINCIPAL_NAME))); assertTrue(ctx.definesLocation(TreeLocation.create(root, policyPath + "/allow/" + AccessControlConstants.REP_PRIVILEGES))); List<String> existingRegular = ImmutableList.of( "/", "/jcr:system" ); for (String path : existingRegular) { assertFalse(path, ctx.definesLocation(TreeLocation.create(root, path))); assertFalse(path, ctx.definesLocation(TreeLocation.create(root, PathUtils.concat(path, JcrConstants.JCR_PRIMARYTYPE)))); } List<String> nonExistingItem = ImmutableList.of( '/' + AccessControlConstants.REP_REPO_POLICY, "/content/" + AccessControlConstants.REP_POLICY, "/content/" + AccessControlConstants.REP_PRIVILEGES, "/content/" + AccessControlConstants.REP_REPO_POLICY, "/jcr:system/" + AccessControlConstants.REP_POLICY, PermissionConstants.PERMISSIONS_STORE_PATH + "/nonexisting"); for (String path : nonExistingItem) { assertTrue(path, ctx.definesLocation(TreeLocation.create(root, path))); assertTrue(path, ctx.definesLocation(TreeLocation.create(root, PathUtils.concat(path, AccessControlConstants.REP_PRIVILEGES)))); } } }
43.048611
140
0.719955
2ff24294cc88603a38815e228f3d6e1582981fd4
303
package com.xwj.ioc; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyConfigs { /* @Bean(value = {"cs","cs2","cs3"}) public C c(){ return new C(); } @Bean("ds") public D d(){ return new D(); }*/ }
16.833333
60
0.683168
7bf333e56b49d570e9c481a76d3768a54b72d353
219
package com.java.basic; import java.util.Scanner; public class ConnectedAreasinaMatrix { public static void main(String[] args) { Scanner in = new Scanner(System.in); // todo } }
16.846154
45
0.616438
75ee3b8a610ab3a07b6fb3e0af63c09049473032
3,114
package com.cyc.kb.client.quant; /* * #%L * File: QuantifiedRestrictedVariable.java * Project: KB Client * %% * Copyright (C) 2013 - 2018 Cycorp, 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. * #L% */ import com.cyc.base.cycobject.CycObject; import com.cyc.kb.client.QuantifierImpl; import com.cyc.kb.client.SentenceImpl; import com.cyc.kb.exception.KbException; /** * THIS CLASS IS NOT SUPPORTED IN KB API 1.0. * @author vijay */ public class QuantifiedRestrictedVariable extends SentenceImpl { private QuantifierImpl quantifier; // private KBCollection collection; // Unquantified Literal private RestrictedVariable restrictedVariable; protected QuantifiedRestrictedVariable (CycObject core) throws KbException { super(core); // Should we attempt to set quantifier and collection from // the CycFormulaSentence. } // // public QuantifiedRestrictedVariable (Quantifier q, KBCollection c) throws KBApiException{ // // Send in CycFormulaSentence here. // this(doSomething(q, c)); // this.quantifier = q; // this.collection = c; // } // // private static CycFormulaSentence doSomething(Quantifier q, KBCollection c) throws KBApiException { // /* // CycFormulaSentence cfs = null; // Variable v = new Variable("?IND"); // Predicate p = Predicate.get("isa"); // // cfs = CycFormulaSentence.makeFormulaSentence(p.getCore(), v.getCore(), c.getCore()); // return CycFormulaSentence.makeFormulaSentence(q.getCore(), v.getCore(), cfs); // */ // // CycFormulaSentence cfs = c.toSentence(); // return CycFormulaSentence.makeFormulaSentence(q.getCore(), c.getVariable().getCore(), cfs); // // } public QuantifiedRestrictedVariable (QuantifierImpl q, RestrictedVariable ul) throws KbException { this(ul.getCore()); this.setQuantifier(q); this.setRestrictedVariable(ul); } public QuantifierImpl getQuantifier() { return quantifier; } private void setQuantifier(QuantifierImpl quantifier) { this.quantifier = quantifier; } public RestrictedVariable getRestrictedVariable() { return restrictedVariable; } private void setRestrictedVariable(RestrictedVariable restrictedVariable) { this.restrictedVariable = restrictedVariable; } @Override protected boolean isValidCore(CycObject tempCore) { // We are constructing the sentence, we will be sure it is WFF. // If we check the WFF of the CycLSentence we are generating, WFF will create // a skolem term for the "thereExists ?IND" of the QuantifiedCollection. return true; } }
30.529412
103
0.717084
d0fecee90243daa7340e4be3c2d1754845937224
524
package me.albert.amazingbot.events.notice.notify; import me.albert.amazingbot.bot.Bot; import me.albert.amazingbot.objects.contact.Group; public class GroupNotifyEvent extends NotifyEvent { protected long group_id; protected long user_id; public long getGroupID() { return group_id; } public long getUserID() { return user_id; } public Group getGroup(boolean... noCache) { return Bot.getApi().getGroupInfo(group_id, noCache.length > 0); } }
23.818182
72
0.667939
1a6c00bee4cae549cc8ccb2641f944fde9c195c5
556
package edu.kit.textannotation.annotationplugin.textmodel; /** * This exception is thrown if an annotation profile file was read from disk, but is malformed. * * @see InvalidFileFormatException * @see SchemaValidator */ public class InvalidAnnotationProfileFormatException extends InvalidFileFormatException { private String message; public InvalidAnnotationProfileFormatException(String message) { super(message); this.message = message; } @Override public String getMessage() { return message; } }
25.272727
95
0.733813
ed35d5c13e96a490c0d1125c33eabd6d17f122a1
2,403
// // ์ด ํŒŒ์ผ์€ JAXB(JavaTM Architecture for XML Binding) ์ฐธ์กฐ ๊ตฌํ˜„ 2.2.6 ๋ฒ„์ „์„ ํ†ตํ•ด ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. // <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>๋ฅผ ์ฐธ์กฐํ•˜์‹ญ์‹œ์˜ค. // ์ด ํŒŒ์ผ์„ ์ˆ˜์ •ํ•˜๋ฉด ์†Œ์Šค ์Šคํ‚ค๋งˆ๋ฅผ ์žฌ์ปดํŒŒ์ผํ•  ๋•Œ ์ˆ˜์ • ์‚ฌํ•ญ์ด ์†์‹ค๋ฉ๋‹ˆ๋‹ค. // ์ƒ์„ฑ ๋‚ ์งœ: 2012.10.05 ์‹œ๊ฐ„ 10:52:30 AM KST // package com.athena.chameleon.engine.entity.xml.application.weblogic.v8_1; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "parserFactory", "entityMapping" }) @XmlRootElement(name = "xml") public class Xml { @XmlElement(name = "parser-factory") protected ParserFactory parserFactory; @XmlElement(name = "entity-mapping") protected List<EntityMapping> entityMapping; /** * parserFactory ์†์„ฑ์˜ ๊ฐ’์„ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค. * * @return * possible object is * {@link ParserFactory } * */ public ParserFactory getParserFactory() { return parserFactory; } /** * parserFactory ์†์„ฑ์˜ ๊ฐ’์„ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค. * * @param value * allowed object is * {@link ParserFactory } * */ public void setParserFactory(ParserFactory value) { this.parserFactory = value; } /** * Gets the value of the entityMapping property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the entityMapping property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEntityMapping().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EntityMapping } * * */ public List<EntityMapping> getEntityMapping() { if (entityMapping == null) { entityMapping = new ArrayList<EntityMapping>(); } return this.entityMapping; } }
26.7
90
0.604245
bfcbb70f2bcf2ae73d160c47e978bc0b34452e36
1,119
package com.github.zuihou.authority.controller.common; import com.github.zuihou.authority.dto.common.ParameterPageDTO; import com.github.zuihou.authority.dto.common.ParameterSaveDTO; import com.github.zuihou.authority.dto.common.ParameterUpdateDTO; import com.github.zuihou.authority.entity.common.Parameter; import com.github.zuihou.authority.service.common.ParameterService; import com.github.zuihou.base.controller.SuperController; import com.github.zuihou.security.annotation.PreAuth; import io.swagger.annotations.Api; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * <p> * ๅ‰็ซฏๆŽงๅˆถๅ™จ * ๅ‚ๆ•ฐ้…็ฝฎ * </p> * * @author zuihou * @date 2020-02-05 */ @Slf4j @Validated @RestController @RequestMapping("/parameter") @Api(value = "Parameter", tags = "ๅ‚ๆ•ฐ้…็ฝฎ") @PreAuth(replace = "parameter:") public class ParameterController extends SuperController<ParameterService, Long, Parameter, ParameterPageDTO, ParameterSaveDTO, ParameterUpdateDTO> { }
31.971429
149
0.808758
41cecee90c4569d49edb1b59a83f017eaf0990a3
2,532
package com.dbpj.neo4j.controller; import com.dbpj.neo4j.vo.ResultVO; import com.dbpj.neo4j.enums.ResultEnum; import com.dbpj.neo4j.node.Conference; import com.dbpj.neo4j.service.ConferenceService; import com.dbpj.neo4j.utils.ResultVOUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * @Author: Jeremy * @Date: 2018/12/11 16:00 */ @RestController @RequestMapping("/neo4j/conference") public class ConferenceController { @Autowired private ConferenceService conferenceService; // ๆ’ๅ…ฅไผš่ฎฎ @CrossOrigin @PostMapping("/insert") public ResultVO insertConferenceInfo(@RequestParam(value = "type") Integer type, @RequestParam(value = "conference") String cName){ if (type != 3){ return ResultVOUtil.error(ResultEnum.TYPE_ERROR); } // ่Žทๅ–ไผš่ฎฎไฟกๆฏ Conference conference = new Conference(); conference.setCName(cName); // ่ฎฐๅฝ•ๆ‰ง่กŒๆ—ถ้—ด long runtime = 0; long startTime = System.currentTimeMillis(); //่Žทๅ–ๅผ€ๅง‹ๆ—ถ้—ด conferenceService.save(conference); long endTime = System.currentTimeMillis(); //่Žทๅ–็ป“ๆŸๆ—ถ้—ด runtime += endTime-startTime; // ่ฟ”ๅ›ž Map<String, Long> ret = new TreeMap<>(); ret.put("time", runtime); return ResultVOUtil.success(ret); } // ๅˆ ้™คไผš่ฎฎ @CrossOrigin @PostMapping("/delete") public ResultVO deleteConferenceInfo(@RequestParam(value = "type") Integer type, @RequestParam(value = "conference") String cName){ if (type != 3){ return ResultVOUtil.error(ResultEnum.TYPE_ERROR); } // ่Žทๅ–ไผš่ฎฎไฟกๆฏ Conference conference = new Conference(); conference.setCName(cName); // ่ฎฐๅฝ•ๆ‰ง่กŒๆ—ถ้—ด long runtime = 0; long startTime = System.currentTimeMillis(); //่Žทๅ–ๅผ€ๅง‹ๆ—ถ้—ด List<Conference> conferenceList = conferenceService.findByCName(cName); if(conferenceList.size() == 0){ return ResultVOUtil.success(ResultEnum.CONFERENCE_NOT_EXISTS); } conferenceService.deleteConferences(conferenceList); long endTime = System.currentTimeMillis(); //่Žทๅ–็ป“ๆŸๆ—ถ้—ด runtime += endTime-startTime; // ่ฟ”ๅ›ž Map<String, Long> ret = new TreeMap<>(); ret.put("time", runtime); return ResultVOUtil.success(ret); } }
28.449438
91
0.635071
0e4c9d80ccd09519da4aa2786dab2e6d194c47c7
2,761
package org.modelmapper.bugs; import static org.testng.Assert.assertEquals; import org.modelmapper.AbstractTest; import org.modelmapper.PropertyMap; import org.testng.annotations.Test; /** * Test that demonstrates how explicitly mapped properties are overwritten by field name matching. * * @author boris.strandjev */ @Test public class GH283 extends AbstractTest { public static class PersonDetails { private String firstName; private String lastName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } public static class Requester { private PersonDetails person; private PersonDetails unverifiedRequester; public PersonDetails getUnverifiedRequester() { return unverifiedRequester; } public void setUnverifiedRequester(PersonDetails unverifiedRequester) { this.unverifiedRequester = unverifiedRequester; } public PersonDetails getPerson() { return person; } public void setPerson(PersonDetails person) { this.person = person; } } public static class Order { private Requester requester; public Requester getRequester() { return requester; } public void setRequester(Requester requester) { this.requester = requester; } } public static class OrderView { private PersonDetails requester; public PersonDetails getRequester() { return requester; } public void setRequester(PersonDetails requester) { this.requester = requester; } } public void test() { modelMapper.addMappings(new PropertyMap<Requester, PersonDetails>() { @Override protected void configure() { map(source.getPerson().getFirstName()).setFirstName(null); map(source.getPerson().getLastName()).setLastName(null); } }); modelMapper.addMappings(new PropertyMap<Order, OrderView>() { @Override protected void configure() { map(source.getRequester()).setRequester(null); } }); String requesterFirstName = "John"; String requesterLastName = "Doe"; PersonDetails person = new PersonDetails(); person.setFirstName(requesterFirstName); person.setLastName(requesterLastName); Requester requester = new Requester(); requester.setPerson(person); Order order = new Order(); order.setRequester(requester); OrderView orderView = modelMapper.map(order, OrderView.class); assertEquals(orderView.getRequester().getFirstName(), requesterFirstName, "Expected the correct requested first name"); assertEquals(orderView.getRequester().getLastName(), requesterLastName, "Expected the correct requested last name"); } }
24.219298
99
0.74176
537c1dadaea216d5edbdcf513fa2b4538bba6771
4,682
package com.perosa.bot.traffic.http.client; import com.perosa.bot.traffic.http.client.wrap.Get; import com.perosa.bot.traffic.http.client.wrap.Post; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.HttpsURLConnection; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Map; public class JavaClientImpl implements Forwarder { private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientImpl.class); private static final String JSON_CONTENT_TYPE = "application/json"; public ForwarderResponse get(Get input) throws Exception { return call(input.getUrl() + input.getPath(), "GET", input.getHeaders()); } public ForwarderResponse post(Post input) throws Exception { return call(input.getUrl() + input.getPath(), "POST", input.getHeaders(), input.getBody()); } ForwarderResponse call(String endpoint, String method, Map<String, String> headers) throws Exception { return call(endpoint, method, headers, null); } ForwarderResponse call(String endpoint, String method, Map<String, String> headers, String payload) throws Exception { LOGGER.debug("endpoint: " + endpoint); ForwarderResponse forwarderResponse = new ForwarderResponse(); HttpURLConnection connection = null; BufferedReader reader = null; try { URL url = new URL(endpoint); if (url.getProtocol().equalsIgnoreCase("https")) { connection = (HttpsURLConnection) url.openConnection(); } else { connection = (HttpURLConnection) url.openConnection(); } // Set connection properties connection.setRequestMethod(method); connection.setReadTimeout(3 * 1000); connection.setDoOutput(true); connection.setUseCaches(false); setHeaders(connection, headers); if (payload != null) { OutputStream os = connection.getOutputStream(); os.write(payload.getBytes(StandardCharsets.UTF_8)); os.flush(); os.close(); } int responseCode = connection.getResponseCode(); if (responseCode != 0) { reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder stringBuilder = new StringBuilder(); while ((inputLine = reader.readLine()) != null) { stringBuilder.append(inputLine); } forwarderResponse.setResponseCode(connection.getResponseCode()); forwarderResponse.setBody(stringBuilder.toString()); forwarderResponse.setHeaders(connection.getHeaderFields()); } else { LOGGER.error("responseCode:" + responseCode + " responseMessage:" + connection.getResponseMessage()); throw new RuntimeException("responseCode:" + responseCode + " message:" + connection.getResponseMessage()); } } catch (IOException e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { } } if (connection != null) { connection.disconnect(); } } return forwarderResponse; } void setHeaders(HttpURLConnection connection, Map<String, String> headers) { if (headers.get("Content-Type") != null) { connection.setRequestProperty("Content-Type", headers.get("Content-Type")); } if (headers.get("Accept") != null) { connection.setRequestProperty("Accept", headers.get("Accept")); } if (headers.get("Host") != null) { connection.setRequestProperty("Host", headers.get("Host")); } if (headers.get("Accept-Encoding") != null) { connection.setRequestProperty("Accept-Encoding", headers.get("Accept-Encoding")); } if (headers.get("User-Agent") != null) { connection.setRequestProperty("User-Agent", headers.get("User-Agent")); } if (headers.get("Authorization") != null) { connection.setRequestProperty("Authorization", headers.get("Authorization")); } } }
35.469697
123
0.610636
71adf481abeabc5ba92d13ce39d6c9f3ea876bde
1,331
package com.ofdbox.core; import com.ofdbox.core.model.OFD; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class OFDWriter { public static void write(OFD ofd, File file) { System.out.println(file); try { OutputStream out = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(out); ZipOutputStream zipOutputStream = new ZipOutputStream(bos); ofd.getFileManager().files().forEach(f -> { String path = f.substring(f.indexOf("/") + 1); ZipEntry zipEntry = new ZipEntry(path); // System.out.println(path); try { zipOutputStream.putNextEntry(zipEntry); zipOutputStream.write(ofd.getFileManager().readBytes(f)); } catch (IOException e) { e.printStackTrace(); } // System.out.println(f); }); zipOutputStream.closeEntry(); zipOutputStream.close(); bos.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } ofd.getFileManager().files().forEach(f -> { // System.out.println(f); }); } }
29.577778
77
0.539444
80f5e2367a98939e256943adac0ffc450fce6893
1,639
/** * */ package org.spring.dubbo.demo.client; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spring.dubbo.demo.intf.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * @author LiuJian * */ @Controller public class DubboController { AtomicLong longSeq = new AtomicLong(0); private static final Logger logger = LoggerFactory.getLogger(DubboController.class); public DubboController() { } @Autowired private DemoClient demoClient; @RequestMapping(value = "/hello", produces = "text/plain; charset=utf-8") @ResponseBody public String showDubboText(String name) { long seq = longSeq.incrementAndGet(); logger.info("seq:" + seq + " " + name); String resp = demoClient.sayHello(name); logger.info("seq:" + seq + " " + resp); return resp; } @RequestMapping("/person") @ResponseBody public String showDubboText(Person p) { return demoClient.callp(p); } @RequestMapping(value = "/hongbao", method = { RequestMethod.POST, RequestMethod.GET }) public Map<String, Object> hongbao() { Map<String, Object> hongbaos = new HashMap<String, Object>(); hongbaos.put("key" + String.valueOf(1), "ๆ–ฐๅนดๅคง็คผๅŒ…"); hongbaos.put("key" + String.valueOf(10), "ๆ–ฐๅนด็™พๅนดๅŒ…"); hongbaos.put("key" + String.valueOf(100), "ๆ–ฐๅนด่ดบๅฒๅŒ…"); return hongbaos; } }
27.316667
88
0.738255
bb98e8ff5472287e9273b48ca303a8777338b0ba
896
package com.fqa; import java.util.ArrayList; import java.util.List; import java.util.Map; public class Userfactorythree { private Map<String, Userthree> map; public Userfactorythree(Map<String, Userthree> map) { this.map = map; } public Map<String, Userthree> getMap() { return map; } public Userthree getUser(String uid) { return map.get(uid); } public Userthree delUser(String uid) { return map.remove(uid); } public Userthree updataUser(Userthree user) { return map.put(user.getUid(), user); } public List<Userthree> getUser(List<String> list) { List<Userthree> list1 = new ArrayList<Userthree>(); for (String uid : list) { if (map.containsKey(uid)) { Userthree user = map.get(uid); list1.add(user); } } return list1; } public void putUser(List<Userthree> list) { for (Userthree user : list) { map.put(user.getUid(), user); } } }
19.06383
54
0.680804
d464ea7f43868a1cc5f1736cccac7518567fc24e
785
package draylar.identity.mixin; import net.minecraft.entity.ai.goal.TrackTargetGoal; import net.minecraft.entity.mob.MobEntity; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(TrackTargetGoal.class) public abstract class TrackTargetGoalMixin { @Shadow @Final protected MobEntity mob; @Shadow public abstract void stop(); @Inject(method = "shouldContinue", at = @At("RETURN"), cancellable = true) protected void identity_shouldContinue(CallbackInfoReturnable<Boolean> cir) { // NO-OP } }
34.130435
81
0.784713
ff243702d6b37252410afc24b43a1648e6fff0cb
1,879
package com.company.cards; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public class DeskOfCards { private final Card[] deckOfCards = new Card[4 * 8 * 13]; private static void shuffleArray(Card[] ar) { //Fisherโ€“Yates shuffle Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); Suits s = ar[index].getSuit(); Values v = ar[index].getValue(); ar[index] = ar[i]; ar[i] = new Card(s, v); } } public DeskOfCards() { Suits[] suits = {Suits.CLUB, Suits.DIAMOND, Suits.HEART, Suits.SPADE}; int k = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 4; j++) { deckOfCards[k++] = new Card(suits[j], Values.TWO); deckOfCards[k++] = new Card(suits[j], Values.THREE); deckOfCards[k++] = new Card(suits[j], Values.FOUR); deckOfCards[k++] = new Card(suits[j], Values.FIVE); deckOfCards[k++] = new Card(suits[j], Values.SIX); deckOfCards[k++] = new Card(suits[j], Values.SEVEN); deckOfCards[k++] = new Card(suits[j], Values.EIGHT); deckOfCards[k++] = new Card(suits[j], Values.NINE); deckOfCards[k++] = new Card(suits[j], Values.TEN); deckOfCards[k++] = new Card(suits[j], Values.JACK); deckOfCards[k++] = new Card(suits[j], Values.QUEEN); deckOfCards[k++] = new Card(suits[j], Values.KING); deckOfCards[k++] = new Card(suits[j], Values.ACE); } } shuffleArray(deckOfCards); } public Card[] getDeckOfCards() { return deckOfCards; } public Card getCard(int i) { return deckOfCards[i]; } }
36.134615
78
0.524215
5f7829d8889b87d908eedcdbc668ab8c09e5d46b
992
package io.sandbox.trades.items; import java.util.HashMap; import java.util.UUID; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.StackReference; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.screen.slot.Slot; import net.minecraft.util.ClickType; public class IncreaseLevel extends Item { public static final String name = "increase_level"; public static HashMap<UUID, Boolean> waitingForTick = new HashMap<>(); public IncreaseLevel(Settings settings) { super(settings); } @Override public boolean onStackClicked(ItemStack stack, Slot slot, ClickType clickType, PlayerEntity player) { return false; } @Override public boolean onClicked(ItemStack stack, ItemStack otherStack, Slot slot, ClickType clickType, PlayerEntity player, StackReference cursorStackReference) { if (!player.world.isClient) { waitingForTick.put(player.getUuid(), true); } return false; } }
28.342857
157
0.764113
56a7fd5210d7797c0bed369e6d9cc1358a1bba46
3,046
package GameTheory; import java.util.Objects; import java.util.Scanner; /** * https://www.hackerrank.com/challenges/game-of-stones-1/problem * minimax, alpha beta pruning * memoization - bottomup */ public class GameOfStones { private static Scanner input = new Scanner(System.in); public static void main(String[] args) { int testCases = Integer.parseInt(input.nextLine()); for (int i = 0; i < testCases; i++) { int n = Integer.parseInt(input.nextLine()); int alpha = Integer.MIN_VALUE; int beta = Integer.MAX_VALUE; if (minimax(n, alpha, beta, true) == -1) { System.out.println("Second"); } else { System.out.println("First"); } //String[] mem = new String[n+1]; //Arrays.fill(mem, ""); //System.out.println(findWinner(n, mem)); } } private static int[] possibleMoves = {5, 3, 2}; private static int minimax(int n, int alpha, int beta, boolean max) { // leaf node if (n == 1) { if (max) return -1; else return 1; } if (n <= 6) { if (max) return 1; else return -1; } int bestValue; if (max) { bestValue = Integer.MIN_VALUE; for (int move : possibleMoves) { if (n - move >= 0) { int result = minimax(n - move, alpha, beta, false); if (result > bestValue) { bestValue = result; } alpha = Math.max(alpha, bestValue); if (beta <= alpha) { break; } } } } else { bestValue = Integer.MAX_VALUE; for (int move : possibleMoves) { if (n - move >= 0) { int result = minimax(n - move, alpha, beta, true); if (result < bestValue) { bestValue = result; } beta = Math.min(beta, bestValue); if (beta <= alpha) { break; } } } } return bestValue; } private static String findWinner(int n, String[] mem) { if (n == 1) { return "Second"; } if (n <= 6) { return "First"; } else { if (mem[n] == "") { String winnerOf5 = findWinner(n - 5, mem); String winnerOf3 = findWinner(n - 3, mem); String winnerOf2 = findWinner(n - 2, mem); if (Objects.equals(winnerOf2, "First") && Objects.equals(winnerOf3, "First") && Objects.equals(winnerOf5, "First")) { mem[n] = "Second"; } else { mem[n] = "First"; } } return mem[n]; } } }
29.572816
133
0.432699
f185fccece777a3719d447b8d24655bff222e6ba
5,636
package sample; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.TableView; import javafx.scene.image.Image; import javafx.scene.layout.*; import javafx.stage.Stage; import java.io.File; public class TelaDeMenu extends Application{ public void start(Stage primaryStage) { VBox root = new VBox(); MenuBar menuBar = new MenuBar(); // ---- Menu menuCadastro = new Menu("Cadastrar"); MenuItem itemCadastroAeronave = new MenuItem("Cadastrar Aeronave"); MenuItem itemCadastroAeroporto = new MenuItem("Cadastrar Aeroporto"); MenuItem itemCadastroVoo = new MenuItem("Cadastrar Vรดo"); MenuItem itemCadastroPassageiro = new MenuItem("Cadastrar Passageiro"); MenuItem itemCadastroFuncionario = new MenuItem("Cadastrar Funcionario"); //Eventos para acesso as teslas do programa itemCadastroAeronave.setOnAction(e->{ CadastroAeronave cadastroAeronave = new CadastroAeronave(false); try{ cadastroAeronave.start(new Stage()); }catch (Exception ex){ System.out.println("Erro ao a abrir janela"); } }); itemCadastroAeroporto.setOnAction(e->{ CadastroAeroporto cadastroAeroporto = new CadastroAeroporto(false); try{ cadastroAeroporto.start(new Stage()); }catch (Exception ex){ System.out.println("Erro ao a abrir janela"); } }); itemCadastroVoo.setOnAction(e->{ CadastroVoo cadastroVoo = new CadastroVoo(false); try{ cadastroVoo.start(new Stage()); }catch (Exception ex){ System.out.println("Erro ao a abrir janela"); } }); itemCadastroPassageiro.setOnAction(e->{ CadastroPassageiro cadastroPassageiro = new CadastroPassageiro(false); try{ cadastroPassageiro.start(new Stage()); }catch (Exception ex){ System.out.println("Erro ao a abrir janela"); } }); itemCadastroFuncionario.setOnAction(e->{ CadastroFuncionario cadastroFuncionario = new CadastroFuncionario(); try{ cadastroFuncionario.start(new Stage()); }catch (Exception ex){ System.out.println("Erro ao a abrir janela"); } }); menuCadastro.getItems().addAll(itemCadastroVoo, itemCadastroAeronave, itemCadastroAeroporto, itemCadastroPassageiro, itemCadastroFuncionario); // ----- Menu menuPassagem = new Menu("Gerรชncia de Passagens"); MenuItem itemVendaPassagem = new MenuItem("Vender Passagem"); MenuItem itemCancelaPassagem = new MenuItem("Cancelar Passagem"); menuPassagem.getItems().addAll(itemVendaPassagem, itemCancelaPassagem); itemVendaPassagem.setOnAction(e->{ VendaPassagem vendaPassagem = new VendaPassagem(); try{ vendaPassagem.start(new Stage()); }catch (Exception ex){ System.out.println("Erro ao a abrir janela"); ex.printStackTrace(); } }); // ----- Menu menuRelatorio = new Menu("Relatรณrios"); MenuItem itemRelatorioVoo = new MenuItem("Relatรณrio de Vรดo"); MenuItem itemRelatorioVoos = new MenuItem("Relatรณrio de Vรดos"); MenuItem itemRelatorioPassageiro = new MenuItem("Relatรณrio de Passageiro"); menuRelatorio.getItems().addAll(itemRelatorioVoo, itemRelatorioVoos, itemRelatorioPassageiro); // ---- menuBar.getMenus().addAll(menuCadastro, menuPassagem, menuRelatorio); // =========== itemRelatorioVoos.setOnAction(e->{ RelatorioVoos relatorioVoos = new RelatorioVoos(); try{ relatorioVoos.start(new Stage()); }catch (Exception ex){ System.out.println("Erro ao a abrir janela"); ex.printStackTrace(); } }); itemRelatorioVoo.setOnAction(e->{ RelatorioVoo relatorioVoo = new RelatorioVoo(Main.getVoos().get(0)); try{ relatorioVoo.start(new Stage()); }catch (Exception ex){ System.out.println("Erro ao a abrir janela"); ex.printStackTrace(); } }); itemRelatorioPassageiro.setOnAction(e->{ RelatorioPassageiros relatorioPassageiros = new RelatorioPassageiros(); try{ relatorioPassageiros.start(new Stage()); }catch (Exception ex){ System.out.println("Erro ao a abrir janela"); ex.printStackTrace(); } }); Image logoimg = new Image("file:UTF-Airlines/src/imgs/logo.png"); TableView tableView = new TableView(); BackgroundImage bgLogo = new BackgroundImage(logoimg,BackgroundRepeat.NO_REPEAT,BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER,null); tableView.setBackground(new Background(bgLogo)); root.getChildren().addAll(menuBar, tableView); Scene scene = new Scene(root,600,400); primaryStage.setTitle("UTF-Airlines"); primaryStage.setScene(scene); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
37.324503
148
0.6077
d37ab7eb957e68050ca2190ccfa6acdafabf3a76
1,543
package it.polimi.tssotn.dataprocessor; import java.io.Serializable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; public class Config implements Serializable { /** * generated serial version UID */ private static final long serialVersionUID = 5087417577620830639L; private static Config _instance; static final Logger logger = LoggerFactory .getLogger(InfluenceCalculator.class); private Config() { } public static Config getInstance() { if (_instance == null) { _instance = new Config(); } return _instance; } public static void init(String[] args) { _instance = new Config(); new JCommander(_instance, args); _instance.outputPathBase += "/" + (new java.util.Date().getTime()); logger.debug( "Configuration: --tweetPath {} --newsEntitiesPath {} --outputPathBase {} --runlocal {} --minMatches {}", new Object[] { _instance.tweetsPath, _instance.newsEntitiesPath, _instance.outputPathBase, _instance.runLocal, _instance.minMatches }); } @Parameter(names = { "-t", "--tweetPath" }, required = true) public String tweetsPath; @Parameter(names = { "-n", "--newsEntitiesPath" }, required = true) public String newsEntitiesPath; @Parameter(names = { "-l", "--runLocal" }) public boolean runLocal; @Parameter(names = { "-m", "--minMatches" }) public Integer minMatches = 1; @Parameter(names = { "-o", "--outputPathBase" }, required = true) public String outputPathBase; }
25.295082
109
0.701231
bc2582a5add9c2325f8761a87021b8bcacc0d73d
713
package com.exasol.sql.ddl.drop; import com.exasol.sql.Table; /** * Visitor for {@code DROP TABLE} statements. */ public interface DropTableVisitor { /** * Visit a {@code DROP TABLE} statement. * * @param dropTable {@code DROP TABLE} statement to visit */ public void visit(final DropTable dropTable); /** * Visit the {@code TABLE} to be dropped. * * @param table {@code TABLE} to visit */ public void visit(final Table table); /** * Visit the {@code CASCADE CONSTRAINTS} option. * * @param cascadeConstraints {@code CASCADE CONSTRAINTS} option to visit */ public void visit(final CascadeConstraints cascadeConstraints); }
23.766667
76
0.639551
ad91c8326d41daaa2187aa329b42288f2f19401a
1,109
package com.yunionyun.mcp.mcclient.utils.pricespec; import java.util.ArrayList; public class RdsSpec { private String brand; private String region; private String zone; private String rdsType; private ArrayList<RdsDiskSpec> disks; public RdsSpec(String brand, String region, String zone, String rdsType, String diskType, int sizeGB) { this.brand = brand; this.region = region; this.zone = zone; this.rdsType = rdsType; this.disks = new ArrayList<RdsDiskSpec>(); this.addDisk(diskType, sizeGB); } public RdsSpec addDisk(String diskType, int sizeGB) { this.disks.add(new RdsDiskSpec(diskType, sizeGB)); return this; } public ArrayList<ResourceSpec> getSpecs() { ArrayList<ResourceSpec> specs = new ArrayList<ResourceSpec>(); specs.add(new RdsCpuMemSpec(this.brand, this.region, this.zone, this.rdsType)); for (int i = 0; i < this.disks.size(); i++) { RdsDiskSpec idisk = this.disks.get(i); specs.add( new DiskSpec(this.brand, this.region, this.zone, idisk.resourceType, idisk.diskType, idisk.sizeGB)); } return specs; } }
29.972973
106
0.703336
3a8680ab745dfb58700c62b177a2f8a116a68269
3,057
package net.svenwollinger.battlemaker.input.editor; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import net.svenwollinger.battlemaker.map.Map; import net.svenwollinger.battlemaker.windows.editor.EditorWindow; public class EditorKeyListener implements KeyListener{ EditorWindow wndInstance; public EditorKeyListener(EditorWindow _instance) { this.wndInstance = _instance; } boolean ctrlPressed = false; @Override public void keyPressed(KeyEvent arg0) { float speed = 0.2F; if(ctrlPressed && arg0.getKeyCode() == KeyEvent.VK_S) { wndInstance.editorInstance.saveMap(false); } if(arg0.getKeyCode() == KeyEvent.VK_CONTROL) { ctrlPressed = true; } if(arg0.getKeyCode() == KeyEvent.VK_F) { Map cMap = wndInstance.editorInstance.currentMap; for(int y = 0; y < cMap.getHeight(); y++) for(int x = 0; x < cMap.getWidth(); x++) cMap.layers.get(wndInstance.editorInstance.currentLayer)[x][y] = wndInstance.editorInstance.selectedTexture; } if(arg0.getKeyCode() == KeyEvent.VK_C) { wndInstance.editorInstance.selectedTexture = wndInstance.editorInstance.copyTexture(wndInstance.mouseMotionListener.mousePos); wndInstance.editorInstance.textureViewer.repaint(); } if(arg0.getKeyCode() == KeyEvent.VK_T) { wndInstance.editorInstance.currentMap.removeEntity(wndInstance.mouseMotionListener.mousePos); } if(arg0.getKeyCode() == KeyEvent.VK_Z) { wndInstance.editorInstance.showGrid = !wndInstance.editorInstance.showGrid; wndInstance.repaint(); } if(arg0.getKeyCode() == KeyEvent.VK_D) { wndInstance.editorInstance.showDebug = !wndInstance.editorInstance.showDebug; wndInstance.repaint(); } if(arg0.getKeyCode() == KeyEvent.VK_ADD) { //wndInstance.zoom(-1, null); wndInstance.editorInstance.changeLayer(1); } if(arg0.getKeyCode() == KeyEvent.VK_SUBTRACT) { //wndInstance.zoom(1, null); wndInstance.editorInstance.changeLayer(-1); } if(arg0.getKeyCode() == KeyEvent.VK_L) { wndInstance.editorInstance.currentMap.addLayer(); } if(arg0.getKeyCode() == KeyEvent.VK_K) { wndInstance.editorInstance.currentMap.removeLayer(); } if(arg0.getKeyCode() == KeyEvent.VK_DOWN) { wndInstance.editorInstance.cameraPos.y = wndInstance.editorInstance.cameraPos.y - speed; wndInstance.repaint(); } if(arg0.getKeyCode() == KeyEvent.VK_UP) { wndInstance.editorInstance.cameraPos.y = wndInstance.editorInstance.cameraPos.y + speed; wndInstance.repaint(); } if(arg0.getKeyCode() == KeyEvent.VK_RIGHT) { wndInstance.editorInstance.cameraPos.x = wndInstance.editorInstance.cameraPos.x - speed; wndInstance.repaint(); } if(arg0.getKeyCode() == KeyEvent.VK_LEFT) { wndInstance.editorInstance.cameraPos.x = wndInstance.editorInstance.cameraPos.x + speed; wndInstance.repaint(); } } @Override public void keyReleased(KeyEvent arg0) { if(arg0.getKeyCode() == KeyEvent.VK_CONTROL) { ctrlPressed = false; } } @Override public void keyTyped(KeyEvent arg0) { } }
28.305556
129
0.725875
a2b69af1ce5339cce998810ef64a68ece1aa9700
24,025
/** * Copyright (c) ObjectFabric Inc. All rights reserved. * * This file is part of ObjectFabric (objectfabric.com). * * ObjectFabric is licensed under the Apache License, Version 2.0, the terms * of which may be found at http://www.apache.org/licenses/LICENSE-2.0.html. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ package com.objectfabric; import com.objectfabric.misc.Debug; import com.objectfabric.misc.Log; import com.objectfabric.misc.PlatformAdapter; import com.objectfabric.misc.PlatformClass; import com.objectfabric.misc.ThreadAssert; import com.objectfabric.misc.ThreadAssert.SingleThreaded; @SingleThreaded class ImmutableReader extends BufferReader { private char[] _chars = new char[16]; private int _charCount; protected ImmutableReader() { } void reset() { if (Debug.COMMUNICATIONS) ThreadAssert.getOrCreateCurrent().resetReaderDebugCounter(this); } /* * Fixed lengths. */ private static final int BYTE_LENGTH = 1; public final boolean canReadByte() { int needed = BYTE_LENGTH; if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { Helper.getInstance().setExpectedClass(ImmutableClass.BYTE_INDEX); needed += ImmutableWriter.DEBUG_OVERHEAD; } return remaining() >= needed; } public final byte readByte() { return readByte(0); } public final byte readByte(int tag) { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) assertDebugInfo(ImmutableClass.BYTE_INDEX, tag); return readByteFromBuffer(); } public final boolean canReadByteBoxed() { int needed = BOOLEAN_LENGTH + BYTE_LENGTH; if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { Helper.getInstance().setExpectedClass(ImmutableClass.BYTE_BOXED_INDEX); needed += ImmutableWriter.DEBUG_OVERHEAD; } return remaining() >= needed; } public final Byte readByteBoxed() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) assertDebugInfo(ImmutableClass.BYTE_BOXED_INDEX, 0); if (readBooleanFromBuffer()) return new Byte(readByteFromBuffer()); return null; // Marker Byte } // private static final int BOOLEAN_LENGTH = 1; public final boolean canReadBoolean() { int needed = BOOLEAN_LENGTH; if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { Helper.getInstance().setExpectedClass(ImmutableClass.BOOLEAN_INDEX); needed += ImmutableWriter.DEBUG_OVERHEAD; } return remaining() >= needed; } public final boolean readBoolean() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) assertDebugInfo(ImmutableClass.BOOLEAN_INDEX, 0); return readBooleanFromBuffer(); } public final boolean canReadBooleanBoxed() { int needed = BOOLEAN_LENGTH + BOOLEAN_LENGTH; if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { Helper.getInstance().setExpectedClass(ImmutableClass.BOOLEAN_BOXED_INDEX); needed += ImmutableWriter.DEBUG_OVERHEAD; } return remaining() >= needed; } public final Boolean readBooleanBoxed() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) assertDebugInfo(ImmutableClass.BOOLEAN_BOXED_INDEX, 0); if (readBooleanFromBuffer()) return new Boolean(readBooleanFromBuffer()); return null; // Marker Boolean } // private static final int SHORT_LENGTH = Short.SIZE / 8; public final boolean canReadShort() { int needed = SHORT_LENGTH; if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { Helper.getInstance().setExpectedClass(ImmutableClass.SHORT_INDEX); needed += ImmutableWriter.DEBUG_OVERHEAD; } return remaining() >= needed; } public final short readShort() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) assertDebugInfo(ImmutableClass.SHORT_INDEX, 0); return readShortFromBuffer(); } public final boolean canReadShortBoxed() { int needed = BOOLEAN_LENGTH + SHORT_LENGTH; if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { Helper.getInstance().setExpectedClass(ImmutableClass.SHORT_BOXED_INDEX); needed += ImmutableWriter.DEBUG_OVERHEAD; } return remaining() >= needed; } public final Short readShortBoxed() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) assertDebugInfo(ImmutableClass.SHORT_BOXED_INDEX, 0); if (readBooleanFromBuffer()) return new Short(readShortFromBuffer()); return null; // Marker Short } // private static final int CHARACTER_LENGTH = Character.SIZE / 8; public final boolean canReadCharacter() { int needed = CHARACTER_LENGTH; if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { Helper.getInstance().setExpectedClass(ImmutableClass.CHARACTER_INDEX); needed += ImmutableWriter.DEBUG_OVERHEAD; } return remaining() >= needed; } public final char readCharacter() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) assertDebugInfo(ImmutableClass.CHARACTER_INDEX, 0); return readCharacterFromBuffer(); } public final boolean canReadCharacterBoxed() { int needed = BOOLEAN_LENGTH + CHARACTER_LENGTH; if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { Helper.getInstance().setExpectedClass(ImmutableClass.CHARACTER_BOXED_INDEX); needed += ImmutableWriter.DEBUG_OVERHEAD; } return remaining() >= needed; } public final Character readCharacterBoxed() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) assertDebugInfo(ImmutableClass.CHARACTER_BOXED_INDEX, 0); if (readBooleanFromBuffer()) return new Character(readCharacterFromBuffer()); return null; // Marker Character } // private static final int INTEGER_LENGTH = Integer.SIZE / 8; public final boolean canReadInteger() { int needed = INTEGER_LENGTH; if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { Helper.getInstance().setExpectedClass(ImmutableClass.INTEGER_INDEX); needed += ImmutableWriter.DEBUG_OVERHEAD; } return remaining() >= needed; } public final int readInteger() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) assertDebugInfo(ImmutableClass.INTEGER_INDEX, 0); return readIntegerFromBuffer(); } public final boolean canReadIntegerBoxed() { int needed = BOOLEAN_LENGTH + INTEGER_LENGTH; if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { Helper.getInstance().setExpectedClass(ImmutableClass.INTEGER_BOXED_INDEX); needed += ImmutableWriter.DEBUG_OVERHEAD; } return remaining() >= needed; } public final Integer readIntegerBoxed() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) assertDebugInfo(ImmutableClass.INTEGER_BOXED_INDEX, 0); if (readBooleanFromBuffer()) return new Integer(readIntegerFromBuffer()); return null; // Marker Integer } // private static final int LONG_LENGTH = Long.SIZE / 8; public final boolean canReadLong() { int needed = LONG_LENGTH; if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { Helper.getInstance().setExpectedClass(ImmutableClass.LONG_INDEX); needed += ImmutableWriter.DEBUG_OVERHEAD; } return remaining() >= needed; } public final long readLong() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) assertDebugInfo(ImmutableClass.LONG_INDEX, 0); return readLongFromBuffer(); } public final boolean canReadLongBoxed() { int needed = BOOLEAN_LENGTH + LONG_LENGTH; if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { Helper.getInstance().setExpectedClass(ImmutableClass.LONG_BOXED_INDEX); needed += ImmutableWriter.DEBUG_OVERHEAD; } return remaining() >= needed; } public final Long readLongBoxed() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) assertDebugInfo(ImmutableClass.LONG_BOXED_INDEX, 0); if (readBooleanFromBuffer()) return new Long(readLongFromBuffer()); return null; // Marker Long } // private static final int DATE_LENGTH = LONG_LENGTH; public final boolean canReadDate() { int needed = DATE_LENGTH; if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { Helper.getInstance().setExpectedClass(ImmutableClass.DATE_INDEX); needed += ImmutableWriter.DEBUG_OVERHEAD; } return remaining() >= needed; } public final java.util.Date readDate() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) assertDebugInfo(ImmutableClass.DATE_INDEX, 0); long ticks = readLongFromBuffer(); if (ticks >= 0) return new java.util.Date((ticks - 621355968000000000L) / 10000); return null; // Marker Date } /* * Non fixed lengths. */ private static final int FLOAT_DEBUG = 0; private static final int FLOAT_VALUE = 1; @SuppressWarnings("fallthrough") public final float readFloat() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { int step = FLOAT_DEBUG; if (interrupted()) step = resumeInt(); switch (step) { case FLOAT_DEBUG: { if (!canReadDebugInfo()) { interruptInt(FLOAT_DEBUG); return 0; } Helper.getInstance().setExpectedClass(ImmutableClass.FLOAT_INDEX); assertDebugInfo(ImmutableClass.FLOAT_INDEX, 0); } case FLOAT_VALUE: { float value = readFloatNoDebug(); if (interrupted()) { interruptInt(FLOAT_VALUE); return 0; } return value; } default: throw new IllegalStateException(); } } return readFloatNoDebug(); } private final float readFloatNoDebug() { if (interrupted()) resume(); if ((getFlags() & CompileTimeSettings.SERIALIZATION_BINARY_FLOAT_AND_DOUBLE) == 0) { String value = readString(false, 0); if (interrupted()) { interrupt(null); return 0; } return PlatformAdapter.stringToFloat(value); } if (remaining() < INTEGER_LENGTH) { interrupt(null); return 0; } int i = readIntegerFromBuffer(); return PlatformAdapter.intToFloat(i); } private static final int FLOAT_BOXED_DEBUG = -1; private static final int FLOAT_BOXED_NULL = 0; private static final int FLOAT_BOXED_VALUE = 1; @SuppressWarnings("fallthrough") public final Float readFloatBoxed() { int step = Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications() ? FLOAT_BOXED_DEBUG : FLOAT_BOXED_NULL; if (interrupted()) step = resumeInt(); if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { if (step == FLOAT_BOXED_DEBUG) { if (!canReadDebugInfo()) { interruptInt(FLOAT_BOXED_DEBUG); return null; // Marker Float } Helper.getInstance().setExpectedClass(ImmutableClass.FLOAT_BOXED_INDEX); assertDebugInfo(ImmutableClass.FLOAT_BOXED_INDEX, 0); step = FLOAT_BOXED_NULL; } } switch (step) { case FLOAT_BOXED_NULL: { if (!canReadBoolean()) { interruptInt(FLOAT_BOXED_NULL); return null; // Marker Float } if (readBooleanFromBuffer()) return null; // Marker Float } case FLOAT_BOXED_VALUE: { float value = readFloatNoDebug(); if (interrupted()) { interruptInt(FLOAT_BOXED_VALUE); return null; // Marker Float } return new Float(value); // Converter } default: throw new IllegalStateException(); } } // private static final int DOUBLE_DEBUG = 0; private static final int DOUBLE_VALUE = 1; @SuppressWarnings("fallthrough") public final double readDouble() { if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { int step = DOUBLE_DEBUG; if (interrupted()) step = resumeInt(); switch (step) { case DOUBLE_DEBUG: { if (!canReadDebugInfo()) { interruptInt(DOUBLE_DEBUG); return 0; } Helper.getInstance().setExpectedClass(ImmutableClass.DOUBLE_INDEX); assertDebugInfo(ImmutableClass.DOUBLE_INDEX, 0); } case DOUBLE_VALUE: { double value = readDoubleNoDebug(); if (interrupted()) { interruptInt(DOUBLE_VALUE); return 0; } return value; } default: throw new IllegalStateException(); } } return readDoubleNoDebug(); } private final double readDoubleNoDebug() { if (interrupted()) resume(); if ((getFlags() & CompileTimeSettings.SERIALIZATION_BINARY_FLOAT_AND_DOUBLE) == 0) { String value = readString(false, 0); if (interrupted()) { interrupt(null); return 0; } return PlatformAdapter.stringToDouble(value); } if (remaining() < LONG_LENGTH) { interrupt(null); return 0; } return PlatformAdapter.longToDouble(readLongFromBuffer()); } private static final int DOUBLE_BOXED_DEBUG = -1; private static final int DOUBLE_BOXED_NULL = 0; private static final int DOUBLE_BOXED_VALUE = 1; @SuppressWarnings("fallthrough") public final Double readDoubleBoxed() { int step = Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications() ? DOUBLE_BOXED_DEBUG : DOUBLE_BOXED_NULL; if (interrupted()) step = resumeInt(); if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { if (step == DOUBLE_BOXED_DEBUG) { if (!canReadDebugInfo()) { interruptInt(DOUBLE_BOXED_DEBUG); return null; // Marker Double } Helper.getInstance().setExpectedClass(ImmutableClass.DOUBLE_BOXED_INDEX); assertDebugInfo(ImmutableClass.DOUBLE_BOXED_INDEX, 0); step = DOUBLE_BOXED_NULL; } } switch (step) { case DOUBLE_BOXED_NULL: { if (!canReadBoolean()) { interruptInt(DOUBLE_BOXED_NULL); return null; // Marker Double } if (readBooleanFromBuffer()) return null; // Marker Double } case DOUBLE_BOXED_VALUE: { double value = readDoubleNoDebug(); if (interrupted()) { interruptInt(DOUBLE_BOXED_VALUE); return null; // Marker Double } return new Double(value); // Converter } default: throw new IllegalStateException(); } } // public final String readString() { return readString(true, 0); } public final String readString(boolean debug, int tag) { int value; if (interrupted()) value = resumeInt(); else { value = Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications() && debug ? -2 : -1; _charCount = 0; } if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications() && debug) { if (value == -2) { if (!canReadDebugInfo()) { interruptInt(-2); return null; } Helper.getInstance().setExpectedClass(ImmutableClass.STRING_INDEX); assertDebugInfo(ImmutableClass.STRING_INDEX, tag); } } for (;;) { if (value < 0) { if (remaining() == 0) { interruptInt(-1); return null; } value = readByteFromBuffer() & 0xff; } if ((value & ImmutableWriter.STRING_ENC_DOES_NOT_FIT_ON_1_BYTE_MASK) == 0) { append((char) value); } else if ((value & ImmutableWriter.STRING_ENC_DOES_NOT_FIT_ON_2_BYTES_MASK) == 0) { if (remaining() == 0) { interruptInt(value); return null; } value &= ~ImmutableWriter.STRING_ENC_DOES_NOT_FIT_ON_1_BYTE_MASK; value = value << 8 | readByteFromBuffer() & 0xff; append((char) value); } else if ((value & ImmutableWriter.STRING_ENC_EOF_MASK) == 0) { if (remaining() < CHARACTER_LENGTH) { interruptInt(value); return null; } append(readCharacterFromBuffer()); } else if ((value & ImmutableWriter.STRING_ENC_NULL_MASK) == 0) return new String(_chars, 0, _charCount); else return null; value = -1; } } private final void append(char value) { if (_charCount >= _chars.length) { char[] temp = new char[_chars.length << 1]; PlatformAdapter.arraycopy(_chars, 0, temp, 0, _chars.length); _chars = temp; } _chars[_charCount++] = value; } // public final byte[] readBinary() { return readBinary(ImmutableClass.BINARY_INDEX); } @SuppressWarnings("null") private final byte[] readBinary(int classId) { int index = Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications() ? -2 : -1; byte[] array = null; if (interrupted()) { index = resumeInt(); array = (byte[]) resume(); } if (Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) { if (index == -2) { if (!canReadDebugInfo()) { interrupt(null); interruptInt(-2); return null; } Helper.getInstance().setExpectedClass(classId); assertDebugInfo(classId, 0); } } if (index < 0) { if (remaining() < INTEGER_LENGTH) { interrupt(null); interruptInt(-1); return null; } int length = readIntegerFromBuffer(); if (length < 0) return null; array = new byte[length]; index = 0; } for (; index < array.length; index++) { if (remaining() == 0) { interrupt(array); interruptInt(index); return null; } array[index] = readByteFromBuffer(); } return array; } // public final java.math.BigInteger readBigInteger() { byte[] data = readBinary(ImmutableClass.BIG_INTEGER_INDEX); if (data != null) return new java.math.BigInteger(data); return null; // Marker BigInteger } // public final java.math.BigDecimal readDecimal() { byte[] a = readBinary(ImmutableClass.DECIMAL_INDEX); if (a != null) { byte[] b = new byte[a.length - 4]; PlatformAdapter.arraycopy(a, 0, b, 0, b.length); int b0 = a[a.length - 4] & 0x000000ff; int b1 = (a[a.length - 3] << 8) & 0x0000ff00; int b2 = (a[a.length - 2] << 16) & 0x00ff0000; int b3 = (a[a.length - 1] << 24) & 0xff000000; int scale = b3 | b2 | b1 | b0; return new java.math.BigDecimal(new java.math.BigInteger(b), scale); } return null; // Marker BigDecimal } // Debug public final boolean canReadDebugInfo() { if (!Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) throw new IllegalStateException(); return remaining() >= ImmutableWriter.DEBUG_OVERHEAD; } private final void assertDebugInfo(int classId, int tag) { if (!Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) throw new IllegalStateException(); if (Debug.COMMUNICATIONS_LOG_ALL) { String name = ImmutableClass.ALL.get(classId).toString(); Log.write(PlatformClass.getSimpleName(getClass()) + ", " + ThreadAssert.getOrCreateCurrent().getReaderDebugCounter(this) + ", class: " + name + ", tag: " + tag); } Debug.assertion(classId == Helper.getInstance().getExpectedClass()); long readDebugCounter = readLongFromBuffer(); byte readClassId = readByteFromBuffer(); int readTag = readIntegerFromBuffer(); int custom1 = readIntegerFromBuffer(); int custom2 = readIntegerFromBuffer(); Debug.assertion(readTag == tag); Debug.assertion(readClassId == (byte) classId); /* * Ignore when exit code as it is written by another writer. */ if (tag != TObjectWriter.DEBUG_TAG_CODE || !TObjectWriter.isExitCode(peekByteFromBuffer())) { long debugCounter = ThreadAssert.getOrCreateCurrent().getAndIncrementReaderDebugCounter(this); Debug.assertion(readDebugCounter == debugCounter); int localCustom1 = getCustomDebugInfo1(); if (custom1 > 0 && localCustom1 > 0) Debug.assertion(custom1 == localCustom1); int localCustom2 = getCustomDebugInfo2(); Debug.assertion(custom2 == localCustom2); } } int getCustomDebugInfo1() { if (!Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) throw new IllegalStateException(); return 0; } int getCustomDebugInfo2() { if (!Debug.COMMUNICATIONS && ImmutableWriter.getCheckCommunications()) throw new IllegalStateException(); return 0; } }
30.644133
173
0.581686
8ede234ec0da3994421cd3a7620856eed5bc6bd5
663
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Actions; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; /** * * @author Danielle S. Franรงa */ public class SimpleAuth extends Authenticator { public String username = null; public String password = null; public SimpleAuth(String user, String pwd) { username = user; password = pwd; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication (username,password); } }
22.862069
71
0.631976
f9e9cab31ff129c51eee51445167d618ad6c8984
997
package dev.paddock.adp.mCubed.scrobble; import dev.paddock.adp.mCubed.utilities.XMLDocument; import dev.paddock.adp.mCubed.utilities.XMLNode; public abstract class ScrobbleResponse { public static <T extends ScrobbleResponse> T parse(Class<T> clazz, String response) throws ScrobbleException { try { XMLDocument document = XMLDocument.read(response); XMLNode root = document.getRootNode(); String status = root.getAttribute("status"); if ("ok".equalsIgnoreCase(status)) { T scrobbleResponse = clazz.newInstance(); scrobbleResponse.parse(root); return scrobbleResponse; } else { XMLNode errorNode = root.getChildNode("error"); throw new ScrobbleException(errorNode.getAttribute("code"), errorNode.getNodeText().trim()); } } catch (IllegalAccessException e) { throw new ScrobbleException(e); } catch (InstantiationException e) { throw new ScrobbleException(e); } } protected abstract void parse(XMLNode node); }
34.37931
112
0.722166
d32f73909250c08165224af6633f2ed4e5e53351
1,003
package com.example.girish.todo.model.parsingModel; /** * Created by Girish on 8/18/2017. */ public class SupplierOrderDisplayModel { String productName; String productQuantity; String productImage; public SupplierOrderDisplayModel(String productName, String productQuantity, String productImage) { this.productName = productName; this.productQuantity = productQuantity; this.productImage = productImage; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductQuantity() { return productQuantity; } public void setProductQuantity(String productQuantity) { this.productQuantity = productQuantity; } public String getProductImage() { return productImage; } public void setProductImage(String productImage) { this.productImage = productImage; } }
24.463415
103
0.692921
a117674730991f7f9ada00ed7e2471b3d1af4450
291
package paxi.maokitty.source.annotation; import java.lang.annotation.*; /** * Created by maokitty on 19/5/3. * ๅšไบ›ไธŠไธ‹ๆ–‡็š„ๆ้†’ */ @Retention(RetentionPolicy.SOURCE) @Documented @Target({ElementType.TYPE,ElementType.METHOD}) public @interface Recall { int traceIndex(); String tip(); }
18.1875
46
0.725086
804aaa53cd50e088cda0a083d0400e34244d7c20
248,238
/* * Copyright (C) 2020 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.gyroscope; import com.irurueta.algebra.Matrix; import com.irurueta.algebra.WrongSizeException; import com.irurueta.navigation.LockedException; import com.irurueta.navigation.NotReadyException; import com.irurueta.navigation.frames.CoordinateTransformation; import com.irurueta.navigation.frames.ECEFFrame; import com.irurueta.navigation.frames.FrameType; import com.irurueta.navigation.frames.InvalidSourceAndDestinationFrameTypeException; import com.irurueta.navigation.frames.NEDFrame; import com.irurueta.navigation.frames.NEDPosition; import com.irurueta.navigation.frames.converters.NEDtoECEFFrameConverter; import com.irurueta.navigation.inertial.BodyKinematics; import com.irurueta.navigation.inertial.calibration.AngularSpeedTriad; import com.irurueta.navigation.inertial.calibration.BodyKinematicsGenerator; import com.irurueta.navigation.inertial.calibration.CalibrationException; import com.irurueta.navigation.inertial.calibration.IMUErrors; import com.irurueta.navigation.inertial.calibration.StandardDeviationFrameBodyKinematics; import com.irurueta.navigation.inertial.estimators.ECEFKinematicsEstimator; import com.irurueta.numerical.robust.RobustEstimatorMethod; import com.irurueta.statistics.GaussianRandomizer; import com.irurueta.statistics.UniformRandomizer; import com.irurueta.units.AngularSpeed; import com.irurueta.units.AngularSpeedUnit; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import static org.junit.Assert.*; public class PROSACRobustKnownFrameGyroscopeCalibratorTest implements RobustKnownFrameGyroscopeCalibratorListener { private static final double TIME_INTERVAL_SECONDS = 0.02; 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 MIN_ANGLE_DEGREES = -180.0; private static final double MAX_ANGLE_DEGREES = 180.0; private static final double MIN_LATITUDE_DEGREES = -90.0; private static final double MAX_LATITUDE_DEGREES = 90.0; private static final double MIN_LONGITUDE_DEGREES = -180.0; private static final double MAX_LONGITUDE_DEGREES = 180.0; private static final double MIN_HEIGHT = -50.0; private static final double MAX_HEIGHT = 50.0; private static final int MEASUREMENT_NUMBER = 1000; private static final int OUTLIER_PERCENTAGE = 20; private static final double THRESHOLD = 1e-18; private static final double LARGE_THRESHOLD = 5e-4; private static final double ABSOLUTE_ERROR = 1e-9; private static final double LARGE_ABSOLUTE_ERROR = 5e-5; private static final double VERY_LARGE_ABSOLUTE_ERROR = 1e-2; private static final double OUTLIER_ERROR_FACTOR = 100.0; private static final int TIMES = 100; private int mCalibrateStart; private int mCalibrateEnd; private int mCalibrateNextIteration; private int mCalibrateProgressChange; @Test public void testConstructor1() throws WrongSizeException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertNull(calibrator.getMeasurements()); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertFalse(calibrator.isCommonAxisUsed()); assertNull(calibrator.getListener()); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); Assert.assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertNull(calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); } @Test public void testConstructor2() throws WrongSizeException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(this); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertNull(calibrator.getMeasurements()); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertFalse(calibrator.isCommonAxisUsed()); assertSame(calibrator.getListener(), this); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertNull(calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); } @Test public void testConstructor3() throws WrongSizeException { final List<StandardDeviationFrameBodyKinematics> measurements = Collections.emptyList(); final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(measurements); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertSame(calibrator.getMeasurements(), measurements); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertFalse(calibrator.isCommonAxisUsed()); assertNull(calibrator.getListener()); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertNull(calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); } @Test public void testConstructor4() throws WrongSizeException { final List<StandardDeviationFrameBodyKinematics> measurements = Collections.emptyList(); final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(measurements, this); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertSame(calibrator.getMeasurements(), measurements); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertFalse(calibrator.isCommonAxisUsed()); assertSame(calibrator.getListener(), this); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertNull(calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); } @Test public void testConstructor5() throws WrongSizeException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(true); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertNull(calibrator.getMeasurements()); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertTrue(calibrator.isCommonAxisUsed()); assertNull(calibrator.getListener()); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertNull(calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); } @Test public void testConstructor6() throws WrongSizeException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(true, this); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertNull(calibrator.getMeasurements()); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertTrue(calibrator.isCommonAxisUsed()); assertSame(calibrator.getListener(), this); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertNull(calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); } @Test public void testConstructor7() throws WrongSizeException { final List<StandardDeviationFrameBodyKinematics> measurements = Collections.emptyList(); final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(measurements, true); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertSame(calibrator.getMeasurements(), measurements); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertTrue(calibrator.isCommonAxisUsed()); assertNull(calibrator.getListener()); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertNull(calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); } @Test public void testConstructor8() throws WrongSizeException { final List<StandardDeviationFrameBodyKinematics> measurements = Collections.emptyList(); final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(measurements, true, this); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertSame(calibrator.getMeasurements(), measurements); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertTrue(calibrator.isCommonAxisUsed()); assertSame(calibrator.getListener(), this); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertNull(calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); } @Test public void testConstructor9() throws WrongSizeException { final double[] qualityScores = new double[ PROSACRobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS]; PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(qualityScores); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertNull(calibrator.getMeasurements()); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertFalse(calibrator.isCommonAxisUsed()); assertNull(calibrator.getListener()); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertSame(qualityScores, calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); // Force IllegalArgumentException calibrator = null; try { calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator( new double[1]); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } assertNull(calibrator); } @Test public void testConstructor10() throws WrongSizeException { final double[] qualityScores = new double[ PROSACRobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS]; PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(qualityScores, this); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertNull(calibrator.getMeasurements()); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertFalse(calibrator.isCommonAxisUsed()); assertSame(calibrator.getListener(), this); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertSame(qualityScores, calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); // Force IllegalArgumentException calibrator = null; try { calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator( new double[1], this); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } assertNull(calibrator); } @Test public void testConstructor11() throws WrongSizeException { final double[] qualityScores = new double[ PROSACRobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS]; final List<StandardDeviationFrameBodyKinematics> measurements = Collections.emptyList(); PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(qualityScores, measurements); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertSame(calibrator.getMeasurements(), measurements); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertFalse(calibrator.isCommonAxisUsed()); assertNull(calibrator.getListener()); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertSame(qualityScores, calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); // Force IllegalArgumentException calibrator = null; try { calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator( new double[1], measurements); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } assertNull(calibrator); } @Test public void testConstructor12() throws WrongSizeException { final double[] qualityScores = new double[ PROSACRobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS]; final List<StandardDeviationFrameBodyKinematics> measurements = Collections.emptyList(); PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(qualityScores, measurements, this); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertSame(calibrator.getMeasurements(), measurements); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertFalse(calibrator.isCommonAxisUsed()); assertSame(calibrator.getListener(), this); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertSame(qualityScores, calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); // Force IllegalArgumentException calibrator = null; try { calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(new double[1], measurements, this); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } assertNull(calibrator); } @Test public void testConstructor13() throws WrongSizeException { final double[] qualityScores = new double[ PROSACRobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS]; PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator( qualityScores, true); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertNull(calibrator.getMeasurements()); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertTrue(calibrator.isCommonAxisUsed()); assertNull(calibrator.getListener()); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertSame(qualityScores, calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); // Force IllegalArgumentException calibrator = null; try { calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator( new double[1], true); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } assertNull(calibrator); } @Test public void testConstructor14() throws WrongSizeException { final double[] qualityScores = new double[ PROSACRobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS]; PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(qualityScores, true, this); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertNull(calibrator.getMeasurements()); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertTrue(calibrator.isCommonAxisUsed()); assertSame(calibrator.getListener(), this); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertSame(qualityScores, calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); // Force IllegalArgumentException calibrator = null; try { calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator( new double[1], true, this); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } assertNull(calibrator); } @Test public void testConstructor15() throws WrongSizeException { final double[] qualityScores = new double[ PROSACRobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS]; final List<StandardDeviationFrameBodyKinematics> measurements = Collections.emptyList(); PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(qualityScores, measurements, true); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertSame(calibrator.getMeasurements(), measurements); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertTrue(calibrator.isCommonAxisUsed()); assertNull(calibrator.getListener()); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertSame(qualityScores, calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); // Force IllegalArgumentException calibrator = null; try { calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator( new double[1], measurements, true); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } assertNull(calibrator); } @Test public void testConstructor16() throws WrongSizeException { final double[] qualityScores = new double[ PROSACRobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS]; final List<StandardDeviationFrameBodyKinematics> measurements = Collections.emptyList(); PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(qualityScores, measurements, true, this); // check default values assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); assertEquals(calibrator.isComputeAndKeepInliersEnabled(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_INLIERS); assertEquals(calibrator.isComputeAndKeepResiduals(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_COMPUTE_AND_KEEP_RESIDUALS); assertEquals(calibrator.getMethod(), RobustEstimatorMethod.PROSAC); assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); final AngularSpeed bgx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bgx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); final AngularSpeed bgy1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(bgy1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgy1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); final AngularSpeed bgz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bgz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bgz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); final AngularSpeedTriad initialBiasTriad1 = calibrator.getInitialBiasAsTriad(); assertEquals(initialBiasTriad1.getValueX(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueY(), 0.0, 0.0); assertEquals(initialBiasTriad1.getValueZ(), 0.0, 0.0); assertEquals(initialBiasTriad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad initialBiasTriad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(initialBiasTriad2); assertEquals(initialBiasTriad1, initialBiasTriad2); assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); final double[] bias1 = new double[3]; assertArrayEquals(calibrator.getInitialBias(), bias1, 0.0); final double[] bias2 = new double[3]; calibrator.getInitialBias(bias2); assertArrayEquals(bias1, bias2, 0.0); final Matrix biasMatrix1 = new Matrix(3, 1); assertEquals(calibrator.getInitialBiasAsMatrix(), biasMatrix1); final Matrix biasMatrix2 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(biasMatrix2); assertEquals(biasMatrix1, biasMatrix2); final Matrix mg1 = calibrator.getInitialMg(); assertEquals(mg1, new Matrix(3, 3)); final Matrix mg2 = new Matrix(3, 3); calibrator.getInitialMg(mg2); assertEquals(mg1, mg2); final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); final Matrix gg2 = new Matrix(3, 3); calibrator.getInitialGg(gg2); assertEquals(gg1, gg2); assertSame(calibrator.getMeasurements(), measurements); assertEquals(GyroscopeCalibratorMeasurementOrSequenceType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS_MEASUREMENT, calibrator.getMeasurementOrSequenceType()); assertTrue(calibrator.isOrderedMeasurementsOrSequencesRequired()); assertTrue(calibrator.isQualityScoresRequired()); assertTrue(calibrator.isCommonAxisUsed()); assertSame(calibrator.getListener(), this); assertEquals(RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS, calibrator.getMinimumRequiredMeasurementsOrSequences()); assertFalse(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertTrue(calibrator.isLinearCalibratorUsed()); assertFalse(calibrator.isPreliminarySolutionRefined()); assertEquals(calibrator.getProgressDelta(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(calibrator.getConfidence(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); assertEquals(calibrator.getMaxIterations(), RobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS, 0.0); assertNull(calibrator.getInliersData()); assertTrue(calibrator.isResultRefined()); assertTrue(calibrator.isCovarianceKept()); assertSame(qualityScores, calibrator.getQualityScores()); assertNull(calibrator.getEstimatedBiases()); assertFalse(calibrator.getEstimatedBiases(null)); assertNull(calibrator.getEstimatedBiasesAsMatrix()); assertFalse(calibrator.getEstimatedBiasesAsMatrix(null)); assertNull(calibrator.getEstimatedBiasX()); assertNull(calibrator.getEstimatedBiasY()); assertNull(calibrator.getEstimatedBiasZ()); assertNull(calibrator.getEstimatedBiasAngularSpeedX()); assertFalse(calibrator.getEstimatedBiasAngularSpeedX(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedY()); assertFalse(calibrator.getEstimatedBiasAngularSpeedY(null)); assertNull(calibrator.getEstimatedBiasAngularSpeedZ()); assertFalse(calibrator.getEstimatedBiasAngularSpeedZ(null)); assertNull(calibrator.getEstimatedBiasAsTriad()); assertFalse(calibrator.getEstimatedBiasAsTriad(null)); assertNull(calibrator.getEstimatedMg()); assertNull(calibrator.getEstimatedSx()); assertNull(calibrator.getEstimatedSy()); assertNull(calibrator.getEstimatedSz()); assertNull(calibrator.getEstimatedMxy()); assertNull(calibrator.getEstimatedMxz()); assertNull(calibrator.getEstimatedMyx()); assertNull(calibrator.getEstimatedMyz()); assertNull(calibrator.getEstimatedMzx()); assertNull(calibrator.getEstimatedMzy()); assertNull(calibrator.getEstimatedGg()); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getPreliminarySubsetSize(), RobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); assertNull(calibrator.getEstimatedBiasXVariance()); assertNull(calibrator.getEstimatedBiasXStandardDeviation()); assertNull(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasYVariance()); assertNull(calibrator.getEstimatedBiasYStandardDeviation()); assertNull(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasZVariance()); assertNull(calibrator.getEstimatedBiasZStandardDeviation()); assertNull(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviation()); assertFalse(calibrator.getEstimatedBiasStandardDeviation(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationAverage()); assertNull(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(null)); assertNull(calibrator.getEstimatedBiasStandardDeviationNorm()); assertNull(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed()); assertFalse(calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(null)); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); // Force IllegalArgumentException calibrator = null; try { calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator( new double[1], measurements, true, this); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } assertNull(calibrator); } @Test public void testGetSetThreshold() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getThreshold(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_THRESHOLD, 0.0); // set new value calibrator.setThreshold(1.0); // check assertEquals(calibrator.getThreshold(), 1.0, 0.0); // Force IllegalArgumentException try { calibrator.setThreshold(0.0); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testIsSetComputeAndKeepInliersEnabled() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertFalse(calibrator.isComputeAndKeepInliersEnabled()); // set new value calibrator.setComputeAndKeepInliersEnabled(true); // check assertTrue(calibrator.isComputeAndKeepInliersEnabled()); } @Test public void testIsSetComputeAndKeepResidualsEnabled() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertFalse(calibrator.isComputeAndKeepResiduals()); // set new value calibrator.setComputeAndKeepResidualsEnabled(true); // check assertTrue(calibrator.isComputeAndKeepResiduals()); } @Test public void testGetSetInitialBiasX() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); // set new value final Matrix bg = generateBg(); final double biasX = bg.getElementAtIndex(0); calibrator.setInitialBiasX(biasX); // check assertEquals(calibrator.getInitialBiasX(), biasX, 0.0); } @Test public void testGetSetInitialBiasY() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); // set new value final Matrix bg = generateBg(); final double biasY = bg.getElementAtIndex(1); calibrator.setInitialBiasY(biasY); // check assertEquals(calibrator.getInitialBiasY(), biasY, 0.0); } @Test public void testGetSetInitialBiasZ() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); // set new value final Matrix bg = generateBg(); final double biasZ = bg.getElementAtIndex(2); calibrator.setInitialBiasZ(biasZ); // check assertEquals(calibrator.getInitialBiasZ(), biasZ, 0.0); } @Test public void testGetSetInitialBiasAngularSpeedX() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value final AngularSpeed bx1 = calibrator.getInitialBiasAngularSpeedX(); assertEquals(bx1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bx1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); // set new value final Matrix bg = generateBg(); final double biasX = bg.getElementAtIndex(0); final AngularSpeed bx2 = new AngularSpeed(biasX, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.setInitialBiasX(bx2); // check final AngularSpeed bx3 = calibrator.getInitialBiasAngularSpeedX(); final AngularSpeed bx4 = new AngularSpeed(0.0, AngularSpeedUnit.DEGREES_PER_SECOND); calibrator.getInitialBiasAngularSpeedX(bx4); assertEquals(bx2, bx3); assertEquals(bx2, bx4); } @Test public void testGetSetInitialBiasAngularSpeedY() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value final AngularSpeed by1 = calibrator.getInitialBiasAngularSpeedY(); assertEquals(by1.getValue().doubleValue(), 0.0, 0.0); assertEquals(by1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); // set new value final Matrix bg = generateBg(); final double biasY = bg.getElementAtIndex(1); final AngularSpeed by2 = new AngularSpeed(biasY, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.setInitialBiasY(by2); // check final AngularSpeed by3 = calibrator.getInitialBiasAngularSpeedY(); final AngularSpeed by4 = new AngularSpeed(0.0, AngularSpeedUnit.DEGREES_PER_SECOND); calibrator.getInitialBiasAngularSpeedY(by4); assertEquals(by2, by3); assertEquals(by2, by4); } @Test public void testGetSetInitialBiasAngularSpeedZ() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value final AngularSpeed bz1 = calibrator.getInitialBiasAngularSpeedZ(); assertEquals(bz1.getValue().doubleValue(), 0.0, 0.0); assertEquals(bz1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); // set new value final Matrix bg = generateBg(); final double biasZ = bg.getElementAtIndex(2); final AngularSpeed bz2 = new AngularSpeed(biasZ, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.setInitialBiasZ(bz2); // check final AngularSpeed bz3 = calibrator.getInitialBiasAngularSpeedZ(); final AngularSpeed bz4 = new AngularSpeed(0.0, AngularSpeedUnit.DEGREES_PER_SECOND); calibrator.getInitialBiasAngularSpeedZ(bz4); assertEquals(bz2, bz3); assertEquals(bz2, bz4); } @Test public void testSetInitialBias1() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check initial values assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); // set new values final Matrix bg = generateBg(); final double biasX = bg.getElementAtIndex(0); final double biasY = bg.getElementAtIndex(1); final double biasZ = bg.getElementAtIndex(2); calibrator.setInitialBias(biasX, biasY, biasZ); // check assertEquals(biasX, calibrator.getInitialBiasX(), 0.0); assertEquals(biasY, calibrator.getInitialBiasY(), 0.0); assertEquals(biasZ, calibrator.getInitialBiasZ(), 0.0); } @Test public void testSetInitialBias2() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check initial values assertEquals(calibrator.getInitialBiasX(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasY(), 0.0, 0.0); assertEquals(calibrator.getInitialBiasZ(), 0.0, 0.0); // set new values final Matrix bg = generateBg(); final double biasX = bg.getElementAtIndex(0); final double biasY = bg.getElementAtIndex(1); final double biasZ = bg.getElementAtIndex(2); final AngularSpeed bx = new AngularSpeed(biasX, AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed by = new AngularSpeed(biasY, AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeed bz = new AngularSpeed(biasZ, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.setInitialBias(bx, by, bz); // check assertEquals(biasX, calibrator.getInitialBiasX(), 0.0); assertEquals(biasY, calibrator.getInitialBiasY(), 0.0); assertEquals(biasZ, calibrator.getInitialBiasZ(), 0.0); } @Test public void testGetSetInitialBiasAsTriad() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default values final AngularSpeedTriad triad1 = calibrator.getInitialBiasAsTriad(); assertEquals(triad1.getValueX(), 0.0, 0.0); assertEquals(triad1.getValueY(), 0.0, 0.0); assertEquals(triad1.getValueZ(), 0.0, 0.0); assertEquals(triad1.getUnit(), AngularSpeedUnit.RADIANS_PER_SECOND); final AngularSpeedTriad triad2 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(triad2); assertEquals(triad1, triad2); // set new values final Matrix bg = generateBg(); final double initialBiasX = bg.getElementAtIndex(0); final double initialBiasY = bg.getElementAtIndex(1); final double initialBiasZ = bg.getElementAtIndex(2); final AngularSpeedTriad triad3 = new AngularSpeedTriad( AngularSpeedUnit.RADIANS_PER_SECOND, initialBiasX, initialBiasY, initialBiasZ); calibrator.setInitialBias(triad3); final AngularSpeedTriad triad4 = calibrator.getInitialBiasAsTriad(); final AngularSpeedTriad triad5 = new AngularSpeedTriad(); calibrator.getInitialBiasAsTriad(triad5); assertEquals(triad3, triad4); assertEquals(triad3, triad5); } @Test public void testGetSetInitialSx() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getInitialSx(), 0.0, 0.0); // set new value final Matrix mg = generateMg(); final double initialSx = mg.getElementAt(0, 0); calibrator.setInitialSx(initialSx); // check assertEquals(initialSx, calibrator.getInitialSx(), 0.0); } @Test public void testGetSetInitialSy() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getInitialSy(), 0.0, 0.0); // set new value final Matrix mg = generateMg(); final double initialSy = mg.getElementAt(1, 1); calibrator.setInitialSy(initialSy); // check assertEquals(initialSy, calibrator.getInitialSy(), 0.0); } @Test public void testGetSetInitialSz() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getInitialSz(), 0.0, 0.0); // set new value final Matrix mg = generateMg(); final double initialSz = mg.getElementAt(2, 2); calibrator.setInitialSz(initialSz); // check assertEquals(initialSz, calibrator.getInitialSz(), 0.0); } @Test public void testGetSetInitialMxy() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); // set new value final Matrix mg = generateMg(); final double initialMxy = mg.getElementAt(0, 1); calibrator.setInitialMxy(initialMxy); // check assertEquals(initialMxy, calibrator.getInitialMxy(), 0.0); } @Test public void testGetSetInitialMxz() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); // set new value final Matrix mg = generateMg(); final double initialMxz = mg.getElementAt(0, 2); calibrator.setInitialMxz(initialMxz); // check assertEquals(initialMxz, calibrator.getInitialMxz(), 0.0); } @Test public void testGetSetInitialMyx() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); // set new value final Matrix mg = generateMg(); final double initialMyx = mg.getElementAt(1, 0); calibrator.setInitialMyx(initialMyx); // check assertEquals(initialMyx, calibrator.getInitialMyx(), 0.0); } @Test public void testGetSetInitialMyz() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); // set new value final Matrix mg = generateMg(); final double initialMyz = mg.getElementAt(1, 2); calibrator.setInitialMyz(initialMyz); // check assertEquals(initialMyz, calibrator.getInitialMyz(), 0.0); } @Test public void testGetSetInitialMzx() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); // set new value final Matrix mg = generateMg(); final double initialMzx = mg.getElementAt(2, 0); calibrator.setInitialMzx(initialMzx); // check assertEquals(initialMzx, calibrator.getInitialMzx(), 0.0); } @Test public void testGetSetInitialMzy() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); // set new value final Matrix mg = generateMg(); final double initialMzy = mg.getElementAt(2, 1); calibrator.setInitialMzy(initialMzy); // check assertEquals(initialMzy, calibrator.getInitialMzy(), 0.0); } @Test public void testSetInitialScalingFactors() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default values assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); // set new value final Matrix mg = generateMg(); final double initialSx = mg.getElementAt(0, 0); final double initialSy = mg.getElementAt(1, 1); final double initialSz = mg.getElementAt(2, 2); calibrator.setInitialScalingFactors(initialSx, initialSy, initialSz); // check assertEquals(initialSx, calibrator.getInitialSx(), 0.0); assertEquals(initialSy, calibrator.getInitialSy(), 0.0); assertEquals(initialSz, calibrator.getInitialSz(), 0.0); } @Test public void testSetInitialCrossCouplingErrors() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default values assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); // set new values final Matrix mg = generateMg(); final double initialMxy = mg.getElementAt(0, 1); final double initialMxz = mg.getElementAt(0, 2); final double initialMyx = mg.getElementAt(1, 0); final double initialMyz = mg.getElementAt(1, 2); final double initialMzx = mg.getElementAt(2, 0); final double initialMzy = mg.getElementAt(2, 1); calibrator.setInitialCrossCouplingErrors(initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); // check assertEquals(initialMxy, calibrator.getInitialMxy(), 0.0); assertEquals(initialMxz, calibrator.getInitialMxz(), 0.0); assertEquals(initialMyx, calibrator.getInitialMyx(), 0.0); assertEquals(initialMyz, calibrator.getInitialMyz(), 0.0); assertEquals(initialMzx, calibrator.getInitialMzx(), 0.0); assertEquals(initialMzy, calibrator.getInitialMzy(), 0.0); } @Test public void testSetInitialScalingFactorsAndCrossCouplingErrors() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default values assertEquals(calibrator.getInitialSx(), 0.0, 0.0); assertEquals(calibrator.getInitialSy(), 0.0, 0.0); assertEquals(calibrator.getInitialSz(), 0.0, 0.0); assertEquals(calibrator.getInitialMxy(), 0.0, 0.0); assertEquals(calibrator.getInitialMxz(), 0.0, 0.0); assertEquals(calibrator.getInitialMyx(), 0.0, 0.0); assertEquals(calibrator.getInitialMyz(), 0.0, 0.0); assertEquals(calibrator.getInitialMzx(), 0.0, 0.0); assertEquals(calibrator.getInitialMzy(), 0.0, 0.0); // set new values final Matrix mg = generateMg(); final double initialSx = mg.getElementAt(0, 0); final double initialSy = mg.getElementAt(1, 1); final double initialSz = mg.getElementAt(2, 2); final double initialMxy = mg.getElementAt(0, 1); final double initialMxz = mg.getElementAt(0, 2); final double initialMyx = mg.getElementAt(1, 0); final double initialMyz = mg.getElementAt(1, 2); final double initialMzx = mg.getElementAt(2, 0); final double initialMzy = mg.getElementAt(2, 1); calibrator.setInitialScalingFactorsAndCrossCouplingErrors( initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); // check assertEquals(initialSx, calibrator.getInitialSx(), 0.0); assertEquals(initialSy, calibrator.getInitialSy(), 0.0); assertEquals(initialSz, calibrator.getInitialSz(), 0.0); assertEquals(initialMxy, calibrator.getInitialMxy(), 0.0); assertEquals(initialMxz, calibrator.getInitialMxz(), 0.0); assertEquals(initialMyx, calibrator.getInitialMyx(), 0.0); assertEquals(initialMyz, calibrator.getInitialMyz(), 0.0); assertEquals(initialMzx, calibrator.getInitialMzx(), 0.0); assertEquals(initialMzy, calibrator.getInitialMzy(), 0.0); } @Test public void testGetSetInitialBias() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value final double[] bias1 = calibrator.getInitialBias(); assertArrayEquals(new double[3], bias1, 0.0); // set new value final Matrix bg = generateBg(); final double[] bias2 = bg.getBuffer(); calibrator.setInitialBias(bias2); // check final double[] bias3 = calibrator.getInitialBias(); final double[] bias4 = new double[3]; calibrator.getInitialBias(bias4); assertArrayEquals(bias2, bias3, 0.0); assertArrayEquals(bias2, bias4, 0.0); // Force IllegalArgumentException try { calibrator.setInitialBias(new double[1]); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testGetSetInitialBiasAsMatrix() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value final Matrix bias1 = calibrator.getInitialBiasAsMatrix(); assertEquals(bias1, new Matrix(3, 1)); // set new value final Matrix bias2 = generateBg(); calibrator.setInitialBias(bias2); // check final Matrix bias3 = calibrator.getInitialBiasAsMatrix(); final Matrix bias4 = new Matrix(3, 1); calibrator.getInitialBiasAsMatrix(bias4); assertEquals(bias2, bias3); assertEquals(bias2, bias4); // Force IllegalArgumentException try { calibrator.getInitialBiasAsMatrix(new Matrix(1, 1)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { calibrator.getInitialBiasAsMatrix(new Matrix(3, 3)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { calibrator.setInitialBias(new Matrix(1, 1)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { calibrator.setInitialBias(new Matrix(3, 3)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testGetSetInitialMg() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value final Matrix mg1 = calibrator.getInitialMg(); assertEquals(new Matrix(3, 3), mg1); // set new value final Matrix mg2 = generateMg(); calibrator.setInitialMg(mg2); // check final Matrix mg3 = calibrator.getInitialMg(); final Matrix mg4 = new Matrix(3, 3); calibrator.getInitialMg(mg4); assertEquals(mg2, mg3); assertEquals(mg2, mg4); // Force IllegalArgumentException try { calibrator.getInitialMg(new Matrix(1, 3)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { calibrator.getInitialMg(new Matrix(3, 1)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { calibrator.setInitialMg(new Matrix(1, 3)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { calibrator.setInitialMg(new Matrix(3, 1)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testGetSetInitialGg() throws WrongSizeException, LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value final Matrix gg1 = calibrator.getInitialGg(); assertEquals(gg1, new Matrix(3, 3)); // set new value final Matrix gg2 = generateGg(); calibrator.setInitialGg(gg2); // check final Matrix gg3 = calibrator.getInitialGg(); final Matrix gg4 = new Matrix(3, 3); calibrator.getInitialGg(gg4); assertEquals(gg2, gg3); assertEquals(gg2, gg4); // Force IllegalArgumentException try { calibrator.getInitialGg(new Matrix(1, 3)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { calibrator.getInitialGg(new Matrix(3, 1)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { calibrator.setInitialGg(new Matrix(1, 3)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { calibrator.setInitialGg(new Matrix(3, 1)); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testGetSetMeasurements() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertNull(calibrator.getMeasurements()); // set new value final List<StandardDeviationFrameBodyKinematics> measurements = Collections.emptyList(); calibrator.setMeasurements(measurements); // check assertSame(measurements, calibrator.getMeasurements()); } @Test public void testIsSetCommonAxisUsed() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertFalse(calibrator.isCommonAxisUsed()); // set new value calibrator.setCommonAxisUsed(true); // check assertTrue(calibrator.isCommonAxisUsed()); } @Test public void testGetSetListener() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertNull(calibrator.getListener()); // set new value calibrator.setListener(this); // check assertSame(calibrator.getListener(), this); } @Test public void testIsSetLinearCalibratorUsed() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertTrue(calibrator.isLinearCalibratorUsed()); // set new value calibrator.setLinearCalibratorUsed(false); // check assertFalse(calibrator.isLinearCalibratorUsed()); } @Test public void testIsSetPreliminarySolutionRefined() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertFalse(calibrator.isPreliminarySolutionRefined()); // set new value calibrator.setPreliminarySolutionRefined(true); // check assertTrue(calibrator.isPreliminarySolutionRefined()); } @Test public void testGetSetProgressDelta() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getProgressDelta(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_PROGRESS_DELTA, 0.0); // set new value calibrator.setProgressDelta(0.5f); // check assertEquals(calibrator.getProgressDelta(), 0.5f, 0.0); // Force IllegalArgumentException try { calibrator.setProgressDelta(-1.0f); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { calibrator.setProgressDelta(2.0f); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testGetSetConfidence() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getConfidence(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_CONFIDENCE, 0.0); // set new value calibrator.setConfidence(0.8); // check assertEquals(calibrator.getConfidence(), 0.8, 0.0); // Force IllegalArgumentException try { calibrator.setConfidence(-1.0); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { calibrator.setConfidence(2.0); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testGetSetMaxIterations() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getMaxIterations(), PROSACRobustKnownFrameGyroscopeCalibrator.DEFAULT_MAX_ITERATIONS); // set new value calibrator.setMaxIterations(1); assertEquals(calibrator.getMaxIterations(), 1); // force IllegalArgumentException try { calibrator.setMaxIterations(0); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testIsSetResultRefined() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertTrue(calibrator.isResultRefined()); // set new value calibrator.setResultRefined(false); // check assertFalse(calibrator.isResultRefined()); } @Test public void testIsSetCovarianceKept() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertTrue(calibrator.isCovarianceKept()); // set new value calibrator.setCovarianceKept(false); // check assertFalse(calibrator.isCovarianceKept()); } @Test public void testGetSetQualityScores() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertNull(calibrator.getQualityScores()); // set new value final double[] qualityScores = new double[ PROSACRobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS]; calibrator.setQualityScores(qualityScores); // check assertSame(qualityScores, calibrator.getQualityScores()); // Force IllegalArgumentException try { calibrator.setQualityScores(new double[6]); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testGetSetPreliminarySubsetSize() throws LockedException { final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(); // check default value assertEquals(calibrator.getPreliminarySubsetSize(), PROSACRobustKnownFrameGyroscopeCalibrator.MINIMUM_MEASUREMENTS); // set new value calibrator.setPreliminarySubsetSize(8); // check assertEquals(calibrator.getPreliminarySubsetSize(), 8); // force IllegalArgumentException try { calibrator.setPreliminarySubsetSize(6); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testCalibrateGeneralNoNoiseInlier() throws WrongSizeException, InvalidSourceAndDestinationFrameTypeException, LockedException, CalibrationException, NotReadyException { int numValid = 0; for (int t = 0; t < TIMES; t++) { final Matrix ba = generateBa(); final Matrix bg = generateBg(); final Matrix ma = generateMaGeneral(); final Matrix mg = generateMg(); final Matrix gg = generateGg(); final double accelNoiseRootPSD = getAccelNoiseRootPSD(); final double gyroNoiseRootPSD = getGyroNoiseRootPSD(); final double accelQuantLevel = 0.0; final double gyroQuantLevel = 0.0; final IMUErrors errorsOutlier = new IMUErrors(ba, bg, ma, mg, gg, accelNoiseRootPSD, gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final IMUErrors errorsInlier = new IMUErrors(ba, bg, ma, mg, gg, 0.0, 0.0, accelQuantLevel, gyroQuantLevel); final Random random = new Random(); final UniformRandomizer randomizer = new UniformRandomizer(random); final double latitude = Math.toRadians( randomizer.nextDouble(MIN_LATITUDE_DEGREES, MAX_LATITUDE_DEGREES)); final double longitude = Math.toRadians( randomizer.nextDouble(MIN_LONGITUDE_DEGREES, MAX_LONGITUDE_DEGREES)); final double height = randomizer.nextDouble(MIN_HEIGHT, MAX_HEIGHT); final NEDPosition nedPosition = new NEDPosition(latitude, longitude, height); final double sqrtTimeInterval = Math.sqrt(TIME_INTERVAL_SECONDS); final double specificForceStandardDeviation = getAccelNoiseRootPSD() / sqrtTimeInterval; final double angularRateStandardDeviation = getGyroNoiseRootPSD() / sqrtTimeInterval; final GaussianRandomizer errorRandomizer = new GaussianRandomizer( random, 0.0, angularRateStandardDeviation); final List<StandardDeviationFrameBodyKinematics> measurements = new ArrayList<>(); final double[] qualityScores = new double[MEASUREMENT_NUMBER]; double error; for (int i = 0; i < MEASUREMENT_NUMBER; i++) { final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final CoordinateTransformation nedC = new CoordinateTransformation( roll, pitch, yaw, FrameType.BODY_FRAME, FrameType.LOCAL_NAVIGATION_FRAME); final NEDFrame nedFrame = new NEDFrame(nedPosition, nedC); final ECEFFrame ecefFrame = NEDtoECEFFrameConverter .convertNEDtoECEFAndReturnNew(nedFrame); // compute ground-truth kinematics that should be generated at provided // position, velocity and orientation final BodyKinematics trueKinematics = ECEFKinematicsEstimator .estimateKinematicsAndReturnNew(TIME_INTERVAL_SECONDS, ecefFrame, ecefFrame); // apply known calibration parameters to distort ground-truth and generate a // measured kinematics sample final BodyKinematics measuredKinematics; if (randomizer.nextInt(0, 100) < OUTLIER_PERCENTAGE) { // outlier measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errorsOutlier, random); error = Math.abs(errorRandomizer.nextDouble()); } else { // inlier measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errorsInlier, random); error = 0.0; } final StandardDeviationFrameBodyKinematics measurement = new StandardDeviationFrameBodyKinematics(measuredKinematics, ecefFrame, ecefFrame, TIME_INTERVAL_SECONDS, specificForceStandardDeviation, angularRateStandardDeviation); measurements.add(measurement); qualityScores[i] = 1.0 / (1.0 + error); } final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(qualityScores, measurements, false, this); calibrator.setThreshold(THRESHOLD); // estimate reset(); assertTrue(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertEquals(mCalibrateStart, 0); assertEquals(mCalibrateEnd, 0); assertEquals(mCalibrateNextIteration, 0); assertEquals(mCalibrateProgressChange, 0); calibrator.calibrate(); // check assertTrue(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertEquals(mCalibrateStart, 1); assertEquals(mCalibrateEnd, 1); assertTrue(mCalibrateNextIteration > 0); assertTrue(mCalibrateProgressChange >= 0); final Matrix estimatedBg = calibrator.getEstimatedBiasesAsMatrix(); final Matrix estimatedMg = calibrator.getEstimatedMg(); final Matrix estimatedGg = calibrator.getEstimatedGg(); if (!bg.equals(estimatedBg, LARGE_ABSOLUTE_ERROR)) { continue; } if (!gg.equals(estimatedGg, LARGE_ABSOLUTE_ERROR)) { continue; } assertTrue(bg.equals(estimatedBg, LARGE_ABSOLUTE_ERROR)); assertNotNull(estimatedMg); assertTrue(gg.equals(estimatedGg, LARGE_ABSOLUTE_ERROR)); assertEstimatedResult(estimatedBg, estimatedMg, estimatedGg, calibrator, true); assertNotNull(calibrator.getEstimatedCovariance()); checkGeneralCovariance(calibrator.getEstimatedCovariance()); assertTrue(calibrator.getEstimatedMse() > 0.0); assertNotEquals(calibrator.getEstimatedChiSq(), 0.0); numValid++; break; } assertTrue(numValid > 0); } @Test public void testCalibrateCommonAxisNoNoiseInlier() throws WrongSizeException, InvalidSourceAndDestinationFrameTypeException, LockedException, CalibrationException, NotReadyException { int numValid = 0; for (int t = 0; t < TIMES; t++) { final Matrix ba = generateBa(); final Matrix bg = generateBg(); final Matrix ma = generateMaCommonAxis(); final Matrix mg = generateMg(); final Matrix gg = generateGg(); final double accelNoiseRootPSD = getAccelNoiseRootPSD(); final double gyroNoiseRootPSD = getGyroNoiseRootPSD(); final double accelQuantLevel = 0.0; final double gyroQuantLevel = 0.0; final IMUErrors errorsOutlier = new IMUErrors(ba, bg, ma, mg, gg, accelNoiseRootPSD, gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final IMUErrors errorsInlier = new IMUErrors(ba, bg, ma, mg, gg, 0.0, 0.0, accelQuantLevel, gyroQuantLevel); final Random random = new Random(); final UniformRandomizer randomizer = new UniformRandomizer(random); final double latitude = Math.toRadians( randomizer.nextDouble(MIN_LATITUDE_DEGREES, MAX_LATITUDE_DEGREES)); final double longitude = Math.toRadians( randomizer.nextDouble(MIN_LONGITUDE_DEGREES, MAX_LONGITUDE_DEGREES)); final double height = randomizer.nextDouble(MIN_HEIGHT, MAX_HEIGHT); final NEDPosition nedPosition = new NEDPosition(latitude, longitude, height); final double sqrtTimeInterval = Math.sqrt(TIME_INTERVAL_SECONDS); final double specificForceStandardDeviation = getAccelNoiseRootPSD() / sqrtTimeInterval; final double angularRateStandardDeviation = getGyroNoiseRootPSD() / sqrtTimeInterval; final GaussianRandomizer errorRandomizer = new GaussianRandomizer( random, 0.0, angularRateStandardDeviation); final List<StandardDeviationFrameBodyKinematics> measurements = new ArrayList<>(); final double[] qualityScores = new double[MEASUREMENT_NUMBER]; double error; for (int i = 0; i < MEASUREMENT_NUMBER; i++) { final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final CoordinateTransformation nedC = new CoordinateTransformation( roll, pitch, yaw, FrameType.BODY_FRAME, FrameType.LOCAL_NAVIGATION_FRAME); final NEDFrame nedFrame = new NEDFrame(nedPosition, nedC); final ECEFFrame ecefFrame = NEDtoECEFFrameConverter .convertNEDtoECEFAndReturnNew(nedFrame); // compute ground-truth kinematics that should be generated at provided // position, velocity and orientation final BodyKinematics trueKinematics = ECEFKinematicsEstimator .estimateKinematicsAndReturnNew(TIME_INTERVAL_SECONDS, ecefFrame, ecefFrame); // apply known calibration parameters to distort ground-truth and generate a // measured kinematics sample final BodyKinematics measuredKinematics; if (randomizer.nextInt(0, 100) < OUTLIER_PERCENTAGE) { // outlier measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errorsOutlier, random); error = Math.abs(errorRandomizer.nextDouble()); } else { // inlier measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errorsInlier, random); error = 0.0; } final StandardDeviationFrameBodyKinematics measurement = new StandardDeviationFrameBodyKinematics(measuredKinematics, ecefFrame, ecefFrame, TIME_INTERVAL_SECONDS, specificForceStandardDeviation, angularRateStandardDeviation); measurements.add(measurement); qualityScores[i] = 1.0 / (1.0 + error); } final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(qualityScores, measurements, true, this); calibrator.setThreshold(THRESHOLD); // estimate reset(); assertTrue(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertEquals(mCalibrateStart, 0); assertEquals(mCalibrateEnd, 0); assertEquals(mCalibrateNextIteration, 0); assertEquals(mCalibrateProgressChange, 0); calibrator.calibrate(); // check assertTrue(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertEquals(mCalibrateStart, 1); assertEquals(mCalibrateEnd, 1); assertTrue(mCalibrateNextIteration > 0); assertTrue(mCalibrateProgressChange >= 0); final Matrix estimatedBg = calibrator.getEstimatedBiasesAsMatrix(); final Matrix estimatedMg = calibrator.getEstimatedMg(); final Matrix estimatedGg = calibrator.getEstimatedGg(); if (!bg.equals(estimatedBg, LARGE_ABSOLUTE_ERROR)) { continue; } if (!mg.equals(estimatedMg, VERY_LARGE_ABSOLUTE_ERROR)) { continue; } if (!gg.equals(estimatedGg, LARGE_ABSOLUTE_ERROR)) { continue; } assertTrue(bg.equals(estimatedBg, LARGE_ABSOLUTE_ERROR)); assertTrue(mg.equals(estimatedMg, VERY_LARGE_ABSOLUTE_ERROR)); assertTrue(gg.equals(estimatedGg, LARGE_ABSOLUTE_ERROR)); assertEstimatedResult(estimatedBg, estimatedMg, estimatedGg, calibrator, true); assertNotNull(calibrator.getEstimatedCovariance()); checkCommonAxisCovariance(calibrator.getEstimatedCovariance()); assertTrue(calibrator.getEstimatedMse() > 0.0); assertNotEquals(calibrator.getEstimatedChiSq(), 0.0); numValid++; break; } assertTrue(numValid > 0); } @Test public void testCalibrateGeneralWithInlierNoise() throws WrongSizeException, InvalidSourceAndDestinationFrameTypeException, LockedException, CalibrationException, NotReadyException { int numValid = 0; for (int t = 0; t < TIMES; t++) { final Matrix ba = generateBa(); final Matrix bg = generateBg(); final Matrix ma = generateMaGeneral(); final Matrix mg = generateMg(); final Matrix gg = generateGg(); final double accelNoiseRootPSD = getAccelNoiseRootPSD(); final double gyroNoiseRootPSD = getGyroNoiseRootPSD(); final double accelQuantLevel = 0.0; final double gyroQuantLevel = 0.0; final IMUErrors errorsOutlier = new IMUErrors(ba, bg, ma, mg, gg, OUTLIER_ERROR_FACTOR * accelNoiseRootPSD, OUTLIER_ERROR_FACTOR * gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final IMUErrors errorsInlier = new IMUErrors(ba, bg, ma, mg, gg, accelNoiseRootPSD, gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final Random random = new Random(); final UniformRandomizer randomizer = new UniformRandomizer(random); final double latitude = Math.toRadians( randomizer.nextDouble(MIN_LATITUDE_DEGREES, MAX_LATITUDE_DEGREES)); final double longitude = Math.toRadians( randomizer.nextDouble(MIN_LONGITUDE_DEGREES, MAX_LONGITUDE_DEGREES)); final double height = randomizer.nextDouble(MIN_HEIGHT, MAX_HEIGHT); final NEDPosition nedPosition = new NEDPosition(latitude, longitude, height); final double sqrtTimeInterval = Math.sqrt(TIME_INTERVAL_SECONDS); final double specificForceStandardDeviation = getAccelNoiseRootPSD() / sqrtTimeInterval; final double angularRateStandardDeviation = getGyroNoiseRootPSD() / sqrtTimeInterval; final GaussianRandomizer errorRandomizer = new GaussianRandomizer( random, 0.0, angularRateStandardDeviation); final List<StandardDeviationFrameBodyKinematics> measurements = new ArrayList<>(); final double[] qualityScores = new double[MEASUREMENT_NUMBER]; double error; for (int i = 0; i < MEASUREMENT_NUMBER; i++) { final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final CoordinateTransformation nedC = new CoordinateTransformation( roll, pitch, yaw, FrameType.BODY_FRAME, FrameType.LOCAL_NAVIGATION_FRAME); final NEDFrame nedFrame = new NEDFrame(nedPosition, nedC); final ECEFFrame ecefFrame = NEDtoECEFFrameConverter .convertNEDtoECEFAndReturnNew(nedFrame); // compute ground-truth kinematics that should be generated at provided // position, velocity and orientation final BodyKinematics trueKinematics = ECEFKinematicsEstimator .estimateKinematicsAndReturnNew(TIME_INTERVAL_SECONDS, ecefFrame, ecefFrame); // apply known calibration parameters to distort ground-truth and generate a // measured kinematics sample final BodyKinematics measuredKinematics; if (randomizer.nextInt(0, 100) < OUTLIER_PERCENTAGE) { // outlier measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errorsOutlier, random); error = Math.abs(errorRandomizer.nextDouble()); } else { // inlier measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errorsInlier, random); error = 0.0; } final StandardDeviationFrameBodyKinematics measurement = new StandardDeviationFrameBodyKinematics(measuredKinematics, ecefFrame, ecefFrame, TIME_INTERVAL_SECONDS, specificForceStandardDeviation, angularRateStandardDeviation); measurements.add(measurement); qualityScores[i] = 1.0 / (1.0 + error); } final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(qualityScores, measurements, false, this); calibrator.setThreshold(LARGE_THRESHOLD); // estimate reset(); assertTrue(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertEquals(mCalibrateStart, 0); assertEquals(mCalibrateEnd, 0); assertEquals(mCalibrateNextIteration, 0); assertEquals(mCalibrateProgressChange, 0); calibrator.calibrate(); // check assertTrue(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertEquals(mCalibrateStart, 1); assertEquals(mCalibrateEnd, 1); assertTrue(mCalibrateNextIteration > 0); assertTrue(mCalibrateProgressChange >= 0); final Matrix estimatedBg = calibrator.getEstimatedBiasesAsMatrix(); final Matrix estimatedMg = calibrator.getEstimatedMg(); final Matrix estimatedGg = calibrator.getEstimatedGg(); if (!bg.equals(estimatedBg, LARGE_ABSOLUTE_ERROR)) { continue; } if (!gg.equals(estimatedGg, LARGE_ABSOLUTE_ERROR)) { continue; } assertTrue(bg.equals(estimatedBg, LARGE_ABSOLUTE_ERROR)); assertNotNull(estimatedMg); assertTrue(gg.equals(estimatedGg, LARGE_ABSOLUTE_ERROR)); assertEstimatedResult(estimatedBg, estimatedMg, estimatedGg, calibrator, true); assertNotNull(calibrator.getEstimatedCovariance()); checkGeneralCovariance(calibrator.getEstimatedCovariance()); assertTrue(calibrator.getEstimatedMse() > 0.0); assertNotEquals(calibrator.getEstimatedChiSq(), 0.0); numValid++; break; } assertTrue(numValid > 0); } @Test public void testCalibrateCommonAxisWithInlierNoise() throws WrongSizeException, InvalidSourceAndDestinationFrameTypeException, LockedException, CalibrationException, NotReadyException { int numValid = 0; for (int t = 0; t < TIMES; t++) { final Matrix ba = generateBa(); final Matrix bg = generateBg(); final Matrix ma = generateMaCommonAxis(); final Matrix mg = generateMg(); final Matrix gg = generateGg(); final double accelNoiseRootPSD = getAccelNoiseRootPSD(); final double gyroNoiseRootPSD = getGyroNoiseRootPSD(); final double accelQuantLevel = 0.0; final double gyroQuantLevel = 0.0; final IMUErrors errorsOutlier = new IMUErrors(ba, bg, ma, mg, gg, OUTLIER_ERROR_FACTOR * accelNoiseRootPSD, OUTLIER_ERROR_FACTOR * gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final IMUErrors errorsInlier = new IMUErrors(ba, bg, ma, mg, gg, accelNoiseRootPSD, gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final Random random = new Random(); final UniformRandomizer randomizer = new UniformRandomizer(random); final double latitude = Math.toRadians( randomizer.nextDouble(MIN_LATITUDE_DEGREES, MAX_LATITUDE_DEGREES)); final double longitude = Math.toRadians( randomizer.nextDouble(MIN_LONGITUDE_DEGREES, MAX_LONGITUDE_DEGREES)); final double height = randomizer.nextDouble(MIN_HEIGHT, MAX_HEIGHT); final NEDPosition nedPosition = new NEDPosition(latitude, longitude, height); final double sqrtTimeInterval = Math.sqrt(TIME_INTERVAL_SECONDS); final double specificForceStandardDeviation = getAccelNoiseRootPSD() / sqrtTimeInterval; final double angularRateStandardDeviation = getGyroNoiseRootPSD() / sqrtTimeInterval; final GaussianRandomizer errorRandomizer = new GaussianRandomizer( random, 0.0, angularRateStandardDeviation); final List<StandardDeviationFrameBodyKinematics> measurements = new ArrayList<>(); final double[] qualityScores = new double[MEASUREMENT_NUMBER]; double error; for (int i = 0; i < MEASUREMENT_NUMBER; i++) { final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final CoordinateTransformation nedC = new CoordinateTransformation( roll, pitch, yaw, FrameType.BODY_FRAME, FrameType.LOCAL_NAVIGATION_FRAME); final NEDFrame nedFrame = new NEDFrame(nedPosition, nedC); final ECEFFrame ecefFrame = NEDtoECEFFrameConverter .convertNEDtoECEFAndReturnNew(nedFrame); // compute ground-truth kinematics that should be generated at provided // position, velocity and orientation final BodyKinematics trueKinematics = ECEFKinematicsEstimator .estimateKinematicsAndReturnNew(TIME_INTERVAL_SECONDS, ecefFrame, ecefFrame); // apply known calibration parameters to distort ground-truth and generate a // measured kinematics sample final BodyKinematics measuredKinematics; if (randomizer.nextInt(0, 100) < OUTLIER_PERCENTAGE) { // outlier measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errorsOutlier, random); error = Math.abs(errorRandomizer.nextDouble()); } else { // inlier measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errorsInlier, random); error = 0.0; } final StandardDeviationFrameBodyKinematics measurement = new StandardDeviationFrameBodyKinematics(measuredKinematics, ecefFrame, ecefFrame, TIME_INTERVAL_SECONDS, specificForceStandardDeviation, angularRateStandardDeviation); measurements.add(measurement); qualityScores[i] = 1.0 / (1.0 + error); } final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(qualityScores, measurements, true, this); calibrator.setThreshold(LARGE_THRESHOLD); // estimate reset(); assertTrue(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertEquals(mCalibrateStart, 0); assertEquals(mCalibrateEnd, 0); assertEquals(mCalibrateNextIteration, 0); assertEquals(mCalibrateProgressChange, 0); calibrator.calibrate(); // check assertTrue(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertEquals(mCalibrateStart, 1); assertEquals(mCalibrateEnd, 1); assertTrue(mCalibrateNextIteration > 0); assertTrue(mCalibrateProgressChange >= 0); final Matrix estimatedBg = calibrator.getEstimatedBiasesAsMatrix(); final Matrix estimatedMg = calibrator.getEstimatedMg(); final Matrix estimatedGg = calibrator.getEstimatedGg(); if (!bg.equals(estimatedBg, LARGE_ABSOLUTE_ERROR)) { continue; } if (!gg.equals(estimatedGg, LARGE_ABSOLUTE_ERROR)) { continue; } assertTrue(bg.equals(estimatedBg, LARGE_ABSOLUTE_ERROR)); assertNotNull(estimatedMg); assertTrue(gg.equals(estimatedGg, LARGE_ABSOLUTE_ERROR)); assertEstimatedResult(estimatedBg, estimatedMg, estimatedGg, calibrator, true); assertNotNull(calibrator.getEstimatedCovariance()); checkCommonAxisCovariance(calibrator.getEstimatedCovariance()); assertTrue(calibrator.getEstimatedMse() > 0.0); assertNotEquals(calibrator.getEstimatedChiSq(), 0.0); numValid++; break; } assertTrue(numValid > 0); } @Test public void testCalibrateGeneralNoRefinement() throws WrongSizeException, InvalidSourceAndDestinationFrameTypeException, LockedException, CalibrationException, NotReadyException { int numValid = 0; for (int t = 0; t < TIMES; t++) { final Matrix ba = generateBa(); final Matrix bg = generateBg(); final Matrix ma = generateMaGeneral(); final Matrix mg = generateMg(); final Matrix gg = generateGg(); final double accelNoiseRootPSD = getAccelNoiseRootPSD(); final double gyroNoiseRootPSD = getGyroNoiseRootPSD(); final double accelQuantLevel = 0.0; final double gyroQuantLevel = 0.0; final IMUErrors errorsOutlier = new IMUErrors(ba, bg, ma, mg, gg, accelNoiseRootPSD, gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final IMUErrors errorsInlier = new IMUErrors(ba, bg, ma, mg, gg, 0.0, 0.0, accelQuantLevel, gyroQuantLevel); final Random random = new Random(); final UniformRandomizer randomizer = new UniformRandomizer(random); final double latitude = Math.toRadians( randomizer.nextDouble(MIN_LATITUDE_DEGREES, MAX_LATITUDE_DEGREES)); final double longitude = Math.toRadians( randomizer.nextDouble(MIN_LONGITUDE_DEGREES, MAX_LONGITUDE_DEGREES)); final double height = randomizer.nextDouble(MIN_HEIGHT, MAX_HEIGHT); final NEDPosition nedPosition = new NEDPosition(latitude, longitude, height); final double sqrtTimeInterval = Math.sqrt(TIME_INTERVAL_SECONDS); final double specificForceStandardDeviation = getAccelNoiseRootPSD() / sqrtTimeInterval; final double angularRateStandardDeviation = getGyroNoiseRootPSD() / sqrtTimeInterval; final GaussianRandomizer errorRandomizer = new GaussianRandomizer( random, 0.0, angularRateStandardDeviation); final List<StandardDeviationFrameBodyKinematics> measurements = new ArrayList<>(); final double[] qualityScores = new double[MEASUREMENT_NUMBER]; double error; for (int i = 0; i < MEASUREMENT_NUMBER; i++) { final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final CoordinateTransformation nedC = new CoordinateTransformation( roll, pitch, yaw, FrameType.BODY_FRAME, FrameType.LOCAL_NAVIGATION_FRAME); final NEDFrame nedFrame = new NEDFrame(nedPosition, nedC); final ECEFFrame ecefFrame = NEDtoECEFFrameConverter .convertNEDtoECEFAndReturnNew(nedFrame); // compute ground-truth kinematics that should be generated at provided // position, velocity and orientation final BodyKinematics trueKinematics = ECEFKinematicsEstimator .estimateKinematicsAndReturnNew(TIME_INTERVAL_SECONDS, ecefFrame, ecefFrame); // apply known calibration parameters to distort ground-truth and generate a // measured kinematics sample final BodyKinematics measuredKinematics; if (randomizer.nextInt(0, 100) < OUTLIER_PERCENTAGE) { // outlier measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errorsOutlier, random); error = Math.abs(errorRandomizer.nextDouble()); } else { // inlier measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errorsInlier, random); error = 0.0; } final StandardDeviationFrameBodyKinematics measurement = new StandardDeviationFrameBodyKinematics(measuredKinematics, ecefFrame, ecefFrame, TIME_INTERVAL_SECONDS, specificForceStandardDeviation, angularRateStandardDeviation); measurements.add(measurement); qualityScores[i] = 1.0 / (1.0 + error); } final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(qualityScores, measurements, false, this); calibrator.setThreshold(THRESHOLD); calibrator.setResultRefined(false); calibrator.setPreliminarySolutionRefined(false); // estimate reset(); assertTrue(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertEquals(mCalibrateStart, 0); assertEquals(mCalibrateEnd, 0); assertEquals(mCalibrateNextIteration, 0); assertEquals(mCalibrateProgressChange, 0); calibrator.calibrate(); // check assertTrue(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertEquals(mCalibrateStart, 1); assertEquals(mCalibrateEnd, 1); assertTrue(mCalibrateNextIteration > 0); assertTrue(mCalibrateProgressChange >= 0); final Matrix estimatedBg = calibrator.getEstimatedBiasesAsMatrix(); final Matrix estimatedMg = calibrator.getEstimatedMg(); final Matrix estimatedGg = calibrator.getEstimatedGg(); if (!bg.equals(estimatedBg, LARGE_ABSOLUTE_ERROR)) { continue; } if (!gg.equals(estimatedGg, LARGE_ABSOLUTE_ERROR)) { continue; } assertTrue(bg.equals(estimatedBg, LARGE_ABSOLUTE_ERROR)); assertNotNull(estimatedMg); assertTrue(gg.equals(estimatedGg, LARGE_ABSOLUTE_ERROR)); assertEstimatedResult(estimatedBg, estimatedMg, estimatedGg, calibrator, false); assertNull(calibrator.getEstimatedCovariance()); assertEquals(calibrator.getEstimatedMse(), 0.0, 0.0); assertEquals(calibrator.getEstimatedChiSq(), 0.0, 0.0); numValid++; break; } assertTrue(numValid > 0); } @Test public void testCalibrateGeneralNonLinearWithInitialValue() throws WrongSizeException, InvalidSourceAndDestinationFrameTypeException, LockedException, CalibrationException, NotReadyException { int numValid = 0; for (int t = 0; t < TIMES; t++) { final Matrix ba = generateBa(); final Matrix bg = generateBg(); final Matrix ma = generateMaGeneral(); final Matrix mg = generateMg(); final Matrix gg = generateGg(); final double accelNoiseRootPSD = getAccelNoiseRootPSD(); final double gyroNoiseRootPSD = getGyroNoiseRootPSD(); final double accelQuantLevel = 0.0; final double gyroQuantLevel = 0.0; final IMUErrors errorsOutlier = new IMUErrors(ba, bg, ma, mg, gg, accelNoiseRootPSD, gyroNoiseRootPSD, accelQuantLevel, gyroQuantLevel); final IMUErrors errorsInlier = new IMUErrors(ba, bg, ma, mg, gg, 0.0, 0.0, accelQuantLevel, gyroQuantLevel); final Random random = new Random(); final UniformRandomizer randomizer = new UniformRandomizer(random); final double latitude = Math.toRadians( randomizer.nextDouble(MIN_LATITUDE_DEGREES, MAX_LATITUDE_DEGREES)); final double longitude = Math.toRadians( randomizer.nextDouble(MIN_LONGITUDE_DEGREES, MAX_LONGITUDE_DEGREES)); final double height = randomizer.nextDouble(MIN_HEIGHT, MAX_HEIGHT); final NEDPosition nedPosition = new NEDPosition(latitude, longitude, height); final double sqrtTimeInterval = Math.sqrt(TIME_INTERVAL_SECONDS); final double specificForceStandardDeviation = getAccelNoiseRootPSD() / sqrtTimeInterval; final double angularRateStandardDeviation = getGyroNoiseRootPSD() / sqrtTimeInterval; final GaussianRandomizer errorRandomizer = new GaussianRandomizer( random, 0.0, angularRateStandardDeviation); final List<StandardDeviationFrameBodyKinematics> measurements = new ArrayList<>(); final double[] qualityScores = new double[MEASUREMENT_NUMBER]; double error; for (int i = 0; i < MEASUREMENT_NUMBER; i++) { final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final CoordinateTransformation nedC = new CoordinateTransformation( roll, pitch, yaw, FrameType.BODY_FRAME, FrameType.LOCAL_NAVIGATION_FRAME); final NEDFrame nedFrame = new NEDFrame(nedPosition, nedC); final ECEFFrame ecefFrame = NEDtoECEFFrameConverter .convertNEDtoECEFAndReturnNew(nedFrame); // compute ground-truth kinematics that should be generated at provided // position, velocity and orientation final BodyKinematics trueKinematics = ECEFKinematicsEstimator .estimateKinematicsAndReturnNew(TIME_INTERVAL_SECONDS, ecefFrame, ecefFrame); // apply known calibration parameters to distort ground-truth and generate a // measured kinematics sample final BodyKinematics measuredKinematics; if (randomizer.nextInt(0, 100) < OUTLIER_PERCENTAGE) { // outlier measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errorsOutlier, random); error = Math.abs(errorRandomizer.nextDouble()); } else { // inlier measuredKinematics = BodyKinematicsGenerator .generate(TIME_INTERVAL_SECONDS, trueKinematics, errorsInlier, random); error = 0.0; } final StandardDeviationFrameBodyKinematics measurement = new StandardDeviationFrameBodyKinematics(measuredKinematics, ecefFrame, ecefFrame, TIME_INTERVAL_SECONDS, specificForceStandardDeviation, angularRateStandardDeviation); measurements.add(measurement); qualityScores[i] = 1.0 / (1.0 + error); } final PROSACRobustKnownFrameGyroscopeCalibrator calibrator = new PROSACRobustKnownFrameGyroscopeCalibrator(qualityScores, measurements, false, this); calibrator.setThreshold(THRESHOLD); calibrator.setInitialBias(bg); calibrator.setInitialMg(mg); calibrator.setInitialGg(gg); calibrator.setLinearCalibratorUsed(false); // estimate reset(); assertTrue(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertEquals(mCalibrateStart, 0); assertEquals(mCalibrateEnd, 0); assertEquals(mCalibrateNextIteration, 0); assertEquals(mCalibrateProgressChange, 0); calibrator.calibrate(); // check assertTrue(calibrator.isReady()); assertFalse(calibrator.isRunning()); assertEquals(mCalibrateStart, 1); assertEquals(mCalibrateEnd, 1); assertTrue(mCalibrateNextIteration > 0); assertTrue(mCalibrateProgressChange >= 0); final Matrix estimatedBg = calibrator.getEstimatedBiasesAsMatrix(); final Matrix estimatedMg = calibrator.getEstimatedMg(); final Matrix estimatedGg = calibrator.getEstimatedGg(); if (!bg.equals(estimatedBg, LARGE_ABSOLUTE_ERROR)) { continue; } if (!gg.equals(estimatedGg, LARGE_ABSOLUTE_ERROR)) { continue; } assertTrue(bg.equals(estimatedBg, LARGE_ABSOLUTE_ERROR)); assertNotNull(estimatedMg); assertTrue(gg.equals(estimatedGg, LARGE_ABSOLUTE_ERROR)); assertEstimatedResult(estimatedBg, estimatedMg, estimatedGg, calibrator, true); assertNotNull(calibrator.getEstimatedCovariance()); checkGeneralCovariance(calibrator.getEstimatedCovariance()); assertTrue(calibrator.getEstimatedMse() > 0.0); assertNotEquals(calibrator.getEstimatedChiSq(), 0.0); numValid++; break; } assertTrue(numValid > 0); } @Override public void onCalibrateStart(final RobustKnownFrameGyroscopeCalibrator calibrator) { checkLocked((PROSACRobustKnownFrameGyroscopeCalibrator) calibrator); mCalibrateStart++; } @Override public void onCalibrateEnd(final RobustKnownFrameGyroscopeCalibrator calibrator) { checkLocked((PROSACRobustKnownFrameGyroscopeCalibrator) calibrator); mCalibrateEnd++; } @Override public void onCalibrateNextIteration( final RobustKnownFrameGyroscopeCalibrator calibrator, final int iteration) { checkLocked((PROSACRobustKnownFrameGyroscopeCalibrator) calibrator); mCalibrateNextIteration++; } @Override public void onCalibrateProgressChange( final RobustKnownFrameGyroscopeCalibrator calibrator, final float progress) { checkLocked((PROSACRobustKnownFrameGyroscopeCalibrator) calibrator); mCalibrateProgressChange++; } private void reset() { mCalibrateStart = 0; mCalibrateEnd = 0; mCalibrateNextIteration = 0; mCalibrateProgressChange = 0; } private void checkLocked(final PROSACRobustKnownFrameGyroscopeCalibrator calibrator) { assertTrue(calibrator.isRunning()); try { calibrator.setInitialBiasX(0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialBiasY(0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialBiasZ(0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialBiasX(null); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialBiasY(null); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialBiasZ(null); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialBias(0.0, 0.0, 0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialBias(null, null, null); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialBias((AngularSpeedTriad) null); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialSx(0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialSy(0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialSz(0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialMxy(0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialMxz(0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialMyx(0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialMyz(0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialMzx(0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialMzy(0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialScalingFactors(0.0, 0.0, 0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialCrossCouplingErrors( 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialScalingFactorsAndCrossCouplingErrors( 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialBias((double[]) null); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialBias((Matrix) null); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialMg(null); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setInitialGg(null); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setMeasurements(null); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setCommonAxisUsed(true); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setListener(this); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setLinearCalibratorUsed(true); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setPreliminarySolutionRefined(true); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setProgressDelta(0.5f); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setConfidence(0.5); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setMaxIterations(500); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setResultRefined(true); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setCovarianceKept(true); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setPreliminarySubsetSize(5); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.calibrate(); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } catch (final Exception e) { fail("LockedException expected but not thrown"); } try { calibrator.setThreshold(0.1); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setQualityScores(null); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setComputeAndKeepInliersEnabled(true); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } try { calibrator.setComputeAndKeepResidualsEnabled(true); fail("LockedException expected but not thrown"); } catch (final LockedException ignore) { } } private void assertEstimatedResult( final Matrix bg, final Matrix mg, final Matrix gg, final PROSACRobustKnownFrameGyroscopeCalibrator calibrator, final boolean checkCovariance) throws WrongSizeException { final double[] estimatedBiases = calibrator.getEstimatedBiases(); assertArrayEquals(bg.getBuffer(), estimatedBiases, 0.0); final double[] estimatedBiases2 = new double[3]; calibrator.getEstimatedBiases(estimatedBiases2); assertArrayEquals(estimatedBiases, estimatedBiases2, 0.0); final Matrix bg2 = new Matrix(3, 1); calibrator.getEstimatedBiasesAsMatrix(bg2); assertEquals(bg, bg2); assertEquals(bg.getElementAtIndex(0), calibrator.getEstimatedBiasX(), 0.0); assertEquals(bg.getElementAtIndex(1), calibrator.getEstimatedBiasY(), 0.0); assertEquals(bg.getElementAtIndex(2), calibrator.getEstimatedBiasZ(), 0.0); final AngularSpeed bgx1 = calibrator.getEstimatedBiasAngularSpeedX(); final AngularSpeed bgx2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getEstimatedBiasAngularSpeedX(bgx2); assertEquals(bgx1, bgx2); assertEquals(calibrator.getEstimatedBiasX(), bgx1.getValue().doubleValue(), 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, bgx1.getUnit()); final AngularSpeed bgy1 = calibrator.getEstimatedBiasAngularSpeedY(); final AngularSpeed bgy2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getEstimatedBiasAngularSpeedY(bgy2); assertEquals(bgy1, bgy2); assertEquals(calibrator.getEstimatedBiasY(), bgy1.getValue().doubleValue(), 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, bgy1.getUnit()); final AngularSpeed bgz1 = calibrator.getEstimatedBiasAngularSpeedZ(); final AngularSpeed bgz2 = new AngularSpeed(0.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getEstimatedBiasAngularSpeedZ(bgz2); assertEquals(bgz1, bgz2); assertEquals(calibrator.getEstimatedBiasZ(), bgz1.getValue().doubleValue(), 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, bgz1.getUnit()); assertEquals(mg.getElementAt(0, 0), calibrator.getEstimatedSx(), 0.0); assertEquals(mg.getElementAt(1, 1), calibrator.getEstimatedSy(), 0.0); assertEquals(mg.getElementAt(2, 2), calibrator.getEstimatedSz(), 0.0); assertEquals(mg.getElementAt(0, 1), calibrator.getEstimatedMxy(), 0.0); assertEquals(mg.getElementAt(0, 2), calibrator.getEstimatedMxz(), 0.0); assertEquals(mg.getElementAt(1, 0), calibrator.getEstimatedMyx(), 0.0); assertEquals(mg.getElementAt(1, 2), calibrator.getEstimatedMyz(), 0.0); assertEquals(mg.getElementAt(2, 0), calibrator.getEstimatedMzx(), 0.0); assertEquals(mg.getElementAt(2, 1), calibrator.getEstimatedMzy(), 0.0); assertEquals(gg, calibrator.getEstimatedGg()); if (checkCovariance) { assertCovariance(calibrator); } } private void assertCovariance( final PROSACRobustKnownFrameGyroscopeCalibrator calibrator) { assertNotNull(calibrator.getEstimatedBiasXVariance()); assertNotNull(calibrator.getEstimatedBiasXVariance()); assertNotNull(calibrator.getEstimatedBiasXStandardDeviation()); final AngularSpeed stdBx1 = calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(); assertNotNull(stdBx1); final AngularSpeed stdBx2 = new AngularSpeed(1.0, AngularSpeedUnit.RADIANS_PER_SECOND); assertTrue(calibrator.getEstimatedBiasXStandardDeviationAsAngularSpeed(stdBx2)); assertEquals(stdBx1, stdBx2); assertNotNull(calibrator.getEstimatedBiasYVariance()); assertNotNull(calibrator.getEstimatedBiasYStandardDeviation()); final AngularSpeed stdBy1 = calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(); assertNotNull(stdBy1); final AngularSpeed stdBy2 = new AngularSpeed(1.0, AngularSpeedUnit.RADIANS_PER_SECOND); assertTrue(calibrator.getEstimatedBiasYStandardDeviationAsAngularSpeed(stdBy2)); assertEquals(stdBy1, stdBy2); assertNotNull(calibrator.getEstimatedBiasZVariance()); assertNotNull(calibrator.getEstimatedBiasZStandardDeviation()); final AngularSpeed stdBz1 = calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(); assertNotNull(stdBz1); final AngularSpeed stdBz2 = new AngularSpeed(1.0, AngularSpeedUnit.RADIANS_PER_SECOND); assertTrue(calibrator.getEstimatedBiasZStandardDeviationAsAngularSpeed(stdBz2)); assertEquals(stdBz1, stdBz2); final AngularSpeedTriad std1 = calibrator.getEstimatedBiasStandardDeviation(); assertEquals(calibrator.getEstimatedBiasXStandardDeviation(), std1.getValueX(), 0.0); assertEquals(calibrator.getEstimatedBiasYStandardDeviation(), std1.getValueY(), 0.0); assertEquals(calibrator.getEstimatedBiasZStandardDeviation(), std1.getValueZ(), 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, std1.getUnit()); final AngularSpeedTriad std2 = new AngularSpeedTriad(); calibrator.getEstimatedBiasStandardDeviation(std2); final double avgStd = (calibrator.getEstimatedBiasXStandardDeviation() + calibrator.getEstimatedBiasYStandardDeviation() + calibrator.getEstimatedBiasZStandardDeviation()) / 3.0; assertEquals(avgStd, calibrator.getEstimatedBiasStandardDeviationAverage(), 0.0); final AngularSpeed avg1 = calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(); assertEquals(avgStd, avg1.getValue().doubleValue(), 0.0); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, avg1.getUnit()); final AngularSpeed avg2 = new AngularSpeed(1.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getEstimatedBiasStandardDeviationAverageAsAngularSpeed(avg2); assertEquals(avg1, avg2); assertEquals(std1.getNorm(), calibrator.getEstimatedBiasStandardDeviationNorm(), ABSOLUTE_ERROR); final AngularSpeed norm1 = calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(); assertEquals(std1.getNorm(), norm1.getValue().doubleValue(), ABSOLUTE_ERROR); assertEquals(AngularSpeedUnit.RADIANS_PER_SECOND, norm1.getUnit()); final AngularSpeed norm2 = new AngularSpeed(1.0, AngularSpeedUnit.RADIANS_PER_SECOND); calibrator.getEstimatedBiasStandardDeviationNormAsAngularSpeed(norm2); assertEquals(norm1, norm2); } private void checkCommonAxisCovariance(final Matrix covariance) { assertEquals(covariance.getRows(), 21); assertEquals(covariance.getColumns(), 21); for (int j = 0; j < 18; j++) { final boolean colIsZero = j == 8 || j == 10 || j == 11; for (int i = 0; i < 18; i++) { final boolean rowIsZero = i == 8 || i == 10 || i == 11; if (colIsZero || rowIsZero) { assertEquals(covariance.getElementAt(i, j), 0.0, 0.0); } } } } private void checkGeneralCovariance(final Matrix covariance) { assertEquals(covariance.getRows(), 21); assertEquals(covariance.getColumns(), 21); for (int i = 0; i < 21; i++) { assertNotEquals(covariance.getElementAt(i, i), 0.0); } } 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 generateMaGeneral() 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 generateMaCommonAxis() throws WrongSizeException { final Matrix result = new Matrix(3, 3); result.fromArray(new double[]{ 500e-6, -300e-6, 200e-6, 0.0, -600e-6, 250e-6, 0.0, 0.0, 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; } private double getAccelNoiseRootPSD() { return 100.0 * MICRO_G_TO_METERS_PER_SECOND_SQUARED; } private double getGyroNoiseRootPSD() { return 0.01 * DEG_TO_RAD / 60.0; } }
50.475397
119
0.685326
ac3607a1ac8585587ff902d81a6c5214303e2471
666
package com.github.thiagogarbazza.expressionresolver.resolver.log; import lombok.NoArgsConstructor; import java.math.BigDecimal; import static com.github.thiagogarbazza.expressionresolver.resolver.NormalizeResult.normalizeResult; import static lombok.AccessLevel.PRIVATE; @NoArgsConstructor(access = PRIVATE) public class ResolverFunctionLog { private static final ResolverFunctionLog INSTANCE = new ResolverFunctionLog(); public BigDecimal resolver(BigDecimal value) { final double log = Math.log10(value.doubleValue()); return normalizeResult(log); } public static ResolverFunctionLog getResolverFunctionLog() { return INSTANCE; } }
25.615385
100
0.803303
d34f8edc20afea8af5bfc82a0e1ee9e82517b169
537
package br.com.elementalsource.mock.infra.property.impl; import br.com.elementalsource.mock.infra.property.FileProperty; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("FilePropertyModel") public class FilePropertyModel implements FileProperty { private final String fileBase; public FilePropertyModel(@Value("${file.base}") String fileBase) { this.fileBase = fileBase; } public String getFileBase() { return fileBase; } }
25.571429
70
0.756052
d681a96ad2de6c541739adf65142f980528118f8
272
package com.hs.basis; import lombok.extern.slf4j.Slf4j; import org.junit.Test; /** * TODO * * @Author heshang.ink * @Date 2019/9/6 10:31 */ @Slf4j public class StringDemo { @Test public void testFinal() { String s = "Hello"; s = "world"; log.info(s); } }
12.363636
33
0.632353
60eadce04e97d738b910265d128b0b6ba2b91864
1,048
package com.learn.ssm.chapter4.typehandler; import com.learn.ssm.chapter4.enumeration.SexEnum; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.TypeHandler; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class SexEnumTypeHandler implements TypeHandler<SexEnum> { @Override public void setParameter(PreparedStatement ps, int i, SexEnum parameter, JdbcType jdbcType) throws SQLException { ps.setInt(i, parameter.getId()); } @Override public SexEnum getResult(ResultSet rs, String columnName) throws SQLException { int id = rs.getInt(columnName); return SexEnum.getSexById(id); } @Override public SexEnum getResult(ResultSet rs, int columnIndex) throws SQLException { int id = rs.getInt(columnIndex); return SexEnum.getSexById(id); } @Override public SexEnum getResult(CallableStatement cs, int columnIndex) throws SQLException { int id = cs.getInt(columnIndex); return SexEnum.getSexById(id); } }
25.560976
80
0.776718
aa1d4d230a5ce7ec2d10e3ae74a627eec160fa49
5,603
/* * 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 focus; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import javafx.application.Platform; import javafx.scene.control.TextArea; import org.apache.commons.lang3.StringUtils; /* * * * @author rakesh */ /** * * @author rakesh */ public class Start_Crawling { TextArea progressText; static String host; public void start(TextArea jtf,TextArea pagesCounterText) throws IOException, ClassNotFoundException, SQLException{ progressText=jtf; String tp_regex,ip_regex,turl,iurl; ArrayList<String> entry_page_urls,index_urls,thread_urls; //host="https://community.mybb.com"; //HOST //turl="community.mybb.com/thread-209344.html"; //ThreadURL without schema //iurl="community.mybb.com/forum-176.html"; //IndexURL without shema /* host="http://forum.ucweb.com"; threadURL="http://forum.ucweb.com/forum.php?mod=viewthread&tid=1137449&extra=page%3D1"; indexURL="http://forum.ucweb.com/forum.php?mod=forumdisplay&fid=104"; */ /* host="https://fluxbb.org/forums/"; threadURL="fluxbb.org/forums/viewtopic.php?id=8856"; indexURL="fluxbb.org/forums/viewforum.php?id=1"; */ host=Config.entryURL; turl=Config.threadURL; iurl=Config.indexURL; turl=turl.substring(turl.indexOf("://")+3, turl.length()); iurl=iurl.substring(iurl.indexOf("://")+3, iurl.length()); System.out.println(turl); System.out.println(iurl); //Note : Do not add slash in the host URL //Note : regex only matches the path not the complete URL System.out.println("\n Host > "+host); Platform.runLater(() ->progressText.appendText("\nHost > "+host)); //url="forum.ucweb.com/forum.php?mod=viewthread&tid=1103035&extra=page%3D1"; //url="forum.statcounter.com/vb/showthread.php?t=35854";//www.discogs.com/forum/thread/403125"; System.out.println("\n Thread URL > "+turl); final String turl_final=turl; Platform.runLater(() ->progressText.appendText("\n\nThread URL > "+turl_final)); turl=turl.substring(turl.indexOf("/")+1, turl.length()); String[] str={turl}; //convert entryURL string to string array //generate regex Regex_Generate rj=new Regex_Generate(str); tp_regex=rj.generateRegex(str); // get the regex Platform.runLater(() ->progressText.appendText("\nGenerated Thread Page Regex > "+tp_regex)); System.out.println("4. Thread Regex > "+tp_regex); //Generate Regex For Index Pages System.out.println("5. Index URL > "+iurl); final String iurl_final=iurl; Platform.runLater(() ->progressText.appendText("\n\nIndex URL > "+iurl_final)); //Note : regex only matches the path not the complete URL iurl=iurl.substring(iurl.indexOf("/")+1, iurl.length()); String str1[]={iurl}; //convert entryURL string to string array //generate regex rj=new Regex_Generate(str1); ip_regex=rj.generateRegex(str1); // get the regex Platform.runLater(() ->progressText.appendText("\nGenerated Index Page Regex > "+ip_regex)); System.out.println("6. Index Regex > "+ip_regex); //Initialize filter class Filter filter_obj=new Filter(ip_regex,tp_regex); //pass regex to filter class // TEST IT **********//Crawl_URL entry_url_obj=new Crawl_URL(progressText,host,filter_obj,pagesCounterText); System.out.println("2. Entry Url > "+host); Platform.runLater(() ->progressText.appendText("\n\nEntry URL > "+host)); Crawl_EntryPage x=new Crawl_EntryPage(progressText,host,filter_obj,pagesCounterText);//http://forum.ucweb.com"); //Get Links (Paths Only) From Entry Page entry_page_urls=x.crawl_page(); //Filter URL's index_urls=filter_obj.filterIndexURL(entry_page_urls); thread_urls=filter_obj.filterThreadURL(entry_page_urls); Platform.runLater(() -> progressText.appendText("\n\nIndex URLS From Entry Page >"+index_urls.size()+index_urls.toString()+"\n")); System.out.println("7. Index URLS From Entry Page > "+index_urls.toString()); Platform.runLater(() -> progressText.appendText("\n\nThread URLS From Entry Page > "+thread_urls.size()+thread_urls.toString()+"\n")); System.out.println("8. Thread URLS From Entry Page > "+thread_urls.toString()); String entry_url_host=host; //Crawling sub index pages if(StringUtils.countMatches(host, "/")>2){ // remove baseline added while entry entryURL generation phase entry_url_host=host.substring(0,StringUtils.ordinalIndexOf(host, "/", 3)); } Platform.runLater(() -> progressText.appendText("\n\nStarting Crawling\n************************************************************")); Crawl_IndexPage crawli=new Crawl_IndexPage(filter_obj,progressText,entry_url_host,index_urls,thread_urls,ip_regex,tp_regex,pagesCounterText); crawli.crawl(); } }
35.238994
161
0.62056
4013c0e79374d61f359d9dedd970dd22ba60b52d
5,066
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. * under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|karaf operator|. name|jaas operator|. name|modules operator|. name|krb5 package|; end_package begin_import import|import name|java operator|. name|io operator|. name|File import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|PrintStream import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|directory operator|. name|api operator|. name|util operator|. name|Strings import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|directory operator|. name|server operator|. name|kerberos operator|. name|kdc operator|. name|AbstractKerberosITest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|directory operator|. name|shared operator|. name|kerberos operator|. name|codec operator|. name|types operator|. name|EncryptionType import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|directory operator|. name|shared operator|. name|kerberos operator|. name|crypto operator|. name|checksum operator|. name|ChecksumType import|; end_import begin_class specifier|public class|class name|KarafKerberosITest extends|extends name|AbstractKerberosITest block|{ specifier|protected name|String name|createKrb5Conf parameter_list|( name|ChecksumType name|checksumType parameter_list|, name|EncryptionType name|encryptionType parameter_list|, name|boolean name|isTcp parameter_list|) throws|throws name|IOException block|{ name|File name|file init|= name|folder operator|. name|newFile argument_list|( literal|"krb5.conf" argument_list|) decl_stmt|; name|PrintStream name|out init|= operator|new name|PrintStream argument_list|( name|file argument_list|) decl_stmt|; name|out operator|. name|println argument_list|( literal|"[libdefaults]" argument_list|) expr_stmt|; name|out operator|. name|println argument_list|( literal|"default_realm = " operator|+ name|REALM argument_list|) expr_stmt|; name|out operator|. name|println argument_list|( literal|"default_tkt_enctypes = " operator|+ name|encryptionType operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|out operator|. name|println argument_list|( literal|"default_tgs_enctypes = " operator|+ name|encryptionType operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|out operator|. name|println argument_list|( literal|"permitted_enctypes = " operator|+ name|encryptionType operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|out operator|. name|println argument_list|( literal|"default-checksum_type = " operator|+ name|checksumType operator|. name|getName argument_list|() argument_list|) expr_stmt|; if|if condition|( name|isTcp condition|) block|{ name|out operator|. name|println argument_list|( literal|"udp_preference_limit = 1" argument_list|) expr_stmt|; block|} name|out operator|. name|println argument_list|( literal|"[realms]" argument_list|) expr_stmt|; name|out operator|. name|println argument_list|( name|REALM operator|+ literal|" = {" argument_list|) expr_stmt|; name|out operator|. name|println argument_list|( literal|"kdc = " operator|+ name|HOSTNAME operator|+ literal|":" operator|+ name|kdcServer operator|. name|getTransports argument_list|() index|[ literal|0 index|] operator|. name|getPort argument_list|() argument_list|) expr_stmt|; name|out operator|. name|println argument_list|( literal|"}" argument_list|) expr_stmt|; name|out operator|. name|println argument_list|( literal|"[domain_realm]" argument_list|) expr_stmt|; name|out operator|. name|println argument_list|( literal|"." operator|+ name|Strings operator|. name|lowerCaseAscii argument_list|( name|REALM argument_list|) operator|+ literal|" = " operator|+ name|REALM argument_list|) expr_stmt|; name|out operator|. name|println argument_list|( name|Strings operator|. name|lowerCaseAscii argument_list|( name|REALM argument_list|) operator|+ literal|" = " operator|+ name|REALM argument_list|) expr_stmt|; name|out operator|. name|close argument_list|() expr_stmt|; return|return name|file operator|. name|getAbsolutePath argument_list|() return|; block|} block|} end_class end_unit
14.557471
602
0.786814
101ee19cccf0f71a1ac36122006149dd3a79969b
6,486
package com.github.leleact.jtest.apache.http.client.examples; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpClientConnection; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.conn.ConnectionRequest; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @Slf4j class ApacheHttpClientTest { @Test void test1() throws InterruptedException, ExecutionException, IOException { HttpClientContext context = HttpClientContext.create(); HttpClientConnectionManager connMrg = new BasicHttpClientConnectionManager(); HttpRoute route = new HttpRoute(new HttpHost("localhost", 80)); // Request new connection. This can be a long process ConnectionRequest connRequest = connMrg.requestConnection(route, null); // Wait for connection up to 10 sec HttpClientConnection conn = connRequest.get(10, TimeUnit.SECONDS); try { // If not open if (!conn.isOpen()) { // establish connection based on its route info connMrg.connect(conn, route, 1000, context); // and mark it as route complete connMrg.routeComplete(conn, route, context); } // Do useful things with the connection. } finally { connMrg.releaseConnection(conn, null, 1, TimeUnit.MINUTES); } } @Test void connPerRouteTest() { final String url = "http://localhost:8080/block"; // ้ป˜่ฎค็š„httpClientsๆœ€ๅคง20ไธช้“พๆŽฅ๏ผŒๅŒไธ€ไธชrouteๆœ€ๅคšๅŒๆ—ถ็”จ2ไธช final CloseableHttpClient httpclient = HttpClients.createDefault(); List<Thread> threadList = new ArrayList<>(); for (int i = 0; i < 10; i++) { Thread t = new Thread(new Runnable() { @Override public void run() { HttpPost httpPost = null; try { httpPost = new HttpPost(url); // ๅฆ‚ๆžœไธ่ฎพ็ฝฎrequestTimeOut๏ผŒๅฝ“httpClientๆฑ ไธญ็š„่ต„ๆบ็”จๅฎŒไน‹ๅŽ๏ผŒไผšไธ€็›ด็ญ‰ๅพ… @see MainClientExec.java:191 RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(60000).setSocketTimeout(60000).build(); httpPost.setConfig(requestConfig); httpPost.setHeader("content-type", "application/json"); httpPost.setEntity(new StringEntity("{\"name\":\"xxx\"}", StandardCharsets.UTF_8)); String response = httpclient.execute(httpPost, new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException { return EntityUtils.toString(httpResponse.getEntity()); } }); log.info("response: {}", response); } catch (IOException e) { log.info("ไธปๆœบ้€š่ฎฏๅผ‚ๅธธ", e); } finally { if (httpPost != null) { httpPost.releaseConnection(); } } } }); threadList.add(t); t.start(); } for (Thread t : threadList) { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } @Test void httpClientPostTest() { final PoolingHttpClientConnectionManager poolingmgr = new PoolingHttpClientConnectionManager(); poolingmgr.setMaxTotal(2); poolingmgr.setDefaultMaxPerRoute(2); RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout( 6000).setSocketTimeout(60000).build(); final CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager( poolingmgr).setDefaultRequestConfig(requestConfig).build(); Thread t = new Thread(new Runnable() { @Override public void run() { int times = 10; int i = 0; while (i++ < times) { log.info("======================็ฌฌ {} ๆฌก http่ฏทๆฑ‚ๅผ€ๅง‹ ============================", i); HttpPost post = new HttpPost("http://localhost:8080/hello"); post.setEntity(new StringEntity("world", StandardCharsets.UTF_8)); try { String response = httpclient.execute(post, new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException { return EntityUtils.toString(httpResponse.getEntity()); } }); } catch (IOException e) { log.warn(e.getMessage(), e); } log.info("======================็ฌฌ {} ๆฌก http่ฏทๆฑ‚็ป“ๆŸ ============================", i); try { Thread.sleep(30000L * i); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t.start(); try { t.join(); } catch (InterruptedException e) { log.info("", e); } } }
41.576923
169
0.567993
b9c0d4fac6a96f372e8633d66d02391eb9c95130
4,298
package com.rzspider.project.spider.spidertask.utils; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.JobBuilder; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.TriggerBuilder; import org.quartz.TriggerKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.rzspider.common.constant.ScheduleConstants; import com.rzspider.common.constant.project.SpiderConstant; import com.rzspider.project.spider.spidertask.domain.Spidertask; /** * ๅฎšๆ—ถไปปๅŠกๅทฅๅ…ท็ฑป * * @author ricozhou * */ public class SpiderScheduleUtils { private static final Logger log = LoggerFactory.getLogger(SpiderScheduleUtils.class); /** * ่Žทๅ–่งฆๅ‘ๅ™จkey */ public static TriggerKey getTriggerKey(Integer taskId) { return TriggerKey.triggerKey(SpiderConstant.JOB_NAME + taskId); } /** * ่Žทๅ–jobKey */ public static JobKey getJobKey(Integer taskId) { return JobKey.jobKey(SpiderConstant.JOB_NAME + taskId); } /** * ่Žทๅ–่กจ่พพๅผ่งฆๅ‘ๅ™จ */ public static CronTrigger getCronTrigger(Scheduler scheduler, Integer taskId) { try { return (CronTrigger) scheduler.getTrigger(getTriggerKey(taskId)); } catch (SchedulerException e) { log.error(e.getMessage()); } return null; } /** * ๅˆ›ๅปบๅฎšๆ—ถไปปๅŠก */ public static void createScheduleJob(Scheduler scheduler, Spidertask spidertask) { try { // ๆž„ๅปบjobไฟกๆฏ JobDetail jobDetail = JobBuilder.newJob(SpiderScheduleJob.class) .withIdentity(getJobKey(spidertask.getTaskId())).build(); // ่กจ่พพๅผ่ฐƒๅบฆๆž„ๅปบๅ™จ CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(spidertask.getCronExpression()); // ๆŒ‰ๆ–ฐ็š„cronExpression่กจ่พพๅผๆž„ๅปบไธ€ไธชๆ–ฐ็š„trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(spidertask.getTaskId())) .withSchedule(scheduleBuilder).build(); // ๆ”พๅ…ฅๅ‚ๆ•ฐ๏ผŒ่ฟ่กŒๆ—ถ็š„ๆ–นๆณ•ๅฏไปฅ่Žทๅ– jobDetail.getJobDataMap().put(ScheduleConstants.JOB_PARAM_KEY, spidertask); scheduler.scheduleJob(jobDetail, trigger); // ๆš‚ๅœไปปๅŠก if (spidertask.getJobStatus() == ScheduleConstants.Status.PAUSE.getValue()) { pauseJob(scheduler, spidertask.getTaskId()); } } catch (SchedulerException e) { log.error(e.getMessage()); } } /** * ๆ›ดๆ–ฐๅฎšๆ—ถไปปๅŠก */ public static void updateScheduleJob(Scheduler scheduler, Spidertask spidertask) { try { TriggerKey triggerKey = getTriggerKey(spidertask.getTaskId()); // ่กจ่พพๅผ่ฐƒๅบฆๆž„ๅปบๅ™จ CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(spidertask.getCronExpression()); CronTrigger trigger = getCronTrigger(scheduler, spidertask.getTaskId()); // ๆŒ‰ๆ–ฐ็š„cronExpression่กจ่พพๅผ้‡ๆ–ฐๆž„ๅปบtrigger // ๆ•ๆ‰ๅผ‚ๅธธ๏ผŒไธ‡ไธ€ๆญคไปปๅŠกๅทฒ็ป่ฟ่กŒ็ป“ๆŸๆฒกๆœ‰ไบ†cronไผšๆŠฅๅผ‚ๅธธ๏ผŒ้œ€่ฆๆ–ฐๅปบ try { trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); // ๅ‚ๆ•ฐ trigger.getJobDataMap().put(ScheduleConstants.JOB_PARAM_KEY, spidertask); scheduler.rescheduleJob(triggerKey, trigger); } catch (Exception e) { e.printStackTrace(); createScheduleJob(scheduler, spidertask); } // ๆš‚ๅœไปปๅŠก if (spidertask.getJobStatus() == ScheduleConstants.Status.PAUSE.getValue()) { pauseJob(scheduler, spidertask.getTaskId()); } } catch (Exception e) { log.error(e.getMessage()); } } /** * ็ซ‹ๅณๆ‰ง่กŒไปปๅŠก */ public static void run(Scheduler scheduler, Spidertask spidertask) { try { // ๅ‚ๆ•ฐ JobDataMap dataMap = new JobDataMap(); dataMap.put(ScheduleConstants.JOB_PARAM_KEY, spidertask); scheduler.triggerJob(getJobKey(spidertask.getTaskId()), dataMap); } catch (SchedulerException e) { log.error(e.getMessage()); } } /** * ๆš‚ๅœไปปๅŠก */ public static void pauseJob(Scheduler scheduler, Integer taskId) { try { scheduler.pauseJob(getJobKey(taskId)); } catch (SchedulerException e) { log.error(e.getMessage()); } } /** * ๆขๅคไปปๅŠก */ public static void resumeJob(Scheduler scheduler, Integer taskId) { try { scheduler.resumeJob(getJobKey(taskId)); } catch (SchedulerException e) { log.error(e.getMessage()); } } /** * ๅˆ ้™คๅฎšๆ—ถไปปๅŠก */ public static void deleteScheduleJob(Scheduler scheduler, Integer taskId) { try { scheduler.deleteJob(getJobKey(taskId)); } catch (SchedulerException e) { log.error(e.getMessage()); } } }
25.891566
106
0.73127
c3e2ab6fdd9ee56a7c6f4ef59b1dbaf5a559c2eb
622
package com.github.sys.model; import java.time.LocalDateTime; import lombok.Data; /** * link table is sec_menu * Copyright ยฉ 2019, github and/or its affiliates. All rights reserved. **/ @Data public class SecMenu { private Integer id; /**็ˆถ่œๅ•ID๏ผŒไธ€็บง่œๅ•ไธบ0*/ private Integer parentId; /**่œๅ•ๅ็งฐ*/ private String name; /**่œๅ•URL*/ private String url; /**็ฑปๅž‹ 0๏ผš็›ฎๅฝ• 1๏ผš่œๅ• 2๏ผšๆŒ‰้’ฎ*/ private Integer type; /**่œๅ•ๅ›พๆ ‡*/ private String icon; /**ๅค‡ๆณจ*/ private String mark; /**ๅˆ›ๅปบๆ—ถ้—ด*/ private LocalDateTime createTime; /**ๆ›ดๆ–ฐๆ—ถ้—ด*/ private LocalDateTime updateTime; }
16.810811
71
0.62701
af683c44e9b85b929bc3f893ee9d340bc68a1b4a
22,181
/* The following code was generated by JFlex 1.4.1 on 23/07/17 13:45 */ /* * 04/27/2010 * * TouistlTokenMaker.java - Scanner for Touistl. * * This library is distributed under a modified BSD license. See the included * RSyntaxTextArea.License.txt file for details. */ package gui.editionView.editor; import java.io.*; import javax.swing.text.Segment; import org.fife.ui.rsyntaxtextarea.*; /** * This class is a scanner generated by * <a href="http://www.jflex.de/">JFlex</a> 1.4.1 * on 23/07/17 13:45 from the specification file * <tt>Touistl.jflex</tt> */ public class TouistlTokenMaker extends AbstractJFlexCTokenMaker { /** This character denotes the end of file */ public static final int YYEOF = -1; /** initial size of the lookahead buffer */ private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ public static final int YYINITIAL = 0; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = "\11\0\1\3\1\10\1\0\1\3\23\0\1\3\1\42\2\0\1\6"+ "\3\0\1\46\1\46\1\41\1\41\1\41\1\41\1\5\1\41\12\1"+ "\1\41\1\7\1\44\1\43\1\45\1\6\1\0\1\2\1\40\21\2"+ "\1\37\6\2\1\41\1\47\1\41\1\0\1\4\1\0\1\12\1\24"+ "\1\34\1\11\1\17\1\15\1\25\1\16\1\14\2\2\1\21\1\30"+ "\1\20\1\26\1\31\1\35\1\27\1\22\1\13\1\33\1\2\1\23"+ "\1\36\1\32\1\2\uff85\0"; /** * Translates characters to character classes */ private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); /** * Translates DFA states to action switch labels. */ private static final int [] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = "\1\0\1\1\1\2\1\3\1\4\4\1\1\5\21\3"+ "\1\6\1\1\2\6\1\7\1\1\3\0\1\10\1\11"+ "\6\3\1\12\1\13\11\3\1\13\4\3\1\6\1\11"+ "\1\14\6\3\1\13\11\3\1\15\11\3"; private static int [] zzUnpackAction() { int [] result = new int[89]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int zzUnpackAction(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\50\0\120\0\170\0\240\0\310\0\360\0\u0118"+ "\0\u0140\0\50\0\u0168\0\u0190\0\u01b8\0\u01e0\0\u0208\0\u0230"+ "\0\u0258\0\u0280\0\u02a8\0\u02d0\0\u02f8\0\u0320\0\u0348\0\u0370"+ "\0\u0398\0\u03c0\0\u03e8\0\50\0\u0410\0\u0438\0\u0460\0\50"+ "\0\u0488\0\310\0\u04b0\0\u0118\0\u04d8\0\u0500\0\u0528\0\u0550"+ "\0\u0578\0\u05a0\0\u05c8\0\u05f0\0\170\0\u0618\0\u0640\0\u0668"+ "\0\u0690\0\u06b8\0\u06e0\0\u0708\0\u0730\0\u0758\0\u0780\0\170"+ "\0\u07a8\0\u07d0\0\u07f8\0\u0820\0\u0848\0\50\0\u04b0\0\u0870"+ "\0\u0898\0\u08c0\0\u08e8\0\u0910\0\u0938\0\u0960\0\u0988\0\u09b0"+ "\0\u09d8\0\u0a00\0\u0a28\0\u0a50\0\u0a78\0\u0aa0\0\u0ac8\0\170"+ "\0\u0af0\0\u0b18\0\u0b40\0\u0b68\0\u0b90\0\u0bb8\0\u0be0\0\u0c08"+ "\0\u0c30"; private static int [] zzUnpackRowMap() { int [] result = new int[89]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int zzUnpackRowMap(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int high = packed.charAt(i++) << 16; result[j++] = high | packed.charAt(i++); } return j; } /** * The transition table of the DFA */ private static final int [] ZZ_TRANS = zzUnpackTrans(); private static final String ZZ_TRANS_PACKED_0 = "\1\2\1\3\1\4\1\5\1\6\1\7\1\10\1\11"+ "\1\12\1\13\1\14\1\15\1\16\1\17\1\4\1\20"+ "\1\21\1\22\1\23\1\24\1\25\1\4\1\26\1\4"+ "\1\27\2\4\1\30\1\31\2\4\1\32\1\33\1\34"+ "\1\35\1\36\1\37\1\34\1\40\1\41\51\0\1\3"+ "\1\4\1\0\1\42\1\43\3\0\30\4\10\0\2\4"+ "\1\0\1\4\4\0\30\4\12\0\1\5\45\0\1\42"+ "\1\4\1\0\1\42\4\0\30\4\14\0\1\34\43\0"+ "\1\44\1\45\1\0\1\44\4\0\30\45\16\0\1\46"+ "\41\0\2\4\1\0\1\4\4\0\1\4\1\47\1\4"+ "\1\50\24\4\10\0\2\4\1\0\1\4\4\0\2\4"+ "\1\51\4\4\1\52\20\4\10\0\2\4\1\0\1\4"+ "\4\0\5\4\1\53\10\4\1\54\11\4\10\0\2\4"+ "\1\0\1\4\4\0\4\4\1\55\2\4\1\56\20\4"+ "\10\0\2\4\1\0\1\4\4\0\1\4\1\57\13\4"+ "\1\60\12\4\10\0\2\4\1\0\1\4\4\0\7\4"+ "\1\52\1\61\6\4\1\62\5\4\1\63\2\4\10\0"+ "\2\4\1\0\1\4\4\0\15\4\1\64\12\4\10\0"+ "\2\4\1\0\1\4\4\0\6\4\1\64\21\4\10\0"+ "\2\4\1\0\1\4\4\0\22\4\1\65\1\4\1\66"+ "\3\4\10\0\2\4\1\0\1\4\4\0\5\4\1\53"+ "\22\4\10\0\2\4\1\0\1\4\4\0\3\4\1\67"+ "\24\4\10\0\2\4\1\0\1\4\4\0\16\4\1\70"+ "\11\4\10\0\2\4\1\0\1\4\4\0\15\4\1\52"+ "\12\4\10\0\2\4\1\0\1\4\4\0\7\4\1\71"+ "\20\4\10\0\2\4\1\0\1\4\4\0\1\4\1\72"+ "\26\4\10\0\2\4\1\0\1\4\4\0\15\4\1\73"+ "\12\4\10\0\2\4\1\0\1\4\4\0\15\4\1\74"+ "\12\4\52\0\1\34\47\0\1\34\1\0\1\34\45\0"+ "\1\75\53\0\1\76\1\0\1\77\47\0\2\45\1\0"+ "\1\45\4\0\30\45\7\0\10\46\1\0\37\46\1\0"+ "\2\4\1\0\1\4\4\0\2\4\1\100\25\4\10\0"+ "\2\4\1\0\1\4\4\0\4\4\1\101\23\4\10\0"+ "\2\4\1\0\1\4\4\0\10\4\1\102\6\4\1\103"+ "\10\4\10\0\2\4\1\0\1\4\4\0\1\70\27\4"+ "\10\0\2\4\1\0\1\4\4\0\6\4\1\104\21\4"+ "\10\0\2\4\1\0\1\4\4\0\22\4\1\105\5\4"+ "\10\0\2\4\1\0\1\4\4\0\2\4\1\106\25\4"+ "\10\0\2\4\1\0\1\4\4\0\10\4\1\107\17\4"+ "\10\0\2\4\1\0\1\4\4\0\16\4\1\110\11\4"+ "\10\0\2\4\1\0\1\4\4\0\11\4\1\111\16\4"+ "\10\0\2\4\1\0\1\4\4\0\20\4\1\112\7\4"+ "\10\0\2\4\1\0\1\4\4\0\1\4\1\113\1\4"+ "\1\114\24\4\10\0\2\4\1\0\1\4\4\0\2\4"+ "\1\70\25\4\10\0\2\4\1\0\1\4\4\0\13\4"+ "\1\115\14\4\10\0\2\4\1\0\1\4\4\0\16\4"+ "\1\64\11\4\10\0\2\4\1\0\1\4\4\0\14\4"+ "\1\116\13\4\10\0\2\4\1\0\1\4\4\0\3\4"+ "\1\117\24\4\10\0\2\4\1\0\1\4\4\0\16\4"+ "\1\52\11\4\10\0\2\4\1\0\1\4\4\0\20\4"+ "\1\120\7\4\10\0\2\4\1\0\1\4\4\0\2\4"+ "\1\120\25\4\54\0\1\34\3\0\2\4\1\0\1\4"+ "\4\0\1\4\1\55\26\4\10\0\2\4\1\0\1\4"+ "\4\0\4\4\1\70\23\4\10\0\2\4\1\0\1\4"+ "\4\0\6\4\1\121\21\4\10\0\2\4\1\0\1\4"+ "\4\0\15\4\1\122\12\4\10\0\2\4\1\0\1\4"+ "\4\0\7\4\1\55\20\4\10\0\2\4\1\0\1\4"+ "\4\0\6\4\1\120\21\4\10\0\2\4\1\0\1\4"+ "\4\0\6\4\1\26\21\4\10\0\2\4\1\0\1\4"+ "\4\0\11\4\1\105\16\4\10\0\2\4\1\0\1\4"+ "\4\0\1\4\1\123\26\4\10\0\2\4\1\0\1\4"+ "\4\0\6\4\1\55\21\4\10\0\2\4\1\0\1\4"+ "\4\0\2\4\1\124\25\4\10\0\2\4\1\0\1\4"+ "\4\0\23\4\1\64\4\4\10\0\2\4\1\0\1\4"+ "\4\0\11\4\1\125\16\4\10\0\2\4\1\0\1\4"+ "\4\0\11\4\1\22\16\4\10\0\2\4\1\0\1\4"+ "\4\0\1\4\1\126\13\4\1\26\12\4\10\0\2\4"+ "\1\0\1\4\4\0\15\4\1\127\12\4\10\0\2\4"+ "\1\0\1\4\4\0\1\4\1\122\26\4\10\0\2\4"+ "\1\0\1\4\4\0\11\4\1\64\16\4\10\0\2\4"+ "\1\0\1\4\4\0\10\4\1\130\17\4\10\0\2\4"+ "\1\0\1\4\4\0\21\4\1\70\6\4\10\0\2\4"+ "\1\0\1\4\4\0\2\4\1\131\25\4\10\0\2\4"+ "\1\0\1\4\4\0\7\4\1\52\20\4\10\0\2\4"+ "\1\0\1\4\4\0\7\4\1\70\20\4\10\0\2\4"+ "\1\0\1\4\4\0\10\4\1\70\17\4\10\0\2\4"+ "\1\0\1\4\4\0\11\4\1\70\16\4\7\0"; private static int [] zzUnpackTrans() { int [] result = new int[3160]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; } private static int zzUnpackTrans(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); value--; do result[j++] = value; while (--count > 0); } return j; } /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; /** * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code> */ private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = "\1\0\1\11\7\1\1\11\21\1\1\11\3\1\1\11"+ "\1\1\3\0\31\1\1\11\33\1"; private static int [] zzUnpackAttribute() { int [] result = new int[89]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; } private static int zzUnpackAttribute(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** the input device */ private java.io.Reader zzReader; /** the current state of the DFA */ private int zzState; /** the current lexical state */ private int zzLexicalState = YYINITIAL; /** this buffer contains the current text to be matched and is the source of the yytext() string */ private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; /** the textposition at the last accepting state */ private int zzMarkedPos; /** the textposition at the last state to be included in yytext */ private int zzPushbackPos; /** the current text position in the buffer */ private int zzCurrentPos; /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** number of newlines encountered up to the start of the matched text */ private int yyline; /** the number of characters up to the start of the matched text */ private int yychar; /** * the number of characters from the last newline up to the start of the * matched text */ private int yycolumn; /** * zzAtBOL == true <=> the scanner is currently at the beginning of a line */ private boolean zzAtBOL = true; /** zzAtEOF == true <=> the scanner is at the EOF */ private boolean zzAtEOF; /* user code: */ /** * Constructor. This must be here because JFlex does not generate a * no-parameter constructor. */ public TouistlTokenMaker() { } /** * Adds the token specified to the current linked list of tokens. * * @param tokenType The token's type. * @see #addToken(int, int, int) */ private void addHyperlinkToken(int start, int end, int tokenType) { int so = start + offsetShift; addToken(zzBuffer, start,end, tokenType, so, true); } /** * Adds the token specified to the current linked list of tokens. * * @param tokenType The token's type. */ private void addToken(int tokenType) { addToken(zzStartRead, zzMarkedPos-1, tokenType); } /** * Adds the token specified to the current linked list of tokens. * * @param tokenType The token's type. * @see #addHyperlinkToken(int, int, int) */ private void addToken(int start, int end, int tokenType) { int so = start + offsetShift; addToken(zzBuffer, start,end, tokenType, so, false); } /** * Adds the token specified to the current linked list of tokens. * * @param array The character array. * @param start The starting offset in the array. * @param end The ending offset in the array. * @param tokenType The token's type. * @param startOffset The offset in the document at which this token * occurs. * @param hyperlink Whether this token is a hyperlink. */ @Override public void addToken(char[] array, int start, int end, int tokenType, int startOffset, boolean hyperlink) { super.addToken(array, start,end, tokenType, startOffset, hyperlink); zzStartRead = zzMarkedPos; } /** * {@inheritDoc} */ public String[] getLineCommentStartAndEnd(int languageIndex) { return new String[] { "//", null }; } /** * Returns the first token in the linked list of tokens generated * from <code>text</code>. This method must be implemented by * subclasses so they can correctly implement syntax highlighting. * * @param text The text from which to get tokens. * @param initialTokenType The token type we should start with. * @param startOffset The offset into the document at which * <code>text</code> starts. * @return The first <code>Token</code> in a linked list representing * the syntax highlighted text. */ public Token getTokenList(Segment text, int initialTokenType, int startOffset) { resetTokenList(); this.offsetShift = -text.offset + startOffset; // Start off in the proper state. int state = Token.NULL; switch (initialTokenType) { default: state = Token.NULL; } s = text; try { yyreset(zzReader); yybegin(state); return yylex(); } catch (IOException ioe) { ioe.printStackTrace(); return new TokenImpl(); } } /** * Refills the input buffer. * * @return <code>true</code> if EOF was reached, otherwise * <code>false</code>. */ private boolean zzRefill() { // Patched version to keep! return zzCurrentPos>=s.offset+s.count; } /** * Resets the scanner to read from a new input stream. * Does not close the old reader. * * All internal variables are reset, the old input stream * <b>cannot</b> be reused (internal buffer is discarded and lost). * Lexical state is set to <tt>YY_INITIAL</tt>. * * @param reader the new input stream */ public final void yyreset(java.io.Reader reader) { // Patched version to keep! // 's' has been updated. zzBuffer = s.array; /* * We replaced the line below with the two below it because zzRefill * no longer "refills" the buffer (since the way we do it, it's always * "full" the first time through, since it points to the segment's * array). So, we assign zzEndRead here. */ //zzStartRead = zzEndRead = s.offset; zzStartRead = s.offset; zzEndRead = zzStartRead + s.count - 1; zzCurrentPos = zzMarkedPos = zzPushbackPos = s.offset; zzLexicalState = YYINITIAL; zzReader = reader; zzAtBOL = true; zzAtEOF = false; } /** * Creates a new scanner * There is also a java.io.InputStream version of this constructor. * * @param in the java.io.Reader to read input from. */ public TouistlTokenMaker(java.io.Reader in) { this.zzReader = in; } /** * Creates a new scanner. * There is also java.io.Reader version of this constructor. * * @param in the java.io.Inputstream to read input from. */ public TouistlTokenMaker(java.io.InputStream in) { this(new java.io.InputStreamReader(in)); } /** * Unpacks the compressed character translation table. * * @param packed the packed character translation table * @return the unpacked character translation table */ private static char [] zzUnpackCMap(String packed) { char [] map = new char[0x10000]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ while (i < 128) { int count = packed.charAt(i++); char value = packed.charAt(i++); do map[j++] = value; while (--count > 0); } return map; } /** * Closes the input stream. */ public final void yyclose() throws java.io.IOException { zzAtEOF = true; /* indicate end of file */ zzEndRead = zzStartRead; /* invalidate buffer */ if (zzReader != null) zzReader.close(); } /** * Returns the current lexical state. */ public final int yystate() { return zzLexicalState; } /** * Enters a new lexical state * * @param newState the new lexical state */ public final void yybegin(int newState) { zzLexicalState = newState; } /** * Returns the text matched by the current regular expression. */ public final String yytext() { return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); } /** * Returns the character at position <tt>pos</tt> from the * matched text. * * It is equivalent to yytext().charAt(pos), but faster * * @param pos the position of the character to fetch. * A value from 0 to yylength()-1. * * @return the character at position pos */ public final char yycharat(int pos) { return zzBuffer[zzStartRead+pos]; } /** * Returns the length of the matched text region. */ public final int yylength() { return zzMarkedPos-zzStartRead; } /** * Reports an error that occured while scanning. * * In a wellformed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong * (e.g. a JFlex bug producing a faulty scanner etc.). * * Usual syntax/scanner level error handling should be done * in error fallback rules. * * @param errorCode the code of the errormessage to display */ private void zzScanError(int errorCode) { String message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (ArrayIndexOutOfBoundsException e) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); } /** * Pushes the specified amount of characters back into the input stream. * * They will be read again by then next call of the scanning method * * @param number the number of characters to be read again. * This number must not be greater than yylength()! */ public void yypushback(int number) { if ( number > yylength() ) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos -= number; } /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. * * @return the next token * @exception java.io.IOException if any I/O-Error occurs */ public org.fife.ui.rsyntaxtextarea.Token yylex() throws java.io.IOException { int zzInput; int zzAction; // cached fields: int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; char [] zzBufferL = zzBuffer; char [] zzCMapL = ZZ_CMAP; int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = zzLexicalState; zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) zzInput = zzBufferL[zzCurrentPosL++]; else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = YYEOF; break zzForAction; } else { zzInput = zzBufferL[zzCurrentPosL++]; } } int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; if (zzNext == -1) break zzForAction; zzState = zzNext; int zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; } } } // store back cached position zzMarkedPos = zzMarkedPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 10: { addToken(Token.RESERVED_WORD); } case 14: break; case 3: { addToken(Token.IDENTIFIER); } case 15: break; case 12: { addToken(Token.LITERAL_NUMBER_FLOAT); } case 16: break; case 11: { addToken(Token.FUNCTION); } case 17: break; case 4: { addToken(Token.WHITESPACE); } case 18: break; case 8: { addToken(Token.VARIABLE); } case 19: break; case 1: { addToken(Token.ERROR_IDENTIFIER); } case 20: break; case 6: { addToken(Token.OPERATOR); } case 21: break; case 2: { addToken(Token.LITERAL_NUMBER_DECIMAL_INT); } case 22: break; case 13: { addToken(Token.LITERAL_BOOLEAN); } case 23: break; case 9: { addToken(Token.COMMENT_MARKUP); } case 24: break; case 5: { addNullToken(); return firstToken; } case 25: break; case 7: { addToken(Token.SEPARATOR); } case 26: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; switch (zzLexicalState) { case YYINITIAL: { addNullToken(); return firstToken; } case 90: break; default: return null; } } else { zzScanError(ZZ_NO_MATCH); } } } } }
29.108924
82
0.590009
704eeb39461c2f950cf554798e6c5a6fa5906b69
984
package com.tencent.mm.a; import anet.channel.security.ISecurity; import java.security.MessageDigest; public final class a { public static final String c(byte[] bArr) { int i = 0; char[] cArr = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; try { MessageDigest instance = MessageDigest.getInstance(ISecurity.SIGN_ALGORITHM_MD5); instance.update(bArr); byte[] digest = instance.digest(); int length = digest.length; char[] cArr2 = new char[(length * 2)]; int i2 = 0; while (i < length) { byte b = digest[i]; int i3 = i2 + 1; cArr2[i2] = cArr[(b >>> 4) & 15]; i2 = i3 + 1; cArr2[i3] = cArr[b & 15]; i++; } return new String(cArr2); } catch (Exception e) { return null; } } }
31.741935
113
0.456301
4f7396e7f5777548d212e811a3272758c8f08a6d
6,250
// Copyright (c) 2003-present, Jodd Team (http://jodd.org) // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package jodd.servlet.upload; import jodd.core.JoddCore; import jodd.servlet.ServletUtil; import jodd.upload.FileUploadFactory; import jodd.upload.MultipartStreamParser; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.Enumeration; /** * Handles multi-part requests and extract uploaded files and parameters from * it. Multi-part forms should be defined as: * <p> * * <code> * &lt;form method="post" enctype="multipart/form-data" accept-charset="<i>charset</i>"... * </code> * * <p> * "accept-charset" may be used in case when jsp page uses specific * encoding. If default encoding is used, this attribute is not required. * * <p> * MultipleRequest class may be created in two ways:<br> * 1) with the constructors, when user must prevent instantiating more than once;<br> * 2) using static factory methods, which always return valid MultipleRequest instance. * * <p> * This class loads complete request. To prevent big uploads (and potential * DoS attacks) check content length <b>before</b> loading. */ public class MultipartRequest extends MultipartStreamParser { // ---------------------------------------------------------------- properties private HttpServletRequest request; private String characterEncoding; /** * Returns actual http servlet request instance. */ public HttpServletRequest getServletRequest() { return request; } /** * Returns request content length. Usually used before loading, to check the upload size. */ public int getContentLength() { return request.getContentLength(); } /** * Returns current encoding. */ public String getCharacterEncoding() { return characterEncoding; } // ---------------------------------------------------------------- constructors /** * Creates new multi-part request with form encoding and file upload factory. * After construction stream is <b>not</b> yet parsed! Use {@link #parseMultipartRequest()} or * {@link #parseRequest()} to parse before further usage. * * <p> * If not specified, character encoding is read from the request. If not specified there, * default Jodd encoding is used. * * <p> * Multiple instantiation doesn't work, since input stream can be parsed just once. * Still, if it is needed, use {@link #getInstance(javax.servlet.http.HttpServletRequest, FileUploadFactory, String)} * instead. * * @param request http request * @param encoding form encoding or <code>null</code> * @param fileUploadFactory file factory, or <code>null</code> for default factory */ public MultipartRequest(HttpServletRequest request, FileUploadFactory fileUploadFactory, String encoding) { super(fileUploadFactory); this.request = request; if (encoding != null) { this.characterEncoding = encoding; } else { this.characterEncoding = request.getCharacterEncoding(); } if (this.characterEncoding == null) { this.characterEncoding = JoddCore.encoding; } } // ---------------------------------------------------------------- factories private static final String MREQ_ATTR_NAME = MultipartRequest.class.getName(); /** * Returns new or existing instance of <code>MultipartRequest</code>. */ public static MultipartRequest getInstance(HttpServletRequest request, FileUploadFactory fileUploadFactory, String encoding) throws IOException { MultipartRequest mreq = (MultipartRequest) request.getAttribute(MREQ_ATTR_NAME); if (mreq == null) { mreq = new MultipartRequest(request, fileUploadFactory, encoding); request.setAttribute(MREQ_ATTR_NAME, mreq); } if (!mreq.isParsed()) { mreq.parseRequest(); } return mreq; } /** * Returns new or existing instance of <code>MultipartRequest</code>. */ public static MultipartRequest getInstance(HttpServletRequest request) throws IOException { return getInstance(request, null, null); } // ---------------------------------------------------------------- load /** * Loads and parse multi-part request. It <b>doesn't</b> check if request is multi-part. * Must be called on same request at most <b>once</b>. */ public void parseMultipartRequest() throws IOException { parseRequestStream(request.getInputStream(), characterEncoding); } /** * Checks if request if multi-part and parse it. If request is not multi-part it * copies all parameters, to make usage the same in both cases. * * @see MultipartRequestWrapper */ public void parseRequest() throws IOException { if (ServletUtil.isMultipartRequest(request)) { parseRequestStream(request.getInputStream(), characterEncoding); } else { Enumeration names = request.getParameterNames(); while (names.hasMoreElements()) { String paramName = (String) names.nextElement(); String[] values = request.getParameterValues(paramName); putParameters(paramName, values); } } } }
35.310734
146
0.71104
d90049f206d51a2f4e862173ae86fe57f57a5fb5
686
package com.parkinfo.request.parkService.serviceFlow; import com.parkinfo.enums.ServiceFlowImgType; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; @Data public class AddServiceFlowImgRequest { @ApiModelProperty(value = "id ็ผ–่พ‘ๆ—ถไผ ้€’") private String id; @ApiModelProperty(value = "ๆต็จ‹ๅ›พ็ฑปๅž‹",example = "DISCOUNT_POLICY,SETTLED_IN_APPLY,MEETING_RESERVE,COMPANY_REGISTER,LICENCE_HANDLE") @NotNull(message = "ๆต็จ‹ๅ›พ็ฑปๅž‹ไธ่ƒฝไธบ็ฉบ") private ServiceFlowImgType imgType; @ApiModelProperty(value = "ๆต็จ‹ๅ›พๅœฐๅ€") @NotBlank(message = "ๆต็จ‹ๅ›พๅœฐๅ€ไธ่ƒฝไธบ็ฉบ") private String path; }
29.826087
131
0.782799
094d8d95249c4930fb63537e0ca1aa3115edbad3
2,228
package com.IceMetalPunk.weatherworks; import java.util.Random; import cpw.mods.fml.common.IWorldGenerator; import net.minecraft.init.Blocks; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.feature.WorldGenMinable; public class WeatherGenerator implements IWorldGenerator { @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { int type=random.nextInt(6); int rX=0,rY=0,rZ=0; for (int tries=0; tries<10; ++tries) { if (type==0) { rX=random.nextInt(16); rY=random.nextInt(16); rZ=random.nextInt(16); WorldGenMinable veinGen=new WorldGenMinable(WeatherWorks.sunstoneOre, 0, 7, Blocks.stone); veinGen.generate(world, random, chunkX*16+rX, rY, chunkZ*16+rZ); } else if (type==1) { rX=random.nextInt(16); rY=random.nextInt(16); rZ=random.nextInt(16); WorldGenMinable veinGen=new WorldGenMinable(WeatherWorks.waterstoneOre, 0, 7, Blocks.stone); veinGen.generate(world, random, chunkX*16+rX, rY, chunkZ*16+rZ); } else if (type==2) { rX=random.nextInt(16); rY=random.nextInt(16); rZ=random.nextInt(16); WorldGenMinable veinGen=new WorldGenMinable(WeatherWorks.thunderstoneOre, 0, 7, Blocks.stone); veinGen.generate(world, random, chunkX*16+rX, rY, chunkZ*16+rZ); } else if (type==3) { rX=random.nextInt(16); rY=random.nextInt(16); rZ=random.nextInt(16); WorldGenMinable veinGen=new WorldGenMinable(WeatherWorks.cloudstoneOre, 0, 7, Blocks.stone); veinGen.generate(world, random, chunkX*16+rX, rY, chunkZ*16+rZ); } else if (type==4) { rX=random.nextInt(16); rY=random.nextInt(16); rZ=random.nextInt(16); WorldGenMinable veinGen=new WorldGenMinable(WeatherWorks.earthstoneOre, 0, 7, Blocks.stone); veinGen.generate(world, random, chunkX*16+rX, rY, chunkZ*16+rZ); } else { rX=random.nextInt(16); rY=random.nextInt(16); rZ=random.nextInt(16); WorldGenMinable veinGen=new WorldGenMinable(WeatherWorks.moonstoneOre, 0, 7, Blocks.stone); veinGen.generate(world, random, chunkX*16+rX, rY, chunkZ*16+rZ); } } } }
35.365079
136
0.710503
9fb726e35c4d42b004c7c2320f38be6c5b5f7e55
1,167
package seedu.address.model.card; import static java.util.Objects.requireNonNull; import static seedu.address.commons.util.AppUtil.checkArgument; /** * Represent an answer to a question. */ public class Answer { public static final String MESSAGE_ANSWER_CONSTRAINTS = "Answer must not be an empty string."; public final String value; /** * Constructs a {@code answer}. * * @param answer A answer. */ public Answer(String answer) { requireNonNull(answer); checkArgument(isValidAnswer(answer), MESSAGE_ANSWER_CONSTRAINTS); this.value = answer; } /** * Returns if a given string is a valid answer. */ public static boolean isValidAnswer(String test) { return !test.trim().equals(""); } @Override public String toString() { return value; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Answer && value.equals(((Answer) other).value)); } @Override public int hashCode() { return value.hashCode(); } }
24.3125
98
0.624679
121f41b7b10c52b87468f6d31645d96515982d00
1,195
package us.ihmc.exampleSimulations.harmonograph; import us.ihmc.graphicsDescription.yoGraphics.YoGraphicsListRegistry; import us.ihmc.simulationconstructionset.SimulationConstructionSet; public class HarmonographSimulation { private static final double simulateDT = 0.0002; private static final int recordFrequency = 100; public HarmonographSimulation() { YoGraphicsListRegistry yoGraphicsListRegistry = new YoGraphicsListRegistry(); HarmonographRobot robot = new HarmonographRobot(yoGraphicsListRegistry); SimulationConstructionSet simulationConstructionSet = new SimulationConstructionSet(robot); simulationConstructionSet.addYoGraphicsListRegistry(yoGraphicsListRegistry); simulationConstructionSet.setDT(simulateDT, recordFrequency); HarmonographPaperJPanel harmonographPaperJPanel = robot.getHarmonographPaperJPanel(); simulationConstructionSet.addExtraJpanel(harmonographPaperJPanel, "Harmonograph Paper", false); Thread thread = new Thread(simulationConstructionSet); thread.start(); } public static void main(String[] args) { new HarmonographSimulation(); } }
31.447368
101
0.772385
76e1f01579a1a4bcbe351a751e9b41b787991bf4
1,379
package io.basc.framework.aop.support; import io.basc.framework.aop.MethodInterceptor; import io.basc.framework.aop.ProxyInstanceTarget; import io.basc.framework.core.reflect.DefaultMethodInvoker; import io.basc.framework.core.reflect.MethodInvoker; import io.basc.framework.util.ArrayUtils; import java.lang.reflect.Method; import java.util.function.Supplier; public abstract class AbstractProxyMethodInvoker extends DefaultMethodInvoker implements MethodInterceptor { private static final long serialVersionUID = 1L; public AbstractProxyMethodInvoker(Supplier<?> instanceSupplier, Class<?> sourceClass, Method method) { super(instanceSupplier, sourceClass, method, false); } public Object intercept(MethodInvoker invoker, Object[] args) throws Throwable { if (ArrayUtils.isEmpty(args) && ProxyInstanceTarget.class.isAssignableFrom(getSourceClass()) && invoker.getMethod().getName().equals(ProxyInstanceTarget.PROXY_TARGET_METHOD_NAME)) { return getInstance(); } MethodInterceptor methodInterceptor = getMethodInterceptor(invoker); if (methodInterceptor == null) { return invoker.invoke(args); } return methodInterceptor.intercept(invoker, args); } protected abstract MethodInterceptor getMethodInterceptor(MethodInvoker invoker); @Override public Object invoke(Object... args) throws Throwable { return intercept(clone(), args); } }
34.475
108
0.79913
c52d760ca7d55a597c25b63d53a2e2517f5da908
6,297
package name.imatsko.tinyrenderer; import org.apache.log4j.Logger; /** * Created by rigel92 on 03.03.15. */ public class Canvas extends ImageBuffer { public static final Logger LOG=Logger.getLogger(Canvas.class); public static final int LEFT_TOP = 1; public static final int LEFT_BOTTOM = 2; private int coord_origin = LEFT_TOP; public Canvas(ImageBuffer imgBuf) { super(imgBuf); } public Canvas(int w, int h) { super(w, h); } public int getCoordinateOrigin() { return coord_origin; } public void setCoordinateOrigin(int coord_origin) { if(coord_origin != LEFT_TOP && coord_origin != LEFT_BOTTOM) { throw new IllegalArgumentException("Illegal coordinate origin"); } this.coord_origin = coord_origin; } @Override public void setPixel(int x, int y, Color color) { if(coord_origin == LEFT_TOP) { super.setPixel(x, y, color); } else if(coord_origin == LEFT_BOTTOM) { super.setPixel(x, height - 1 - y, color); } else { throw new IllegalArgumentException("Illegal coordinate origin"); } } @Override public int [] getPixel(int x, int y) { if(coord_origin == LEFT_TOP) { return super.getRawPixel(x, y); } else if(coord_origin == LEFT_BOTTOM) { return super.getRawPixel(x, height-1 - y); } else { throw new IllegalArgumentException("Illegal coordinate origin"); } } public void drawLine(int x1, int y1, int x2, int y2, Color color) { checkCoordinateBoundaries(x1, y1); checkCoordinateBoundaries(x2, y2); int deltaX = Math.abs(x1-x2); int deltaY = Math.abs(y1-y2); boolean steep = false; if (deltaX < deltaY) { int buf; buf = x1; x1 = y1; y1 = buf; buf = y2; y2 = x2; x2 = buf; steep = true; } if (x1 > x2) { int buf; buf = x1; x1 = x2; x2 = buf; buf = y1; y1 = y2; y2 = buf; } int dx = x2 - x1; int dy = Math.abs(y2 - y1); int error = dx / 2; // ะ—ะดะตััŒ ะธัะฟะพะปัŒะทัƒะตั‚ัั ะพะฟั‚ะธะผะธะทะฐั†ะธั ั ัƒะผะฝะพะถะตะฝะธะตะผ ะฝะฐ dx, ั‡ั‚ะพะฑั‹ ะธะทะฑะฐะฒะธั‚ัŒัั ะพั‚ ะปะธัˆะฝะธั… ะดั€ะพะฑะตะน int ystep = (y1 < y2) ? 1 : -1; // ะ’ั‹ะฑะธั€ะฐะตะผ ะฝะฐะฟั€ะฐะฒะปะตะฝะธะต ั€ะพัั‚ะฐ ะบะพะพั€ะดะธะฝะฐั‚ั‹ y int y = y1; for (int x = x1; x <= x2; x++) { setPixel(steep ? y : x, steep ? x : y, color); // ะะต ะทะฐะฑั‹ะฒะฐะตะผ ะฒะตั€ะฝัƒั‚ัŒ ะบะพะพั€ะดะธะฝะฐั‚ั‹ ะฝะฐ ะผะตัั‚ะพ error -= dy; if (error < 0) { y += ystep; error += dx; } } } public void drawTriangle(int x1, int y1, int x2, int y2, int x3, int y3, Color color) { int[] x_coord = {x1, x2, x3}; int[] y_coord = {y1, y2, y3}; int len = 3; for (int i = 0; i < len; i++) { for (int j = 0; j < len-1; j++) { if(y_coord[j] < y_coord[j+1]) { int bufy = y_coord[j]; y_coord[j] = y_coord[j+1]; y_coord[j+1] = bufy; int bufx = x_coord[j]; x_coord[j] = x_coord[j+1]; x_coord[j+1] = bufx; } } } y1 = y_coord[0]; y2 = y_coord[1]; y3 = y_coord[2]; x1 = x_coord[0]; x2 = x_coord[1]; x3 = x_coord[2]; int dx1 = Math.abs(x1 - x2); int dx2 = Math.abs(x1 - x3); int dy1 = y1 - y2; int dy2 = y1 - y3; int error1 = dy1/2; int error2 = dy2/2; int step_x1 = (x1 < x2) ? 1 : -1; int step_x2 = (x1 < x3) ? 1 : -1; int x_i1 = x1; int x_i2 = x1; if(dy1 == 0 || dy2 == 0) { x_i1 = x1; x_i2 = x2; } else { for (int y = y1; y > y2; y += -1) { error1 -= dx1; error2 -= dx2; while (error1 < 0) { x_i1 += step_x1; error1 += dy1; } while (error2 < 0) { x_i2 += step_x2; error2 += dy2; } if(step_x1 >= 0) { if(x_i1 > x2) x_i1 = x2; } else { if(x_i1 < x2) x_i1 = x2; } swipeLine(x_i1, x_i2, y, color); } } dx1 = Math.abs(x3 - x_i1); dx2 = Math.abs(x3 - x_i2); dy1 = y2 - y3; dy2 = y2 - y3; error1 = dy1/2; error2 = dy2/2; step_x1 = (x3 > x_i1) ? 1 : -1; step_x2 = (x3 > x_i2) ? 1 : -1; if(dy1 == 0 && dy2 == 0) { // swipeLine(x_i1, x_i2, y1, color); } else { for (int y = y2; y > y3; y += -1) { error1 -= dx1; error2 -= dx2; while (error1 < 0) { x_i1 += step_x1; error1 += dy1; } while (error2 < 0) { x_i2 += step_x2; error2 += dy2; } if(step_x1 >= 0) { if(x_i1 > x3) x_i1 = x3; } else { if(x_i1 < x3) x_i1 = x3; } if(step_x2 >= 0) { if(x_i2 > x3) x_i2 = x3; } else { if(x_i2 < x3) x_i2 = x3; } swipeLine(x_i1, x_i2, y, color); } } } private void swipeLine(int x1, int x2, int y, Color color) { if (x1 > x2) { int buf = x1; x1 = x2; x2 = buf; } for (int x_j = x1; x_j <= x2; x_j++) { try { setPixel(x_j, y, color); } catch (IndexOutOfBoundsException e) { // skip pixels out of image } } } }
24.597656
115
0.408925
48e751a1a7a2aacf4de5ebcab7f2037799cee696
1,842
package com.mon.host.controller; import cn.hutool.log.Log; import cn.hutool.log.LogFactory; import com.mon.host.common.enums.HostType; import com.mon.host.common.rest.RestResponse; import com.mon.host.dto.HostMonAgent; import com.mon.host.service.IHostMonitorService; import io.swagger.annotations.Api; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; /** * <p> * ไธปๆœบ็›‘ๆŽง ๅ‰็ซฏๆŽงๅˆถๅ™จ * </p> * * @author xt * @since 2018-8-31 */ @RestController @RequestMapping(value = "/api/", produces = MediaType.APPLICATION_JSON_VALUE) @Api(value = "HostMonitorController", description = "ไธปๆœบ็›‘ๆŽง", produces = MediaType.APPLICATION_JSON_VALUE) public class HostMonitorController { @Resource private IHostMonitorService networkMonitorService; private static final Log log = LogFactory.get(); /** * ๅพ—ๅˆฐไธปๆœบๅŠจๆ€ไฝฟ็”จ็އ็›‘ๆŽงๆ•ฐๆฎ * @param startMillSeconds ๅผ€ๅง‹ๆ—ถ้—ด * @param endMillSeconds ็ป“ๆŸๆ—ถ้—ด * @return * @throws Exception */ @RequestMapping(value = "/{type}/dynamic/{startMillSeconds}/{endMillSeconds}", method = RequestMethod.GET) @ResponseBody public RestResponse findNetWorkPayloadDynamic(@PathVariable String type, @PathVariable long startMillSeconds, @PathVariable long endMillSeconds) throws Exception { return RestResponse.success(networkMonitorService.findHostPayload(HostType.getHostType(type), startMillSeconds,endMillSeconds)); } @RequestMapping(value = "/{type}/{hostName}/info", method = RequestMethod.POST) @ResponseBody public RestResponse saveNetWorkPayload(@PathVariable String type ,@PathVariable String hostName, @RequestBody HostMonAgent agent) throws Exception { networkMonitorService.saveHostPayload(HostType.getHostType(type), agent); return RestResponse.success(); } }
34.754717
167
0.752986
de46191579a2ef4ec70c5e7ce62dcda6f2b590f9
373
public String XXX(String a, String b) { int p = Integer.parseInt(a, 2); int q = Integer.parseInt(b, 2); int sum = p ^ q; int carry = (p & q) << 1; while (carry != 0) { p = sum; q = carry; sum = p ^ q; carry = (p & q) << 1; } return Integer.toBinaryString(sum); }
24.866667
43
0.412869
8531734174b594d6731fbccde5e36e55e90b488b
1,587
package cn.istary.customview.widget; /* * CREATED BY: Sinry * TIME: 2019/4/2 23:00 * DESCRIPTION: ่‡ช็”ฑ่ฝไฝ“ */ import android.content.Context; import android.util.AttributeSet; import android.util.Log; import java.util.ArrayList; public class FreeFallBallView extends AbstractBallView { private static final String TAG = "FreeFallBallView"; public FreeFallBallView(Context context) { super(context); } public FreeFallBallView(Context context, AttributeSet attrs) { super(context, attrs); } public FreeFallBallView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void initBalls() { mBalls = new ArrayList<>(); Ball ball = new Ball.Builder() .setRadius(40) .setVY(0) .setVX(0) .setAY(1) .setY(-(mHeight >> 1)) .build(); mBalls.add(ball); } @Override protected void updateBall() { for (Ball ball : mBalls) { Log.d(TAG, "updateBall: speed = " + ball.getVY() + " y = " + ball.y); ball.y += ball.getVY(); if (ball.y > mHeight / 2) { ball.turnY(); ball.setColor(randomRGB()); continue; } if (ball.y < -(mHeight / 2)) { ball.turnY(); ball.setColor(randomRGB()); continue; } ball.setVY(ball.getVY() + ball.getAY()); } } }
23.338235
84
0.530561
b2319a483d91019f5ed602bd6c9f67ab163c84b4
2,396
package io.particle.android.sdk.cloud.models; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; /** * Required and optional user information used in sign up process. */ @ParametersAreNonnullByDefault public class SignUpInfo implements Parcelable { private String username, password; @SerializedName("grant_type") @Nullable private String grantType; @SerializedName("account_info") @Nullable private AccountInfo accountInfo; public SignUpInfo(String username, String password) { this.username = username; this.password = password; } public SignUpInfo(String username, String password, AccountInfo accountInfo) { this.username = username; this.password = password; this.accountInfo = accountInfo; } public String getUsername() { return username; } public String getPassword() { return password; } @Nullable public String getGrantType() { return grantType; } public void setGrantType(@Nullable String grantType) { this.grantType = grantType; } @Nullable public AccountInfo getAccountInfo() { return accountInfo; } public void setAccountInfo(@Nullable AccountInfo accountInfo) { this.accountInfo = accountInfo; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.username); dest.writeString(this.password); dest.writeString(this.grantType); dest.writeParcelable(this.accountInfo, flags); } protected SignUpInfo(Parcel in) { this.username = in.readString(); this.password = in.readString(); this.grantType = in.readString(); this.accountInfo = in.readParcelable(AccountInfo.class.getClassLoader()); } public static final Parcelable.Creator<SignUpInfo> CREATOR = new Parcelable.Creator<SignUpInfo>() { @Override public SignUpInfo createFromParcel(Parcel source) { return new SignUpInfo(source); } @Override public SignUpInfo[] newArray(int size) { return new SignUpInfo[size]; } }; }
26.043478
103
0.670701
0580c20c1b82ed94a254e830dc9643f796d37951
13,192
package com.CommonUtils.Utils.DynaticUtils.Services.Impls; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.cglib.beans.BeanMap; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Service; import com.CommonUtils.Utils.NetworkUtils.HttpUtils.HttpUtil; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.lang.TypeReference; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; @Service("beanUtilService") @Slf4j public final class BeanUtilServiceImpl implements ApplicationContextAware { private ApplicationContext applicationContext = null; private Binder binder = null; private static final String GET_BEAN_ERROR_DESC = "่Žทๅ–Beanๅผ‚ๅธธ๏ผŒๅผ‚ๅธธๅŽŸๅ› ไธบ๏ผš"; @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; this.binder = Binder.get(this.applicationContext.getEnvironment()); } /** * * bean่ฝฌmap๏ผŒ่ฏทไฝฟ็”จcn.hutool.core.bean.BeanUtil.beanToMap * @deprecated * */ @Deprecated(since="bean่ฝฌmap๏ผŒ่ฏทไฝฟ็”จcn.hutool.core.bean.BeanUtil.beanToMap") public static <T> Map<String, Object> beanToMap(final T bean, final boolean isGetAll) { if (isGetAll) { return com.CommonUtils.Utils.ReflectUtils.ReflectUtil.getBeanFieldValue(bean); } Map<String, Object> result = new HashMap<>(); if (null != bean) { BeanMap beanMap = BeanMap.create(bean); Iterator<Map.Entry<String, Object>> iter = Convert.convert(new TypeReference<Iterator<Map.Entry<String, Object>>>() {}, beanMap.entrySet().iterator()); while (iter.hasNext()) { Entry<String, Object> entry = iter.next(); result.put(entry.getKey() + "", entry.getValue()); } } return result; } /**map่ฝฌbean๏ผŒ่ฏทไฝฟ็”จcn.hutool.core.bean.BeanUtil.mapToBean * @deprecated * */ @Deprecated(since="map่ฝฌbean๏ผŒ่ฏทไฝฟ็”จcn.hutool.core.bean.BeanUtil.mapToBean") public static <T> T mapToBean(final Map<String, Object> map, final T bean) { BeanMap beanMap = BeanMap.create(bean); beanMap.putAll(map); return bean; } /** * List<T>่ฝฌๆขไธบList<Map<String,ย Object>>ย ๏ผŒ่ฏทไฝฟ็”จcn.hutool.core.bean.BeanUtil.beanToMap * @deprecated * */ @Deprecated(since="List<T>่ฝฌๆขไธบList<Map<String,ย Object>>ย ๏ผŒ่ฏทไฝฟ็”จcn.hutool.core.bean.BeanUtil.beanToMap") public static <T> List<Map<String, Object>> beanListToMapList(final List<T> objectList, final boolean isGetAll) { List<Map<String, Object>> result = new ArrayList<>(); if (null != objectList && !objectList.isEmpty()) { for (T bean : objectList) { Map<String, Object> map = beanToMap(bean, isGetAll); result.add(map); } } return result; } /**List<Map<String,Object>>่ฝฌๆขไธบList<T>ย ๏ผŒ่ฏทไฝฟ็”จcn.hutool.core.bean.BeanUtil.mapToBean * @deprecated * */ @Deprecated(since="List<Map<String,Object>>่ฝฌๆขไธบList<T>ย ๏ผŒ่ฏทไฝฟ็”จcn.hutool.core.bean.BeanUtil.mapToBean") public static <T> List<T> mapListToBeanList(final List<Map<String,Object>> mapList, final Class<T> clazz) throws InstantiationException, IllegalAccessException { List<T> result = new ArrayList<>(); if (null != mapList && !mapList.isEmpty()) { for (Map<String,Object> map : mapList) { T bean = clazz.newInstance(); mapToBean(map, bean); result.add(bean); } } return result; } public static <T, R> List<R> transfer(final Function<? super T, ? extends R> mapper, final Collection<T> beans) { if (!CollUtil.isEmpty(beans)) { return beans.stream().map(mapper).collect(Collectors.toList()); } else { return Collections.emptyList(); } } @SafeVarargs public static <T, R> List<R> transfer(final Function<? super T, ? extends R> mapper, final T ... beans) { if (!ArrayUtil.isEmpty(beans)) { return transfer(mapper, CollUtil.newArrayList(beans)); } else { return Collections.emptyList(); } } /** * Bean็›ธไบ’่ฝฌๅŒ–๏ผŒๅฆ‚DTOไธŽBEANๅฑžๆ€ง่ฝฌๅŒ–๏ผŒ้€‚็”จไบŽไธคไธชๅฎžไฝ“ๅฑžๆ€งๅญ—ๆฎตๅ‡ ไนŽๅฎŒๅ…จ็›ธๅŒ * */ public static boolean convertBySpring(final Object src, final Object dst, final String ... ignoreProperties) { try { BeanUtils.copyProperties(src, dst, ignoreProperties); return true; } catch (Exception ex) { log.error("Bean็›ธไบ’่ฝฌๅŒ–ๅคฑ่ดฅ๏ผŒๅผ‚ๅธธๅŽŸๅ› ไธบ๏ผš{}", ex); return false; } } /** * Bean็›ธไบ’่ฝฌๅŒ–๏ผŒๅฆ‚DTOไธŽBEANๅฑžๆ€ง่ฝฌๅŒ–๏ผŒ้€‚็”จไบŽไธคไธชๅฎžไฝ“ๅฑžๆ€งๅญ—ๆฎตๅชๆœ‰้ƒจๅˆ†ๅญ—ๆฎต็›ธๅŒ * */ public static boolean convertByJackson(final Object src, final Object dst) { try { //่ฏปๅ…ฅ้œ€่ฆๆ›ดๆ–ฐ็š„็›ฎๆ ‡ๅฎžไฝ“ ObjectReader objectReader = getInstanceForObjectMapper(Include.NON_DEFAULT).readerForUpdating(dst); //ๆญคไปฃ็ ๆŠŠๅฎžไฝ“่ฝฌๆขไธบjson๏ผŒไฝ†ๆ นๆฎInclude่ฟ›่กŒ่ฟ‡ๆปค String srcJson = getInstanceForObjectMapper(Include.NON_DEFAULT).writeValueAsString(src); //ๅฐ†ๆบๅฎžไฝ“็š„ๅ€ผ่ต‹ๅ€ผๅˆฐ็›ฎๆ ‡ๅฎžไฝ“ objectReader.readValue(srcJson); return true; } catch (Exception ex) { log.error("Bean็›ธไบ’่ฝฌๅŒ–ๅคฑ่ดฅ๏ผŒๅผ‚ๅธธๅŽŸๅ› ไธบ๏ผš{}", ex); return false; } } private static class ObjectMapperSingletonContainer { private static ObjectMapper instance = new ObjectMapper(); private static ObjectMapper setSerializationInclusion(final Include incl) { /* * ้€š่ฟ‡่ฏฅๆ–นๆณ•ๅฏนmapperๅฏน่ฑก่ฟ›่กŒ่ฎพ็ฝฎ * ๆ‰€ๆœ‰ๅบๅˆ—ๅŒ–็š„ๅฏน่ฑก้ƒฝๅฐ†ๆŒ‰็…ง่ง„ๅˆ™่ฟ›่กŒๅบๅˆ—ๅŒ– * Include.ALWAYS ้ป˜่ฎค * Include.NON_DEFAULT ๅฑžๆ€งไธบ้ป˜่ฎคๅ€ผ็š„ไธๅบๅˆ—ๅŒ– * Include.NON_EMPTY ๅฑžๆ€งไธบ็ฉบ๏ผˆ""๏ผ‰ๆˆ–่€…ไธบNULL้ƒฝไธๅบๅˆ—ๅŒ– * Include.NON_NULL ๅฑžๆ€งไธบNULLไธๅบๅˆ—ๅŒ– * */ instance.setSerializationInclusion(incl); return instance; } static { /* * ้…็ฝฎ่ฏฅobjectMapperๅœจๅๅบๅˆ—ๅŒ–ๆ—ถ๏ผŒๅฟฝ็•ฅ็›ฎๆ ‡ๅฏน่ฑกๆฒกๆœ‰็š„ๅฑžๆ€งใ€‚ * ๅ‡กๆ˜ฏไฝฟ็”จ่ฏฅobjectMapperๅๅบๅˆ—ๅŒ–ๆ—ถ๏ผŒ้ƒฝไผšๆ‹ฅๆœ‰่ฏฅ็‰นๆ€ง * */ instance.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } } private static ObjectMapper getInstanceForObjectMapper(final Include incl) { return ObjectMapperSingletonContainer.setSerializationInclusion(incl); } /** * ่Žทๅ–@Scope("session")็š„bean * @deprecated * */ @Deprecated(since="่Žทๅ–@Scope(\"session\")็š„bean") public static Object getBean(final boolean allowCreateSession, final String beanName) { return HttpUtil.getHttpSession(allowCreateSession).getAttribute(beanName); } public static Object getBean(final HttpServletRequest httpServletRequest, final boolean allowCreateSession, final String beanName) { return httpServletRequest.getSession(allowCreateSession).getAttribute(beanName); } /** * ๆณจๅ…ฅ@Scope("session")็š„bean * @deprecated * */ @Deprecated(since="ๆณจๅ…ฅ@Scope(\"session\")็š„bean") public static void setBean(final boolean allowCreateSession, final String beanName, final Serializable beanInstance) { HttpUtil.getHttpSession(allowCreateSession).setAttribute(beanName, beanInstance); } public static void setBean(final HttpServletRequest httpServletRequest, final boolean allowCreateSession, final String beanName, final Serializable beanInstance) { httpServletRequest.getSession(allowCreateSession).setAttribute(beanName, beanInstance); } public <T> Optional<T> getBean(final Class<T> clazz) { T result = null; try { result = this.applicationContext.getBean(clazz); } catch (Exception ex) { log.error(GET_BEAN_ERROR_DESC, ex); } return Optional.ofNullable(result); } public <T> Optional<T> getBean(final String name, final Class<T> clazz) { T result = null; try { result = this.applicationContext.getBean(name, clazz); } catch (Exception ex) { log.error(GET_BEAN_ERROR_DESC, ex); } return Optional.ofNullable(result); } public Optional<Object> getBean(final String name) { Object result = null; try { result = this.applicationContext.getBean(name); } catch (Exception ex) { log.error(GET_BEAN_ERROR_DESC, ex); } return Optional.ofNullable(result); } public <T> void addBean(final Class<T> beanClazz, final String beanName) { addBean(beanClazz, beanName, null, null); } public <T> void addBean(final Class<T> beanClazz, final String beanName, final String initMethodName, final String destroyMethodName) { try { GenericBeanDefinition bean = new GenericBeanDefinition(); bean.setBeanClass(beanClazz); bean.setAutowireCandidate(true); if (!StrUtil.isEmptyIfStr(initMethodName)) { bean.setInitMethodName(initMethodName); } if (!StrUtil.isEmptyIfStr(destroyMethodName)) { bean.setDestroyMethodName(destroyMethodName); } DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) this.applicationContext.getAutowireCapableBeanFactory(); defaultListableBeanFactory.registerBeanDefinition(beanName, bean); defaultListableBeanFactory.initializeBean(bean, beanName); } catch (Exception ex) { log.error("ๆ–ฐๅขžBeanๅผ‚ๅธธ๏ผŒๅผ‚ๅธธๅŽŸๅ› ไธบ๏ผš", ex); } } public <T> void addBean(final Class<T> beanClazz, final String beanName, final String initMethodName, final String destroyMethodName, final Map<String, Object> fieldInfo) { try { //ๅˆ›ๅปบbeanไฟกๆฏ. BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(beanClazz); //่ฎพ็ฝฎbeanๅญ—ๆฎตไฟกๆฏ CollUtil.forEach//JavaCollectionsUtil.mapProcessor ( fieldInfo, (final String key, final Object value, final int indx) -> beanDefinitionBuilder.addPropertyValue(key, value) ); if (!StrUtil.isEmptyIfStr(initMethodName)) { beanDefinitionBuilder.setInitMethodName(initMethodName); } if (!StrUtil.isEmptyIfStr(destroyMethodName)) { beanDefinitionBuilder.setDestroyMethodName(destroyMethodName); } //่Žทๅ–BeanFactory DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) this.applicationContext.getAutowireCapableBeanFactory(); defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition()); } catch (Exception ex) { log.error("ๆ–ฐๅขžBeanๅผ‚ๅธธ๏ผŒๅผ‚ๅธธๅŽŸๅ› ไธบ๏ผš", ex); } } public void removeBean(final String beanName) { //่Žทๅ–BeanFactory DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) this.applicationContext.getAutowireCapableBeanFactory(); //ๅˆ ้™คbean. defaultListableBeanFactory.removeBeanDefinition(beanName); } /** * ๆ˜พ็คบๆ‰€ๆœ‰Bean็š„ๅŸบ็ก€ไฟกๆฏ * */ public Map<String, Class<?>> showBeansBaseInfo(final boolean isPrintInfo) { Map<String, Class<?>> result = new HashMap<>(); if (isPrintInfo) { log.info("============================================ๆ˜พ็คบๅทฒๅŠ ่ฝฝ็š„BEAN----ๅผ€ๅง‹==============================================="); } String[] beans = this.applicationContext.getBeanDefinitionNames(); CollUtil.newArrayList(beans).forEach ( bean -> { result.put(bean, this.applicationContext.getType(bean)); if (isPrintInfo) { log.info("Beanๅ็งฐไธบ๏ผš{}๏ผŒ็ฑปๅž‹ไธบ๏ผš{}", bean, this.applicationContext.getType(bean)); } } ); if (isPrintInfo) { log.info("============================================ๆ˜พ็คบๅทฒๅŠ ่ฝฝ็š„BEAN----็ป“ๆŸ==============================================="); } return result; } public int shutdownApplication() { return SpringApplication.exit(this.applicationContext); } /**็”จไบŽๅœจapplication.properties่Žทๅ–ๅฑžๆ€ง๏ผŒ * * * ๅ‡่ฎพๅœจpropertes้…็ฝฎไธญๆœ‰่ฟ™ๆ ทไธ€ไธช้…็ฝฎ๏ผšcom.didispace.foo=bar * * @Data @ConfigurationProperties(prefix = "com.didispace") public class FooProperties { private String foo; } FooProperties foo = binder.bind("com.didispace", Bindable.of(FooProperties.class)).get(); * * */ public <T> T getProperties(final String propertiesKey, final Class<T> clazz) { return this.binder.bind(propertiesKey, Bindable.of(clazz)).get(); } public <K, V> Map<K, V> getProperties(final String propertiesKey, final Class<K> keyType, final Class<V> valueType) { return this.binder.bind(propertiesKey, Bindable.mapOf(keyType, valueType)).get(); } public <T> List<T> getPropertiesList(final String propertiesKey, final Class<T> clazz) { return this.binder.bind(propertiesKey, Bindable.listOf(clazz)).get(); } public <T> Set<T> getPropertiesSet(final String propertiesKey, final Class<T> clazz) { return this.binder.bind(propertiesKey, Bindable.setOf(clazz)).get(); } }
34.087855
172
0.712553
95c153e5626ecbc45b8d909747aca4f76264b37e
162
package com.atguigu.common.valid; /** * @program: gulimail * @description: * @author: Mr.Wang * @create: 2020-07-04 20:39 **/ public interface AddGroup { }
14.727273
33
0.660494
138056d274990d4e30be6e9003e809008bd682e6
2,754
package com.github.birdgeek.breadbot.utility; import java.util.List; import java.util.ArrayList; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class Service { protected String username; protected String password; protected List<String> moderators; protected List<String> ignoredUsers; protected String defaultDiscordRelayChannel; protected String defaultDiscordAnnounceChannel; protected String homeDiscordInviteLink; protected boolean enable; public Service() { } public Service(JSONObject user, JSONObject settings) { username = makeString(user.get("username")); password = makeString(user.get("password")); if(user.containsKey("oauth")) { password = makeString(user.get("oauth")); } defaultDiscordRelayChannel = makeString(settings.get("default-discord-relay-channel-id")); defaultDiscordAnnounceChannel = makeString(settings.get("default-discord-announce-channel-id")); enable = makeBoolean(settings.get("enable")); homeDiscordInviteLink = ""; if(settings.containsKey("discord-link")) { homeDiscordInviteLink = makeString(settings.get("discord-link")); } moderators = makeList((JSONArray)settings.get("moderators")); ignoredUsers = makeList((JSONArray)settings.get("ignored-users")); } protected static List<String> makeList(JSONArray j) { List<String> r = new ArrayList<String>(); if(j == null) return r; for(Object o : j.toArray()) { r.add((String)o); } return r; } protected static String makeString(Object j) { if(j != null) return (String)j; return ""; } protected static boolean makeBoolean(Object j) { if(j != null) { if(j.getClass().getName().equalsIgnoreCase("java.lang.Boolean")) return ((Boolean)j).booleanValue(); else return ((String)j).equalsIgnoreCase("true"); } return false; } public String getUsername() { return username; } public String getPassword() { return password; } public String getDefaultDiscordRelayChannel() { return defaultDiscordRelayChannel; } public String getDefaultDiscordAnnounceChannel() { return defaultDiscordAnnounceChannel; } public String getDiscordInviteLink() { return homeDiscordInviteLink; } public boolean isEnabled() { return enable; } public List<String> getModerators() { return moderators; } public List<String> getIgnoredUsers() { return ignoredUsers; } public String toString() { return "Name: " + username + "\nPassword: " + password + "\nModerators: " + moderators.toString() + "\nIgnored Users: " + ignoredUsers.toString() + "\nDefault Discord Relay Channel: " + defaultDiscordRelayChannel + "\nDefault Discord Announce Channel: " + defaultDiscordAnnounceChannel + "\nEnable: " + enable; } }
26.228571
312
0.721496
bedf7e11c121524b05e52622d7d3d643b49824e6
1,421
package com.oauth2app.models; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.Set; @Entity @Table(name = "user") public class User { private long id; private String username; private String password; private Set<Authority> authorities; public User() { } public User(String username, String password, Set<Authority> authorities) { this.username = username; this.password = password; this.authorities = authorities; } @Id @NotNull @GeneratedValue(strategy = GenerationType.AUTO) public long getId() { return id; } public void setId(long id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @ManyToMany(fetch = FetchType.EAGER) @JoinTable( name = "user_authority", joinColumns = @JoinColumn(name = "id_user"), inverseJoinColumns = @JoinColumn(name = "name") ) public Set<Authority> getAuthorities() { return authorities; } public void setAuthorities(Set<Authority> authorities) { this.authorities = authorities; } }
21.530303
79
0.626319
e3c631661a69e274b540548cfdd83575bcbfe6fe
230
package com.yonyou.etl.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.yonyou.etl.entity.SysBdLocalopt; /** * @author yhao */ public interface SysBdLocaloptMapper extends BaseMapper<SysBdLocalopt> { }
20.909091
72
0.8
a57f1ad1e011948f1d8953f05e5c2f1e3b339fbf
1,013
package io.cryptoapis.exchanges.services; import io.cryptoapis.abstractServices.AbstractServicesConfig; import io.cryptoapis.common_models.ApiResponse; import io.cryptoapis.utils.Utils; import io.cryptoapis.utils.config.EndpointConfig; import java.util.Map; public class MetadataService extends AbstractServicesConfig { private static final String PATH = "/{0}/{1}"; public MetadataService(EndpointConfig endpointConfig) { super(endpointConfig); } @Override protected String getPath() { return PATH; } public ApiResponse getExchangesList(Map<String, String> params) { return Utils.sendListRequest("exchanges", params, url, endpointConfig); } public ApiResponse getAssetsList(Map<String, String> params) { return Utils.sendListRequest("assets", params, url, endpointConfig); } public ApiResponse getSymbolsList(Map<String, String> params) { return Utils.sendListRequest("mappings", params, url, endpointConfig); } }
28.138889
79
0.732478
b1498e9f5ef2719d8573c881514e384e9b2c24d7
4,071
package com.travelport.schema.air_v29_0; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import com.travelport.schema.common_v29_0.BaseRsp; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://www.travelport.com/schema/common_v29_0}BaseRsp"> * &lt;sequence> * &lt;element ref="{http://www.travelport.com/schema/air_v29_0}ETR" maxOccurs="unbounded" minOccurs="0"/> * &lt;element ref="{http://www.travelport.com/schema/air_v29_0}TCR" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="RefundFailureInfo" type="{http://www.travelport.com/schema/air_v29_0}typeTicketFailureInfo" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "etr", "tcr", "refundFailureInfo" }) @XmlRootElement(name = "AirRefundRsp") public class AirRefundRsp extends BaseRsp { @XmlElement(name = "ETR") protected List<ETR> etr; @XmlElement(name = "TCR") protected List<TCR> tcr; @XmlElement(name = "RefundFailureInfo") protected List<TypeTicketFailureInfo> refundFailureInfo; /** * Provider: ACH.Gets the value of the etr property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the etr property. * * <p> * For example, to add a new item, do as follows: * <pre> * getETR().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ETR } * * */ public List<ETR> getETR() { if (etr == null) { etr = new ArrayList<ETR>(); } return this.etr; } /** * Provider: ACH.Gets the value of the tcr property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the tcr property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTCR().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TCR } * * */ public List<TCR> getTCR() { if (tcr == null) { tcr = new ArrayList<TCR>(); } return this.tcr; } /** * Gets the value of the refundFailureInfo property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the refundFailureInfo property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRefundFailureInfo().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TypeTicketFailureInfo } * * */ public List<TypeTicketFailureInfo> getRefundFailureInfo() { if (refundFailureInfo == null) { refundFailureInfo = new ArrayList<TypeTicketFailureInfo>(); } return this.refundFailureInfo; } }
28.87234
158
0.615574
8dd153079fb5e22e14599ef386b4510060a04392
428
package org.baifei.modules.message.service; import java.util.List; import org.baifei.modules.message.entity.SysMessageTemplate; import org.baifei.common.system.base.service.JeecgService; /** * @Description: ๆถˆๆฏๆจกๆฟ * @Author: jeecg-boot * @Date: 2019-04-09 * @Version: V1.0 */ public interface ISysMessageTemplateService extends JeecgService<SysMessageTemplate> { List<SysMessageTemplate> selectByCode(String code); }
25.176471
86
0.775701
eaaf899cf8edc56fc533e1431e24de9c1a593a71
1,247
// Targeted by JavaCPP version 1.5.3-SNAPSHOT: DO NOT EDIT THIS FILE package org.bytedeco.arrow_dataset; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import org.bytedeco.arrow.*; import static org.bytedeco.arrow.global.arrow.*; import org.bytedeco.parquet.*; import static org.bytedeco.arrow.global.parquet.*; import static org.bytedeco.arrow.global.arrow_dataset.*; /** \brief A trivial DataFragment that yields ScanTask out of a fixed set of * RecordBatch. */ @Namespace("arrow::dataset") @NoOffset @Properties(inherit = org.bytedeco.arrow.presets.arrow_dataset.class) public class SimpleDataFragment extends DataFragment { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public SimpleDataFragment(Pointer p) { super(p); } public SimpleDataFragment(@ByVal RecordBatchVector record_batches) { super((Pointer)null); allocate(record_batches); } private native void allocate(@ByVal RecordBatchVector record_batches); public native @ByVal Status Scan(@SharedPtr ScanContext scan_context, ScanTaskIterator out); public native @Cast("bool") boolean splittable(); public native @SharedPtr ScanOptions scan_options(); }
36.676471
120
0.768244
37e36213ae8917a212b499720d22e42f614ef55d
3,417
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). package org.rocksdb; import java.util.Map; /** * WALFilter allows an application to inspect write-ahead-log (WAL) * records or modify their processing on recovery. */ public interface WalFilter { /** * Provide ColumnFamily-&gt;LogNumber map to filter * so that filter can determine whether a log number applies to a given * column family (i.e. that log hasn't been flushed to SST already for the * column family). * * We also pass in name&gt;id map as only name is known during * recovery (as handles are opened post-recovery). * while write batch callbacks happen in terms of column family id. * * @param cfLognumber column_family_id to lognumber map * @param cfNameId column_family_name to column_family_id map */ void columnFamilyLogNumberMap(final Map<Integer, Long> cfLognumber, final Map<String, Integer> cfNameId); /** * LogRecord is invoked for each log record encountered for all the logs * during replay on logs on recovery. This method can be used to: * * inspect the record (using the batch parameter) * * ignoring current record * (by returning WalProcessingOption::kIgnoreCurrentRecord) * * reporting corrupted record * (by returning WalProcessingOption::kCorruptedRecord) * * stop log replay * (by returning kStop replay) - please note that this implies * discarding the logs from current record onwards. * * @param logNumber log number of the current log. * Filter might use this to determine if the log * record is applicable to a certain column family. * @param logFileName log file name - only for informational purposes * @param batch batch encountered in the log during recovery * @param newBatch new batch to populate if filter wants to change * the batch (for example to filter some records out, or alter some * records). Please note that the new batch MUST NOT contain * more records than original, else recovery would be failed. * * @return Processing option for the current record. */ LogRecordFoundResult logRecordFound(final long logNumber, final String logFileName, final WriteBatch batch, final WriteBatch newBatch); class LogRecordFoundResult { public static LogRecordFoundResult CONTINUE_UNCHANGED = new LogRecordFoundResult(WalProcessingOption.CONTINUE_PROCESSING, false); final WalProcessingOption walProcessingOption; final boolean batchChanged; /** * @param walProcessingOption the processing option * @param batchChanged Whether batch was changed by the filter. * It must be set to true if newBatch was populated, * else newBatch has no effect. */ public LogRecordFoundResult(final WalProcessingOption walProcessingOption, final boolean batchChanged) { this.walProcessingOption = walProcessingOption; this.batchChanged = batchChanged; } } /** * Returns a name that identifies this WAL filter. * The name will be printed to LOG file on start up for diagnosis. * * @return the name */ String name(); }
38.829545
81
0.710272
7466fce2dcbb76ce783884847dbe9ac80a3547a9
2,007
package contest.codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Round_336A_Div2 { static BufferedReader br; static PrintWriter out; static StringTokenizer st; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); //br = new BufferedReader(new FileReader("in.txt")); //out = new PrintWriter(new FileWriter("out.txt")); int n = readInt(); int s = readInt(); Person[] p = new Person[n]; for (int i = 0; i < n; i++) p[i] = new Person(readInt(), readInt()); Arrays.sort(p); int currTime = 0; for (int i = 0; i < n; i++) { currTime += s - p[i].floor; s = p[i].floor; currTime = Math.max(currTime, p[i].time); } currTime += s; out.println(currTime); out.close(); } static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine().trim()); return st.nextToken(); } static long readLong() throws IOException { return Long.parseLong(next()); } static int readInt() throws IOException { return Integer.parseInt(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readCharacter() throws IOException { return next().charAt(0); } static String readLine() throws IOException { return br.readLine().trim(); } static class Person implements Comparable<Person> { int floor, time; Person(int floor, int time) { this.floor = floor; this.time = time; } @Override public int compareTo(Person o) { if (o.floor == floor) return time - o.time; return o.floor - floor; } } }
23.892857
62
0.643747
852730297f42fdbd66657486c95a2f6f7ebf034e
2,522
// Copyright 2021 LinkedIn Corporation. All rights reserved. // Licensed under the BSD-2 Clause license. // See LICENSE in the project root for license information. package com.linkedin.cdi.keys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.regions.Region; public class S3Keys extends JobKeys { private static final Logger LOG = LoggerFactory.getLogger(S3Keys.class); private String bucket = ""; private String endpoint = ""; private String prefix = ""; private String filesPattern = ".*"; private Region region = Region.AWS_GLOBAL; private Integer maxKeys = 0; private String accessKey; private String secretId; private Integer connectionTimeout; String targetFilePattern; @Override public void logDebugAll() { super.logDebugAll(); LOG.debug("These are values in S3SourceV2:"); LOG.debug("S3 Bucket: {}", bucket); LOG.debug("S3 endpoint: {}", endpoint); LOG.debug("S3 prefix: {}", prefix); LOG.debug("S3 files pattern: {}", filesPattern); } public String getBucket() { return bucket; } public void setBucket(String bucket) { this.bucket = bucket; } public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getFilesPattern() { return filesPattern; } public void setFilesPattern(String filesPattern) { this.filesPattern = filesPattern; } public Region getRegion() { return region; } public void setRegion(Region region) { this.region = region; } public Integer getMaxKeys() { return maxKeys; } public void setMaxKeys(Integer maxKeys) { this.maxKeys = maxKeys; } public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretId() { return secretId; } public void setSecretId(String secretId) { this.secretId = secretId; } public Integer getConnectionTimeout() { return connectionTimeout; } public void setConnectionTimeout(Integer connectionTimeout) { this.connectionTimeout = connectionTimeout; } public String getTargetFilePattern() { return targetFilePattern; } public void setTargetFilePattern(String targetFilePattern) { this.targetFilePattern = targetFilePattern; } }
22.122807
74
0.702617
7b896da0216a868e1ddd33e8ca50348fccf9236d
1,493
/*********************************************************** * @Description : * @author : ๆขๅฑฑๅนฟ(Laing Shan Guang) * @date : 2018/3/18 ไธ‹ๅˆ6:57 * @email : liangshanguang2@gmail.com ***********************************************************/ package chapter1basic; public class P19CountOperate extends Thread { public P19CountOperate() { System.out.println("*********ๆž„้€ ๅ‡ฝๆ•ฐ๏ผšstart*********"); //ๅฝ“ๅ‰็บฟ็จ‹็š„ๆž„้€ ๅ‡ฝๆ•ฐๆ˜ฏๅœจไธปๅ‡ฝๆ•ฐMainไธญๆ‰ง่กŒๅœฐ System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName()); System.out.println("Thread.currentThread().isAlive() = " + Thread.currentThread().isAlive()); // ๅฝ“ๅ‰็š„ๆž„้€ ๅ‡ฝๆ•ฐๅฑžไบŽ็บฟ็จ‹Thread-0 System.out.println("this.getName() = " + this.getName()); System.out.println("this.isAlive() = " + this.isAlive()); System.out.println("*********ๆž„้€ ๅ‡ฝๆ•ฐ๏ผšend***********"); System.out.println(); } @Override public void run() { System.out.println("*********runๅ‡ฝๆ•ฐ๏ผšstart*********"); //ๅฝ“ๅ‰็บฟ็จ‹็š„runๅ‡ฝๆ•ฐๆ˜ฏๅœจๅฝ“ๅ‰็บฟ็จ‹Thread-0ไธญๆ‰ง่กŒๅœฐ System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName()); System.out.println("Thread.currentThread().isAlive() = " + Thread.currentThread().isAlive()); // ๅฝ“ๅ‰็š„ๆž„้€ ๅ‡ฝๆ•ฐๅฑžไบŽ็บฟ็จ‹Thread-0 System.out.println("this.getName() = " + this.getName()); System.out.println("this.isAlive() = " + this.isAlive()); System.out.println("*********runๅ‡ฝๆ•ฐ๏ผšend***********"); } }
43.911765
101
0.537173
2e3b65072ff15abe1239ddd6708a1bff2eb3f61d
1,749
package com.vinternship.mcmsbackend.controllers; import com.vinternship.mcmsbackend.models.Genre; import com.vinternship.mcmsbackend.repositories.GenreRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/api") public class GenreController { @Autowired GenreRepository genreRepository; @GetMapping("/genres") public ResponseEntity<List<Genre>> getAllGenres(@RequestParam(required = false) String name) { try { List<Genre> genres = new ArrayList<Genre>(); if (name == null) { genreRepository.findAll().forEach(genres::add); } else { genreRepository.findGenreByNameContaining(name).forEach(genres::add); } if (genres.isEmpty()) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } return new ResponseEntity<>(genres, HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); } } @PostMapping("/genres") public ResponseEntity<Genre> createGenre(@RequestBody Genre genre) { try { Genre _genre = genreRepository.save(new Genre( genre.getName() )); return new ResponseEntity<>(_genre, HttpStatus.CREATED); } catch (Exception e) { return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); } } }
33
98
0.656375
1c4934ab97fff4d5d581a35be70d3bdb00aba944
1,357
package io.github.fallingsoulm.easy.archetype.generate.core; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.Date; import java.util.List; import java.util.Map; /** * ่กจไฟกๆฏ * * @author luyanan * @since 2021/2/1 **/ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class TableInfoEntity implements Serializable { private static final long serialVersionUID = -1928615724129283736L; /** * ่กจๅ็งฐ * * @since 2021/2/1 */ private String tableName; /** * ๅค„็†่ฟ™ไธชๅŽ็š„ๅ็งฐ * * @since 2021/2/1 */ private String entityName; /** * ๆณจ้‡Š * * @since 2021/2/1 */ private String comment; /** * ๆ•ฐๆฎๅบ“ๅผ•ๆ“Ž * * @since 2021/2/1 */ private String engine; /** * ๅˆ›ๅปบๆ—ถ้—ด * * @since 2021/2/1 */ private Date createTime; /** * ๆ•ฐๆฎๅบ“็ผ–็  * * @since 2021/2/1 */ private String encode; /** * ๅญ—ๆฎตไฟกๆฏ * * @since 2021/2/1 */ private List<TableFieldEntity> tableFieldEntityList; /** * ็ดขๅผ•ไฟกๆฏ * * @since 2021/2/1 */ private List<TableIndexEntity> tableIndexEntityList; /** * ้™„ๅŠ ไฟกๆฏ * * @since 2021/2/1 */ private Map<String, Object> data; /** * idๅญ—ๆฎตๅ็งฐ * * @since 2021/2/1 */ private String idFieldName; /** * id็š„ๅญ—ๆฎต็ฑปๅž‹ * * @since 2021/2/1 */ private String idFieldType; }
12.92381
68
0.638909
5015a487c6dce605d58050fb32a642beec16a6f7
135
package nihao; public class hello { public static void main (String [] args) { System.out.println("hello java!"); } }
11.25
43
0.614815
a32885f4ad550faa05db580f8f391a60e713b30a
920
package org.lndroid.framework.usecases.user; import java.io.IOException; import java.lang.reflect.Type; import org.lndroid.framework.WalletData; import org.lndroid.framework.client.IPluginClient; import org.lndroid.framework.common.IPluginData; import org.lndroid.framework.defaults.DefaultPlugins; import org.lndroid.framework.usecases.GetData; public class GetChannelBalance extends GetData<WalletData.ChannelBalance, Long> { public GetChannelBalance(IPluginClient client){ super(client, DefaultPlugins.GET_CHANNEL_BALANCE); } @Override protected WalletData.ChannelBalance getData(IPluginData in) { in.assignDataType(WalletData.ChannelBalance.class); try { return in.getData(); } catch (IOException e) { return null; } } @Override protected Type getRequestType() { return WalletData.GetRequestLong.class; } }
28.75
81
0.729348
5b1b4c26174690a7ac801e0fe9840974ca733d40
407
package com.ejzblog.mall.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.ejzblog.mall.mapper.AbstractBaseMapper; /** * <p> * Description๏ผš * </p> * * @author Mango * @version v1.0.0 * @date 2021-12-28 18:35 * @see com.ejzblog.mall.service.impl */ public class AbstractBaseServiceImpl<M extends AbstractBaseMapper<T>, T> extends ServiceImpl<M, T> { }
20.35
100
0.727273
9ef038b75cecac0141927fe2869db47b2954124b
457
private static void copyImage(String srcImg, String destImg) { try { FileChannel srcChannel = new FileInputStream(srcImg).getChannel(); FileChannel dstChannel = new FileOutputStream(destImg).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { e.printStackTrace(); } }
38.083333
80
0.599562
cc7f2f8f6b423485bc409607fa546347a4b05d20
453
package org.xyy.b2c.root.product.mapper; import org.xyy.b2c.leaf.product.model.ProductCollection; public interface ProductCollectionMapper { int deleteByPrimaryKey(Integer id); int insert(ProductCollection record); int insertSelective(ProductCollection record); ProductCollection selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(ProductCollection record); int updateByPrimaryKey(ProductCollection record); }
26.647059
62
0.801325
216c2f88bd77871198a88cb9d6c8058d0dd3bc0b
626
/* Copyright (c) 2008-2011, The University of Edinburgh. * All Rights Reserved */ package uk.ac.ed.ph.snuggletex.definitions; import uk.ac.ed.ph.snuggletex.tokens.FlowToken; /** * This enumeration specifies how text-based {@link FlowToken}s should be handled when being merged * into the resulting XHTML DOM. * * @author David McKain */ public enum TextFlowContext { /** This token will start a new XHTML Block */ START_NEW_XHTML_BLOCK, /** This token is allowed in inline XHTML */ ALLOW_INLINE, /** This token makes no output and can be used anywhere */ IGNORE, ; }
22.357143
99
0.677316
8af1d8503374a8e4691f7f4011b112e073986f7d
2,059
package com.heroku.sdk.deploy.utils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import com.heroku.sdk.deploy.App; /** * @author Joe Kutner on 10/24/17. * Twitter: @codefinger */ public class Main { public interface DeployFunction<T, B, R> { R apply(T t, B b) throws IOException; } private static List<File> includesToFiles(String includes) { List<String> includeStrings = includesToList(includes, File.pathSeparator); List<File> includeFiles = new ArrayList<>(includeStrings.size()); for (String includeString : includeStrings) { if (!includeString.isEmpty()) { includeFiles.add(new File(includeString)); } } return includeFiles; } private static List<String> includesToList(String includes, String delim) { return includes == null || includes.isEmpty() ? new ArrayList<String>() : Arrays.asList(includes.split(delim)); } public static void deploy(DeployFunction<String, List<String>, App> f) throws Exception { String appName = System.getProperty("heroku.appName", null); String jdkVersion = System.getProperty("heroku.jdkVersion", null); List<File> includes = includesToFiles(System.getProperty("heroku.includes", "")); String buildFileName = System.getProperty("heroku.buildFileName", "slug.tgz"); String buildpacksDelim = System.getProperty("heroku.buildpacksDelim", ","); List<String> buildpacks = includesToList(System.getProperty("heroku.buildpacks", ""), buildpacksDelim); if (appName == null) { throw new IllegalArgumentException("Heroku app name must be provided with heroku.appName system property!"); } f.apply(appName, buildpacks). deploy(includes, new HashMap<String,String>(), jdkVersion, new HashMap<String,String>(), buildFileName); } public static Boolean isDebug() { String debug = System.getenv("HEROKU_DEBUG"); return "1".equals(debug) || "true".equals(debug); } }
33.209677
114
0.702283
42dbf9ddadfb9ecde2e030391969a08f14141d7f
637
package org.i3xx.util.ctree.parser; import java.io.BufferedReader; import java.io.IOException; public class FileReader extends AbstractLineReader { private String fileName; /** * @param in The reader to read from * @throws IOException */ public FileReader(String fileName) throws IOException { super(); this.fileName = fileName; } /** * @return true if a line is available to be read * @throws IOException */ public boolean available() throws IOException { if(in==null){ in = new BufferedReader(new java.io.FileReader(fileName)); } return super.available(); } }
20.548387
62
0.66876
343c8db8e19d6b9ff1e4659ba2259ece42c182a2
547
package com.mydreamplus.smartdevice.dao.jpa; import com.mydreamplus.smartdevice.entity.DeviceGroup; import org.springframework.data.repository.PagingAndSortingRepository; /** * Created with IntelliJ IDEA. * User: liji * Date: 16/7/11 * Time: ไธ‹ๅˆ5:19 * To change this template use File | Settings | File Templates. */ public interface GroupRepository extends PagingAndSortingRepository<DeviceGroup, Long> { /** * Find by mac address device group. * @return the device group */ DeviceGroup findByName(String name); }
24.863636
88
0.736746
049a5ae453260e5f45dd89d5579bbfc74fe45277
21,750
/** * Copyright (c) 2019 by Software.com * All rights reserved */ package com.swdc.netbeans.plugin; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import com.swdc.netbeans.plugin.managers.EventTrackerManager; import com.swdc.netbeans.plugin.managers.OfflineManager; import com.swdc.netbeans.plugin.managers.SoftwareSessionManager; import com.swdc.netbeans.plugin.managers.StatusBarManager; import com.swdc.netbeans.plugin.models.FileDetails; import com.swdc.netbeans.plugin.models.NetbeansProject; import com.swdc.snowplow.tracker.entities.UIElementEntity; import com.swdc.snowplow.tracker.events.UIInteractionType; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.swing.JOptionPane; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import org.apache.commons.lang.StringUtils; import org.netbeans.api.autoupdate.UpdateElement; import org.netbeans.api.autoupdate.UpdateManager; import org.netbeans.api.autoupdate.UpdateUnit; import org.netbeans.api.editor.EditorRegistry; import org.netbeans.api.project.FileOwnerQuery; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectManager; import org.netbeans.modules.parsing.api.Source; import org.openide.awt.HtmlBrowser.URLDisplayer; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; import org.openide.text.Line; import org.openide.text.NbDocument; import org.openide.util.Exceptions; import swdc.java.ops.http.ClientResponse; import swdc.java.ops.http.OpsHttpClient; import swdc.java.ops.manager.FileUtilManager; import swdc.java.ops.manager.UtilManager; /** * */ public class SoftwareUtil { public static final Logger LOG = Logger.getLogger("SoftwareUtil"); public static final String CODENAME = "com.swdc.netbeans.plugin"; private final static Object UTIL_LOCK = new Object(); private static SoftwareUtil instance = null; public static final Gson gson = new GsonBuilder().create(); // set the api endpoint to use public final static String API_ENDPOINT = "https://api.software.com"; // set the launch url to use public final static String LAUNCH_URL = "https://app.software.com"; public static String IDE_NAME = "netbeans"; public static String IDE_VERSION = ""; private static int DASHBOARD_LABEL_WIDTH = 25; private static int DASHBOARD_VALUE_WIDTH = 25; private static int MARKER_WIDTH = 4; private static String SERVICE_NOT_AVAIL = "Our service is temporarily unavailable.\n\nPlease try again later.\n"; private static int lastDayOfMonth = 0; // netbeans plugin id public final static int PLUGIN_ID = 11; public static final AtomicBoolean SEND_TELEMTRY = new AtomicBoolean(true); public final static ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool(); private static final long DAYS_IN_SECONDS = 60 * 60 * 24; private final static int EOF = -1; private static String workspace_name = null; private final static Map<String, String> sessionMap = new HashMap<String, String>(); public static boolean TELEMETRY_ON = true; private static boolean appAvailable = true; private static boolean loggedInCacheState = false; private static long lastAppAvailableCheck = 0; private static boolean showStatusText = true; private static Document lastDocument = null; private static String regex = "^\\S+@\\S+\\.\\S+$"; private static Pattern pattern = Pattern.compile(regex); static { try { IDE_VERSION = System.getProperty("netbeans.buildnumber"); } catch (Exception e) { IDE_VERSION = "unknown"; } } public static void updateServerStatus(boolean isOnlineStatus) { appAvailable = isOnlineStatus; } public static void updateLastDocument(Document doc) { lastDocument = doc; } public static boolean isAppAvailable() { return appAvailable; } public static class UserStatus { public boolean loggedIn; } public static String getWorkspaceName() { if (workspace_name == null) { workspace_name = generateToken(); } return workspace_name; } public static String getVersion() { for (UpdateUnit updateUnit : UpdateManager.getDefault().getUpdateUnits()) { UpdateElement updateElement = updateUnit.getInstalled(); if (updateElement != null) { if (SoftwareUtil.CODENAME.equals(updateElement.getCodeName())) { return updateElement.getSpecificationVersion(); } } } return "Unknown"; } public static boolean softwareSessionFileExists() { // don't auto create the file String file = FileUtilManager.getSoftwareSessionFile(false); // check if it exists File f = new File(file); return f.exists(); } public static boolean hasJwt() { String jwt = FileUtilManager.getItem("jwt"); return (jwt != null && !jwt.equals("")); } public static String getReadmeFile() { String file = FileUtilManager.getSoftwareDir(true); if (UtilManager.isWindows()) { file += "\\netbeansCt_README.txt"; } else { file += "/netbeansCt_README.txt"; } return file; } public static boolean isServerOnline() { long nowInSec = Math.round(System.currentTimeMillis() / 1000); boolean pastThreshold = (nowInSec - lastAppAvailableCheck > 120); if (pastThreshold) { ClientResponse resp = OpsHttpClient.softwareGet("/ping", null); appAvailable = resp.isOk(); lastAppAvailableCheck = nowInSec; } return appAvailable; } public static void showLoginPrompt() { boolean isOnline = isServerOnline(); if (isOnline) { String msg = "To see your coding data in Code Time, please log in to your account."; Object[] options = {"Log in", "Not now"}; int choice = JOptionPane.showOptionDialog( null, msg, "Code Time", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (choice == 0) { SoftwareSessionManager.launchLogin("email", UIInteractionType.keyboard, false); } } } public static void showAuthSelectPrompt(boolean isSignup) { String promptText = isSignup ? "Sign up" : "Log in"; String[] options = new String[]{ "Google", "GitHub", "Email" }; String input = (String) JOptionPane.showInputDialog( null, promptText + " using", promptText, JOptionPane.QUESTION_MESSAGE, null, options, // Array of choices options[0]); // Initial choice SoftwareSessionManager.launchLogin(input.toLowerCase(), UIInteractionType.click, true); } public static String generateToken() { String uuid = UUID.randomUUID().toString(); return uuid.replace("-", ""); } public static void launchSoftwareTopForty() { String url = "https://api.software.com/music/top40"; try { URL launchUrl = new URL(url); URLDisplayer.getDefault().showURL(launchUrl); } catch (MalformedURLException e) { LOG.log(Level.WARNING, "Failed to launch the url: {0}, error: {1}", new Object[]{url, e.getMessage()}); } } public static void fetchCodeTimeMetricsDashboard(JsonObject summary) { OfflineManager offlineMgr = OfflineManager.getInstance(); String dashboardFile = FileUtilManager.getCodeTimeDashboardFile(); String api = "/dashboard?linux=" + UtilManager.isLinux() + "&showToday=true"; ClientResponse resp = OpsHttpClient.softwareGet(api, FileUtilManager.getItem("jwt")); String dashboardContent = resp.getJsonStr(); // append the summary content String summaryInfoContent = offlineMgr.getSessionSummaryInfoFileContent(); if (summaryInfoContent != null) { dashboardContent += summaryInfoContent; } // write the dashboard content to the dashboard file offlineMgr.saveFileContent(dashboardContent, dashboardFile); } public static void launchCodeTimeMetricsDashboard() { JsonObject sessionSummary = OfflineManager.getInstance().getSessionSummaryFileAsJson(); fetchCodeTimeMetricsDashboard(sessionSummary); String codeTimeFile = FileUtilManager.getCodeTimeDashboardFile(); File f = new File(codeTimeFile); try { // open the file in the editor FileObject fo = FileUtil.createData(f); DataObject d = DataObject.find(fo); NbDocument.openDocument(d, PLUGIN_ID, Line.ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS); } catch (IOException ex) { Exceptions.printStackTrace(ex); } // delete the legacy file String legacyFileName = codeTimeFile.substring(0, codeTimeFile.lastIndexOf(".")); File legacyFile = new File(legacyFileName); if (legacyFile.exists()) { legacyFile.delete(); } } public static String getDashboardRow(String label, String value) { String content = getDashboardLabel(label) + " : " + getDashboardValue(value) + "\n"; return content; } public static String getSectionHeader(String label) { String content = label + "\n"; // add 3 to account for the " : " between the columns int dashLen = DASHBOARD_LABEL_WIDTH + DASHBOARD_VALUE_WIDTH + 15; for (int i = 0; i < dashLen; i++) { content += "-"; } content += "\n"; return content; } public static String getDashboardLabel(String label) { return getDashboardDataDisplay(DASHBOARD_LABEL_WIDTH, label); } public static String getDashboardValue(String value) { String valueContent = getDashboardDataDisplay(DASHBOARD_VALUE_WIDTH, value); String paddedContent = ""; for (int i = 0; i < 11; i++) { paddedContent += " "; } paddedContent += valueContent; return paddedContent; } public static String getDashboardDataDisplay(int widthLen, String data) { int len = widthLen - data.length(); String content = ""; for (int i = 0; i < len; i++) { content += " "; } return content + "" + data; } public static Project getProjectForPath(String fullFileName) { File f = new File(fullFileName); return FileOwnerQuery.getOwner(f.toURI()); } public static Project getProject(Document d) { Source source = Source.create(d); if (source == null) { return null; } FileObject fileObject = source.getFileObject(); if (fileObject == null) { return null; } return FileOwnerQuery.getOwner(fileObject); } public static Project getFirstActiveProject() { Set<Project> modifiedProjects = ProjectManager.getDefault().getModifiedProjects(); if (modifiedProjects.size() > 0) { // return the 1st one return modifiedProjects.iterator().next(); } JTextComponent jtc = EditorRegistry.lastFocusedComponent(); if (jtc != null) { Document d = jtc.getDocument(); return getProject(d); } return new NetbeansProject(); } public static FileDetails getFileDetails(String fullFileName) { FileDetails fileDetails = new FileDetails(); if (StringUtils.isNotBlank(fullFileName)) { fileDetails.full_file_name = fullFileName; File f = new File(fullFileName); if (f.exists()) { Project p = getProjectForPath(fullFileName); if (p != null) { fileDetails.project_directory = p.getProjectDirectory().getPath(); fileDetails.project_name = p.getProjectDirectory().getName(); } fileDetails.character_count = f.length(); fileDetails.file_name = f.getName(); if (StringUtils.isNotBlank(fileDetails.project_directory) && fullFileName.indexOf(fileDetails.project_directory) != -1) { // strip out the project_file_name String[] parts = fullFileName.split(fileDetails.project_directory); if (parts.length > 1) { fileDetails.project_file_name = parts[1]; } else { fileDetails.project_file_name = fullFileName; } } else { fileDetails.project_file_name = fullFileName; } fileDetails.line_count = getLineCount(fullFileName); fileDetails.syntax = (fullFileName.contains(".")) ? fullFileName.substring(fullFileName.lastIndexOf(".") + 1) : ""; } } return fileDetails; } public static int getLineCount(String fileName) { Stream<String> stream = null; try { Path path = Paths.get(fileName); stream = Files.lines(path); return (int) stream.count(); } catch (Exception e) { return 0; } finally { if (stream != null) { try { stream.close(); } catch (Exception e) { // } } } } public static Date atStartOfWeek(long local_now) { // find out how many days to go back int daysBack = 0; Calendar cal = Calendar.getInstance(); if (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) { int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); while (dayOfWeek != Calendar.SUNDAY) { daysBack++; dayOfWeek -= 1; } } else { daysBack = 7; } long startOfDayInSec = atStartOfDay(new Date(local_now * 1000)).toInstant().getEpochSecond(); long startOfWeekInSec = startOfDayInSec - (DAYS_IN_SECONDS * daysBack); return new Date(startOfWeekInSec * 1000); } public static Date atStartOfDay(Date date) { LocalDateTime localDateTime = dateToLocalDateTime(date); LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN); return localDateTimeToDate(startOfDay); } public static Date atEndOfDay(Date date) { LocalDateTime localDateTime = dateToLocalDateTime(date); LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX); return localDateTimeToDate(endOfDay); } private static LocalDateTime dateToLocalDateTime(Date date) { return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); } private static Date localDateTimeToDate(LocalDateTime localDateTime) { return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); } public static Date getJavaDateFromSeconds(long seconds) { Instant instant = Instant.ofEpochSecond( seconds ); Date date = Date.from( instant ); return date; } public static String getTimeOfDay(Date d) { return new SimpleDateFormat("h:mm a").format(d); } public static String getTodayInStandardFormat() { SimpleDateFormat formatDay = new SimpleDateFormat("YYYY-MM-dd"); String day = formatDay.format(new Date()); return day; } public static boolean isNewDay() { String currentDay = FileUtilManager.getItem("currentDay", ""); String day = getTodayInStandardFormat(); return !day.equals(currentDay); } public static JsonArray readAsJsonArray(String data) { try { JsonArray jsonArray = gson.fromJson(buildJsonReader(data), JsonArray.class); return jsonArray; } catch (Exception e) { return null; } } public static JsonObject readAsJsonObject(String data) { try { JsonObject jsonObject = gson.fromJson(buildJsonReader(data), JsonObject.class); return jsonObject; } catch (Exception e) { return null; } } public static JsonElement readAsJsonElement(String data) { try { JsonElement jsonElement = gson.fromJson(buildJsonReader(data), JsonElement.class); return jsonElement; } catch (Exception e) { return null; } } public static JsonReader buildJsonReader(String data) { // Clean the data data = cleanJsonString(data); JsonReader reader = new JsonReader(new StringReader(data)); reader.setLenient(true); return reader; } /** * Replace byte order mark, new lines, and trim * @param data * @return clean data */ public static String cleanJsonString(String data) { data = data.replace("\ufeff", "").replace("/\r\n/g", "").replace("/\n/g", "").trim(); int braceIdx = data.indexOf("{"); int bracketIdx = data.indexOf("["); // multi editor writes to the data.json file can cause an undefined string before the json object, remove it if (braceIdx > 0 && (braceIdx < bracketIdx || bracketIdx == -1)) { // there's something before the 1st brace data = data.substring(braceIdx); } else if (bracketIdx > 0 && (bracketIdx < braceIdx || braceIdx == -1)) { // there's something before the 1st bracket data = data.substring(bracketIdx); } return data; } public static Project getOpenProject() { if (lastDocument != null) { return getProject(lastDocument); } return getFirstActiveProject(); } public static void launchFile(String fsPath) { File f = new File(fsPath); try { // open the file in the editor FileObject fo = FileUtil.createData(f); DataObject d = DataObject.find(fo); NbDocument.openDocument(d, PLUGIN_ID, Line.ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } public static boolean showingStatusText() { return showStatusText; } public static void toggleStatusBar(UIInteractionType interactionType) { String cta_text = !showStatusText ? "Show status bar metrics" : "Hide status bar metrics"; showStatusText = !showStatusText; StatusBarManager.updateStatusBar(); UIElementEntity elementEntity = new UIElementEntity(); elementEntity.element_name = interactionType == UIInteractionType.click ? "ct_toggle_status_bar_metrics_btn" : "ct_toggle_status_bar_metrics_cmd"; elementEntity.element_location = interactionType == UIInteractionType.click ? "ct_menu_tree" : "ct_command_palette"; elementEntity.color = interactionType == UIInteractionType.click ? "blue" : null; elementEntity.cta_text = cta_text; elementEntity.icon_name = interactionType == UIInteractionType.click ? "slash-eye" : null; EventTrackerManager.getInstance().trackUIInteraction(interactionType, elementEntity); } public static String buildQueryString(JsonObject obj) { StringBuilder sb = new StringBuilder(); Iterator<String> keys = obj.keySet().iterator(); while(keys.hasNext()) { String key = keys.next(); if (!obj.get(key).isJsonNull()) { if (sb.length() > 0) { sb.append("&"); } String val = obj.get(key).getAsString(); try { val = URLEncoder.encode(val, "UTF-8"); } catch (UnsupportedEncodingException e) { LOG.log(Level.INFO, "Unable to url encode value, error: {0}", e.getMessage()); } sb.append(key).append("=").append(val); } } return "?" + sb.toString(); } }
35.48124
154
0.627218
0c5c41c89d2c7b3e13fab9cb3903418b008414a3
6,658
package com.example.android.scaletypeexplorer; import android.app.Activity; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.text.InputFilter; import android.text.Spanned; import android.view.MenuItem; public class SettingsActivity extends AppCompatPreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().setDisplayHomeAsUpEnabled(true); if (getFragmentManager().findFragmentByTag(PREF_FRAGMENT_TAG) == null) { getFragmentManager().beginTransaction() .replace(android.R.id.content, new MainPreferenceFragment(), PREF_FRAGMENT_TAG) .commit(); } } public static class MainPreferenceFragment extends PreferenceFragment { private ListPreference mPrefScaleType; private EditTextPreference mPrefWidthPercentage; private EditTextPreference mPrefHeightPercentage; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); mPrefScaleType = (ListPreference) findPreference(PREF_SCALE_TYPE); mPrefWidthPercentage = (EditTextPreference) findPreference(PREF_WIDTH_PERCENTAGE); mPrefHeightPercentage = (EditTextPreference) findPreference(PREF_HEIGHT_PERCENTAGE); bindPreferenceSummaryToValue(mPrefScaleType); bindPreferenceSummaryToValue(mPrefWidthPercentage); bindPreferenceSummaryToValue(mPrefHeightPercentage); // Percentages apply only to the matrix scale type. Ensure that percentage are between // 0.0 and 100.0 inclusive. Don't allow more than one decimal place. InputFilter minMaxFilter[] = {new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { String s = dest.toString().substring(0, dstart) + dest.toString().substring(dend, dest.length()); s = s.substring(0, dstart) + source.toString() + s.substring(dstart); int decimalPos = s.indexOf("."); if (decimalPos != -1 && s.length() - decimalPos > 2) { return ""; } Float value; try { value = Float.valueOf(s); } catch (NumberFormatException e) { return ""; } if (value > 100.0f) { return ""; } return null; } }}; mPrefWidthPercentage.getEditText().setFilters(minMaxFilter); mPrefHeightPercentage.getEditText().setFilters(minMaxFilter); } EditTextPreference getPrefWidthPercentage() { return mPrefWidthPercentage; } EditTextPreference getPrefHeightPercentage() { return mPrefHeightPercentage; } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return super.onOptionsItemSelected(item); } private static void bindPreferenceSummaryToValue(Preference preference) { preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); sBindPreferenceSummaryToValueListener .onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.getContext()) .getString(preference.getKey(), "")); } /** * A preference value change listener that updates the preference's summary * to reflect its new value. */ private static final Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String stringValue = newValue.toString(); if (preference instanceof ListPreference) { ListPreference listPreference = (ListPreference) preference; int index = listPreference.findIndexOfValue(stringValue); preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null); // Enabled percentages for the matrix scale type only. if (preference.getKey().equals(PREF_SCALE_TYPE)) { MainPreferenceFragment frag = (MainPreferenceFragment) ((Activity) preference.getContext()) .getFragmentManager().findFragmentByTag(PREF_FRAGMENT_TAG); if (newValue.equals("MATRIX")) { frag.getPrefWidthPercentage().setEnabled(true); frag.getPrefHeightPercentage().setEnabled(true); } else { frag.getPrefWidthPercentage().setEnabled(false); frag.getPrefHeightPercentage().setEnabled(false); } } } else { preference.setSummary(stringValue); } return true; } }; @SuppressWarnings("unused") private static final String TAG = SettingsActivity.class.getSimpleName(); private static final String PREF_FRAGMENT_TAG = "PREF_FRAG"; // Preference file keys. If these change, preferences.xml may also need to change. public static final String PREF_SCALE_TYPE_MATRIX = "MATRIX"; public static final String PREF_SCALE_TYPE_DEFAULT = PREF_SCALE_TYPE_MATRIX; public static final String PREF_SCALE_TYPE = "pref_scale_type"; public static final String PREF_WIDTH_PERCENTAGE = "pref_width_percentage"; public static final String PREF_WIDTH_PERCENTAGE_DEFAULT = "20"; public static final String PREF_HEIGHT_PERCENTAGE = "pref_height_percentage"; public static final String PREF_HEIGHT_PERCENTAGE_DEFAULT = "20"; }
44.386667
117
0.618504
cb0b6bcd74e2d20ff7953415c82e5646660a6317
3,838
package serpapi; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatchers; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; import static org.mockito.Mockito.*; /** * Test main class */ public class SerpApiClientTest { GoogleSearch search; @Before public void setUp() throws Exception { if (System.getenv("API_KEY") != null) { GoogleSearch.api_key_default = System.getenv("API_KEY"); } } @Test public void buildParameter() throws SerpApiSearchException { Map<String, String> parameter = new HashMap<>(); parameter.put("q", "Coffee"); parameter.put("location", "Austin, Texas"); search = new GoogleSearch(parameter); search.buildQuery("/search", "html"); assertEquals(search.parameter.get("source"), "java"); assertEquals(search.parameter.get(GoogleSearch.API_KEY_NAME), GoogleSearch.api_key_default); } @Test public void builParameterForInstance() throws SerpApiSearchException { GoogleSearch search = new GoogleSearch(); search.buildQuery("/search", "json"); assertEquals(search.parameter.get("source"), "java"); assertEquals(search.parameter.get("output"), "json"); assertEquals(search.parameter.get(GoogleSearch.API_KEY_NAME), GoogleSearch.api_key_default); } @Test public void getApiKey() throws Exception { GoogleSearch.api_key_default = "abc"; assertEquals("abc", GoogleSearch.getApiKey()); } @Test public void asJson() throws Exception { GoogleSearch search = new GoogleSearch(); JsonObject expectation = new JsonObject(); expectation.add("status", new JsonPrimitive("ok")); assertEquals(expectation, search.asJson("{\"status\": \"ok\"}")); } @Test public void getHtml() throws Exception { SerpApiHttpClient search = mock(SerpApiHttpClient.class); String htmlContent = ReadJsonFile.readAsString(Paths.get("src/test/java/serpapi/data/search_coffee_sample.html")); when(search.getResults(ArgumentMatchers.<String, String>anyMap())).thenReturn(htmlContent); Map<String, String> parameter = new HashMap<>(); parameter.put("q", "Coffee"); parameter.put("location", "Austin, Texas"); GoogleSearch result = new GoogleSearch(parameter); result.search = search; assertEquals(htmlContent, result.getHtml()); } @Test public void getJson() throws Exception { Map<String, String> parameter = new HashMap<>(); parameter.put("q", "Coffee"); parameter.put("location", "Austin, Texas"); SerpApiHttpClient stub = mock(SerpApiHttpClient.class); when(stub.getResults(ArgumentMatchers.<String, String>anyMap())) .thenReturn(ReadJsonFile.readAsJson(Paths.get("src/test/java/serpapi/data/search_coffee_sample.json")).toString()); GoogleSearch search = new GoogleSearch(parameter); search.search = stub; assertEquals(3, search.getJson().getAsJsonArray("local_results").size()); } @Test public void searchCoffee() throws SerpApiSearchException { // skip test if no api_key provided if(System.getenv("API_KEY") == null) return; Map<String, String> parameter = new HashMap<>(); parameter.put("q", "Coffee"); parameter.put("location", "Austin, Texas, United States"); parameter.put("hl", "en"); parameter.put("gl", "us"); parameter.put("google_domain", "google.com"); // parameter.put("api_key", "demo"); parameter.put("safe", "active"); parameter.put("start", "10"); parameter.put("num", "10"); parameter.put("device", "desktop"); GoogleSearch result = new GoogleSearch(parameter); JsonObject results = result.getJson(); assertTrue(results.getAsJsonArray("organic_results").size() > 5); } }
31.983333
123
0.698801
db3f28bd5cb1281b6b23faeb63bed0ccbbba2c85
3,152
package igentuman.ncsteamadditions.network; import io.netty.buffer.ByteBuf; import nc.network.tile.ProcessorUpdatePacket; import nc.network.tile.TileUpdatePacket; import nc.tile.ITileGui; import nc.tile.internal.fluid.Tank; import net.minecraft.util.math.BlockPos; import java.util.Iterator; import java.util.List; public class NCSProcessorUpdatePacket extends TileUpdatePacket { public boolean isProcessing; public double time; public int energyStored; public double baseProcessTime; public double baseProcessPower; public List<Tank.TankInfo> tanksInfo; public float currentReactivity; public float targetReactivity; public int adjustmentAttempts; public NCSProcessorUpdatePacket() { } public NCSProcessorUpdatePacket(BlockPos pos, boolean isProcessing, double time, int energyStored, double baseProcessTime, double baseProcessPower, List<Tank> tanks, float currentReactivity, float targetReactivity, int adjustmentAttempts) { this.pos = pos; this.isProcessing = isProcessing; this.time = time; this.energyStored = energyStored; this.baseProcessTime = baseProcessTime; this.baseProcessPower = baseProcessPower; this.tanksInfo = Tank.TankInfo.infoList(tanks); this.currentReactivity = currentReactivity; this.targetReactivity = targetReactivity; this.adjustmentAttempts = adjustmentAttempts; } public void fromBytes(ByteBuf buf) { this.pos = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt()); this.isProcessing = buf.readBoolean(); this.time = buf.readDouble(); this.energyStored = buf.readInt(); this.baseProcessTime = buf.readDouble(); this.baseProcessPower = buf.readDouble(); byte numberOfTanks = buf.readByte(); this.tanksInfo = Tank.TankInfo.readBuf(buf, numberOfTanks); this.currentReactivity = buf.readFloat(); this.targetReactivity = buf.readFloat(); this.adjustmentAttempts = buf.readInt(); } public void toBytes(ByteBuf buf) { buf.writeInt(this.pos.getX()); buf.writeInt(this.pos.getY()); buf.writeInt(this.pos.getZ()); buf.writeBoolean(this.isProcessing); buf.writeDouble(this.time); buf.writeInt(this.energyStored); buf.writeDouble(this.baseProcessTime); buf.writeDouble(this.baseProcessPower); buf.writeByte(this.tanksInfo.size()); Iterator var2 = this.tanksInfo.iterator(); while(var2.hasNext()) { Tank.TankInfo info = (Tank.TankInfo)var2.next(); info.writeBuf(buf); } buf.writeFloat(this.currentReactivity); buf.writeFloat(this.targetReactivity); buf.writeInt(this.adjustmentAttempts); } public static class Handler extends nc.network.tile.TileUpdatePacket.Handler<NCSProcessorUpdatePacket, ITileGui<NCSProcessorUpdatePacket>> { public Handler() { } protected void onTileUpdatePacket(NCSProcessorUpdatePacket message, ITileGui processor) { processor.onTileUpdatePacket(message); } } }
37.082353
244
0.696701
ee103b67dede95430f0526b17dfb7e8c96b4d581
539
package project3; //Name: Duong Phan public class Edge implements Comparable<Edge> { public String ID; public Vertex v1, v2; public double len; public Edge(Vertex v1, Vertex v2) { this.v1 = v1; this.v2 = v2; } public Edge(String ID, Vertex v1, Vertex v2) { this(v1, v2); this.ID = ID; } public Edge(Vertex v1, Vertex v2, double len) { this(v1, v2); this.len = len; } @Override public int compareTo(Edge e) { if (len > e.len) return 1; else if (len < e.len) return -1; else { return 0; } } }
14.567568
48
0.621521
823f6c5d7d00b987edbae183b4ffb4aca453bc29
3,311
/* * 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. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.osgi.soft; import static org.assertj.core.api.BDDAssertions.then; import java.util.HashMap; import java.util.List; import java.util.Map; import org.assertj.core.api.AbstractListAssert; import org.assertj.core.api.AbstractMapAssert; import org.assertj.core.api.AbstractSoftAssertions; import org.assertj.core.api.Assertions; import org.assertj.core.api.ObjectAssert; import org.assertj.core.api.ProxyableListAssert; import org.junit.jupiter.api.Test; public class CustomSoftAssertionTest { @Test void verify_classloaders() { // GIVEN Class<?> assertClass = TestProxyableMapAssert.class; Class<?> superClass = assertClass.getSuperclass(); // THEN then(assertClass.getClassLoader()).as("Custom assertion class must be from a different class loader than it's super class") .isNotSameAs(superClass.getClassLoader()); then(superClass.getClassLoader()).as("Custom assertion super class must be from the assertj-core class loader") .isSameAs(Assertions.class.getClassLoader()); } @Test void custom_soft_assertions_success() { // GIVEN TestSoftAssertions softly = new TestSoftAssertions(); Map<String, String> map = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); // WHEN softly.assertThat(map).containsKeys("key1", "key2").containsValues("value1", "value2"); // THEN softly.assertAll(); } @Test void custom_soft_assertions_failure() { // GIVEN TestSoftAssertions softly = new TestSoftAssertions(); Map<String, String> map = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); // WHEN softly.assertThat(map).containsKeys("key1", "key3").containsValues("value3", "value2"); // THEN then(softly.wasSuccess()).isFalse(); then(softly.errorsCollected()).hasSize(2); } public static class TestProxyableMapAssert<KEY, VALUE> extends AbstractMapAssert<TestProxyableMapAssert<KEY, VALUE>, Map<KEY, VALUE>, KEY, VALUE> { public TestProxyableMapAssert(Map<KEY, VALUE> actual) { super(actual, TestProxyableMapAssert.class); } @Override protected <ELEMENT> AbstractListAssert<?, List<? extends ELEMENT>, ELEMENT, ObjectAssert<ELEMENT>> newListAssertInstance(List<? extends ELEMENT> newActual) { return new ProxyableListAssert<>(newActual); } } public static class TestSoftAssertions extends AbstractSoftAssertions { @SuppressWarnings("unchecked") public <K, V> TestProxyableMapAssert<K, V> assertThat(Map<K, V> actual) { return proxy(TestProxyableMapAssert.class, Map.class, actual); } } }
36.384615
161
0.710359
49572ced8b8c0713085c1e108216c9fe76a4e312
1,083
package org.kairosdb.core.health; import com.google.inject.Binding; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static com.google.common.base.Preconditions.checkNotNull; public class HealthCheckServiceImpl implements HealthCheckService { private final List<HealthStatus> checks = new ArrayList<>(); @Inject public HealthCheckServiceImpl(final Injector injector) { checkNotNull(injector); final Map<Key<?>, Binding<?>> bindings = injector.getAllBindings(); for (final Key<?> key : bindings.keySet()) { final Class<?> bindingClass = key.getTypeLiteral().getRawType(); if (HealthStatus.class.isAssignableFrom(bindingClass)) { checks.add((HealthStatus) injector.getInstance(bindingClass)); } } } @Override public List<HealthStatus> getChecks() { return Collections.unmodifiableList(checks); } }
29.27027
78
0.700831
9f896337506b5bf3e2281866f9f9d8fdf3c5dd2a
536
package org.example.quickstart.controller; import org.example.quickstart.bean.Mouse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/hello") public class HelloController { @Autowired private Mouse mouse; @GetMapping("/mouse") public Mouse getMouse() { return mouse; } }
25.52381
62
0.779851
7f76e6ac645f111f26fab7bbddc81d70ed6362ab
7,270
/* * 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.servicecomb.demo.jaxrs.server.multiErrorCode; import java.util.ArrayList; import java.util.List; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Response.Status; import org.apache.servicecomb.demo.multiErrorCode.MultiRequest; import org.apache.servicecomb.demo.multiErrorCode.MultiResponse200; import org.apache.servicecomb.demo.multiErrorCode.MultiResponse400; import org.apache.servicecomb.demo.multiErrorCode.MultiResponse500; import org.apache.servicecomb.provider.rest.common.RestSchema; import org.apache.servicecomb.swagger.extend.annotations.ResponseHeaders; import org.apache.servicecomb.swagger.invocation.Response; import org.apache.servicecomb.swagger.invocation.exception.InvocationException; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ResponseHeader; @RestSchema(schemaId = "MultiErrorCodeService") @Path("MultiErrorCodeService") public class MultiErrorCodeService { @Path("/errorCode") @POST @ApiResponses({ @ApiResponse(code = 200, response = MultiResponse200.class, message = ""), @ApiResponse(code = 400, response = MultiResponse400.class, message = ""), @ApiResponse(code = 500, response = MultiResponse500.class, message = "")}) public MultiResponse200 errorCode(MultiRequest request) { if (request.getCode() == 400) { MultiResponse400 r = new MultiResponse400(); r.setCode(400); r.setMessage("bad request"); throw new InvocationException(javax.ws.rs.core.Response.Status.BAD_REQUEST, r); } else if (request.getCode() == 500) { MultiResponse500 r = new MultiResponse500(); r.setCode(500); r.setMessage("internal error"); throw new InvocationException(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR, r); } else { MultiResponse200 r = new MultiResponse200(); r.setCode(200); r.setMessage("success result"); return r; } } @Path("/errorCodeWithHeader") @POST @ApiResponses({ @ApiResponse(code = 200, response = MultiResponse200.class, message = ""), @ApiResponse(code = 400, response = MultiResponse400.class, message = ""), @ApiResponse(code = 500, response = MultiResponse500.class, message = "")}) @ResponseHeaders({@ResponseHeader(name = "x-code", response = String.class)}) public Response errorCodeWithHeader(MultiRequest request) { Response response = new Response(); if (request.getCode() == 400) { MultiResponse400 r = new MultiResponse400(); r.setCode(400); r.setMessage("bad request"); response.setStatus(Status.BAD_REQUEST); // If got many types for different status code, we can only using InvocationException for failed error code like 400-500. // The result for Failed Family(e.g. 400-500), can not set return value as target type directly or will give exception. response.setResult(new InvocationException(Status.BAD_REQUEST, r)); response.setHeader("x-code", "400"); } else if (request.getCode() == 500) { MultiResponse500 r = new MultiResponse500(); r.setCode(500); r.setMessage("internal error"); response.setStatus(Status.INTERNAL_SERVER_ERROR); response.setResult(new InvocationException(Status.INTERNAL_SERVER_ERROR, r)); response.setHeader("x-code", "500"); } else { MultiResponse200 r = new MultiResponse200(); r.setCode(200); r.setMessage("success result"); response.setStatus(Status.OK); // If error code is OK family(like 200), we can use the target type. response.setResult(r); response.setHeader("x-code", "200"); } return response; } // using JAX-RS providers, users need to add dependencies for implementations, see pom for an example. @Path("/errorCodeWithHeaderJAXRS") @POST @ApiResponses({ @ApiResponse(code = 200, response = MultiResponse200.class, message = ""), @ApiResponse(code = 400, response = MultiResponse400.class, message = ""), @ApiResponse(code = 500, response = MultiResponse500.class, message = "")}) @ResponseHeaders({@ResponseHeader(name = "x-code", response = String.class)}) public javax.ws.rs.core.Response errorCodeWithHeaderJAXRS(MultiRequest request) { javax.ws.rs.core.Response response; if (request.getCode() == 400) { MultiResponse400 r = new MultiResponse400(); r.setCode(request.getCode()); r.setMessage(request.getMessage()); // If got many types for different status code, we can only using InvocationException for failed error code like 400-500. // The result for Failed Family(e.g. 400-500), can not set return value as target type directly or will give exception. response = javax.ws.rs.core.Response.status(Status.BAD_REQUEST) .entity(new InvocationException(Status.BAD_REQUEST, r)) .header("x-code", "400") .build(); } else if (request.getCode() == 500) { MultiResponse500 r = new MultiResponse500(); r.setCode(request.getCode()); r.setMessage(request.getMessage()); response = javax.ws.rs.core.Response.status(Status.INTERNAL_SERVER_ERROR) .entity(new InvocationException(Status.INTERNAL_SERVER_ERROR, r)) .header("x-code", "500") .build(); } else { MultiResponse200 r = new MultiResponse200(); r.setCode(request.getCode()); r.setMessage(request.getMessage()); // If error code is OK family(like 200), we can use the target type. response = javax.ws.rs.core.Response.status(Status.OK) .entity(r) .header("x-code", "200") .build(); } return response; } @Path("/noClientErrorCode") @POST @ApiResponses({ @ApiResponse(code = 400, response = NoClientErrorCode400.class, message = "")}) public List<NoClientErrorCode200> noClientErrorCode(MultiRequest request) { if (request.getCode() == 400) { NoClientErrorCode400 r = new NoClientErrorCode400(); r.setCode(request.getCode()); r.setMessage(request.getMessage()); r.setT400(400); throw new InvocationException(Status.BAD_REQUEST, r); } else { NoClientErrorCode200 r = new NoClientErrorCode200(); r.setCode(request.getCode()); r.setMessage(request.getMessage()); r.setT200(200); List<NoClientErrorCode200> result = new ArrayList<>(); result.add(r); return result; } } }
43.27381
127
0.7011
b2c2e323c8b03e22350bc726b5120e01169c64bd
5,318
/* * $Id: Loader.java,v 1.1.1.1 2004/03/26 12:26:16 edankert Exp $ * * Copyright (C) 2004, Cladonia Ltd. All rights reserved. * * This software is the proprietary information of Cladonia Ltd. * Use is subject to license terms. */ package com.cladonia.util.loader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.StringTokenizer; /** * A generic application loader. * * @version $Revision: 1.1.1.1 $, $Date: 2004/03/26 12:26:16 $ * @author Dogsbay */ public class Loader { static final boolean VERBOSE = false; public static void main( String[] args) throws Exception { new Loader( args); } public Loader( String[] args) throws Exception { initProperties(); // String repositories = "xngr-editor.jar"+";"+getLibraryPath()+";"+getExtensionPath(); // String mainClass = "com.cladonia.xngreditor.Main"; if (VERBOSE) System.out.println("-------------------- Loading --------------------"); ExtensionClassLoader classLoader = new ExtensionClassLoader( this.getClass().getClassLoader()); if ( System.getProperty( "endorsed.libraries") != null) { StringTokenizer st = new StringTokenizer( System.getProperty( "endorsed.libraries"), ",;:"); while ( st.hasMoreTokens()) { classLoader.addEndorsedLibrary( new File( st.nextToken())); } } if ( System.getProperty( "libraries") != null) { StringTokenizer st = new StringTokenizer( System.getProperty( "libraries"), ",;:"); while ( st.hasMoreTokens()) { classLoader.addLibrary( new File( st.nextToken())); } } if ( System.getProperty( "extension.dir") != null) { classLoader.addExtensionDirectory( new File( System.getProperty( "extension.dir"))); } if ( System.getProperty( "extensions") != null) { StringTokenizer st = new StringTokenizer( System.getProperty( "extensions"), ",;:"); while ( st.hasMoreTokens()) { classLoader.addExtension( new File( st.nextToken())); } } if ( System.getProperty( "plugins.lib.dir") != null) { classLoader.addPluginsLibDirectory( new File( System.getProperty( "plugins.lib.dir"))); } if ( System.getProperty( "plugins.dir") != null) { classLoader.addPluginsDirectory( new File( System.getProperty( "plugins.dir"))); } Thread.currentThread().setContextClassLoader( classLoader); if (VERBOSE) System.out.println("-------------------- Executing -----------------"); invokeMain( classLoader, System.getProperty( "main.class"), args); } private void invokeMain( ClassLoader classloader, String classname, String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { if(VERBOSE) System.out.println("Trying to loadClass: classname: "+classname); Class invokedClass = classloader.loadClass(classname); Class[] methodParamTypes = new Class[2]; methodParamTypes[0] = classloader.getClass(); methodParamTypes[1] = args.getClass(); Method main = invokedClass.getDeclaredMethod( "main", methodParamTypes); Object[] methodParams = new Object[2]; methodParams[0] = classloader; methodParams[1] = args; main.invoke(null, methodParams); } private void initProperties() { Properties properties = null; if ( System.getProperty( "loader.properties.file") == null) { System.setProperty( "loader.properties.file", "loader.properties"); } File file = new File( System.getProperty( "loader.properties.file")); if ( file.exists()) { try { properties = new Properties(); properties.load( new FileInputStream( file)); } catch ( Exception e) { properties = null; } } else { if(VERBOSE) { File testFile = new File("testFile.test"); try { testFile.createNewFile(); System.err.println("Loader::initProperties - testFile for current dir: "+testFile.getAbsolutePath()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(VERBOSE) System.err.println("Loader::initProperties - cannot load loader.properties file: "+file.toString()); } if ( properties != null) { setProperty( properties, "libraries"); setProperty( properties, "extension.dir"); setProperty( properties, "endorsed.libraries"); setProperty( properties, "main.class"); setProperty( properties, "extensions"); setProperty( properties, "plugins.dir"); setProperty( properties, "plugins.lib.dir"); } } private void setProperty( Properties properties, String key) { if ( System.getProperty( key) == null) { if ( properties.getProperty( key) != null) { System.setProperty( key, properties.getProperty( key)); } } } }
34.089744
193
0.613012
f06fc408a57d202dab06a8949a35b709e8ff3b8c
12,131
package examples; /* * @author JJR Kotze (email 15692183@sun.ac.za) * For Department of Civil Engineering, Stellenbosch University * 29 October 2012 (Version 1.0 of CFS design) */ import section.*; import dSM.*; import java.text.*; import capacityDesign.*; import loadFactorscufsm.LoadFactorsCUFSM; public class EngineerBending { public static double maxlength; public static void main(String[] args) { DSMBending DSMB; DecimalFormat df = new DecimalFormat("#.###"); /* * SPECIFY THE FOLLOWING PARAMETERS */ String secName = "ZL 89x41x10x0.8"; //choose name from section database String matName = "550Mpa"; //choose material from material database String axis = "X"; //specify as either "X" (symmetric axis) or "Y" String loadDistr = "uniSS"; //specify as either "uniSS" (uniformly distributed simply supported) or "Other" String loadAppl = "SC"; //specify as either "SC" (applied to shear centre) ; "TF" (load applied to Tension Flange) ; "CF" (load applied to compression flange) String bracing = "No"; //bracing spacing for SS: specify as either "No" (no bracing) ; "C" (bracing at half span) ; "T" (Bracing at third points: this applies for centre unbraced section) double maxAppliedMoment = 1.0; //Note for Y-axis bending:specify as positive if max moment generates compression at lips ; negative if max moment generates compression at the web: boolean distCheck = false; //False: don't do distortional check ; True: include distortional check. double Lx = 1000.0; //effective lengths double Ly = Lx; double Lz = Lx; double Mmax = 0.0; // double M1 = 0.0; double M2 = 0.0; double M3 = 0.0; double M4 = 0.0; double M5 = 0.0; //DSM PARAMETERS //y-bending: ZL section double[] loadFactors = {1.3001,1.2769,1.1954,1.09,0.9834,0.88491,0.79713,0.72004,0.65266,0.5938,0.54227,0.49703,0.45716,0.42189,0.39056,0.36264,0.33765,0.31522,0.295,0.27672,0.26015,0.24508,0.23133,0.21876,0.20723,0.19665,0.18689,0.17788,0.16955,0.16184}; int turningpoint = 1100; //the length at which the graph peaks between distortional and global buckling: specify in multiples of "multiples" int multiples = 100; //The length multiples at which you want the output in the table double Mol = 0.94; double Mod = 0.63; double Mo = 1.0; //specify as 0.0 or 1.0. 0.0: uses EW method to determin Mo ; else if set to 1.0 uses the factors from cufsm to determine Mo double fy = 0.0; //specify as 0.0 if the yield stress of the material is in the database, otherwise specify the yield stress /* * END OF PARAMETERS */ /* * PRINT RESULTS */ //EFFECTIVE WIDTH METHOD: CAPACITY FOR A SPECIFIED EFFECTIVE LENGTH SectionDatabase sd = Parameters.getSectionDatabase(); LoadFactorsCUFSM currrentLoadFactor = new LoadFactorsCUFSM(loadFactors,Mo,multiples,turningpoint); //this will go and find the appropriate factor as listed in Moed[] for the determination of Mo String digit2 = secName.substring(0,2); if(digit2.equals("CL")){ LCBending LCB = new LCBending(secName,matName,maxAppliedMoment,axis,Lx,Ly,Lz,distCheck,Mmax,M1,M2,M3,M4,M5,loadDistr,loadAppl,bracing); sd.getLCSection(secName).printSectionProperties(); if(axis == "X"){ LCB.printResultsAboutX(); }else{ if(maxAppliedMoment<0.0){ LCB.printResultsAboutYTension(); }else{ LCB.printResultsAboutYCompression(); } } maxlength = LCB.maxLength()/multiples; }else if(digit2.equals("ZL")){ LZBending LZB = new LZBending(secName,matName,maxAppliedMoment,axis,Lx,Ly,Lz,distCheck,Mmax,M1,M2,M3,M4,M5,loadDistr,loadAppl,bracing); sd.getZLSection(secName).printSectionProperties(); if(axis.equals("X")){ LZB.printResultsAboutX(); }else{ LZB.printResultsAboutY(); } maxlength = LZB.maxLength()/multiples; }else if(digit2.equals("GS")){ maxlength = sd.getGSSection(secName).getMaxlength(); } //PRINT DSM RESULTS FOR A SPECIFIED EFFECTIVE LENGTH DSMB = new DSMBending(secName,matName,axis,maxAppliedMoment,currrentLoadFactor.getLoadFactor(Lx),Mol,Mod,Lx,Ly,Lz,fy,Mmax, M1, M2, M3, M4, M5, loadDistr, loadAppl, bracing); DSMB.printDSMBendingResult(); /* * CREATING TABLES * Iterative procedure for calculating capacity for different effective lengths * FIRST: EFFECTIVE WIDTH METHOD RESULTS FOR BENDING */ String orientation; if(digit2.equals("CL")){ if(axis.equals("X")){ orientation = "ORIENTATION: N.A"; }else{ if(maxAppliedMoment<0.0){ orientation = "COMPRESSION OCCURS AT THE WEB"; }else{ orientation = "COMPRESSION OCCURS AT THE EDGE STIFFENER"; } } }else if(digit2.equals("ZL")){ orientation = "ORIENTATION: N.A"; }else if(digit2.equals("GS")){ orientation = "ORIENTATION: N.A"; }else{ orientation = ""; } System.out.println("\n\n\n\n\nBENDING EFFECTIVE WIDTH RESULTS FOR THE "+secName+" SECTION:"); System.out.println("BENDING ABOUT THE : "+axis+" AXIS"); System.out.println(orientation); System.out.println("USING LENGTH INTERVALS OF "+multiples+" mm"); System.out.println("*************************************************************"); System.out.println("Length Mb Mbd Ms M Fail"); System.out.println(" (mm) (kNm) (kNm) (kNm) (kNm) ()"); System.out.println("*************************************************************"); if(digit2.equals("CL")){ for(int i=1;i<maxlength;i++){ double length = i*multiples; LCBending EW = new LCBending(secName,matName,maxAppliedMoment,axis,length,length,length,distCheck,Mmax,M1,M2,M3,M4,M5,loadDistr,loadAppl,bracing); double mb = EW.nominalMemberMomentCapMbNoDistCheck()/1000000.; double mbd = EW.distMemberCapacity()/1000000.; double ms = EW.nominalSectionMomentCapMs()/1000000.; double m = EW.UltimateMemberCapacity()/1000000.; String fail; if(EW.willItfail()){ fail ="YES"; }else{ fail = "NO"; } System.out.println(""); System.out.print(df.format(length)+" "); System.out.print(df.format(mb)+" "); System.out.print(df.format(mbd)+" "); System.out.print(df.format(ms)+" "); System.out.print(df.format(m)+" "); System.out.print(fail); } }else if(digit2.equals("ZL")){ for(int i=1;i<maxlength;i++){ double length = i*multiples; LZBending EW = new LZBending(secName,matName,maxAppliedMoment,axis,length,length,length,distCheck,Mmax,M1,M2,M3,M4,M5,loadDistr,loadAppl,bracing); double mb = EW.nominalMemberMomentCapMbNoDistCheck()/1000000.; double mbd = EW.distMemberCapacity()/1000000.; double ms = EW.nominalSectionMomentCapMs()/1000000.; double m = EW.UltimateMemberCapacity()/1000000.; String fail; if(EW.willItfail()){ fail ="YES"; }else{ fail = "NO"; } System.out.println(""); System.out.print(df.format(length)+" "); System.out.print(df.format(mb)+" "); System.out.print(df.format(mbd)+" "); System.out.print(df.format(ms)+" "); System.out.print(df.format(m)+" "); System.out.print(fail); } }else if(digit2.equals("GS")){ //Cannot be betermined according Effective width method System.out.println("THIS SECTION CANNOT BE DETERMINED ACCORDING THE EFFECTIVE WIDTH METHOD"); }else{ //UNKNOWN SECTION System.out.println("THIS SECTION IS UNKNOWN FOR THE EFFECTIVE WIDTH METHOD"); } /* * PART2: DIRECT STRENGTH METHOD TABLE PRINT */ System.out.println("\n\n\n\n\nBENDING DIRECT STRENGTH METHOD RESULTS FOR THE "+secName+" SECTION:"); System.out.println("BENDING ABOUT THE : "+axis+" AXIS"); System.out.println(orientation); System.out.println("USING LENGTH INTERVALS OF "+multiples+" mm"); System.out.println("*************************************************************"); System.out.println("Length Moc Mol Mod Mbe Mbl Mbd Mb M"); System.out.println(" (mm) (MPa) (MPa) (MPa) (kNm) (kNm) (kNm) (kNm) (kNm)"); System.out.println("*************************************************************"); for(int i=1;i<maxlength;i++){ double length = i*multiples; DSMBending DSM = new DSMBending(secName,matName,axis,maxAppliedMoment,currrentLoadFactor.getLoadFactor(length),Mol,Mod,length,length,length,fy,Mmax, M1, M2, M3, M4, M5, loadDistr, loadAppl, bracing); double moc = DSM.getMo()/1000000.; double mol = DSM.getMol()/1000000.; double mod = DSM.getMod()/1000000.; double mbe = DSM.nominalMemberMomentCapEuler()/1000000.; double mbl = DSM.nominalMemberMomentCapLocal()/1000000.; double mbd = DSM.nominalMemberMomentCapDistortional()/1000000.; double mb = DSM.getMb()/1000000.; double m = DSM.getDesignCapacity()/1000000.; System.out.println(""); // System.out.print(df.format(length)+" "); // System.out.print(df.format(moc)+" "); // System.out.print(df.format(mol)+" "); // System.out.print(df.format(mod)+" "); // System.out.print(df.format(mbe)+" "); // System.out.print(df.format(mbl)+" "); // System.out.print(df.format(mbd)+" "); // System.out.print(df.format(mb)+" "); System.out.print(df.format(m)+" "); } } /* * CL 89X41X10X0.8 CUFSM DATA */ // //x-bending // double[] loadFactors = {0.95287,0.93553,0.87204,0.7916,0.71195,0.63924,0.57483,0.51841,0.46916,0.42616,0.38855,0.35556,0.32651,0.30086,0.27811,0.25786,0.23977,0.22356,0.20899,0.19583,0.18393}; // int turningpoint = 1000; //the length at which the graph peaks between distortional and global buckling: specify in multiples of "multiples" // int multiples = 100; //The length multiples at which you want the output in the table // double Mol = 0.53; // double Mod = 0.56; //y-bending: lip in compression // double[] loadFactors = {1.1775,1.1162,1.0341,0.94503,0.85762,0.7762,0.70253,0.63693,0.57897,0.52794,0.48304,0.44352,0.40858,0.37768,0.35025,0.32581,0.30397,0.28439,0.26679,0.25088,0.23648}; // int turningpoint = 1000; //the length at which the graph peaks between distortional and global buckling: specify in multiples of "multiples" // int multiples = 100; //The length multiples at which you want the output in the table // double Mol = 1.22; // double Mod = 0.62; //y-bending: web in compression //double[] loadFactors = {7.7474,7.5659,7.1946,6.8437,6.512,6.1985}; //int turningpoint = 2500; //the length at which the graph peaks between distortional and global buckling: specify in multiples of "multiples" //int multiples = 100; //The length multiples at which you want the output in the table //double Mol = 0.29; //double Mod = 7.7474; /* * ZL 89X41X10X0.8 CUFSM DATA */ //x-bending: ZL section //double[] loadFactors = {1.0607,0.97021,0.84574,0.73364,0.6395,0.56133,0.49625,0.4417,0.39563,0.35642,0.32279,0.29375,0.26852,0.24645,0.22705,0.20991,0.19468,0.1811,0.16894,0.158,0.14814,0.1392,0.13109,0.12369,0.11694,0.11075,0.10507,0.099838,0.095012,0.090552,0.086419}; //int turningpoint = 1000; //the length at which the graph peaks between distortional and global buckling: specify in multiples of "multiples" //int multiples = 100; //The length multiples at which you want the output in the table //double Mol = 0.53; //double Mod = 0.56; //y-bending: ZL section //double[] loadFactors = {1.3001,1.2769,1.1954,1.09,0.9834,0.88491,0.79713,0.72004,0.65266,0.5938,0.54227,0.49703,0.45716,0.42189,0.39056,0.36264,0.33765,0.31522,0.295,0.27672,0.26015,0.24508,0.23133,0.21876,0.20723,0.19665,0.18689,0.17788,0.16955,0.16184}; //int turningpoint = 1100; //the length at which the graph peaks between distortional and global buckling: specify in multiples of "multiples" //int multiples = 100; //The length multiples at which you want the output in the table //double Mol = 0.94; //double Mod = 0.63; }
43.794224
277
0.652048
83ce98a911ef03294f1b6c66fa5811f49c375dc3
1,478
package kr.co.popone.fitts.di.module; import dagger.internal.Factory; import dagger.internal.Preconditions; import javax.inject.Provider; import kr.co.popone.fitts.model.api.FittsServiceApi; import retrofit2.Retrofit; public final class ServiceModule_ProvideFittsServiceApiFactory implements Factory<FittsServiceApi> { private final ServiceModule module; private final Provider<Retrofit> retrofitProvider; public ServiceModule_ProvideFittsServiceApiFactory(ServiceModule serviceModule, Provider<Retrofit> provider) { this.module = serviceModule; this.retrofitProvider = provider; } public FittsServiceApi get() { return provideInstance(this.module, this.retrofitProvider); } public static FittsServiceApi provideInstance(ServiceModule serviceModule, Provider<Retrofit> provider) { return proxyProvideFittsServiceApi(serviceModule, (Retrofit) provider.get()); } public static ServiceModule_ProvideFittsServiceApiFactory create(ServiceModule serviceModule, Provider<Retrofit> provider) { return new ServiceModule_ProvideFittsServiceApiFactory(serviceModule, provider); } public static FittsServiceApi proxyProvideFittsServiceApi(ServiceModule serviceModule, Retrofit retrofit) { return (FittsServiceApi) Preconditions.checkNotNull(serviceModule.provideFittsServiceApi(retrofit), "Cannot return null from a non-@Nullable @Provides method"); } }
43.470588
169
0.774696
93abd554f65cb37c965852dd1e995f6a2b5fd393
947
package com.mmnaseri.cs.skiena.ch08.s1; import com.mmnaseri.cs.qa.annotation.Quality; import com.mmnaseri.cs.qa.annotation.Stage; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; /** * @author Mohammad Milad Naseri (mmnaseri@programmer.net) * @since 1.0 (11/13/16, 8:42 AM) */ @Quality(Stage.UNTESTED) public class MemoizingDynamicFibonacciNumberGenerator implements FibonacciNumberGenerator { private final List<BigInteger> cache; public MemoizingDynamicFibonacciNumberGenerator() { cache = new ArrayList<>(); cache.add(BigInteger.ONE); cache.add(BigInteger.ONE); } @Override public BigInteger generate(int index) { while (cache.size() <= index) { cache.add(null); } if (cache.get(index) == null) { cache.set(index, generate(index - 1).add(generate(index - 2))); } return cache.get(index); } }
26.305556
91
0.664203
f3b791ab551491540fa3c888788e6df1f3ec1864
2,236
/* * Copyright 2008-2013 Exigen Insurance Solutions, Inc. All Rights Reserved. * */ package com.exigeninsurance.x4j.analytic.xlsx.core.node; import org.apache.poi.xssf.model.StylesTable; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.openxmlformats.schemas.drawingml.x2006.main.CTOfficeStyleSheet; import com.exigeninsurance.x4j.analytic.xlsx.core.expression.XLSXExpression; import com.exigeninsurance.x4j.analytic.xlsx.transform.PdfStyle; import com.exigeninsurance.x4j.analytic.xlsx.transform.xlsx.XLSXStylesTable; import com.exigeninsurance.x4j.analytic.xlsx.utils.ColorHelper; abstract public class CellNode extends Node { public static final String DEFAULT_FILL = "#FFFFFF"; protected XLSXExpression expression; protected XSSFCell cell; private String axis; private ColorHelper colorHelper; public CellNode(XSSFSheet sheet,XSSFCell cell,XLSXExpression expr) { super(sheet); expression = expr; this.cell = cell; StylesTable stylesSource = sheet.getWorkbook().getStylesSource(); CTOfficeStyleSheet office = null; if(stylesSource instanceof XLSXStylesTable){ office = ((XLSXStylesTable)stylesSource).getStyleSheet(); } this.setColorHelper(new ColorHelper(office)); } public CellNode(XSSFSheet sheet) { super(sheet); } public XLSXExpression getExpression() { return expression; } public void setExpression(XLSXExpression expression) { this.expression = expression; } public XSSFCell getCell() { return cell; } public void setAxis(String axis) { this.axis = axis; } public String getAxis() { return axis; } public String getFill(PdfStyle pdfStyle) { if (pdfStyle != null) { return getColorHelper().colorToHex(pdfStyle.getFill().getBgColor()); } return DEFAULT_FILL; } public XSSFCellStyle getCellStyle() { return getCell().getCellStyle(); } public ColorHelper getColorHelper() { return colorHelper; } public void setColorHelper(ColorHelper colorHelper) { this.colorHelper = colorHelper; } }
23.787234
77
0.721825
4a1243861b33bb5f016a7eb00fef00cdf09a6522
5,107
package com.egoveris.dashboard.web.vm; import java.util.List; import java.util.Locale; import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.ContextParam; import org.zkoss.bind.annotation.ContextType; import org.zkoss.bind.annotation.Init; import org.zkoss.util.Locales; import org.zkoss.web.Attributes; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.Sessions; import org.zkoss.zk.ui.select.Selectors; import org.zkoss.zk.ui.select.annotation.VariableResolver; import org.zkoss.zk.ui.select.annotation.Wire; import org.zkoss.zk.ui.util.Clients; import org.zkoss.zkplus.spring.SpringUtil; import org.zkoss.zul.Hlayout; import org.zkoss.zul.Listitem; import org.zkoss.zul.Window; import com.egoveris.commons.databaseconfiguration.propiedades.AppProperty; import com.egoveris.dashboard.web.util.DashboardConstants; import com.egoveris.sharedsecurity.conf.service.Utilitarios; @VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class) public class ControlUsuarioVM { @Wire private Hlayout controlUsuarioLayout; private AppProperty appProperty; private String usuarioLogeado; private List<Listitem> idiomas; private Listitem idiomaSel; /** * Inicializa el panel de control usuario. Carga el usuario logeado * y los idiomas disponibles (en caso de querer cambiarlo) * * @param view */ @Init public void init(@ContextParam(ContextType.VIEW) Component view) { Selectors.wireComponents(view, this, false); if (SpringUtil.getBean(DashboardConstants.BEAN_DBPROPERTY) != null) { appProperty = (AppProperty) SpringUtil.getBean(DashboardConstants.BEAN_DBPROPERTY); } loadInfoUser(); String lenguaje = appProperty.getString(DashboardConstants.APP_LANG); Locale preferedLocale = Locales.getLocale(lenguaje); Sessions.getCurrent().setAttribute(Attributes.PREFERRED_LOCALE, preferedLocale); } /** * En el panel de usuario, a traves de las variables de sesion * muestra el siguiente texto: USUARIO - REPARTICION - SECTOR */ private void loadInfoUser() { String user = ""; String reparticion = null; String sector = null; if (Executions.getCurrent().getDesktop().getSession().hasAttribute(DashboardConstants.SESSION_USERNAME)) { user = (String) Executions.getCurrent().getDesktop().getSession() .getAttribute(DashboardConstants.SESSION_USERNAME); } if (Executions.getCurrent().getDesktop().getSession().hasAttribute(DashboardConstants.SESSION_USER_REPARTICION)) { reparticion = (String) Executions.getCurrent().getDesktop().getSession() .getAttribute(DashboardConstants.SESSION_USER_REPARTICION); } if (Executions.getCurrent().getDesktop().getSession().hasAttribute(DashboardConstants.SESSION_USER_SECTOR)) { sector = (String) Executions.getCurrent().getDesktop().getSession() .getAttribute(DashboardConstants.SESSION_USER_SECTOR); } String infoUser = user + " " + (reparticion == null ? " " : reparticion) + " " + (sector == null ? " " : sector); setUsuarioLogeado(infoUser); } @Command public void irEscritorio() { if (appProperty != null) { Executions.sendRedirect(DashboardConstants.getHostEDT()); } } @Command public void miInformacion() { if (appProperty != null) { Executions.sendRedirect(appProperty.getString(DashboardConstants.PROPERTY_URL_MIINFORMACION)); } } @Command public void cambiarCargo() { Utilitarios.closePopUps("win_seleccionDeReparticion"); Window cambiarIdiomaWindow = (Window) Executions.createComponents(DashboardConstants.WINDOW_CAMBIO_SECTOR, controlUsuarioLayout, null); cambiarIdiomaWindow.doModal(); } /** * Comando que abre la ventana de cambio de idioma */ @Command public void openCambiarIdiomaWindow() { Utilitarios.closePopUps("cambiarIdiomaWindow"); Window cambiarIdiomaWindow = (Window) Executions.createComponents(DashboardConstants.WINDOW_CAMBIO_IDIOMA, controlUsuarioLayout, null); cambiarIdiomaWindow.doModal(); } /** * Comando que cambia el idioma de sesion */ @Command public void cambiarIdioma() { if (idiomaSel != null) { Locale preferedLocale = Locales.getLocale(idiomaSel.getValue().toString()); Sessions.getCurrent().setAttribute(Attributes.PREFERRED_LOCALE, preferedLocale); Executions.sendRedirect(null); } } /** * Comando que realiza el logout */ @Command public void logout() { Clients.evalJavaScript("egoverisLogout()"); Clients.evalJavaScript("localStorage.removeItem('egoverisLogged')"); Executions.getCurrent().getSession().invalidate(); Executions.sendRedirect(DashboardConstants.URL_LOGOUT); } public String getUsuarioLogeado() { return usuarioLogeado; } public void setUsuarioLogeado(String usuarioLogeado) { this.usuarioLogeado = usuarioLogeado; } public List<Listitem> getIdiomas() { return idiomas; } public void setIdiomas(List<Listitem> idiomas) { this.idiomas = idiomas; } public Listitem getIdiomaSel() { return idiomaSel; } public void setIdiomaSel(Listitem idiomaSel) { this.idiomaSel = idiomaSel; } }
29.350575
116
0.758175
09b02204d90d0e7eead40856016cdb1856d9aac1
3,448
package net.dijkema.jndbm.streams; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; public class NDbmDataInputStream implements DataInput { private InputStream _in=null; /////////////////////////////////////////////////////////////////////// public void reset(InputStream i) { _in=i; } public NDbmDataInputStream(InputStream in) { _in=in; } /////////////////////////////////////////////////////////////////////// public String readLine() throws IOException { throw new IOException("This method is not implemented"); } public int readUnsignedByte() throws IOException { throw new IOException("This method is not implemented"); } public int readUnsignedShort() throws IOException { throw new IOException("This method is not implemented"); } public void readFully(byte[] arg0) throws IOException { throw new IOException("This method is not implemented"); } public void readFully(byte[] arg0, int arg1, int arg2) throws IOException { throw new IOException("This method is not implemented"); } /////////////////////////////////////////////////////////////////////// public boolean readBoolean() throws IOException { int b=_in.read(); if (b=='T') { return true; } else { return false; } } public byte readByte() throws IOException { return (byte) _in.read(); } public char readChar() throws IOException { return (char) readShort(); } public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } public static int getInt(byte[] b) { //((((int) b[7])-'a')<<28)| //((((int) b[6])-'a')<<24)| return ((((int) b[5])-' ')<<30)| ((((int) b[4])-' ')<<24)| ((((int) b[3])-' ')<<18)| ((((int) b[2])-' ')<<12)| ((((int) b[1])-' ')<<6)| (((int) b[0])-' '); } public int readInt() throws IOException { byte[] b={0,0,0,0,0,0}; // 32 bit/6 => 6 ,0,0}; _in.read(b); return getInt(b); } public long readLong() throws IOException { byte[] b={0,0,0,0,0,0,0,0,0,0,0}; // 64 bit/8 => 11 ,0,0,0,0,0}; _in.read(b); long i= //((((long) b[15])-'a')<<60)| //((((long) b[14])-'a')<<56)| //((((long) b[13])-'a')<<52)| //((((long) b[12])-'a')<<48)| //((((long) b[11])-'a')<<44)| ((((long) b[10])-' ')<<60)| ((((long) b[9])-' ')<<54)| ((((long) b[8])-' ')<<48)| ((((long) b[7])-' ')<<42)| ((((long) b[6])-' ')<<36)| ((((long) b[5])-' ')<<30)| ((((long) b[4])-' ')<<24)| ((((long) b[3])-' ')<<18)| ((((long) b[2])-' ')<<12)| ((((long) b[1])-' ')<<6)| (((long) b[0])-' '); return i; } public short readShort() throws IOException { byte[] b={0,0,0}; // 16bits/6=3 ,0}; _in.read(b); int c=//((((int) b[3])-'a')<<12)| ((((int) b[2])-' ')<<12)| ((((int) b[1])-' ')<<6)| (((int) b[0])-' '); return (short) c; } public static int sizeOfShort() { return 3; } public static int sizeOfInt() { return 6; } public static int sizeOfLong() { return 11; } public String readUTF() throws IOException { int l=readInt(); byte[] b=new byte[l]; _in.read(b); return new String(b,"UTF-8"); } public int skipBytes(int b) throws IOException { return (int) _in.skip(b); } }
23.944444
76
0.515371
ca4d55a89ca47743b973a7c30e490d453f3c009a
1,185
package daniking.geoactivity.mixin.recharge; import daniking.geoactivity.api.item.Rechargeable; import daniking.geoactivity.common.item.util.GAMiningToolItem; import daniking.geoactivity.common.util.RechargeUtil; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.MiningToolItem; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(MiningToolItem.class) public class MiningToolItemMixin { @Inject(method = "postHit", at = @At("HEAD"), cancellable = true) private void markFatiguedOnEntityHit(ItemStack stack, LivingEntity target, LivingEntity attacker, CallbackInfoReturnable<Boolean> cir) { if (stack.getItem() instanceof Rechargeable && stack.getItem() instanceof GAMiningToolItem) { RechargeUtil.initDestroyedNbt((PlayerEntity) attacker, stack); if (RechargeUtil.isFatigued(stack)) { cir.setReturnValue(false); } } } }
42.321429
140
0.76962
a40cbd4ce641f29b3549aba0ea68a1abebb026d0
2,043
package neo.vm.types; import org.apache.commons.lang3.NotImplementedException; import neo.vm.AbstractStackItem; import neo.vm.IInteropInterface; /** * the interop interface stack item. * * @author coranos * */ public final class InteropInterfaceStackItem extends AbstractStackItem { /** * the interop interface. */ private final IInteropInterface object; /** * the cosntructor. * * @param value * the value. */ public InteropInterfaceStackItem(final IInteropInterface value) { object = value; } @Override public int compareTo(final AbstractStackItem o) { if (o instanceof InteropInterfaceStackItem) { final InteropInterfaceStackItem that = (InteropInterfaceStackItem) o; return object.compareTo(that.object); } throw new RuntimeException("object is not a InteropInterface:" + o); } @Override public boolean getBoolean() { return object != null; } @Override public byte[] getByteArray() { throw new NotImplementedException("GetByteArray"); } @Override @SuppressWarnings("unchecked") public <T extends IInteropInterface> T getInterface(final Class<T> cl) { return (T) object; } @Override public boolean isArray() { return false; } @Override public boolean isStruct() { return false; } } // using System; // // namespace Neo.VM.Types // { // internal class InteropInterface : StackItem // { // private IInteropInterface _object; // // public InteropInterface(IInteropInterface value) // { // this._object = value; // } // // public override bool Equals(StackItem other) // { // if (ReferenceEquals(this, other)) return true; // if (ReferenceEquals(null, other)) return false; // InteropInterface i = other as InteropInterface; // if (i == null) return false; // return _object.Equals(i._object); // } // // public override bool GetBoolean() // { // return _object != null; // } // // public override byte[] GetByteArray() // { // throw new NotSupportedException(); // } // // public override T GetInterface<T>() // { // return _object as T; // } // } // }
19.457143
73
0.695056