Example usage for java.lang StringBuffer setCharAt

List of usage examples for java.lang StringBuffer setCharAt

Introduction

In this page you can find the example usage for java.lang StringBuffer setCharAt.

Prototype

@Override
public synchronized void setCharAt(int index, char ch) 

Source Link

Usage

From source file:org.apache.mahout.clustering.kmeans.GenKMeansDataset.java

public int run(String[] args) throws Exception {
    long numSamples = 20;
    int numClusters = 2;
    int dimension = 2;
    double meanMin = 0;
    double meanMax = 1000;
    double stdMin = -100;
    double stdMax = 100;
    String datasetFile = "";
    String sampleDir = TEST_INPUT_PATH_SAMPLES;
    String clusterDir = TEST_INPUT_PATH_INITCLUSTERS;
    String compressCodec = "org.apache.hadoop.io.compress.DefaultCodec";
    String compress = "false";
    String compressType = "BLOCK";
    boolean textOutput = false;

    String welcomeMsg = "Generating Mahout KMeans Input Dataset";
    String usage = "Usage: org.apache.mahout.clustering.kmeans.GenKMeansDataset -sampleDir sampleDirectory -clusterDir centroidDirectory -numClusters numberofClusters -numSamples numberOfSamples -samplesPerFile numberOfSamplesPerFile -sampleDimension dimensionOfEachSample [ -centroidMin minValueOfEachDimensionForCenters -centroidMax maxValueOfEachDimensionForCenters -stdMin minStandardDeviationOfClusters -stdMax maxStandardDeviationOfClusters -maxIteration maxIter (The samples are generated using Gaussian Distribution around a set of centers which are also generated using UniformDistribution) -textOutput (Output text result instead of mahout vector)";
    System.out.println(welcomeMsg);
    if (args.length == 0) {
        System.err.println(usage);
        System.exit(-1);/*from  w  w  w  .  j  ava2s  .co  m*/
    }
    for (int i = 0; i < args.length; i++) {
        if (args[i].startsWith("-numSamples")) {
            numSamples = Long.parseLong(args[++i]);
        } else if (args[i].startsWith("-sampleDir")) {
            sampleDir = args[++i];
        } else if (args[i].startsWith("-clusterDir")) {
            clusterDir = args[++i];
        } else if (args[i].startsWith("-numClusters")) {
            numClusters = Integer.parseInt(args[++i]);
        } else if (args[i].startsWith("-samplesPerFile")) {
            SAMPLES_PER_FILE = Long.parseLong(args[++i]);
        } else if (args[i].startsWith("-sampleDimension")) {
            dimension = Integer.parseInt(args[++i]);
        } else if (args[i].startsWith("-centroidMin")) {
            meanMin = Double.parseDouble(args[++i]);
        } else if (args[i].startsWith("-centroidMax")) {
            meanMax = Double.parseDouble(args[++i]);
        } else if (args[i].startsWith("-stdMin")) {
            stdMin = Double.parseDouble(args[++i]);
        } else if (args[i].startsWith("-stdMax")) {
            stdMax = Double.parseDouble(args[++i]);
        } else if (args[i].startsWith("-datasetFile")) {
            datasetFile = args[++i];
        } else if (args[i].startsWith("-maxIteration")) {
        } else if (args[i].startsWith("-compressCodec")) {
            compressCodec = args[++i];
        } else if (args[i].startsWith("-compressType")) {
            compressType = args[++i];
        } else if (args[i].startsWith("-compress")) {
            compress = args[++i];
        } else if (args[i].startsWith("-textOutput")) {
            textOutput = true;
        } else {
            LOG.warn("Illegal format for parameter : " + args[i]);
        }
    }

    SampleProducer sp = new DemoSampleProducer();

    //if no dataset input, use random generator
    if (datasetFile.equals("")) {
        LOG.info("KMeans Clustering Input Dataset : Synthetic");
        GaussianSampleGenerator gsg = new GaussianSampleGenerator();
        MersenneTwisterRNG rng = new MersenneTwisterRNG();
        ContinuousUniformGenerator ug = new ContinuousUniformGenerator(meanMin, meanMax, rng);
        ContinuousUniformGenerator ugStd = new ContinuousUniformGenerator(stdMin, stdMax, rng);

        //generate samples
        double[][][] genParams = new double[numClusters][dimension][2];
        for (int k = 0; k < numClusters; k++) {
            for (int d = 0; d < dimension; d++) {
                genParams[k][d][0] = ug.nextValue(); //the d-th dimension of mean k
                genParams[k][d][1] = ugStd.nextValue(); //the stddev of d-th dimension of mean k
            }
        }

        LOG.info("Successfully generated Sample Generator Seeds");
        LOG.info("samples seeds are: ");
        for (int k = 0; k < numClusters; k++) {
            StringBuffer vec = new StringBuffer("(");
            for (int d = 0; d < dimension; d++) {
                vec.append(genParams[k][d][0] + ",");
            }
            vec.setCharAt(vec.length() - 1, ')');
            StringBuffer vecStd = new StringBuffer("(");
            for (int d = 0; d < dimension; d++) {
                vecStd.append(genParams[k][d][1] + ",");
            }
            vecStd.setCharAt(vecStd.length() - 1, ')');
            LOG.info("mean: " + vec.toString() + " std: " + vecStd.toString());
        }
        gsg.setGenParams(numSamples, dimension, genParams, meanMin, meanMax);

        sp = gsg;

    } else {

        LOG.info("KMeans Clustering Input Dataset : from file " + datasetFile);
        // if dataset file is provided, use dataset file as input
        initialCentroids = new ArrayList<Vector>(numClusters);
        DatasetSampleReader dp = new DatasetSampleReader(datasetFile);
        sp = dp;
    }

    JobConf jobConf = new JobConf(getConf(), GenKMeansDataset.class);
    jobConf.set("mapred.output.compress", compress);
    jobConf.set("mapred.output.compression.type", compressType);
    jobConf.set("mapred.output.compression.codec", compressCodec);
    LOG.info("mapred.output.compression.codec=" + jobConf.get("mapred.output.compression.codec"));
    FileSystem fs = FileSystem.get(new Path(sampleDir).toUri(), jobConf);

    sp.setFileSystem(fs, jobConf);

    LOG.info("Generate K-Means input Dataset : samples = " + numSamples + "sample dimension" + dimension
            + " cluster num =" + numClusters);

    //delete input and output directory
    fs.delete(new Path(sampleDir));
    LOG.info("Start producing samples...");
    long sampleNum = sp.produceSamples(new Path(sampleDir), textOutput);
    LOG.info("Finished producing samples");
    // pick k initial cluster centers at random
    fs.delete(new Path(clusterDir));
    LOG.info("Start generating initial cluster centers ...");
    sp.produceInitialCentroids(numClusters, new Path(clusterDir, "part-00000"));
    LOG.info("Finished generating initial cluster centers");
    return 0;
}

