Example usage for java.util HashSet contains

List of usage examples for java.util HashSet contains

Introduction

In this page you can find the example usage for java.util HashSet contains.

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:com.microsoft.azure.storage.table.TableEncryptionPolicy.java

/**
 * Return a decrypted entity. This method is used for decrypting entity properties.
 *//*from  w ww .  jav a2 s  .c o m*/
HashMap<String, EntityProperty> decryptEntity(HashMap<String, EntityProperty> properties,
        HashSet<String> encryptedPropertyDetailsSet, String partitionKey, String rowKey,
        Key contentEncryptionKey, EncryptionData encryptionData) throws StorageException {
    HashMap<String, EntityProperty> decryptedProperties = new HashMap<String, EntityProperty>();

    try {
        switch (encryptionData.getEncryptionAgent().getEncryptionAlgorithm()) {
        case AES_CBC_256:
            Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");

            for (Map.Entry<String, EntityProperty> kvp : properties.entrySet()) {
                if (kvp.getKey() == Constants.EncryptionConstants.TABLE_ENCRYPTION_KEY_DETAILS
                        || kvp.getKey() == Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS) {
                    // Do nothing. Do not add to the result properties.
                } else if (encryptedPropertyDetailsSet.contains(kvp.getKey())) {
                    MessageDigest digest = MessageDigest.getInstance("SHA-256");
                    byte[] columnIVFull = digest
                            .digest(Utility.binaryAppend(encryptionData.getContentEncryptionIV(),
                                    (partitionKey + rowKey + kvp.getKey()).getBytes(Constants.UTF8_CHARSET)));

                    byte[] columnIV = new byte[16];
                    System.arraycopy(columnIVFull, 0, columnIV, 0, 16);

                    myAes.init(Cipher.DECRYPT_MODE, contentEncryptionKey, new IvParameterSpec(columnIV));

                    byte[] src = kvp.getValue().getValueAsByteArray();
                    byte[] dest = myAes.doFinal(src, 0, src.length);
                    String destString = new String(dest, Constants.UTF8_CHARSET);
                    decryptedProperties.put(kvp.getKey(), new EntityProperty(destString));
                } else {
                    decryptedProperties.put(kvp.getKey(), kvp.getValue());
                }
            }
            return decryptedProperties;

        default:
            throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                    SR.INVALID_ENCRYPTION_ALGORITHM, null);
        }
    } catch (StorageException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR, SR.DECRYPTION_LOGIC_ERROR, ex);
    }
}

From source file:annis.visualizers.iframe.partitur.PartiturVisualizer.java

