问:
Reading a string line by line in python
I have the following string that is generated using tkinter and then read using textEntry.get():

```<code>"
=========New Coffee Order===============
=========Bean Information===============
Type: Ethiopian
Origin: Single

=========Roaster/price==================
Steve's Beans
8.50/lb

Everyday Espresso
10.00/lb

Critical Coffee
6.00/lb

=========End Coffee Order==============
"
</code>```

I am trying to use fpdf to generate a pdf file of this information that follows a formatting guide. My question is this:

How can I tell python to read a string in a way that interprets each line and not simply as a list of characters?

My initial idea was to tell python to read this string line by line and assign values to each line. However that seems like it might be inefficient, Is there a better way to do this?

Thank you.

答:
str.split('\n') will do the trick:

```<code>In [135]: text.split('\n')
Out[135]:
['"',
 '=========New Coffee Order===============',
 '=========Bean Information===============',
 'Type: Ethiopian',
 'Origin: Single',
 '',
 '=========Roaster/price==================',
 "Steve's Beans",
 '8.50/lb',
 '',
 'Everyday Espresso',
 '10.00/lb',
 '',
 'Critical Coffee ',
 '6.00/lb',
 '',
 '',
 '=========End Coffee Order==============',
 '"']
</code>```

All you'll need to do is iterate over the returned list, line by line:

```<code>for line in text.split('\n'):
    ...
</code>```

Comparing @Robᵩ's and my solutions:

```<code>In [137]: %timeit text.splitlines()
1000000 loops, best of 3: 1.8 µs per loop

In [138]: %timeit text.split('\n')
1000000 loops, best of 3: 1.31 µs per loop
</code>```

Title: Reading a string line by line in python

Body:
I have the following string that is generated using tkinter and then read using textEntry.get():

"
=========New Coffee Order===============
=========Bean Information===============
Type: Ethiopian
Origin: Single

=========Roaster/price==================
Steve's Beans
8.50/lb

Everyday Espresso
10.00/lb

Critical Coffee
6.00/lb

=========End Coffee Order==============
"

I am trying to use fpdf to generate a pdf file of this information that follows a formatting guide. My question is this:

How can I tell python to read a string in a way that interprets each line and not simply as a list of characters?

My initial idea was to tell python to read this string line by line and assign values to each line. However that seems like it might be inefficient, Is there a better way to do this?

Thank you.

Body:
str.split('\n') will do the trick:

In [135]: text.split('\n')
Out[135]:
['"',
 '=========New Coffee Order===============',
 '=========Bean Information===============',
 'Type: Ethiopian',
 'Origin: Single',
 '',
 '=========Roaster/price==================',
 "Steve's Beans",
 '8.50/lb',
 '',
 'Everyday Espresso',
 '10.00/lb',
 '',
 'Critical Coffee ',
 '6.00/lb',
 '',
 '',
 '=========End Coffee Order==============',
 '"']

All you'll need to do is iterate over the returned list, line by line:

for line in text.split('\n'):
    ...

Comparing @Robᵩ's and my solutions:

In [137]: %timeit text.splitlines()
1000000 loops, best of 3: 1.8 µs per loop

In [138]: %timeit text.split('\n')
1000000 loops, best of 3: 1.31 µs per loop


来源: stackexchange

问:
Add Access-Control-Allow-Origin: * easily to JSON
On my web server I have a folder (say the link is: www.foo.com/json/).

Inside this link, I have a json file, like foo.json. I want to access this file from another website. I've tried to research "CORS" but it seems pretty complicated, and I don't use any backend in on my website foo.com. I've heard you can simply use php and put this in:

```<code><?php
header("Access-Control-Allow-Origin: *");
</code>```

How do I add this to that folder that has the .json so that when I do:

```<code>$.getJSON("http://foo.com/json/foo.json", function(json) {
    console.log(json
)});
</code>```

It won't throw the error. I want this to be simple to let any website do it, I just don't know how to connect it all.

答:
Don't access the JSON file directly, use a PHP page in the middle. So you call www.foo.com/json/, which will run the default PHP file in that folder (say index.php). Now this PHP page will set the CORS header like you mentioned:

```<code>header("Access-Control-Allow-Origin: *");
</code>```

and then read the JSON file and add it to the response along with the correct MIME type:

```<code>header("content-type: application/json");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
On my web server I have a folder (say the link is: www.foo.com/json/).

Inside this link, I have a json file, like foo.json. I want to access this file from another website. I've tried to research "CORS" but it seems pretty complicated, and I don't use any backend in on my website foo.com. I've heard you can simply use php and put this in:

<?php
header("Access-Control-Allow-Origin: *");

How do I add this to that folder that has the .json so that when I do:

$.getJSON("http://foo.com/json/foo.json", function(json) {
    console.log(json
)});

It won't throw the error. I want this to be simple to let any website do it, I just don't know how to connect it all.

Body:
Don't access the JSON file directly, use a PHP page in the middle. So you call www.foo.com/json/, which will run the default PHP file in that folder (say index.php). Now this PHP page will set the CORS header like you mentioned:

header("Access-Control-Allow-Origin: *");

and then read the JSON file and add it to the response along with the correct MIME type:

header("content-type: application/json");

ContentLicense: CC BY-SA 4.0


问:
Cannot hide the match messages in Angular password form

Hi, I got a problem I want to show the messages only when passwords match or not match but the messages appear all the time any suggestions? And I would like to not be able to click the button if the passwords are different!

```<code>@*<form name="form" ng-submit="vm.login()" role="form">*@
<form accept-charset="UTF-8" role="form" id="login-recordar" ng-submit="vm.login()">

    @*New password field!*@
    <div>
        <div class="form-group input-group" ng-class="{ 'has-error': form.password.$dirty && form.password.$error.required }">
            <span class="input-group-addon">
                <i class="glyphicon glyphicon-lock"></i><label for="password1">New Password</label>
            </span>
            <input class="form-control" placeholder="Password" name="password" type="password" data-toggle="popover" data-trigger="focus" data-content="Minimum 8 characters long and should contain at least one (small- and capital letter and number)." id="password" value="" required="" autofocus="" onkeypress="capLock(event)" ng-model="mAddEditView.User.Password" ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/" />
        </div>
        <span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
        <span id="divMayus" style="visibility:hidden">Caps Lock is on!</span>
    </div>

    @*Confirm Password field!*@
    <div>
        <div class="form-group input-group" ng-class="{ 'has-error': form.password1.$dirty && form.password1.$error.required }">
            <span class="input-group-addon">
                <i class="glyphicon glyphicon-lock"></i><label for="password1">Confirm Password</label>
            </span>
            <input class="form-control" placeholder="Password" name="password1" type="password" data-toggle="popover" data-trigger="focus" data-content="The password should match." id="password1" value="" required="" onkeypress="capLock(event)" ng-model="mAddEditView.User.Password" ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/" />

        </div>
        <span ng-show="form.password1.$dirty && form.password1.$error.required" class="help-block">Password is required</span>
        <span ng-show="mAddEditView.User.Password !== mAddEditView.User.Password1" class="help-block"><font style="color:red;">Password is not valid!</font></span>
        @* code for checking if password match *@
        <span ng-show="form.password1.$valid && mAddEditView.User.Password === mAddEditView.User.Password1"><font style="color:white;">Password Matched</font></span>

        <span id="divMayus" style="visibility:hidden">Caps Lock is on!</span>
    </div>

    <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block" value="Login" ng-disabled="form.$invalid || vm.dataLoading || errors.mail.isExists || mAddEditView.User.Password !== mAddEditView.User.Password1">
            Change Password
        </button>

    </div>
</code>```

答:
You can update your ng-show  condition for message to

```<code>ng-show="form.password1.$valid && form.password1.$dirty && form.password.$dirty && mAddEditView.User.Password === mAddEditView.User.Password1"
</code>```

So that it'll show only when user started editing both fields & user added valid password according to RegExp & then last condition to check if both are same.

*Required validation is necessary for making form invalid & avoiding user to submit it. So adding required attribute & for submit button form.$invalid will handle it itself

Body:
Hi, I got a problem I want to show the messages only when passwords match or not match but the messages appear all the time any suggestions? And I would like to not be able to click the button if the passwords are different!

@*<form name="form" ng-submit="vm.login()" role="form">*@
<form accept-charset="UTF-8" role="form" id="login-recordar" ng-submit="vm.login()">

    @*New password field!*@

                New Password

            <input class="form-control" placeholder="Password" name="password" type="password" data-toggle="popover" data-trigger="focus" data-content="Minimum 8 characters long and should contain at least one (small- and capital letter and number)." id="password" value="" required="" autofocus="" onkeypress="capLock(event)" ng-model="mAddEditView.User.Password" ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/" />

        Password is required
        Caps Lock is on!

    @*Confirm Password field!*@

                Confirm Password

            <input class="form-control" placeholder="Password" name="password1" type="password" data-toggle="popover" data-trigger="focus" data-content="The password should match." id="password1" value="" required="" onkeypress="capLock(event)" ng-model="mAddEditView.User.Password" ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/" />

        Password is required
        Password is not valid!
        @* code for checking if password match *@
        Password Matched

        Caps Lock is on!

        <button type="submit" class="btn btn-primary btn-block" value="Login" ng-disabled="form.$invalid || vm.dataLoading || errors.mail.isExists || mAddEditView.User.Password !== mAddEditView.User.Password1">
            Change Password
        </button>

Body:
You can update your ng-show  condition for message to

ng-show="form.password1.$valid && form.password1.$dirty && form.password.$dirty && mAddEditView.User.Password === mAddEditView.User.Password1"

So that it'll show only when user started editing both fields & user added valid password according to RegExp & then last condition to check if both are same.

*Required validation is necessary for making form invalid & avoiding user to submit it. So adding required attribute & for submit button form.$invalid will handle it itself


问:
Picasso Library - Out of Memory
I am using Picasso library latest version 2.4.0 in my app for downloading and caching images. There are roughly 25-30 images of size 300KB-400KB each. I think that this is no way something big or heavy.

Even though the app is running fine, I'm getting out of memory allocations in my logcat. Can anyone explain why is this happening?

Code for loading images in GridView adapter:

```<code>Picasso.with(mContext).load(getUrl()).placeholder(R.drawable.placeholder)
            .into(viewholder.image);
