Exemplo n.º 1
1
 protected static boolean checkIdle(final Point p) throws NimbitsException {
   final Calendar c = Calendar.getInstance();
   c.add(Calendar.SECOND, p.getIdleSeconds() * -1);
   boolean retVal = false;
   final List<Entity> result =
       EntityServiceFactory.getInstance()
           .getEntityByKey(
               UserServiceFactory.getServerInstance().getAdmin(), p.getOwner(), EntityType.user);
   if (!result.isEmpty()) {
     final User u = (User) result.get(0);
     final List<Value> v = ValueServiceFactory.getInstance().getCurrentValue(p);
     if (p.getIdleSeconds() > 0
         && !v.isEmpty()
         && v.get(0).getTimestamp().getTime() <= c.getTimeInMillis()
         && !p.getIdleAlarmSent()) {
       p.setIdleAlarmSent(true);
       EntityServiceFactory.getInstance().addUpdateEntity(u, p);
       // PointServiceFactory.getInstance().updatePoint(u, p);
       final Value va = ValueFactory.createValueModel(v.get(0), AlertType.IdleAlert);
       SubscriptionServiceFactory.getInstance().processSubscriptions(u, p, va);
       retVal = true;
     }
   }
   return retVal;
 }
 static List populatedArray(int n) {
   List a = ParallelArray.createEmpty(n, Object.class, ParallelArray.defaultExecutor()).asList();
   assertTrue(a.isEmpty());
   for (int i = 0; i < n; ++i) a.add(new Integer(i));
   assertFalse(a.isEmpty());
   assertEquals(n, a.size());
   return a;
 }
  @Nullable
  public static PyType getType(@NotNull PsiElement resolved, @NotNull List<PyType> elementTypes) {
    final String qualifiedName = getQualifiedName(resolved);

    final List<Integer> paramListTypePositions = new ArrayList<>();
    final List<Integer> ellipsisTypePositions = new ArrayList<>();
    for (int i = 0; i < elementTypes.size(); i++) {
      final PyType type = elementTypes.get(i);
      if (type instanceof PyTypeParser.ParameterListType) {
        paramListTypePositions.add(i);
      } else if (type instanceof PyTypeParser.EllipsisType) {
        ellipsisTypePositions.add(i);
      }
    }

    if (!paramListTypePositions.isEmpty()) {
      if (!("typing.Callable".equals(qualifiedName) && paramListTypePositions.equals(list(0)))) {
        return null;
      }
    }
    if (!ellipsisTypePositions.isEmpty()) {
      if (!("typing.Callable".equals(qualifiedName) && ellipsisTypePositions.equals(list(0))
          || "typing.Tuple".equals(qualifiedName)
              && ellipsisTypePositions.equals(list(1))
              && elementTypes.size() == 2)) {
        return null;
      }
    }

    if ("typing.Union".equals(qualifiedName)) {
      return PyUnionType.union(elementTypes);
    }
    if ("typing.Optional".equals(qualifiedName) && elementTypes.size() == 1) {
      return PyUnionType.union(elementTypes.get(0), PyNoneType.INSTANCE);
    }
    if ("typing.Callable".equals(qualifiedName) && elementTypes.size() == 2) {
      final PyTypeParser.ParameterListType paramList =
          as(elementTypes.get(0), PyTypeParser.ParameterListType.class);
      if (paramList != null) {
        return new PyCallableTypeImpl(paramList.getCallableParameters(), elementTypes.get(1));
      }
      if (elementTypes.get(0) instanceof PyTypeParser.EllipsisType) {
        return new PyCallableTypeImpl(null, elementTypes.get(1));
      }
    }
    if ("typing.Tuple".equals(qualifiedName)) {
      if (elementTypes.size() > 1 && elementTypes.get(1) instanceof PyTypeParser.EllipsisType) {
        return PyTupleType.createHomogeneous(resolved, elementTypes.get(0));
      }
      return PyTupleType.create(resolved, elementTypes);
    }
    final PyType builtinCollection = getBuiltinCollection(resolved);
    if (builtinCollection instanceof PyClassType) {
      final PyClassType classType = (PyClassType) builtinCollection;
      return new PyCollectionTypeImpl(classType.getPyClass(), false, elementTypes);
    }
    return null;
  }
Exemplo n.º 4
0
 private SNode searchInSuperTypes(SNode subType, CoercionMatcher superType, boolean isWeak) {
   StructuralNodeSet<?> frontier = new StructuralNodeSet();
   StructuralNodeSet<?> newFrontier = new StructuralNodeSet();
   StructuralNodeSet<?> yetPassed = new StructuralNodeSet();
   frontier.add(subType);
   while (!frontier.isEmpty()) {
     Set<SNode> yetPassedRaw = new THashSet<SNode>();
     // collecting a set of frontier's ancestors
     StructuralNodeSet<?> ancestors = new StructuralNodeSet();
     for (SNode node : frontier) {
       mySubTyping.collectImmediateSuperTypes(node, isWeak, ancestors, null);
       yetPassedRaw.add(node);
     }
     ArrayList<SNode> ancestorsSorted;
     ancestorsSorted = new ArrayList<SNode>(ancestors);
     Collections.sort(
         ancestorsSorted,
         new Comparator<SNode>() {
           @Override
           public int compare(SNode o1, SNode o2) {
             return TypesUtil.depth(o2) - TypesUtil.depth(o1);
           }
         });
     List<SNode> results = new ArrayList<SNode>();
     for (SNode ancestor : ancestorsSorted) {
       if (superType.matchesWith(ancestor)) {
         results.add(ancestor);
       }
     }
     if (!results.isEmpty()) {
       if (results.size() > 1) {
         results = SubtypingUtil.eliminateSuperTypes(results);
       }
       if (!results.isEmpty()) {
         return results.get(0);
       }
     }
     for (SNode passedNodeRaw : yetPassedRaw) {
       yetPassed.add(passedNodeRaw);
     }
     for (SNode passedNode : yetPassed) {
       ancestors.removeStructurally(passedNode);
     }
     for (SNode ancestor : ancestors) {
       Pair<Boolean, SNode> answer =
           getCoerceCacheAnswer(ancestor, superType.getMatchingPattern(), isWeak);
       if (answer != null) {
         if (answer.o1 && answer.o2 == null) {
           // System.out.println("coerce optimized");
           continue;
         }
       }
       newFrontier.addStructurally(ancestor);
       yetPassed.addStructurally(ancestor);
     }
     frontier = newFrontier;
     newFrontier = new StructuralNodeSet();
   }
   return null;
 }
