问:
Template deduction: porting to C++11
Following code is legal for C++14 compiler

```<code>// g++ -std=c++14 -pedantic -pthread main.cpp
// output: 1 2 3 4 5 1 1 1
#include <algorithm>
#include <vector>
#include <functional>
#include <iterator>
#include <iostream>

int main()
{
  std::vector<int> a = { 1, 2, 3, 2, 4, 5, 1, 1, 3, 5, 1, 5 }, b = { 2, 5, 5, 3 }, c;

  std::copy_if(a.begin(), a.end(), std::back_inserter(c),
    std::bind(std::less<>(),   // this won't work in pre-C++14
      std::bind(
        std::count<std::vector<int>::iterator, int>,
          std::bind(static_cast<std::vector<int>::iterator (std::vector<int>::*)()>(&std::vector<int>::begin), &c),
          std::bind(static_cast<std::vector<int>::iterator (std::vector<int>::*)()>(&std::vector<int>::end), &c),
          std::placeholders::_1
      ),
      std::bind(
        std::minus<>(), // this won't work in pre-C++14
          std::bind(
            std::count<std::vector<int>::iterator, int>,
              a.begin(),
              a.end(),
              std::placeholders::_1
          ),
          std::bind(
            std::count<std::vector<int>::iterator, int>,
              b.begin(),
              b.end(),
              std::placeholders::_1
          )
      )
    )
  );

  std::copy(c.begin(), c.end(), std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;
}
</code>```

It is meant to create vector c from elements of vector a  , excluding those that match count and value of elements in vector b. E.g. if a contains three  2 and b - two of them, only one 2 would be present in c.

a) how possible to adapt this code for C++11? Intuitive leap that less<> and minus<> parameter would be ...::difference_type didn't work, compiler messages aren't helpful either

b) current version removes last matches sequence-wise. What code would remove first matches?

答:
The real answer is to just not use bind(). Use a lambda:

```<code>std::copy_if(a.begin(), a.end(), std::back_inserter(c), [&](int elem){
    return std::count(c.begin(), c.end(), elem) <
        std::count(a.begin(), a.end(), elem) - std::count(b.begin(), b.end(), elem);
});
</code>```

This is far shorter than the solution with std::bind(), works in C++11, and is far easier to understand. And we don't have to do manual template deduction either.

We could have also written it this way:

```<code>std::copy_if(a.begin(), a.end(), std::back_inserter(c), [&](int& elem){
    return std::count(&elem + 1, &a[a.size()], elem) >=
        std::count(b.begin(), b.end(), elem);
});
</code>```

Note that I'm now taking elem by reference. This also makes it more easier to see how to implement your proposed extension removing the first match. That's just changing which side of elem in a we're comparing:

```<code>std::copy_if(a.begin(), a.end(), std::back_inserter(c), [&](int& elem) {
    return std::count(&a[0], &elem, elem) >=
        std::count(b.begin(), b.end(), elem);
});
</code>```

Title: Template deduction: porting to C++11

Body:
Following code is legal for C++14 compiler

// g++ -std=c++14 -pedantic -pthread main.cpp
// output: 1 2 3 4 5 1 1 1
#include <algorithm>
#include <vector>
#include <functional>
#include <iterator>
#include <iostream>

int main()
{
  std::vector<int> a = { 1, 2, 3, 2, 4, 5, 1, 1, 3, 5, 1, 5 }, b = { 2, 5, 5, 3 }, c;

  std::copy_if(a.begin(), a.end(), std::back_inserter(c),
    std::bind(std::less<>(),   // this won't work in pre-C++14
      std::bind(
        std::count<std::vector<int>::iterator, int>,
          std::bind(static_cast<std::vector<int>::iterator (std::vector<int>::*)()>(&std::vector<int>::begin), &c),
          std::bind(static_cast<std::vector<int>::iterator (std::vector<int>::*)()>(&std::vector<int>::end), &c),
          std::placeholders::_1
      ),
      std::bind(
        std::minus<>(), // this won't work in pre-C++14
          std::bind(
            std::count<std::vector<int>::iterator, int>,
              a.begin(),
              a.end(),
              std::placeholders::_1
          ),
          std::bind(
            std::count<std::vector<int>::iterator, int>,
              b.begin(),
              b.end(),
              std::placeholders::_1
          )
      )
    )
  );

  std::copy(c.begin(), c.end(), std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;
}

It is meant to create vector c from elements of vector a  , excluding those that match count and value of elements in vector b. E.g. if a contains three  2 and b - two of them, only one 2 would be present in c.

a) how possible to adapt this code for C++11? Intuitive leap that less<> and minus<> parameter would be ...::difference_type didn't work, compiler messages aren't helpful either

b) current version removes last matches sequence-wise. What code would remove first matches?

Body:
The real answer is to just not use bind(). Use a lambda:

std::copy_if(a.begin(), a.end(), std::back_inserter(c), [&](int elem){
    return std::count(c.begin(), c.end(), elem) <
        std::count(a.begin(), a.end(), elem) - std::count(b.begin(), b.end(), elem);
});

This is far shorter than the solution with std::bind(), works in C++11, and is far easier to understand. And we don't have to do manual template deduction either.

We could have also written it this way:

std::copy_if(a.begin(), a.end(), std::back_inserter(c), [&](int& elem){
    return std::count(&elem + 1, &a[a.size()], elem) >=
        std::count(b.begin(), b.end(), elem);
});

Note that I'm now taking elem by reference. This also makes it more easier to see how to implement your proposed extension removing the first match. That's just changing which side of elem in a we're comparing:

std::copy_if(a.begin(), a.end(), std::back_inserter(c), [&](int& elem) {
    return std::count(&a[0], &elem, elem) >=
        std::count(b.begin(), b.end(), elem);
});


来源: stackexchange

问:
Regular expression: replace the suffix of a string ending in '.js' but not 'min.js'
Assume infile is a variable holding the name of an input file, and similarly outfile for output file.  If infile ends in .js, I'd like to replace with .min.js and that's easy enough (I think).

outfile = re.sub(r'\b.js$', '.min.js', infile)