</code>```

Here is my Logcat output:

```<code>I/dalvikvm-heap(11142): Grow heap (frag case) to 53.860MB for 2720016-byte allocation
I/dalvikvm-heap(11142): Forcing collection of SoftReferences for 3265936-byte allocation
E/dalvikvm-heap(11142): Out of memory on a 3265936-byte allocation.
I/dalvikvm(11142): "Picasso-/images/posters/34.71.jpg" prio=5 tid=18 RUNNABLE
I/dalvikvm(11142):   | group="main" sCount=0 dsCount=0 obj=0x4283f248 self=0x60a47830
I/dalvikvm(11142):   | sysTid=11196 nice=10 sched=0/0 cgrp=apps/bg_non_interactive I/dalvikvm(11142):   | state=R schedstat=( 2070202497 1858185620 3947 ) utm=172 stm=35 core=3
I/dalvikvm(11142):   at android.graphics.Bitmap.nativeCreate(Native Method)
I/dalvikvm(11142):   at android.graphics.Bitmap.createBitmap(Bitmap.java:726)
I/dalvikvm(11142):   at android.graphics.Bitmap.createBitmap(Bitmap.java:703)
I/dalvikvm(11142):   at android.graphics.Bitmap.createBitmap(Bitmap.java:636)
I/dalvikvm(11142):   at com.squareup.picasso.BitmapHunter.transformResult(BitmapHunter.I/dalvikvm(11142):   at com.squareup.picasso.BitmapHunter.hunt(BitmapHunter.java:168)
I/dalvikvm(11142):   at com.squareup.picasso.BitmapHunter.run(BitmapHunter.java:111)
I/dalvikvm(11142):   at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:390I/dalvikvm(11142):   at java.util.concurrent.FutureTask.run(FutureTask.java:234)
I/dalvikvm(11142):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.I/dalvikvm(11142):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.I/dalvikvm(11142):   at java.lang.Thread.run(Thread.java:841)
I/dalvikvm(11142):   at com.squareup.picasso.Utils$PicassoThread.run(Utils.java:408)
I/dalvikvm-heap(11142): Forcing collection of SoftReferences for 3265936-byte allocation
E/dalvikvm-heap(11142): Out of memory on a 3265936-byte allocation.
I/dalvikvm(11142): "Picasso-/images/posters/34.71.jpg" prio=5 tid=17 RUNNABLE
I/dalvikvm(11142):   | group="main" sCount=0 dsCount=0 obj=0x42841b88 self=0x5ec91f90
I/dalvikvm(11142):   | sysTid=11183 nice=10 sched=0/0 cgrp=apps/bg_non_interactive I/dalvikvm(11142):   | state=R schedstat=( 2050467088 1713164574 3713 ) utm=172 stm=32 core=3
I/dalvikvm(11142):   at android.graphics.Bitmap.nativeCreate(Native Method)
I/dalvikvm(11142):   at android.graphics.Bitmap.createBitmap(Bitmap.java:726)
I/dalvikvm(11142):   at android.graphics.Bitmap.createBitmap(Bitmap.java:703)
I/dalvikvm(11142):   at android.graphics.Bitmap.createBitmap(Bitmap.java:636)
I/dalvikvm(11142):   at com.squareup.picasso.BitmapHunter.transformResult(BitmapHunter.I/dalvikvm(11142):   at com.squareup.picasso.BitmapHunter.hunt(BitmapHunter.java:168)
I/dalvikvm(11142):   at com.squareup.picasso.BitmapHunter.run(BitmapHunter.java:111)
I/dalvikvm(11142):   at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:390I/dalvikvm(11142):   at java.util.concurrent.FutureTask.run(FutureTask.java:234)
I/dalvikvm(11142):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.I/dalvikvm(11142):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.I/dalvikvm(11142):   at java.lang.Thread.run(Thread.java:841)
I/dalvikvm(11142):   at com.squareup.picasso.Utils$PicassoThread.run(Utils.java:408)
</code>```

答:
All the others answers sounds good when mentioning .fit().

I think it can be interesting to mention downside of .fit though:

fit() is measuring the dimensions of the target ImageView and internally uses resize() to reduce the image size to the dimensions of the ImageView. There are two things to know about fit(). First, calling fit() can delay the image request since Picasso will need to wait until the size of the ImageView can be measured. Second, you only can use fit() with an ImageView as the target (we'll look at other targets later).

The advantage is that the image is at the lowest possible resolution, without affecting its quality. A lower resolution means less data to be hold in the cache. This can significantly reduce the impact of images in the memory footprint of your app. In summary, if you prefer a lower memory impact over a little faster loading times, fit() is a great tool.

TLDR:

Can only be used with ImageView targets

May slow down loading

Source: https://futurestud.io/tutorials/picasso-image-resizing-scaling-and-fit

Title: Picasso Library - Out of Memory

Body:
I am using Picasso library latest version 2.4.0 in my app for downloading and caching images. There are roughly 25-30 images of size 300KB-400KB each. I think that this is no way something big or heavy.

Even though the app is running fine, I'm getting out of memory allocations in my logcat. Can anyone explain why is this happening?

Code for loading images in GridView adapter:

Picasso.with(mContext).load(getUrl()).placeholder(R.drawable.placeholder)
            .into(viewholder.image);

Here is my Logcat output:

I/dalvikvm-heap(11142): Grow heap (frag case) to 53.860MB for 2720016-byte allocation
I/dalvikvm-heap(11142): Forcing collection of SoftReferences for 3265936-byte allocation
E/dalvikvm-heap(11142): Out of memory on a 3265936-byte allocation.
I/dalvikvm(11142): "Picasso-/images/posters/34.71.jpg" prio=5 tid=18 RUNNABLE
I/dalvikvm(11142):   | group="main" sCount=0 dsCount=0 obj=0x4283f248 self=0x60a47830
I/dalvikvm(11142):   | sysTid=11196 nice=10 sched=0/0 cgrp=apps/bg_non_interactive I/dalvikvm(11142):   | state=R schedstat=( 2070202497 1858185620 3947 ) utm=172 stm=35 core=3
I/dalvikvm(11142):   at android.graphics.Bitmap.nativeCreate(Native Method)
I/dalvikvm(11142):   at android.graphics.Bitmap.createBitmap(Bitmap.java:726)
I/dalvikvm(11142):   at android.graphics.Bitmap.createBitmap(Bitmap.java:703)
I/dalvikvm(11142):   at android.graphics.Bitmap.createBitmap(Bitmap.java:636)
I/dalvikvm(11142):   at com.squareup.picasso.BitmapHunter.transformResult(BitmapHunter.I/dalvikvm(11142):   at com.squareup.picasso.BitmapHunter.hunt(BitmapHunter.java:168)
I/dalvikvm(11142):   at com.squareup.picasso.BitmapHunter.run(BitmapHunter.java:111)
I/dalvikvm(11142):   at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:390I/dalvikvm(11142):   at java.util.concurrent.FutureTask.run(FutureTask.java:234)
I/dalvikvm(11142):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.I/dalvikvm(11142):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.I/dalvikvm(11142):   at java.lang.Thread.run(Thread.java:841)
I/dalvikvm(11142):   at com.squareup.picasso.Utils$PicassoThread.run(Utils.java:408)
I/dalvikvm-heap(11142): Forcing collection of SoftReferences for 3265936-byte allocation
E/dalvikvm-heap(11142): Out of memory on a 3265936-byte allocation.
I/dalvikvm(11142): "Picasso-/images/posters/34.71.jpg" prio=5 tid=17 RUNNABLE
I/dalvikvm(11142):   | group="main" sCount=0 dsCount=0 obj=0x42841b88 self=0x5ec91f90
I/dalvikvm(11142):   | sysTid=11183 nice=10 sched=0/0 cgrp=apps/bg_non_interactive I/dalvikvm(11142):   | state=R schedstat=( 2050467088 1713164574 3713 ) utm=172 stm=32 core=3
I/dalvikvm(11142):   at android.graphics.Bitmap.nativeCreate(Native Method)
I/dalvikvm(11142):   at android.graphics.Bitmap.createBitmap(Bitmap.java:726)
I/dalvikvm(11142):   at android.graphics.Bitmap.createBitmap(Bitmap.java:703)
I/dalvikvm(11142):   at android.graphics.Bitmap.createBitmap(Bitmap.java:636)
I/dalvikvm(11142):   at com.squareup.picasso.BitmapHunter.transformResult(BitmapHunter.I/dalvikvm(11142):   at com.squareup.picasso.BitmapHunter.hunt(BitmapHunter.java:168)
I/dalvikvm(11142):   at com.squareup.picasso.BitmapHunter.run(BitmapHunter.java:111)
I/dalvikvm(11142):   at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:390I/dalvikvm(11142):   at java.util.concurrent.FutureTask.run(FutureTask.java:234)
I/dalvikvm(11142):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.I/dalvikvm(11142):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.I/dalvikvm(11142):   at java.lang.Thread.run(Thread.java:841)
I/dalvikvm(11142):   at com.squareup.picasso.Utils$PicassoThread.run(Utils.java:408)


答:
Assuming the lines are separated by UNIX line breaks, and the text is in a variable called text

```<code>lines = text.split("\n")
</code>```

will do the job. You can then iterate over the list lines and do what you need to do to each line.

Title: Reading a string line by line in python

Body:
Assuming the lines are separated by UNIX line breaks, and the text is in a variable called text

lines = text.split("\n")

will do the job. You can then iterate over the list lines and do what you need to do to each line.


问:
How do i get refs value from dynamically generated array in React
I got my data from firebase, looped through it and displayed it on the frontend. Now I am trying to get the refs value of the already displayed value when I click on it. For example, when I click on Dino, i should be able to see the value 'Dino' on my console tab of Chrome browser.

Here is a link to the picture of the array list displayed on react frontend

```<code><ul>
    <li onClick={this.handleSubmit}>
        {
            Object.keys(this.props.group).map(function(keyName, keyIndex) {
                return(
                    <div key={keyIndex}>{keyName}</div>
                )
            })
        }
    </li>
</ul>
</code>```

答:
You'll need to bind a click event to each div within the li. I would actually rewrite it like so:

```<code> <ul>
    {
        Object.keys(this.props.group).map( (keyName, keyIndex) => {
            return(
                <li key={keyIndex} onClick={this.handleSubmit.bind(this, keyName}>
                    {keyName}
                </li>
            )
        })
    }
</ul>
</code>```

Then your handleSubmit function will get the keyName as a param:

```<code>handleSubmit(keyName){
    // Do something...
}
</code>```

Body:
I got my data from firebase, looped through it and displayed it on the frontend. Now I am trying to get the refs value of the already displayed value when I click on it. For example, when I click on Dino, i should be able to see the value 'Dino' on my console tab of Chrome browser.

Here is a link to the picture of the array list displayed on react frontend

        {
            Object.keys(this.props.group).map(function(keyName, keyIndex) {
                return(

{keyName}

                )
            })
        }

Body:
You'll need to bind a click event to each div within the li. I would actually rewrite it like so:

 <ul>
    {
        Object.keys(this.props.group).map( (keyName, keyIndex) => {
            return(
                <li key={keyIndex} onClick={this.handleSubmit.bind(this, keyName}>
                    {keyName}
                </li>
            )
        })
    }
</ul>

Then your handleSubmit function will get the keyName as a param:

handleSubmit(keyName){
    // Do something...
}


问:
WPF - Why doesn't Microsoft supply a decent set of most-used controls ?
I've been playing with WPF for some months now, and I quite like it.
But one of the things I don't get is why MS doesn't put a little more effort in helping developers by supplying basic controls, and I need to get this off my chest :)

For example, I figure most applications somewhere will need to let you edit some properties - for configuration or whatever.
What would be the most used types in a proprety-grid editor ?

text

numbers (byte, float/double, int, etc)

colors

....etc.

So why isn't there even something as simple as a control to edit numbers ? Like a generic NumericUpDown control that allows you to type in numbers (no text, no pasting invalid input) or spin them up/down according to some given rules (decimal, floating point, min/maxvalue) ?
Why isn't there a generic colorpicker, so people get the same user-experience in every application ?
Why isn't there a standard implementation of a SearchTextBox, a BreadCrumb-control, or all these other standard control types users have gotten accustomed to the last 10 years ?

(..but at least they DID have the time to implement a generic splashscreen - because everyone knows that greatly increases user-productivity....)

The well-known ideal is always to give people the same user-experience over different applications. So even if some of those controls would be easy to make - it would be preferred to have one version over different applications.

I see people all over the internet trying to do the same stuff over and over again.
Okay, so MS started a WPF Toolkit project on Codeplex that tries to implement some controls, but only did so half-heartedly and is completely dead by now (last update of the roadmap dates back to Mar 21 2009).

The result of this is that a lot of people starting a WPF-project end up spending a lot of time on trying to figure out how to create some generic controls and get really frustrated.

Wasn't the mantra "Developers, developers, developers!" ..?

/Rant

答:
There are a lot of 3rd party vendors out there that provide powerful custom controls (editor, navigation, grids, menus, property grids, ...).

It's - in general - cheaper to buy from them than to rewrite your own (when it fits your need of course).

Historically, Microsoft has always encouraged a rich "component-based" eco-system around what they provider out-of-the-box features. This has been true from the beginning of component programming (VBX, OCX, ...) with Microsoft technology. This is arguable, but that's the strategy :-)

ContentLicense: CC BY-SA 2.5


问:
The Go Template ParseFiles func parsing multiple files
What would it happen if I pass two or more files to Go Template's ParseFiles func?

```<code>func (*Template) ParseFiles
</code>```

It helps says:

ParseFiles parses the named files and associates the resulting templates with t. If an error occurs, parsing stops and the returned template is nil; otherwise it is t. There must be at least one file. Since the templates created by ParseFiles are named by the base names of the argument files, t should usually have the name of one of the (base) names of the files. If it does not, depending on t's contents before calling ParseFiles, t.Execute may fail. In that case use t.ExecuteTemplate to execute a valid template.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

But I'm still not sure what would the differences be that affects the output, for

```<code>MyTempl.ParseFiles(tf1)
</code>```

vs.

```<code>MyTempl.ParseFiles(tf1, tf2)
</code>```

Will the content of tf2 be appended to that of tf1?

答:
First a little about the "template" concept:

A template.Template value is "the representation of a parsed template". But the wording here is a little "imperfect". A template.Template value may be (and usually is) a collection of multiple, associated templates. template.Template has an unexported field:

```<code>tmpl   map[string]*Template // Map from name to defined templates.
</code>```

This tmpl field holds all other associated templates, templates that are visible to the template, and which can be referred to by their names.

You can read more about this in this answer: Go template name

Back to the Template.ParseFiles() method. This method parses multiple templates from the files passed to it as parameters. The templates parsed form the files will be named after the file names (without folders, just the file name), and they will be added to the internal, associated templates map of the t template designated by the method receiver.

The parsed templates will not be appended. Multiple, separate template.Template values will be created for them, but they will be associated (so they can refer to each other, e.g. they can include each other).

Let's see an example. Let's assume we have these 2 template files:

a.html is:

```<code>I'm a.
</code>```

And b.html:

```<code>I'm b.
</code>```

And an example code:

```<code>t := template.New("a.html")
if _, err := t.ParseFiles("a.html", "b.html"); err != nil {
    panic(err)
}
if err := t.Execute(os.Stdout, nil); err != nil {
    panic(err)
}
</code>```

This example creates a new, empty template named a.html, then parses 2 files: a.html and b.html.

What will be the result? t will denote the a.html template, because we created it prior with that specific name. Running the code, the output will be:

```<code>I'm a.
</code>```

Now if we change the first line to:

```<code>t := template.New("x.html")
</code>```

And leave the rest unchanged, running it we see something similar:

```<code>panic: template: "x.html" is an incomplete or empty template
</code>```

The reason is that t denotes a template named x.html but it's empty, as we didn't parse anything "into" it, and the parsed files also didn't match the name x.html. So attempting to execute it results in an error.

Now if we try to execute one of its associated, named template:

```<code>if err := t.ExecuteTemplate(os.Stdout, "a.html", nil); err != nil {
    panic(err)
}
</code>```

It succeeds, and again gives:

```<code>I'm a.
</code>```

Body:
What would it happen if I pass two or more files to Go Template's ParseFiles func?

func (*Template) ParseFiles

It helps says:

ParseFiles parses the named files and associates the resulting templates with t. If an error occurs, parsing stops and the returned template is nil; otherwise it is t. There must be at least one file. Since the templates created by ParseFiles are named by the base names of the argument files, t should usually have the name of one of the (base) names of the files. If it does not, depending on t's contents before calling ParseFiles, t.Execute may fail. In that case use t.ExecuteTemplate to execute a valid template.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

But I'm still not sure what would the differences be that affects the output, for

MyTempl.ParseFiles(tf1)

vs.

MyTempl.ParseFiles(tf1, tf2)

Will the content of tf2 be appended to that of tf1?

Body:
First a little about the "template" concept:

A template.Template value is "the representation of a parsed template". But the wording here is a little "imperfect". A template.Template value may be (and usually is) a collection of multiple, associated templates. template.Template has an unexported field:

tmpl   map[string]*Template // Map from name to defined templates.

This tmpl field holds all other associated templates, templates that are visible to the template, and which can be referred to by their names.

You can read more about this in this answer: Go template name

Back to the Template.ParseFiles() method. This method parses multiple templates from the files passed to it as parameters. The templates parsed form the files will be named after the file names (without folders, just the file name), and they will be added to the internal, associated templates map of the t template designated by the method receiver.

The parsed templates will not be appended. Multiple, separate template.Template values will be created for them, but they will be associated (so they can refer to each other, e.g. they can include each other).

Let's see an example. Let's assume we have these 2 template files:

a.html is:

I'm a.

And b.html:

I'm b.

And an example code:

t := template.New("a.html")
if _, err := t.ParseFiles("a.html", "b.html"); err != nil {
    panic(err)
}
if err := t.Execute(os.Stdout, nil); err != nil {
    panic(err)
}

This example creates a new, empty template named a.html, then parses 2 files: a.html and b.html.

What will be the result? t will denote the a.html template, because we created it prior with that specific name. Running the code, the output will be:

I'm a.

Now if we change the first line to:

t := template.New("x.html")

And leave the rest unchanged, running it we see something similar:

panic: template: "x.html" is an incomplete or empty template

The reason is that t denotes a template named x.html but it's empty, as we didn't parse anything "into" it, and the parsed files also didn't match the name x.html. So attempting to execute it results in an error.

Now if we try to execute one of its associated, named template:

if err := t.ExecuteTemplate(os.Stdout, "a.html", nil); err != nil {
    panic(err)
}

It succeeds, and again gives:

I'm a.


问:
Algorithm to find counterfeit coin amongst n coins
So this is the classic problem of finding a counterfeit coin among a set of coins using only a weighing balance. For completeness, here is one example of such a problem:

A well-known example has nine (or fewer) items, say coins (or balls), that are identical in weight save for one, which in this example is lighter than the others—a counterfeit (an oddball). The difference is only perceptible by weighing them on scale—but only the coins themselves can be weighed. Is it possible to isolate the counterfeit coin with only two weighings?

We are dealing with the case where only one of the coins is counterfeit and we know how it is so (i.e. we know it is heavier/lighter).

My question is, is there a general efficient algorithm to solve the generalized version of this problem for N coins with one counterfeit. I have been thinking about it and so far I have that if N is of the form 3^k, then you can find the counterfeit in ⌈log_3_(N)⌉ by splitting them into groups of three recursively. Is this true for all N, not jus those of the from 3^k and if so, can we do better?

答:
I've used this code, however sometimes it is off by 1((:</p>

```<code>def how_many_measurements(n):
    import math
    if n<2:
        x = 0
    elif n >= 2 and n<=4:
        x = 1
    elif n>4 and n<12:
        x = 2
    else:
        x= math.ceil(math.log((2*n+1),3))
    return x
</code>```

Body:
I've used this code, however sometimes it is off by 1((:

def how_many_measurements(n):
    import math
    if n<2:
        x = 0
    elif n >= 2 and n<=4:
        x = 1
    elif n>4 and n<12:
        x = 2
    else:
        x= math.ceil(math.log((2*n+1),3))
    return x


问:
Control Width Of Div Elements Inside Jumbotron
I have some text inside a jumbotron that has a complex background image.  To make the text stand out, I added a background color to the containing div to make it more readable.  However, the div width is the same size as the columns.  Is there any way to set the width so that the div is the same width as the text?  I don't want extra space to either side of the centered text.</p>

```<code><div class="jumbotron">
    <div class="container">
        <div class="row">
            <div class="col-lg-10 col-lg-push-1 text-center" style="background-color: rgba(0,0,0,0.5); border-radius: 25px;">
                <h1>Some text, more text,<br>and more text</h1>
                <p><a href="" class="btn btn-primary btn-lg">Learn more <i class="fa fa-angle-double-right"></i></a></p>
            </div>
        </div>
    </div>
</div>
</code>```

答:
You can add .text-center to the parent .row, then remove the .col-* classes from the div with the background image and add display: inline-block

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Some text, more text,
and more text

Learn more

```

Body:
I have some text inside a jumbotron that has a complex background image.  To make the text stand out, I added a background color to the containing div to make it more readable.  However, the div width is the same size as the columns.  Is there any way to set the width so that the div is the same width as the text?  I don't want extra space to either side of the centered text.

Some text, more text,
and more text

Learn more

Body:
You can add .text-center to the parent .row, then remove the .col-* classes from the div with the background image and add display: inline-block

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="jumbotron">
  <div class="container">
    <div class="row text-center">
      <div style="background-color: rgba(0,0,0,0.5); border-radius: 25px; display: inline-block;">
        <h1>Some text, more text,<br>and more text</h1>
        <p><a href="" class="btn btn-primary btn-lg">Learn more <i class="fa fa-angle-double-right"></i></a></p>
      </div>
    </div>
  </div>
</div>


问:
List of installed gems?
Is there a Ruby method I can call to get the list of installed gems?

I  want to parse the output of gem list.

Is there a different way to do this?

答:
Here's a really nice one-liner to print all the Gems along with their version, homepage, and description:</p>

```<code>Gem::Specification.sort{|a,b| a.name <=> b.name}.map {|a| puts "#{a.name} (#{a.version})"; puts "-" * 50; puts a.homepage; puts a.description; puts "\n\n"};nil
</code>```

Title: List of installed gems?

Body:
Here's a really nice one-liner to print all the Gems along with their version, homepage, and description:

Gem::Specification.sort{|a,b| a.name <=> b.name}.map {|a| puts "#{a.name} (#{a.version})"; puts "-" * 50; puts a.homepage; puts a.description; puts "\n\n"};nil


问:
Resource not found for the segment user - Application Token
I am able to authenticate and get an application token to use the Microsoft Graph API.  I have set all of the delegated and admin permissions to have access to the users.  I have also used the graph explorer to verify what permissions I need:  https://developer.microsoft.com/en-us/graph/graph-explorer#

I verified my user GUID (my ID) through Azure AD as well as the Graph Explorer using their https://graph.microsoft.com/v1.0/me/ call while signed in.  Given I'm using the application token so I must specify a user (see below).

Here is what I'm passing

```<code>GET https://graph.microsoft.com/v1.0/user/{my GUID from Azure AD}
Authorization: bearer {myAccessToken}
Content-Type: application/json
</code>```

I suspect it's a syntax issue or a permissions issue.

答:
The URL should be:

```<code>https://graph.microsoft.com/v1.0/users/{GUID}
</code>```

And you instead of a Content-Type header, you should send a:

```<code>Accept: application/json
</code>```

Body:
I am able to authenticate and get an application token to use the Microsoft Graph API.  I have set all of the delegated and admin permissions to have access to the users.  I have also used the graph explorer to verify what permissions I need:  https://developer.microsoft.com/en-us/graph/graph-explorer#

I verified my user GUID (my ID) through Azure AD as well as the Graph Explorer using their https://graph.microsoft.com/v1.0/me/ call while signed in.  Given I'm using the application token so I must specify a user (see below).

Here is what I'm passing

GET https://graph.microsoft.com/v1.0/user/{my GUID from Azure AD}
Authorization: bearer {myAccessToken}
Content-Type: application/json

I suspect it's a syntax issue or a permissions issue.

Body:
The URL should be:

https://graph.microsoft.com/v1.0/users/{GUID}

And you instead of a Content-Type header, you should send a:

Accept: application/json


问:
React Native ART library documentation
Does anyone have a clue where to find the documentation? I saw a number of components using this library but strangely couldn't find the documentation?</p>

答:
React Native ART is a RN version of React ART, which is itself a React implementation of the ART library. And the latter has some docs:

http://sebmarkbage.github.io/art/

They're not exhaustive but should be enough to get you started.

Title: React Native ART library documentation


问:
TextBox Style - Binding to width of text
I have a style for a textBox. I have in it a change to the textBox control template with a additional rectangle. I want the width of the rectangle to be bound to the width of the text that has been typed.

Here is the current style

```<code><Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBoxBase}">
                <Border Name="Border"
                        Padding="2"
                        Background="{DynamicResource White#}">

                    <StackPanel VerticalAlignment="Center">
                        <ScrollViewer Margin="0" x:Name="PART_ContentHost" />
                        <Rectangle x:Name="Rect1" Width="{Binding ActualWidth, ElementName=PART_ContentHost}" Height="2" Fill="{TemplateBinding Foreground}" Opacity="0.8">
                            <Rectangle.LayoutTransform>
                                <ScaleTransform ScaleX="0" />
                            </Rectangle.LayoutTransform>
                        </Rectangle>
                    </StackPanel>
                </Border>
           </ControlTemplate>

        </Setter.Value>
    </Setter>
</code>```

This xaml bar stretches I want it just to be as wide as the text

What do I have to put in the setter for the control template and what does the binding have to be?

答:
So Ed's is better. I didn't even think about just handling focus and letting the ActualWidth of the ScrollViewer provide the value. I was thinking more immersed of actually measuring Text Element within the ScrollViewer as a logical child element which would have been much more involved in my opinion. Except his way works. However I also ran into an issue awhile back where by strict requirements only XAML was allowed with no codebehind to accomplish the same thing. Except it was a single instance form input and this quick hack was allowed.

I'd go with Ed's personally but submitted just as a quick alternative you can do something like this, and just piggy back the values to get ActualWidth off another element. It's not elegant, but it is simple...

PoC xaml;

```<code>Grid VerticalAlignment="Center" HorizontalAlignment="Center">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

            <TextBlock x:Name="theText"
                       Text="{Binding Text, ElementName=theBox, UpdateSourceTrigger=PropertyChanged}"
                       HorizontalAlignment="Left" Opacity="0"/>
            <TextBox   x:Name="theBox"
                       Height="30" Width="250" MaxLength="50"/>
            <Rectangle Grid.Row="1" Fill="Green"
                       Width="{Binding ActualWidth, ElementName=theText}"
                       HorizontalAlignment="Left" Height="25"/>
    </Grid>
</code>```

Cheers!

Body:
I have a style for a textBox. I have in it a change to the textBox control template with a additional rectangle. I want the width of the rectangle to be bound to the width of the text that has been typed.

Here is the current style

<Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBoxBase}">
                <Border Name="Border"
                        Padding="2"
                        Background="{DynamicResource White#}">

                    <StackPanel VerticalAlignment="Center">
                        <ScrollViewer Margin="0" x:Name="PART_ContentHost" />
                        <Rectangle x:Name="Rect1" Width="{Binding ActualWidth, ElementName=PART_ContentHost}" Height="2" Fill="{TemplateBinding Foreground}" Opacity="0.8">
                            <Rectangle.LayoutTransform>
                                <ScaleTransform ScaleX="0" />
                            </Rectangle.LayoutTransform>
                        </Rectangle>
                    </StackPanel>
                </Border>
           </ControlTemplate>

        </Setter.Value>
    </Setter>

This xaml bar stretches I want it just to be as wide as the text

What do I have to put in the setter for the control template and what does the binding have to be?

Body:
So Ed's is better. I didn't even think about just handling focus and letting the ActualWidth of the ScrollViewer provide the value. I was thinking more immersed of actually measuring Text Element within the ScrollViewer as a logical child element which would have been much more involved in my opinion. Except his way works. However I also ran into an issue awhile back where by strict requirements only XAML was allowed with no codebehind to accomplish the same thing. Except it was a single instance form input and this quick hack was allowed.

I'd go with Ed's personally but submitted just as a quick alternative you can do something like this, and just piggy back the values to get ActualWidth off another element. It's not elegant, but it is simple...

PoC xaml;

Grid VerticalAlignment="Center" HorizontalAlignment="Center">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

            <TextBlock x:Name="theText"
                       Text="{Binding Text, ElementName=theBox, UpdateSourceTrigger=PropertyChanged}"
                       HorizontalAlignment="Left" Opacity="0"/>
            <TextBox   x:Name="theBox"
                       Height="30" Width="250" MaxLength="50"/>
            <Rectangle Grid.Row="1" Fill="Green"
                       Width="{Binding ActualWidth, ElementName=theText}"
                       HorizontalAlignment="Left" Height="25"/>
    </Grid>

Cheers!


问:
Excel VBA Regex Function That Returns Multiple Matches Into A Single Cell
I need help getting my Excel function to work. The goal is to run an in-cell function that extracts all pattern matches of a regex function from the input of another cell into one cell, not an array of cells.

I have tried this using an array which returns two matches in the function dialogue box preview but only outputs the first match in the cell. I have also tried using a collection but had no luck with that.

Here is my current code and a sample of text that would be used as the function's string input:

```<code>Function RegexMatches(strInput As String) As Variant

Dim rMatch As Match
Dim arrayMatches
Dim i As Long

arrayMatches = Array()

With New RegExp
    .Global = True
    .MultiLine = True
    .IgnoreCase = True
    .Pattern = "(Code)[\s][\d]{2,4}"
        For Each rMatch In .Execute(strInput)
        ReDim Preserve arrayMatches(i)
        arrayMatches(i) = rMatch.Value
        i = i + 1
    Next
End With

    RegexMatches = arrayMatches
End Function
</code>```

Sample strInput from an Excel cell:

Code 123 some random text

goes here and continues to the next line

Code 4567 followed by more text

including new lines not just wrapped text

The desired output from this function would be both (2) matched values from the regex function into a single cell (e.g. "Code 123 Code 4567").

Any help is greatly appreciated!

答:
Looks like you missed off the end of your function (as per Mat's Mug's comment)? Try this (which is as per Wiktor's comment).

Edit: amended in light of Mat's Mug's suggestion.

```<code>Function RegexMatches(strInput As String) As String

Dim rMatch As Object
Dim s As String
Dim arrayMatches()
Dim i As Long

With New RegExp
    .Global = True
    .MultiLine = True
    .IgnoreCase = True
    .Pattern = "(Code)[\s][\d]{2,4}"
    If .test(strInput) Then
        For Each rMatch In .Execute(strInput)
            ReDim Preserve arrayMatches(i)
            arrayMatches(i) = rMatch.Value
            i = i + 1
            's = s & " " & rMatch
        Next
    End If
End With

RegexMatches = Join(arrayMatches, " ")

End Function
</code>```

Body:
I need help getting my Excel function to work. The goal is to run an in-cell function that extracts all pattern matches of a regex function from the input of another cell into one cell, not an array of cells.

I have tried this using an array which returns two matches in the function dialogue box preview but only outputs the first match in the cell. I have also tried using a collection but had no luck with that.

Here is my current code and a sample of text that would be used as the function's string input:

Function RegexMatches(strInput As String) As Variant

Dim rMatch As Match
Dim arrayMatches
Dim i As Long

arrayMatches = Array()

With New RegExp
    .Global = True
    .MultiLine = True
    .IgnoreCase = True
    .Pattern = "(Code)[\s][\d]{2,4}"
        For Each rMatch In .Execute(strInput)
        ReDim Preserve arrayMatches(i)
        arrayMatches(i) = rMatch.Value
        i = i + 1
    Next
End With

    RegexMatches = arrayMatches
End Function

Sample strInput from an Excel cell:

Code 123 some random text

goes here and continues to the next line

Code 4567 followed by more text

including new lines not just wrapped text

The desired output from this function would be both (2) matched values from the regex function into a single cell (e.g. "Code 123 Code 4567").

Any help is greatly appreciated!

Body:
Looks like you missed off the end of your function (as per Mat's Mug's comment)? Try this (which is as per Wiktor's comment).

Edit: amended in light of Mat's Mug's suggestion.

Function RegexMatches(strInput As String) As String

Dim rMatch As Object
Dim s As String
Dim arrayMatches()
Dim i As Long

With New RegExp
    .Global = True
    .MultiLine = True
    .IgnoreCase = True
    .Pattern = "(Code)[\s][\d]{2,4}"
    If .test(strInput) Then
        For Each rMatch In .Execute(strInput)
            ReDim Preserve arrayMatches(i)
            arrayMatches(i) = rMatch.Value
            i = i + 1
            's = s & " " & rMatch
        Next
    End If
End With

RegexMatches = Join(arrayMatches, " ")

End Function


问:
Executing elm-test throws runtime exception: Cannot read property 'href' of undefined
The following test results in a runtime exception:

```<code>test "search yields profile" <|
\_ ->
    let
        -- Setup
        location =
            Navigation.Location "" "" "" "" "" "" "" "" "" "" ""

        ( model, _ ) =
            Home.init location

        -- Test
        ( newState, _ ) =
            model |> Home.update (Search "Scott")

        -- Verify
        ( onlyOne, isContentProvider1 ) =
            ( (newState.contentProviders |> List.length) == 1
            , newState.contentProviders |> List.member contentProvider1
            )
    in
        Expect.equal (onlyOne && isContentProvider1) True
</code>```

TypeError: Cannot read property 'href' of undefined
    at Object.getLocation (eval at <anonymous> (my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:37),
<anonymous>:1392 6:17)
    at Function.eval (eval at <anonymous> (my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:37),
<anonymous>:14127:43)
    at A2 (eval at <anonymous> (my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:37),
<anonymous>:92:11)
    at eval (eval at <anonymous> (my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:37),
<anonymous>:21270:31)
    at eval (eval at <anonymous> (my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:37),
<anonymous>:22757:4)
    at my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:32
    at Object.evalElmCode (my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:76)
    at my_path\AppData\Roaming\npm\node_modules\elm-test\bin\elm-test:196:14
    at my_path\AppData\Roaming\npm\node_modules\elm-test\node_modules\graceful-fs\graceful-fs.js:78:16
    at tryToString (fs.js:456:3)
```

My hunch is that the Navigaton.Location is behind the exception. However, I have no clue how to resolve the issue.

The source code can be found on GitHub.

答:
I don't know if you've found an answer to this on Elm Slack, but I've spent some time looking into this and have found the cause of the problem.

In short, the problem is including your call to Navigation.program in an Elm file that gets run using elm-test.  In your case, Navigation.program is in Home.elm.  Move it to a different module (or temporarily comment it out) and your tests should run.

In more detail, the native code behind Navigation.program gets document.location and passes that into your init function.  However, when running elm-test, you don't have a document object as there isn't a browser.  elm-test will make up a skeletal document object instead, but this object has no location property and hence an exception is thrown attempting to get location.href.

There is some guidance to this effect in the elm-test package documentation (point 1 under 'Application-specific techniques'):

Avoid importing your Main module. Most of your code belongs in other modules, so import those instead.

Alternatively, document.location has now been polyfilled in elm-test version 0.18.9, so upgrading to that version will also fix this problem.

Body:
The following test results in a runtime exception:

test "search yields profile" <|
\_ ->
    let
        -- Setup
        location =
            Navigation.Location "" "" "" "" "" "" "" "" "" "" ""

        ( model, _ ) =
            Home.init location

        -- Test
        ( newState, _ ) =
            model |> Home.update (Search "Scott")

        -- Verify
        ( onlyOne, isContentProvider1 ) =
            ( (newState.contentProviders |> List.length) == 1
            , newState.contentProviders |> List.member contentProvider1
            )
    in
        Expect.equal (onlyOne && isContentProvider1) True

TypeError: Cannot read property 'href' of undefined
    at Object.getLocation (eval at <anonymous> (my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:37),
<anonymous>:1392 6:17)
    at Function.eval (eval at <anonymous> (my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:37),
<anonymous>:14127:43)
    at A2 (eval at <anonymous> (my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:37),
<anonymous>:92:11)
    at eval (eval at <anonymous> (my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:37),
<anonymous>:21270:31)
    at eval (eval at <anonymous> (my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:37),
<anonymous>:22757:4)
    at my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:32
    at Object.evalElmCode (my_path\AppData\Roaming\npm\node_modules\elm-test\lib\runner.js:84:76)
    at my_path\AppData\Roaming\npm\node_modules\elm-test\bin\elm-test:196:14
    at my_path\AppData\Roaming\npm\node_modules\elm-test\node_modules\graceful-fs\graceful-fs.js:78:16
    at tryToString (fs.js:456:3)

My hunch is that the Navigaton.Location is behind the exception. However, I have no clue how to resolve the issue.

The source code can be found on GitHub.


问:
SQL Count grouped rows for Accordion Panel
I have a blog table with two rows:
The only columns that matter for this are:

```<code>if_blog   data_blog    titulo
1         2017/07/07   title 1
2         2017/07/07   title 2
</code>```

I've created a menu thats ordered by date, and when you click on the date, it drops down the related posts.

The problem is that my query only shows 1 title (probably because of the GROUP BY data_blog.

The query I'm using is:

```<code>$datasb = $db->query("SELECT * FROM blog GROUP BY data_blog");
$datasb->execute();
while($rows_datas = $datasb->fetch(PDO::FETCH_ASSOC)){
  echo '
       <div class="panel-heading">
          <h4 class="panel-title">
          <a data-toggle="collapse" data-parent="#accordion" href="#'.$rows_datas['id_blog'].'">'.$rows_datas['data_blog'].'</a>
          </h4>
       </div>
       <div id="'.$rows_datas['id_blog'].'" class="panel-collapse collapse">
          <div class="panel-body">'.$rows_datas['titulo'].'</div>
       </div>
        ';
}
</code>```

This gives me the correct result of a link 2017/0707, but only one submenu with title1.

How can I get the total rows of the given date?

答:
Solved it, but I don't know if this is the best way:</p>

```<code>$datasb = $db->query("SELECT * FROM blog GROUP BY data_blog");
$datasb->execute();
   while($rows_datas = $datasb->fetch(PDO::FETCH_ASSOC)){
       echo '
           <div class="panel-heading">
             <h4 class="panel-title">
             <a data-toggle="collapse" data-parent="#accordion" href="#'.$rows_datas['id_blog'].'"> '.$rows_datas['data_blog'].'</a>
             </h4>
           </div>
           <div id="'.$rows_datas['id_blog'].'" class="panel-collapse collapse">
       ';
          $posts = $db->prepare("SELECT * FROM blog WHERE data_blog = ?");
          $posts->bindValue(1, $rows_datas['data_blog']);
          $posts->execute();
            while($rows_posts = $posts->fetch(PDO::FETCH_ASSOC)){
              echo '
                    <div class="panel-body painel">
                       <a href="">'.$rows_posts['titulo'].'</a>
                    </div>
              ';
            }
      echo '</div>';
      }
</code>```

Body:
I have a blog table with two rows:
The only columns that matter for this are:

if_blog   data_blog    titulo
1         2017/07/07   title 1
2         2017/07/07   title 2

I've created a menu thats ordered by date, and when you click on the date, it drops down the related posts.

The problem is that my query only shows 1 title (probably because of the GROUP BY data_blog.

The query I'm using is:

$datasb = $db->query("SELECT * FROM blog GROUP BY data_blog");
$datasb->execute();
while($rows_datas = $datasb->fetch(PDO::FETCH_ASSOC)){
  echo '

          '.$rows_datas['data_blog'].'

'.$rows_datas['titulo'].'

        ';
}

This gives me the correct result of a link 2017/0707, but only one submenu with title1.

How can I get the total rows of the given date?

Body:
Solved it, but I don't know if this is the best way:

$datasb = $db->query("SELECT * FROM blog GROUP BY data_blog");
$datasb->execute();
   while($rows_datas = $datasb->fetch(PDO::FETCH_ASSOC)){
       echo '
           <div class="panel-heading">
             <h4 class="panel-title">
             <a data-toggle="collapse" data-parent="#accordion" href="#'.$rows_datas['id_blog'].'"> '.$rows_datas['data_blog'].'</a>
             </h4>
           </div>
           <div id="'.$rows_datas['id_blog'].'" class="panel-collapse collapse">
       ';
          $posts = $db->prepare("SELECT * FROM blog WHERE data_blog = ?");
          $posts->bindValue(1, $rows_datas['data_blog']);
          $posts->execute();
            while($rows_posts = $posts->fetch(PDO::FETCH_ASSOC)){
              echo '
                    <div class="panel-body painel">
                       <a href="">'.$rows_posts['titulo'].'</a>
                    </div>
              ';
            }
      echo '</div>';
      }


答:
str.splitlines() converts a single multi-line string into a list of single-line strings.

Quoting the documentation:

Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines.

```<code>lines = text.splitlines()
</code>```

Title: Reading a string line by line in python

Body:
I have the following string that is generated using tkinter and then read using textEntry.get():

"
=========New Coffee Order===============
=========Bean Information===============
Type: Ethiopian
Origin: Single

=========Roaster/price==================
Steve's Beans
8.50/lb

Everyday Espresso
10.00/lb

Critical Coffee
6.00/lb

=========End Coffee Order==============
"

I am trying to use fpdf to generate a pdf file of this information that follows a formatting guide. My question is this:

How can I tell python to read a string in a way that interprets each line and not simply as a list of characters?

My initial idea was to tell python to read this string line by line and assign values to each line. However that seems like it might be inefficient, Is there a better way to do this?

Thank you.

Body:
str.splitlines() converts a single multi-line string into a list of single-line strings.

Quoting the documentation:

Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines.

lines = text.splitlines()


问:
ipad tabbar rotation
please help with this noob questions but really making me go crazy>

if I create a project from scratch (using windows based app) for the ipad,
and add a tabbar , with firstviewController, and secondviewController, it works fine,
starts in landscape mode,
but in info.plist I set it to Landscape(left home button),
but really in simulator starts with the button on the right side!

in the FirstViewController.m

(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
interfaceOrientation == UIInterfaceOrientationLandscapeRight)
return YES;
else {
return NO;  }}

so it starts in landscape, and rotates as the simulator rotates,

but if I create a template app for iphone tabbar,
set the info.plist
Initial interface orientation> Landscape (left home button)

and add the code above, IT DOESNT WORK!!!
simulator starts with button at left but tab bar on the side,

same problem that I had with an app that Im porting from iphone to ipad, (landscape intended)
I get to the landscape start mode, but the tab bar remains on the side!

also the only way to make the old ported app to show the simulator on the side was with
UIInterfaceOrientation UIIntefaceOrientationLandscapeLeft (didnt work with Initial interface orientation), does not let me choose the value for the key, but it shows the simulator on landscape,,

so,,
what can I do please to show the tab bar on landscape mode???
the tabbar from scratch was made to see if the code will work , but it didnt??
why does it work in the tab bar made from windows app and not tab bar app?
I just want the tab bar to show in landscape ahhh,

thanks

答: in the info.plist set Supported Interface Orientations</p>

Title: ipad tabbar rotation


问:
sequelize force mark migration done
I re-created my database on one of my dev environment and now when I run the migration via sequelize db:migrate, it tries to run the migrations from the first.

I don't want to re-sync/re-create the database since running migrations on the dev environment ensures that the migrations are correctly written.

Is there a way to force-mark some migrations as 'done'?

答:
Sequelize-cli stores the migration data on a table called SequelizeMeta.

You can copy the migration filename from your existing DB and insert into the above mentioned table in new environment's DB.
All the migrations recorded would be considered as they have already ran.

Though this would stop selected migrations from running, it's not the best approach to be taken.

This metadata could also be stored in a json, though I am not very aware of the structure for it.

You can dig through the docs here

Title: sequelize force mark migration done


问:
Excel 2013 VBA multiple email addresses to Outlook
I am coding in Excel 2013. I've got a table of client data that will increase and decrease in number over time depending my active veteran caseload:

Column A - Last Name

Column B - First Name

Column C - Email Address

Column D - etc...

I need the code to reference column C and place all the emails therein in the BCC of a single Outlook email. The code I have created (through my study) allows for only hard-coded email addresses to the TO, CC or BCC fields of Outlook--with a semicolon between multiple entries.  My issue is that the number of email addresses will vary depending on the number of records in the spreadsheet so hard-coding them is useless. The code below has all the functionality I require with the exception of the email problem.

```<code>Sub SendBasicEmail()
Dim olApp As Outlook.Application
Dim olEmail As Outlook.MailItem
Set olApp = New Outlook.Application
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
    .BodyFormat = olFormatHTML
    .Display
    .HTMLBody = "<h3>Testing</h3><br>" & "<br>" & .HTMLBody
    .Attachments.Add "xxx/test.pdf"
    .To = ""
    .BCC = ""
    .Subject = "Test Message"
    '.Send
End With
End Sub
</code>```

答:
The code will loop through the contents of sheet 1 (just change to sheet("whateveryoucalledyoursheet")) and keep the cell row. </p>

```<code>Sub SendBasicEmail()
dim ws as worksheet, y
Dim olApp As Outlook.Application
Dim olEmail As Outlook.MailItem
set ws = sheets(1)
for each y in ws.range("A1:A" & ws.range("A1").SpecialCells(xlCellTypeLastCell).row)

Set olApp = New Outlook.Application
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
    .BodyFormat = olFormatHTML
    .Display
    .HTMLBody = "<h3>Testing</h3><br>" & "<br>" & .HTMLBody
    .Attachments.Add "xxx/test.pdf"
    .To = ws.range("A" & y.row)
    .BCC = ws.range("C" & y.row)
    .Subject = "Test Message"
    ' use display to check the email out before you send
    .display
    '.Send
End With
next y

end sub
</code>```

Body:
I am coding in Excel 2013. I've got a table of client data that will increase and decrease in number over time depending my active veteran caseload:

Column A - Last Name

Column B - First Name

Column C - Email Address

Column D - etc...

I need the code to reference column C and place all the emails therein in the BCC of a single Outlook email. The code I have created (through my study) allows for only hard-coded email addresses to the TO, CC or BCC fields of Outlook--with a semicolon between multiple entries.  My issue is that the number of email addresses will vary depending on the number of records in the spreadsheet so hard-coding them is useless. The code below has all the functionality I require with the exception of the email problem.

Sub SendBasicEmail()
Dim olApp As Outlook.Application
Dim olEmail As Outlook.MailItem
Set olApp = New Outlook.Application
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
    .BodyFormat = olFormatHTML
    .Display
    .HTMLBody = "
Testing

" & "
" & .HTMLBody
    .Attachments.Add "xxx/test.pdf"
    .To = ""
    .BCC = ""
    .Subject = "Test Message"
    '.Send
End With
End Sub

Body:
The code will loop through the contents of sheet 1 (just change to sheet("whateveryoucalledyoursheet")) and keep the cell row.

Sub SendBasicEmail()
dim ws as worksheet, y
Dim olApp As Outlook.Application
Dim olEmail As Outlook.MailItem
set ws = sheets(1)
for each y in ws.range("A1:A" & ws.range("A1").SpecialCells(xlCellTypeLastCell).row)

Set olApp = New Outlook.Application
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
    .BodyFormat = olFormatHTML
    .Display
    .HTMLBody = "<h3>Testing</h3><br>" & "<br>" & .HTMLBody
    .Attachments.Add "xxx/test.pdf"
    .To = ws.range("A" & y.row)
    .BCC = ws.range("C" & y.row)
    .Subject = "Test Message"
    ' use display to check the email out before you send
    .display
    '.Send
End With
next y

end sub


问:
How to display both id and name while using an aggregate function in SQL SERVER
I am making a scorecard which needs to call the id, name and the total income earned by players in a game. Each round is stored by the user's id and the money earned by the user in that round.The userid and gamer name is stored in a separate table called'USER_MASTER'. There are multiple rounds in a game. At the end, i am supposed to show the scorecard where each person's id, name and sum of money earned is to be shown. With what i try, i am only able to bring id and sum of score in a single select statement using group by. I am unable to call both id and name as it throws up an error

'TESTDB.dbo.USER_MASTER.GAMER_NAME' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Is there a way to sum up and show both id and name in the same select statement?
The query i used is:

```<code>SELECT x.GAMER_CODE as "USER_ID", y.GAMER_NAME as "USERNAME",
sum(x.Round_Score) as TOTAL_SCORE
FROM [TESTDB].[dbo].[Game_Details] x
INNER JOIN TESTDB.dbo.USER_MASTER y
on x.GAMER_CODE=y.GAMER_CODE
Group By x.GAMER_CODE;
</code>```

EDIT: I am using SQL SERVER 2012.

答:
Since you group by id, you should safely be able to just add the name to the group by too.  Does that work for you?</p>

```<code>SELECT x.GAMER_CODE as "USER_ID", y.GAMER_NAME as "USERNAME",
sum(x.Round_Score) as TOTAL_SCORE
FROM [TESTDB].[dbo].[Game_Details] x
INNER JOIN TESTDB.dbo.USER_MASTER y
   on x.GAMER_CODE=y.GAMER_CODE
Group By x.GAMER_CODE, y.GAMER_NAME;
</code>```

Body:
I am making a scorecard which needs to call the id, name and the total income earned by players in a game. Each round is stored by the user's id and the money earned by the user in that round.The userid and gamer name is stored in a separate table called'USER_MASTER'. There are multiple rounds in a game. At the end, i am supposed to show the scorecard where each person's id, name and sum of money earned is to be shown. With what i try, i am only able to bring id and sum of score in a single select statement using group by. I am unable to call both id and name as it throws up an error

'TESTDB.dbo.USER_MASTER.GAMER_NAME' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Is there a way to sum up and show both id and name in the same select statement?
The query i used is:

SELECT x.GAMER_CODE as "USER_ID", y.GAMER_NAME as "USERNAME",
sum(x.Round_Score) as TOTAL_SCORE
FROM [TESTDB].[dbo].[Game_Details] x
INNER JOIN TESTDB.dbo.USER_MASTER y
on x.GAMER_CODE=y.GAMER_CODE
Group By x.GAMER_CODE;

EDIT: I am using SQL SERVER 2012.

Body:
Since you group by id, you should safely be able to just add the name to the group by too.  Does that work for you?

SELECT x.GAMER_CODE as "USER_ID", y.GAMER_NAME as "USERNAME",
sum(x.Round_Score) as TOTAL_SCORE
FROM [TESTDB].[dbo].[Game_Details] x
INNER JOIN TESTDB.dbo.USER_MASTER y
   on x.GAMER_CODE=y.GAMER_CODE
Group By x.GAMER_CODE, y.GAMER_NAME;


问:
Android | How to use IsolatedProcess
As far as i understand, an IsolatedProcess is here to run untrusted code.

But if the IsolatedProcess is basicly a process without any permissions, how can one send the untrusted code (lets say a class) to the IsolatedProcess?

I mean the IsolatedProcess have no access to the files in the device , to the internet, or anything else.

So what is the way to send the untrusted code to the IsolatedProcess?

I am trying to pass Constructors to the IsolatedProcess so he can start this untrusted classes safetly, but all the communication between processes must be with Serializable objects, and a Constructor is not a Serializable object.

答:
You're misunderstanding the purpose of isolatedProcess. It doesn't provide APIs to do what you want because it isn't how it's intended to be used and using it like that wouldn't be a good security practice. It's designed to provide a layer of security that an attacker needs to bypass once they've gained remote code execution via an exploit. You simply shouldn't run untrusted Java code because Android isn't designed to do it. It will still have access to native APIs including the kernel's system calls, etc. within an isolatedProcess. isolatedProcess drops nearly all privileges (gets a unique UID / GID and runs in the isolated_app SELinux domain) but it's not a very good sandbox alone. If you're determined to do it, then doing it within isolatedProcess is better than outside it, but you would be rolling your own code for it.

The main user of isolatedProcess is Chrome. Each site instance is rendered by a separate isolatedProcess service. It doesn't run untrusted Java or native code. An attacker needs a remote code execution exploit to gain control over the isolatedProcess. Chrome also doesn't only rely on isolatedProcess for the second layer of defence. It uses a strict seccomp-bpf filter to greatly reduce kernel attack surface.

Title: Android | How to use IsolatedProcess


问:
Creating my own SAP dashboard/reporting tool for mobile
Is it possible to create my own mobile dashboard, reporting tool for SAP? I understand the standard components to be used for this purpose are:

Business Objects Enterprise Server XI - this provides reporting functionalities for SAP

Business Objects Mobile Server - this connects to Enterprise Server and optimizes reports stored there for mobile devices

Mobile Web Browser or Mobile Business Objects Report Client - for viewing the reports

I don't intend to purchase the components mentioned above. I only want to know if it's feasible to build my own solution. I am familiar with BAPI's to retrieve data from SAP. What is the proper approach to build an SAP reporting tool?

Thank you!

答:
This might not be the answer you'd expect, but how about i-net Clear Reports (used to be called i-net Crystal-Clear)? Since you know the data backend, you can easily attach the report server to it, create reports with the (free!) report designer provided (which is somewhat like Crystal Reports) and, well, run them.

You can even use your existing Crystal Reports templates, since they are supported by i-net Clear Reports.

Now using the report repository you could even store the reports in a convenient way on the server and - here comes what I think you want most - access them from your mobile device.

There are three ways to do that: use the iPhone app, use the Android app or access the remote interface from e.g. your tablet device. From there you can run whatever report you have in the repository. In your case, with a dashboard: encapsulate all the reports you'd like to have in one report file (using subreports) and there you are.

Disclosure: Yep, I work for the company who made all this ;)

P.S. we're working on even better ways to realize dashboards, so stay tuned.


问:
.NET Core serving HTML file outside wwwroot can't load JS files
I am experimenting with different ways to secure an Angular CLI app with .NET Core Authorization.

To make it as secure as possible, I would like to keep all of the Angular CLI output files from being publicly available and keep them in the default "dist" folder preconfigured by the CLI.

I can load the index.html from an authorized controller by returning a PhysicalFileResult...

```<code>public IActionResult Index()
{
    return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(), "dist", "index.html"),"text/HTML");
}
</code>```

But I get 404s on all of the bundle.js files when the page loads.

Is it possible to serve the app this way without involving the static file middleware or making the files publicly available (preferably without having to manually change the src for each bundled js file in index.html)?

答:
Just place your authorization middleware before the static one. </p>

<pre class="lang-cs prettyprint-override"><code>// has to be first so user gets authenticated before the static middleware is called
app.UseIdentity();

app.Use(async (context, next) =>
{
    // for pathes which begin with "app" check if user is logged in
    if(context.Request.Path.StartsWith("app") && httpContext.User==null)
    {
        // return "Unauthorized"
        context.Response.StatusCode = 401;
        return;
    }

    // If user is logged in, call next middleware
    await next.Invoke();
});

app.UseStaticFiles();
</code>```

Body:
I am experimenting with different ways to secure an Angular CLI app with .NET Core Authorization.

To make it as secure as possible, I would like to keep all of the Angular CLI output files from being publicly available and keep them in the default "dist" folder preconfigured by the CLI.

I can load the index.html from an authorized controller by returning a PhysicalFileResult...

public IActionResult Index()
{
    return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(), "dist", "index.html"),"text/HTML");
}