@Override
public void writeOutput(VisualizerInput input, Writer writer) {
    try {//  w ww .  j a va2  s. com

        nodes = input.getResult().getGraph().getNodes();
        token = input.getResult().getGraph().getTokens();

        // get partitur
        PartiturParser partitur = new PartiturParser(input.getResult().getGraph(), input.getNamespace());

        // check right to left
        boolean isRTL = checkRTL(input.getResult().getTokenList());

        List<String> tierNames = new LinkedList<String>(partitur.getKnownTiers());
        Collections.sort(tierNames);

        // get keys that are allowed to select
        LinkedHashSet<String> keys = new LinkedHashSet<String>();
        String mapping = input.getMappings().getProperty("annos");
        if (mapping == null) {
            // default to the alphabetical order
            keys.addAll(partitur.getNameslist());
        } else {
            String[] splitted = mapping.split(",");
            for (int k = 0; k < splitted.length; k++) {
                String s = splitted[k].trim();
                if (partitur.getNameslist().contains(s)) {
                    keys.add(s);
                }
            }
        }

        writer.append(
                "<!DOCTYPE html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
        writer.append("<link href=\"" + input.getResourcePath("jbar.css")
                + "\" rel=\"stylesheet\" type=\"text/css\" >");
        writer.append("<link href=\"" + input.getResourcePath("jquery.tooltip.css")
                + "\" rel=\"stylesheet\" type=\"text/css\" >");
        writer.append("<link href=\"" + input.getResourcePath("jquery.noty.css")
                + "\" rel=\"stylesheet\" type=\"text/css\" >");
        writer.append("<link href=\"" + input.getResourcePath("partitur.css")
                + "\" rel=\"stylesheet\" type=\"text/css\" >");
        writer.append("<script src=\"" + input.getResourcePath("jquery-1.7.1.min.js") + "\"></script>");
        writer.append("<script src=\"" + input.getResourcePath("jquery.jbar.js") + "\"></script>");
        writer.append("<script src=\"" + input.getResourcePath("jquery.tooltip.min.js") + "\"></script>");
        writer.append("<script src=\"" + input.getResourcePath("jquery.noty.js") + "\"></script>");
        writer.append("<script>");
        writer.append(convertToJavacSriptArray(new LinkedList<String>()));
        writer.append("\nvar levelNames = [");
        int i = 0;
        for (String levelName : tierNames) {
            if (keys.contains(levelName)) {
                writer.append((i++ > 0 ? ", " : "") + "\"" + levelName + "\"");
            }
        }
        writer.append("];\n</script>");
        writer.append("<script type=\"text/javascript\" src=\"" + input.getResourcePath("PartiturVisualizer.js")
                + "\"></script>");

        writer.append("</head>");
        writer.append("<body>\n");

        writer.append("<ul id=\"toolbar\"></ul>");
        writer.append("<div id=\"partiture\">");

        if (isRTL) {
            writer.append("<table class=\"partitur_table\" dir=\"rtl\">\n");
        } else {
            writer.append("<table class=\"partitur_table\")\">\n");
        }

        for (String tier : keys) {
            List<String> indexlist = new ArrayList<String>();

            for (List<PartiturParser.ResultElement> span : partitur.getResultlist()) {
                for (PartiturParser.ResultElement strr : span) {
                    if (strr.getName().equals(tier) && !indexlist.contains(strr.getId())) {
                        indexlist.add(strr.getId());
                    }
                }
            }

            String[] currentarray; //Saves annotation-ids of the current row

            while (!indexlist.isEmpty()) { //Create Rows until all Annotations fit in
                List<String> currentdontuselist = new LinkedList<String>(); //Lists all Annotations that should not be added to the current row
                writer.append("<tr class=\"level_" + tier + "\"><th>" + tier + "</th>"); //new row

                currentarray = new String[partitur.getResultlist().size()];
                for (int iterator3 = 0; iterator3 < partitur.getResultlist().size(); iterator3++) {
                    currentarray[iterator3] = null;
                }

                int spanCounter = 0;
                for (List<PartiturParser.ResultElement> span : partitur.getResultlist()) { //for each Token
                    for (PartiturParser.ResultElement annotationelement : span) { // for each Annotation annotationelement of that Token
                        if (indexlist.contains(annotationelement.getId())
                                && !currentdontuselist.contains(annotationelement.getId())) {
                            boolean neu = false; //Should the Annotation be added?
                            if (currentarray[spanCounter] == null) {
                                indexlist.remove(annotationelement.getId());
                                currentarray[spanCounter] = annotationelement.getId();
                                neu = true;
                            }
                            //get all other annotationelement.id (earlier Ids => dontuselist)
                            int span2Counter = 0;
                            for (List<PartiturParser.ResultElement> span2 : partitur.getResultlist()) {
                                for (PartiturParser.ResultElement strr2 : span2) {
                                    if (strr2.getId().equals(annotationelement.getId()) && neu) //{
                                    {
                                        if (currentarray[span2Counter] == null) {
                                            currentarray[span2Counter] = annotationelement.getId();
                                        }
                                    }
                                    if (span2Counter <= spanCounter
                                            && !currentdontuselist.contains(strr2.getId())) {
                                        currentdontuselist.add(strr2.getId());
                                    }
                                }
                                span2Counter++;
                            }
                            //break; //Not needed?
                        }
                    }
                    spanCounter++;
                }

                //Write Row
                int length = 1;
                for (int iterator5 = 0; iterator5 < currentarray.length; iterator5 += length) {
                    StringBuffer tokenIdsArray = new StringBuffer();
                    StringBuffer eventIdsArray = new StringBuffer();
                    boolean unused = true;
                    length = 1;
                    if (currentarray[iterator5] == null) { //empty entry
                        writer.append("<td></td>");
                    } else {
                        PartiturParser.ResultElement element = null;
                        HashSet<Integer> common = new HashSet<Integer>();
                        boolean found = false;
                        int outputSpanCounter = 0;
                        for (List<PartiturParser.ResultElement> outputSpan : partitur.getResultlist()) {
                            for (PartiturParser.ResultElement strr : outputSpan) {
                                if (strr.getId().equals(currentarray[iterator5])) {
                                    if (!found) {
                                        element = strr;
                                    }
                                    if (!common.contains(outputSpanCounter)) {
                                        common.add(outputSpanCounter);
                                    }
                                    found = true;
                                    if (unused) {
                                        tokenIdsArray.append("" + strr.getId() + "_" + outputSpanCounter);
                                        eventIdsArray
                                                .append(tier + "_" + strr.getId() + "_" + outputSpanCounter);
                                        unused = false;
                                    } else {
                                        tokenIdsArray.append("," + strr.getId() + "_" + outputSpanCounter);
                                        eventIdsArray.append(
                                                "," + tier + "_" + strr.getId() + "_" + outputSpanCounter);
                                    }
                                }
                            }
                            outputSpanCounter++;
                        }
                        for (int iterator7 = iterator5 + 1; iterator7 < currentarray.length; iterator7++) {
                            if (common.contains(iterator7)) {
                                length++;
                            } else {
                                break;
                            }
                        }

                        for (int iterator8 = 0; iterator8 < currentarray.length; iterator8++) {
                            if (common.contains(iterator8)) {
                                Long id = ((PartiturParser.Token) partitur.getToken().toArray()[iterator8])
                                        .getId();
                                if (unused) {
                                    tokenIdsArray.append("" + id);
                                    eventIdsArray.append(tier + "_" + id);
                                    unused = false;
                                } else {
                                    tokenIdsArray.append("," + id);
                                    eventIdsArray.append("," + tier + "_" + id);
                                }
                            }
                        }

                        String color = "black";
                        if (input.getMarkableExactMap().containsKey("" + element.getNodeId())) {
                            color = input.getMarkableExactMap().get("" + element.getNodeId());
                        }
                        if (found) {
                            writer.append("<td class=\"single_event\" " + "id=\"event_" + tier + "_"
                                    + element.getId() + "_" + iterator5 + "\" " + "style=\"color:" + color
                                    + ";\" " + "colspan=" + length + " " + "annis:tokenIds=\"" + tokenIdsArray
                                    + "\" " + "annis:eventIds=\"" + eventIdsArray + "\" " + "title=\""
                                    + partitur.namespaceForTier(tier) + ":" + tier + " = "
                                    + StringEscapeUtils.escapeXml(element.getValue()) + "\"  " //tier =tier, event.getValue()= element.name
                                    + "onMouseOver=\"toggleAnnotation(this, true);\" "
                                    + "onMouseOut=\"toggleAnnotation(this, false);\" "
                                    + addTimeAttribute(element.getNodeId()) + ">" + element.getValue()
                                    + "</td>");
                        } else {
                            writer.append("<td class=\"single_event\" >error</td>");
                        }
                    }
                }
                writer.append("</tr>"); //finish row
            }
        }

        // add token itself
        writer.append("<tr><th>tok</th>");

        for (PartiturParser.Token token : partitur.getToken()) {
            String color = "black";

            if (input.getMarkableExactMap().containsKey("" + token.getId())) {
                color = input.getMarkableExactMap().get("" + token.getId());
            }
            writer.append("<td class=\"tok\" style=\"color:" + color + ";\" " + "id=\"token_" + token.getId()
                    + "\" " + ">" + token.getValue() + "</td>");
        }
        writer.append("</tr>");

        writer.append("</table>\n");
        writer.append("</div>\n");
        writer.append("</body></html>");

    } catch (Exception ex) {
        log.error(null, ex);
        try {
            String annisLine = "";
            for (int i = 0; i < ex.getStackTrace().length; i++) {
                if (ex.getStackTrace()[i].getClassName().startsWith("annis.")) {
                    annisLine = ex.getStackTrace()[i].toString();
                }
            }

            writer.append("<html><body>Error occured (" + ex.getClass().getName() + "): "
                    + ex.getLocalizedMessage() + "<br/>" + annisLine + "</body></html>");
        } catch (IOException ex1) {
            log.error(null, ex1);
        }
    }
}

From source file:com.mission_base.arviewer_android.viewer.ArvosPoi.java

/**
 * Returns the list of all objects to be drawn for the augment in the opengl
 * view.//from w ww.j a  v a2 s .  com
 * 
 * @param time
 *            Returns the list of all objects to be drawn for the augment in
 *            the opengl view.
 * @param result
 *            The list to add the resulting objects to.
 * @param arvosObjects
 *            The previous list of objects.
 */
public void getObjects(long time, List<ArvosObject> result, List<ArvosObject> arvosObjects) {
    float deviceLatitude = mInstance.mLatitude;
    float deviceLongitude = mInstance.mLongitude;
    float poiLatitude = 0f;
    float poiLongitude = 0f;

    float offsetX = 0f;
    float offsetZ = 0f;

    if (mLatitude != null) {
        poiLatitude = mLatitude;
        Location currentLocation = new Location(LocationManager.GPS_PROVIDER);
        currentLocation.setLatitude(deviceLatitude);

        Location poiLocation = new Location(LocationManager.GPS_PROVIDER);
        poiLocation.setLatitude(poiLatitude);

        offsetZ = currentLocation.distanceTo(poiLocation);
        if (deviceLatitude > poiLatitude) {
            if (offsetZ < 0) {
                offsetZ = -offsetZ;
            }
        } else {
            if (offsetZ > 0) {
                offsetZ = -offsetZ;
            }
        }

    }
    if (mLongitude != null) {
        poiLongitude = mLongitude;
        Location currentLocation = new Location(LocationManager.GPS_PROVIDER);
        currentLocation.setLongitude(deviceLongitude);

        Location poiLocation = new Location(LocationManager.GPS_PROVIDER);
        poiLocation.setLongitude(poiLongitude);

        offsetX = currentLocation.distanceTo(poiLocation);
        if (deviceLongitude > poiLongitude) {
            if (offsetX > 0) {
                offsetX = -offsetX;
            }
        } else {
            if (offsetX < 0) {
                offsetX = -offsetX;
            }
        }
    }

    HashSet<String> objectsToDraw = new HashSet<String>();
    for (ArvosPoiObject poiObject : mPoiObjects) {
        ArvosObject arvosObject = poiObject.getObject(time, arvosObjects);
        if (arvosObject != null) {
            arvosObject.mPosition[0] += offsetX;
            arvosObject.mPosition[2] += offsetZ;

            objectsToDraw.add(arvosObject.mName);
            result.add(arvosObject);
        }
    }

    synchronized (mObjectsClicked) {
        for (ArvosPoiObject poiObject : mObjectsClicked) {
            poiObject.onClick();
        }
        mObjectsClicked.clear();
    }

    for (ArvosPoiObject poiObject : mObjectsToDeactivate) {
        poiObject.stop();
    }
    mObjectsToDeactivate.clear();

    for (ArvosPoiObject poiObject : mObjectsToStart) {
        poiObject.start(time);

        if (!objectsToDraw.contains(poiObject.mName)) {
            ArvosObject arvosObject = poiObject.getObject(time, arvosObjects);
            if (arvosObject != null) {
                objectsToDraw.add(arvosObject.mName);
                result.add(arvosObject);
            }
        }
    }
    mObjectsToStart.clear();
}

From source file:com.aimluck.eip.mail.util.ALMailUtils.java

/**
 * ??1?????/* ww  w .j a  v  a 2 s  .c  o m*/
 *
 * @param addresses
 * @return
 */
public static String getAddressString(Address[] addresses) {
    if (addresses == null || addresses.length <= 0) {
        return "";
    }
    HashSet<String> foundAddress = new HashSet<String>();

    StringBuffer sb = new StringBuffer();
    InternetAddress addr = null;
    int length = addresses.length;
    for (int i = 0; i < length; i++) {
        addr = (InternetAddress) addresses[i];
        if (foundAddress.contains(addr.getAddress())) {
            continue;
        }
        foundAddress.add(addr.getAddress());

        if (addr.getPersonal() != null) {
            String personaladdr = getOneString(getTokens(addr.getPersonal(), "\r\n"), "");
            sb.append(personaladdr).append(" <").append(addr.getAddress()).append(">, ");
        } else {
            sb.append(addr.getAddress()).append(", ");
        }
    }
    String addressStr = sb.toString();
    return addressStr.substring(0, addressStr.length() - 2);
}

From source file:monasca.thresh.infrastructure.persistence.hibernate.AlarmSqlImpl.java

@SuppressWarnings("unchecked")
private void getAlarmedMetrics(final StatelessSession session, final Map<String, Alarm> alarmMap,
        final Map<String, String> tenantIdMap, final LookupHelper binder) {

    String rawHQLQuery = "select a.id, md.name as metric_def_name, mdg.id.name, mdg.value, mdg.id.dimensionSetId from MetricDefinitionDb as md, "
            + "MetricDefinitionDimensionsDb as mdd, " + "AlarmMetricDb as am, " + "AlarmDb as a, "
            + "MetricDimensionDb as mdg where md.id = mdd.metricDefinition.id and mdd.id = am.alarmMetricId.metricDefinitionDimensions.id and "
            + "am.alarmMetricId.alarm.id = a.id and mdg.id.dimensionSetId = mdd.metricDimensionSetId and %s";

    final Query query = binder.apply(session.createQuery(binder.formatHQL(rawHQLQuery)));
    final List<Object[]> metricRows = query.list();
    final HashSet<String> existingAlarmId = Sets.newHashSet();
    final Map<String, List<MetricDefinition>> alarmMetrics = this.getAlarmedMetrics(metricRows);

    for (final Object[] row : metricRows) {
        final String alarmId = (String) row[ALARM_ID];
        final Alarm alarm = alarmMap.get(alarmId);
        // This shouldn't happen but it is possible an Alarm gets created after the AlarmDefinition is
        // marked deleted and any existing alarms are deleted but before the Threshold Engine gets the
        // AlarmDefinitionDeleted message
        if (alarm == null) {
            continue;
        }//from www  .  j a  v a 2s . c  o m
        if (!existingAlarmId.contains(alarmId)) {
            List<MetricDefinition> mdList = alarmMetrics.get(alarmId);
            for (MetricDefinition md : mdList) {
                alarm.addAlarmedMetric(new MetricDefinitionAndTenantId(md, tenantIdMap.get(alarmId)));
            }

        }
        existingAlarmId.add(alarmId);
    }
}

From source file:edu.cens.loci.ui.widget.GenericEditorView.java

/**
 * Prepare this editor using the given {@link DataKind} for defining
 * structure and {@link ValuesDelta} describing the content to edit.
 *///from  ww  w .  jav a2s  .  c  o  m
public void setValues(DataKind kind, ValuesDelta entry, EntityDelta state, boolean readOnly,
        ViewIdGenerator vig) {
    mKind = kind;
    mEntry = entry;
    mState = state;
    mReadOnly = readOnly;
    mViewIdGenerator = vig;

    setId(vig.getId(state, kind, entry, ViewIdGenerator.NO_VIEW_INDEX));

    final boolean enabled = !readOnly;

    //Log.d(TAG, "setValues: kind=" + mKind.mimeType);

    if (!entry.isVisible()) {
        // Hide ourselves entirely if deleted
        setVisibility(View.GONE);
        return;
    } else {
        setVisibility(View.VISIBLE);
    }

    // Display label selector if multiple types available
    final boolean hasTypes = EntityModifier.hasEditTypes(kind);
    mLabel.setVisibility(hasTypes ? View.VISIBLE : View.GONE);
    mLabel.setEnabled(enabled);
    if (hasTypes) {
        mType = EntityModifier.getCurrentType(entry, kind);
        rebuildLabel();
    }

    // Build out set of fields
    mFields.removeAllViews();
    boolean hidePossible = false;
    int n = 0;

    if (mKind.mimeType.equals(WifiFingerprint.CONTENT_ITEM_TYPE)) {

        //Log.d(TAG, "setValues: Wifi");

        for (EditField field : kind.fieldList) {
            Button fieldView = (Button) mInflater.inflate(RES_WIFI_FIELD, mFields, false);

            mWifiFieldButtonId = vig.getId(state, kind, entry, n++);

            fieldView.setId(mWifiFieldButtonId);

            final String column = field.column;
            final String value = entry.getAsString(column);
            fieldView.setText("Fingerprint on " + MyDateUtils.getAbrv_MMM_d_h_m(new Long(value)));

            final String extra1column = field.extra1;
            final String extra1value = entry.getAsString(extra1column);
            try {
                mWifiFingerprint = new LociWifiFingerprint(extra1value);
                mWifiFingerprintTimeStamp = MyDateUtils.getDateFormatLong(new Long(value));
            } catch (JSONException e) {
                MyLog.e(LociConfig.D.JSON, TAG, "LociWifiFingerprint parsing failed");
                e.printStackTrace();
            }

            // Hide field when empty and optional value
            final boolean couldHide = (field.optional);
            final boolean willHide = (mHideOptional && couldHide);
            fieldView.setVisibility(willHide ? View.GONE : View.VISIBLE);
            fieldView.setEnabled(enabled);
            hidePossible = hidePossible || couldHide;

            fieldView.setOnClickListener(this);

            mFields.addView(fieldView);
        }
    } else if (mKind.mimeType.equals(Keyword.CONTENT_ITEM_TYPE)) {

        //Log.d(TAG, "setValues: Keywords");

        for (EditField field : kind.fieldList) {

            AutoCompleteTextView fieldView = (AutoCompleteTextView) mInflater.inflate(RES_AUTOCOMPLETE_FIELD,
                    mFields, false);
            fieldView.setId(vig.getId(state, kind, entry, n++));
            if (field.titleRes > 0) {
                fieldView.setHint(field.titleRes);
            }
            int inputType = field.inputType;
            fieldView.setInputType(inputType);
            fieldView.setMinLines(field.minLines);

            // Read current value from state
            final String column = field.column;
            final String value = entry.getAsString(column);
            fieldView.setText(value);

            // Prepare listener for writing changes
            fieldView.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    // Trigger event for newly changed value
                    onFieldChanged(column, s.toString());
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });

            // Hide field when empty and optional value
            final boolean couldHide = (field.optional);
            final boolean willHide = (mHideOptional && couldHide);
            fieldView.setVisibility(willHide ? View.GONE : View.VISIBLE);
            fieldView.setEnabled(enabled);
            hidePossible = hidePossible || couldHide;

            String[] usedKeywords = getResources().getStringArray(R.array.keyword_default);

            LociDbUtils myDb = new LociDbUtils(getContext());
            ArrayList<String> suggestedKeywords = myDb.getSavedKeywords();
            HashSet<String> suggestedKeywordsSet = new HashSet<String>();

            for (String keyword : suggestedKeywords) {
                suggestedKeywordsSet.add(keyword);
            }

            //Log.d(TAG, "size of usedKeywords : " + usedKeywords.length);
            //Log.d(TAG, "size of suggestedKeywords : " + suggestedKeywords.size());

            for (String usedKeyword : usedKeywords) {
                if (!suggestedKeywordsSet.contains(usedKeyword))
                    suggestedKeywords.add(usedKeyword);
            }

            //Log.d(TAG, "size of suggestedKeywords : " + suggestedKeywords.size());

            Collections.sort(suggestedKeywords);

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getContext(),
                    R.layout.item_suggestion_list, suggestedKeywords);
            fieldView.setAdapter(adapter);
            fieldView.setThreshold(0);

            mFields.addView(fieldView);
        }

    } else {

        //Log.d(TAG, "General Types...");

        for (EditField field : kind.fieldList) {
            // Inflate field from definition
            EditText fieldView = (EditText) mInflater.inflate(RES_FIELD, mFields, false);
            fieldView.setId(vig.getId(state, kind, entry, n++));
            if (field.titleRes > 0) {
                fieldView.setHint(field.titleRes);
            }
            int inputType = field.inputType;
            fieldView.setInputType(inputType);
            if (inputType == InputType.TYPE_CLASS_PHONE) {
                fieldView.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
            }
            fieldView.setMinLines(field.minLines);

            // Read current value from state
            final String column = field.column;
            final String value = entry.getAsString(column);
            fieldView.setText(value);

            //Log.d(TAG, "setValues: column=" + column);
            //Log.d(TAG, "setValues: value=" + value);

            // Prepare listener for writing changes
            fieldView.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    // Trigger event for newly changed value
                    onFieldChanged(column, s.toString());
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });

            // Hide field when empty and optional value
            final boolean couldHide = (field.optional);
            final boolean willHide = (mHideOptional && couldHide);
            fieldView.setVisibility(willHide ? View.GONE : View.VISIBLE);
            fieldView.setEnabled(enabled);
            hidePossible = hidePossible || couldHide;

            mFields.addView(fieldView);
        }
    }

    // When hiding fields, place expandable
    if (hidePossible) {
        mMore.setVisibility(mHideOptional ? View.VISIBLE : View.GONE);
        mLess.setVisibility(mHideOptional ? View.GONE : View.VISIBLE);
    } else {
        mMore.setVisibility(View.GONE);
        mLess.setVisibility(View.GONE);
    }
    mMore.setEnabled(enabled);
    mLess.setEnabled(enabled);
}