But my question is if infile ends in .min.js, then I do not want the substitution to take place.  (Otherwise, I'll end up with .min.min.js)  How can I accomplish this by using regular expression?

PS: This is not homework.  If you're curious what this is for: this is for a small python script to do mass compress of JavaScript files in a directory.

答:
For tasks this simple, there's no need for regexps. String methods can be more readable, eg.:</p>

```<code>if filename.endswith('.js') and not filename.endswith('.min.js'):
    filename= filename[:-3]+'.min.js'
</code>```

OwnerDisplayName: Kevin Le

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Khnle

Body:
For tasks this simple, there's no need for regexps. String methods can be more readable, eg.:

if filename.endswith('.js') and not filename.endswith('.min.js'):
    filename= filename[:-3]+'.min.js'

OwnerDisplayName: bobince


问:
Does a lightweight markup language library for Android exist?
Suppose I want to render/present a text transmitted in the form of some lightweight markup language. Are there any ready-to-use libraries for Android, which take as input text in a lightweight markup language and present it nicely? When I say lightweight markup language, I mean Markdown (http://en.wikipedia.org/wiki/Markdown) or something similar.

答:
You can look at:

MarkdownJ

I haven't tried this.

JMD

This works, but the latest build has issues with some numbers in the text being interpreted as entities; e.g. "The 39th President" becomes "The &39;th President".

PegDown

This works properly, but in the rather old 0.8.0.1 version I am currently using it's really surprisingly CPU intensive(*) - much more so that JMD.  It's dependent on the separate parboiled PEG parser (which also has a newer version than I am currently using). (Stricken based on comment below)

(*) The excessive CPU load seems to only occur on the IBM Classic JVM for the AS/400.

NOTE: I have used these only on Java VMs, not on Android, but I know of no reason why any or all of them should not work on Android.

ContentLicense: CC BY-SA 3.0


问:
Jquery bootgrid plugin double pagination
i have a problem. I need to alter the jquery bootgrid plugin so it allows multiple magination. I.E.  if a user sends array of parameters like ['top-left', 'bottom-left'], bootgrid must have both pagination on top and on the bottom left of the bootgrid table.

I created this method where i add them but there is only the possibility to add 2 in the same row, it creates empty pagination div on top but insert 2 paginations in the bottom div

```<code>    Grid.prototype.setPaginationBar = function (params) {
            if (params[0] == "top-left") {
                $('.table-responsive').prepend(this.footer);
                var bar = $('.paginationBar');
                $(bar).insertBefore('.infoBar');
                $(bar).addClass('paginationBarLeft');
                $(bar).removeClass('paginationBar');
            }
            else if (params[0] == "top-right") {
                $('.table-responsive').prepend(this.footer);
            }
            else if (params[0] == "bottom-left") {
                var bar = $('.paginationBar');
                $(bar).insertBefore('.infoBar');
                $(bar).addClass('paginationBarLeft');
                $(bar).removeClass('paginationBar');
            }

            this.header = this.footer.clone();
            $('.table-responsive').prepend(this.header);
    };
</code>```

i call the method like this

```<code>        var params = ['bottom-right', 'bottom-left'];
        $("#employee_grid").bootgrid("setPaginationBar", params);
</code>```

And heres is the method the is called by bootgrid after mine method

```<code>    function renderPagination() {
        if (this.options.navigation !== 0) {
            var selector = getCssSelector(this.options.css.pagination),
                headerPagination = this.header.find(selector)._bgShowAria(this.rowCount !== -1),
                footerPagination = this.footer.find(selector)._bgShowAria(this.rowCount !== -1);
            if (this.rowCount !== -1 && (headerPagination.length + footerPagination.length) > 0) {
                var tpl = this.options.templates,
                    current = this.current,
                    totalPages = this.totalPages,
                    pagination = $(tpl.pagination.resolve(getParams.call(this))),
                    offsetRight = totalPages - current,
                    offsetLeft = (this.options.padding - current) * -1,
                    startWith = ((offsetRight >= this.options.padding) ?
                        Math.max(offsetLeft, 1) :
                        Math.max((offsetLeft - this.options.padding + offsetRight), 1)),
                    maxCount = this.options.padding * 2 + 1,
                    count = (totalPages >= maxCount) ? maxCount : totalPages;

                renderPaginationItem.call(this, pagination, "first", "«", "first")
                    ._bgEnableAria(current > 1);
                renderPaginationItem.call(this, pagination, "prevPage", "<", "prevPage")
                    ._bgEnableAria(current > 1);

                for (var i = 0; i < count; i++) {
                    var pos = i + startWith;
                    renderPaginationItem.call(this, pagination, pos, pos, "page-" + pos)
                        ._bgEnableAria()._bgSelectAria(pos === current);
                }

                if (count === 0) {
                    renderPaginationItem.call(this, pagination, 1, 1, "page-" + 1)
                        ._bgEnableAria(false)._bgSelectAria();
                }

                renderPaginationItem.call(this, pagination, "nextPage", ">", "nextPage")
                    ._bgEnableAria(totalPages > current);
                renderPaginationItem.call(this, pagination, "last", "»", "last")
                    ._bgEnableAria(totalPages > current);

                replacePlaceHolder.call(this, headerPagination, pagination, 1);
                replacePlaceHolder.call(this, footerPagination, pagination, 2);
                //Pagination ADA fix
                paginationADA();
            }
        }
    }
</code>```

I would be very thankful if someone could help me as i cant figure out how to make the bootgrid to have multiple paginations, one on top and one on bottom

答:
Fixed the issue by calling the method after grid initializes...</p>

```<code>    }).on("loaded.rs.jquery.bootgrid", function () {
        /* Executes after data is loaded and rendered */
        var params = ['top-right', 'bottom-right'];
        $("#employee_grid").bootgrid("setPaginationBar", params);
        Ladda.stopAll();
        //Delete
</code>```

Body:
i have a problem. I need to alter the jquery bootgrid plugin so it allows multiple magination. I.E.  if a user sends array of parameters like ['top-left', 'bottom-left'], bootgrid must have both pagination on top and on the bottom left of the bootgrid table.

I created this method where i add them but there is only the possibility to add 2 in the same row, it creates empty pagination div on top but insert 2 paginations in the bottom div

    Grid.prototype.setPaginationBar = function (params) {
            if (params[0] == "top-left") {
                $('.table-responsive').prepend(this.footer);
                var bar = $('.paginationBar');
                $(bar).insertBefore('.infoBar');
                $(bar).addClass('paginationBarLeft');
                $(bar).removeClass('paginationBar');
            }
            else if (params[0] == "top-right") {
                $('.table-responsive').prepend(this.footer);
            }
            else if (params[0] == "bottom-left") {
                var bar = $('.paginationBar');
                $(bar).insertBefore('.infoBar');
                $(bar).addClass('paginationBarLeft');
                $(bar).removeClass('paginationBar');
            }

            this.header = this.footer.clone();
            $('.table-responsive').prepend(this.header);
    };

i call the method like this

        var params = ['bottom-right', 'bottom-left'];
        $("#employee_grid").bootgrid("setPaginationBar", params);

And heres is the method the is called by bootgrid after mine method

    function renderPagination() {
        if (this.options.navigation !== 0) {
            var selector = getCssSelector(this.options.css.pagination),
                headerPagination = this.header.find(selector)._bgShowAria(this.rowCount !== -1),
                footerPagination = this.footer.find(selector)._bgShowAria(this.rowCount !== -1);
            if (this.rowCount !== -1 && (headerPagination.length + footerPagination.length) > 0) {
                var tpl = this.options.templates,
                    current = this.current,
                    totalPages = this.totalPages,
                    pagination = $(tpl.pagination.resolve(getParams.call(this))),
                    offsetRight = totalPages - current,
                    offsetLeft = (this.options.padding - current) * -1,
                    startWith = ((offsetRight >= this.options.padding) ?
                        Math.max(offsetLeft, 1) :
                        Math.max((offsetLeft - this.options.padding + offsetRight), 1)),
                    maxCount = this.options.padding * 2 + 1,
                    count = (totalPages >= maxCount) ? maxCount : totalPages;

                renderPaginationItem.call(this, pagination, "first", "«", "first")
                    ._bgEnableAria(current > 1);
                renderPaginationItem.call(this, pagination, "prevPage", "<", "prevPage")
                    ._bgEnableAria(current > 1);

                for (var i = 0; i < count; i++) {
                    var pos = i + startWith;
                    renderPaginationItem.call(this, pagination, pos, pos, "page-" + pos)
                        ._bgEnableAria()._bgSelectAria(pos === current);
                }

                if (count === 0) {
                    renderPaginationItem.call(this, pagination, 1, 1, "page-" + 1)
                        ._bgEnableAria(false)._bgSelectAria();
                }

                renderPaginationItem.call(this, pagination, "nextPage", ">", "nextPage")
                    ._bgEnableAria(totalPages > current);
                renderPaginationItem.call(this, pagination, "last", "»", "last")
                    ._bgEnableAria(totalPages > current);

                replacePlaceHolder.call(this, headerPagination, pagination, 1);
                replacePlaceHolder.call(this, footerPagination, pagination, 2);
                //Pagination ADA fix
                paginationADA();
            }
        }
    }

I would be very thankful if someone could help me as i cant figure out how to make the bootgrid to have multiple paginations, one on top and one on bottom

Body:
Fixed the issue by calling the method after grid initializes...

    }).on("loaded.rs.jquery.bootgrid", function () {
        /* Executes after data is loaded and rendered */
        var params = ['top-right', 'bottom-right'];
        $("#employee_grid").bootgrid("setPaginationBar", params);
        Ladda.stopAll();
        //Delete


问:
How to start with Framework7 Vue with material design?
I want to  Maintain both iOS and Material Themes in single app with vue. but in the documentation Framework7 vue can not find how to starts with material design.I know I have to make some changes , but can not get any hint with vue. I am facing some overlapping issues after navigating to other pages.
Please help me. or suggest a template with framework7 vue.</p>

答:
//IOS:
  require('framework7/dist/css/framework7.material.css');
  require('framework7/dist/css/framework7.material.colors.css');
  require('framework7-icons/css/framework7-icons.css');

//Android:
  require('framework7/dist/css/framework7.ios.css');
  require('framework7/dist/css/framework7.ios.colors.css');
  require('framework7-icons/css/framework7-icons.css');```
</div>
</div>
</p>

<p>i have used require you can change it into import statments.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>new Vue({
      el: '#app',
      template: '<app/>',
      // Init Framework7 by passing parameters here
      framework7: {
        root: '#app',
        /* Uncomment to enable Material theme: */
        material: true,
        routes: Routes
      },
      // Register App Component
      components: {
        app: App
      }
  })</code>```

set material to true for material and for iso set it to false.
that it it will work like charam

Body:
//IOS:
  require('framework7/dist/css/framework7.material.css');
  require('framework7/dist/css/framework7.material.colors.css');
  require('framework7-icons/css/framework7-icons.css');

//Android:
  require('framework7/dist/css/framework7.ios.css');
  require('framework7/dist/css/framework7.ios.colors.css');
  require('framework7-icons/css/framework7-icons.css');

i have used require you can change it into import statments.

new Vue({
      el: '#app',
      template: '<app/>',
      // Init Framework7 by passing parameters here
      framework7: {
        root: '#app',
        /* Uncomment to enable Material theme: */
        material: true,
        routes: Routes
      },
      // Register App Component
      components: {
        app: App
      }
  })

set material to true for material and for iso set it to false.
that it it will work like charam


问:
How to de- serialize the DoccatModel object in java?
I am trying to serialize a DoccatModel Object in Java (I am using OpenNLP algorithm).

It's able to serialize the object properly and I am writing that to an external file. But, I'm not able to deserialise the object back.

I am trying to use ObjectInputStream to read that file back. It's throwing an error:

"java.io.StreamCorruptedException: invalid stream header: 504B0304"

I just want to know how to de serialize the DoccatModel object back so that I can use it further.

The code is as follows. [Apologies for bad code since its still in development stage]

```<code>private static void runDocCat(String textField, String updateField, String tgtField)
{
    String dbName;
    String tableName;
    DoccatModel model = null;
    JSONArray allDesc = null;
    DataConfig BSC = null;
    try
    {
        BSC = new DataConfig();
    }
    catch (Exception e1)
    {
        e1.printStackTrace();
    }

    try
    {
        dbName = BSC.getdbName();
        tableName = BSC.tablename;
        String dataQuery = "SELECT ID, VOC, " + tgtField + " from " + dbName + "." + tableName;
        allDesc = BSC.getJSONArray(dataQuery);
        File file = new File("voc.train");
        BufferedWriter output = new BufferedWriter(new FileWriter(file));

        for (int i = 0; i < allDesc.length(); i++)
        {
            String tgt = allDesc.getJSONObject(i).getString(tgtField);
            if (tgt.length() < 3)
                tgt = "Unknown";
           tgt = tgt.replaceAll(" ", "");
           String desc = allDesc.getJSONObject(i).getString(textField);
           desc = desc.replaceAll("\\r", " ").replaceAll("\\n", ".");
           if (!desc.trim().equalsIgnoreCase("nothing"))
           {
                DocumentSample currDoc = new DocumentSample(tgt, desc);
                output.write(currDoc.toString());
                output.newLine();
           }
        }

        output.close();
        System.out.println("Training Data Generated!");
        ObjectStream<String> lineStream = new PlainTextByLineStream(new FileReader(file));
        ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
        model = DocumentCategorizerME.train("en", sampleStream);
        System.out.println("Model Data \n\n" + model);
        // Write to a file
        OutputStream modelOut = null;
        try
        {
            String modelfile = "C:\\VOC_Classification\\model.ser";
            modelOut = new BufferedOutputStream(new FileOutputStream(modelfile));
            model.serialize(modelOut);
            System.out.println("Model Data \n\n" + model);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (modelOut != null)
            try
            {
                modelOut.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }

    // try
    // {
    // FileOutputStream fileOut = new FileOutputStream("modelfile.ser");
    // ObjectOutputStream out = new ObjectOutputStream(fileOut);
    // out.writeObject(model);
    // out.close();
    // fileOut.close();
    // System.out.printf("Serialized data is saved in modelfile.ser");
    // } catch (IOException i)
    // {
    // i.printStackTrace();
    // }

    DoccatModel model_SER = null;
    try
    {
        FileInputStream fileIn = new FileInputStream("C:\\VOC_Classification\\model.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);
        model_SER = (DoccatModel) in.readObject();
        in.close();
        fileIn.close();
    } catch (IOException e)
    {
        e.printStackTrace();
    }

    System.out.println("\nTraining Done!\n");

    DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
    System.out.println(" ---------- Starting categorising process ----------");
    System.out.println("\nProcess Running, Please wait...\n");
    for (int i = 0; i < allDesc.length(); i++)
    {

    dataQuery = "SELECT ID, VOC," + tgtField + " from " + dbName + "." + tableName;
    allDesc = BSC.getJSONArray(dataQuery);
    String ID = allDesc.getJSONObject(i).getString("ID");
    String desc = allDesc.getJSONObject(i).getString(textField);
    String newdesc = desc.replaceAll("\\n", ".").replaceAll("\\r", " ");
    if (!newdesc.trim().equalsIgnoreCase("nothing"))
    {
        double[] outcomes = myCategorizer.categorize(newdesc);
        String category = myCategorizer.getBestCategory(outcomes);
        if (!category.equalsIgnoreCase("Unknown"))
        {
        String updQuery = "UPDATE " + dbName + "." + tableName + " set " + updateField + " = " + "'"
            + category + "'" + " WHERE ID = " + ID;
        BSC.executeUpdate(updQuery);
        }
    }

    }
    System.out.println(" ---------- Process Completed Successfully ----------");
    System.out.println("\nCheck your table  \"" + tableName + "\" for results");
    System.out.print("\n\nPress 1 to finish : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int ch = Integer.parseInt(br.readLine());
    } catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            BSC.connectionClose();
          }
          catch (SQLException e)
          {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }
      }
   }
}
</code>```

答:
The OpenNLP documentation is unclear, but there is a simple way of doing this.</p>

```<code> private DoccatModel deSerializeModel(String modelPath) throws
        IOException {
    FileInputStream fileInputStream = new FileInputStream(modelPath);
    DoccatModel model = new DoccatModel(fileInputStream);
    return model;
}
</code>```

Body:
I am trying to serialize a DoccatModel Object in Java (I am using OpenNLP algorithm).

It's able to serialize the object properly and I am writing that to an external file. But, I'm not able to deserialise the object back.

I am trying to use ObjectInputStream to read that file back. It's throwing an error:

"java.io.StreamCorruptedException: invalid stream header: 504B0304"

I just want to know how to de serialize the DoccatModel object back so that I can use it further.

The code is as follows. [Apologies for bad code since its still in development stage]

private static void runDocCat(String textField, String updateField, String tgtField)
{
    String dbName;
    String tableName;
    DoccatModel model = null;
    JSONArray allDesc = null;
    DataConfig BSC = null;
    try
    {
        BSC = new DataConfig();
    }
    catch (Exception e1)
    {
        e1.printStackTrace();
    }

    try
    {
        dbName = BSC.getdbName();
        tableName = BSC.tablename;
        String dataQuery = "SELECT ID, VOC, " + tgtField + " from " + dbName + "." + tableName;
        allDesc = BSC.getJSONArray(dataQuery);
        File file = new File("voc.train");
        BufferedWriter output = new BufferedWriter(new FileWriter(file));

        for (int i = 0; i < allDesc.length(); i++)
        {
            String tgt = allDesc.getJSONObject(i).getString(tgtField);
            if (tgt.length() < 3)
                tgt = "Unknown";
           tgt = tgt.replaceAll(" ", "");
           String desc = allDesc.getJSONObject(i).getString(textField);
           desc = desc.replaceAll("\\r", " ").replaceAll("\\n", ".");
           if (!desc.trim().equalsIgnoreCase("nothing"))
           {
                DocumentSample currDoc = new DocumentSample(tgt, desc);
                output.write(currDoc.toString());
                output.newLine();
           }
        }

        output.close();
        System.out.println("Training Data Generated!");
        ObjectStream<String> lineStream = new PlainTextByLineStream(new FileReader(file));
        ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
        model = DocumentCategorizerME.train("en", sampleStream);
        System.out.println("Model Data \n\n" + model);
        // Write to a file
        OutputStream modelOut = null;
        try
        {
            String modelfile = "C:\\VOC_Classification\\model.ser";
            modelOut = new BufferedOutputStream(new FileOutputStream(modelfile));
            model.serialize(modelOut);
            System.out.println("Model Data \n\n" + model);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (modelOut != null)
            try
            {
                modelOut.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }

    // try
    // {
    // FileOutputStream fileOut = new FileOutputStream("modelfile.ser");
    // ObjectOutputStream out = new ObjectOutputStream(fileOut);
    // out.writeObject(model);
    // out.close();
    // fileOut.close();
    // System.out.printf("Serialized data is saved in modelfile.ser");
    // } catch (IOException i)
    // {
    // i.printStackTrace();
    // }

    DoccatModel model_SER = null;
    try
    {
        FileInputStream fileIn = new FileInputStream("C:\\VOC_Classification\\model.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);
        model_SER = (DoccatModel) in.readObject();
        in.close();
        fileIn.close();
    } catch (IOException e)
    {
        e.printStackTrace();
    }

    System.out.println("\nTraining Done!\n");

    DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
    System.out.println(" ---------- Starting categorising process ----------");
    System.out.println("\nProcess Running, Please wait...\n");
    for (int i = 0; i < allDesc.length(); i++)
    {

    dataQuery = "SELECT ID, VOC," + tgtField + " from " + dbName + "." + tableName;
    allDesc = BSC.getJSONArray(dataQuery);
    String ID = allDesc.getJSONObject(i).getString("ID");
    String desc = allDesc.getJSONObject(i).getString(textField);
    String newdesc = desc.replaceAll("\\n", ".").replaceAll("\\r", " ");
    if (!newdesc.trim().equalsIgnoreCase("nothing"))
    {
        double[] outcomes = myCategorizer.categorize(newdesc);
        String category = myCategorizer.getBestCategory(outcomes);
        if (!category.equalsIgnoreCase("Unknown"))
        {
        String updQuery = "UPDATE " + dbName + "." + tableName + " set " + updateField + " = " + "'"
            + category + "'" + " WHERE ID = " + ID;
        BSC.executeUpdate(updQuery);
        }
    }

    }
    System.out.println(" ---------- Process Completed Successfully ----------");
    System.out.println("\nCheck your table  \"" + tableName + "\" for results");
    System.out.print("\n\nPress 1 to finish : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int ch = Integer.parseInt(br.readLine());
    } catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            BSC.connectionClose();
          }
          catch (SQLException e)
          {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }
      }
   }
}

Body:
The OpenNLP documentation is unclear, but there is a simple way of doing this.

 private DoccatModel deSerializeModel(String modelPath) throws
        IOException {
    FileInputStream fileInputStream = new FileInputStream(modelPath);
    DoccatModel model = new DoccatModel(fileInputStream);
    return model;
}


问:
iTextSharp automatically shrinking images when end of the page reach
I'm using iTextSharp to display images in a pdf report. Here I want display two images in a row and it's working as expected but having a issue when end of the page reaches. The issue is that last row images get shrink to fit in same page, it doesn't automatically add it to the next page. All images having same dimension and resolution.

答:
Please, provide us with the code.

I wrote the test below (although it's in java, there should be no problem) and the results seem to be correct.

```<code>    public void tableWithImagesTest01() throws IOException, InterruptedException {
    String testName = "tableWithImagesTest01.pdf";
    String outFileName = destinationFolder + testName;
    String cmpFileName = sourceFolder + "cmp_" + testName;

    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName));
    Document doc = new Document(pdfDoc, PageSize.A3);

    Image image1 = new Image(ImageDataFactory.create(sourceFolder + "itis.jpg"));
    Table table = new Table(2);
    for (int i = 0; i < 20; i++) {
        table.addCell(new Cell().add(image1));
        table.addCell(new Cell().add(image1));
        table.addCell(new Cell().add(new Paragraph("Hello")));
        table.addCell(new Cell().add(new Paragraph("World")));
    }
    doc.add(table);

    doc.close();
    Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
</code>```

The result pdf looks like this:

Maybe you use summat image1.setAutoScale(true);? Still we need your code to look at.

Body:
Please, provide us with the code.

I wrote the test below (although it's in java, there should be no problem) and the results seem to be correct.

    public void tableWithImagesTest01() throws IOException, InterruptedException {
    String testName = "tableWithImagesTest01.pdf";
    String outFileName = destinationFolder + testName;
    String cmpFileName = sourceFolder + "cmp_" + testName;

    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName));
    Document doc = new Document(pdfDoc, PageSize.A3);

    Image image1 = new Image(ImageDataFactory.create(sourceFolder + "itis.jpg"));
    Table table = new Table(2);
    for (int i = 0; i < 20; i++) {
        table.addCell(new Cell().add(image1));
        table.addCell(new Cell().add(image1));
        table.addCell(new Cell().add(new Paragraph("Hello")));
        table.addCell(new Cell().add(new Paragraph("World")));
    }
    doc.add(table);

    doc.close();
    Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}

The result pdf looks like this:

Maybe you use summat image1.setAutoScale(true);? Still we need your code to look at.


问:
Vaadin SessionDestroyListener session access
Is it possible to access session attributes inside the  Vaadin SessionDestroyListener ? Or is it called after session getting destroyed ?
How the call back order regarding to HttpSessionListener, before or after ? </p>

答:
While the session object is available by calling sessionDestroyEvent.getSession(), its state is CLOSING and all attributes have already been removed from it (rather simple to test this...).

EDIT

@Morfic is completely right, so he gets the credit: when in a SessionDestroyListener's sessionDestroy() method, the session's attributes are, indeed, still available (I was not careful in my tests; re-did them, using the latest Vaadin release, 8.0.4).


问:
Sequential Touch Actions throws exception

The problem

I'm trying to scroll on an Ionic App. I would like to scroll until an element is visible.
To test the procedure, I've written two sequential actions.
While testing just the first one is evaluated, the second one throws an exception Support for this gesture is not yet implemented.
How do I scroll, like a user would do, untill an element is visible if I cannot repeat actions?

Environment

Appium version 1.6.4-beta

Desktop OS/version used to run Appium: OSX Sierra

Real device or emulator/simulator: iPad Mini

Code To Reproduce Issue

```<code>TouchAction action = new TouchAction(this.driver);
Thread.sleep(5000);
action.press(150, 150).moveTo(0, 350).release().perform();
Thread.sleep(10000);
action.press(150, 150).moveTo(0, 350).release().perform();
</code>```

答:
The only possible, and horrible, solution that I've found is:

```<code>while( !element.isDisplayed() ){

    TouchAction action = new TouchAction(this.driver);
    action.press(150, 150).moveTo(0, 350).release().perform();
    Thread.sleep(5000);

}
</code>```

Hopefully someone can suggest a cleaner solution.

Body:
The problem

I'm trying to scroll on an Ionic App. I would like to scroll until an element is visible.
To test the procedure, I've written two sequential actions.
While testing just the first one is evaluated, the second one throws an exception Support for this gesture is not yet implemented.
How do I scroll, like a user would do, untill an element is visible if I cannot repeat actions?

Environment

Appium version 1.6.4-beta

Desktop OS/version used to run Appium: OSX Sierra

Real device or emulator/simulator: iPad Mini

Code To Reproduce Issue

TouchAction action = new TouchAction(this.driver);
Thread.sleep(5000);
action.press(150, 150).moveTo(0, 350).release().perform();
Thread.sleep(10000);
action.press(150, 150).moveTo(0, 350).release().perform();

Body:
The only possible, and horrible, solution that I've found is:

while( !element.isDisplayed() ){

    TouchAction action = new TouchAction(this.driver);
    action.press(150, 150).moveTo(0, 350).release().perform();
    Thread.sleep(5000);

}

Hopefully someone can suggest a cleaner solution.


问:
Encoding: 008D character?
Problem: I have a bunch of txt files written in Portuguese on a Windows machine using NotePad. Some of them seem to have been encoded as ANSI. When I open these files using gedit on Ubuntu, some of them contain boxes containing 008D (see screenshot). This is after converting them to UTF-8.

When I print the file contents to the terminal using cat, head or more, this is the output of the same file. Note that everything from última vez up to and including the strange character isn't printed to the terminal.

```<code>Olá madrinha! Eu gostava de ir contigo passar férias na montanha, porque acho que vai ser divertido e há muito tempo que já não vou a tua casa e na últimaar a ter saudades. Madrinha, não sei porque és tão simpática comigo mas para mim, és a melhor madrinha do mundo inteiro.  Madrinha, ajudas-me sempre que preciso e estás sempre a apoiar-me por isso, quero ir a tua casa para te apoiar a ti.  Obrigada madrinha, por me apoiares.  Muito obrigado madrinha
</code>```

When I open the same file using atom.io, everything looks as it should:

Questions: Most pressingly: How can I get rid of this character without opening all files and manually deleting them? And secondly, what is this, i.e., what should I google to solve similar problems?

答:
Found the magical keywords ('remove unicode string using sed'). This does the trick: https://stackoverflow.com/a/8562661/1331521:</p>

```<code># Define unicode character you want to remove;
# In this case 008D:
CHARS=$(python -c 'print u"\u008D".encode("utf8")')

# Then run sed on all files in directory
sed -i 's/['"$CHARS"']//g' *
</code>```

Title: Encoding: 008D character?

Body:
Problem: I have a bunch of txt files written in Portuguese on a Windows machine using NotePad. Some of them seem to have been encoded as ANSI. When I open these files using gedit on Ubuntu, some of them contain boxes containing 008D (see screenshot). This is after converting them to UTF-8.

When I print the file contents to the terminal using cat, head or more, this is the output of the same file. Note that everything from última vez up to and including the strange character isn't printed to the terminal.

Olá madrinha! Eu gostava de ir contigo passar férias na montanha, porque acho que vai ser divertido e há muito tempo que já não vou a tua casa e na últimaar a ter saudades. Madrinha, não sei porque és tão simpática comigo mas para mim, és a melhor madrinha do mundo inteiro.  Madrinha, ajudas-me sempre que preciso e estás sempre a apoiar-me por isso, quero ir a tua casa para te apoiar a ti.  Obrigada madrinha, por me apoiares.  Muito obrigado madrinha

When I open the same file using atom.io, everything looks as it should:

Questions: Most pressingly: How can I get rid of this character without opening all files and manually deleting them? And secondly, what is this, i.e., what should I google to solve similar problems?

Body:
Found the magical keywords ('remove unicode string using sed'). This does the trick: https://stackoverflow.com/a/8562661/1331521:

# Define unicode character you want to remove;
# In this case 008D:
CHARS=$(python -c 'print u"\u008D".encode("utf8")')

# Then run sed on all files in directory
sed -i 's/['"$CHARS"']//g' *


问:
Stop animation from taking my view out of screen android
This is my xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <Button
        android:id="@+id/bounceBallButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Bounce Ball" />

    <ImageView
        android:id="@+id/bounceBallImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/bounceBallButton"
        android:src="@drawable/ball" />

</RelativeLayout>
</code>```

and this is my animation code to bounce my imageview:

```<code>Button bounceBallButton = (Button) findViewById(R.id.bounceBallButton);
final ImageView bounceBallImage = (ImageView) findViewById(R.id.bounceBallImage);
bounceBallImage.clearAnimation();
TranslateAnimation transAnim = new TranslateAnimation(0, 0, 0, getDisplayHeight());
transAnim.setStartOffset(500);
transAnim.setDuration(3000);
transAnim.setFillAfter(true);
transAnim.setInterpolator(new BounceInterpolator());
bounceBallImage.startAnimation(transAnim);
</code>```

My problem is that the animation takes my imageview below my screen. I want it to hit at the bottom of my screen and bounce and not go below it.

答:
You animate Y position to getDisplayHeight(). Which means, that you tell the framework:

animate this view's top Y position to the screen's bottom.

And framework does exactly what you say.

What you want to do is to animate to getDisplayHeight() - bounceBallImage.getHeight(). But as soon as you do that, you'll find out, that it gives you the same result. That's because getHeight() returns 0, and that's because your view's hasn't been drawn, hence it has not height.

See here how to know the height of the view as soon as it is measured. You'd be using getMeasuredHeight() instead of getHeight().

Body:
This is my xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <Button
        android:id="@+id/bounceBallButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Bounce Ball" />

    <ImageView
        android:id="@+id/bounceBallImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/bounceBallButton"
        android:src="@drawable/ball" />

</RelativeLayout>

and this is my animation code to bounce my imageview:

Button bounceBallButton = (Button) findViewById(R.id.bounceBallButton);
final ImageView bounceBallImage = (ImageView) findViewById(R.id.bounceBallImage);
bounceBallImage.clearAnimation();
TranslateAnimation transAnim = new TranslateAnimation(0, 0, 0, getDisplayHeight());
transAnim.setStartOffset(500);
transAnim.setDuration(3000);
transAnim.setFillAfter(true);
transAnim.setInterpolator(new BounceInterpolator());
bounceBallImage.startAnimation(transAnim);

My problem is that the animation takes my imageview below my screen. I want it to hit at the bottom of my screen and bounce and not go below it.


问:
Angular - getting GET variable using $location
I'm tring to get a GET var from the url using Angular $location.search() but it didn't work.

This is the code:

jsfiddle

and this is the GET

```<code>var app = angular.module('myApp',[]);

app.controller('odinvite', function ($scope, $location)
    {
        //$scope.mytry = 5;
        $scope.mytry =$location.search().username;
    }
);
</code>```

What's the problem? There is other way besides?

thanks!

EDIT -

I tried to add manually hash to the url like this - "mydomain.com/foo.php#?username=7" and it worked!
But I don't to add hash every time and I want the $location to grab it automatically.

I also tried to add this -

```<code> app.config(['$locationProvider', function($locationProvider) {
        $locationProvider.html5Mode(true);
    }]);
</code>```

to solve it but it gave me an error -

```<code>Error: [$location:nobase] http://errors.angularjs.org/1.4.8/$location/nobase
    at angular.js:38
    at hf.$get (angular.js:12196)
    at Object.e [as invoke] (angular.js:4523)
    at angular.js:4340
    at d (angular.js:4482)
    at Object.e [as invoke] (angular.js:4514)
    at M.instance (angular.js:9182)
    at D (angular.js:8299)
    at g (angular.js:7731)
    at angular.js:7611
(anonymous) @ angular.js:12520
(anonymous) @ angular.js:9292
$apply @ angular.js:16157
(anonymous) @ angular.js:1679
e @ angular.js:4523
c @ angular.js:1677
yc @ angular.js:1697
Zd @ angular.js:1591
(anonymous) @ angular.js:29013
b @ angular.js:3057
If @ angular.js:3346
d @ angular.js:3334
</code>```

答: This is an issue with JS Fiddle and the way query string properties work with iFrames.  See here: How to pass GET parameters to jsFiddle</p>

Body:
I'm tring to get a GET var from the url using Angular $location.search() but it didn't work.

This is the code:

jsfiddle

and this is the GET

var app = angular.module('myApp',[]);

app.controller('odinvite', function ($scope, $location)
    {
        //$scope.mytry = 5;
        $scope.mytry =$location.search().username;
    }
);

What's the problem? There is other way besides?

thanks!

EDIT -

I tried to add manually hash to the url like this - "mydomain.com/foo.php#?username=7" and it worked!
But I don't to add hash every time and I want the $location to grab it automatically.

I also tried to add this -

 app.config(['$locationProvider', function($locationProvider) {
        $locationProvider.html5Mode(true);
    }]);

to solve it but it gave me an error -

Error: [$location:nobase] http://errors.angularjs.org/1.4.8/$location/nobase
    at angular.js:38
    at hf.$get (angular.js:12196)
    at Object.e [as invoke] (angular.js:4523)
    at angular.js:4340
    at d (angular.js:4482)
    at Object.e [as invoke] (angular.js:4514)
    at M.instance (angular.js:9182)
    at D (angular.js:8299)
    at g (angular.js:7731)
    at angular.js:7611
(anonymous) @ angular.js:12520
(anonymous) @ angular.js:9292
$apply @ angular.js:16157
(anonymous) @ angular.js:1679
e @ angular.js:4523
c @ angular.js:1677
yc @ angular.js:1697
Zd @ angular.js:1591
(anonymous) @ angular.js:29013
b @ angular.js:3057
If @ angular.js:3346
d @ angular.js:3334


问:
HTML picture in div won't fill out body completely
I want to use a picture (jpg) as a background for my page.

This is how I tried to tackle the problem :
Create the body, inside the body put a div with the id backgroundWallpaper.
Inside the div i put the image.
The problem is though that it's completely filled out to the site (horizontal) and also to the top but at the bottom there is a small gap between the picture and the browser. I changed the body background to crimson red to demonstrate you the gap. I use the latest version of safari as my browser. This is my code :
index.html

```<code><!DOCTYPE html>
 <html>
  <head>
   <meta charset="utf-8">
   <title>name</title>
   <linkrel="stylesheet"
   href"http://meyerweb.com/eric/tools/css/reset/reset.css">
   <link rel="stylesheet" href="main.css">
  </head>
  <body>
   <div id="backgroundWallpaper">
    <img src=".../img/1.jpg" alt="image could not be loaded">
   </div>
  </body>
 </html>
</code>```

This is my css file

```<code>body {
 background: crimson;
 margin: 0;
 padding: 0;
}

#backgroundWallpaper img {
 max-width: 100%;
}
</code>```

答:
In case you don't want to see the image when you scroll down the page</p>

```<code>#backgroundWallpaper{
  background-image: url(...);
  background-size: cover;
  background-position: center;
  position: absolute;
  top: 0;
  width: 100%;
  height: 100vh; /* viewport height */
}
</code>```

Body:
I want to use a picture (jpg) as a background for my page.

This is how I tried to tackle the problem :
Create the body, inside the body put a div with the id backgroundWallpaper.
Inside the div i put the image.
The problem is though that it's completely filled out to the site (horizontal) and also to the top but at the bottom there is a small gap between the picture and the browser. I changed the body background to crimson red to demonstrate you the gap. I use the latest version of safari as my browser. This is my code :
index.html

<!DOCTYPE html>

   <meta charset="utf-8">
   <title>name</title>
   <linkrel="stylesheet"
   href"http://meyerweb.com/eric/tools/css/reset/reset.css">
   <link rel="stylesheet" href="main.css">

This is my css file

body {
 background: crimson;
 margin: 0;
 padding: 0;
}

#backgroundWallpaper img {
 max-width: 100%;
}

Body:
In case you don't want to see the image when you scroll down the page

#backgroundWallpaper{
  background-image: url(...);
  background-size: cover;
  background-position: center;
  position: absolute;
  top: 0;
  width: 100%;
  height: 100vh; /* viewport height */
}


问:
SQL Server Windows Authentication and Hibernate
Trying to connect, using Hibernate 4.3, to SQL Server with Windows Authentication, i'm getting a:

"No Persistence provider for EntityManager named instanceTest"

I have loaded the sqljdbc_auth.dll library and im using this url:

```<code>jdbc:sqlserver://localhost:1433;databaseName=WIN_AUTHDB;integratedSecurity=true
</code>```

The parameters which i am using to create the entity manager factory are:

```<code>properties.put("background-validation", "true");
properties.put("hibernate.c3p0.idle_test_period", "3600");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.max_fetch_depth", "3");
properties.put("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
properties.put("hibernate.connection.url","jdbc:sqlserver://localhost:1433;databaseName=WIN_AUTHDB;integratedSecurity=true");
</code>```

Im missing something? Maybe is the dll not loaded? The error is thrown at this line:

```<code>Persistence.createEntityManagerFactory("instanceTest", initProperties(properties));
</code>```

The database is correctly configured, i have connected through Windows Authentication with the SQL Server Management. Also, in a previous test, i achieved to create a database using the driver without hibernate.

Thanks in advance.

答:
Along those, add the below property </p>

```<code>properties.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
</code>```

Body:
Trying to connect, using Hibernate 4.3, to SQL Server with Windows Authentication, i'm getting a:

"No Persistence provider for EntityManager named instanceTest"

I have loaded the sqljdbc_auth.dll library and im using this url:

jdbc:sqlserver://localhost:1433;databaseName=WIN_AUTHDB;integratedSecurity=true

The parameters which i am using to create the entity manager factory are:

properties.put("background-validation", "true");
properties.put("hibernate.c3p0.idle_test_period", "3600");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.max_fetch_depth", "3");
properties.put("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
properties.put("hibernate.connection.url","jdbc:sqlserver://localhost:1433;databaseName=WIN_AUTHDB;integratedSecurity=true");

Im missing something? Maybe is the dll not loaded? The error is thrown at this line:

Persistence.createEntityManagerFactory("instanceTest", initProperties(properties));

The database is correctly configured, i have connected through Windows Authentication with the SQL Server Management. Also, in a previous test, i achieved to create a database using the driver without hibernate.

Thanks in advance.

Body:
Along those, add the below property

properties.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");


问:
I want to display 13.00 rather than 13
now I have 3 textboxes that the user can type in them his degrees and the average will be calculated and displayed in another textbox! I've made the result to show just two fractional digits by calling the Math.Round() Method
This is my code:

```<code>double Sum = int.Parse(textBox1.Text) + int.Parse(textBox2.Text) + int.Parse(textBox3.Text);
double Avg =  Sum / 3;
textBox4.Text = Math.Round(Avg, 2).ToString();
</code>```

My problem is whenever the average is equal to an integer number like 20, I want it to display 20.00

答:
Since C# 6.0 you can use string interpolation to format variables into a string (in this case, format the number with two decimal places):

```<code>$"{Avg:.00}"
</code>```

Alternatively, use string#Format:

```<code>string.Format("{0:.00}", Avg);
</code>```

If you don't want to use either of those, you can use the ToString function with this parameter for that as mentioned in the comments:

```<code>Avg.ToString("0.00")
</code>```

Title: I want to display 13.00 rather than 13

Body:
now I have 3 textboxes that the user can type in them his degrees and the average will be calculated and displayed in another textbox! I've made the result to show just two fractional digits by calling the Math.Round() Method
This is my code:

double Sum = int.Parse(textBox1.Text) + int.Parse(textBox2.Text) + int.Parse(textBox3.Text);
double Avg =  Sum / 3;
textBox4.Text = Math.Round(Avg, 2).ToString();

My problem is whenever the average is equal to an integer number like 20, I want it to display 20.00

Body:
Since C# 6.0 you can use string interpolation to format variables into a string (in this case, format the number with two decimal places):

$"{Avg:.00}"

Alternatively, use string#Format:

string.Format("{0:.00}", Avg);

If you don't want to use either of those, you can use the ToString function with this parameter for that as mentioned in the comments:

Avg.ToString("0.00")


问:
Fixed navigation header in navigation drawer while scrolling through items
CURRENT STATE: NavigationDrawer with a NavigationHeader and NavigationMenu items. The items are large in number so scrolling is required in order to access the items towards the bottom.

REQUIREMENT: When scrolling down to the bottom, the NavigationHeader should stay fixed

Here's my activity_main layout file

```<code><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    android:background="#00000000"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer"
    />

</android.support.v4.widget.DrawerLayout>
</code>```

Here's my navigation_header_main layout file

```<code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical"
android:background="#3d3b3b"

android:theme="@style/ThemeOverlay.AppCompat.Dark">

<android.support.v7.widget.AppCompatImageView
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:src="@drawable/categories"
    android:padding="1dp"
    />

</RelativeLayout>
</code>```

P.S I am new to android dev. Please ask for more resources if required

答:
Just wrap the navigation view into a linear layout

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include layout="@layout/nav_header_main"/>

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="#00000000"
            android:fitsSystemWindows="true"
            app:menu="@menu/activity_main_drawer"/>

    </LinearLayout>
```

Body:
CURRENT STATE: NavigationDrawer with a NavigationHeader and NavigationMenu items. The items are large in number so scrolling is required in order to access the items towards the bottom.

REQUIREMENT: When scrolling down to the bottom, the NavigationHeader should stay fixed

Here's my activity_main layout file

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    android:background="#00000000"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer"
    />

</android.support.v4.widget.DrawerLayout>

Here's my navigation_header_main layout file

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical"
android:background="#3d3b3b"

android:theme="@style/ThemeOverlay.AppCompat.Dark">

<android.support.v7.widget.AppCompatImageView
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:src="@drawable/categories"
    android:padding="1dp"
    />

</RelativeLayout>

P.S I am new to android dev. Please ask for more resources if required


问:
500 error on UrlFetchApp
I am trying to pass data of a product list from Magento API to Google Spreadsheet.
No authentication was required for the Magento API as I was retrieving the data as a Guest. The API is working perfectly with RestClient.

However, 500 error occurred when fetching the REST resource from Googe Apps Script.

```<code>Exception: Request failed for
http://mymagentohost/api/rest/products?limit=2
returned code 500. Truncated server response: Service temporary
unavailable (use muteHttpExceptions option to examine full response)
</code>```

This is my Google Apps Script:

```<code>function myscript() {
  var url = "http://mymagentohost/api/rest/products?limit=2"
  var response = UrlFetchApp.fetch(url);

  var out = JSON.parse(response.getContentText());
  var doc = SpreadsheetApp.create("Product Info");
  var cell = doc.getRange('a1');
  var index = 0;
  for (var i in out) {
  var value = out[i];
  cell.offset(index, 0).setValue(i);
  cell.offset(index, 1).setValue(value);
  index++;
}
</code>```

Any ideas?

答:
Hey the trick is to add the following headers to your request

```<code>var url = "http://mymagentohost/api/rest/products?limit=2"

var params = {
  headers: { 'Content-Type': "application/json", 'Accept': "application/json"},
  muteHttpExceptions: true,
  method: "GET",
  contentType: "application/json",
  validateHttpsCertificates: false,
};

var response = UrlFetchApp.fetch(url, params);
</code>```

Believe the key params for Magento not to return 500 "Service temporary unavailable" are the Content-Type and Accept headers but all params mentioned in example are useful, YMMV.

Title: 500 error on UrlFetchApp

Body:
I am trying to pass data of a product list from Magento API to Google Spreadsheet.
No authentication was required for the Magento API as I was retrieving the data as a Guest. The API is working perfectly with RestClient.

However, 500 error occurred when fetching the REST resource from Googe Apps Script.

Exception: Request failed for
http://mymagentohost/api/rest/products?limit=2
returned code 500. Truncated server response: Service temporary
unavailable (use muteHttpExceptions option to examine full response)

This is my Google Apps Script:

function myscript() {
  var url = "http://mymagentohost/api/rest/products?limit=2"
  var response = UrlFetchApp.fetch(url);

  var out = JSON.parse(response.getContentText());
  var doc = SpreadsheetApp.create("Product Info");
  var cell = doc.getRange('a1');
  var index = 0;
  for (var i in out) {
  var value = out[i];
  cell.offset(index, 0).setValue(i);
  cell.offset(index, 1).setValue(value);
  index++;
}

Any ideas?

Body:
Hey the trick is to add the following headers to your request

var url = "http://mymagentohost/api/rest/products?limit=2"

var params = {
  headers: { 'Content-Type': "application/json", 'Accept': "application/json"},
  muteHttpExceptions: true,
  method: "GET",
  contentType: "application/json",
  validateHttpsCertificates: false,
};

var response = UrlFetchApp.fetch(url, params);

Believe the key params for Magento not to return 500 "Service temporary unavailable" are the Content-Type and Accept headers but all params mentioned in example are useful, YMMV.


问:
Javascript - Google Maps API V3 draw line on street using street name
I'm currently creating a custom map using the Javascript Google Maps V3 API.

I alreay know how to add markers, but currently I need to do something more "complex".
I need help right now to find a way to draw in the map, lines in the streets that I want.

Do you know how to do it or have some reference?

答:
Below is a good starting point and refernece for you to research further, this uses google polylines to draw lines on map for this example, the user pick to points on the map and a line is contructed...Please not you will have to use a valid key for this example to work... hope this helps best of luck

      // This example creates an interactive map which constructs a polyline based on
      // user clicks. Note that the polyline only appears once its path property
      // contains two LatLng coordinates.

      var poly;
      var map;

      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 7,
          center: {lat: 41.879, lng: -87.624}  // Center the map on Chicago, USA.
        });

        poly = new google.maps.Polyline({
          strokeColor: '#000000',
          strokeOpacity: 1.0,
          strokeWeight: 3
        });
        poly.setMap(map);

        // Add a listener for the click event
        map.addListener('click', addLatLng);
      }

      // Handles click events on a map, and adds a new point to the Polyline.
      function addLatLng(event) {
        var path = poly.getPath();

        // Because path is an MVCArray, we can simply append a new coordinate
        // and it will automatically appear.
        path.push(event.latLng);

        // Add a new marker at the new plotted point on the polyline.
        var marker = new google.maps.Marker({
          position: event.latLng,
          title: '#' + path.getLength(),
          map: map
        });
      }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }</code>```

<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Complex Polylines</title>

```

