问:
How to get the location of all text present in an image using OpenCV?
I have this image that contains text (numbers and alphabets) in it. I want to get the location of all the text and numbers present in this image. Also I want to extract all the text as well.

How do I get the coordinates as well as the all the text (numbers and alphabets) in my image? For eg 10B, 44, 16, 38, 22B etc

答:
Alright, here's another possible solution. I know you work with Python - I work with C++. I'll give you some ideas and hopefully, if you desire so, you will be able to implement this answer.

The main idea is to not use pre-processing at all (at least not at the initial stage) and instead focus on each target character, get some properties, and filter every blob according to these properties.

I'm trying to not use pre-processing because: 1) Filters and morphological stages could degrade the quality of the blobs and 2) your target blobs appear to exhibit some characteristics that we could exploit, mainly: aspect ratio and area.

Check it out, the numbers and letters all appear to be taller than wider… furthermore, they appear to vary within a certain area value. For example, you want to discard objects "too wide" or "too big".

The idea is that I'll filter everything that does not fall within pre-calculated values. I examined the characters (numbers and letters) and came with minimum, maximum area values and a minimum aspect ratio (here, the ratio between height and width).

Let's work on the algorithm. Start by reading the image and resizing it to half the dimensions. Your image is way too big. Convert to grayscale and get a binary image via otsu, here's in pseudo-code:

```<code>//Read input:
inputImage = imread( "diagram.png" );

//Resize Image;
resizeScale = 0.5;

inputResized = imresize( inputImage, resizeScale );

//Convert to grayscale;
inputGray = rgb2gray( inputResized );

//Get binary image via otsu:
binaryImage = imbinarize( inputGray, "Otsu" );
</code>```

Cool. We will work with this image. You need to examine every white blob, and apply a "properties filter". I’m using connected components with stats to loop trough each blob and get its area and aspect ratio, in C++ this is done as follows:

```<code>//Prepare the output matrices:
cv::Mat outputLabels, stats, centroids;
int connectivity = 8;

//Run the binary image through connected components:
int numberofComponents = cv::connectedComponentsWithStats( binaryImage, outputLabels, stats, centroids, connectivity );

//Prepare a vector of colors – color the filtered blobs in black
std::vector<cv::Vec3b> colors(numberofComponents+1);
colors[0] = cv::Vec3b( 0, 0, 0 ); // Element 0 is the background, which remains black.

//loop through the detected blobs:
for( int i = 1; i <= numberofComponents; i++ ) {

    //get area:
    auto blobArea = stats.at<int>(i, cv::CC_STAT_AREA);

    //get height, width and compute aspect ratio:
    auto blobWidth = stats.at<int>(i, cv::CC_STAT_WIDTH);
    auto blobHeight = stats.at<int>(i, cv::CC_STAT_HEIGHT);
    float blobAspectRatio = (float)blobHeight/(float)blobWidth;

    //Filter your blobs…

};
</code>```

Now, we will apply the properties filter. This is just a comparison with the pre-calculated thresholds.  I used the following values:

```<code>Minimum Area: 40  Maximum Area:400
MinimumAspectRatio:  1
</code>```

Inside your for loop, compare the current blob properties with these values. If the tests are positive, you "paint" the blob black. Continuing inside the for loop:

```<code>    //Filter your blobs…

    //Test the current properties against the thresholds:
    bool areaTest =  (blobArea > maxArea)||(blobArea < minArea);
    bool aspectRatioTest = !(blobAspectRatio > minAspectRatio); //notice we are looking for TALL elements!

    //Paint the blob black:
    if( areaTest || aspectRatioTest ){
        //filtered blobs are colored in black:
        colors[i] = cv::Vec3b( 0, 0, 0 );
    }else{
        //unfiltered blobs are colored in white:
        colors[i] = cv::Vec3b( 255, 255, 255 );
    }
</code>```

After the loop, construct the filtered image:

```<code>cv::Mat filteredMat = cv::Mat::zeros( binaryImage.size(), CV_8UC3 );
for( int y = 0; y < filteredMat.rows; y++ ){
    for( int x = 0; x < filteredMat.cols; x++ )
    {
        int label = outputLabels.at<int>(y, x);
        filteredMat.at<cv::Vec3b>(y, x) = colors[label];
    }
}
</code>```

And… that's pretty much it. You filtered all the elements that are not similar to what you are looking for. Running the algorithm you get this result:

I've additionally found the Bounding Boxes of the blobs to better visualize the results:

As you see, some elements are miss-detected. You can refine the "properties filter" to better identify the characters you are looking for. A deeper solution, involving a little bit of machine learning, requires the construction of an "ideal feature vector", extracting features from the blobs, and comparing both vectors via a similarity measure. You can also apply some post-processing to improve the results...

Body:
Alright, here's another possible solution. I know you work with Python - I work with C++. I'll give you some ideas and hopefully, if you desire so, you will be able to implement this answer.

The main idea is to not use pre-processing at all (at least not at the initial stage) and instead focus on each target character, get some properties, and filter every blob according to these properties.

I'm trying to not use pre-processing because: 1) Filters and morphological stages could degrade the quality of the blobs and 2) your target blobs appear to exhibit some characteristics that we could exploit, mainly: aspect ratio and area.

Check it out, the numbers and letters all appear to be taller than wider… furthermore, they appear to vary within a certain area value. For example, you want to discard objects "too wide" or "too big".

The idea is that I'll filter everything that does not fall within pre-calculated values. I examined the characters (numbers and letters) and came with minimum, maximum area values and a minimum aspect ratio (here, the ratio between height and width).

Let's work on the algorithm. Start by reading the image and resizing it to half the dimensions. Your image is way too big. Convert to grayscale and get a binary image via otsu, here's in pseudo-code:

//Read input:
inputImage = imread( "diagram.png" );

//Resize Image;
resizeScale = 0.5;

inputResized = imresize( inputImage, resizeScale );

//Convert to grayscale;
inputGray = rgb2gray( inputResized );

//Get binary image via otsu:
binaryImage = imbinarize( inputGray, "Otsu" );

Cool. We will work with this image. You need to examine every white blob, and apply a "properties filter". I’m using connected components with stats to loop trough each blob and get its area and aspect ratio, in C++ this is done as follows:

//Prepare the output matrices:
cv::Mat outputLabels, stats, centroids;
int connectivity = 8;

//Run the binary image through connected components:
int numberofComponents = cv::connectedComponentsWithStats( binaryImage, outputLabels, stats, centroids, connectivity );

//Prepare a vector of colors – color the filtered blobs in black
std::vector<cv::Vec3b> colors(numberofComponents+1);
colors[0] = cv::Vec3b( 0, 0, 0 ); // Element 0 is the background, which remains black.

//loop through the detected blobs:
for( int i = 1; i <= numberofComponents; i++ ) {

    //get area:
    auto blobArea = stats.at<int>(i, cv::CC_STAT_AREA);

    //get height, width and compute aspect ratio:
    auto blobWidth = stats.at<int>(i, cv::CC_STAT_WIDTH);
    auto blobHeight = stats.at<int>(i, cv::CC_STAT_HEIGHT);
    float blobAspectRatio = (float)blobHeight/(float)blobWidth;

    //Filter your blobs…

};

Now, we will apply the properties filter. This is just a comparison with the pre-calculated thresholds.  I used the following values:

Minimum Area: 40  Maximum Area:400
MinimumAspectRatio:  1

Inside your for loop, compare the current blob properties with these values. If the tests are positive, you "paint" the blob black. Continuing inside the for loop:

    //Filter your blobs…

    //Test the current properties against the thresholds:
    bool areaTest =  (blobArea > maxArea)||(blobArea < minArea);
    bool aspectRatioTest = !(blobAspectRatio > minAspectRatio); //notice we are looking for TALL elements!

    //Paint the blob black:
    if( areaTest || aspectRatioTest ){
        //filtered blobs are colored in black:
        colors[i] = cv::Vec3b( 0, 0, 0 );
    }else{
        //unfiltered blobs are colored in white:
        colors[i] = cv::Vec3b( 255, 255, 255 );
    }

After the loop, construct the filtered image:

cv::Mat filteredMat = cv::Mat::zeros( binaryImage.size(), CV_8UC3 );
for( int y = 0; y < filteredMat.rows; y++ ){
    for( int x = 0; x < filteredMat.cols; x++ )
    {
        int label = outputLabels.at<int>(y, x);
        filteredMat.at<cv::Vec3b>(y, x) = colors[label];
    }
}

And… that's pretty much it. You filtered all the elements that are not similar to what you are looking for. Running the algorithm you get this result:

I've additionally found the Bounding Boxes of the blobs to better visualize the results:

As you see, some elements are miss-detected. You can refine the "properties filter" to better identify the characters you are looking for. A deeper solution, involving a little bit of machine learning, requires the construction of an "ideal feature vector", extracting features from the blobs, and comparing both vectors via a similarity measure. You can also apply some post-processing to improve the results...


来源: stackexchange

问:
How do I calculate two text boxes and display the answer in another?
I am trying to add the two text boxes and show the result in a third, whenever I try to add the third box, it makes it invalid. Any suggestions?
Here is my code!</p>

```<code>
    <br>
    <br>
    <p4>Calculate Two Fields</p4>
    <p4 id="answer"></p4>
    <br>
    <br>

    Number 1<input type="text" id="num1" <br>
    <br>
    Number 2<input type="text" id="num2" <br>
    <br>
    <button onclick="calculate()">Calculate</button>

    <script>
        function calculate() {
            var field1 = document.getElementById(num1).value;
            var field2 = document.getElementById(num2).value;

            var result = parseFloat(field1) + parseFloat(field2)

            if (!isNaN(result))

            {
                document.getElementById("answer").innerHTML = "The answer is " + result;

            }
    </script>
</code>```

答:
I cant see any mistake except ; or } .

Its better to use onchange or other events events to remove clicking  to get better ui/ux.

But you can do it with angularjs better.you can use ng-model for each input and in third input write {{model1+model2}}.

You can do it with vue.js too .the different is that you should use vmodel instead of ng-model.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to add the two text boxes and show the result in a third, whenever I try to add the third box, it makes it invalid. Any suggestions?
Here is my code!

    <p4>Calculate Two Fields</p4>
    <p4 id="answer"></p4>

    Number 1<input type="text" id="num1"

    Number 2<input type="text" id="num2"

    <button onclick="calculate()">Calculate</button>


问:
Send data from one page to another instead of preloading?
Say I have a blog route that loads a complete array of all blog posts. The individual blog posts live at blog/[postId]. Is there a Sapper-idiomatic way to pass the data for the individual post from blog to blog/[postId]?