From source file:DummyAppletContext.java

/**
 * Gets the document URL.//w w w  .j  a v  a2 s . c om
 *
* @return      a "file:" URL for the current directory
 */
public URL getDocumentBase() {
    URL url = null;
    try {
        File dummy = new File("dummy.html");
        String path = dummy.getAbsolutePath();
        if (!File.separator.equals("/")) {
            StringBuffer buffer = new StringBuffer();
            if (path.charAt(0) != File.separator.charAt(0)) {
                buffer.append("/");
            }
            StringTokenizer st = new StringTokenizer(path, File.separator);
            while (st.hasMoreTokens()) {
                buffer.append(st.nextToken() + "/");
            }
            if (File.separator.equals("\\") && (buffer.charAt(2) == ':')) {
                buffer.setCharAt(2, '|');
            } else {
            }
            path = buffer.toString();
            path = path.substring(0, path.length() - 1);
        }
        url = new URL("file", "", -1, path);
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    }
    return url;
}

From source file:jdiff.API.java

/** 
 * <b>NOT USED</b>. /*  w w  w .j a  v a 2 s .c  om*/
 *
 * Replace all instances of <p> with <p/>. Just for the small number
 * of HMTL tags which don't require a matching end tag.
 * Also make HTML conform to the simple HTML requirements such as 
 * no double hyphens. Double hyphens are replaced by - and the character
 * entity for a hyphen.
 *
 * Cases where this fails and has to be corrected in the XML by hand: 
 *  Attributes' values missing their double quotes , e.g. size=-2
 *  Mangled HTML tags e.g. &lt;ttt> 
 *
 * <p><b>NOT USED</b>. There is often too much bad HTML in
 * doc blocks to try to handle every case correctly. Better just to
 * stuff the *lt; and &amp: characters with stuffHTMLTags(). Though
 * the resulting XML is not as elegant, it does the job with less
 * intervention by the user.
 */