Body:
Below is a good starting point and refernece for you to research further, this uses google polylines to draw lines on map for this example, the user pick to points on the map and a line is contructed...Please not you will have to use a valid key for this example to work... hope this helps best of luck

      // This example creates an interactive map which constructs a polyline based on
      // user clicks. Note that the polyline only appears once its path property
      // contains two LatLng coordinates.

      var poly;
      var map;

      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 7,
          center: {lat: 41.879, lng: -87.624}  // Center the map on Chicago, USA.
        });

        poly = new google.maps.Polyline({
          strokeColor: '#000000',
          strokeOpacity: 1.0,
          strokeWeight: 3
        });
        poly.setMap(map);

        // Add a listener for the click event
        map.addListener('click', addLatLng);
      }

      // Handles click events on a map, and adds a new point to the Polyline.
      function addLatLng(event) {
        var path = poly.getPath();

        // Because path is an MVCArray, we can simply append a new coordinate
        // and it will automatically appear.
        path.push(event.latLng);

        // Add a new marker at the new plotted point on the polyline.
        var marker = new google.maps.Marker({
          position: event.latLng,
          title: '#' + path.getLength(),
          map: map
        });
      }

      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Complex Polylines</title>

  </head>
  <body>
    <div id="map"></div>

    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>


问:
Apache mod-headers - keep only specific cookies
I am trying to use a "RequestHeader edit" directive to manipulate the "Cookie" header and only keep a specific set of cookies from that header.