But I get 404s on all of the bundle.js files when the page loads.

Is it possible to serve the app this way without involving the static file middleware or making the files publicly available (preferably without having to manually change the src for each bundled js file in index.html)?

Body:
Just place your authorization middleware before the static one.

// has to be first so user gets authenticated before the static middleware is called
app.UseIdentity();

app.Use(async (context, next) =>
{
    // for pathes which begin with "app" check if user is logged in
    if(context.Request.Path.StartsWith("app") && httpContext.User==null)
    {
        // return "Unauthorized"
        context.Response.StatusCode = 401;
        return;
    }

    // If user is logged in, call next middleware
    await next.Invoke();
});

app.UseStaticFiles();


问:
How can I tell react router v4 where to load the component?
This is the thing that confuses me about react router 4. I currently have the routes setup in the main parent component index.jsx. The navigation bar is in it's own component NavBar.jsx.

I want it so that when you click a link in NavBar.jsx, it loads the component into Body.jsx. Currently It loads a component across the entire screen replacing everything.

I believe with React Router 3 you were supposed to do something with this.props.children but if you guys and gals can shed some light on this for me, I'd greatly appreciate it. Thank you.

Here's the top most component code:

ReactDOM.render(
  <Router>

      <Route path="/" component={Index} />

  </Router>

, document.getElementById('app'));```

My components go from Index > Body > TabArea
The navbar is in Index > Banner > HotelTop

Tab Area is the location I want to render the component that HotelTop's navbar chooses.

答:
I believe there is no way to specify where to render the route component with React Router 4. It is always rendered in-place. So you component will always be a child of the Route which has rendered it.

But you can have many Router setups in the app — for example one in the Body.jsx and another one in a some Sidebar.jsx — thus you can achieve the result you need.

Body:
This is the thing that confuses me about react router 4. I currently have the routes setup in the main parent component index.jsx. The navigation bar is in it's own component NavBar.jsx.

I want it so that when you click a link in NavBar.jsx, it loads the component into Body.jsx. Currently It loads a component across the entire screen replacing everything.

I believe with React Router 3 you were supposed to do something with this.props.children but if you guys and gals can shed some light on this for me, I'd greatly appreciate it. Thank you.

Here's the top most component code:

ReactDOM.render(
  <Router>

      <Route path="/" component={Index} />

  </Router>

, document.getElementById('app'));

My components go from Index > Body > TabArea
The navbar is in Index > Banner > HotelTop

Tab Area is the location I want to render the component that HotelTop's navbar chooses.


问:
Java: Maven project: Distinct test automation architecture
Hello stackoverflowers!

I have a question to test automation (Selenium) specialists with several years experience:
What is the best/distinct test automation architecture/structure of files in Java (Maven) project? Example structures are provided below.

UI view of a system:

3 pages: home, registration, accounts.

1.1.1. "Home" page has search bar with "First name" field and "Search" button.

1.1.2. "Accounts" page has the same type of search bar as "Home" page has, but with "First name", "Last name" fields and "Search" button.

1.2.1. "Registration" page has "button1" to open "modal window1", which has 2 radio buttons.

1.2.2. "Accounts" page has "button2" to open "modal window2", which has the same 2 radio buttons as "modal window1" has and 1 "Code" field.

Structures:

1.

System

home

home Page Objects

"First name" field

"Search" button

registration

registration Page Objects

"button1"

radio button 1

radio button 2

accounts

accounts Page Objects

"First name" field

"Search" button

"Last name" field

"button2"

radio button 1

radio button 2

"Code" field

2.

System

Forms

Forms Page Objects

"button1"

"button2"

Search bars

Search bars Page Objects

"First name" field

"Last name" field

"Search" button

Modal windows

Modal windows Page Objects

radio button 1

radio button 2

"Code" field

Which of these 2 architectures/structures is the better/more distinct one?

Thanks in advance for a suggestion!

答:
You can use NoraUi framework (Gherkin > Cucumber > Java (Step/page/Selenium)).

Maven archetype for create a Robot.

Official documentation

You can learn here

Lot of sample here


问:
Linux device driver maps serial fpga registers to memory
There is a FPGA based register set (512 bytes) that can be read/write with a special protocol. I want to write a device driver that makes it possible for the user process to read/write these registers like a memory (array, pointer) and not with read() / write() functions or by dealing with the protocol.

Is this really possible?

Where I can find some description how to do this?

What are the main steps?

答:
You need a device driver that implements mmap() so that the user space application can access the registers by load and store instructions.

Your driver should disable caching when it maps the registers so that reads and writes always interact with your FPGA. Possibly your driver also needs to disable buffering, in case your hardware cannot handle burst writes to the registers.

My designs generally are structured this way. I have a generic device driver enables applications to mmap() the control logic. The device driver also enables the application to use poll() to wait for interrupts from the hardware, in case that is needed. It is so much less headache not to have to update a device driver just because the hardware has changed.


问:
Unable to delete rows from .csv file pyexcel
Here is my function:

```<code>     def prepare_file(time, mkt):
        # renames file to corresponding market name
        global previous_time
        for file in glob.glob(os.getcwd()+'\Reports\*'):
            # if it's the most recently downloaded file
            if time > previous_time:
                previous_time = time
                # remove rows for properties that have not changed status
                sheet = pyexcel.get_sheet(file_name=file)
                for row in sheet:
                    if row[1] in changed_addresses:
                        pass
                    else:
                        del row
                # save file as correct name
                sheet.save_as(
                    os.getcwd() + '\\Reports\\' + mkt[0] + '.csv'
                )
                os.remove(file)