Essentially, if you're on blog I'd like to preload the code for displaying blog/[postId]. And then when you click a link to blog/[postId], navigate there instantly and display data from blog. But of course if you navigate directly to blog/[postId] then preload() should still be called.

prefetch doesn't quite do it because that still requires a network request. I also tried a preload that checks a store and doesn't issue the network request unless its empty, but you can't use stores in

答:
Thanks @three for your comment which led me to the answer.

If a route or _layout component exports preload(), it always gets called on navigation. So I ended up doing this by storing the fetched data in the second parameter to preload(), which is conventionally called session and appears to be shared among all components. And I only called this.fetch() if the data was not already present.

{#each posts as post}

{/each}
```

<p>Then in <code>[slug].svelte</code> check <code>session.posts</code> for the post you're looking for, and if it isn't present, load it.</p>

<pre class="lang-html prettyprint-override"><code><!-- blog/[slug].svelte -->
<script context="module">
  export async function preload (page, session) {
    const {slug} = page.params
    const {posts} = session
    let post

    if (undefined === posts) {
      const response = await this.fetch(`blog/${slug}.json`)
      post = await response.json()
    } else {
      post = posts.find(p => p.slug === slug)
    }

    if (undefined === post) {
      this.error(404, "Sorry we couldn\'t find that post")
    }

    return {post}
  }
</script>

<script>
  export let post
</script>

<!-- ... render post -->
</code>```

Now navigation is instantaneous. For ultimate robustness you could add checks to reload if the data were stale (say older than 5 minutes, whatever).

Edit

You don't actually need to be using sessions, per se. If you just want to make the session parameter to preload(page, session) not be undefined you can use this in server.js:

sapper.middleware({
  // Define session parameter as an empty object
  session: (req, res) => ({})
})
```

Body:
Thanks @three for your comment which led me to the answer.

If a route or _layout component exports preload(), it always gets called on navigation. So I ended up doing this by storing the fetched data in the second parameter to preload(), which is conventionally called session and appears to be shared among all components. And I only called this.fetch() if the data was not already present.

<!-- blog/index.svelte -->
<script context="module">
  export async function preload (page, session) {
    let {posts} = session;
    if (undefined === posts) {
      const response = await this.fetch('blog/posts.json');
      posts = await response.json();
      session.posts = posts
    }

    return {posts}
  }
</script>

<script>
  export let posts;
</script>

{#each posts as post}
  <!-- ... -->
{/each}

Then in [slug].svelte check session.posts for the post you're looking for, and if it isn't present, load it.

<!-- blog/[slug].svelte -->
<script context="module">
  export async function preload (page, session) {
    const {slug} = page.params
    const {posts} = session
    let post

    if (undefined === posts) {
      const response = await this.fetch(`blog/${slug}.json`)
      post = await response.json()
    } else {
      post = posts.find(p => p.slug === slug)
    }

    if (undefined === post) {
      this.error(404, "Sorry we couldn\'t find that post")
    }

    return {post}
  }
</script>

<script>
  export let post
</script>

<!-- ... render post -->

Now navigation is instantaneous. For ultimate robustness you could add checks to reload if the data were stale (say older than 5 minutes, whatever).

Edit

You don't actually need to be using sessions, per se. If you just want to make the session parameter to preload(page, session) not be undefined you can use this in server.js:

sapper.middleware({
  // Define session parameter as an empty object
  session: (req, res) => ({})
})


问:
react-native hellow world app - working in emulator but not in physical device
I'm new to React-native and i create my first hello world program. In android studio emulator it works fine.
Emulator shows

I used following commands

```<code>react-native start
react-native run-android
</code>```

But when i get the app-debug.apk file from output folder and install in my physical mobile phone it gives following error. (This is a screenshot)

Have i done wrong somewhere?

Thank you

答:
https://facebook.github.io/react-native/docs/running-on-device
follow these steps, don't copy an apk file.</p>

Body:
I'm new to React-native and i create my first hello world program. In android studio emulator it works fine.
Emulator shows

I used following commands

react-native start
react-native run-android

But when i get the app-debug.apk file from output folder and install in my physical mobile phone it gives following error. (This is a screenshot)

Have i done wrong somewhere?

Thank you


问:
What are libapp.so and libflutter.so?
My Flutter application bundle contains native libraries, libapp.so and libflutter.so, each around 8-9MB. How can I find what is contributing to size of those files or which dependencies they're coming from? </p>

答:
Flutter is a portable UI tool kit, means everything that flutter depends upon must be included with in the APK file. So every flutter will have those mentioned .so files.

The mentioned .so files includes Dart language dependency, skia engine, flutter framework, platform related native code etc.

Title: What are libapp.so and libflutter.so?


问:
Best practice.
 or
,  or , etc
I haven't done serious web dev since 2013. I was usually pretty conscious of best practice. Lately as I'm using templates I'm seeing alot of  instead of  such as I had learned. Did something change? Is best practice changed?

答:
In HTML (up to HTML 4): use

In HTML 5:
 is preferred, but
 and
 is also acceptable

In XHTML:
 is preferred. Can also use
 or

Notes:

 is not valid in HTML 5, it will be thought of as two line
breaks.

XHTML is case sensitive, HTML is not case sensitive.

For backward compatibility, some old browsers would parse XHTML as
HTML and fail on
 but not

Reference:

http://www.w3schools.com/tags/tag_br.asp

http://en.wikipedia.org/wiki/XHTML

Title:
Best practice.
 or
,  or , etc

Body:
In HTML (up to HTML 4): use <br>

In HTML 5: <br> is preferred, but <br/> and <br /> is also acceptable

In XHTML: <br /> is preferred. Can also use <br/> or <br></br>

Notes:

<br></br> is not valid in HTML 5, it will be thought of as two line
breaks.

XHTML is case sensitive, HTML is not case sensitive.

For backward compatibility, some old browsers would parse XHTML as
HTML and fail on
 but not

Reference:

http://www.w3schools.com/tags/tag_br.asp

http://en.wikipedia.org/wiki/XHTML


问:
Javascript using RegEx to get multiple lines
I used the code below to get every 5 lines from an external text file. It works ok when testing with https://regex101.com/ but when running on Javascript the console return just 3 lines
Anyone knows what is the issue, please

It also works if data is included inside the function but doesn't work if loading from local file

```<code>reader = new FileReader();
if (filePath.files && filePath.files[0]) {
    reader.onload = function(e) {
      const regex = /(?:.*\s){1,5}/gm;

      // This one works as expected
      // const str = `    Line 1
      // Line 2
      // Line 3
      // Line 4
      // Line 5
      // Line 1
      // Line 2
      // Line 3
      // Line 4
      // Line 5`;

      //Loading from external file does not work
      const str = e.target.result;
      let m;

      while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
          regex.lastIndex++;
        }

        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
          console.log(`Found match, group ${groupIndex}: ${match}`);
        });
      }
</code>```

Testing Data:

```<code>Line 1
Line 2
Line 3
Line 4
Line 5
Line 1
Line 2
Line 3
Line 4
Line 5
</code>```

Result:

```<code>Found match, group 0: Line 1
Line 2
Line 3
</code>```

答:
I would not use regex - I would use .split() with \n separator, and this chunk() method to group them.

const str = `Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10`;

Array.prototype.chunk = function(size) {
  const chunked_arr = [];
  let index = 0;
  while (index < this.length) {
    chunked_arr.push(this.slice(index, size + index));
    index += size;
  }
  return chunked_arr;
}

const matches = str.split("\n").chunk(5);
console.log(matches);```

Body:
I used the code below to get every 5 lines from an external text file. It works ok when testing with https://regex101.com/ but when running on Javascript the console return just 3 lines
Anyone knows what is the issue, please

It also works if data is included inside the function but doesn't work if loading from local file

reader = new FileReader();
if (filePath.files && filePath.files[0]) {
    reader.onload = function(e) {
      const regex = /(?:.*\s){1,5}/gm;

      // This one works as expected
      // const str = `    Line 1
      // Line 2
      // Line 3
      // Line 4
      // Line 5
      // Line 1
      // Line 2
      // Line 3
      // Line 4
      // Line 5`;

      //Loading from external file does not work
      const str = e.target.result;
      let m;

      while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
          regex.lastIndex++;
        }

        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
          console.log(`Found match, group ${groupIndex}: ${match}`);
        });
      }

Testing Data:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 1
Line 2
Line 3
Line 4
Line 5

Result:

Found match, group 0: Line 1
Line 2
Line 3


问:
IIS7 HttpModule and ISAPI Filter execution order
I have a site using ISAPI Rewrite as well as a custom HttpModule that both do Url redirects and rewrites.

In IIS 6, everything worked fine: The ISAPI Rewrite filter would run first, followed by the HttpModule. In IIS 7 (Integrated mode) the order is now the reverse, which poses a problem.

My problem, specifically, is that the HttpModule has a condition where it will issue a Url rewrite using context.RewritePath. It will explicitly add "index.aspx" to the path if no document was provided, so a request to /test/ gets rewritten to /test/index.aspx.

At some point after the path is rewritten, the ISAPI Rewrite filter executes. We've got a rule that does the opposite of the module: a request to /test/index.aspx gets 301-redirected to /test/. Thus, we have an endless loop.

How is the execution order of HttpModules and ISAPI Filters determined in IIS 7? Can the order be changed? I found this question, but it didn't really help. I'm not a master of IIS 7, but I do understand to some extent that modules and ISAPI filters run "together". Unfortunately, they are still administered differently and I can't figure out how to force one to run before the other. Help!

Note: let's assume I cannot change the existing code. It worked in IIS 6. I just want to know if there's a way to make it work in IIS 7 Integrated mode.

答: Have a look at the following article which explains the IIS 7 pipeline.  The order of the pipeline cannot be changed.  Not sure if this is an option or not, but you could potentially replace the ISAPI Rewrite with the IIS URL Rewrite module.  This may allow your application to run in the integrated pipeline mode, otherwise, you may need to switch your app pool to run in classic mode.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Can you round a date to either the 1st or 15th based on they day of the month using r?
In the below piece of code I generate a date based off:

grabbing the first date from a character string that has one or more dates

adding a numeric value (lead time) to that date to get a new date

What I am trying to do is to now make the resulting date either the 15th of the month or the 1st of the month.  This would be done by saying "if the day of the month is 15th or greater, then make the date the 15th of said month, if it is less than 15 then make the date the 1st of said month")

I am much more familiar with SQL but not quite sure how do to this the most simple way in R

Code:

```<code>AAR_Combined_w_LL$newvalue <-mdy(substr(AAR_Combined_w_LL$order_cutoffs,0,10)) + AAR_Combined_w_LL$lead_time
</code>```

sample data:

```<code>                 season article_number                    order_cutoffs amount_of_limited_order_cut_offs retail_intro_date lead_time
1 adidas Fall/Winter 2020         GI7954 12/17/2019,01/14/2020,02/25/2020                                3        2020-07-01       105
2 adidas Fall/Winter 2020         GI7955 12/17/2019,01/14/2020,02/25/2020                                3        2020-07-01       105
3 adidas Fall/Winter 2020         P82146                       12/17/2019                                1        2020-06-01        75
4 adidas Fall/Winter 2020         S86676                       12/17/2019                                1        2020-06-01        75
5 adidas Fall/Winter 2020         P82145                       12/17/2019                                1        2020-06-01        75
6 adidas Fall/Winter 2020         S86673                       12/17/2019                                1        2020-06-01        75
  1st_Booking_Deadline   1st_BW_Retail_Windows 2nd_Booking_Deadline   2nd_BW_Retail_Windows 3rd_Booking_Deadline 3rd_BW_Retail_Windows
1           2019-12-06 2020-07-01 - 2020-08-01           2020-01-24 2020-09-01 - 2020-11-01
2           2019-12-06 2020-07-01 - 2020-08-01           2020-01-24 2020-09-01 - 2020-11-01
3           2019-12-06 2020-06-01 - 2020-11-01
4           2019-12-06 2020-06-01 - 2020-11-01
5           2019-12-06 2020-06-01 - 2020-11-01
6           2019-12-06 2020-06-01 - 2020-11-01
  4th_Booking_Deadline 4th_BW_Retail_Windows 5th_Booking_Deadline 5th_BW_Retail_Windows            Booking_Deadlines Booking_Deadline_Intervals
1                                                                                2019-12-06, 2020-01-24, , ,                           2
2                                                                                2019-12-06, 2020-01-24, , ,                           2
3                                                                                2019-12-06, , , ,                        NULL
4                                                                                2019-12-06, , , ,                        NULL
5                                                                                2019-12-06, , , ,                        NULL
6                                                                                2019-12-06, , , ,                        NULL
    newvalue
1 2020-03-31
2 2020-03-31
3 2020-03-01
4 2020-03-01
5 2020-03-01
6 2020-03-01
</code>```

Body:
In the below piece of code I generate a date based off:

grabbing the first date from a character string that has one or more dates

adding a numeric value (lead time) to that date to get a new date

What I am trying to do is to now make the resulting date either the 15th of the month or the 1st of the month.  This would be done by saying "if the day of the month is 15th or greater, then make the date the 15th of said month, if it is less than 15 then make the date the 1st of said month")

I am much more familiar with SQL but not quite sure how do to this the most simple way in R

Code:

AAR_Combined_w_LL$newvalue <-mdy(substr(AAR_Combined_w_LL$order_cutoffs,0,10)) + AAR_Combined_w_LL$lead_time

sample data:

                 season article_number                    order_cutoffs amount_of_limited_order_cut_offs retail_intro_date lead_time
1 adidas Fall/Winter 2020         GI7954 12/17/2019,01/14/2020,02/25/2020                                3        2020-07-01       105
2 adidas Fall/Winter 2020         GI7955 12/17/2019,01/14/2020,02/25/2020                                3        2020-07-01       105
3 adidas Fall/Winter 2020         P82146                       12/17/2019                                1        2020-06-01        75
4 adidas Fall/Winter 2020         S86676                       12/17/2019                                1        2020-06-01        75
5 adidas Fall/Winter 2020         P82145                       12/17/2019                                1        2020-06-01        75
6 adidas Fall/Winter 2020         S86673                       12/17/2019                                1        2020-06-01        75
  1st_Booking_Deadline   1st_BW_Retail_Windows 2nd_Booking_Deadline   2nd_BW_Retail_Windows 3rd_Booking_Deadline 3rd_BW_Retail_Windows
1           2019-12-06 2020-07-01 - 2020-08-01           2020-01-24 2020-09-01 - 2020-11-01
2           2019-12-06 2020-07-01 - 2020-08-01           2020-01-24 2020-09-01 - 2020-11-01
3           2019-12-06 2020-06-01 - 2020-11-01
4           2019-12-06 2020-06-01 - 2020-11-01
5           2019-12-06 2020-06-01 - 2020-11-01
6           2019-12-06 2020-06-01 - 2020-11-01
  4th_Booking_Deadline 4th_BW_Retail_Windows 5th_Booking_Deadline 5th_BW_Retail_Windows            Booking_Deadlines Booking_Deadline_Intervals
1                                                                                2019-12-06, 2020-01-24, , ,                           2
2                                                                                2019-12-06, 2020-01-24, , ,                           2
3                                                                                2019-12-06, , , ,                        NULL
4                                                                                2019-12-06, , , ,                        NULL
5                                                                                2019-12-06, , , ,                        NULL
6                                                                                2019-12-06, , , ,                        NULL
    newvalue
1 2020-03-31
2 2020-03-31
3 2020-03-01
4 2020-03-01
5 2020-03-01
6 2020-03-01

Body:
You could get the day, compare and assign value based on it.

library(lubridate)
x <- as.Date(c('2020-03-31','2020-03-31','2020-03-01','2020-03-01','2020-03-01'))

day(x) <- c(1, 15)[(day(x) >= 15) + 1]

This is another way of writing

day(x) <- ifelse(day(x) >= 15, 15, 1)
x
#[1] "2020-03-15" "2020-03-15" "2020-03-01" "2020-03-01" "2020-03-01"


问:
Lubridate putting dates into the future in R
When I do this code:

```<code>library(lubridate)
df$date <- format(as.Date(df$date, "%m/%d/%y") , "%Y")
</code>```

Some of the dates that are meant to be in the 1900s, eg: 1960, turn to 2060. I'm not sure how to fix this. The date range I want is 1951 - 2014, and I have around 8000 observations.

Body:
When I do this code:

library(lubridate)
df$date <- format(as.Date(df$date, "%m/%d/%y") , "%Y")

Some of the dates that are meant to be in the 1900s, eg: 1960, turn to 2060. I'm not sure how to fix this. The date range I want is 1951 - 2014, and I have around 8000 observations.

Body:
We can also do this with chron as the cut-off date is 1961 by default

as.Date(chron::dates(c('01/12/60', '01/12/78' ,'01/01/91', '01/01/54')))
#[1] "1960-01-12" "1978-01-12" "1991-01-01" "1954-01-01"


Title: Can you round a date to either the 1st or 15th based on they day of the month using r?

Body:
We can use ifelse

library(lubridate)
day(x) <- ifelse(day(x) > 15, 15, 1)
x
#[1] "2020-03-15" "2020-03-15" "2020-03-01" "2020-03-01" "2020-03-01"

Or with case_when

day(x) <- case_when(day(x) > 15 ~ 15, TRUE ~ 1)

Or using base R

day(x) <- ifelse(as.integer(format(x, "%d")) > 15, 15, 1)

Or another option is gsubfn to change from a character string

library(gsubfn)
as.Date(gsubfn("(\\d+)$", ~ ifelse(as.numeric(x) > 15, 15, 1), as.character(x)))
#[1] "2020-03-15" "2020-03-15" "2020-03-01" "2020-03-01" "2020-03-01"

data

x <- as.Date(c('2020-03-31','2020-03-31','2020-03-01','2020-03-01','2020-03-01'))


答:
Add this line in package.json

```<code>script:{
--
 "android-dev": "adb reverse tcp:8081 tcp:8081 && react-native run-android"
}
</code>```

and run this command :

```<code>adb reverse tcp:8081 tcp:8081
react-native run-android
</code>```

Title: react-native hellow world app - working in emulator but not in physical device

Body:
Add this line in package.json

script:{
--
 "android-dev": "adb reverse tcp:8081 tcp:8081 && react-native run-android"
}

and run this command :

adb reverse tcp:8081 tcp:8081
react-native run-android


问:
Replacements for switch statement in Python?
I want to write a function in Python that returns different fixed values based on the value of an input index.

In other languages I would use a switch or case statement, but Python does not appear to have a switch statement.  What are the recommended Python solutions in this scenario?

答:
In addition to the dictionary methods (which I really like, BTW), you can also use if-elif-else to obtain the switch/case/default functionality:

```<code>if x == 'a':
    # Do the thing
elif x == 'b':
    # Do the other thing
if x in 'bc':
    # Fall-through by not using elif, but now the default case includes case 'a'!
elif x in 'xyz':
    # Do yet another thing
else:
    # Do the default
</code>```

This of course is not identical to switch/case - you cannot have fall-through as easily as leaving off the break statement, but you can have a more complicated test. Its formatting is nicer than a series of nested ifs, even though functionally that's what it is closer to.

Body:
In addition to the dictionary methods (which I really like, BTW), you can also use if-elif-else to obtain the switch/case/default functionality:

if x == 'a':
    # Do the thing
elif x == 'b':
    # Do the other thing
if x in 'bc':
    # Fall-through by not using elif, but now the default case includes case 'a'!
elif x in 'xyz':
    # Do yet another thing
else:
    # Do the default

This of course is not identical to switch/case - you cannot have fall-through as easily as leaving off the break statement, but you can have a more complicated test. Its formatting is nicer than a series of nested ifs, even though functionally that's what it is closer to.

OwnerDisplayName: Matthew Schinckel

LastEditorDisplayName: Matthew Schinckel


问:
Ant task to determine if a file is readonly
I need to write an ant task to determine if a certain file is readonly, and if it is, fail.  I would like to avoid using a custom selector to do this do to the nature of our build system.  Anyone have any ideas how to go about doing this? I'm using ant 1.8 + ant-contrib.

Thanks!

答:
I'm sure there are better ways but I'll throw a few possible methods out there.

Use the copy task to create a temp duplicate then attempt to copy this file to overwrite the original. The failonerror attribute will come in handy

Use the java task to execute a task which executes some simple code such as:

File f = new File( path );
f.canWrite()......


问:
How do I select suitable rows from different relevant columns? (pandas Dataframe)
Everyone.I am the beginner for Pandas.
  My aim: select the most valuable team from the "team_list".
  the most valuable team means: most goals,least Yellow and Red Cards .
  the "team_list" consists of "Team","Goals","Yellow Cards","Red Cards" - four columns.
team_list shows