Exemplo n.º 5
0
 /**
  * @param table_list lista de tabelas
  * @param visited_tables lista de tabelas visitadas
  * @param final_table tabela final/pretendida
  */
 public static Node iterativeDepthFirstSearch(
     int[][] initial_table, int[][] final_table, int max_depth) {
   List table_list = new List();
   table_list.addFirst(initial_table, 0, "");
   List visited_tables = new List();
   int[][] current_table = new int[3][3];
   int depth = 0;
   String path = new String();
   while (!table_list.isEmpty()) {
     List child_nodes = new List();
     path = table_list.getPath();
     depth = table_list.getDepth();
     current_table = table_list.remove();
     if (isSolution(current_table, final_table)) return new Node(current_table, depth, path, null);
     visited_tables.addFirst(current_table, depth, path);
     if (depth < max_depth) {
       child_nodes = playDFS(child_nodes, current_table, depth, path);
       // verifica se algum dos filhos já foi visitado
       while (!child_nodes.isEmpty()) {
         int d = child_nodes.getDepth();
         String s = child_nodes.getPath();
         int[][] child_table = child_nodes.remove();
         if (!visited_tables.contains(child_table)) table_list.addFirst(child_table, d, s);
       }
     }
   }
   return iterativeDepthFirstSearch(initial_table, final_table, max_depth + 1);
 }
 @Override
 public void run(ContinuationContext context) {
   final List<Change> changesForPatch;
   try {
     final List<CommittedChangeList> lst = loadSvnChangeListsForPatch(myDescription);
     changesForPatch = CommittedChangesTreeBrowser.collectChanges(lst, true);
     for (Change change : changesForPatch) {
       if (change.getBeforeRevision() != null) {
         preloadRevisionContents(change.getBeforeRevision());
       }
       if (change.getAfterRevision() != null) {
         preloadRevisionContents(change.getAfterRevision());
       }
     }
   } catch (VcsException e) {
     context.handleException(e, true);
     return;
   }
   final List<Change> binaryChanges = filterOutBinary(changesForPatch);
   if (binaryChanges != null && !binaryChanges.isEmpty()) {
     myTheirsBinaryChanges.addAll(binaryChanges);
   }
   if (!changesForPatch.isEmpty()) {
     myTheirsChanges.addAll(changesForPatch);
   }
 }
Exemplo n.º 7
0
  private void purgeQueue() {

    final ReferenceContext refContext = queue.getFirst().ref;

    // divide them up by source
    while (!queue.isEmpty()) {
      VCcontext context = queue.removeFirst();
      for (final VariantContext vc : context.vcs) {
        if (vc.getSource().equals(source1)) sourceVCs1.add(vc);
        else sourceVCs2.add(vc);
      }
    }

    writeAndPurgeAllEqualVariants(sourceVCs1, sourceVCs2, SAME_STATUS);

    if (sourceVCs1.isEmpty()) {
      writeAll(sourceVCs2, source2, null);
    } else if (sourceVCs2.isEmpty()) {
      writeAll(sourceVCs1, source1, null);
    } else {
      resolveByHaplotype(refContext);
    }

    // allow for GC of the data
    sourceVCs1.clear();
    sourceVCs2.clear();
  }
Exemplo n.º 8
0
    /**
     * Set list shown or progress bar show
     *
     * @param shown
     * @param animate
     * @return this fragment
     */
    public ItemListFragment<E> setListShown(final boolean shown, final boolean animate) {
        if (!isUsable()) {
            return this;
        }

        if (shown == listShown) {
            if (shown) {
                // List has already been shown so hide/show the empty view with
                // no fade effect
                if (items.isEmpty()) {
                    hide(listView).show(emptyView);
                } else {
                    hide(emptyView).show(listView);
                }
            }
            return this;
        }

        listShown = shown;

        if (shown) {
            if (!items.isEmpty()) {
                hide(progressBar).hide(emptyView).fadeIn(listView, animate)
                        .show(listView);
            } else {
                hide(progressBar).hide(listView).fadeIn(emptyView, animate)
                        .show(emptyView);
            }
        } else {
            hide(listView).hide(emptyView).fadeIn(progressBar, animate)
                    .show(progressBar);
        }
        return this;
    }