public static String convertHTMLTagsToXHTML(String htmlText) {
    StringBuffer sb = new StringBuffer(htmlText);
    int i = 0;
    boolean inTag = false;
    String tag = null;
    // Needs to re-evaluate this length at each loop
    while (i < sb.length()) {
        char c = sb.charAt(i);
        if (inTag) {
            if (c == '>') {
                // OPTION Could fail at or fix some errorneous tags here
                // Make the best guess as to whether this tag is terminated
                if (Comments.isMinimizedTag(tag) && htmlText.indexOf("</" + tag + ">", i) == -1)
                    sb.insert(i, "/");
                inTag = false;
            } else {
                // OPTION could also make sure that attribute values are
                // surrounded by quotes.
                tag += c;
            }
        }
        if (c == '<') {
            inTag = true;
            tag = "";
        }
        // -- is not allowed in XML, but !-- is part of an comment,
        // and --> is also part of a comment
        if (c == '-' && i > 0 && sb.charAt(i - 1) == '-') {
            if (!(i > 1 && sb.charAt(i - 2) == '!')) {
                sb.setCharAt(i, '&');
                sb.insert(i + 1, "#045;");
                i += 5;
            }
        }
        i++;
    }
    if (inTag) {
        // Oops. Someone forgot to close their HTML tag, e.g. "<code."
        // Close it for them.
        sb.insert(i, ">");
    }
    return sb.toString();
}

From source file:org.openadaptor.auxil.connector.jdbc.writer.AbstractSQLWriter.java

/**
 * Generate a prepared statement to insert named values into a database table.
 * <br>/*from  w  ww. j  a va2 s. co m*/
 * Note that it does not check that the table name is valid, or that the
 * columnNames exist in that table.
 * 
 * @param connection the database connection to use
 * @param tableName the name of the table to insert into
 * @param columnNames String[] of the table column names
 */

protected PreparedStatement generatePreparedStatement(Connection connection, String tableName,
        String[] columnNames) throws SQLException {
    StringBuffer sql = new StringBuffer("INSERT INTO " + quoteIdentifier(tableName) + "(");
    StringBuffer params = new StringBuffer();
    for (int i = 0; i < columnNames.length; i++) {
        sql.append(quoteIdentifier(columnNames[i]) + ",");
        params.append("?,");
    }
    sql.setCharAt(sql.length() - 1, ')'); //Swap last comma for a bracket.
    params.setCharAt(params.length() - 1, ')');//Ditto
    sql.append(" VALUES (").append(params);
    if (log.isDebugEnabled()) {
        log.debug("Generated Prepared stmt: " + sql.toString());
    }
    return connection.prepareStatement(sql.toString());
}

From source file:com.avricot.prediction.utils.Steemer.java

