问:
How to search for all the characters from a string in all Dictionary.Values()
First of all I know that out there are many similar posts which I have listed below, however, none to my knowledge answer the problem I'm facing this is because all that I have found are asking how to search for a string in 'dict.values()' and not to search every single character in the string and check whether it is in the 'dict.values()' and if it has found any characters in the string that appear in the characters of 'dict.values()' it will return which and how many.

Links to similar posts which don't answer the question but could be useful to some:

How to search if dictionary value contains certain string with Python

Find dictionary items whose key matches a substring

How can I check if the characters in a string are in a dictionary of values?

How to search if dictionary value contains certain string with Python

This is what I have so far but don't seem to work at all...

```<code>characters = {'small':'abcdefghijklmnopqrstuvwxyz',
              'big':'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
              'nums':'0123456789',
              'special':"!#$%&()*+,-./:;<=>?@[\]^_{|}~",}

password = 'aAb'

def count(pass_word,char_set):

    num_of_char = 0
    char_list = []

    for char in pass_word:
        if i in char_set.values():
            num_of_char +=1
            char_list += i

    return char_list, num_of_char

#Print result

print(count(password,characters))
</code>```

The output should be something similar to:

```<code>'a','A','b'
3
</code>```

Hopefully, you understand what I mean and if anything unclear please comment so that I can improve it.

答:
```<code>def count(password, char_dict):
    sanitized_pass = [char for char in password if any(char in v for v in char_dict.values())]
    return sanitized_pass, len(sanitized_pass)
</code>```

Here's one way.  Another would be to build a set of all the acceptable c
characters and pass that to the function with the password

```<code>from itertools import chain

char_set = set(chain.from_iterable(characters.values()))

def count(password, chars):
    sanitized_pass = [char for char in password if char in char_set]
    return sanitized_pass, len(sanitized_pass)
</code>```

Body:
First of all I know that out there are many similar posts which I have listed below, however, none to my knowledge answer the problem I'm facing this is because all that I have found are asking how to search for a string in 'dict.values()' and not to search every single character in the string and check whether it is in the 'dict.values()' and if it has found any characters in the string that appear in the characters of 'dict.values()' it will return which and how many.

Links to similar posts which don't answer the question but could be useful to some:

How to search if dictionary value contains certain string with Python

Find dictionary items whose key matches a substring

How can I check if the characters in a string are in a dictionary of values?

How to search if dictionary value contains certain string with Python

This is what I have so far but don't seem to work at all...

characters = {'small':'abcdefghijklmnopqrstuvwxyz',
              'big':'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
              'nums':'0123456789',
              'special':"!#$%&()*+,-./:;<=>?@[\]^_{|}~",}

password = 'aAb'

def count(pass_word,char_set):

    num_of_char = 0
    char_list = []

    for char in pass_word:
        if i in char_set.values():
            num_of_char +=1
            char_list += i

    return char_list, num_of_char

#Print result

print(count(password,characters))

The output should be something similar to:

'a','A','b'
3

Hopefully, you understand what I mean and if anything unclear please comment so that I can improve it.

Body:
def count(password, char_dict):
    sanitized_pass = [char for char in password if any(char in v for v in char_dict.values())]
    return sanitized_pass, len(sanitized_pass)

Here's one way.  Another would be to build a set of all the acceptable c
characters and pass that to the function with the password

from itertools import chain

char_set = set(chain.from_iterable(characters.values()))

def count(password, chars):
    sanitized_pass = [char for char in password if char in char_set]
    return sanitized_pass, len(sanitized_pass)


来源: stackexchange

问:
CSS 2 fluid 1 fixed column
I am trying to achieve this layout.

left column fixed size

right column fluid, it may have x number of elements inside, for example up to 4 divs 50px wide (this is done dynamically) so it must be max 200px wide, or if it has 3 such elements, then it must be 150px wide...

center column fluid, takes all the rest space

The closest I have comes is this:

#container {
    overflow:hidden;
    width: 100%;
}

#leftcol {
    border: 1px solid #0f0;
    float: left;
    width: 80px;
}

#rightcol {
    border: 1px solid #0f0;
    float: right;

}