Exemplo n.º 9
0
  public Map<String, CodeRecord> get(String codeTableId) {
    logger.info("加载代码表#" + codeTableId + "的数据...");
    TSysCodeTable codeDic = JpaTool.get(TSysCodeTable.class, codeTableId);
    List<CodeRecord> codes = null;
    if (codeDic == null) {
      List<TSysCodeTable> groupingCodeTables = sysCodeTableDao.getGroupingCodeTables();
      for (TSysCodeTable codeTable : groupingCodeTables) {
        codes = searchCodes(codeTableId, codeTable);
        if (codes.isEmpty() == false) {
          break;
        }
      }

      // 存在排序值为空默认按编码升序排序
      if (codes != null && codes.isEmpty() == false) {
        Map<String, Object> propMap = new HashMap<String, Object>(2);
        propMap.put("order", null);
        propMap.put("order", "");
        List<CodeRecord> list = CollectionQueryTool.orQuery(codes, propMap);
        if (list.isEmpty() == false) {
          codes = CollectionQueryTool.order(codes, Order.asc("code"));
        }
      }
    } else {
      codes = searchCodes(codeTableId, codeDic);
    }
    Map<String, CodeRecord> map = new LinkedCaseInsensitiveMap<CodeRecord>(codes.size());
    for (CodeRecord codeRecord : codes) {
      map.put(codeRecord.getCode(), codeRecord);
    }
    if (map.isEmpty()) {
      logger.warn("代码表#" + codeTableId + "不存在或数据为空!");
    }
    return map;
  }
Exemplo n.º 10
0
  /** Writes data pending message into a specific socket defined by the key */
  private void write(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();

    synchronized (pendingWriteData) {
      List<ByteBuffer> queue = pendingWriteData.get(socketChannel);
      if (queue == null) {
        queue = new ArrayList<>();
        pendingWriteData.put(socketChannel, queue);
      }

      // Write until there's no more data ...
      while (!queue.isEmpty()) {
        ByteBuffer buf = queue.get(0);
        socketChannel.write(buf);
        if (buf.remaining() > 0) {
          logger.finest("Write Buffer Full!");
          break;
        }
        queue.remove(0);
      }

      if (queue.isEmpty()) {
        // All data written, change selector interest
        logger.finest("No more Data to write!");
        key.interestOps(SelectionKey.OP_READ);
      }
    }
  }
  @Override
  public void startElement(String uri, String localName, String qName, Attributes attributes)
      throws SAXException {
    assertSAX(!myParseStack.isEmpty());
    ElementHandlerBase current = myParseStack.get(myParseStack.size() - 1);
    if (mySb.length() > 0) {
      current.characters(mySb.toString().trim(), myPending, myLockBuilder);
      mySb.setLength(0);
    }

    while (true) {
      final boolean createNewChild = current.startElement(uri, localName, qName, attributes);
      if (createNewChild) {
        assertSAX(myElementsMap.containsKey(qName));
        final ElementHandlerBase newChild = myElementsMap.get(qName).get();
        newChild.preAttributesEffect(myDataCallback);
        newChild.updateStatus(attributes, myPending, myLockBuilder);
        newChild.preEffect(myDataCallback);
        myParseStack.add(newChild);
        return;
      } else {
        // go up
        current.postEffect(myDataCallback);
        myParseStack.remove(myParseStack.size() - 1);
        assertSAX(!myParseStack.isEmpty());
        current = myParseStack.get(myParseStack.size() - 1);
      }
    }
  }
Exemplo n.º 12
0
  /**
   * Adds the {@code tags} to the {@code books}.
   *
   * @param realm Instance of Realm to use.
   * @param books List of {@link RBook}s to add tags to.
   * @param tags List {@link RTag}s.
   */
  public static void addTagsToBooks(Realm realm, List<RBook> books, List<RTag> tags) {
    if (books == null || tags == null) throw new IllegalArgumentException("No nulls allowed.");
    if (books.isEmpty() || tags.isEmpty()) return;

    // Get names of new/updated book tags.
    String newBookTagName = Minerva.prefs().getNewBookTag(null);
    String updatedBookTagName = Minerva.prefs().getUpdatedBookTag(null);

    // Sometimes this method is called when we're already in a transaction. We can't nest them.
    boolean isInXactAlready = realm.isInTransaction();
    if (!isInXactAlready) realm.beginTransaction();

    // Loop through books and add tags to them.
    for (int i = books.size() - 1; i >= 0; i--) {
      RBook book = books.get(i);
      for (RTag tag : tags) {
        // If the book doesn't already have the tag,
        if (!book.tags.contains(tag)) {
          // add the tag to the book,
          book.tags.add(tag);
          // and add the book to the tag.
          tag.taggedBooks.add(book);
        }
        // Make sure that we set new/updated state to true if those tags were added (and it wasn't
        // already).
        if (newBookTagName != null && newBookTagName.equals(tag.name) && !book.isNew)
          book.isNew = true;
        if (updatedBookTagName != null && updatedBookTagName.equals(tag.name) && !book.isUpdated)
          book.isUpdated = true;
      }
    }
    // Again, if there's an outer transaction already ongoing, don't finish it here.
    if (!isInXactAlready) realm.commitTransaction();
  }