</code>```

The idea is to find the most recently downloaded file in a directory, open it, remove all rows that do not contain a address from the changed_addresses list, and save it as a string contained in the mkt list.

Everything works fine except for the deletion of the rows. It iterates through them correctly, and understands when a row should be deleted, but the outputted file still contains all the rows that should be gone.

is del row not the correct command for this case?

答:
Using csv I think this should work:

```<code>import csv
import os
import glob

def prepare_file(time, mkt):
   # renames file to corresponding market name
   global previous_time
   for file in glob.glob(os.getcwd()+'\Reports\*'):
       # if it's the most recently downloaded file
       if time > previous_time:
           previous_time = time
           # remove rows for properties that have not changed status
           fin = open(file, 'r')
           fout = open((os.getcwd() + '\\Reports\\' + mkt[0] + '.csv'), 'w', newline='')
           reader = csv.reader(fin)
           writer = csv.writer(fout)

           for row in reader:
               if row[1] not in changed_addresses:
                   writer.writerow(row)

           # close files
           fin.close()
           fout.close()

           # remove original
           os.remove(file)
</code>```

So first opening your datafile with name file, and later saving it with the new name.

Body:
Here is my function:

     def prepare_file(time, mkt):
        # renames file to corresponding market name
        global previous_time
        for file in glob.glob(os.getcwd()+'\Reports\*'):
            # if it's the most recently downloaded file
            if time > previous_time:
                previous_time = time
                # remove rows for properties that have not changed status
                sheet = pyexcel.get_sheet(file_name=file)
                for row in sheet:
                    if row[1] in changed_addresses:
                        pass
                    else:
                        del row
                # save file as correct name
                sheet.save_as(
                    os.getcwd() + '\\Reports\\' + mkt[0] + '.csv'
                )
                os.remove(file)

The idea is to find the most recently downloaded file in a directory, open it, remove all rows that do not contain a address from the changed_addresses list, and save it as a string contained in the mkt list.

Everything works fine except for the deletion of the rows. It iterates through them correctly, and understands when a row should be deleted, but the outputted file still contains all the rows that should be gone.

is del row not the correct command for this case?

Body:
Using csv I think this should work:

import csv
import os
import glob

def prepare_file(time, mkt):
   # renames file to corresponding market name
   global previous_time
   for file in glob.glob(os.getcwd()+'\Reports\*'):
       # if it's the most recently downloaded file
       if time > previous_time:
           previous_time = time
           # remove rows for properties that have not changed status
           fin = open(file, 'r')
           fout = open((os.getcwd() + '\\Reports\\' + mkt[0] + '.csv'), 'w', newline='')
           reader = csv.reader(fin)
           writer = csv.writer(fout)

           for row in reader:
               if row[1] not in changed_addresses:
                   writer.writerow(row)

           # close files
           fin.close()
           fout.close()

           # remove original
           os.remove(file)

So first opening your datafile with name file, and later saving it with the new name.


问:
Is there a difference between int(floatvar) and (int)floatvar?

Possible Duplicate:

  C++: What's the difference between function(myVar) and (function)myVar ?

I have seen and used both variants of these typecasts:

```<code>int(floatvar)