#centercol {
    border: 1px solid #000;
    margin-left: 80px;

}
.box{
  width:50px;
  height:20px;
  background:red;
  float:left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">

  <div id="leftcol">
    fixed 80px
  </div>
  <div id="rightcol">
    <div class="box">1</div>
    <div class="box">2</div>
    <div class="box">3</div>
    <div class="box">4</div>
  </div>
  <div id="centercol">
    fluid center
  </div>

</div></code>```

but center fluid is not correct width.

I can change some html if it will be easier to achieve desired effect.

答:
You can do it with the Flexbox:

body {margin: 0}

#container {
  display: flex; /* displays flex-items (children) inline */
  overflow: hidden;
}

#leftcol {
  border: 1px solid #0f0;
  width: 80px;
}

#centercol {
  flex: 1; /* takes the remaining horizontal space */
  border: 1px solid #000;
}

#rightcol {
  display: flex;
  border: 1px solid #0f0;
  max-width: 200px; /* adjust to your needs */
}

.box {
  width: 50px;
  height: 20px;
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div id="leftcol">
    fixed 80px
  </div>
  <div id="centercol">
    fluid center
  </div>
  <div id="rightcol">
    <div class="box">1</div>
    <div class="box">2</div>
    <div class="box">3</div>
    <div class="box">4</div>
  </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: CSS 2 fluid 1 fixed column

Body:
I am trying to achieve this layout.

left column fixed size

right column fluid, it may have x number of elements inside, for example up to 4 divs 50px wide (this is done dynamically) so it must be max 200px wide, or if it has 3 such elements, then it must be 150px wide...

center column fluid, takes all the rest space

The closest I have comes is this:

#container {
    overflow:hidden;
    width: 100%;
}

#leftcol {
    border: 1px solid #0f0;
    float: left;
    width: 80px;
}

#rightcol {
    border: 1px solid #0f0;
    float: right;

}

#centercol {
    border: 1px solid #000;
    margin-left: 80px;

}
.box{
  width:50px;
  height:20px;
  background:red;
  float:left;
}

    fixed 80px

1

2

3

4

    fluid center

but center fluid is not correct width.

I can change some html if it will be easier to achieve desired effect.

Body:
You can do it with the Flexbox:

body {margin: 0}

#container {
  display: flex; /* displays flex-items (children) inline */
  overflow: hidden;
}

#leftcol {
  border: 1px solid #0f0;
  width: 80px;
}

#centercol {
  flex: 1; /* takes the remaining horizontal space */
  border: 1px solid #000;
}

#rightcol {
  display: flex;
  border: 1px solid #0f0;
  max-width: 200px; /* adjust to your needs */
}

.box {
  width: 50px;
  height: 20px;
  background: red;
}

<div id="container">
  <div id="leftcol">
    fixed 80px
  </div>
  <div id="centercol">
    fluid center
  </div>
  <div id="rightcol">
    <div class="box">1</div>
    <div class="box">2</div>
    <div class="box">3</div>
    <div class="box">4</div>
  </div>
</div>

ContentLicense: CC BY-SA 4.0


问:
I created Analysis services databases by xmla scripts. But I can't show the values in table. e.g. run DAX 'evaluate table_name',there presents nothing
I want to create many Analysis Services Databases, but don't want to create Analysis Services Tabular Projects manually. So I run some xmla scripts. The databases are constructed After running, but I can't show or use the values in the table. when I run the DAX script 'evaluate table_name', there present nothing.

the example xmla scripts:

```<code>{
</code>```

"create": {
    "database": {
      "name": "SQA_200_12",
      "compatibilityLevel": 1200,
      "model": {
        "culture": "en-US",
        "dataSources": [
          {
            "name": "SqlServer localhost SQATables",
            "connectionString": "Provider=SQLNCLI11;Data Source=localhost;Initial Catalog=SQATables;Integrated Security=SSPI;Persist Security Info=false",
            "impersonationMode": "impersonateAccount",
            "account": "fareast\v-yanze",
            "annotations": [
              {
                "name": "ConnectionEditUISource",
                "value": "SqlServer"
              }
            ]
          }
        ],
        "tables": [
          {
            "name": "200_12",
            "columns": [
              {
                "name": "Year",
                "dataType": "string",
                "sourceColumn": "Year",
                "sourceProviderType": "Char"
              },
              {
                "name": "Award",
                "dataType": "string",
                "sourceColumn": "Award",
                "sourceProviderType": "Char"
              },
              {
                "name": "Category",
                "dataType": "string",
                "sourceColumn": "Category",
                "sourceProviderType": "Char"
              },
              {
                "name": "Nominated work",
                "dataType": "string",
                "sourceColumn": "Nominated work",
                "sourceProviderType": "Char"
              },
              {
                "name": "Result",
                "dataType": "string",
                "sourceColumn": "Result",
                "sourceProviderType": "Char"
              }
            ],
            "partitions": [
              {
                "name": "200_12",
                "dataView": "full",
                "source": {
                  "query": " SELECT [dbo].[200_12].* FROM [dbo].[200_12] ",
                  "dataSource": "SqlServer localhost SQATables"
                }
              }
            ],
            "annotations": [
              {
                "name": "_TM_ExtProp_QueryDefinition",
                "value": " SELECT [dbo].[200_12].* FROM [dbo].[200_12] "
              },
              {
                "name": "_TM_ExtProp_DbTableName",
                "value": "200_12"
              },
              {
                "name": "_TM_ExtProp_DbSchemaName",
                "value": "dbo"
              }
            ]
          }
        ],
        "annotations": [
          {
            "name": "ClientCompatibilityLevel",
            "value": "400"
          }
        ]
      }
    }
  }
}

Or are there any different ways to create analysis services databases conveniently. Thank you.

答: It looks like you have not processed the model. Right click the name of the model database in SSMS, and select the Process option.</p>

Body:
I want to create many Analysis Services Databases, but don't want to create Analysis Services Tabular Projects manually. So I run some xmla scripts. The databases are constructed After running, but I can't show or use the values in the table. when I run the DAX script 'evaluate table_name', there present nothing.

the example xmla scripts:

{

"create": {
    "database": {
      "name": "SQA_200_12",
      "compatibilityLevel": 1200,
      "model": {
        "culture": "en-US",
        "dataSources": [
          {
            "name": "SqlServer localhost SQATables",
            "connectionString": "Provider=SQLNCLI11;Data Source=localhost;Initial Catalog=SQATables;Integrated Security=SSPI;Persist Security Info=false",
            "impersonationMode": "impersonateAccount",
            "account": "fareast\v-yanze",
            "annotations": [
              {
                "name": "ConnectionEditUISource",
                "value": "SqlServer"
              }
            ]
          }
        ],
        "tables": [
          {
            "name": "200_12",
            "columns": [
              {
                "name": "Year",
                "dataType": "string",
                "sourceColumn": "Year",
                "sourceProviderType": "Char"
              },
              {
                "name": "Award",
                "dataType": "string",
                "sourceColumn": "Award",
                "sourceProviderType": "Char"
              },
              {
                "name": "Category",
                "dataType": "string",
                "sourceColumn": "Category",
                "sourceProviderType": "Char"
              },
              {
                "name": "Nominated work",
                "dataType": "string",
                "sourceColumn": "Nominated work",
                "sourceProviderType": "Char"
              },
              {
                "name": "Result",
                "dataType": "string",
                "sourceColumn": "Result",
                "sourceProviderType": "Char"
              }
            ],
            "partitions": [
              {
                "name": "200_12",
                "dataView": "full",
                "source": {
                  "query": " SELECT [dbo].[200_12].* FROM [dbo].[200_12] ",
                  "dataSource": "SqlServer localhost SQATables"
                }
              }
            ],
            "annotations": [
              {
                "name": "_TM_ExtProp_QueryDefinition",
                "value": " SELECT [dbo].[200_12].* FROM [dbo].[200_12] "
              },
              {
                "name": "_TM_ExtProp_DbTableName",
                "value": "200_12"
              },
              {
                "name": "_TM_ExtProp_DbSchemaName",
                "value": "dbo"
              }
            ]
          }
        ],
        "annotations": [
          {
            "name": "ClientCompatibilityLevel",
            "value": "400"
          }
        ]
      }
    }
  }
}

Or are there any different ways to create analysis services databases conveniently. Thank you.


问:
How can Airflow be used to run distinct tasks of one workflow in separate machines?
disclaimer: I'm not (yet) a user of Airflow, just found about it today and I'm starting to explore if it may fit my uses cases.

I have one data processing workflow that is a sequential (not parallel) execution of multiple tasks. However, some of the tasks need to run on specific machines. Can Airflow manage this? What would be the advised implementation model for this use case?

Thanks.

答:
Yes, you can achieve this in Airflow with queues. You can tie tasks to a specific queue. Then for each worker on a machine, you can set it to only pickup tasks from select queues.

In code, it would look like this:

```<code>task_1 = BashOperator(
    dag=dag,
    task_id='task_a',
    ...
)

task_2 = PythonOperator(
    dag=dag,
    task_id='task_b',
    queue='special',
    ...
)
</code>```

Note that there is this setting in airflow.cfg:

```<code># Default queue that tasks get assigned to and that worker listen on.
default_queue = default
</code>```

So if you started your workers with this:

```<code>Server A> airflow worker
Server B> airflow worker --queues special
Server C> airflow worker --queues default,special
</code>```

Then task_1 can be picked up by servers A+C and task_2 can be picked up by servers B+C.

Body:
Yes, you can achieve this in Airflow with queues. You can tie tasks to a specific queue. Then for each worker on a machine, you can set it to only pickup tasks from select queues.

In code, it would look like this:

task_1 = BashOperator(
    dag=dag,
    task_id='task_a',
    ...
)

task_2 = PythonOperator(
    dag=dag,
    task_id='task_b',
    queue='special',
    ...
)

Note that there is this setting in airflow.cfg:

# Default queue that tasks get assigned to and that worker listen on.
default_queue = default

So if you started your workers with this:

Server A> airflow worker
Server B> airflow worker --queues special
Server C> airflow worker --queues default,special

Then task_1 can be picked up by servers A+C and task_2 can be picked up by servers B+C.


问:
Android - Get Location Only One Time
i need to get the current user location on an android app, so i've read some tutorials and samples on the web, but i see that in all the examples, the location is retrived from a "onLocationChange" that mean that every time the location change, the code in the "onLocationChange" is executed.

i need only to get the user location at the moment the app is started.

Thanks for your help!

答: You can do this with LocationManager.getLastKnownLocation</p>

ContentLicense: CC BY-SA 2.5

Title: Android - Get Location Only One Time


问:
Configure Make to fail immediately with bad target
I am launching multiple builds of a verilog compiler using Make.  I am only using Make to take advantage of the -j flag.  My file looks something like this

```<code>allfpga: fpga0 fpga1 fpga2 fpga3 fpga4 fpga5 fpga6

fpga0:
    cd fpgas/$(@)/build && $(MAKE)
fpga1:
    cd fpgas/$(@)/build && $(MAKE)
fpga2:
    cd fpgas/$(@)/build && $(MAKE)
fpga3:
    cd fpgas/$(@)/build && $(MAKE)
fpga4:
    cd fpgas/$(@)/build && $(MAKE)
fpga5:
    cd fpgas/$(@)/build && $(MAKE)
fpga6:
    cd fpgas/$(@)/build && $(MAKE)
</code>```

And I invoke one of make -j2 allfpga or make -j2 fpga0 fpag3 fpga5 fpga6

However if there is a typo (such as in the command I gave fpag3), in the second make target, the system will happily spend minutes building, and then stop early.

My question, how can I get make to stop initially if some of the targets are not real ones?

答:
There's no good way to get make to "pre-screen" all your requested targets.  Make can't know if a target is buildable until it tries to build it (for example it could be created based on some other target using a pattern rule or something).

However, you could do something like this:

```<code>ALLFPGAS := fpga0 fpga1 fpga2 fpga3 fpga4 fpga5 fpga6

# Get any command line goal which is not one of ALLFPGAS
unknown := $(filter-out $(ALLFPGAS),$(MAKECMDGOALS))

# If there are any, bail!
$(if $(unknown),$(error Unknown FPGA: $(unknown)))

allfpga: $(ALLFPGAS)

$(ALLFPGAS):
        cd fpgas/$@/build && $(MAKE)

.PHONY: allfpga $(ALLFPGAS)
</code>```

Body:
I am launching multiple builds of a verilog compiler using Make.  I am only using Make to take advantage of the -j flag.  My file looks something like this

allfpga: fpga0 fpga1 fpga2 fpga3 fpga4 fpga5 fpga6

fpga0:
    cd fpgas/$(@)/build && $(MAKE)
fpga1:
    cd fpgas/$(@)/build && $(MAKE)
fpga2:
    cd fpgas/$(@)/build && $(MAKE)
fpga3:
    cd fpgas/$(@)/build && $(MAKE)
fpga4:
    cd fpgas/$(@)/build && $(MAKE)
fpga5:
    cd fpgas/$(@)/build && $(MAKE)
fpga6:
    cd fpgas/$(@)/build && $(MAKE)

And I invoke one of make -j2 allfpga or make -j2 fpga0 fpag3 fpga5 fpga6

However if there is a typo (such as in the command I gave fpag3), in the second make target, the system will happily spend minutes building, and then stop early.

My question, how can I get make to stop initially if some of the targets are not real ones?

Body:
There's no good way to get make to "pre-screen" all your requested targets.  Make can't know if a target is buildable until it tries to build it (for example it could be created based on some other target using a pattern rule or something).

However, you could do something like this:

ALLFPGAS := fpga0 fpga1 fpga2 fpga3 fpga4 fpga5 fpga6

# Get any command line goal which is not one of ALLFPGAS
unknown := $(filter-out $(ALLFPGAS),$(MAKECMDGOALS))

# If there are any, bail!
$(if $(unknown),$(error Unknown FPGA: $(unknown)))

allfpga: $(ALLFPGAS)

$(ALLFPGAS):
        cd fpgas/$@/build && $(MAKE)

.PHONY: allfpga $(ALLFPGAS)


问:
C++ unwanted destruction
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

```<code>#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}
</code>```

答:
The line b = B(); in C constructor instantiates a new object of type B, and uses B's copy constructor to copy such object in C::b.

When C constructor returns b doesn't get destroyed, but the B temporary object used to call b's copy constructor is.

You could just remove such instruction in order to avoid instantiation of a B temporary, in this case b will just be constructed using the default constructor.

Title: C++ unwanted destruction

Body:
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}


问:
Labelling a marker on a Google Cluster Maps
With the help of another StackOverflow post I've got a map working which makes the markers into clickable links.

I also need the markers to have a label of some kind so the user knows where they'll link to (right now, they're just blank pins) but I'm not sure how to modify this code to build that function in.

```<code>function initMap() {

var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 7,
      center: {lat: 53.618939, lng: -2.1602328}
    });

var locations = [
 ["http://www.google.com", {lat: 53.618939, lng: -2.1601132}],
 ["http://www.google.com", {lat: 53.61953, lng: -2.1623746}],
 ["http://www.google.com", {lat: 53.6178993, lng: -2.1601596}],
 ["http://www.google.com", {lat: 53.5369545, lng: -1.9941523}],
 ["http://www.google.com", {lat: 53.5380496, lng: -1.9974085}],];

var markers = locations.map(function(location) {
    var marker = new google.maps.Marker({
        map: map,
        position: location[1],
        url: location[0] //Will be different for each marker
    });

    google.maps.event.addListener(marker, 'click', function(){
        window.location.href = this.url;
    });
    return marker;
});

// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
</code>```

答:
To label each marker with a unique letter (at least for up to 26 markers), you can follow this example in the documentation

```<code>var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;

var markers = locations.map(function(location) {
  var marker = new google.maps.Marker({
    map: map,
    position: location[1],
    label: labels[labelIndex++ % labels.length],
    url: location[0] //Will be different for each marker
  });

  google.maps.event.addListener(marker, 'click', function() {
    window.location.href = this.url;
  });
  return marker;
});
</code>```

proof of concept fiddle

code snippet:

// In the following example, markers appear when the user clicks on the map.
// Each marker is labeled with a single alphabetical character.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;

function initMap() {

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: {
      lat: 53.618939,
      lng: -2.1602328
    }
  });

  var locations = [
    ["http://www.google.com", {lat: 53.618939,lng: -2.1601132}],
    ["http://www.google.com", {lat: 53.61953,lng: -2.1623746}],
    ["http://www.google.com", {lat: 53.6178993,lng: -2.1601596}],
    ["http://www.google.com", {lat: 53.5369545,lng: -1.9941523}],
    ["http://www.google.com", {lat: 53.5380496,lng: -1.9974085}],
  ];

  var markers = locations.map(function(location) {
    var marker = new google.maps.Marker({
      map: map,
      position: location[1],
      label: labels[labelIndex++ % labels.length],
      url: location[0] //Will be different for each marker
    });

    google.maps.event.addListener(marker, 'click', function() {
      window.location.href = this.url;
    });
    return marker;
  });

  // Add a marker clusterer to manage the markers.
  var markerCluster = new MarkerClusterer(map, markers, {
    imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
  });
}
google.maps.event.addDomListener(window, "load", initMap);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}</code>```

```

Body:
With the help of another StackOverflow post I've got a map working which makes the markers into clickable links.

I also need the markers to have a label of some kind so the user knows where they'll link to (right now, they're just blank pins) but I'm not sure how to modify this code to build that function in.

function initMap() {

var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 7,
      center: {lat: 53.618939, lng: -2.1602328}
    });

var locations = [
 ["http://www.google.com", {lat: 53.618939, lng: -2.1601132}],
 ["http://www.google.com", {lat: 53.61953, lng: -2.1623746}],
 ["http://www.google.com", {lat: 53.6178993, lng: -2.1601596}],
 ["http://www.google.com", {lat: 53.5369545, lng: -1.9941523}],
 ["http://www.google.com", {lat: 53.5380496, lng: -1.9974085}],];

var markers = locations.map(function(location) {
    var marker = new google.maps.Marker({
        map: map,
        position: location[1],
        url: location[0] //Will be different for each marker
    });

    google.maps.event.addListener(marker, 'click', function(){
        window.location.href = this.url;
    });
    return marker;
});

// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}

Body:
To label each marker with a unique letter (at least for up to 26 markers), you can follow this example in the documentation

var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;

var markers = locations.map(function(location) {
  var marker = new google.maps.Marker({
    map: map,
    position: location[1],
    label: labels[labelIndex++ % labels.length],
    url: location[0] //Will be different for each marker
  });

  google.maps.event.addListener(marker, 'click', function() {
    window.location.href = this.url;
  });
  return marker;
});

proof of concept fiddle

code snippet:

// In the following example, markers appear when the user clicks on the map.
// Each marker is labeled with a single alphabetical character.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;

function initMap() {

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: {
      lat: 53.618939,
      lng: -2.1602328
    }
  });

  var locations = [
    ["http://www.google.com", {lat: 53.618939,lng: -2.1601132}],
    ["http://www.google.com", {lat: 53.61953,lng: -2.1623746}],
    ["http://www.google.com", {lat: 53.6178993,lng: -2.1601596}],
    ["http://www.google.com", {lat: 53.5369545,lng: -1.9941523}],
    ["http://www.google.com", {lat: 53.5380496,lng: -1.9974085}],
  ];

  var markers = locations.map(function(location) {
    var marker = new google.maps.Marker({
      map: map,
      position: location[1],
      label: labels[labelIndex++ % labels.length],
      url: location[0] //Will be different for each marker
    });

    google.maps.event.addListener(marker, 'click', function() {
      window.location.href = this.url;
    });
    return marker;
  });

  // Add a marker clusterer to manage the markers.
  var markerCluster = new MarkerClusterer(map, markers, {
    imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
  });
}
google.maps.event.addDomListener(window, "load", initMap);

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/src/markerclusterer.js"></script>
<div id="map"></div>


问:
Testem receiving imports compiled to `require` when using ES2015/React presets to Babel
I have a project which is set up so that it builds with reactand jsx. It works fine to build it using node_modules/webpack/bin/webpack.js --config webpack.config.js and I can run the result in the browser with no problems. However, when I run npm test and view the test runner in the browser, I get the error: "Uncaught ReferenceError: require is not defined at dashboard-tests.js:3". It seems that webpack is compiling my tests (but not my normal code) into a version of javascriptthat can't be run in browsers.

Here are the relevant files:

.babelrc:

```<code>{
   "presets": ["es2015", "react"]
}
</code>```

testem.json:

```<code>{
  "framework": [
    "jasmine"
  ],
  "launch_in_dev": [
    "PhantomJS"
  ],
  "launch_in_ci": [
    "PhantomJS"
  ],
  "serve_files": [
    "tmp/**/*-test{,s}.js"
  ],
  "on_start": "babel static_source --out-dir tmp",
  "on_exit": "yes | rm -r tmp"
}
</code>```

package.json:

```<code>{
  "main": "index.js",
  "scripts": {
    "test": "testem"
  },
  "dependencies": {
    "jquery": "^3.2.1",
    "prop-types": "^15.6.0",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "react-feather": "^1.0.7"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "jasmine-es6": "^0.4.3",
    "testem": "^1.18.4",
    "webpack": "^3.6.0"
  }
}
</code>```

webpack.config.js:

```<code>var path = require("path");
var webpack = require('webpack');

module.exports = {
  context: __dirname,
  entry: './static_source/js/index.js',
  output: {
    path: path.resolve('./app/static/js/'),
    filename: "compiled.js"
  },
  plugins: [],
  module: {
    loaders: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }
    ],
  }
}
</code>```

dashboard-tests:

```<code>import React from 'react';
import ReactDOM from "react-dom";
import TestUtils from "react-dom/test-utils";