Exemplo n.º 13
0
 public void run() {
   if (myBook != null) {
     for (BookmarkQuery query = new BookmarkQuery(myBook, 20); ; query = query.next()) {
       final List<Bookmark> thisBookBookmarks = myCollection.bookmarks(query);
       if (thisBookBookmarks.isEmpty()) {
         break;
       }
       myThisBookAdapter.addAll(thisBookBookmarks);
       myAllBooksAdapter.addAll(thisBookBookmarks);
     }
   }
   for (BookmarkQuery query = new BookmarkQuery(20); ; query = query.next()) {
     final List<Bookmark> allBookmarks = myCollection.bookmarks(query);
     if (allBookmarks.isEmpty()) {
       break;
     }
     myAllBooksAdapter.addAll(allBookmarks);
   }
   runOnUiThread(
       new Runnable() {
         public void run() {
           setProgressBarIndeterminateVisibility(false);
         }
       });
 }
  static void logPlugins() {
    List<String> loadedBundled = new ArrayList<String>();
    List<String> disabled = new ArrayList<String>();
    List<String> loadedCustom = new ArrayList<String>();

    for (IdeaPluginDescriptor descriptor : ourPlugins) {
      final String version = descriptor.getVersion();
      String s = descriptor.getName() + (version != null ? " (" + version + ")" : "");
      if (descriptor.isEnabled()) {
        if (descriptor.isBundled() || SPECIAL_IDEA_PLUGIN.equals(descriptor.getName()))
          loadedBundled.add(s);
        else loadedCustom.add(s);
      } else {
        disabled.add(s);
      }
    }

    Collections.sort(loadedBundled);
    Collections.sort(loadedCustom);
    Collections.sort(disabled);

    getLogger().info("Loaded bundled plugins: " + StringUtil.join(loadedBundled, ", "));
    if (!loadedCustom.isEmpty()) {
      getLogger().info("Loaded custom plugins: " + StringUtil.join(loadedCustom, ", "));
    }
    if (!disabled.isEmpty()) {
      getLogger().info("Disabled plugins: " + StringUtil.join(disabled, ", "));
    }
  }
Exemplo n.º 15
0
 protected boolean updateSubAwardBudgetDetails(Budget budget, BudgetSubAwards subAward)
     throws Exception {
   List<String[]> errorMessages = new ArrayList<String[]>();
   boolean success =
       getKcBusinessRulesEngine().applyRules(new BudgetSubAwardsEvent(subAward, budget, ""));
   if (subAward.getNewSubAwardFile().getBytes().length == 0) {
     success = false;
   }
   if (success) {
     getPropDevBudgetSubAwardService()
         .updateSubAwardBudgetDetails(budget, subAward, errorMessages);
   }
   if (!errorMessages.isEmpty()) {
     for (String[] message : errorMessages) {
       String[] messageParameters = null;
       if (message.length > 1) {
         messageParameters = Arrays.copyOfRange(message, 1, message.length);
       }
       if (success) {
         GlobalVariables.getMessageMap()
             .putWarning(Constants.SUBAWARD_FILE_FIELD_NAME, message[0], messageParameters);
       } else {
         GlobalVariables.getMessageMap()
             .putError(Constants.SUBAWARD_FILE_FIELD_NAME, message[0], messageParameters);
       }
     }
   }
   if (success && errorMessages.isEmpty()) {
     GlobalVariables.getMessageMap()
         .putInfo(Constants.SUBAWARD_FILE_FIELD_NAME, Constants.SUBAWARD_FILE_DETAILS_UPDATED);
   }
   return success;
 }
Exemplo n.º 16
0
  /**
   * Removes the {@code tags} from the {@code books}.
   *
   * @param realm Instance of Realm to use.
   * @param books List of {@link RBook}s to remove tags from.
   * @param tags List {@link RTag}s.
   */
  public static void removeTagsFromBooks(Realm realm, List<RBook> books, List<RTag> tags) {
    if (books == null || tags == null) throw new IllegalArgumentException("No nulls allowed.");
    if (books.isEmpty() || tags.isEmpty()) return;

    // Get names of new/updated book tags.
    String newBookTagName = Minerva.prefs().getNewBookTag(null);
    String updatedBookTagName = Minerva.prefs().getUpdatedBookTag(null);

    realm.beginTransaction();
    // Loop through books and remove tags from them.
    for (int i = books.size() - 1; i >= 0; i--) {
      RBook book = books.get(i);
      for (RTag tag : tags) {
        // If the book has the tag, remove it,
        if (book.tags.remove(tag)) {
          // and remove the book from the tag.
          tag.taggedBooks.remove(book);
        }
        // Make sure that we new/updated state if we had those tags removed.
        if (newBookTagName != null && newBookTagName.equals(tag.name)) book.isNew = false;
        if (updatedBookTagName != null && updatedBookTagName.equals(tag.name))
          book.isUpdated = false;
      }
    }
    realm.commitTransaction();
  }
