@Override
  public void write() {
    for (int i = 0; i < revoluteJoints.size(); i++) {
      ImmutablePair<OneDegreeOfFreedomJoint, OneDoFJoint> jointPair = revoluteJoints.get(i);
      OneDegreeOfFreedomJoint pinJoint = jointPair.getLeft();
      OneDoFJoint revoluteJoint = jointPair.getRight();

      pinJoint.setTau(revoluteJoint.getTau());
    }
  }
  @Override
  public ImmutablePair<String, JSONObject> generate(
      JSONObject constraints, YodaEnvironment yodaEnvironment) {
    String hasQualityRole;
    String prepositionClassString;
    JSONObject child;
    List<String> keys =
        (List<String>)
            constraints.keySet().stream().map(x -> (String) x).collect(Collectors.toList());
    keys.remove("class");
    hasQualityRole = keys.get(0);
    JSONObject prepositionContent = (JSONObject) constraints.get(hasQualityRole);
    prepositionClassString = (String) prepositionContent.get("class");
    child =
        SemanticsModel.parseJSON(
            ((JSONObject) prepositionContent.get(YodaSkeletonOntologyRegistry.inRelationTo.name))
                .toJSONString());

    QualityDegree prepositionClass = Ontology.qualityDegreeNameMap.get(prepositionClassString);
    String ppString = null;
    try {
      ppString =
          yodaEnvironment
              .lex
              .getPOSForClass(
                  prepositionClass, Lexicon.LexicalEntry.PART_OF_SPEECH.PREPOSITION, false)
              .stream()
              .findAny()
              .get();
    } catch (Lexicon.NoLexiconEntryException e) {
      ppString = "of";
    }

    JSONObject ansJSON = SemanticsModel.parseJSON("{\"class\":\"" + prepositionClass.name + "\"}");
    SemanticsModel.wrap(
        ansJSON, YodaSkeletonOntologyRegistry.unknownThingWithRoles.name, hasQualityRole);

    ImmutablePair<String, JSONObject> nestedPhrase =
        NaturalLanguageGenerator.getAppropriatePhraseGenerationRoutine(child)
            .generate(child, yodaEnvironment);

    SemanticsModel.putAtPath(
        ansJSON,
        hasQualityRole + "." + YodaSkeletonOntologyRegistry.inRelationTo.name,
        nestedPhrase.getRight());
    String ansString = ppString + " " + nestedPhrase.getLeft();

    return new ImmutablePair<>(ansString, ansJSON);
  }
  public void updateRobotConfigurationBasedOnFullRobotModel() {
    for (int i = 0; i < revoluteJoints.size(); i++) {
      ImmutablePair<OneDegreeOfFreedomJoint, OneDoFJoint> jointPair = revoluteJoints.get(i);
      OneDegreeOfFreedomJoint pinJoint = jointPair.getLeft();
      OneDoFJoint revoluteJoint = jointPair.getRight();

      pinJoint.setQ(revoluteJoint.getQ());
    }

    FloatingJoint floatingJoint = rootJointPair.getLeft();
    FloatingInverseDynamicsJoint sixDoFJoint = rootJointPair.getRight();

    RigidBodyTransform transform = sixDoFJoint.getJointTransform3D();
    floatingJoint.setRotationAndTranslation(transform);
  }