import Dashboard from './dashboard';

describe('Dashboard', function() {
  it('exists', function() {
    expect(Dashboard).not.toBe(undefined);
  });

  it('renders arrows', function() {
    var dashboard = <Dashboard />;
    var renderedDashboard = TestUtils.renderIntoDocument(dashboard);

    var arrowsDiv = TestUtils.findRenderedComponentWithClass('arrows');

    expect(arrowsDiv).not.toBe(undefined);
  });
});
</code>```

答:
You are using Babel to compile your test source files. Babel is just a transpiler, it takes ES+ files and translates them to ES5 files. Because import does not exist in ES5 Babel replaces them with require().

To fix the problem you need to bundle your source file into one, using Webpack.

You will need a separate Webpack configuration file, let's call it webpack.config.test.js. In this file we need to instruct Webpack to fetch all your static_source/**/*-test{,s}.js files as entry-points.
You will need the glob module : npm install glob --save-dev.
Then add the webpack.config.test.js file with this content :

```<code>var path = require("path");
var glob = require('glob');
var webpack = require('webpack');

module.exports = {
  context: __dirname,
  // we look for all file ending with -test(s?).js and return the absolute path
  entry: glob
      .sync('./static_source/js/**/*-test{,s}.js')
      .map(function(file) { return path.resolve(__dirname, file) }),
  output: {
    // save the resulting bundle in the ./tmp/ directory
    path: path.resolve('./tmp/'),
    filename: "compiled.js"
  },
  plugins: [],
  module: {
    loaders: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }
    ],
  }
}
</code>```

On the testem.json file replace the on_start with a before_test to Webpack, and the serve_files to map to the bundled file.

```<code>"before_tests": "webpack --config webpack.config.test.js ",
"serve_files": [
    "tmp/compiled.js"
],
</code>```

When testem will be launched it will trigger the Webpack test compilation.
Now you should have a tmp/compiled.js file with all your test files bundled. You may need to do some tweaking but it should basically works.

Body:
I have a project which is set up so that it builds with reactand jsx. It works fine to build it using node_modules/webpack/bin/webpack.js --config webpack.config.js and I can run the result in the browser with no problems. However, when I run npm test and view the test runner in the browser, I get the error: "Uncaught ReferenceError: require is not defined at dashboard-tests.js:3". It seems that webpack is compiling my tests (but not my normal code) into a version of javascriptthat can't be run in browsers.

Here are the relevant files:

.babelrc:

{
   "presets": ["es2015", "react"]
}

testem.json:

{
  "framework": [
    "jasmine"
  ],
  "launch_in_dev": [
    "PhantomJS"
  ],
  "launch_in_ci": [
    "PhantomJS"
  ],
  "serve_files": [
    "tmp/**/*-test{,s}.js"
  ],
  "on_start": "babel static_source --out-dir tmp",
  "on_exit": "yes | rm -r tmp"
}

package.json:

{
  "main": "index.js",
  "scripts": {
    "test": "testem"
  },
  "dependencies": {
    "jquery": "^3.2.1",
    "prop-types": "^15.6.0",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "react-feather": "^1.0.7"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "jasmine-es6": "^0.4.3",
    "testem": "^1.18.4",
    "webpack": "^3.6.0"
  }
}

webpack.config.js:

var path = require("path");
var webpack = require('webpack');

module.exports = {
  context: __dirname,
  entry: './static_source/js/index.js',
  output: {
    path: path.resolve('./app/static/js/'),
    filename: "compiled.js"
  },
  plugins: [],
  module: {
    loaders: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }
    ],
  }
}

dashboard-tests:

import React from 'react';
import ReactDOM from "react-dom";
import TestUtils from "react-dom/test-utils";

import Dashboard from './dashboard';

describe('Dashboard', function() {
  it('exists', function() {
    expect(Dashboard).not.toBe(undefined);
  });

  it('renders arrows', function() {
    var dashboard = <Dashboard />;
    var renderedDashboard = TestUtils.renderIntoDocument(dashboard);

    var arrowsDiv = TestUtils.findRenderedComponentWithClass('arrows');

    expect(arrowsDiv).not.toBe(undefined);
  });
});

Body:
You are using Babel to compile your test source files. Babel is just a transpiler, it takes ES+ files and translates them to ES5 files. Because import does not exist in ES5 Babel replaces them with require().

To fix the problem you need to bundle your source file into one, using Webpack.

You will need a separate Webpack configuration file, let's call it webpack.config.test.js. In this file we need to instruct Webpack to fetch all your static_source/**/*-test{,s}.js files as entry-points.
You will need the glob module : npm install glob --save-dev.
Then add the webpack.config.test.js file with this content :

var path = require("path");
var glob = require('glob');
var webpack = require('webpack');

module.exports = {
  context: __dirname,
  // we look for all file ending with -test(s?).js and return the absolute path
  entry: glob
      .sync('./static_source/js/**/*-test{,s}.js')
      .map(function(file) { return path.resolve(__dirname, file) }),
  output: {
    // save the resulting bundle in the ./tmp/ directory
    path: path.resolve('./tmp/'),
    filename: "compiled.js"
  },
  plugins: [],
  module: {
    loaders: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }
    ],
  }
}

On the testem.json file replace the on_start with a before_test to Webpack, and the serve_files to map to the bundled file.

"before_tests": "webpack --config webpack.config.test.js ",
"serve_files": [
    "tmp/compiled.js"
],

When testem will be launched it will trigger the Webpack test compilation.
Now you should have a tmp/compiled.js file with all your test files bundled. You may need to do some tweaking but it should basically works.


问:
How to use batch account created with user subscription in Data Factory Linked Service?
I have created a Batch Service with user subscription and created a key vault also,

http://csharpcorner.mindcrackerinc.netdna-cdn.com/article/de/Images/image007.jpg

Now how can I use that batch service in the Data Factory Linked Service.
Because it is asking for access key.

What Key I have to give here?

I have created a Key from Key Vault, it created as a Version, starting time and Expiration time but unable to fine the key.

答:
It's required to provide Batch Account Access Key in Data Factory Linked Service. It has nothing to do with Keys/Secrets stored in Azure Key Vault.

To get Access Key go to Azure Portal, open your Batch Account, navigate to Keys tab and select any of keys listed there. Keys tab should look like this:


问:
Looking for guidelines setting proper ResultSet Type in PreparedStatement API
We recently find using resultSetType=TYPE_SCROLL_INSENSITIVE in prepareStatement(String sql, int resultSetType, int resultSetConcurrency) instead of the default prepareStatement(String sql) can cause db2 to generate/use a different access plan, which could lead to significantly different query time, depending on table-size/filter range/etc.

We use DB2 LUW V10.5 FP8.

Just wondering if there any guidelines on how to choose this resultSetType attribute, in terms of performance optimization, for DB2, or other RDBMS in general? Btw, we don't change our ResultSet, so using *INSENSITIVE is allowed for us.

答:
TYPE_SCROLL_INSENSITIVE

Should be used with care, default is ASENSITIVE.  Which allows Db2 to create either an INSENSITIVE or SENSITIVE cursor depending on what it thinks is best.

With Db2 for i at least, INSENSITIVE causes the DB to create a copy of the data.


问:
Why are there Debug & Release builds for .Net, but not for Java?
In .Net, you can specifically compile your projects under "Debug" or "Release" settings, Release having more optimizations. I know that this is deemed unnecessary in Java, because the jitter does these optimizations. What is the reason for the difference? (meaning, why is a pre-"jitter" compilation required/helpful)

Why is it deemed necessary in .Net/CLR, but not in Java/JDK?

答:
Sun's javac compiler does have the concept of debugging information which can be (optionally) omitted from the compiled class output.

Look at the documentation, and check out the -g flag options:

```<code>-g
  Generate all debugging information, including local
  variables. By default, only line number and source
  file information is generated.