Exemplo n.º 17
0
 @Nullable
 private PyType resolveQualifierType(
     @NotNull List<Token<PyElementType>> tokens,
     @NotNull PyFile file,
     @NotNull TypeEvalContext context,
     @NotNull Map<TextRange, PyType> types,
     @NotNull Map<PyType, TextRange> fullRanges,
     @NotNull Map<PyType, PyImportElement> imports) {
   if (tokens.isEmpty()) {
     return null;
   }
   final Token<PyElementType> firstToken = tokens.get(0);
   final String firstText = firstToken.getText().toString();
   final TextRange firstRange = firstToken.getRange();
   final List<RatedResolveResult> resolveResults = file.multiResolveName(firstText);
   if (resolveResults.isEmpty()) {
     return getImplicitlyResolvedType(tokens, context, types, fullRanges, firstRange);
   }
   final List<PyType> members = Lists.newArrayList();
   for (RatedResolveResult result : resolveResults) {
     final PsiElement resolved = result.getElement();
     PyType type = null;
     if (resolved instanceof PyTargetExpression) {
       type =
           PyTypingTypeProvider.getTypeFromTargetExpression(
               (PyTargetExpression) resolved, context);
     }
     if (type == null && resolved instanceof PyTypedElement) {
       type = context.getType((PyTypedElement) resolved);
     }
     if (type != null) {
       if (!allowResolveToType(type)) {
         continue;
       }
       if (type instanceof PyClassLikeType) {
         type = ((PyClassLikeType) type).toInstance();
       }
       types.put(firstRange, type);
       fullRanges.put(type, firstRange);
       for (PyFromImportStatement fromImportStatement : file.getFromImports()) {
         for (PyImportElement importElement : fromImportStatement.getImportElements()) {
           if (firstText.equals(importElement.getVisibleName())) {
             imports.put(type, importElement);
           }
         }
       }
       for (PyImportElement importElement : file.getImportTargets()) {
         if (firstText.equals(importElement.getVisibleName())) {
           imports.put(type, importElement);
         }
       }
     }
     members.add(type);
   }
   if (!members.isEmpty()) {
     tokens.remove(0);
   }
   return PyUnionType.union(members);
 }
  /**
   * identify additional groups that are not directly attached to amino acids.
   *
   * @param mc {@link ModifiedCompound}.
   * @param chain a {@link Chain}.
   * @return a list of added groups.
   */
  private void identifyAdditionalAttachments(
      ModifiedCompound mc, List<Group> ligands, Map<String, Chain> mapChainIdChain) {
    if (ligands.isEmpty()) {
      return;
    }

    // TODO: should the additional groups only be allowed to the identified
    // ligands or both amino acids and ligands? Currently only on ligands
    // ligands to amino acid bonds for same modification of unknown category
    // will be combined in mergeModComps()
    // TODO: how about chain-chain links?
    List<Group> identifiedGroups = new ArrayList<Group>();
    for (StructureGroup num : mc.getGroups(false)) {
      Group group;
      try {
        // String numIns = "" + num.getResidueNumber();
        // if (num.getInsCode() != null) {
        //	numIns += num.getInsCode();
        // }
        ResidueNumber resNum = new ResidueNumber();
        resNum.setChainId(num.getChainId());
        resNum.setSeqNum(num.getResidueNumber());
        resNum.setInsCode(num.getInsCode());
        // group = chain.getGroupByPDB(numIns);
        group = mapChainIdChain.get(num.getChainId()).getGroupByPDB(resNum);
      } catch (StructureException e) {
        logger.error("Exception: ", e);
        // should not happen
        continue;
      }
      identifiedGroups.add(group);
    }

    int start = 0;

    int n = identifiedGroups.size();
    while (n > start) {
      for (Group group1 : ligands) {
        for (int i = start; i < n; i++) {
          Group group2 = identifiedGroups.get(i);
          if (!identifiedGroups.contains(group1)) {
            List<Atom[]> linkedAtoms =
                StructureUtil.findAtomLinkages(group1, group2, false, bondLengthTolerance);
            if (!linkedAtoms.isEmpty()) {
              for (Atom[] atoms : linkedAtoms) {
                mc.addAtomLinkage(
                    StructureUtil.getStructureAtomLinkage(atoms[0], false, atoms[1], false));
              }
              identifiedGroups.add(group1);
              break;
            }
          }
        }
      }

      start = n;
      n = identifiedGroups.size();
    }
  }
Exemplo n.º 19
0
  @Test
  public void testParameterToPairsWhenNameIsInvalid() throws Exception {
    List<Pair> pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1));
    List<Pair> pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1));

    assertTrue(pairs_a.isEmpty());
    assertTrue(pairs_b.isEmpty());
  }
  @Override
  @SuppressWarnings("deprecation")
  public Object getValue(ELContext context, Object base, Object property) throws ELException {

    // Don't call into the chain unless it's been decorated.
    if (legacyVR instanceof ChainAwareVariableResolver) {
      return null;
    }

    if (base != null) {
      return null;
    }
    if (base == null && property == null) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "base and property"); // ?????
      throw new PropertyNotFoundException(message);
    }
    context.setPropertyResolved(true);
    Object result = null;

    FacesContext facesContext = (FacesContext) context.getContext(FacesContext.class);
    String propString = property.toString();
    Map<String, Object> stateMap = RequestStateManager.getStateMap(facesContext);
    try {
      // If we are already in the midst of an expression evaluation
      // that touched this resolver...
      //noinspection unchecked
      List<String> varNames = (List<String>) stateMap.get(RequestStateManager.REENTRANT_GUARD);
      if (varNames != null && !varNames.isEmpty() && varNames.contains(propString)) {
        // take no action and return.
        context.setPropertyResolved(false);
        return null;
      }
      // Make sure subsequent calls don't take action.
      if (varNames == null) {
        varNames = new ArrayList<>();
        stateMap.put(RequestStateManager.REENTRANT_GUARD, varNames);
      }
      varNames.add(propString);

      result = legacyVR.resolveVariable(facesContext, propString);
    } catch (EvaluationException ex) {
      context.setPropertyResolved(false);
      throw new ELException(ex);
    } finally {
      // Make sure to remove the guard after the call returns
      //noinspection unchecked
      List<String> varNames = (List<String>) stateMap.get(RequestStateManager.REENTRANT_GUARD);
      if (varNames != null && !varNames.isEmpty()) {
        varNames.remove(propString);
      }
      // Make sure that the ELContext "resolved" indicator is set
      // in accordance wth the result of the resolution.
      context.setPropertyResolved(result != null);
    }
    return result;
  }