```<code>RequestHeader edit Cookie "PATTERN TO REMOVE ALL COOKIES DESPITE OF .." ""
</code>```

Incoming

```<code>someCookie=someValue; anotherCookie=yada61; cookieToKeep-1=myValue; cookieToKeep-2=myValue2; lastCookie=yada1
</code>```

To keep

```<code>cookieToKeep-1=myValue; cookieToKeep-2=myValue2;
</code>```

Goal is to remove all cookies but any cookie that starts with "cookieToKeep-".

I found that Pattern (CookieToKeep-\d=(([\w]*;)|[^\s]+)) gives me all matches for the cookies I need, but I need the negative of this pattern.

答: Try negative lookahead (for each cookie name): ^(?!cookieToKeep-).*.

Body:
I am trying to use a "RequestHeader edit" directive to manipulate the "Cookie" header and only keep a specific set of cookies from that header.

RequestHeader edit Cookie "PATTERN TO REMOVE ALL COOKIES DESPITE OF .." ""

Incoming

someCookie=someValue; anotherCookie=yada61; cookieToKeep-1=myValue; cookieToKeep-2=myValue2; lastCookie=yada1

To keep

cookieToKeep-1=myValue; cookieToKeep-2=myValue2;

Goal is to remove all cookies but any cookie that starts with "cookieToKeep-".