-g:none
  Do not generate any debugging information.
-g:{keyword list}
  Generate only some kinds of debugging information,
  specified by a comma separated list of keywords.
  Valid keywords are:
    source
      Source file debugging information
    lines
      Line number debugging information
    vars
      Local variable debugging information
</code>```

These are perhaps not quite as extensive as the bytecode optimisations the .NET compilers might perform (which I'm not familiar with, sorry), but I think in theory they are there for performance reasons (smaller classfiles, etc).

In practise I strongly suspect they wouldn't make much difference to runtime performance on modern hardwares + JVMs, but they are there.

Body:
Sun's javac compiler does have the concept of debugging information which can be (optionally) omitted from the compiled class output.

Look at the documentation, and check out the -g flag options:

-g
  Generate all debugging information, including local
  variables. By default, only line number and source
  file information is generated.
-g:none
  Do not generate any debugging information.
-g:{keyword list}
  Generate only some kinds of debugging information,
  specified by a comma separated list of keywords.
  Valid keywords are:
    source
      Source file debugging information
    lines
      Line number debugging information
    vars
      Local variable debugging information

These are perhaps not quite as extensive as the bytecode optimisations the .NET compilers might perform (which I'm not familiar with, sorry), but I think in theory they are there for performance reasons (smaller classfiles, etc).

In practise I strongly suspect they wouldn't make much difference to runtime performance on modern hardwares + JVMs, but they are there.


问:
How do I apply code to all files within a folder?
I'm relatively new to programming, but created a c script to rotate images and create a copy of them. However, I was hoping to apply it to a large number of files, so I was wondering if there was a way to apply a program / function to all images within a specific folder. Thanks!</p>

答:
You could pass wildcards to the executable. The shell would expand the wildcard to all files it matches. Your main program could look like this:

```<code>int main(argc, char ** argv)
{
    for(int arg=1; arg<argc; arg++)
        doStuffToFile(argv[arg]);
}
</code>```

That is the best solution if you plan to use this quite a lot. If you just need a quick fix you'd be better of with a shell script. This is how it would be done in bash:

for file in /path/*
do
    [ -e "$file" ] || continue
    program "$file"
done
```

Body:
You could pass wildcards to the executable. The shell would expand the wildcard to all files it matches. Your main program could look like this:

int main(argc, char ** argv)
{
    for(int arg=1; arg<argc; arg++)
        doStuffToFile(argv[arg]);
}

That is the best solution if you plan to use this quite a lot. If you just need a quick fix you'd be better of with a shell script. This is how it would be done in bash:

for file in /path/*
do
    [ -e "$file" ] || continue
    program "$file"
done


问:
Can we have one click recaptcha only - not the picture puzzle captcha after it
I integrated recaptcha in my forms
(https://www.google.com/recaptcha/intro/index.html)

However it is very confusing when the rest of the form has not be filled properly, then a picture-captcha opens. this is very troubling.

Can this be prevented? I would like just the recaptcha with 1 click-confirmation, even if the form has not been filled in completely.

答:
If you got here because you were looking for a way to temporarily disable the puzzle for automated testing: There are test keys that you can use for this purpose.
https://developers.google.com/recaptcha/docs/faq</p>


问:
Undefined in res.redirect - express, request, fs, node-uuid, path and multer
I am trying to redirect the user to a signature route, passing the file name as a URL argument he is telling me that he is undefined...

Sample file as a URL argument after upload.

```<code>http://localhost:3000/undefined?arquivo-assinado=82a35943-5796-4d9b-b397-80d8942b6c65.pdf
</code>```

Side-nav option click redirect to template

```<code>api.get("/company-parallel-and-branch", function (req, res) {
  var path = __dirname + '/routes/company-parallel-and-branch/';
  res.sendFile(path + "company-parallel-and-branch.html");

  require('./digital-certificate/authentication');
  require('./digital-certificate/pades-signature');
});
</code>```

app.js

```<code>var http = require('http');
var express    = require('express'),
    mongoose = require('mongoose'),
    ejs = require('ejs'),
    nunjucks   = require('nunjucks'),
    path = require('path'),
    mysql      = require('mysql'),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    logger = require('morgan'),
    io = require('socket.io');
var errorHandler = require('errorhandler');

app.use('/upload', require('./digital-certificate/upload'));
app.use('/authentication', require('./digital-certificate/authentication'));
app.use('/pades-signature', require('./digital-certificate/pades-signature'));
app.use('/pades-signature-server-key', require('./digital-certificate/pades-signature-server-key'));
app.use('/cades-signature', require('./digital-certificate/cades-signature'));
app.use('/cades-signature-server-key', require('./digital-certificate/cades-signature-server-key'));
</code>```

Uploader in company-and-branch.html

```<code><form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="sendFileManager">
  <input type="submit" value="Upload" name="submit">
</form>
</code>```

upload.js router

```<code>var express = require('express');
var request = require('request');
var fs = require('fs');
var uuid = require('node-uuid');
var path = require('path');
var multer = require('multer');

var upload = multer();
var router = express.Router();
var appRoot = process.cwd();

router.get('/', function(req, res, next) {
    res.render('upload');
});

router.post('/', upload.single('sendFileManager'), function(req, res, next) {
    var fileExt = path.extname(req.file.originalname);
    var filename = uuid.v4() + fileExt;

    var appDataPath = appRoot + '/public/app-data/';
    if (!fs.existsSync(appDataPath)){
        fs.mkdirSync(appDataPath);
    }

    fs.writeFileSync(appDataPath + filename, req.file.buffer);

    res.redirect(req.query.goto + '?arquivo-assinado=' + filename);
});

module.exports = router;
</code>```

This route pades-signature.js processes file uploaded

```<code>var express = require('express');
var request = require('request');
var fs = require('fs');
var uuid = require('node-uuid');
var restPki = require('./lacuna-restpki');
var client = require('./restpki-client');

var router = express.Router();
var appRoot = process.cwd();

/*
 * GET /pades-signature
 *
 * This route initiates a PAdES signature using REST PKI and renders the signature page.
 *
 * Both PAdES signature examples, with a server file and with a file uploaded by the user, use this route. The difference
 * is that, when the file is uploaded by the user, the route is called with a URL argument named "userfile".
 */