/**
 * Turns u and i preceded AND followed by a vowel to UpperCase<br>
 * Turns y preceded OR followed by a vowel to UpperCase<br>
 * Turns u preceded by q to UpperCase<br>
  */*  w ww .  ja  v  a2  s  . co m*/
  * @param buffer java.util.StringBuffer - the buffer to treat
  * @return java.util.StringBuffer - the treated buffer
  */
 private StringBuffer treatVowels(StringBuffer buffer) {
     for (int c = 0; c < buffer.length(); c++) {
         char ch = buffer.charAt(c);

         if (c == 0) // first char
         {
             if (buffer.length() > 1) {
                 if (ch == 'y' && isVowel(buffer.charAt(c + 1)))
                     buffer.setCharAt(c, 'Y');
             }
         } else if (c == buffer.length() - 1) // last char
         {
             if (ch == 'u' && buffer.charAt(c - 1) == 'q')
                 buffer.setCharAt(c, 'U');
             if (ch == 'y' && isVowel(buffer.charAt(c - 1)))
                 buffer.setCharAt(c, 'Y');
         } else // other cases
         {
             if (ch == 'u') {
                 if (buffer.charAt(c - 1) == 'q')
                     buffer.setCharAt(c, 'U');
                 else if (isVowel(buffer.charAt(c - 1)) && isVowel(buffer.charAt(c + 1)))
                     buffer.setCharAt(c, 'U');
             }
             if (ch == 'i') {
                 if (isVowel(buffer.charAt(c - 1)) && isVowel(buffer.charAt(c + 1)))
                     buffer.setCharAt(c, 'I');
             }
             if (ch == 'y') {
                 if (isVowel(buffer.charAt(c - 1)) || isVowel(buffer.charAt(c + 1)))
                     buffer.setCharAt(c, 'Y');
             }
         }
     }

     return buffer;
 }

From source file:com.hp.hpl.jena.sparql.engine.http.HttpQuery.java

private void basicAuthentication(HttpURLConnection httpConnection2) {
    // Do basic authentication : do directly, not via an Authenticator, because it 
    // avoids an extra round trip (Java normally does the request without authetication,
    // then reties with)

    if (user != null || password != null) {
        try {/*from  w  w  w  . ja va 2  s.c o  m*/
            if (user == null || password == null)
                log.warn("Only one of user/password is set");
            // We want: "Basic user:password" except user:password is base 64 encoded.
            // Build string, get as UTF-8, bytes, translate to base 64. 
            StringBuffer x = new StringBuffer();
            byte b[] = x.append(user).append(":").append(password).toString().getBytes("UTF-8");
            String y = Base64.encodeBase64String(b);
            httpConnection.setRequestProperty("Authorization", "Basic " + y);
            // Overwrite any password details we copied.
            // Still leaves the copy in the HTTP connection.  But this only basic auth. 
            for (int i = 0; i < x.length(); i++)
                x.setCharAt(i, '*');
            for (int i = 0; i < b.length; i++)
                b[i] = (byte) 0;
        } catch (UnsupportedEncodingException ex) {
            // Can't happen - UTF-8 is required of all Java platforms. 
            throw new ARQInternalErrorException("UTF-8 is broken on this platform", ex);
        }
    }
}

From source file:com.mgmtp.jfunk.data.generator.util.GeneratingExpression.java

/**
 * Replaces randomly selected characters in the given string with forbidden characters according
 * to the given expression./*from ww w . j av  a 2  s  .c o  m*/
 * 
 * @param bad
 *            if bad = -2 all characters are replaced, if bad = -1 1 - (all - 1) are replaced,
 *            if bad > 0 the exact number of characters is replaced
 * @param input
 *            the input string
 * @return input with <code>bad</code> replaced characters
 */
public String negateString(final String input, int bad) {
    int length = input.length();
    Range[] ranges = getRanges();
    int[] lengths = new int[ranges.length];
    // arrange lengths
    for (int i = 0; i < lengths.length; i++) {
        Range r = ranges[i];
        lengths[i] = r.getMin();
        length -= r.getMin();
    }
    /**
     * distribute remaining lengths
     */
    int i = 0;
    // only 1000 tries otherwise break as it just does not work
    while (length > 0 && i < 1000) {
        int index = i % lengths.length;
        Range r = ranges[index];
        if (lengths[index] < r.getMax()) {
            lengths[index] += 1;
            length--;
        }
        i++;
    }

    // generate completely negative string
    String replaceString = generate(lengths, -2);
    if (replaceString.length() == 0) {
        log.warn("No negative characters possible in this expression. All characters are allowed.");
        return input;
    }
    // now replace the #bad character in the input string
    List<Integer> l = new ArrayList<Integer>(input.length());
    for (i = 0; i < input.length(); i++) {
        l.add(i);
    }
    if (bad == -2) {
        // all false
        bad = input.length();
    } else if (bad == -1) {
        bad = 1 + random.getInt(input.length() - 1);
    }
    Collections.shuffle(l);
    StringBuffer base = new StringBuffer(input);
    int j = 0;
    for (i = 0; i < bad; i++) {
        int index = l.remove(0);
        char replaceChar = ' ';
        if (index < replaceString.length()) {
            replaceChar = replaceString.charAt(index);
        }
        while ((index == 0 || index >= replaceString.length() || index == input.length() - 1)
                && Character.isSpaceChar(replaceChar)) {
            replaceChar = replaceString.charAt(j);
            j = (j + 1) % replaceString.length();
        }
        base.setCharAt(index, replaceChar);
    }
    if (log.isDebugEnabled()) {
        log.debug("False characters in string; " + input + " became " + base);
    }
    return base.toString();
}