I found that Pattern (CookieToKeep-\d=(([\w]*;)|[^\s]+)) gives me all matches for the cookies I need, but I need the negative of this pattern.


问:
Not able to read conf file in spark scala
I would like to read a conf file in to my spark application. The conf file is located in Hadoop edge node directory.

omega.conf

```<code>username = "surrender"
location = "USA"
</code>```

My Spark Code :

```<code>package com.test.spark

import org.apache.spark.{SparkConf, SparkContext}
import java.io.File
import com.typesafe.config.{ Config, ConfigFactory }

object DemoMain {

 def main(args: Array[String]): Unit = {
 println("Lets Get Started ")
 val conf = new SparkConf().setAppName("SIMPLE")
 val sc = new SparkContext(conf)
 val sqlContext = new org.apache.spark.sql.hive.HiveContext(sc)
 val conf_loc = "/home/cloudera/localinputfiles/omega.conf"
 loadConfigFile(conf_loc)

 }

   def loadConfigFile(loc:String):Unit ={
       val config = ConfigFactory.parseFile(new File(loc))
       val username = config.getString("username")
       println(username)

 }

}
</code>```

I am running this spark application using spark-submit

```<code>  spark-submit --class com.test.spark.DemoMain --master local /home/cloudera/dev/jars/spark_examples.jar
</code>```