Example #4
0
 @SuppressWarnings("static-method")
 protected ImmutablePair<BitmapDrawable, Boolean> scaleImage(
     final ImmutablePair<Bitmap, Boolean> loadResult) {
   final Bitmap bitmap = loadResult.left;
   return ImmutablePair.of(
       bitmap != null ? ImageUtils.scaleBitmapToFitDisplay(bitmap) : null, loadResult.right);
 }
  @SuppressWarnings("unchecked")
  public List<Record> runNewTableRecord() throws Exception {
    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();

    TargetRunner runner =
        new TargetRunner.Builder(HiveMetastoreTarget.class, hiveTarget)
            .setOnRecordError(OnRecordError.STOP_PIPELINE)
            .build();
    runner.runInit();

    LinkedHashMap<String, HiveTypeInfo> columns = new LinkedHashMap<>();
    columns.put("name", HiveType.STRING.getSupport().generateHiveTypeInfoFromResultSet("STRING"));
    columns.put(
        "surname", HiveType.STRING.getSupport().generateHiveTypeInfoFromResultSet("STRING"));

    LinkedHashMap<String, HiveTypeInfo> partitions = new LinkedHashMap<>();
    partitions.put("dt", HiveType.STRING.getSupport().generateHiveTypeInfoFromResultSet("STRING"));

    Field newTableField =
        HiveMetastoreUtil.newSchemaMetadataFieldBuilder(
            "default",
            "tbl",
            columns,
            partitions,
            true,
            BaseHiveIT.getDefaultWareHouseDir(),
            HiveMetastoreUtil.generateAvroSchema(columns, "tbl"));

    Record record = RecordCreator.create();
    record.set(newTableField);
    Assert.assertTrue(HiveMetastoreUtil.isSchemaChangeRecord(record));

    runner.runWrite(ImmutableList.of(record));

    assertTableStructure(
        "default.tbl",
        ImmutablePair.of("tbl.name", Types.VARCHAR),
        ImmutablePair.of("tbl.surname", Types.VARCHAR),
        ImmutablePair.of("tbl.dt", Types.VARCHAR));

    try {
      return runner.getEventRecords();
    } finally {
      runner.runDestroy();
    }
  }
 public boolean isCurrentTimeInSchedule() {
   DateTime now = DateTime.now();
   if (dayOfWeekRange != null && !dayOfWeekRange.contains(now.getDayOfWeek())) {
     return false;
   }
   if (dayOfMonthRange != null && !dayOfMonthRange.contains(now.getDayOfMonth())) {
     return false;
   }
   if (timeRange != null) {
     Interval interval =
         new Interval(
             timeRange.getLeft().toDateTimeToday(), timeRange.getRight().toDateTimeToday());
     if (!interval.contains(now)) {
       return false;
     }
   }
   return true;
 }
Example #7
0
 /**
  * Load a previously saved image.
  *
  * @param file the file on disk
  * @param forceKeep keep the image if it is there, without checking its freshness
  * @return a pair with <code>true</code> in the second component if the image was there and is
  *     fresh enough or <code>false</code> otherwise, and the image (possibly <code>null</code> if
  *     the second component is <code>false</code> and the image could not be loaded, or if the
  *     second component is <code>true</code> and <code>onlySave</code> is also <code>true</code>)
  */
 @NonNull
 private ImmutablePair<Bitmap, Boolean> loadCachedImage(final File file, final boolean forceKeep) {
   if (file.exists()) {
     final boolean freshEnough =
         listId >= StoredList.STANDARD_LIST_ID
             || file.lastModified() > (System.currentTimeMillis() - (24 * 60 * 60 * 1000))
             || forceKeep;
     if (freshEnough && onlySave) {
       return ImmutablePair.of((Bitmap) null, true);
     }
     final BitmapFactory.Options bfOptions = new BitmapFactory.Options();
     bfOptions.inTempStorage = new byte[16 * 1024];
     bfOptions.inPreferredConfig = Bitmap.Config.RGB_565;
     setSampleSize(file, bfOptions);
     final Bitmap image = BitmapFactory.decodeFile(file.getPath(), bfOptions);
     if (image == null) {
       Log.e("Cannot decode bitmap from " + file.getPath());
       return ImmutablePair.of((Bitmap) null, false);
     }
     return ImmutablePair.of(image, freshEnough);
   }
   return ImmutablePair.of((Bitmap) null, false);
 }