(int)floatvar
</code>```

Is there any difference between the two? Are there any preferences about when to use which?

答:
No, it's the same thing.

Anyway, for C++ cast static_cast is preferable.

Body:
Possible Duplicate:

  C++: What's the difference between function(myVar) and (function)myVar ?

I have seen and used both variants of these typecasts:

int(floatvar)

(int)floatvar

Is there any difference between the two? Are there any preferences about when to use which?


问:
phpunit and AppendIterator data provider?
A PHPUnit data provider allows the return of an iterator, but when using an AppendIterator only the last iterator appended is used.  Am I setting things up wrong or can AppendIterators not be used as PHPUnit data providers?

Test file:

```<code><?php

use PHPUnit\Framework\TestCase;

class AppendIteratorTest extends TestCase
{
    /**
     * @dataProvider getAppendIterator
     */
    public function testAppendIterator($item) {
        echo PHP_EOL."test> $item".PHP_EOL;
    }

    public function getAppendIterator() {
        $iterator = new AppendIterator();
        $iterator->append(new ArrayIterator([[0], [1]]));
        $iterator->append(new ArrayIterator([[2], [3]]));
        $iterator->append(new ArrayIterator([[4], [5]]));

        foreach($iterator as $i) {
            echo 'foreach> '.print_r($i, true);
        }

        return $iterator;
    }
}
</code>```

Test file output:

```<code>    $ vendor/bin/phpunit --debug AppendIteratorTest.php
        foreach> Array
    (
        [0] => 0
    )
    foreach> Array
    (
        [0] => 1
    )
    foreach> Array
    (
        [0] => 2
    )
    foreach> Array
    (
        [0] => 3
    )
    foreach> Array
    (
        [0] => 4
    )
    foreach> Array
    (
        [0] => 5
    )
    PHPUnit 6.2.3 by Sebastian Bergmann and contributors.

    Starting test 'AppendIteratorTest::testAppendIterator with data set #0 (4)'.
    R
    test> 4

    Starting test 'AppendIteratorTest::testAppendIterator with data set #1 (5)'.
    R                                                                  2 / 2 (100%)
    test> 5

    Time: 24 ms, Memory: 4.00MB

    There were 2 risky tests:

    1) AppendIteratorTest::testAppendIterator with data set #0 (4)
    This test did not perform any assertions

    2) AppendIteratorTest::testAppendIterator with data set #1 (5)
    This test did not perform any assertions

    OK, but incomplete, skipped, or risky tests!
    Tests: 2, Assertions: 0, Risky: 2.