Spark job is initiated ,but it throws me the below error .It says that No configuration setting found for key 'username'

```<code>   17/03/29 12:57:37 INFO SparkContext: Created broadcast 0 from textFile at DemoMain.scala:25
Exception in thread "main" com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'username'
    at com.typesafe.config.impl.SimpleConfig.findKey(SimpleConfig.java:115)
    at com.typesafe.config.impl.SimpleConfig.find(SimpleConfig.java:136)
    at com.typesafe.config.impl.SimpleConfig.find(SimpleConfig.java:150)
    at com.typesafe.config.impl.SimpleConfig.find(SimpleConfig.java:155)
    at com.typesafe.config.impl.SimpleConfig.getString  (SimpleConfig.java:197)
    at com.test.spark.DemoMain$.loadConfigFile(DemoMain.scala:53)
    at com.test.spark.DemoMain$.main(DemoMain.scala:27)
    at com.test.spark.DemoMain.main(DemoMain.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at  org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:672)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:180)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:205)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:120)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
</code>```

Please help me on fixing this issue

答:
I just tried its working fine i test this with below code

```<code>val config=ConfigFactory.parseFile(new File("/home/sandy/my.conf"))
  println("::::::::::::::::::::"+config.getString("username"))
</code>```

and conf file is

username = "surrender"

location = "USA"

Please check location of your file by printing it.

Body:
I would like to read a conf file in to my spark application. The conf file is located in Hadoop edge node directory.

omega.conf

username = "surrender"
location = "USA"

My Spark Code :

package com.test.spark

import org.apache.spark.{SparkConf, SparkContext}
import java.io.File
import com.typesafe.config.{ Config, ConfigFactory }

object DemoMain {

 def main(args: Array[String]): Unit = {
 println("Lets Get Started ")
 val conf = new SparkConf().setAppName("SIMPLE")
 val sc = new SparkContext(conf)
 val sqlContext = new org.apache.spark.sql.hive.HiveContext(sc)
 val conf_loc = "/home/cloudera/localinputfiles/omega.conf"
 loadConfigFile(conf_loc)

 }