Exemplo n.º 21
0
  @Test
  public void testCreateOrganizationAndAdminWithConfirmationAndActivation() throws Exception {
    setup.set(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS, "true");
    setup.set(PROPERTIES_NOTIFY_ADMIN_OF_ACTIVATION, "true");
    setup.set(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS, "false");
    setup.set(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION, "true");

    final String orgName = uniqueOrg();
    final String userName = uniqueUsername();
    final String email = uniqueEmail();

    OrganizationOwnerInfo org_owner =
        createOwnerAndOrganization(
            orgName, userName, "Test User", email, "testpassword", false, false);

    assertNotNull(org_owner);

    List<Message> user_inbox = Mailbox.get(email);

    assertFalse(user_inbox.isEmpty());

    Message confirmation = user_inbox.get(0);
    assertEquals("User Account Confirmation: " + email, confirmation.getSubject());

    String token = getTokenFromMessage(confirmation);
    logger.info(token);

    ActivationState state =
        setup.getMgmtSvc().handleConfirmationTokenForAdminUser(org_owner.owner.getUuid(), token);
    assertEquals(ActivationState.CONFIRMED_AWAITING_ACTIVATION, state);

    confirmation = user_inbox.get(1);
    String body =
        ((MimeMultipart) confirmation.getContent()).getBodyPart(0).getContent().toString();
    Boolean subbedEmailed = StringUtils.contains(body, "$");

    assertFalse(subbedEmailed);

    assertEquals("User Account Confirmed", confirmation.getSubject());

    List<Message> sysadmin_inbox = Mailbox.get("*****@*****.**");
    assertFalse(sysadmin_inbox.isEmpty());

    Message activation = sysadmin_inbox.get(0);
    assertEquals("Request For Admin User Account Activation " + email, activation.getSubject());

    token = getTokenFromMessage(activation);
    logger.info(token);

    state = setup.getMgmtSvc().handleActivationTokenForAdminUser(org_owner.owner.getUuid(), token);
    assertEquals(ActivationState.ACTIVATED, state);

    Message activated = user_inbox.get(2);
    assertEquals("User Account Activated", activated.getSubject());

    MockImapClient client = new MockImapClient("mockserver.com", "test-user-2", "somepassword");
    client.processMail();
  }
Exemplo n.º 22
0
  /**
   * Persists a Audit
   *
   * @param object
   * @param persisted
   * @param auditingType
   */
  public void audit(Object object, Object persisted, AuditingType auditingType) {

    try {

      if (isEntity(object)) {

        Field[] fields = object.getClass().getDeclaredFields();
        Method[] methods = object.getClass().getDeclaredMethods();
        Method.setAccessible(methods, true);
        Field.setAccessible(fields, true);

        AbstractAuditing auditing = Configuration.getAbstractAuditing();
        auditing.setIdentifier(Long.valueOf(getId(object).toString()));
        auditing.setEntity(getEntityName(object.getClass()));
        auditing.setAuditingType(auditingType);
        auditing.setEventDate(new Date());
        if (FacesContext.getCurrentInstance() != null) {
          auditing.setIp(FacesUtils.getIP());
        }
        auditing.setAuditClass(object.getClass());
        AbstractAuditingListener listener = Configuration.getAuditingListener();
        if (listener != null) {
          listener.onSave(auditing);
        }

        List<AbstractMetadata> metadatas = null;
        boolean auditPersited = false;
        if (auditingType.equals(AuditingType.INSERT) || auditingType.equals(AuditingType.DELETE)) {
          entityManager.persist(auditing);
          metadatas = getMetadata(object, null, auditing);
          auditPersited = true;
        } else if (auditingType.equals(AuditingType.UPDATE)) {
          metadatas = getMetadata(object, persisted, auditing);
          if (metadatas != null && !metadatas.isEmpty()) {
            entityManager.persist(auditing);
            auditPersited = true;
          }
        }

        auditing.setMetadatas(metadatas);
        // add to context
        if (auditPersited == true) {
          AuditContext context = AuditContext.getCurrentInstance();
          if (context != null) {
            context.setAuditing(object, auditing);
          }
        }

        if (metadatas != null && !metadatas.isEmpty()) {
          for (AbstractMetadata metadata : metadatas) {
            entityManager.persist(metadata);
          }
        }
      }
    } catch (Throwable t) {
      logger.log(Level.SEVERE, t.getMessage(), t);
    }
  }