From source file:edu.uci.ics.hyracks.algebricks.rewriter.rules.IntroduceProjectsRule.java

protected boolean introduceProjects(AbstractLogicalOperator parentOp, int parentInputIndex,
        Mutable<ILogicalOperator> opRef, Set<LogicalVariable> parentUsedVars, IOptimizationContext context)
        throws AlgebricksException {
    AbstractLogicalOperator op = (AbstractLogicalOperator) opRef.getValue();
    boolean modified = false;

    usedVars.clear();//from   w  ww  .j a v a 2 s  .  co  m
    VariableUtilities.getUsedVariables(op, usedVars);

    // In the top-down pass, maintain a set of variables that are used in op and all its parents.
    HashSet<LogicalVariable> parentsUsedVars = new HashSet<LogicalVariable>();
    parentsUsedVars.addAll(parentUsedVars);
    parentsUsedVars.addAll(usedVars);

    // Descend into children.        
    for (int i = 0; i < op.getInputs().size(); i++) {
        Mutable<ILogicalOperator> inputOpRef = op.getInputs().get(i);
        if (introduceProjects(op, i, inputOpRef, parentsUsedVars, context)) {
            modified = true;
        }
    }

    if (modified) {
        context.computeAndSetTypeEnvironmentForOperator(op);
    }
    // In the bottom-up pass, determine which live variables are not used by op's parents.
    // Such variables are be projected away.
    liveVars.clear();
    VariableUtilities.getLiveVariables(op, liveVars);
    producedVars.clear();
    VariableUtilities.getProducedVariables(op, producedVars);
    liveVars.removeAll(producedVars);

    projectVars.clear();
    for (LogicalVariable liveVar : liveVars) {
        if (parentsUsedVars.contains(liveVar)) {
            projectVars.add(liveVar);
        }
    }

    // Some of the variables that are live at this op are not used above.
    if (projectVars.size() != liveVars.size()) {
        // Add a project operator under each of op's qualifying input branches.
        for (int i = 0; i < op.getInputs().size(); i++) {
            ILogicalOperator childOp = op.getInputs().get(i).getValue();
            liveVars.clear();
            VariableUtilities.getLiveVariables(childOp, liveVars);
            List<LogicalVariable> vars = new ArrayList<LogicalVariable>();
            vars.addAll(projectVars);
            // Only retain those variables that are live in the i-th input branch.
            vars.retainAll(liveVars);
            if (vars.size() != liveVars.size()) {
                ProjectOperator projectOp = new ProjectOperator(vars);
                projectOp.getInputs().add(new MutableObject<ILogicalOperator>(childOp));
                op.getInputs().get(i).setValue(projectOp);
                context.computeAndSetTypeEnvironmentForOperator(projectOp);
                modified = true;
            }
        }
    } else if (op.getOperatorTag() == LogicalOperatorTag.PROJECT) {
        // Check if the existing project has become useless.
        liveVars.clear();
        VariableUtilities.getLiveVariables(op.getInputs().get(0).getValue(), liveVars);
        ProjectOperator projectOp = (ProjectOperator) op;
        List<LogicalVariable> projectVars = projectOp.getVariables();
        if (liveVars.size() == projectVars.size() && liveVars.containsAll(projectVars)) {
            boolean eliminateProject = true;
            // For UnionAll the variables must also be in exactly the correct order.
            if (parentOp.getOperatorTag() == LogicalOperatorTag.UNIONALL) {
                eliminateProject = canEliminateProjectBelowUnion((UnionAllOperator) parentOp, projectOp,
                        parentInputIndex);
            }
            if (eliminateProject) {
                // The existing project has become useless. Remove it.
                parentOp.getInputs().get(parentInputIndex).setValue(op.getInputs().get(0).getValue());
            }
        }
    }

    if (modified) {
        context.computeAndSetTypeEnvironmentForOperator(op);
    }
    return modified;
}