Example #8
0
 /**
  * Load an image from primary or secondary storage.
  *
  * @param url the image URL
  * @param pseudoGeocode the geocode or the shared name
  * @param forceKeep keep the image if it is there, without checking its freshness
  * @return A pair whose first element is the bitmap if available, and the second one is <code>true
  *     </code> if the image is present and fresh enough.
  */
 @NonNull
 private ImmutablePair<Bitmap, Boolean> loadImageFromStorage(
     final String url, @NonNull final String pseudoGeocode, final boolean forceKeep) {
   try {
     final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, false);
     final ImmutablePair<Bitmap, Boolean> image = loadCachedImage(file, forceKeep);
     if (image.right || image.left != null) {
       return image;
     }
     final File fileSec = LocalStorage.getStorageSecFile(pseudoGeocode, url, true);
     return loadCachedImage(fileSec, forceKeep);
   } catch (final Exception e) {
     Log.w("HtmlImage.loadImageFromStorage", e);
   }
   return ImmutablePair.of((Bitmap) null, false);
 }
  private Pair<WebsocketHandlers, Method> getMethod(JsonObject request) {
    String action = request.getAsJsonPrimitive("action").getAsString();

    Pair<WebsocketHandlers, Method> methodPair = methodsCache.get(action);
    if (methodPair != null) {
      return methodPair;
    }

    for (Iterator<WebsocketHandlers> iter = handlers.iterator(); iter.hasNext(); ) {
      WebsocketHandlers current = iter.next();
      Class<? extends WebsocketHandlers> currentClass = current.getClass();
      boolean found = false;
      for (final Method method : currentClass.getMethods()) {
        if (method.isAnnotationPresent(Action.class)) {
          if (method.getAnnotation(Action.class).value().equals(action)) {
            Preconditions.checkState(
                method.getReturnType().equals(WebSocketResponse.class),
                "Method should have %s return type",
                WebSocketResponse.class);
            methodPair = ImmutablePair.of(current, method);
            found = true;
            break;
          }
        }
      }
      if (found) {
        break;
      }
    }
    if (methodPair == null) {
      throw new HiveException(
          String.format(Messages.UNKNOWN_ACTION_REQUESTED_WS, action),
          HttpServletResponse.SC_BAD_REQUEST);
    }
    methodsCache.put(action, methodPair);
    return methodPair;
  }
/**
 * Generate2ColorDeck class.
 *
 * @author Forge
 * @version $Id$
 */
public class DeckGenerator2Color extends DeckGeneratorBase {
  @Override
  protected final float getLandsPercentage() {
    return 0.39f;
  }

  @Override
  protected final float getCreatPercentage() {
    return 0.36f;
  }

  @Override
  protected final float getSpellPercentage() {
    return 0.25f;
  }

  @SuppressWarnings("unchecked")
  final List<ImmutablePair<FilterCMC, Integer>> cmcRelativeWeights =
      Lists.newArrayList(
          ImmutablePair.of(new FilterCMC(0, 2), 6),
          ImmutablePair.of(new FilterCMC(3, 4), 4),
          ImmutablePair.of(new FilterCMC(5, 6), 2),
          ImmutablePair.of(new FilterCMC(7, 20), 1));

  // mana curve of the card pool
  // 20x 0 - 2
  // 16x 3 - 4
  // 12x 5 - 6
  // 4x 7 - 20
  // = 52x - card pool (before further random filtering)

  public DeckGenerator2Color(IDeckGenPool pool, final String clr1, final String clr2) {
    super(pool);
    int c1 = MagicColor.fromName(clr1);
    int c2 = MagicColor.fromName(clr2);

    if (c1 == 0 && c2 == 0) {
      int color1 = r.nextInt(5);
      int color2 = (color1 + 1 + r.nextInt(4)) % 5;
      colors = ColorSet.fromMask(MagicColor.WHITE << color1 | MagicColor.WHITE << color2);
    } else if (c1 == 0 || c2 == 0) {
      byte knownColor = (byte) (c1 | c2);
      int color1 = Arrays.binarySearch(MagicColor.WUBRG, knownColor);
      int color2 = (color1 + 1 + r.nextInt(4)) % 5;
      colors = ColorSet.fromMask(MagicColor.WHITE << color1 | MagicColor.WHITE << color2);
    } else {
      colors = ColorSet.fromMask(c1 | c2);
    }
  }