   def loadConfigFile(loc:String):Unit ={
       val config = ConfigFactory.parseFile(new File(loc))
       val username = config.getString("username")
       println(username)

 }

}

I am running this spark application using spark-submit

  spark-submit --class com.test.spark.DemoMain --master local /home/cloudera/dev/jars/spark_examples.jar

Spark job is initiated ,but it throws me the below error .It says that No configuration setting found for key 'username'

   17/03/29 12:57:37 INFO SparkContext: Created broadcast 0 from textFile at DemoMain.scala:25
Exception in thread "main" com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'username'
    at com.typesafe.config.impl.SimpleConfig.findKey(SimpleConfig.java:115)
    at com.typesafe.config.impl.SimpleConfig.find(SimpleConfig.java:136)
    at com.typesafe.config.impl.SimpleConfig.find(SimpleConfig.java:150)
    at com.typesafe.config.impl.SimpleConfig.find(SimpleConfig.java:155)
    at com.typesafe.config.impl.SimpleConfig.getString  (SimpleConfig.java:197)
    at com.test.spark.DemoMain$.loadConfigFile(DemoMain.scala:53)
    at com.test.spark.DemoMain$.main(DemoMain.scala:27)
    at com.test.spark.DemoMain.main(DemoMain.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at  org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:672)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:180)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:205)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:120)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

Please help me on fixing this issue

Body:
I just tried its working fine i test this with below code

val config=ConfigFactory.parseFile(new File("/home/sandy/my.conf"))
  println("::::::::::::::::::::"+config.getString("username"))

and conf file is

username = "surrender"

location = "USA"

Please check location of your file by printing it.


问:
Pass angularJs variable to javascript Variable
I have Angularjs variable that I want to pass in javascript variable.
I found solution
 here
so it didn't work. My code :

```<code><script>
var demo=angular.module('demo', []);
demo.controller('metrics', function($scope, $http) {
$http.get('http://localhost:8080/metrics').then(function(response)
    {
     $scope.metrics = response.data;
    });
    });
</script>

<div ng-controller="metrics">
<p>{{metrics}}<p>
</div>
<script>
var e = angular.element(document.querySelector('[ng-controller="metrics"]'));
var e1 = e.scope().metrics ;
alert(e1)
</script>
</code>```

I got result from {{metrics}}  but  e1  didn't return something.

Thanks for your help.

答:
From your current code, by the time the JS code executes, it will not contain metrics data.

The JS code should be written in the then response of the API call,

If you do that, the JS code will be called after the metrics gets a value.

```<code>var demo=angular.module('demo', []);
demo.controller('metrics', function($scope, $http) {
   $http.get('http://localhost:8080/metrics').then(function(response)
    {
       $scope.metrics = response.data;
       var e = angular.element(document.querySelector('[ng-controller="metrics"]'));
       var e1 = e.scope().metrics ;
       alert(e1);
    });
});
</code>```

Body:
I have Angularjs variable that I want to pass in javascript variable.
I found solution
 here
so it didn't work. My code :

{{metrics}}

I got result from {{metrics}}  but  e1  didn't return something.

Thanks for your help.

Body:
From your current code, by the time the JS code executes, it will not contain metrics data.

The JS code should be written in the then response of the API call,

If you do that, the JS code will be called after the metrics gets a value.

var demo=angular.module('demo', []);
demo.controller('metrics', function($scope, $http) {
   $http.get('http://localhost:8080/metrics').then(function(response)
    {
       $scope.metrics = response.data;
       var e = angular.element(document.querySelector('[ng-controller="metrics"]'));
       var e1 = e.scope().metrics ;
       alert(e1);
    });
});


问:
Good estimation of the number of cluster in online k-means
I would like to know if there is a best way to guess the number of cluster in online k-means. I'm trying to use kmeans to cluster lines in hough transform algorithm, but the number of cluster depends only of the image.
I would like to parse the image only one time. So I guess that's is not possible, but I want to be sure.

Thank you !!!

答:
One simple way would be a threshold.

Namely if the new element is farther than any cluster above certain threshold you'd open a new cluster with it as a centroid.


问:
Install cx_Oracle for Python
Am on Debian 5, I've been trying to install cx_oracle module for python without any success. First, I installed oracle-xe-client and its dependency (followed tutorial in the following link here).

Then, I used the scripts in /usr/lib/oracle/xe/app/oracle/product/10.2.0/client/bin to populate environment variables such as PATH, ORACLE_HOME and NLS_LANG.

Once, this was completed, I tried to run:

```<code>sudo easy_install cx_oracle
</code>```

But I keep getting the following error:

```<code>Searching for cx-oracle
Reading http://pypi.python.org/simple/cx_oracle/
Reading http://cx-oracle.sourceforge.net
Reading http://starship.python.net/crew/atuining
Best match: cx-Oracle 5.0.4
Downloading http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.0.4.tar.gz?download
Processing cx_Oracle-5.0.4.tar.gz
Running cx_Oracle-5.0.4/setup.py -q bdist_egg --dist-dir /tmp/easy_install-xsylvG/cx_Oracle-5.0.4/egg-dist-tmp-8KoqIx
error: cannot locate an Oracle software installation
</code>```

Any idea what I missed here?

答:
I recommend that you grab the rpm files and install them with alien. That way, you can later on run apt-get purge no-longer-needed.

In my case, the only env variable I needed is LD_LIBRARY_PATH, so I did:

```<code>echo export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client/lib >> ~/.bashrc
source ~/.bashrc
</code>```

I suppose in your case that path variable will be /usr/lib/oracle/xe/app/oracle/product/10.2.0/client/lib.

ContentLicense: CC BY-SA 4.0

Title: Install cx_Oracle for Python

Body:
Am on Debian 5, I've been trying to install cx_oracle module for python without any success. First, I installed oracle-xe-client and its dependency (followed tutorial in the following link here).

Then, I used the scripts in /usr/lib/oracle/xe/app/oracle/product/10.2.0/client/bin to populate environment variables such as PATH, ORACLE_HOME and NLS_LANG.

Once, this was completed, I tried to run:

sudo easy_install cx_oracle

But I keep getting the following error:

Searching for cx-oracle
Reading http://pypi.python.org/simple/cx_oracle/
Reading http://cx-oracle.sourceforge.net
Reading http://starship.python.net/crew/atuining
Best match: cx-Oracle 5.0.4
Downloading http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.0.4.tar.gz?download
Processing cx_Oracle-5.0.4.tar.gz
Running cx_Oracle-5.0.4/setup.py -q bdist_egg --dist-dir /tmp/easy_install-xsylvG/cx_Oracle-5.0.4/egg-dist-tmp-8KoqIx
error: cannot locate an Oracle software installation

Any idea what I missed here?

Body:
I recommend that you grab the rpm files and install them with alien. That way, you can later on run apt-get purge no-longer-needed.

In my case, the only env variable I needed is LD_LIBRARY_PATH, so I did:

echo export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client/lib >> ~/.bashrc
source ~/.bashrc

I suppose in your case that path variable will be /usr/lib/oracle/xe/app/oracle/product/10.2.0/client/lib.


问:
Why can I retrive an image with absolute path in XAML but it doesn't work behind code?
Trying to understand Assembly, Uri and all of those things and there is some stuff I don't understand and hopefully I can ask them here in one go.

I have a solution that contains two "Assembly's" if I understood it correctly like this.

Project Assemblies

Where I want my FetchResources to fetch that image and display it on my MainWindow.

It works without a problem when I do it in xaml like this.

Xaml FetchResources

But in behind-code I use the same Uri but for some reason it won't display the image.

```<code>var uri = new Uri("pack://application,,,/WPF_UserControll_Test;component/Images/71805972.jpg", UriKind.Absolute);
BitmapImage bmi = new BitmapImage();
bmi.UriSource = uri;
testimage.Source = bmi;
</code>```

I'm not sure if I've understood Assembly correctly nor do I understand Uri to the full extent. I've read Microsofts Pack URIs in WPF but it's not clear to me how it works.

Why Can I reach the image through XAML but not in behind-code?

答:
Try this:

MSDN

The following example shows the pack URI for a XAML resource file that is located in the root folder of a referenced, version-specific assembly's project folder.

pack://application:,,,/ReferencedAssembly;v1.0.0.1;component/ResourceFile.xaml

Body:
Trying to understand Assembly, Uri and all of those things and there is some stuff I don't understand and hopefully I can ask them here in one go.

I have a solution that contains two "Assembly's" if I understood it correctly like this.

Project Assemblies

Where I want my FetchResources to fetch that image and display it on my MainWindow.

It works without a problem when I do it in xaml like this.

Xaml FetchResources

But in behind-code I use the same Uri but for some reason it won't display the image.

var uri = new Uri("pack://application,,,/WPF_UserControll_Test;component/Images/71805972.jpg", UriKind.Absolute);
BitmapImage bmi = new BitmapImage();
bmi.UriSource = uri;
testimage.Source = bmi;

I'm not sure if I've understood Assembly correctly nor do I understand Uri to the full extent. I've read Microsofts Pack URIs in WPF but it's not clear to me how it works.

Why Can I reach the image through XAML but not in behind-code?


问:
How to control cordova-plugin-firebase for cordova?
How to control cordova-plugin-firebase for cordova?

I want to show push notifications if user logged in, otherwise it should not show.

Please give me some suggestions.

Thank you.

答:
One option is to add another API for the plugin, to set a boolean (e.g. setLoggedIn()).
You should call it from the JS side with true after login, and false after logout (or login screen is being shown).
On the native side, you should store the value (e.g. on SharedPreferences) and check if the value is true when a new notification arrives.</p>


问:
How to compare ImageView ids on click event?
I have a set of ImageView in which some of them are red colored blink for some time like below.

I want to do that ,When I'm click on colored blinked imageViews it change as tic mark and when I'm click non blinked imageViews it change as cross mark.

My issue is my current code only tic the one imageview and all other imageViews are cross marked.