```<code>I want to solve the question like this,but it isn't python style. How can I do that?

sortGoals=euro.sort_values(by=['Goals'],ascending=False);
sortCards=sortGoals.sort_values(by=['Yellow Cards','Red Cards']);
print (sortCards.head(1));
the result :
              Team  Goals  Yellow Cards  Red Cards
5          Germany     10             4          0

the team information :
euro=DataFrame({'Team':['Croatia','Czech
Republic','Denmark','England','France','Germany',
'Greece','Italy','Netherlands','Poland','Portugal','Republic of
Ireland','Russia','Spain','Sweden','Ukraine'],'Goals':[4,4,4,5,3,10,5,6,2,2,6,1,5,12,5,2],'Yellow
Cards':[9,7,4,5,6,4,9,16,5,7,12,6,6,11,7,5],'Red Cards':[0,0,0,0,0,0,1,0,0,1,0,1,0,0,0,0]})

euro:
                Team  Goals  Yellow Cards  Red Cards
0               Croatia      4             9          0
1        Czech Republic      4             7          0
2               Denmark      4             4          0
3               England      5             5          0
4                France      3             6          0
5               Germany     10             4          0
6                Greece      5             9          1
7                 Italy      6            16          0
8           Netherlands      2             5          0
9                Poland      2             7          1
10             Portugal      6            12          0
11  Republic of Ireland      1             6          1
12               Russia      5             6          0
13                Spain     12            11          0
14               Sweden      5             7          0
15              Ukraine      2             5          0
</code>```

Joran Beasley inspires me, thank you.

```<code>   euro['RedCard_rate']=euro['Red Cards']/euro['Goals'];
   euro['YellowCard_rate']=euro['Yellow Cards']/euro['Goals'];
   sort_teams=euro.sort_values(by=['YellowCard_rate','RedCard_rate']);
   print (sort_teams[['Team','Goals','Yellow Cards','Red Cards']].head(1));

  the results:
          Team  Goals  Yellow Cards  Red Cards
   5   Germany     10             4          0
</code>```

答:
You can do this:

```<code>germany = euro.loc[euro.Team == 'Germany']
</code>```

More on pandas here: https://pandas.pydata.org/docs/user_guide/index.html

Body:
Everyone.I am the beginner for Pandas.
  My aim: select the most valuable team from the "team_list".
  the most valuable team means: most goals,least Yellow and Red Cards .
  the "team_list" consists of "Team","Goals","Yellow Cards","Red Cards" - four columns.
team_list shows

I want to solve the question like this,but it isn't python style. How can I do that?

sortGoals=euro.sort_values(by=['Goals'],ascending=False);
sortCards=sortGoals.sort_values(by=['Yellow Cards','Red Cards']);
print (sortCards.head(1));
the result :
              Team  Goals  Yellow Cards  Red Cards
5          Germany     10             4          0