Exemplo n.º 23
0
  /**
   * Returns a map of colored mana symbol to basic land cards of that color.
   *
   * @param setsToUse which sets to retrieve basic lands from.
   * @return a map of color to basic lands.
   */
  private static Map<String, List<CardInfo>> generateBasicLands(List<String> setsToUse) {

    List<String> landSets = new LinkedList<>();

    // decide from which sets basic lands are taken from
    for (String setCode : setsToUse) {
      ExpansionInfo expansionInfo = ExpansionRepository.instance.getSetByCode(setCode);
      if (expansionInfo.hasBasicLands()) {
        landSets.add(expansionInfo.getCode());
      }
    }

    // if sets have no basic land, take land from block
    if (landSets.isEmpty()) {
      for (String setCode : setsToUse) {
        ExpansionInfo expansionInfo = ExpansionRepository.instance.getSetByCode(setCode);
        List<ExpansionInfo> blockSets =
            ExpansionRepository.instance.getSetsFromBlock(expansionInfo.getBlockName());
        for (ExpansionInfo blockSet : blockSets) {
          if (blockSet.hasBasicLands()) {
            landSets.add(blockSet.getCode());
          }
        }
      }
    }
    // if still no set with lands found, take one by random
    if (landSets.isEmpty()) {
      // if sets have no basic lands and also it has no parent or parent has no lands get last set
      // with lands
      // select a set with basic lands by random
      Random generator = new Random();
      List<ExpansionInfo> basicLandSets =
          ExpansionRepository.instance.getSetsWithBasicLandsByReleaseDate();
      if (basicLandSets.size() > 0) {
        landSets.add(basicLandSets.get(generator.nextInt(basicLandSets.size())).getCode());
      }
    }

    if (landSets.isEmpty()) {
      throw new IllegalArgumentException("No set with basic land was found");
    }

    CardCriteria criteria = new CardCriteria();
    if (!landSets.isEmpty()) {
      criteria.setCodes(landSets.toArray(new String[landSets.size()]));
    }

    Map<String, List<CardInfo>> basicLandMap = new HashMap<>();

    for (ColoredManaSymbol c : ColoredManaSymbol.values()) {
      String landName = DeckGeneratorPool.getBasicLandName(c.toString());
      criteria.rarities(Rarity.LAND).name(landName);
      List<CardInfo> cards = CardRepository.instance.findCards(criteria);
      basicLandMap.put(landName, cards);
    }
    return basicLandMap;
  }
Exemplo n.º 24
0
 public boolean isEmpty() {
   return super.isEmpty()
       && (identifier == null || identifier.isEmpty())
       && (patient == null || patient.isEmpty())
       && (description == null || description.isEmpty())
       && (status == null || status.isEmpty())
       && (notes == null || notes.isEmpty())
       && (concern == null || concern.isEmpty());
 }
 /**
  * Checks that given function has any decorators from {@code abc} module.
  *
  * @param element Python function to check
  * @param context type evaluation context. If it doesn't allow switch to AST, decorators will be
  *     compared by the text of the last component of theirs qualified names.
  * @see PyKnownDecoratorUtil.KnownDecorator
  */
 public static boolean hasAbstractDecorator(
     @NotNull PyDecoratable element, @NotNull TypeEvalContext context) {
   final List<KnownDecorator> knownDecorators = getKnownDecorators(element, context);
   if (knownDecorators.isEmpty()) {
     return false;
   }
   knownDecorators.retainAll(ABSTRACT_DECORATORS);
   return !knownDecorators.isEmpty();
 }
Exemplo n.º 26
0
  void init2ndPass() {
    init2ndPassNamesWithDefaults();

    for (int i = 0; i < properties.size(); i++) {
      Property property = properties.get(i);
      property.setOrdinal(i);
      property.init2ndPass();
      if (property.isPrimaryKey()) {
        propertiesPk.add(property);
      } else {
        propertiesNonPk.add(property);
      }
    }

    if (propertiesPk.size() == 1) {
      pkProperty = propertiesPk.get(0);
      pkType = schema.mapToJavaTypeNullable(pkProperty.getPropertyType());
    } else {
      pkType = "Void";
    }

    propertiesColumns = new ArrayList<Property>(properties);
    for (ToOne toOne : toOneRelations) {
      toOne.init2ndPass();
      Property[] fkProperties = toOne.getFkProperties();
      for (Property fkProperty : fkProperties) {
        if (!propertiesColumns.contains(fkProperty)) {
          propertiesColumns.add(fkProperty);
        }
      }
    }

    for (ToMany toMany : toManyRelations) {
      toMany.init2ndPass();
      // Source Properties may not be virtual, so we do not need the following code:
      // for (Property sourceProperty : toMany.getSourceProperties()) {
      // if (!propertiesColumns.contains(sourceProperty)) {
      // propertiesColumns.add(sourceProperty);
      // }
      // }
    }

    if (active == null) {
      active = schema.isUseActiveEntitiesByDefault();
    }
    active |= !toOneRelations.isEmpty() || !toManyRelations.isEmpty();

    if (hasKeepSections == null) {
      hasKeepSections = schema.isHasKeepSectionsByDefault();
    }

    init2ndPassIndexNamesWithDefaults();

    for (ContentProvider contentProvider : contentProviders) {
      contentProvider.init2ndPass();
    }
  }
Exemplo n.º 27
0
  private Component[][] eliminateUnusedRowsAndColumns(Component[][] table) {
    if (table.length == 0) {
      return table;
    }
    // Could make this into a Set, but I doubt there will be any real gain in performance as these
    // are probably going
    // to be very small.
    List<Integer> rowsToRemove = new ArrayList<Integer>();
    List<Integer> columnsToRemove = new ArrayList<Integer>();

    final int tableRows = table.length;
    final int tableColumns = table[0].length;

    // Scan for unnecessary columns
    columnLoop:
    for (int column = tableColumns - 1; column > 0; column--) {
      for (int row = 0; row < tableRows; row++) {
        if (table[row][column] != table[row][column - 1]) {
          continue columnLoop;
        }
      }
      columnsToRemove.add(column);
    }

    // Scan for unnecessary rows
    rowLoop:
    for (int row = tableRows - 1; row > 0; row--) {
      for (int column = 0; column < tableColumns; column++) {
        if (table[row][column] != table[row - 1][column]) {
          continue rowLoop;
        }
      }
      rowsToRemove.add(row);
    }

    // If there's nothing to remove, just return the same
    if (rowsToRemove.isEmpty() && columnsToRemove.isEmpty()) {
      return table;
    }

    // Build a new table with rows & columns eliminated
    Component[][] newTable = new Component[tableRows - rowsToRemove.size()][];
    int insertedRowCounter = 0;
    for (int row = 0; row < tableRows; row++) {
      Component[] newColumn = new Component[tableColumns - columnsToRemove.size()];
      int insertedColumnCounter = 0;
      for (int column = 0; column < tableColumns; column++) {
        if (columnsToRemove.contains(column)) {
          continue;
        }
        newColumn[insertedColumnCounter++] = table[row][column];
      }
      newTable[insertedRowCounter++] = newColumn;
    }
    return newTable;
  }