From source file:org.etudes.ambrosia.impl.UiPropertyReference.java

/**
 * Write the value for FileItem (commons file upload) values.
 * /*from  w w w  .  j a  v  a 2 s.  com*/
 * @param entity
 *        The entity to write to.
 * @param property
 *        The property to set.
 * @param value
 *        The value to write.
 */
protected void setFileValue(Object entity, String property, FileItem value) {
    // form a "setFoo()" based setter method name
    StringBuffer setter = new StringBuffer("set" + property);
    setter.setCharAt(3, setter.substring(3, 4).toUpperCase().charAt(0));

    try {
        // use this form, providing the setter name and no getter, so we can support properties that are write-only
        PropertyDescriptor pd = new PropertyDescriptor(property, entity.getClass(), null, setter.toString());
        Method write = pd.getWriteMethod();
        Object[] params = new Object[1];

        Class[] paramTypes = write.getParameterTypes();
        if ((paramTypes != null) && (paramTypes.length == 1)) {
            // single value boolean
            if (paramTypes[0] != FileItem.class) {
                M_log.warn(
                        "setFileValue: target not expecting FileItem: " + entity.getClass() + " " + property);
                return;
            }

            params[0] = value;
            write.invoke(entity, params);
        } else {
            M_log.warn("setFileValue: method: " + property + " object: " + entity.getClass()
                    + " : no one parameter setter method defined");
        }
    } catch (IntrospectionException ie) {
        M_log.warn("setFileValue: method: " + property + " object: " + entity.getClass() + " : " + ie);
    } catch (IllegalAccessException ie) {
        M_log.warn("setFileValue: method: " + property + " object: " + entity.getClass() + " :" + ie);
    } catch (IllegalArgumentException ie) {
        M_log.warn("setFileValue: method: " + property + " object: " + entity.getClass() + " :" + ie);
    } catch (InvocationTargetException ie) {
        M_log.warn("setFileValue: method: " + property + " object: " + entity.getClass() + " :" + ie);
    }
}

From source file:org.etudes.ambrosia.impl.UiPropertyReference.java

/**
 * Read the configured selector value from the entity.
 * /*from www. j av a 2 s  .c o m*/
 * @param context
 *        The context.
 * @param entity
 *        The entity to read from.
 * @param selector
 *        The selector name.
 * @return The selector value object found, or null if not.
 */
protected Object getValue(Context context, Object entity, String property) {
    // if no selector named, just use the entity
    if (property == null)
        return entity;

    // if the property is an index reference
    if (property.startsWith("[") && property.endsWith("]")) {
        return getIndexValue(entity, decode(property.substring(1, property.length() - 1)));
    }

    // another form of index, taking the index value from the nested references
    if (property.startsWith("{") && property.endsWith("}")) {
        try {
            String propertiesIndex = property.substring(1, property.length() - 1);
            int i = Integer.parseInt(propertiesIndex);
            PropertyReference ref = this.properties.get(i);
            String index = ref.read(context, entity);

            return getIndexValue(entity, index);
        } catch (NumberFormatException e) {
        } catch (IndexOutOfBoundsException e) {
        }
    }

    // form a "getFoo()" based getter method name
    StringBuffer getter = new StringBuffer("get" + property);
    getter.setCharAt(3, getter.substring(3, 4).toUpperCase().charAt(0));

    try {
        // use this form, providing the getter name and no setter, so we can support properties that are read-only
        PropertyDescriptor pd = new PropertyDescriptor(property, entity.getClass(), getter.toString(), null);
        Method read = pd.getReadMethod();
        Object value = read.invoke(entity, (Object[]) null);
        return value;
    } catch (IntrospectionException ie) {
        M_log.warn("getValue: method: " + property + " object: " + entity.getClass(), ie);
        return null;
    } catch (IllegalAccessException ie) {
        M_log.warn("getValue: method: " + property + " object: " + entity.getClass(), ie);
        return null;
    } catch (IllegalArgumentException ie) {
        M_log.warn("getValue: method: " + property + " object: " + entity.getClass(), ie);
        return null;
    } catch (InvocationTargetException ie) {
        M_log.warn("getValue: method: " + property + " object: " + entity.getClass(), ie);
        return null;
    }
}