the team information :
euro=DataFrame({'Team':['Croatia','Czech
Republic','Denmark','England','France','Germany',
'Greece','Italy','Netherlands','Poland','Portugal','Republic of
Ireland','Russia','Spain','Sweden','Ukraine'],'Goals':[4,4,4,5,3,10,5,6,2,2,6,1,5,12,5,2],'Yellow
Cards':[9,7,4,5,6,4,9,16,5,7,12,6,6,11,7,5],'Red Cards':[0,0,0,0,0,0,1,0,0,1,0,1,0,0,0,0]})

euro:
                Team  Goals  Yellow Cards  Red Cards
0               Croatia      4             9          0
1        Czech Republic      4             7          0
2               Denmark      4             4          0
3               England      5             5          0
4                France      3             6          0
5               Germany     10             4          0
6                Greece      5             9          1
7                 Italy      6            16          0
8           Netherlands      2             5          0
9                Poland      2             7          1
10             Portugal      6            12          0
11  Republic of Ireland      1             6          1
12               Russia      5             6          0
13                Spain     12            11          0
14               Sweden      5             7          0
15              Ukraine      2             5          0

Joran Beasley inspires me, thank you.

   euro['RedCard_rate']=euro['Red Cards']/euro['Goals'];
   euro['YellowCard_rate']=euro['Yellow Cards']/euro['Goals'];
   sort_teams=euro.sort_values(by=['YellowCard_rate','RedCard_rate']);
   print (sort_teams[['Team','Goals','Yellow Cards','Red Cards']].head(1));

  the results:
          Team  Goals  Yellow Cards  Red Cards
   5   Germany     10             4          0

Body:
You can do this:

germany = euro.loc[euro.Team == 'Germany']

More on pandas here: https://pandas.pydata.org/docs/user_guide/index.html


问:
Why am I getting an error that says Property assignment expected when I'm not even using TypeScript?
My Code is

```<code>import React from 'react';
import { Text, StyleSheet, View } from 'react-native';

const ComponentsScreen = () => {
  return {
    <View>
        <Text style={styles.testStyle}>This is the components screen</Text>
    </View>
    };
};

const styles = StyleSheet.create({
    testStyle: {
        fontSize: 30
    }
});

export default ComponentsScreen;
</code>```

I am getting an error which says Property Assignment Expected at my opening View tag, Declaration or Statement expected error at my closing View tag and at the bracket which closes ComponentsScreen, and Expression expected at the bracket closing my return statement. Any solutions?

答:
```<code>return {
    <View>
        <Text style={styles.testStyle}>This is the components screen</Text>
    </View>
}
</code>```

this will return an object.
You should return an JSX.Element instead.

try

```<code>return (
<View>
    <Text style={styles.testStyle}>This is the components screen</Text>
</View>)
</code>```

Body:
My Code is

import React from 'react';
import { Text, StyleSheet, View } from 'react-native';

const ComponentsScreen = () => {
  return {
    <View>
        <Text style={styles.testStyle}>This is the components screen</Text>
    </View>
    };
};

const styles = StyleSheet.create({
    testStyle: {
        fontSize: 30
    }
});

export default ComponentsScreen;

I am getting an error which says Property Assignment Expected at my opening View tag, Declaration or Statement expected error at my closing View tag and at the bracket which closes ComponentsScreen, and Expression expected at the bracket closing my return statement. Any solutions?

Body:
return {
    <View>
        <Text style={styles.testStyle}>This is the components screen</Text>
    </View>
}

this will return an object.
You should return an JSX.Element instead.

try

return (
<View>
    <Text style={styles.testStyle}>This is the components screen</Text>
</View>)


答:
Is this what your looking for?</p>

```<code>df[df['Team'].eq('Germany')]
      Team  Goals  Yellow Cards  Red Cards
5  Germany     10             4          0
</code>```

Title: How do I select suitable rows from different relevant columns? (pandas Dataframe)

Body:
Is this what your looking for?

df[df['Team'].eq('Germany')]
      Team  Goals  Yellow Cards  Red Cards
5  Germany     10             4          0


问:
Dynamic tabs using angular 6
I am using tabset for tabs.

For example: https://stackblitz.com/edit/ngx-bootstrap-tabs-manual?file=app%2Fapp.module.ts

I need to close and add the tabs dynamically using ngx-bootstrap,tabset.

Can anybody help me for the dynamic tabs.

答:
Please replace below HTML code in app.component.html this file for dynamic tab

```<code><alert type="success">
  <strong>Tabs!</strong> you can enable/disable tab switching with the button here.
</alert>

<label for="switcher">Disable tab switching: <input type="checkbox" [(ngModel)]="disableSwitching"></label>
<p>Tab switching is <strong>{{ disableSwitching ? 'disabled' : 'enabled ' }}</strong>.</p>
<hr>
<tabset #tabset>
  <tab *ngFor="let tab of tabsetData" [heading]="tab.tabtitle" [innerHTML]="tab.tabContent"></tab>
</tabset>

<button (click)='goto(0)'>Go to 1</button>
<button (click)='goto(1)'>Go to 2</button>
<button (click)='goto(2)'>Go to 3</button>
</code>```

For app.component.ts file code

```<code>import { Component, ViewChild , ViewChildren , QueryList , AfterViewInit } from '@angular/core';
import { TabsetComponent, TabDirective } from 'ngx-bootstrap/tabs';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit  {
  disableSwitching: boolean;

  @ViewChild('tabset') tabset: TabsetComponent;
  tabsetData = [{
    tabtitle: "First Tab",
    tabContent: "<p>First Tab</p>"
  },{
    tabtitle: "Second Tab",
    tabContent: "<p>Second Tab</p>"
  },{
    tabtitle: "Third Tab",
    tabContent: "<p>Third Tab</p>"
  }];
  ngAfterViewInit(){
    console.log(this.tabset.tabs);
  }

  goto(id){
    this.tabset.tabs[id].active = true;
  }
}
</code>```

Hope this helps! Thank you.

Title: Dynamic tabs using angular 6

Body:
Please replace below HTML code in app.component.html this file for dynamic tab

<alert type="success">
  <strong>Tabs!</strong> you can enable/disable tab switching with the button here.
</alert>

<label for="switcher">Disable tab switching: <input type="checkbox" [(ngModel)]="disableSwitching"></label>
<p>Tab switching is <strong>{{ disableSwitching ? 'disabled' : 'enabled ' }}</strong>.</p>
<hr>
<tabset #tabset>
  <tab *ngFor="let tab of tabsetData" [heading]="tab.tabtitle" [innerHTML]="tab.tabContent"></tab>
</tabset>

<button (click)='goto(0)'>Go to 1</button>
<button (click)='goto(1)'>Go to 2</button>
<button (click)='goto(2)'>Go to 3</button>

For app.component.ts file code

import { Component, ViewChild , ViewChildren , QueryList , AfterViewInit } from '@angular/core';
import { TabsetComponent, TabDirective } from 'ngx-bootstrap/tabs';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit  {
  disableSwitching: boolean;

  @ViewChild('tabset') tabset: TabsetComponent;
  tabsetData = [{
    tabtitle: "First Tab",
    tabContent: "<p>First Tab</p>"
  },{
    tabtitle: "Second Tab",
    tabContent: "<p>Second Tab</p>"
  },{
    tabtitle: "Third Tab",
    tabContent: "<p>Third Tab</p>"
  }];
  ngAfterViewInit(){
    console.log(this.tabset.tabs);
  }

  goto(id){
    this.tabset.tabs[id].active = true;
  }
}

Hope this helps! Thank you.


问:
Position / lot size based on buy entry and stop gap
I'm trying to code in Python my lot size based on a positive order signal.
Below is the expected output which was done in excel.
The logic is:
Lot_size = IF (Order_Signal=1, then Prior_Period_Portfolio_Value * Risk_pct / Stop_gap,
elif(Active=0, 0, prior period lot size))    risk_pct=0.02

I'm having a having a hard time to reproduce this in excel, specifically the last component where it refers to the prior period lot size.

答:
What I learn it from basic app developing courses (PhP) I was use itand on game dev fro sorting data in tables. So the trick here will be to create first the columns and then to add rows as childrens.

On tkinter I will do it like that:

1 - I will create a frame extended vertical as parent

```<code>frame = Frame()
frame.pack(expand=True, fill="y", side="left")
</code>```

2 - I will add entrys extended horizontal as childrens

```<code>entry = Entry(frame)
entry.pack(expand=True, fill="x", side="top")
</code>```

In this case all childrens will have same width.
If you want to use labels just for showing data for every child I will make a frame (same like entry example) and inside of that I will add label (same like entry but with side="right") and all text will have same width, and will be aligned on right.

Body:
What I learn it from basic app developing courses (PhP) I was use itand on game dev fro sorting data in tables. So the trick here will be to create first the columns and then to add rows as childrens.

On tkinter I will do it like that:

1 - I will create a frame extended vertical as parent

frame = Frame()
frame.pack(expand=True, fill="y", side="left")

2 - I will add entrys extended horizontal as childrens

entry = Entry(frame)
entry.pack(expand=True, fill="x", side="top")

In this case all childrens will have same width.
If you want to use labels just for showing data for every child I will make a frame (same like entry example) and inside of that I will add label (same like entry but with side="right") and all text will have same width, and will be aligned on right.


问:
glFrustum, gluPerspective and FOV
I have a program to do augmented reality and in OpenGL I use :

```<code>glFrustum(-near*centerImageX/(GLfloat)fx, near*(imageWidth-centerImageX)/(GLfloat)fx, near*(centerImageY-imageHeight)/(GLfloat)fy, near*centerImageY/(GLfloat)fy, near, far);
</code>```

This is ok, I get the good perspective and my 3D object is well inserted on my photo. Now I would like to be able to zoom in/out. Normally, it's done by changing fov in gluPerspective but I don't use gluPerspective because I can't get a good insertion.

With http://dmi.uib.es/~josemaria/files/OpenGLFAQ/transformations.htm, question "9.085 How can I make a call to glFrustum() that matches my call to gluPerspective()?", I tried with :

```<code>fov=360.0*atan(imageHeight/(2*fy))/Pi;  //computed with parameters top and bottom of my glFrustum
aspect=-centerImageY*fx/(fy*(centerImageX-imageWidth)); //computed with parameters left and bottom of my glFrustum
</code>```

void glFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far);

void gluPerspective( GLdouble fovy, GLdouble aspect,GLdouble near, GLdouble far );

And then :

```<code>gluPerspective(fov, aspect, near, far);
</code>```

But my object is distorted, it's not scaled correctly on all axes, ratio is not kept.

So what do I need to do / modify in my glFrustum parameters to get a zoom in / out effect ?

答:
I am not an OpenGL programmer. My interests mainly lies in algebraic projective geometry.

Per my understanding, The geometric meaning of the projection matrix in the OpenGL function GLFrustum(), which was explained in the  official guide of OpenGL (the nineth edition of the book, OpenGL programming guide-- the official guide to learning OpenGL), from an algebraic point of view, actually corresponds to many geometric meanings that are unluckily different from what the authors expected.

A significant difference between them are:
1. in the official guide, the authors are illustrating a compound linear transform with one of its factors as central projection, so the final compound perspective projecction matrix should be a singular or degenerated matrix;
2. while still in the official guide, at the appendix, the GLFrustum() perspective projection matrix is a nonsingular 4 times 4 square matrix!

Note that: The authors are trying to explain a nonsingular matrix into a theoretically singular one!

The following matrix decomposition (not unique) corresponds to one of the geometric meanings of the nonsingualr GLFrustum() matrix:
enter image description here

LaTeX code of the formulation:

```<code>$$n\underbrace{\color{blue}\left[
\begin{array}{cccc}
 1 & 0 & 0 & 0 \\[12pt]
 0 & 1 & 0 & 0 \\[12pt]
 0 & 0 &\dfrac{n+f}{(n-f) n} & 0 \\[12pt]
 0 & 0 & 0 & 1 \\[12pt]
\end{array}
\right]}_{\color{red}(1)}\cdot \underbrace{\color{blue}\left[
\begin{array}{cccc}
\dfrac{ -2}{l-r} & 0 & 0 & \dfrac{l+r}{l-r} \\[12pt]
 0 & \dfrac{ -2}{b-t} & 0 & \dfrac{b+t}{b-t} \\[12pt]
 0 & 0 & 1 & 0 \\[12pt]
 0 & 0 & 0 & 1 \\[12pt]
\end{array}
\right]}_{\color{red}(2)}\cdot\underbrace{\color{blue}\left[
\begin{array}{cccc}
 1 & 0 & 0 & 0 \\[12pt]
 0 & 1 & 0 & 0 \\[12pt]
 0 & 0 & 1 & 0 \\[12pt]
 0 & 0 & -\dfrac{1}{n} & 1 \\[12pt]
\end{array}
\right]}_{\color{red}(3)}\cdot\underbrace{\color{blue}\left[
\begin{array}{cccc}
 1 & 0 & 0 & 0 \\[12pt]
 0 & 1 & 0 & 0 \\[12pt]
 0 & 0 & 1 & 1 \\[12pt]
 0 & 0 & 0 & \dfrac{1}{n} \\[12pt]
\end{array}
\right]}_{\color{red}(4)}\cdot\underbrace{\color{blue}\left[
\begin{array}{cccc}
 1 & 0 & 0 & 0 \\[12pt]
 0 & 1 & 0 & 0 \\[12pt]
 0 & 0 & 1 & 0 \\[12pt]
 0 & 0 & 0 & \dfrac{2 n f}{f+n} \\[12pt]
\end{array}
\right]}_{\color{red}(5)} $$
</code>```

All of the above matrix factors except for No. (2), have their geoemtric meaning clearly redefined in Unified Framework of Elementary Geometric Transformations. If you choose this factorization as the geometric meaning explanation of the GLFrustum() perspective projection matrix, you will have to make sure any computation or transforms you are doing in your code are consistent to its geometric meaning.

So when you are programming with OpenGL GLFrustum(), probably may have to compare with what has been illustrated in the official guide and what the GLFrustum() perspective projection matrix really means from the view point of pure algebraic projective geometry, and use any one of your own.

Title: glFrustum, gluPerspective and FOV

Body:
I have a program to do augmented reality and in OpenGL I use :

glFrustum(-near*centerImageX/(GLfloat)fx, near*(imageWidth-centerImageX)/(GLfloat)fx, near*(centerImageY-imageHeight)/(GLfloat)fy, near*centerImageY/(GLfloat)fy, near, far);

This is ok, I get the good perspective and my 3D object is well inserted on my photo. Now I would like to be able to zoom in/out. Normally, it's done by changing fov in gluPerspective but I don't use gluPerspective because I can't get a good insertion.

With http://dmi.uib.es/~josemaria/files/OpenGLFAQ/transformations.htm, question "9.085 How can I make a call to glFrustum() that matches my call to gluPerspective()?", I tried with :

fov=360.0*atan(imageHeight/(2*fy))/Pi;  //computed with parameters top and bottom of my glFrustum
aspect=-centerImageY*fx/(fy*(centerImageX-imageWidth)); //computed with parameters left and bottom of my glFrustum

void glFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far);

void gluPerspective( GLdouble fovy, GLdouble aspect,GLdouble near, GLdouble far );

And then :

gluPerspective(fov, aspect, near, far);

But my object is distorted, it's not scaled correctly on all axes, ratio is not kept.

So what do I need to do / modify in my glFrustum parameters to get a zoom in / out effect ?

Body:
I am not an OpenGL programmer. My interests mainly lies in algebraic projective geometry.

Per my understanding, The geometric meaning of the projection matrix in the OpenGL function GLFrustum(), which was explained in the  official guide of OpenGL (the nineth edition of the book, OpenGL programming guide-- the official guide to learning OpenGL), from an algebraic point of view, actually corresponds to many geometric meanings that are unluckily different from what the authors expected.

A significant difference between them are:
1. in the official guide, the authors are illustrating a compound linear transform with one of its factors as central projection, so the final compound perspective projecction matrix should be a singular or degenerated matrix;
2. while still in the official guide, at the appendix, the GLFrustum() perspective projection matrix is a nonsingular 4 times 4 square matrix!

Note that: The authors are trying to explain a nonsingular matrix into a theoretically singular one!

The following matrix decomposition (not unique) corresponds to one of the geometric meanings of the nonsingualr GLFrustum() matrix:
enter image description here

LaTeX code of the formulation:

$$n\underbrace{\color{blue}\left[
\begin{array}{cccc}
 1 & 0 & 0 & 0 \\[12pt]
 0 & 1 & 0 & 0 \\[12pt]
 0 & 0 &\dfrac{n+f}{(n-f) n} & 0 \\[12pt]
 0 & 0 & 0 & 1 \\[12pt]
\end{array}
\right]}_{\color{red}(1)}\cdot \underbrace{\color{blue}\left[
\begin{array}{cccc}
\dfrac{ -2}{l-r} & 0 & 0 & \dfrac{l+r}{l-r} \\[12pt]
 0 & \dfrac{ -2}{b-t} & 0 & \dfrac{b+t}{b-t} \\[12pt]
 0 & 0 & 1 & 0 \\[12pt]
 0 & 0 & 0 & 1 \\[12pt]
\end{array}
\right]}_{\color{red}(2)}\cdot\underbrace{\color{blue}\left[
\begin{array}{cccc}
 1 & 0 & 0 & 0 \\[12pt]
 0 & 1 & 0 & 0 \\[12pt]
 0 & 0 & 1 & 0 \\[12pt]
 0 & 0 & -\dfrac{1}{n} & 1 \\[12pt]
\end{array}
\right]}_{\color{red}(3)}\cdot\underbrace{\color{blue}\left[
\begin{array}{cccc}
 1 & 0 & 0 & 0 \\[12pt]
 0 & 1 & 0 & 0 \\[12pt]
 0 & 0 & 1 & 1 \\[12pt]
 0 & 0 & 0 & \dfrac{1}{n} \\[12pt]
\end{array}
\right]}_{\color{red}(4)}\cdot\underbrace{\color{blue}\left[
\begin{array}{cccc}
 1 & 0 & 0 & 0 \\[12pt]
 0 & 1 & 0 & 0 \\[12pt]
 0 & 0 & 1 & 0 \\[12pt]
 0 & 0 & 0 & \dfrac{2 n f}{f+n} \\[12pt]
\end{array}
\right]}_{\color{red}(5)} $$

All of the above matrix factors except for No. (2), have their geoemtric meaning clearly redefined in Unified Framework of Elementary Geometric Transformations. If you choose this factorization as the geometric meaning explanation of the GLFrustum() perspective projection matrix, you will have to make sure any computation or transforms you are doing in your code are consistent to its geometric meaning.

So when you are programming with OpenGL GLFrustum(), probably may have to compare with what has been illustrated in the official guide and what the GLFrustum() perspective projection matrix really means from the view point of pure algebraic projective geometry, and use any one of your own.


问:
Logic Apps with Form Recogniser (Azure) - Error message: "ActionFailed. An action failed. No dependent actions succeeded."
I have created the logic app to read the invoice data using the form recogniser. When tested, I experienced an error. Any idea how this could be fixed?

Please see below my workflow and other details:

many thanks.

答:
As of the official document from Microsoft, the Analyze form connector only supports PFD format and (JPEG or PNG) image formats. But, the attachment that has come from your email is an octet-stream file which is certainly not supported.

You need to ensure that you are supplying only the supported file formats.


问:
Taking the rows of a data.frame and transposing into one column vector
I would like to take each rows of a data.frame, a [45,6] data.frame and make one continuous column vector with out have to write each index, such as; data.frame1 <- t(data.frame[1,2:6]), I just want the last five columns, then combining with rbind. Is there an R function for this, or is a loop function capable? Note: my loop skills are not so good.

Thanks Kirk

答:
Probably use the apply function. If the data frame (df) has only 6 columns, you can just omit the first column with df[,-1]. Then apply the rbind function to every row (MARGIN=1) and combine the values into a vector with the c function.

```<code>c(apply(df[,-1], MARGIN=1, rbind))
</code>```

Reproducible example

Using the mtcars data:

```<code>> df <- mtcars[1:6]
> head(df)
                   mpg cyl disp  hp drat    wt
Mazda RX4         21.0   6  160 110 3.90 2.620
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875
Datsun 710        22.8   4  108  93 3.85 2.320
Hornet 4 Drive    21.4   6  258 110 3.08 3.215
Hornet Sportabout 18.7   8  360 175 3.15 3.440
Valiant           18.1   6  225 105 2.76 3.460

> x <- c(apply(df[,-1], 1, rbind))
> head(x,20)
 [1]   6.000 160.000 110.000   3.900   2.620   6.000 160.000 110.000   3.900   2.875
[11]   4.000 108.000  93.000   3.850   2.320   6.000 258.000 110.000   3.080   3.215
</code>```

Body:
Probably use the apply function. If the data frame (df) has only 6 columns, you can just omit the first column with df[,-1]. Then apply the rbind function to every row (MARGIN=1) and combine the values into a vector with the c function.

c(apply(df[,-1], MARGIN=1, rbind))

Reproducible example

Using the mtcars data:

> df <- mtcars[1:6]
> head(df)
                   mpg cyl disp  hp drat    wt
Mazda RX4         21.0   6  160 110 3.90 2.620
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875
Datsun 710        22.8   4  108  93 3.85 2.320
Hornet 4 Drive    21.4   6  258 110 3.08 3.215
Hornet Sportabout 18.7   8  360 175 3.15 3.440
Valiant           18.1   6  225 105 2.76 3.460

> x <- c(apply(df[,-1], 1, rbind))
> head(x,20)
 [1]   6.000 160.000 110.000   3.900   2.620   6.000 160.000 110.000   3.900   2.875
[11]   4.000 108.000  93.000   3.850   2.320   6.000 258.000 110.000   3.080   3.215


问:
scikit-learn in R with reticulate
I am trying to use the reticulate package in R. There is a good intro here, but I'm failing to make much progress. Let's say I want to do something simple like build a linear model with scikit-learn. (Yes, I know R can do this perfectly well, but I'm just testing some things now...)

```<code>
library(reticulate)

# import modules
pd <- import("pandas")
np <- import("numpy")
skl_lr <- import("sklearn.linear_model")

# set up variables and response
x <- mtcars[, -1]
y <- mtcars[, 1]

# convert to python objects
pyx <- r_to_py(x)
pyy <- r_to_py(y)

# create model
skl_lr$LinearRegression$fit(pyx, pyy)

Error in py_call_impl(callable, dots$args, dots$keywords) :
  TypeError: fit() missing 1 required positional argument: 'y'

</code>```

Passing the the arguments explicitly does not work.

```<code>skl_lr$LinearRegression$fit(X = pyx, y = pyy)

Error in py_call_impl(callable, dots$args, dots$keywords) :
  TypeError: fit() missing 1 required positional argument: 'self'
</code>```

Any ideas?

Title: scikit-learn in R with reticulate

Body:
I am trying to use the reticulate package in R. There is a good intro here, but I'm failing to make much progress. Let's say I want to do something simple like build a linear model with scikit-learn. (Yes, I know R can do this perfectly well, but I'm just testing some things now...)

library(reticulate)

# import modules
pd <- import("pandas")
np <- import("numpy")
skl_lr <- import("sklearn.linear_model")

# set up variables and response
x <- mtcars[, -1]
y <- mtcars[, 1]

# convert to python objects
pyx <- r_to_py(x)
pyy <- r_to_py(y)

# create model
skl_lr$LinearRegression$fit(pyx, pyy)

Error in py_call_impl(callable, dots$args, dots$keywords) :
  TypeError: fit() missing 1 required positional argument: 'y'

Passing the the arguments explicitly does not work.

skl_lr$LinearRegression$fit(X = pyx, y = pyy)

Error in py_call_impl(callable, dots$args, dots$keywords) :
  TypeError: fit() missing 1 required positional argument: 'self'

Any ideas?

Body:
Just like in normal Python/Scikit, you need to initialize a model object before you can fit it.

lr <- skl_lr$LinearRegression()
lr$fit(pyx, pyy)

lr$coef_
# [1] -0.11144048  0.01333524 -0.02148212  0.78711097 -3.71530393  0.82104075  0.31776281
# [8]  2.52022689  0.65541302 -0.19941925


问:
striim - Connection Not Made: 1
striim running on local. I am trying to flow data from SQL running in Azure VM to Azure CosmosDB SQL API. But i am getting above error when testing connection. However it is connecting while adding source from template</p>

答: What is the connection string used?. Did you try to start the application?. As long as the app starts you shouldn't worry about the test connection.</p>

Title: striim - Connection Not Made: 1


问:
Finding Intersection of NSMutableArrays
I have three NSMutableArray containing names that are added to the lists according to different criterieas.

Here are my arrays pseudocode:

```<code>NSMutableArray *array1 = [@"Jack", @"John", @"Daniel", @"Lisa"];
NSMutableArray *array2 = [@"Jack", @"Bryan", @"Barney", @"Lisa",@"Penelope",@"Angelica"];
NSMutableArray *array3 = [@"Jack", @"Jerome", @"Dan", @"Lindsay", @"Lisa"];
</code>```

I want to find a fourth array which includes the intersection of those three arrays. In this case for example it will be:

```<code>NSMutableArray *array4 = [@"Jack",@"Lisa"];
</code>```

Because all the three array have jack and lisa as an element. Is there way of simply doing this?

答:
Have a look at this post.

In short: if you can use NSSet instead of NSArray, then it's trivial (NSMutableSet has intersectSet:).

Otherwise, you can build an NSSet from your NSArray and go back to the above case.

Title: Finding Intersection of NSMutableArrays

Body:
I have three NSMutableArray containing names that are added to the lists according to different criterieas.

Here are my arrays pseudocode:

NSMutableArray *array1 = [@"Jack", @"John", @"Daniel", @"Lisa"];
NSMutableArray *array2 = [@"Jack", @"Bryan", @"Barney", @"Lisa",@"Penelope",@"Angelica"];
NSMutableArray *array3 = [@"Jack", @"Jerome", @"Dan", @"Lindsay", @"Lisa"];

I want to find a fourth array which includes the intersection of those three arrays. In this case for example it will be:

NSMutableArray *array4 = [@"Jack",@"Lisa"];

Because all the three array have jack and lisa as an element. Is there way of simply doing this?


问:
Application does not write file to internal storage [Android]
I am trying to create and then write a simple file called "thisisafile.txt" in Android. After I run the application, file does not exist in internal storage.

```<code>import java.io.*;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String fileName = "thisisafile.txt";
    writeFile(fileName, "Hello World!");
}

    public static void writeFile(String fileName, String text) {
        File file = new File (fileName);
        try {
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        out.write(text);
        out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Is the file written? If then where, because I can't find it. If not, what am I doing wrong in the code?

答:
Referrence:

https://developer.android.com/training/permissions/requesting#java
https://stackoverflow.com/a/44155064/5207684

Use the following path for a file. It will write file to your root folder of storage.

```<code>String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");

writeToFile("File content".getBytes(), file);
</code>```

writeToFile

```<code>public static void writeToFile(byte[] data, File file) throws IOException {

    BufferedOutputStream bos = null;

    try {
        FileOutputStream fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(data);
    }
    finally {
        if (bos != null) {
            try {
                bos.flush ();
                bos.close ();
            }
            catch (Exception e) {
            }
        }
    }
}
</code>```

add external storage writing AND reading permissions in the manifest:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

After Android 6.0 WRITE_EXTERNAL_STORAGE permission must request in run time

```<code>requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 1);
</code>```

and then can handle the result of permission request in onRequestPermissionsResult() method inside activity called from it.

Example:

```<code>// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
        Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Permission is not granted
    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {
        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed; request the permission
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
} else {
    // Permission has already been granted
}
</code>```

Check on real device instead of Emulator.

Body:
I am trying to create and then write a simple file called "thisisafile.txt" in Android. After I run the application, file does not exist in internal storage.

import java.io.*;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String fileName = "thisisafile.txt";
    writeFile(fileName, "Hello World!");
}

    public static void writeFile(String fileName, String text) {
        File file = new File (fileName);
        try {
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        out.write(text);
        out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Is the file written? If then where, because I can't find it. If not, what am I doing wrong in the code?

Body:
Referrence:

https://developer.android.com/training/permissions/requesting#java
https://stackoverflow.com/a/44155064/5207684

Use the following path for a file. It will write file to your root folder of storage.

String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");

writeToFile("File content".getBytes(), file);

writeToFile

public static void writeToFile(byte[] data, File file) throws IOException {

    BufferedOutputStream bos = null;

    try {
        FileOutputStream fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(data);
    }
    finally {
        if (bos != null) {
            try {
                bos.flush ();
                bos.close ();
            }
            catch (Exception e) {
            }
        }
    }
}

add external storage writing AND reading permissions in the manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

After Android 6.0 WRITE_EXTERNAL_STORAGE permission must request in run time

requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 1);

and then can handle the result of permission request in onRequestPermissionsResult() method inside activity called from it.

Example:

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
        Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Permission is not granted
    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {
        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed; request the permission
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
} else {
    // Permission has already been granted
}

Check on real device instead of Emulator.


问:
Combinations in Pandas Python
I have a dataframe where each row has a particular activity of a user:

```<code>UserID  Date    Purchased
A       1 feb   Laptop
B       2 Feb   Laptop
A       2 Feb   Car
B       2 Feb   House
</code>```

Now I want to find the number of unique users who have purchased 2 different products (not more than 2) and their products should be 'Laptop' and 'Car'. So User A would be fall into this category. I have figured out how to get product count against each user but cant figure out how to filter user A.

答:
You can try something like this:

```<code>df.sort_values('Purchased')\
  .groupby(['UserID'])['Purchased']\
  .agg(['first','last','nunique'])\
  .query('first=="Car" and last=="Laptop" and nunique==2')\
  .reset_index()
</code>```

Output:

```<code>  UserID first    last  nunique
0      A   Car  Laptop        2
</code>```

Title: Combinations in Pandas Python

Body:
I have a dataframe where each row has a particular activity of a user:

UserID  Date    Purchased
A       1 feb   Laptop
B       2 Feb   Laptop
A       2 Feb   Car
B       2 Feb   House

Now I want to find the number of unique users who have purchased 2 different products (not more than 2) and their products should be 'Laptop' and 'Car'. So User A would be fall into this category. I have figured out how to get product count against each user but cant figure out how to filter user A.

Body:
You can try something like this:

df.sort_values('Purchased')\
  .groupby(['UserID'])['Purchased']\
  .agg(['first','last','nunique'])\
  .query('first=="Car" and last=="Laptop" and nunique==2')\
  .reset_index()

Output:

  UserID first    last  nunique
0      A   Car  Laptop        2


问:
How to read AppSettings values from a .json file in ASP.NET Core
I have set up my AppSettings data in file appsettings/Config .json like this:

```<code>{
  "AppSettings": {
        "token": "1234"
    }
}
</code>```

I have searched online on how to read AppSettings values from .json file, but I could not get anything useful.

I tried:

```<code>var configuration = new Configuration();
var appSettings = configuration.Get("AppSettings"); // null
var token = configuration.Get("token"); // null
</code>```

I know with ASP.NET 4.0 you can do this:

```<code>System.Configuration.ConfigurationManager.AppSettings["token"];
</code>```

But how do I do this in ASP.NET Core?

答:
The .NET Core 2.2 way

(No doubt Microsoft will change it again to something completely different in the next .NET version.)

1. appSettings.json

It may look something like this. Here we will be loading Setting1 and Setting2

```<code>{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Setting1": "abc",
  "Setting2": 123
}
</code>```

2. AppSettings.cs

The POCO class to hold Setting1 and Setting2. We will be loading the appsettings.json into this class object. The structure of the POCO class should match the JSON file, properties may be nested within other properties/classes if desired.

```<code>public class AppSettings
{
    public string Setting1 { get; set; }
    public int Setting2 { get; set; }
}
</code>```

3 Startup.cs

Load appSettings.json into you AppSettings object and start using it:

```<code>public class Startup
{
    public Startup(IConfiguration configuration)
    {
        AppSettings settings = new AppSettings();

        Configuration = configuration;
        configuration.Bind(settings);

        // Now start using it
        string setting1 = settings.Setting1;
        int setting2 = settings.Setting2;
    }
</code>```

Body:
I have set up my AppSettings data in file appsettings/Config .json like this:

{
  "AppSettings": {
        "token": "1234"
    }
}

I have searched online on how to read AppSettings values from .json file, but I could not get anything useful.

I tried:

var configuration = new Configuration();
var appSettings = configuration.Get("AppSettings"); // null
var token = configuration.Get("token"); // null

I know with ASP.NET 4.0 you can do this:

System.Configuration.ConfigurationManager.AppSettings["token"];

But how do I do this in ASP.NET Core?

Body:
The .NET Core 2.2 way

(No doubt Microsoft will change it again to something completely different in the next .NET version.)

1. appSettings.json

It may look something like this. Here we will be loading Setting1 and Setting2

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Setting1": "abc",
  "Setting2": 123
}

2. AppSettings.cs

The POCO class to hold Setting1 and Setting2. We will be loading the appsettings.json into this class object. The structure of the POCO class should match the JSON file, properties may be nested within other properties/classes if desired.

public class AppSettings
{
    public string Setting1 { get; set; }
    public int Setting2 { get; set; }
}

3 Startup.cs

Load appSettings.json into you AppSettings object and start using it:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        AppSettings settings = new AppSettings();

        Configuration = configuration;
        configuration.Bind(settings);

        // Now start using it
        string setting1 = settings.Setting1;
        int setting2 = settings.Setting2;
    }


问:
Tensorflow crashes with CUBLAS_STATUS_ALLOC_FAILED
I'm running tensorflow-gpu on Windows 10 using a simple MINST neural network program. When it tries to run, it encounters a CUBLAS_STATUS_ALLOC_FAILED error. A google search doesn't turn up anything.

```<code>I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:885] Found device 0 with properties:
name: GeForce GTX 970
major: 5 minor: 2 memoryClockRate (GHz) 1.253
pciBusID 0000:0f:00.0
Total memory: 4.00GiB
Free memory: 3.31GiB
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:906] DMA: 0
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:916] 0:   Y
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 970, pci bus id: 0000:0f:00.0)
E c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_blas.cc:372] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\stream.cc:1390] attempting to perform BLAS operation using StreamExecutor without BLAS support
Traceback (most recent call last):
  File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1021, in _do_call
    return fn(*args)
  File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1003, in _run_fn
    status, run_metadata)
  File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python35\lib\contextlib.py", line 66, in __exit__
    next(self.gen)
  File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 469, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InternalError: Blas SGEMM launch failed : a.shape=(100, 784), b.shape=(784, 256), m=100, n=256, k=784
         [[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_Placeholder_0/_7, Variable/read)]]
         [[Node: Mean/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_35_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
</code>```

答: In my case, a stale python process was consuming memory. I killed it through task manager, and things are back to normal.</p>

Body:
I'm running tensorflow-gpu on Windows 10 using a simple MINST neural network program. When it tries to run, it encounters a CUBLAS_STATUS_ALLOC_FAILED error. A google search doesn't turn up anything.

I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:885] Found device 0 with properties:
name: GeForce GTX 970
major: 5 minor: 2 memoryClockRate (GHz) 1.253
pciBusID 0000:0f:00.0
Total memory: 4.00GiB
Free memory: 3.31GiB
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:906] DMA: 0
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:916] 0:   Y
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 970, pci bus id: 0000:0f:00.0)
E c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_blas.cc:372] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\stream.cc:1390] attempting to perform BLAS operation using StreamExecutor without BLAS support
Traceback (most recent call last):
  File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1021, in _do_call
    return fn(*args)
  File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1003, in _run_fn
    status, run_metadata)
  File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python35\lib\contextlib.py", line 66, in __exit__
    next(self.gen)
  File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 469, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InternalError: Blas SGEMM launch failed : a.shape=(100, 784), b.shape=(784, 256), m=100, n=256, k=784
         [[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_Placeholder_0/_7, Variable/read)]]
         [[Node: Mean/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_35_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]


问:
How can I transition my Module-Singleton JavaScript to supporting instances?
I've been writing an application and I have had a lot of success breaking different pieces of functionality into the so called "Module" pattern where you have a self-executing singleton with public and private members.

```<code>var WidgetModule = (function($, options) {

    // Private variable
    var someVar;

    // Private functions
    function somePrivateFunction() {

    }

    // Define the public members
    var self = {
        init: function() {

        },
        someFunction: function() {

        }
    };

    return self;

})(jQuery, options);
</code>```

I have now run into a case where I have several modules which I would like to be able to create multiple instances of.

I know this pattern is based on the singleton but I wonder if there was a painless way to modify this pattern to support creating instances of them?

答:
When I need common functionality for multiple objects, here's the pattern I usually use (adjusted to account for the code you presented):

```<code>var Widget = (function($) {
    var pubs = Widget.prototype;

    // Private variable -- global to all instances
    var someVar;

    // The constructor
    function Widget(options) {
        var privateInstanceVar;

        this.privateInstanceFunc = function() {
            return privateInstanceVar;
        };
    }

    // Private functions -- global to all instances
    function somePrivateFunction() {

    }

    // Define the public members
    pubs.init = function() {

    };

    pubs.someFunction = function() {

    };

    return Widget;

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

Usage:

```<code>var w = new Widget({someOption: "here"});
</code>```

As you can see, you can share private data amongst all instances created by the constructor, and if you really want to, you can have private data that's shared only with certain select instance functions. Those functions have to be created in the constructor, which has reuse implications, whereas functions that don't need the truly-private instance data can be on the prototype and therefore be shared by all instances.

Better yet, since you already have a handy scoping function, you can help your tools help you by giving your public functions actual names:

```<code>    pubs.init = Widget_init;
    function Widget_init() {

    }
</code>```

I mostly don't actually code the above, because I've defined a helper factory that makes it a bit more concise (and makes it easier to do specializations of functionality, like a Car inheriting functionality from Vehicle); details here.

Body:
I've been writing an application and I have had a lot of success breaking different pieces of functionality into the so called "Module" pattern where you have a self-executing singleton with public and private members.

var WidgetModule = (function($, options) {

    // Private variable
    var someVar;

    // Private functions
    function somePrivateFunction() {

    }

    // Define the public members
    var self = {
        init: function() {

        },
        someFunction: function() {

        }
    };

    return self;

})(jQuery, options);

I have now run into a case where I have several modules which I would like to be able to create multiple instances of.

I know this pattern is based on the singleton but I wonder if there was a painless way to modify this pattern to support creating instances of them?

Body:
When I need common functionality for multiple objects, here's the pattern I usually use (adjusted to account for the code you presented):

var Widget = (function($) {
    var pubs = Widget.prototype;

    // Private variable -- global to all instances
    var someVar;

    // The constructor
    function Widget(options) {
        var privateInstanceVar;

        this.privateInstanceFunc = function() {
            return privateInstanceVar;
        };
    }

    // Private functions -- global to all instances
    function somePrivateFunction() {

    }

    // Define the public members
    pubs.init = function() {

    };

    pubs.someFunction = function() {

    };

    return Widget;

})(jQuery);

Usage:

var w = new Widget({someOption: "here"});

As you can see, you can share private data amongst all instances created by the constructor, and if you really want to, you can have private data that's shared only with certain select instance functions. Those functions have to be created in the constructor, which has reuse implications, whereas functions that don't need the truly-private instance data can be on the prototype and therefore be shared by all instances.

Better yet, since you already have a handy scoping function, you can help your tools help you by giving your public functions actual names:

    pubs.init = Widget_init;
    function Widget_init() {

    }

I mostly don't actually code the above, because I've defined a helper factory that makes it a bit more concise (and makes it easier to do specializations of functionality, like a Car inheriting functionality from Vehicle); details here.


Title: Pandas: How create columns where sum other columns based on conditional of other column values?

Body:
I have the following pandas DataFrame.

import pandas as pd
df = pd.read_csv('filename.csv')

print(df)

 code1  code2 code3 code4 value1 value2 value3 value4
0 101   101   101   101   1000    1000  1000   1000
1 101   101   101   201   1000    1000  1000   1000
2 101   101   201   201   1000    1000  1000   1000
3 101   201   201   201   1000    1000  1000   1000
4 101   201   201   301   1000    1000  1000   1000
5 101   201   301   301   1000    1000  1000   1000
6 101   301   301   301   1000    1000  1000   1000
7 101   101   101   301   1000    1000  1000   1000
8 101   201   301   0     1000    1000  1000   0
9 101   301   0     0     1000    1000  0      0

....

I need to create one column to sum the column value(value1, value2, value3, value4) considering the columns code (code1, code2, code3, code4) as follows:

  code1 code2 code3 code4 value1 value2 value3 value4 sum_code_101 sum_code_201 sum_code_301
0 101   101   101   101   1000    1000  1000   1000     4000           0           0
1 101   101   101   201   1000    1000  1000   1000     3000           1000        0
2 101   101   201   201   1000    1000  1000   1000     2000           2000        0
3 101   201   201   201   1000    1000  1000   1000     1000           3000        0
4 101   201   201   301   1000    1000  1000   1000     1000           2000        1000
5 101   201   301   301   1000    1000  1000   1000     1000           1000        2000
6 101   301   301   301   1000    1000  1000   1000     1000           0           3000
7 101   101   101   301   1000    1000  1000   1000     3000           0           1000
8 101   201   301   0     1000    1000  1000   0        1000           1000        1000
9 101   301   0     0     1000    1000  0      0        1000           0           1000

I have tried:

df['sum_code_101']=df[df['code1']=='101'],['value1']+df[df['code2']=='101'],['value2']+df[df['code3']=='101'],['value3']+df[df['code4']=='101'],['value4']
df['sum_code_201']=df[df['code1']=='201'],['value1']+df[df['code2']=='201'],['value2']+df[df['code3']=='201'],['value3']+df[df['code4']=='201'],['value4']
df['sum_code_301']=df[df['code1']=='301'],['value1']+df[df['code2']=='301'],['value2']+df[df['code3']=='301'],['value3']+df[df['code4']=='301'],['value4']

However, I got this error message:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

As the real dataframe has 25 differents codes (101, 201, 301..) I need to create a 25 columns to sum their values.

Any Help from You Guys will be very Appreciated, Thank You . . .

Body:
Here is a solution using the pandas apply method. Generally not ideal when you can use column/row operations. But this works.

import pandas as pd
data = {
    'code1': ['101', '101', '101', '101', '101', '101'],
    'code2': ['101', '101', '101', '201', '201', '201'],
    'code3': ['101', '101', '101', '201', '201', '301'],
    'code4': ['101', '201', '201', '201', '301', '301'],
    'value1': [1000, 1000, 1000, 1000, 1000, 1000],
    'value2': [1000, 1000, 1000, 1000, 1000, 1000],
    'value3': [1000, 1000, 1000, 1000, 1000, 1000],
    'value4': [1000, 1000, 1000, 1000, 1000, 1000]
}
df = pd.DataFrame(data)

def apply_to_row(row, value):
    code_cols = ['code1', 'code2', 'code3', 'code4']
    value_cols = ['value1', 'value2', 'value3', 'value4']

    code_value_sum = 0
    for code_col, value_col in zip(code_cols, value_cols):
        if row[code_col] == value:
            code_value_sum += row[value_col]

    return code_value_sum

code_values = ['101', '201', '301'] # probably replace with a distinct value list of code columns
for code_value in code_values:
    df['sum_code_' + str(code_value)] = df.apply(apply_to_row, value=code_value, axis=1)

here is the result:

  code1 code2 code3 code4  value1  value2  value3  value4   sum_code_101  sum_code_201  sum_code_301
0   101   101   101   101    1000    1000    1000    1000          4000     0                0
1   101   101   101   201    1000    1000    1000    1000          3000     1000             0
2   101   101   101   201    1000    1000    1000    1000          3000     1000             0
3   101   201   201   201    1000    1000    1000    1000          1000     3000             0
4   101   201   201   301    1000    1000    1000    1000          1000     2000             1000
5   101   201   301   301    1000    1000    1000    1000          1000     1000             2000

Thanks!


问:
Change HardMarginX for Print PDF File using PdfiumViewer
I used pdfiumViewer to print a label created by itextshape, i finded this code in stackoverflow, it's work good for A4 paper but for custom paper like my label the problem going to happening. This is code:

```<code>public static void PrintPDF(string printer, string paperName, string filename, int copies, bool isduplex = false, bool isHorizontal = false, bool printLabel = false)
    {
        try
        {    // Create the printer settings for our printer
            var printerSettings = new PrinterSettings
            {
                PrinterName = printer,
                Copies = (short)copies,
                Duplex = Duplex.Simplex,

            };

            if (isduplex && printerSettings.CanDuplex && isHorizontal)
            {
                printerSettings.Duplex = Duplex.Horizontal;
            }

            if (isduplex && printerSettings.CanDuplex && isHorizontal == false)
            {
                printerSettings.Duplex = Duplex.Vertical;
            }
            // Create our page settings for the paper size selected
            var pageSettings = new PageSettings(printerSettings)
            {
            };

            if (printLabel == true)
            {
                PaperSize paper = new PaperSize("label", 460, 260);
                pageSettings.PaperSize = paper;
                pageSettings.Margins = new Margins(0, 0, 0, 0);
            }
            else
            {
                foreach (PaperSize paperSize in printerSettings.PaperSizes)
                {
                    if (paperSize.PaperName == paperName)
                    {
                        pageSettings.PaperSize = paperSize;
                        break;
                    }
                }

            }

            // Now print the PDF document
            if (printerSettings.IsValid)
            {
                using (var document = PdfiumViewer.PdfDocument.Load(filename))
                {
                    using (var printDocument = document.CreatePrintDocument(PdfiumViewer.PdfPrintMode.CutMargin))
                    {
                        printDocument.PrintController = new StandardPrintController();
                        printDocument.OriginAtMargins = true;
                        printDocument.PrinterSettings = printerSettings;
                        printDocument.DefaultPageSettings = pageSettings;
                        printDocument.Print();
                    }
                }
            }
        }
        catch
        {
            throw;
        }
    }
</code>```

The problem is the HardMarginX alway is 20. It is readonly properties so i can not change. So when i print, paper alway margin left some space. So anyway i can do to fix this problem.
Thank for reading

答:
```<code>        PaperSize paperSize = new PaperSize("Test", 315, 300);
        paperSize.RawKind = (int)PaperKind.Custom;
</code>```

Using This Code

Body:
I used pdfiumViewer to print a label created by itextshape, i finded this code in stackoverflow, it's work good for A4 paper but for custom paper like my label the problem going to happening. This is code:

public static void PrintPDF(string printer, string paperName, string filename, int copies, bool isduplex = false, bool isHorizontal = false, bool printLabel = false)
    {
        try
        {    // Create the printer settings for our printer
            var printerSettings = new PrinterSettings
            {
                PrinterName = printer,
                Copies = (short)copies,
                Duplex = Duplex.Simplex,

            };

            if (isduplex && printerSettings.CanDuplex && isHorizontal)
            {
                printerSettings.Duplex = Duplex.Horizontal;
            }

            if (isduplex && printerSettings.CanDuplex && isHorizontal == false)
            {
                printerSettings.Duplex = Duplex.Vertical;
            }
            // Create our page settings for the paper size selected
            var pageSettings = new PageSettings(printerSettings)
            {
            };

            if (printLabel == true)
            {
                PaperSize paper = new PaperSize("label", 460, 260);
                pageSettings.PaperSize = paper;
                pageSettings.Margins = new Margins(0, 0, 0, 0);
            }
            else
            {
                foreach (PaperSize paperSize in printerSettings.PaperSizes)
                {
                    if (paperSize.PaperName == paperName)
                    {
                        pageSettings.PaperSize = paperSize;
                        break;
                    }
                }

            }

            // Now print the PDF document
            if (printerSettings.IsValid)
            {
                using (var document = PdfiumViewer.PdfDocument.Load(filename))
                {
                    using (var printDocument = document.CreatePrintDocument(PdfiumViewer.PdfPrintMode.CutMargin))
                    {
                        printDocument.PrintController = new StandardPrintController();
                        printDocument.OriginAtMargins = true;
                        printDocument.PrinterSettings = printerSettings;
                        printDocument.DefaultPageSettings = pageSettings;
                        printDocument.Print();
                    }
                }
            }
        }
        catch
        {
            throw;
        }
    }

The problem is the HardMarginX alway is 20. It is readonly properties so i can not change. So when i print, paper alway margin left some space. So anyway i can do to fix this problem.
Thank for reading

Body:
        PaperSize paperSize = new PaperSize("Test", 315, 300);
        paperSize.RawKind = (int)PaperKind.Custom;

Using This Code


问:
Flutter | How to remove specific key from Shared preferences
here I want to delete the particular product from my cart. and my cart is generated using shared preferences data. so basically I want to remove the particular index from shared preferences.
Hope you understand the question. also here i am using on listview builder for display the data.

Here is code of shared preferences,

```<code>SharedPreferences preferences = await SharedPreferences.getInstance();
List<String> cartitems = preferences.getStringList('cartItems');

 return ListView.builder(
  physics: NeverScrollableScrollPhysics(),
  shrinkWrap: true,
  itemCount: unauthCartItems.length,
  itemBuilder: (context, index) {
    print(unauthCartItems.length);

    return FlatButton(
      onPressed: () {
        //Here i want to clear the Preferences based on index
      },
    );
  },
);
</code>```

答:
Remove the item from the list and save it back to the preference.</p>

```<code>     cartitems.removeAt(index);

     preferences.setStringList(cartitems)
</code>```

Body:
here I want to delete the particular product from my cart. and my cart is generated using shared preferences data. so basically I want to remove the particular index from shared preferences.
Hope you understand the question. also here i am using on listview builder for display the data.

Here is code of shared preferences,

SharedPreferences preferences = await SharedPreferences.getInstance();
List<String> cartitems = preferences.getStringList('cartItems');

 return ListView.builder(
  physics: NeverScrollableScrollPhysics(),
  shrinkWrap: true,
  itemCount: unauthCartItems.length,
  itemBuilder: (context, index) {
    print(unauthCartItems.length);

    return FlatButton(
      onPressed: () {
        //Here i want to clear the Preferences based on index
      },
    );
  },
);

Body:
Remove the item from the list and save it back to the preference.

     cartitems.removeAt(index);

     preferences.setStringList(cartitems)