router.get('/', function(req, res, next) {

    var pdfToSignContent;

    // If the user was redirected here by the route "upload" (signature with file uploaded by user), the "userfile" URL
    // argument will contain the filename under the "public/app-data" folder. Otherwise (signature with server file), we'll
    // sign a sample document.
    if (req.query.userfile) {
        pdfToSignContent = fs.readFileSync(appRoot + '/public/app-data/' + req.query.userfile);
    } else {
        pdfToSignContent = fs.readFileSync(appRoot + '/public/SampleDocument.pdf');
    }

    // Read the contents of the PDF stamp image
    var pdfStampContent = fs.readFileSync(appRoot + '/resources/PdfStamp.png');

    // Request to be sent to REST PKI
    var restRequest = {

        // Base64-encoding of the PDF to be signed
        pdfToSign: new Buffer(pdfToSignContent).toString('base64'),

        // Signature policy (the ID below corresponds to the PAdES basic policy)
        signaturePolicyId: restPki.standardSignaturePolicies.padesBasic,

        // Set a SecurityContext to be used to determine trust in the certificate chain
        securityContextId: restPki.standardSecurityContexts.pkiBrazil,
        // Note: By changing the value above you can accept only certificates from a certain PKI, or
        // from a custom PKI configured on the REST PKI website.

        // Set the visual representation for the signature
        visualRepresentation: {

            image: {

                // We'll use as background the image previously loaded
                resource: {
                    content: new Buffer(pdfStampContent).toString('base64'), // Base64-encoding!
                    mimeType: 'image/png'
                },

                // (optional) Opacity is an integer from 0 to 100 (0 is completely transparent, 100 is completely opaque). If omitted, 100 is assumed.
                opacity: 50,

                // (optional) Specify the image horizontal alignment. Possible values are 'Left', 'Center' and 'Right'. If omitted, 'Center' is assumed.
                horizontalAlign: 'Right',

                // (optional) Specify the image vertical alignment. Possible values are 'Top', 'Center' and 'Bottom'. If omitted, 'Center' is assumed.
                verticalAlign: 'Center'

            },

            text: {

                // The tags {{signerName}} and {{signerNationalId}} will be substituted according to the user's certificate
                // signerName -> full name of the signer
                // signerNationalId -> if the certificate is ICP-Brasil, contains the signer's CPF
                text: 'Signed by {{signerName}} ({{signerNationalId}})',

                // Specify that the signing time should also be rendered
                includeSigningTime: true,

                // Optionally set the horizontal alignment of the text ('Left' or 'Right'), if not set the default is Left
                horizontalAlign: 'Left'

            },

            position: {

                // Page on which to draw the visual representation. Negative values are counted from the end of the document (-1 is last page).
                // Zero means the signature will be placed on a new page appended to the end of the document.
                pageNumber: -1,

                // Measurement units of the values below ('Centimeters' or 'PdfPoints')
                measurementUnits: "Centimeters",

                // Automatic placing of signatures within a container, one after the other
                auto: {

                    // Specification of the container where the signatures will be placed
                    container: {
                        // Specifying left and right (but no width) results in a variable-width container with the given margins
                        left: 1.5,
                        right: 1.5,
                        // Specifying bottom and height (but no top) results in a bottom-aligned fixed-height container
                        bottom: 1.5,
                        height: 3
                    },

                    // Specification of the size of each signature rectangle
                    signatureRectangleSize: {
                        width: 7,
                        height: 3
                    },

                    // The signatures will be placed in the container side by side. If there's no room left, the signatures
                    // will "wrap" to the next row. The value below specifies the vertical distance between rows
                    rowSpacing: 1.5
                }
            }
        }
    };

    // Call the action POST Api/PadesSignatures on REST PKI, which initiates the signature.
    request.post(client.endpoint + 'Api/PadesSignatures', {

        json: true,
        headers: { 'Authorization': 'Bearer ' + client.accessToken },
        body: restRequest

    }, function (err, restRes, body) {

        if (restPki.checkResponse(err, restRes, body, next)) {

            // This operation yields the token, a 43-character case-sensitive URL-safe string, which identifies this signature process.
            // We'll use this value to call the signWithRestPki() method on the Web PKI component (see view 'pades-signature') and also
            // to complete the signature after the form is submitted. This should not be mistaken with the API access token.
            var token = restRes.body.token;

            // The token acquired can only be used for a single signature attempt. In order to retry the signature it is
            // necessary to get a new token. This can be a problem if the user uses the back button of the browser, since the
            // browser might show a cached page that we rendered previously, with a now stale token. To prevent this from happening,
            // we set some response headers specifying that the page should not be cached.
            res.set({
                'Cache-Control': 'private, no-store, max-age=0, no-cache, must-revalidate, post-check=0, pre-check=0',
                'Pragma': 'no-cache'
            });

            // Render the signature page
            res.render('pades-signature', {
                token: token,
                userfile: req.query.userfile
            });
        }

    });
});

/*
 * POST /pades-signature
 *
 * This route receives the form submission from the view 'pades-signature'. We'll call REST PKI to complete the signature.
 */
router.post('/', function(req, res, next) {

    // Retrieve the token from the URL
    var token = req.body.token;

    // Call the action POST Api/PadesSignatures/{token}/Finalize on REST PKI, which finalizes the signature process and returns the signed PDF
    request.post(client.endpoint + 'Api/PadesSignatures/' + token + '/Finalize', {

        json: true,
        headers: { 'Authorization': 'Bearer ' + client.accessToken}

    }, function(err, restRes, body) {

        if (restPki.checkResponse(err, restRes, body, next)) {

            var signedPdfContent = new Buffer(restRes.body.signedPdf, 'base64');

            // At this point, you'd typically store the signed PDF on your database. For demonstration purposes, we'll
            // store the PDF on a temporary folder publicly accessible and render a link to it.
            var filename = uuid.v4() + '.pdf';
            var appDataPath = appRoot + '/public/app-data/';
            if (!fs.existsSync(appDataPath)){
                fs.mkdirSync(appDataPath);
            }
            fs.writeFileSync(appDataPath + filename, signedPdfContent);
            res.render('pades-signature-complete', {
                signedFileName: filename,
                signerCert: restRes.body.certificate
            });

        }
    });
});