From source file:com.zimbra.cs.html.DefangFilter.java

/** Handles an open tag. */
protected boolean handleOpenTag(QName element, XMLAttributes attributes) {
    String eName = element.rawname.toLowerCase();
    if (eName.equals("base")) {
        int index = attributes.getIndex("href");
        if (index != -1) {
            mBaseHref = attributes.getValue(index);
            if (mBaseHref != null) {
                try {
                    mBaseHrefURI = new URI(mBaseHref);
                } catch (URISyntaxException e) {
                    if (!mBaseHref.endsWith("/"))
                        mBaseHref += "/";
                }/*from  w w w  .j  a  v  a  2 s . c om*/
            }
        }
    }
    if (elementAccepted(element.rawname)) {
        HashSet<String> value = mAcceptedElements.get(eName);
        if (value != NULL) {
            HashSet<String> anames = value;
            int attributeCount = attributes.getLength();
            for (int i = 0; i < attributeCount; i++) {
                String aName = attributes.getQName(i).toLowerCase();
                // remove the attribute if it isn't in the list of accepted names
                // or it has invalid content
                if (!anames.contains(aName) || removeAttrValue(eName, aName, attributes, i)) {
                    attributes.removeAttributeAt(i--);
                    attributeCount--;
                } else {
                    sanitizeAttrValue(eName, aName, attributes, i);
                }
            }
        } else {
            attributes.removeAllAttributes();
        }

        if (eName.equals("img") || eName.equals("input")) {
            fixUrlBase(attributes, "src");
        } else if (eName.equals("a") || eName.equals("area")) {
            fixUrlBase(attributes, "href");
        }
        fixUrlBase(attributes, "background");

        if (eName.equals("a") || eName.equals("area")) {
            fixATag(attributes);
        }
        if (mNeuterImages) {
            String srcValue = Strings.nullToEmpty(attributes.getValue("src"));
            if (eName.equals("img") || eName.equals("input")) {
                if (VALID_EXT_URL.matcher(srcValue).find() || (!VALID_INT_IMG.matcher(srcValue).find()
                        && !VALID_IMG_FILE.matcher(srcValue).find())) {
                    neuterTag(attributes, "src", "df");
                } else if (!VALID_INT_IMG.matcher(srcValue).find() && VALID_IMG_FILE.matcher(srcValue).find()
                        && !VALID_CONVERTD_FILE.matcher(srcValue).find()) {
                    neuterTag(attributes, "src", "pn");
                }
            }
            neuterTag(attributes, "background", "df");
        }
        return true;
    } else if (elementRemoved(element.rawname)) {
        mRemovalElementName = element.rawname;
        mRemovalElementCount = 1;
    }
    return false;
}