  @Override
  public final CardPool getDeck(final int size, final boolean forAi) {
    addCreaturesAndSpells(size, cmcRelativeWeights, forAi);

    // Add lands
    int numLands = Math.round(size * getLandsPercentage());
    adjustDeckSize(size - numLands);
    tmpDeck.append(
        String.format(
            "Adjusted deck size to: %d, should add %d land(s)%n", size - numLands, numLands));

    // Add dual lands
    List<String> duals = getDualLandList();
    for (String s : duals) {
      this.cardCounts.put(s, 0);
    }

    int dblsAdded = addSomeStr((numLands / 6), duals);
    numLands -= dblsAdded;

    addBasicLand(numLands);
    tmpDeck.append("DeckSize:").append(tDeck.countAll()).append("\n");

    // System.out.println(tmpDeck.toString());

    return tDeck;
  }
}
Example #11
0
  @Transactional(readOnly = true)
  @Override
  public Pair<Boolean, Boolean> enforcePolicies(final User user) {
    // ------------------------------
    // Verify password policies
    // ------------------------------
    LOG.debug("Password Policy enforcement");

    try {
      int maxPPSpecHistory = 0;
      for (PasswordPolicy policy : getPasswordPolicies(user)) {
        if (user.getPassword() == null && !policy.isAllowNullPassword()) {
          throw new PasswordPolicyException("Password mandatory");
        }

        for (PasswordRuleConf ruleConf : policy.getRuleConfs()) {
          Class<? extends PasswordRule> ruleClass =
              implementationLookup.getPasswordRuleClass(ruleConf.getClass());
          if (ruleClass == null) {
            LOG.warn("Could not find matching password rule for {}", ruleConf.getClass());
          } else {
            // fetch (or create) rule
            PasswordRule rule;
            if (ApplicationContextProvider.getBeanFactory()
                .containsSingleton(ruleClass.getName())) {
              rule =
                  (PasswordRule)
                      ApplicationContextProvider.getBeanFactory().getSingleton(ruleClass.getName());
            } else {
              rule =
                  (PasswordRule)
                      ApplicationContextProvider.getBeanFactory()
                          .createBean(ruleClass, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
              ApplicationContextProvider.getBeanFactory()
                  .registerSingleton(ruleClass.getName(), rule);
            }

            // enforce rule
            rule.enforce(ruleConf, user);
          }
        }

        if (user.verifyPasswordHistory(user.getClearPassword(), policy.getHistoryLength())) {
          throw new PasswordPolicyException("Password value was used in the past: not allowed");
        }

        if (policy.getHistoryLength() > maxPPSpecHistory) {
          maxPPSpecHistory = policy.getHistoryLength();
        }
      }

      // update user's password history with encrypted password
      if (maxPPSpecHistory > 0 && user.getPassword() != null) {
        user.getPasswordHistory().add(user.getPassword());
      }
      // keep only the last maxPPSpecHistory items in user's password history
      if (maxPPSpecHistory < user.getPasswordHistory().size()) {
        for (int i = 0; i < user.getPasswordHistory().size() - maxPPSpecHistory; i++) {
          user.getPasswordHistory().remove(i);
        }
      }
    } catch (Exception e) {
      LOG.error("Invalid password for {}", user, e);
      throw new InvalidEntityException(
          User.class, EntityViolationType.InvalidPassword, e.getMessage());
    } finally {
      // password has been validated, let's remove its clear version
      user.removeClearPassword();
    }

    // ------------------------------
    // Verify account policies
    // ------------------------------
    LOG.debug("Account Policy enforcement");

    boolean suspend = false;
    boolean propagateSuspension = false;
    try {
      if (adminUser.equals(user.getUsername()) || anonymousUser.equals(user.getUsername())) {
        throw new AccountPolicyException("Not allowed: " + user.getUsername());
      }

      for (AccountPolicy policy : getAccountPolicies(user)) {
        for (AccountRuleConf ruleConf : policy.getRuleConfs()) {
          Class<? extends AccountRule> ruleClass =
              implementationLookup.getAccountRuleClass(ruleConf.getClass());
          if (ruleClass == null) {
            LOG.warn("Could not find matching password rule for {}", ruleConf.getClass());
          } else {
            // fetch (or create) rule
            AccountRule rule;
            if (ApplicationContextProvider.getBeanFactory()
                .containsSingleton(ruleClass.getName())) {
              rule =
                  (AccountRule)
                      ApplicationContextProvider.getBeanFactory().getSingleton(ruleClass.getName());
            } else {
              rule =
                  (AccountRule)
                      ApplicationContextProvider.getBeanFactory()
                          .createBean(ruleClass, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
              ApplicationContextProvider.getBeanFactory()
                  .registerSingleton(ruleClass.getName(), rule);
            }

            // enforce rule
            rule.enforce(ruleConf, user);
          }
        }

        suspend |=
            user.getFailedLogins() != null
                && policy.getMaxAuthenticationAttempts() > 0
                && user.getFailedLogins() > policy.getMaxAuthenticationAttempts()
                && !user.isSuspended();
        propagateSuspension |= policy.isPropagateSuspension();
      }
    } catch (Exception e) {
      LOG.error("Invalid username for {}", user, e);
      throw new InvalidEntityException(
          User.class, EntityViolationType.InvalidUsername, e.getMessage());
    }

    return ImmutablePair.of(suspend, propagateSuspension);
  }
  protected void updateEntityActionState() {
    super.updateEntityActionState();

    if (!this.worldObj.isRemote) {
      int i;
      int j;
      int k;
      int i1;

      if (this.allySummonCooldown > 0) {
        --this.allySummonCooldown;

        if (this.allySummonCooldown == 0) {
          i = MathHelper.floor_double(this.posX);
          j = MathHelper.floor_double(this.posY);
          k = MathHelper.floor_double(this.posZ);
          boolean flag = false;

          for (int l = 0; !flag && l <= 5 && l >= -5; l = l <= 0 ? 1 - l : 0 - l) {
            for (i1 = 0; !flag && i1 <= 10 && i1 >= -10; i1 = i1 <= 0 ? 1 - i1 : 0 - i1) {
              for (int j1 = 0; !flag && j1 <= 10 && j1 >= -10; j1 = j1 <= 0 ? 1 - j1 : 0 - j1) {
                if (this.worldObj.getBlock(i + i1, j + l, k + j1) == Blocks.monster_egg) {
                  if (!this.worldObj.getGameRules().getGameRuleBooleanValue("mobGriefing")) {
                    int k1 = this.worldObj.getBlockMetadata(i + i1, j + l, k + j1);
                    ImmutablePair immutablepair = BlockSilverfish.func_150197_b(k1);
                    this.worldObj.setBlock(
                        i + i1,
                        j + l,
                        k + j1,
                        (Block) immutablepair.getLeft(),
                        ((Integer) immutablepair.getRight()).intValue(),
                        3);
                  } else {
                    this.worldObj.func_147480_a(i + i1, j + l, k + j1, false);
                  }

                  Blocks.monster_egg.onBlockDestroyedByPlayer(
                      this.worldObj, i + i1, j + l, k + j1, 0);

                  if (this.rand.nextBoolean()) {
                    flag = true;
                    break;
                  }
                }
              }
            }
          }
        }
      }

      if (this.entityToAttack == null && !this.hasPath()) {
        i = MathHelper.floor_double(this.posX);
        j = MathHelper.floor_double(this.posY + 0.5D);
        k = MathHelper.floor_double(this.posZ);
        int l1 = this.rand.nextInt(6);
        Block block =
            this.worldObj.getBlock(
                i + Facing.offsetsXForSide[l1],
                j + Facing.offsetsYForSide[l1],
                k + Facing.offsetsZForSide[l1]);
        i1 =
            this.worldObj.getBlockMetadata(
                i + Facing.offsetsXForSide[l1],
                j + Facing.offsetsYForSide[l1],
                k + Facing.offsetsZForSide[l1]);

        if (BlockSilverfish.func_150196_a(block)) {
          this.worldObj.setBlock(
              i + Facing.offsetsXForSide[l1],
              j + Facing.offsetsYForSide[l1],
              k + Facing.offsetsZForSide[l1],
              Blocks.monster_egg,
              BlockSilverfish.func_150195_a(block, i1),
              3);
          this.spawnExplosionParticle();
          this.setDead();
        } else {
          this.updateWanderPath();
        }
      } else if (this.entityToAttack != null && !this.hasPath()) {
        this.entityToAttack = null;
      }
    }
  }
 private Pom invokeFactory(final String pomFile) throws Exception {
   final ImmutablePair<Element, String> pomDetails = getPom(pomFile);
   return factory.getInstance(pomDetails.getKey(), pomDetails.getValue(), MODULE_NAME);
 }