module.exports = router;
</code>```

Thank very much for helping me ;]]

答:
Solution is </p>

```<code>router.post('/', upload.single('sendFileManager'), function(req, res, next) {
    var fileExt = path.extname(req.file.originalname);
    var filename = uuid.v4() + fileExt;

    var appDataPath = appRoot + '/public/app-data/';
    if (!fs.existsSync(appDataPath)){
        fs.mkdirSync(appDataPath);
    }

    fs.writeFileSync(appDataPath + filename, req.file.buffer);

    res.redirect('/company-parallel-and-branch' + '?sendFileManager=' + filename);
});
</code>```

Body:
I am trying to redirect the user to a signature route, passing the file name as a URL argument he is telling me that he is undefined...

Sample file as a URL argument after upload.

http://localhost:3000/undefined?arquivo-assinado=82a35943-5796-4d9b-b397-80d8942b6c65.pdf

Side-nav option click redirect to template

api.get("/company-parallel-and-branch", function (req, res) {
  var path = __dirname + '/routes/company-parallel-and-branch/';
  res.sendFile(path + "company-parallel-and-branch.html");

  require('./digital-certificate/authentication');
  require('./digital-certificate/pades-signature');
});

app.js

var http = require('http');
var express    = require('express'),
    mongoose = require('mongoose'),
    ejs = require('ejs'),
    nunjucks   = require('nunjucks'),
    path = require('path'),
    mysql      = require('mysql'),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    logger = require('morgan'),
    io = require('socket.io');
var errorHandler = require('errorhandler');

app.use('/upload', require('./digital-certificate/upload'));
app.use('/authentication', require('./digital-certificate/authentication'));
app.use('/pades-signature', require('./digital-certificate/pades-signature'));
app.use('/pades-signature-server-key', require('./digital-certificate/pades-signature-server-key'));
app.use('/cades-signature', require('./digital-certificate/cades-signature'));
app.use('/cades-signature-server-key', require('./digital-certificate/cades-signature-server-key'));

Uploader in company-and-branch.html

<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="sendFileManager">
  <input type="submit" value="Upload" name="submit">
</form>

upload.js router

var express = require('express');
var request = require('request');
var fs = require('fs');
var uuid = require('node-uuid');
var path = require('path');
var multer = require('multer');

var upload = multer();
var router = express.Router();
var appRoot = process.cwd();

router.get('/', function(req, res, next) {
    res.render('upload');
});

router.post('/', upload.single('sendFileManager'), function(req, res, next) {
    var fileExt = path.extname(req.file.originalname);
    var filename = uuid.v4() + fileExt;

    var appDataPath = appRoot + '/public/app-data/';
    if (!fs.existsSync(appDataPath)){
        fs.mkdirSync(appDataPath);
    }

    fs.writeFileSync(appDataPath + filename, req.file.buffer);

    res.redirect(req.query.goto + '?arquivo-assinado=' + filename);
});

module.exports = router;

This route pades-signature.js processes file uploaded

var express = require('express');
var request = require('request');
var fs = require('fs');
var uuid = require('node-uuid');
var restPki = require('./lacuna-restpki');
var client = require('./restpki-client');

var router = express.Router();
var appRoot = process.cwd();

/*
 * GET /pades-signature
 *
 * This route initiates a PAdES signature using REST PKI and renders the signature page.
 *
 * Both PAdES signature examples, with a server file and with a file uploaded by the user, use this route. The difference
 * is that, when the file is uploaded by the user, the route is called with a URL argument named "userfile".
 */
router.get('/', function(req, res, next) {

    var pdfToSignContent;

    // If the user was redirected here by the route "upload" (signature with file uploaded by user), the "userfile" URL
    // argument will contain the filename under the "public/app-data" folder. Otherwise (signature with server file), we'll
    // sign a sample document.
    if (req.query.userfile) {
        pdfToSignContent = fs.readFileSync(appRoot + '/public/app-data/' + req.query.userfile);
    } else {
        pdfToSignContent = fs.readFileSync(appRoot + '/public/SampleDocument.pdf');
    }

    // Read the contents of the PDF stamp image
    var pdfStampContent = fs.readFileSync(appRoot + '/resources/PdfStamp.png');

    // Request to be sent to REST PKI
    var restRequest = {

        // Base64-encoding of the PDF to be signed
        pdfToSign: new Buffer(pdfToSignContent).toString('base64'),

        // Signature policy (the ID below corresponds to the PAdES basic policy)
        signaturePolicyId: restPki.standardSignaturePolicies.padesBasic,

        // Set a SecurityContext to be used to determine trust in the certificate chain
        securityContextId: restPki.standardSecurityContexts.pkiBrazil,
        // Note: By changing the value above you can accept only certificates from a certain PKI, or
        // from a custom PKI configured on the REST PKI website.

        // Set the visual representation for the signature
        visualRepresentation: {

            image: {

                // We'll use as background the image previously loaded
                resource: {
                    content: new Buffer(pdfStampContent).toString('base64'), // Base64-encoding!
                    mimeType: 'image/png'
                },

                // (optional) Opacity is an integer from 0 to 100 (0 is completely transparent, 100 is completely opaque). If omitted, 100 is assumed.
                opacity: 50,

                // (optional) Specify the image horizontal alignment. Possible values are 'Left', 'Center' and 'Right'. If omitted, 'Center' is assumed.
                horizontalAlign: 'Right',

                // (optional) Specify the image vertical alignment. Possible values are 'Top', 'Center' and 'Bottom'. If omitted, 'Center' is assumed.
                verticalAlign: 'Center'

            },

            text: {

                // The tags {{signerName}} and {{signerNationalId}} will be substituted according to the user's certificate
                // signerName -> full name of the signer
                // signerNationalId -> if the certificate is ICP-Brasil, contains the signer's CPF
                text: 'Signed by {{signerName}} ({{signerNationalId}})',

                // Specify that the signing time should also be rendered
                includeSigningTime: true,

                // Optionally set the horizontal alignment of the text ('Left' or 'Right'), if not set the default is Left
                horizontalAlign: 'Left'

            },

            position: {

                // Page on which to draw the visual representation. Negative values are counted from the end of the document (-1 is last page).
                // Zero means the signature will be placed on a new page appended to the end of the document.
                pageNumber: -1,

                // Measurement units of the values below ('Centimeters' or 'PdfPoints')
                measurementUnits: "Centimeters",

                // Automatic placing of signatures within a container, one after the other
                auto: {

                    // Specification of the container where the signatures will be placed
                    container: {
                        // Specifying left and right (but no width) results in a variable-width container with the given margins
                        left: 1.5,
                        right: 1.5,
                        // Specifying bottom and height (but no top) results in a bottom-aligned fixed-height container
                        bottom: 1.5,
                        height: 3
                    },

                    // Specification of the size of each signature rectangle
                    signatureRectangleSize: {
                        width: 7,
                        height: 3
                    },

                    // The signatures will be placed in the container side by side. If there's no room left, the signatures
                    // will "wrap" to the next row. The value below specifies the vertical distance between rows
                    rowSpacing: 1.5
                }
            }
        }
    };

    // Call the action POST Api/PadesSignatures on REST PKI, which initiates the signature.
    request.post(client.endpoint + 'Api/PadesSignatures', {

        json: true,
        headers: { 'Authorization': 'Bearer ' + client.accessToken },
        body: restRequest

    }, function (err, restRes, body) {

        if (restPki.checkResponse(err, restRes, body, next)) {

            // This operation yields the token, a 43-character case-sensitive URL-safe string, which identifies this signature process.
            // We'll use this value to call the signWithRestPki() method on the Web PKI component (see view 'pades-signature') and also
            // to complete the signature after the form is submitted. This should not be mistaken with the API access token.
            var token = restRes.body.token;

            // The token acquired can only be used for a single signature attempt. In order to retry the signature it is
            // necessary to get a new token. This can be a problem if the user uses the back button of the browser, since the
            // browser might show a cached page that we rendered previously, with a now stale token. To prevent this from happening,
            // we set some response headers specifying that the page should not be cached.
            res.set({
                'Cache-Control': 'private, no-store, max-age=0, no-cache, must-revalidate, post-check=0, pre-check=0',
                'Pragma': 'no-cache'
            });

            // Render the signature page
            res.render('pades-signature', {
                token: token,
                userfile: req.query.userfile
            });
        }

    });
});

/*
 * POST /pades-signature
 *
 * This route receives the form submission from the view 'pades-signature'. We'll call REST PKI to complete the signature.
 */
router.post('/', function(req, res, next) {

    // Retrieve the token from the URL
    var token = req.body.token;

    // Call the action POST Api/PadesSignatures/{token}/Finalize on REST PKI, which finalizes the signature process and returns the signed PDF
    request.post(client.endpoint + 'Api/PadesSignatures/' + token + '/Finalize', {

        json: true,
        headers: { 'Authorization': 'Bearer ' + client.accessToken}

    }, function(err, restRes, body) {

        if (restPki.checkResponse(err, restRes, body, next)) {

            var signedPdfContent = new Buffer(restRes.body.signedPdf, 'base64');

            // At this point, you'd typically store the signed PDF on your database. For demonstration purposes, we'll
            // store the PDF on a temporary folder publicly accessible and render a link to it.
            var filename = uuid.v4() + '.pdf';
            var appDataPath = appRoot + '/public/app-data/';
            if (!fs.existsSync(appDataPath)){
                fs.mkdirSync(appDataPath);
            }
            fs.writeFileSync(appDataPath + filename, signedPdfContent);
            res.render('pades-signature-complete', {
                signedFileName: filename,
                signerCert: restRes.body.certificate
            });

        }
    });
});

module.exports = router;

Thank very much for helping me ;]]

Body:
Solution is

router.post('/', upload.single('sendFileManager'), function(req, res, next) {
    var fileExt = path.extname(req.file.originalname);
    var filename = uuid.v4() + fileExt;

    var appDataPath = appRoot + '/public/app-data/';
    if (!fs.existsSync(appDataPath)){
        fs.mkdirSync(appDataPath);
    }

    fs.writeFileSync(appDataPath + filename, req.file.buffer);

    res.redirect('/company-parallel-and-branch' + '?sendFileManager=' + filename);
});


问:
What is the fastest method(s) for reading and writing a matrix of Float64 to file in julia
Let x = randn(100, 2). I want to write x to its own file. This file will contain x, and only x, and x will only ever be of type Matrix{Float64}. In the past, I have always used HDF5 for this, but it occurs to me that this is over-kill, since in this setup I will only have one array per file. Note that JLD uses HDF5, and so is also over-kill.

1) What is the fastest method for reading and writing x assuming I will only ever want to read the entire matrix?

2) What is the fastest method for reading and writing x assuming I might want to read a slice of the matrix?

3) What is the fastest method for reading and writing x assuming I might want to read a slice of the matrix, or over-write a slice of the matrix (but not change the matrix size)?

答:
You could use the serialize function, provided you heed the warnings in the documentation about non-guarantees between versions etc.

serialize(stream::IO, value)

Write an arbitrary value to a stream in an opaque format, such that it can be read back by deserialize. The read-back value will be as identical as possible to the original. In general, this process will not work if the reading and writing are done by different
    versions of Julia, or an instance of Julia with a different system image. Ptr values are serialized as all-zero bit patterns (NULL).

An 8-byte identifying header is written to the stream first. To avoid writing the header, construct a SerializationState and use it as the first argument to serialize instead. See also Serializer.writeheader.

Really though, JLD (or in fact, its successor, JLD2) is generally the recommended way*.

*Of particular interest to you might be the statements that: "JLD2 saves and loads Julia data structures in a format comprising a subset of HDF5, without any dependency on the HDF5 C library" and that "it typically outperforms the previous JLD package (sometimes by multiple orders of magnitude) and often outperforms Julia's built-in serializer".


问:
CardView with RecyclerView/ListView in ScrollView
tl;dr: How to achieve the layout shown in the screenshot below? Placing ListView to a ScrollView is apparently not recommended, but is there actually any other way to achieve it?

The whole question: I want to have multiple CardViews in my app, and one (or more) of them will have either RecyclerView or ListView in it (it doesn't really matter to me which one of those). The whole view is supposed to be scrollable - not only the ListViews in their parent CardViews. I basically need to achieve similar layout as the Play Store app has.

The first option I tried was this (the code is obviously simplified):

```<code><LinearLayout android:orientation="vertical">
    <CardView>
        <!-- Some content of the first card. -->
    </CardView>
    <CardView>
        <ListView/>
    </CardView>
</LinearLayout>
</code>```

The result was not what I wanted, the ListView was only scrollable in its parent CardView but the whole view wasn't scrollable like it is in the Play Store app. So now I wrapped it all in a ScrollView:

```<code><ScrollView
    android:fillViewport="true"
    android:isScrollContainer="true">
    <LinearLayout orientation="vertical">
        <CardView>
            <!-- Some content of the first card. -->
        </CardView>
        <CardView>
            <ListView/>
        </CardView>
    </LinearLayout>
</ScrollView>
</code>```

And I programmatically set the height of the bottom card to fit the ListView's height (number of elements in the ListView * height of one list item element). Now the whole view is scrollable, and the bottom card's height is the same as the height of the ListView, so the ListView isn't scrollable inside the CardView which is exactly what I wanted.

Now the actual problem: I got it working as described above, but I know this particular issue (ListView in a ScrollView) has been asked about many times before and the answer has always been the same - don't put neither RecyclerView nor ListView in a ScrollView because it causes performance problems. Well, so what's the correct approach then? How did Google do it in the Play Store app? I tried decompiling the Play Store app with APKTool but there weren't any layout files (maybe I did something wrong). Is my approach correct? My ListView will only display a few items (I guess it will be at most 20 items) - will it cause some performance issues in this case?

I wouldn't ask about this if all the answers wouldn't always mention that we shouldn't put ListView in a ScrollView. Is there any other way how to achieve the layout described by the screenshot above?

答:
The first thing to address is why you're "not supposed to" use wrap_content on a ListView or a RecyclerView and put it in a scrollable container: it defeats the entire view-recycling purpose of these components.

What makes a ListView or RecyclerView better than a LinearLayout inside a ScrollView is that the system only needs to create enough views to display everying that fits inside the visible area. When you "scroll" the visible area, the views that disappear off one end can be re-used for the views that scroll into view from the other end. When you make your list/recycler wrap_content, this recycling is impossible, so you might as well just manually add your views to a LinearLayout instead.

That being said, RecyclerView does support using wrap_content... it just means you won't get view recycling. If this performance hit doesn't cause you problems, there's no objectively evil code here.

The only way to know for sure if the performance penalty is problematic or not is to just try it, test it, measure it, and decide for yourself. With 20 items, I suspect you have nothing to worry about.

The next thing to think about is the fact that Google has tons of resources and manpower and can afford to be extremely clever. Perhaps the Play Store app is as you say, with some sort of scrollable parent container that holds cards, each of which have some sort of adapter view within. But it's equally possible that they're doing something completely different, like using a single RecyclerView and "faking" the appearance of cards by using an ItemDecoration. Or perhaps they are using some sort of custom view subclass that the public doesn't have access to.

As for how you could recreate something similar, I suspect a hierarchy like this will work just fine:

```<code><NestedScrollView>
  <LinearLayout>
     <CardView>
       <RecyclerView/>
     </CardView>
     <CardView>
       <RecyclerView/>
     </CardView>
     <CardView>
       <RecyclerView/>
     </CardView>
  </LinearLayout>