From source file:com.java2s.intents4.IntentsDemo4Activity.java

String filterToString(IntentFilter filter) {
    StringBuffer buffer = new StringBuffer("IntentFilter { ");

    Iterator<String> actionsIter = filter.actionsIterator();
    if (actionsIter != null) {
        buffer.append("act=[");
        while (actionsIter.hasNext()) {
            String temp = actionsIter.next().trim();
            buffer.append(temp + ",");
            Log.i(CLASSNAME, "Filter action: >" + temp + "<");
        }//from   w  ww. ja v a2 s .c om
        if (buffer.lastIndexOf(",") >= 0) {
            buffer.setCharAt(buffer.lastIndexOf(","), ']');
        } else {
            buffer.append(']');
        }
        buffer.append(" ");
    }

    Iterator<String> schemesIter = filter.schemesIterator();
    if (schemesIter != null) {
        buffer.append("sche=[");
        while (schemesIter.hasNext()) {
            String temp = schemesIter.next().trim();
            buffer.append(temp + ",");
            Log.i(CLASSNAME, "Filter scheme: >" + temp + "<");
        }
        buffer.setCharAt(buffer.lastIndexOf(","), ']');
        buffer.append(" ");
    }

    Iterator<IntentFilter.AuthorityEntry> authsIter = filter.authoritiesIterator();
    if (authsIter != null) {
        buffer.append("auth=[");
        while (authsIter.hasNext()) {
            IntentFilter.AuthorityEntry entry = authsIter.next();
            String temp = entry.getHost() + ":" + entry.getPort();
            buffer.append(temp + ",");
            Log.i(CLASSNAME, "Filter authority: >" + temp + "<");
        }
        buffer.setCharAt(buffer.lastIndexOf(","), ']');
        buffer.append(" ");
    }

    Iterator<PatternMatcher> pathsIter = filter.pathsIterator();
    if (pathsIter != null) {
        buffer.append("path=[");
        while (pathsIter.hasNext()) {
            PatternMatcher entry = pathsIter.next();
            String temp = entry.toString();
            buffer.append(temp + ",");
            Log.i(CLASSNAME, "Filter path: >" + temp + "<");
        }
        buffer.setCharAt(buffer.lastIndexOf(","), ']');
        buffer.append(" ");
    }

    Iterator<String> typesIter = filter.typesIterator();
    if (typesIter != null) {
        buffer.append("typ=[");
        while (typesIter.hasNext()) {
            String temp = typesIter.next().trim();
            buffer.append(temp + ",");
            Log.i(CLASSNAME, "Filter type: >" + temp + "<");
        }
        buffer.setCharAt(buffer.lastIndexOf(","), ']');
        buffer.append(" ");
    }

    Iterator<String> catsIter = filter.categoriesIterator();
    if (catsIter != null) {
        buffer.append("cat=[");
        while (catsIter.hasNext()) {
            String temp = catsIter.next().trim();
            buffer.append(temp + ",");
            Log.i(CLASSNAME, "Filter category: >" + temp + "<");
        }
        buffer.setCharAt(buffer.lastIndexOf(","), ']');
        buffer.append(" ");
    }

    buffer.append('}');
    return buffer.toString();
}