So how to make tic mark more than one ImageView.

Here is my code:

```<code>  org_id = new int[]{R.id.img1_1, R.id.img1_2, R.id.img1_3, R.id.img1_4};

        all = new int[]{R.id.img1_1, R.id.img1_2, R.id.img1_3, R.id.img1_4};

        Random random = new Random();
        for(int j=0;j<2;j++) {
            id = all[random.nextInt(all.length)];

            ObjectAnimator animator = ObjectAnimator.ofInt(findViewById(id), "backgroundResource", R.drawable.new_stateimg, R.drawable.org_state).setDuration(2000);
            Toast.makeText(Game.this, "index" + findViewById(id), Toast.LENGTH_LONG).show();
            animator.setEvaluator(new ArgbEvaluator());
            animator.start();

        for (int i=0; i < org_id.length; ++i) {
            final int btn = org_id[i];

            findViewById(btn).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    if ((findViewById(id)).equals(findViewById(btn)))
                    {
                        findViewById(id).setBackgroundResource(R.drawable.correct);

                    } else {
                        Toast.makeText(Game.this, "wrong", Toast.LENGTH_SHORT).show();
                        findViewById(btn).setBackgroundResource(R.drawable.cross);

                    }

                }
            });
        }
        }
</code>```

答:
Compare your id like

```<code>    if (id.getId() == btn.getId())
</code>```

Do it in your code.

```<code>     public void onClick(View view) {
             ImageView imgView = (ImageView)view; //edited
             if(imgView.getDrawable().getConstantState().equals
        (getResources().getDrawable(R.drawable.correct).getConstantState()))
             imgView.setBackgroundResource(R.drawable.incorrect);//set here you incorrect image which you want.

            else
                imgView.setBackgroundResource(R.drawable.correct);//set here your correct image

  }
</code>```

Body:
I have a set of ImageView in which some of them are red colored blink for some time like below.

I want to do that ,When I'm click on colored blinked imageViews it change as tic mark and when I'm click non blinked imageViews it change as cross mark.

My issue is my current code only tic the one imageview and all other imageViews are cross marked.

So how to make tic mark more than one ImageView.

Here is my code:

  org_id = new int[]{R.id.img1_1, R.id.img1_2, R.id.img1_3, R.id.img1_4};

        all = new int[]{R.id.img1_1, R.id.img1_2, R.id.img1_3, R.id.img1_4};

        Random random = new Random();
        for(int j=0;j<2;j++) {
            id = all[random.nextInt(all.length)];

            ObjectAnimator animator = ObjectAnimator.ofInt(findViewById(id), "backgroundResource", R.drawable.new_stateimg, R.drawable.org_state).setDuration(2000);
            Toast.makeText(Game.this, "index" + findViewById(id), Toast.LENGTH_LONG).show();
            animator.setEvaluator(new ArgbEvaluator());
            animator.start();

        for (int i=0; i < org_id.length; ++i) {
            final int btn = org_id[i];

            findViewById(btn).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    if ((findViewById(id)).equals(findViewById(btn)))
                    {
                        findViewById(id).setBackgroundResource(R.drawable.correct);

                    } else {
                        Toast.makeText(Game.this, "wrong", Toast.LENGTH_SHORT).show();
                        findViewById(btn).setBackgroundResource(R.drawable.cross);

                    }

                }
            });
        }
        }

Body:
Compare your id like

    if (id.getId() == btn.getId())

Do it in your code.

     public void onClick(View view) {
             ImageView imgView = (ImageView)view; //edited
             if(imgView.getDrawable().getConstantState().equals
        (getResources().getDrawable(R.drawable.correct).getConstantState()))
             imgView.setBackgroundResource(R.drawable.incorrect);//set here you incorrect image which you want.

            else
                imgView.setBackgroundResource(R.drawable.correct);//set here your correct image

  }


问:
node.js buffer strange behavior
I'm trying to duplicate a buffer with slice of its arraybuffer, but the result buffer contains wrong value. Here is the example:

```<code>var sourceBuf = new Buffer(1);
sourceBuf.writeUInt8(1, 0);
var slice = sourceBuf.buffer.slice(0,1);
var resultBuf = new Buffer(slice);
console.log(resultBuf.readUInt8(0));
</code>```

outputs 118

In case of TypedArray all works as I at first expected:

```<code>var sourceBuf = new Uint8Array(1);
sourceBuf[0] = 1;
var slice = sourceBuf.buffer.slice(0,1);
var resultBuf = new Uint8Array(slice);
console.log(resultBuf[0]);
</code>```

outputs 1

So for now I want to know what causes such "different behavior".

答:
You seem to access the internal buffer and read the value. Try accessing the value like this:

```<code>var sourceBuf = new Buffer(1);
sourceBuf.writeUInt8(1, 0);
var slice = sourceBuf.slice(0,1); // Changed this line
var resultBuf = new Buffer(slice);
console.log(resultBuf.readUInt8(0));
</code>```

There are two possible cases on how the error gets generated:

the binary value in the raw buffer gets interpreted the wrong way

robertKlep suggests that the buffer-property is uninitialized internally

In either way, accessing that property seemed to be the error.

Title: node.js buffer strange behavior

Body:
I'm trying to duplicate a buffer with slice of its arraybuffer, but the result buffer contains wrong value. Here is the example:

var sourceBuf = new Buffer(1);
sourceBuf.writeUInt8(1, 0);
var slice = sourceBuf.buffer.slice(0,1);
var resultBuf = new Buffer(slice);
console.log(resultBuf.readUInt8(0));

outputs 118

In case of TypedArray all works as I at first expected:

var sourceBuf = new Uint8Array(1);
sourceBuf[0] = 1;
var slice = sourceBuf.buffer.slice(0,1);
var resultBuf = new Uint8Array(slice);
console.log(resultBuf[0]);

outputs 1

So for now I want to know what causes such "different behavior".

Body:
You seem to access the internal buffer and read the value. Try accessing the value like this:

var sourceBuf = new Buffer(1);
sourceBuf.writeUInt8(1, 0);
var slice = sourceBuf.slice(0,1); // Changed this line
var resultBuf = new Buffer(slice);
console.log(resultBuf.readUInt8(0));

There are two possible cases on how the error gets generated:

the binary value in the raw buffer gets interpreted the wrong way

robertKlep suggests that the buffer-property is uninitialized internally

In either way, accessing that property seemed to be the error.


问:
C3.js responsive x axis timeseries
I'm trying to create a graph that can look good on both mobile and desktop using c3 (http://c3js.org/).

However, I'm having trouble getting the x-axis, which is a timeseries, to display change size for mobile. The only way I've managed to do this is by destroying the graph and re-creating it from scratch. But this prevents me from adding a nice transition to the chart, which would be really nice to have.
[![desktop view][1]][1]

I tried using the tick culling option on the x axis and set a max value of 8, but this option gets ignored when using either flush() or resize() methods.

So my question is: is there any way to change the x axis values without having to destroy the graph and re-generate it?
http://imgur.com/EMECqqB

答:
I have used the onresized: function () {...}

or you can use the onresize: function () { ... }

link

to change the culling max on resized screen:

```<code>        axis: {
            x: {
                 type: 'timeseries',
                 tick: {
                    culling: true,
                    format: '%m-%d',
                    fit:true,
                    culling: {
                        max: window.innerWidth > 500 ? 8 : 5
                    }
                }
            }
        },

        onresized: function () {
            window.innerWidth > 500 ? chart.internal.config.axis_x_tick_culling_max = 8 : chart.internal.config.axis_x_tick_culling_max = 5;
        },
</code>```

Here a example: https://jsfiddle.net/07s4zx6c/2/

Title: C3.js responsive x axis timeseries

Body:
I have used the onresized: function () {...}

or you can use the onresize: function () { ... }

link

to change the culling max on resized screen:

        axis: {
            x: {
                 type: 'timeseries',
                 tick: {
                    culling: true,
                    format: '%m-%d',
                    fit:true,
                    culling: {
                        max: window.innerWidth > 500 ? 8 : 5
                    }
                }
            }
        },

        onresized: function () {
            window.innerWidth > 500 ? chart.internal.config.axis_x_tick_culling_max = 8 : chart.internal.config.axis_x_tick_culling_max = 5;
        },

Here a example: https://jsfiddle.net/07s4zx6c/2/


问:
Extjs, delete button
in this example : http://dev.sencha.com/deploy/dev/examples/grid/progress-bar-pager.html if i want to put an delete button, after the row is deleted from grid, how can i change or delete this record from myData? Because when i change the page, or click o refresh button my row/row's deleted appear again. is there a solution to change the data?

many thanks

答: this is the solution myData.splice (1,1);</p>

Title: Extjs, delete button


问:
Creating a bash script that will create a folder for each name in the file
I have create a text file using ubuntu terminal named users.txt.
In this text file I have 3 user names.
I need to create a bash script that creates 3 folders with the names inside the text file.

Example names:

```<code>Mr A
Mr B
Mr C
</code>```

I should have 3 folders with the above names.

Also in these folders there should also be 3 other folders named Music, Pictures, Documents and also a text file named Welcome.

答:
Something this should do it:

```<code>while IFS= read -r user_name; do
     mkdir -p "${user_name}"/{Music,Pictures,Documents}
     touch "${user_name}/Welcome"
done < users.txt
</code>```

Note that this assumes you run it from the same directory where you want these to appear and the file is in the same folder as the script.

Body:
I have create a text file using ubuntu terminal named users.txt.
In this text file I have 3 user names.
I need to create a bash script that creates 3 folders with the names inside the text file.

Example names:

Mr A
Mr B
Mr C

I should have 3 folders with the above names.

Also in these folders there should also be 3 other folders named Music, Pictures, Documents and also a text file named Welcome.

Body:
Something this should do it:

while IFS= read -r user_name; do
     mkdir -p "${user_name}"/{Music,Pictures,Documents}
     touch "${user_name}/Welcome"
done < users.txt

Note that this assumes you run it from the same directory where you want these to appear and the file is in the same folder as the script.