</NestedScrollView>
</code>```

Body:
tl;dr: How to achieve the layout shown in the screenshot below? Placing ListView to a ScrollView is apparently not recommended, but is there actually any other way to achieve it?

The whole question: I want to have multiple CardViews in my app, and one (or more) of them will have either RecyclerView or ListView in it (it doesn't really matter to me which one of those). The whole view is supposed to be scrollable - not only the ListViews in their parent CardViews. I basically need to achieve similar layout as the Play Store app has.

The first option I tried was this (the code is obviously simplified):

<LinearLayout android:orientation="vertical">
    <CardView>

    </CardView>
    <CardView>
        <ListView/>
    </CardView>
</LinearLayout>

The result was not what I wanted, the ListView was only scrollable in its parent CardView but the whole view wasn't scrollable like it is in the Play Store app. So now I wrapped it all in a ScrollView:

<ScrollView
    android:fillViewport="true"
    android:isScrollContainer="true">
    <LinearLayout orientation="vertical">
        <CardView>

        </CardView>
        <CardView>
            <ListView/>
        </CardView>
    </LinearLayout>
</ScrollView>

And I programmatically set the height of the bottom card to fit the ListView's height (number of elements in the ListView * height of one list item element). Now the whole view is scrollable, and the bottom card's height is the same as the height of the ListView, so the ListView isn't scrollable inside the CardView which is exactly what I wanted.

Now the actual problem: I got it working as described above, but I know this particular issue (ListView in a ScrollView) has been asked about many times before and the answer has always been the same - don't put neither RecyclerView nor ListView in a ScrollView because it causes performance problems. Well, so what's the correct approach then? How did Google do it in the Play Store app? I tried decompiling the Play Store app with APKTool but there weren't any layout files (maybe I did something wrong). Is my approach correct? My ListView will only display a few items (I guess it will be at most 20 items) - will it cause some performance issues in this case?

I wouldn't ask about this if all the answers wouldn't always mention that we shouldn't put ListView in a ScrollView. Is there any other way how to achieve the layout described by the screenshot above?

Body:
The first thing to address is why you're "not supposed to" use wrap_content on a ListView or a RecyclerView and put it in a scrollable container: it defeats the entire view-recycling purpose of these components.

What makes a ListView or RecyclerView better than a LinearLayout inside a ScrollView is that the system only needs to create enough views to display everying that fits inside the visible area. When you "scroll" the visible area, the views that disappear off one end can be re-used for the views that scroll into view from the other end. When you make your list/recycler wrap_content, this recycling is impossible, so you might as well just manually add your views to a LinearLayout instead.

That being said, RecyclerView does support using wrap_content... it just means you won't get view recycling. If this performance hit doesn't cause you problems, there's no objectively evil code here.

The only way to know for sure if the performance penalty is problematic or not is to just try it, test it, measure it, and decide for yourself. With 20 items, I suspect you have nothing to worry about.

The next thing to think about is the fact that Google has tons of resources and manpower and can afford to be extremely clever. Perhaps the Play Store app is as you say, with some sort of scrollable parent container that holds cards, each of which have some sort of adapter view within. But it's equally possible that they're doing something completely different, like using a single RecyclerView and "faking" the appearance of cards by using an ItemDecoration. Or perhaps they are using some sort of custom view subclass that the public doesn't have access to.

As for how you could recreate something similar, I suspect a hierarchy like this will work just fine:

<NestedScrollView>
  <LinearLayout>
     <CardView>
       <RecyclerView/>
     </CardView>
     <CardView>
       <RecyclerView/>
     </CardView>
     <CardView>
       <RecyclerView/>
     </CardView>
  </LinearLayout>
</NestedScrollView>


问:
pi3 GPU functionaly with camera
In my project I have 2 main tasks – image recognition for the camera frames and saving the vidoes.
I think to use pi GPU here for accelerate this.
Is it possible using pi GPU get the frames from camera, than convert and save them in SD card?
And meantime pass the frames to processor for doing image recognition?

Can someone please provide some info about how I can use GPU and processor separately and what video-camera related operations can GPU do.

Thanks

答:
I think you really just want to use the umat class. It makes a lot of opencvs functions run on the GPU (if possible). It can in some cases release a lot of cpu time for other tasks.

Some opencv functions are also often multiple times faster when run on a GPU.

See opencv-transparent-api

You can also easily find examples using it here on stack overflow.

Title: pi3 GPU functionaly with camera


问:
R S4 Methods Applied to List of Objects in a Class
I am a fluent, long-time R user and am starting to familiarize myself with classes and methods.  I am still very new to this and working through concepts.

Specifically today I am trying to apply a method to a list of objects, all of which are in a particular, user-generated class.

Take this example:

```<code>#define car
setClass("car",
  representation(
    name = "character",
    mpg = "numeric"
  )
)

#create some cars
cars <-    lapply(1:nrow(mtcars), function(x) new("car", name =
rownames(mtcars)[x], mpg = mtcars$mpg[x]))

##SAMPLE MPG GROWTH METHOD
setGeneric("grow.mpg", function(car) {
  standardGeneric("grow.mpg")
})