</code>```

答:
Am I setting things up wrong or can AppendIterators not be used as PHPUnit data providers?

Sort of wrong. Data-providers in Phpunit support any array or Traversable (AppendIterator is a Traversable). So it does work (you can see this as you don't get an error).

However there is a (lesser known) detail with data-providers: Each data-set can have a name. The name is the key of the provided array -or- in case of a Traversable the value of Iterator::key(). For the ArrayIterator that are the array keys.

Here your code with the keys made visible as PHP creates them implicitly:

```<code>    $iterator->append(new ArrayIterator([0 => [0], 1 => [1]]));
    $iterator->append(new ArrayIterator([0 => [2], 1 => [3]]));
    $iterator->append(new ArrayIterator([0 => [4], 1 => [5]]));
</code>```

In your keys these will always be 0 and 1. As you have duplicate keys, the last ones will "win". This is the result you see.

So much as an explanation what is going on.

One solution then could be:

```<code>    $iterator->append(new ArrayIterator([0 => [0], 1 => [1]]));
    $iterator->append(new ArrayIterator([2 => [2], 3 => [3]]));
    $iterator->append(new ArrayIterator([4 => [4], 5 => [5]]));
</code>```

There is no default Iterator in PHP which would re-number the keys, also I don't have one in Iterator Garden (IndexingIterator comes close, Börgers examples are down, Nikic iter lib's reindex can do it, ...) a quick inline in your case would be yielding reindexed:

```<code>public function getAppendIterator() {
    $iterator = new AppendIterator();
    $iterator->append(new ArrayIterator([[0], [1]]));
    $iterator->append(new ArrayIterator([[2], [3]]));
    $iterator->append(new ArrayIterator([[4], [5]]));

    $index = 0;
    foreach ($iterator as $i) {
        yield $index++ => $i;
    }
}
</code>```

Here the $index counter is used as key in the yield statement. This makes your data-provider return a Generator which is a Traversable again. Phpunit then can handle it.

The problem is similar when you have multiple data-provider methods that do return data-sets with string keys. All string keys must be unique otherwise the provided data will be overwritten again.

That is b/c internally the data-sets from each data-provider is turned into an array explicitly.

I hope this answers your question and also helps you to create the data-provider you're looking for.

Body:
A PHPUnit data provider allows the return of an iterator, but when using an AppendIterator only the last iterator appended is used.  Am I setting things up wrong or can AppendIterators not be used as PHPUnit data providers?

Test file:

<?php

use PHPUnit\Framework\TestCase;

class AppendIteratorTest extends TestCase
{
    /**
     * @dataProvider getAppendIterator
     */
    public function testAppendIterator($item) {
        echo PHP_EOL."test> $item".PHP_EOL;
    }

    public function getAppendIterator() {
        $iterator = new AppendIterator();
        $iterator->append(new ArrayIterator([[0], [1]]));
        $iterator->append(new ArrayIterator([[2], [3]]));
        $iterator->append(new ArrayIterator([[4], [5]]));

        foreach($iterator as $i) {
            echo 'foreach> '.print_r($i, true);
        }

        return $iterator;
    }
}

Test file output:

    $ vendor/bin/phpunit --debug AppendIteratorTest.php
        foreach> Array
    (
        [0] => 0
    )
    foreach> Array
    (
        [0] => 1
    )
    foreach> Array
    (
        [0] => 2
    )
    foreach> Array
    (
        [0] => 3
    )
    foreach> Array
    (
        [0] => 4
    )
    foreach> Array
    (
        [0] => 5
    )
    PHPUnit 6.2.3 by Sebastian Bergmann and contributors.

    Starting test 'AppendIteratorTest::testAppendIterator with data set #0 (4)'.
    R
    test> 4

    Starting test 'AppendIteratorTest::testAppendIterator with data set #1 (5)'.
    R                                                                  2 / 2 (100%)
    test> 5

    Time: 24 ms, Memory: 4.00MB

    There were 2 risky tests:

    1) AppendIteratorTest::testAppendIterator with data set #0 (4)
    This test did not perform any assertions

    2) AppendIteratorTest::testAppendIterator with data set #1 (5)
    This test did not perform any assertions

    OK, but incomplete, skipped, or risky tests!
    Tests: 2, Assertions: 0, Risky: 2.

Body:
Am I setting things up wrong or can AppendIterators not be used as PHPUnit data providers?

Sort of wrong. Data-providers in Phpunit support any array or Traversable (AppendIterator is a Traversable). So it does work (you can see this as you don't get an error).

However there is a (lesser known) detail with data-providers: Each data-set can have a name. The name is the key of the provided array -or- in case of a Traversable the value of Iterator::key(). For the ArrayIterator that are the array keys.

Here your code with the keys made visible as PHP creates them implicitly:

    $iterator->append(new ArrayIterator([0 => [0], 1 => [1]]));
    $iterator->append(new ArrayIterator([0 => [2], 1 => [3]]));
    $iterator->append(new ArrayIterator([0 => [4], 1 => [5]]));

In your keys these will always be 0 and 1. As you have duplicate keys, the last ones will "win". This is the result you see.

So much as an explanation what is going on.

One solution then could be:

    $iterator->append(new ArrayIterator([0 => [0], 1 => [1]]));
    $iterator->append(new ArrayIterator([2 => [2], 3 => [3]]));
    $iterator->append(new ArrayIterator([4 => [4], 5 => [5]]));

There is no default Iterator in PHP which would re-number the keys, also I don't have one in Iterator Garden (IndexingIterator comes close, Börgers examples are down, Nikic iter lib's reindex can do it, ...) a quick inline in your case would be yielding reindexed:

public function getAppendIterator() {
    $iterator = new AppendIterator();
    $iterator->append(new ArrayIterator([[0], [1]]));
    $iterator->append(new ArrayIterator([[2], [3]]));
    $iterator->append(new ArrayIterator([[4], [5]]));

    $index = 0;
    foreach ($iterator as $i) {
        yield $index++ => $i;
    }
}

Here the $index counter is used as key in the yield statement. This makes your data-provider return a Generator which is a Traversable again. Phpunit then can handle it.

The problem is similar when you have multiple data-provider methods that do return data-sets with string keys. All string keys must be unique otherwise the provided data will be overwritten again.

That is b/c internally the data-sets from each data-provider is turned into an array explicitly.

I hope this answers your question and also helps you to create the data-provider you're looking for.