Exemplo n.º 28
0
  private void resolveByHaplotype(final ReferenceContext refContext) {

    final byte[] source1Haplotype = generateHaplotype(sourceVCs1, refContext);
    final byte[] source2Haplotype = generateHaplotype(sourceVCs2, refContext);

    final SWPairwiseAlignment swConsensus1 =
        new SWPairwiseAlignment(
            refContext.getBases(), source1Haplotype, SW_MATCH, SW_MISMATCH, SW_GAP, SW_GAP_EXTEND);
    final SWPairwiseAlignment swConsensus2 =
        new SWPairwiseAlignment(
            refContext.getBases(), source2Haplotype, SW_MATCH, SW_MISMATCH, SW_GAP, SW_GAP_EXTEND);

    // protect against SW failures
    if (swConsensus1.getCigar().toString().contains("S")
        || swConsensus1.getCigar().getReferenceLength() < 20
        || swConsensus2.getCigar().toString().contains("S")
        || swConsensus2.getCigar().getReferenceLength() < 20) {
      // TODO -- handle errors appropriately
      logger.debug("Bad SW alignment; aborting at " + refContext.getLocus());
      return;
    }

    // order results by start position
    final TreeMap<Integer, VariantContext> source1Map =
        new TreeMap<Integer, VariantContext>(
            HaplotypeCallerGenotypingEngine.generateVCsFromAlignment(
                new Haplotype(source1Haplotype, false, 0, swConsensus1.getCigar()),
                refContext.getBases(),
                refContext.getWindow(),
                source1));
    final TreeMap<Integer, VariantContext> source2Map =
        new TreeMap<Integer, VariantContext>(
            HaplotypeCallerGenotypingEngine.generateVCsFromAlignment(
                new Haplotype(source2Haplotype, false, 0, swConsensus2.getCigar()),
                refContext.getBases(),
                refContext.getWindow(),
                source2));
    if (source1Map.size() == 0 || source2Map.size() == 0) {
      // TODO -- handle errors appropriately
      logger.debug("No source alleles; aborting at " + refContext.getLocus());
      return;
    }

    // create lists and test for equality
    final List<VariantContext> source1Alleles = new ArrayList<VariantContext>(source1Map.values());
    final List<VariantContext> source2Alleles = new ArrayList<VariantContext>(source2Map.values());

    writeAndPurgeAllEqualVariants(source1Alleles, source2Alleles, SAME_BY_HAPLOTYPE_STATUS);
    if (source1Alleles.isEmpty()) {
      writeAll(source2Alleles, source2, null);
    } else if (source2Alleles.isEmpty()) {
      writeAll(source1Alleles, source1, null);
    } else {
      writeDifferences(source1Alleles, source2Alleles);
    }
  }
  @NotNull
  @SuppressWarnings("Duplicates")
  private Collection<String> checkWatchable(
      String reportedPath, boolean isExact, boolean fastPath) {
    if (reportedPath == null) return Collections.emptyList();

    List<String> flatWatchRoots = myFlatWatchRoots;
    List<String> recursiveWatchRoots = myRecursiveWatchRoots;
    if (flatWatchRoots.isEmpty() && recursiveWatchRoots.isEmpty()) return Collections.emptyList();

    List<Pair<String, String>> mapping = myMapping;
    Collection<String> affectedPaths = new SmartList<String>(reportedPath);
    for (Pair<String, String> map : mapping) {
      if (FileUtil.startsWith(reportedPath, map.first)) {
        affectedPaths.add(map.second + reportedPath.substring(map.first.length()));
      } else if (FileUtil.startsWith(reportedPath, map.second)) {
        affectedPaths.add(map.first + reportedPath.substring(map.second.length()));
      }
    }

    Collection<String> changedPaths = new SmartList<String>();
    ext:
    for (String path : affectedPaths) {
      if (fastPath && !changedPaths.isEmpty()) break;

      for (String root : flatWatchRoots) {
        if (FileUtil.namesEqual(path, root)) {
          changedPaths.add(path);
          continue ext;
        }
        if (isExact) {
          String parentPath = new File(path).getParent();
          if (parentPath != null && FileUtil.namesEqual(parentPath, root)) {
            changedPaths.add(path);
            continue ext;
          }
        }
      }

      for (String root : recursiveWatchRoots) {
        if (FileUtil.startsWith(path, root)) {
          changedPaths.add(path);
          continue ext;
        }
        if (!isExact) {
          String parentPath = new File(root).getParent();
          if (parentPath != null && FileUtil.namesEqual(path, parentPath)) {
            changedPaths.add(root);
            continue ext;
          }
        }
      }
    }

    return changedPaths;
  }
Exemplo n.º 30
0
  @Test
  public void shouldNotSaveMotherOrChildFormsIfNullAndEmpty() {
    careService.processAndSaveForms(null, new ArrayList<Map<String, String>>());

    List<MotherCase> mothers = template.loadAll(MotherCase.class);
    assertTrue(mothers.isEmpty());

    List<ChildCase> children = template.loadAll(ChildCase.class);
    assertTrue(children.isEmpty());
  }