setMethod("grow.mpg",
  signature("car"),
  function(car){
    old_mpg <- car@mpg
    car@mpg <- car@mpg * .1 + car@mpg
    message(paste("growing mpg on ", car@name, " from ", old_mpg, " to
    ", car@mpg, sep = ''))
    return(car)
  })

#APPLY METHOD
cars[[1]] <- grow.mpg(cars[[1]])
growing mpg on Mazda RX4 from 25.41 to 27.951
</code>```

This successfully grows mpg by 10% on cars[[1]]:

```<code>cars[[1]]
An object of class "car"
Slot "name":
[1] "Mazda RX4"

Slot "mpg":
[1] 27.951
</code>```

But applying method grow.mpg to all of cars throws the following error:

```<code>cars <- grow.mpg(cars)
Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function ‘grow.mpg’ for
  signature ‘"list"’
</code>```

So two questions:

Why is this?

How do I apply grow.mpg to all of cars?

Thanks in advance!

答:
You've defined your grow.mpg function for objects of class "car". And class(cars[[1]]) is a "car" but class(cars) is "list".

Just like anything else in R (and not really unique to S4 classes), whenever you want to apply the same function to every element in the list and get a new list, back, you just use lapply.

```<code>cars <- lapply(cars, grow.mpg)
</code>```

Body:
I am a fluent, long-time R user and am starting to familiarize myself with classes and methods.  I am still very new to this and working through concepts.

Specifically today I am trying to apply a method to a list of objects, all of which are in a particular, user-generated class.

Take this example:

#define car
setClass("car",
  representation(
    name = "character",
    mpg = "numeric"
  )
)

#create some cars
cars <-    lapply(1:nrow(mtcars), function(x) new("car", name =
rownames(mtcars)[x], mpg = mtcars$mpg[x]))

##SAMPLE MPG GROWTH METHOD
setGeneric("grow.mpg", function(car) {
  standardGeneric("grow.mpg")
})

setMethod("grow.mpg",
  signature("car"),
  function(car){
    old_mpg <- car@mpg
    car@mpg <- car@mpg * .1 + car@mpg
    message(paste("growing mpg on ", car@name, " from ", old_mpg, " to
    ", car@mpg, sep = ''))
    return(car)
  })

#APPLY METHOD
cars[[1]] <- grow.mpg(cars[[1]])
growing mpg on Mazda RX4 from 25.41 to 27.951

This successfully grows mpg by 10% on cars[[1]]:

cars[[1]]
An object of class "car"
Slot "name":
[1] "Mazda RX4"

Slot "mpg":
[1] 27.951

But applying method grow.mpg to all of cars throws the following error:

cars <- grow.mpg(cars)
Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function ‘grow.mpg’ for
  signature ‘"list"’

So two questions:

Why is this?

How do I apply grow.mpg to all of cars?

Thanks in advance!

Body:
You've defined your grow.mpg function for objects of class "car". And class(cars[[1]]) is a "car" but class(cars) is "list".

Just like anything else in R (and not really unique to S4 classes), whenever you want to apply the same function to every element in the list and get a new list, back, you just use lapply.

cars <- lapply(cars, grow.mpg)


问:
Get vector of columns with highest values in matrix
I'd like to be able to create a column vector whose values in each row correspond to the column in a matrix with the max value in that specific row.

For example,
If I have a matrix such as:

```<code>A = [1,5,2;3,1,1;0,1,0];
</code>```

I'd end up with the matrix:

```<code>maxValueColumns = transpose([2,1,2]);
</code>```

Is there an easy/efficient way to do this?

答:
You're looking for max():

```<code>A = [1,5,2;3,1,1;0,1,0];
[~, maxValueColumns] = max(A, [], 2); % 'maxValueColumns' will contain [2; 1; 2]
</code>```

Body:
I'd like to be able to create a column vector whose values in each row correspond to the column in a matrix with the max value in that specific row.

For example,
If I have a matrix such as:

A = [1,5,2;3,1,1;0,1,0];

I'd end up with the matrix:

maxValueColumns = transpose([2,1,2]);

Is there an easy/efficient way to do this?

Body:
You're looking for max():

A = [1,5,2;3,1,1;0,1,0];
[~, maxValueColumns] = max(A, [], 2); % 'maxValueColumns' will contain [2; 1; 2]


问:
Scala how can I count the number of occurrences in a list
```<code>val list = List(1,2,4,2,4,7,3,2,4)
</code>```

I want to implement it like this: list.count(2) (returns 3).

答:
I did not get the size of the list using length but rather size as one the answer above suggested it because of the issue reported here.

```<code>val list = List("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
list.groupBy(x=>x).map(t => (t._1, t._2.size))
</code>```

Body:
val list = List(1,2,4,2,4,7,3,2,4)

I want to implement it like this: list.count(2) (returns 3).

Body:
I did not get the size of the list using length but rather size as one the answer above suggested it because of the issue reported here.

val list = List("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
list.groupBy(x=>x).map(t => (t._1, t._2.size))


问:
Most efficient way to get child object properties from a DirectorySearcher result in Active Directory using C#
I am trying to find the most efficient way possible to get properties from certain types of objects whose parent OUs have been gethered using a DirectorySearcher query. These object's parents are groups that users are a member of (directly or indirectly) in Active Directory.

I think I have found a good recursive solution to get these groups, however once I have my result set, I'm not sure what the most efficient way to fetch the data is. Right now I'm using each result's Path to fetch the data like I would if I was just getting a single object.

I'm wondering if there is a faster way to do this, possibly by adding to my DirectorySeacher's Filter and getting these objects directly in my query results. The objects I'm searching for are objects so it seems the closest I can get to them in the DirectorySearcher query is going to be their parent OU.

```<code>foreach (SearchResult result in matchingADGroups)
{
    // Here I need to get result's child object properties(could be multiple children)
    DirectoryEntry entry = new DirectoryEntry("LDAP://" + result.Path.Substring(7));

    foreach(DirectoryEntry child in entry.Children)
    {
        Shortcut shortcut = new Shortcut();
        shortcut.DisplayName = (string)child.Properties["myDisplayName"].Value;
        shortcut.Id = (string)child.Properties["myId"].Value;

        shortcuts.Add(shortcut);
    }
}
</code>```

答:
I'm always skeptic about recursion when web requests or queries are being performed. But if it works for you, great!.

You can use DirectorySearcher for child nodes to further narrow down the resutls. Setup a DirectorySearcher:

```<code>DirectorySearcher _Search = new DirectorySearcher(entry);
_Search.Filter = "(&(objectCategory=person)(objectClass=user))";//can add more parameters
</code>```

You can add more parameters depending on how the ActiveDirectory is set up.
Next you can specify the properties that you need in the results

```<code>_Search.PropertiesToLoad.Add("distinguishedname");
</code>```

Use FindAll() method to get all objects and iterate them using foreach loop:

```<code>foreach (var result in _Search.FindAll()){
       //DO whatever you want here
       Shortcut shortcut = new Shortcut();
       shortcut.DisplayName = result.DisplayName;

}
</code>```

Hope this helps.

Body:
I am trying to find the most efficient way possible to get properties from certain types of objects whose parent OUs have been gethered using a DirectorySearcher query. These object's parents are groups that users are a member of (directly or indirectly) in Active Directory.

I think I have found a good recursive solution to get these groups, however once I have my result set, I'm not sure what the most efficient way to fetch the data is. Right now I'm using each result's Path to fetch the data like I would if I was just getting a single object.

I'm wondering if there is a faster way to do this, possibly by adding to my DirectorySeacher's Filter and getting these objects directly in my query results. The objects I'm searching for are objects so it seems the closest I can get to them in the DirectorySearcher query is going to be their parent OU.

foreach (SearchResult result in matchingADGroups)
{
    // Here I need to get result's child object properties(could be multiple children)
    DirectoryEntry entry = new DirectoryEntry("LDAP://" + result.Path.Substring(7));

    foreach(DirectoryEntry child in entry.Children)
    {
        Shortcut shortcut = new Shortcut();
        shortcut.DisplayName = (string)child.Properties["myDisplayName"].Value;
        shortcut.Id = (string)child.Properties["myId"].Value;

        shortcuts.Add(shortcut);
    }
}

Body:
I'm always skeptic about recursion when web requests or queries are being performed. But if it works for you, great!.

You can use DirectorySearcher for child nodes to further narrow down the resutls. Setup a DirectorySearcher:

DirectorySearcher _Search = new DirectorySearcher(entry);
_Search.Filter = "(&(objectCategory=person)(objectClass=user))";//can add more parameters

You can add more parameters depending on how the ActiveDirectory is set up.
Next you can specify the properties that you need in the results

_Search.PropertiesToLoad.Add("distinguishedname");

Use FindAll() method to get all objects and iterate them using foreach loop:

foreach (var result in _Search.FindAll()){
       //DO whatever you want here
       Shortcut shortcut = new Shortcut();
       shortcut.DisplayName = result.DisplayName;

}

Hope this helps.


问:
select rows in a dataframe in python based on two criteria
Based on the dataframe (1) below, I wish to create a dataframe (2) where either y or z is equal to 2. Is there a way to do this conveniently?

And if I were to create a dataframe (3) that only contains rows from dataframe (1) but not dataframe (2), how should I approach it?

```<code>    id  x  y  z
    0 324  1  2
    1 213  1  1
    2 529  2  1
    3 347  3  2
    4 109  2  2
</code>```

...

答:
You can create df2 easily enough using a condition:

```<code>df2 = df1[df1.y.eq(2) | df1.z.eq(2)]

df2
      x  y  z
id
0   324  1  2
2   529  2  1
3   347  3  2
4   109  2  2
</code>```

Given df2 and df1, you can perform a set difference operation on the index, like this:

```<code>df3 = df1.iloc[df1.index.difference(df2.index)]

df3
      x  y  z
id
1   213  1  1
</code>```

Body:
Based on the dataframe (1) below, I wish to create a dataframe (2) where either y or z is equal to 2. Is there a way to do this conveniently?

And if I were to create a dataframe (3) that only contains rows from dataframe (1) but not dataframe (2), how should I approach it?

    id  x  y  z
    0 324  1  2
    1 213  1  1
    2 529  2  1
    3 347  3  2
    4 109  2  2

...

Body:
You can create df2 easily enough using a condition:

df2 = df1[df1.y.eq(2) | df1.z.eq(2)]

df2
      x  y  z
id
0   324  1  2
2   529  2  1
3   347  3  2
4   109  2  2

Given df2 and df1, you can perform a set difference operation on the index, like this:

df3 = df1.iloc[df1.index.difference(df2.index)]

df3
      x  y  z
id
1   213  1  1


问:
Assigning a value to variable, stored in a MAP as value
I have the following MAP written in groovy

```<code>def Expected_Value="Jon Doe"
java.util.MAP var1=[node:"username", expected:Expected_Value]
</code>```

Now I want to check if the Expected_Value is Jon Doe, then change it to Hello World.

How do i do that using a Map?

I've got the condition as shown below

```<code>if(var1.get('expected')=="Jon Doe")
{

   \\\\\\\What do i write here\\\\\\\
}
</code>```

答:
Here you go:

You could just assign value as

var1.expected = 'Hello World or

var1.put('expected', 'Hello World') or

var1['expected'] = 'Hello World'

Here is the complete script for reference (just changed variable naming convention for better readablity)

```<code>def expectedValue = 'Jon Doe'
def map = [node:"username", expected:expectedValue]
map.expected = (map.expected != 'Jon Doe') ?: 'Hello World'
println map
</code>```

Body:
I have the following MAP written in groovy

def Expected_Value="Jon Doe"
java.util.MAP var1=[node:"username", expected:Expected_Value]

Now I want to check if the Expected_Value is Jon Doe, then change it to Hello World.

How do i do that using a Map?

I've got the condition as shown below

if(var1.get('expected')=="Jon Doe")
{

   \\\\\\\What do i write here\\\\\\\
}

Body:
Here you go:

You could just assign value as

var1.expected = 'Hello World or

var1.put('expected', 'Hello World') or

var1['expected'] = 'Hello World'

Here is the complete script for reference (just changed variable naming convention for better readablity)

def expectedValue = 'Jon Doe'
def map = [node:"username", expected:expectedValue]
map.expected = (map.expected != 'Jon Doe') ?: 'Hello World'
println map


问:
Haxe / OpenFL solving CORS error without having access to the server?
I know there are tons of questions regarding CORS policy in HTML5 tag.

All of them are talking about the server side settings that you need to change the access headers in the server settings or put the headers yourself in the php file etc.

But i am loading images using Loader class and i don't have access to that server.

how do i change the :

Access-Control-Allow-Origin to *

i tried pushing the headers with the URL Request :

```<code>urlRequest.requestHeaders.push( new URLRequestHeader( 'Access-Control-Allow-Origin', '*' ) );
</code>```

but no matter what i did :

i get this error :

Complete code snippet:

```<code>loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoadComplete);

var request:URLRequest = new URLRequest();
request.url = "http://www.someserver.com/some_image.jpg";

request.contentType = "image/jpeg"; //tried it didn't make a difference
request.requestHeaders.push( new URLRequestHeader( 'Access-Control-Allow-Origin', '*' ) );

loader.load(request);
</code>```

答:
In order to enable cross-origin requests, you will need to add the header on the server side. The alternative is to disable web security:

Disable same origin policy in Chrome

There was a window of time on OpenFL 6.3.0 (before 6.4.0 was released) where there was a regression in the default behavior of openfl.net.Loader (in regards to CORS), but this is resolved in OpenFL 6.4.0 or newer.

Body:
I know there are tons of questions regarding CORS policy in HTML5 tag.

All of them are talking about the server side settings that you need to change the access headers in the server settings or put the headers yourself in the php file etc.

But i am loading images using Loader class and i don't have access to that server.

how do i change the :

Access-Control-Allow-Origin to *

i tried pushing the headers with the URL Request :

urlRequest.requestHeaders.push( new URLRequestHeader( 'Access-Control-Allow-Origin', '*' ) );

but no matter what i did :

i get this error :

Complete code snippet:

loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoadComplete);

var request:URLRequest = new URLRequest();
request.url = "http://www.someserver.com/some_image.jpg";

request.contentType = "image/jpeg"; //tried it didn't make a difference
request.requestHeaders.push( new URLRequestHeader( 'Access-Control-Allow-Origin', '*' ) );

loader.load(request);


问:
Oracle 10g installer disappears
I have been trying to install oracle 10g following this tutorial http://faq.programmerworld.net/database/installing-oracle-10g.html
however, the installer just disappears after choosing the installation path and hitting next.

Welcome page

Deinstall Products

Select Installation Type -> Enterprise Edition

 Enterprise Edition ">

Specify home details

 OraDb10g_home1  Path -> c:\oracle\product\10.2.0\db_1">

Product-Specific Prerequisite Checks

After the last step, the window just disappears, and nothing happens
I looked on the internet and tried various things, the last thing I've been trying to do is this solution http://www.dbforums.com/showthread.php?1641469-Oracle-Installer-Disappears   but I couldn't figure out how to do what is said.

答:
Read this troubleshooting installation guide: https://docs.oracle.com/cd/B19306_01/install.102/b14317/ts.htm#NTDBX404

The first thing I would do is go see if you can find the installation logs, see if you can at least find an error code.

Title: Oracle 10g installer disappears