From source file:edu.cornell.mannlib.vitro.webapp.dao.jena.IndividualDaoJena.java

public Collection<DataPropertyStatement> getExternalIds(String individualURI, String dataPropertyURI) {
    Collection<DataPropertyStatement> externalIdStatements = new ArrayList<DataPropertyStatement>();
    Individual ind = getIndividualByURI(individualURI);
    HashSet<String> externalIdPropURISet = new HashSet<String>();
    HashSet<String> nonExternalIdPropURISet = new HashSet<String>();
    if (ind != null) {
        Collection<DataPropertyStatement> dpsColl = getWebappDaoFactory().getDataPropertyStatementDao()
                .getDataPropertyStatementsForIndividualByDataPropertyURI(ind, dataPropertyURI);
        Iterator<DataPropertyStatement> dpsIt = dpsColl.iterator();
        while (dpsIt.hasNext()) {
            DataPropertyStatement dps = dpsIt.next();
            if (externalIdPropURISet.contains(dps.getDatapropURI())) {
                externalIdStatements.add(dps);
            } else if (!nonExternalIdPropURISet.contains(dps.getDatapropURI())) {
                OntModel tboxOntModel = getOntModelSelector().getTBoxModel();
                tboxOntModel.enterCriticalSection(Lock.READ);
                try {
                    Resource dataprop = tboxOntModel.getResource(dps.getDatapropURI());
                    if (dataprop != null && (tboxOntModel.contains(dataprop, DATAPROPERTY_ISEXTERNALID,
                            ResourceFactory.createTypedLiteral(true))
                            || tboxOntModel.contains(dataprop, DATAPROPERTY_ISEXTERNALID, "TRUE"))) {
                        externalIdPropURISet.add(dps.getDatapropURI());
                        externalIdStatements.add(dps);
                    } else {
                        nonExternalIdPropURISet.add(dps.getDatapropURI());
                    }//w w w  .j ava 2 s . c o m
                } finally {
                    tboxOntModel.leaveCriticalSection();
                }
            }
        }
    }
    return externalIdStatements;
}

From source file:chatbot.Chatbot.java

/** ************************************************************************************************
 * sets the values in tf (term frequency) and tdocfreq (count of
 * documents in which a term appears)//from   w  ww  .j ava2 s  .  co m
 * @param intlineCount is -1 for query
 */
private void processDoc(String doc, Integer intlineCount) {

    if (isNullOrEmpty(doc))
        return;
    String line = removePunctuation(doc);
    line = removeStopWords(line);
    if (isNullOrEmpty(line.trim()))
        return;
    ArrayList<String> tokens = splitToArrayList(line.trim());
    HashSet<String> tokensNoDup = new HashSet<String>();
    HashMap<String, Integer> tdocfreq = new HashMap<String, Integer>();
    for (int i = 0; i < tokens.size(); i++) {
        String token = tokens.get(i);
        Integer tcount = new Integer(0);
        if (tdocfreq.containsKey(token))
            tcount = tdocfreq.get(token);
        int tcountint = tcount.intValue() + 1;
        tcount = new Integer(tcountint);
        tdocfreq.put(token, tcount);
        if (!docfreq.containsKey(token))
            docfreq.put(token, new Integer(1));
        else {
            if (!tokensNoDup.contains(token)) {
                Integer intval = docfreq.get(token);
                int intvalint = intval.intValue();
                docfreq.put(token, new Integer(intvalint + 1));
                tokensNoDup.add(token);
            }
        }
    }
    tf.put(intlineCount, tdocfreq);
}