问:
How can I make a form with custom check boxes that will direct me to different html files on submit form?
I have a form with custom check boxes that I want to hold references to my other html pages. I want the user to select one of the check boxes and then hit the start button at the bottom. What should happen is it will take the user to the html file that was attached to the checkbox. I know this probably didnt make sense so go to the web version of the site to get an idea of what I am trying to do.</p>

```<code>    <form method="post">
    <div class="form-row">
        <div class="col-sm-1">
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="https://www.mometrix.com/academy/wp-content/uploads/2017/12/Algebra-I-1024x683.jpg" class="mr-3" alt="" width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Algebra</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch1" name="AL">
                        <label class="custom-control-label" for="customSwitch1"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="https://www.wikihow.com/images/thumb/a/ae/Find-Area-and-Perimeter-Step-7-Version-2.jpg/aid3987529-v4-728px-Find-Area-and-Perimeter-Step-7-Version-2.jpg" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Area & Perimeter</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch2" name="AP">
                        <label class="custom-control-label" for="customSwitch2"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-12">
        </div>
    </div>
    <div class="form-row">
        <div class="col-sm-1">
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="https://www.mathsisfun.com/numbers/images/arithmetic.svg" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Arithmetic</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch3" name="AR">
                        <label class="custom-control-label" for="customSwitch3"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="https://www.mathsisfun.com/algebra/images/exponent-8-2.svg" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Exponents</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch4" name="EX">
                        <label class="custom-control-label" for="customSwitch4"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-12">
        </div>
    </div>
    <div class="form-row">
        <div class="col-sm-1">
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="https://dmzn2b8hkpq8b.cloudfront.net/images/products/515x515/S411589.jpg" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Geometric Solids</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch5" name="GS">
                        <label class="custom-control-label" for="customSwitch5"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="data:image/png;base64,[encoded data, 11644 characters]" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Probability</h5>
                    <div class="">
                        <input type="checkbox" class="custom-control-input" id="customSwitch6" name="PR">
                        <label class="custom-control-label" for="customSwitch6"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-12">
        </div>
    </div>
    <div class="form-row">
        <div class="col-sm-1">
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDvygQLpB_G08iwALHg6N6rIEm1abgLnEQKZF0Qn6QOZFQDYWP" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Systems of Equations</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch7" name="SE">
                        <label class="custom-control-label" for="customSwitch7"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="http://home.windstream.net/okrebs/Ch8-28.gif" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Trig Statements</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch8" name="TR">
                        <label class="custom-control-label" for="customSwitch8"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-12">
        </div>
    </div>
    <center>
        <button type="submit" class="btn btn-outline-success">Start</button>
    </center>
</form>
</code>```

答:
Here is what I have done with the code you gave me Mister Jojo </p>

```<code>    <script>

    const
        MyForm = document.getElementById('My-Form'),
        all_checkBox = document.querySelectorAll('#My-Form input[type=checkbox]'),
        SubmitBt = document.querySelector('#My-Form button[type=submit]');

    all_checkBox.forEach(chkBx => { chkBx.onchange = ChkBxChanged })

    SubmitBt.disabled = true;

    function ChkBxChanged(e) {
        MyForm.action = '';
        SubmitBt.disabled = true;

        if (this.checked) {
            MyForm.action = this.dataset.page;
            SubmitBt.disabled = false;

            all_checkBox.forEach(cb => {
                if (cb != this) cb.checked = false   // only one should be checked
            })
        }
    }
</script>
<form id="My-Form" action="" method="POST">

    <h5 class="mt-0">Algebra</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch1" name="AL" data-page="index.html">

    <h5 class="mt-0">Area & Perimeter</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch2" name="AP" data-page="index.html">

    <h5 class="mt-0">Arithmetic</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch3" name="AR" data-page="index.html">

    <h5 class="mt-0">Exponents</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch4" name="EX" data-page="index.html">

    <h5 class="mt-0">Geometric Solids</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch5" name="GS" data-page="index.html">

    <h5 class="mt-0">Probability</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch6" name="PR" data-page="index.html">

    <h5 class="mt-0">Systems of Equations</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch8" name="SE" data-page="index.html">
        <button type="submit" class="btn btn-outline-success">Start</button>

</form>
</code>```

Body:
I have a form with custom check boxes that I want to hold references to my other html pages. I want the user to select one of the check boxes and then hit the start button at the bottom. What should happen is it will take the user to the html file that was attached to the checkbox. I know this probably didnt make sense so go to the web version of the site to get an idea of what I am trying to do.

    <form method="post">

Algebra

                        <input type="checkbox" class="custom-control-input" id="customSwitch1" name="AL">

Area & Perimeter

                        <input type="checkbox" class="custom-control-input" id="customSwitch2" name="AP">

Arithmetic

                        <input type="checkbox" class="custom-control-input" id="customSwitch3" name="AR">

Exponents

                        <input type="checkbox" class="custom-control-input" id="customSwitch4" name="EX">

Geometric Solids

                        <input type="checkbox" class="custom-control-input" id="customSwitch5" name="GS">

                <img src="data:image/png;base64,[encoded data, 11644 characters]" class="mr-3" alt="..." width="150" height="150">

Probability

                        <input type="checkbox" class="custom-control-input" id="customSwitch6" name="PR">

Systems of Equations

                        <input type="checkbox" class="custom-control-input" id="customSwitch7" name="SE">

Trig Statements

                        <input type="checkbox" class="custom-control-input" id="customSwitch8" name="TR">

        <button type="submit" class="btn btn-outline-success">Start</button>

</form>

Body:
Here is what I have done with the code you gave me Mister Jojo

    <script>

    const
        MyForm = document.getElementById('My-Form'),
        all_checkBox = document.querySelectorAll('#My-Form input[type=checkbox]'),
        SubmitBt = document.querySelector('#My-Form button[type=submit]');

    all_checkBox.forEach(chkBx => { chkBx.onchange = ChkBxChanged })

    SubmitBt.disabled = true;

    function ChkBxChanged(e) {
        MyForm.action = '';
        SubmitBt.disabled = true;

        if (this.checked) {
            MyForm.action = this.dataset.page;
            SubmitBt.disabled = false;

            all_checkBox.forEach(cb => {
                if (cb != this) cb.checked = false   // only one should be checked
            })
        }
    }
</script>
<form id="My-Form" action="" method="POST">

    <h5 class="mt-0">Algebra</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch1" name="AL" data-page="index.html">

    <h5 class="mt-0">Area &amp; Perimeter</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch2" name="AP" data-page="index.html">

    <h5 class="mt-0">Arithmetic</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch3" name="AR" data-page="index.html">

    <h5 class="mt-0">Exponents</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch4" name="EX" data-page="index.html">

    <h5 class="mt-0">Geometric Solids</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch5" name="GS" data-page="index.html">

    <h5 class="mt-0">Probability</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch6" name="PR" data-page="index.html">

    <h5 class="mt-0">Systems of Equations</h5>
    <input type="checkbox" class="custom-control-input" id="customSwitch8" name="SE" data-page="index.html">
        <button type="submit" class="btn btn-outline-success">Start</button>

</form>


来源: stackexchange

问:
Cross-Branch merging in TFS?
Is it possible to merge to a branch that is not a direct parent or child in TFS?  I suspect that the answer is no as this is what I've experienced while using it.  However, it seems that at certain times it would be really useful when there are different features being worked on that may have different approval cycles (ie. feature one might be approved before feature two).  This becomes exceedingly difficult when we have production branches where we have to merge some feature into a previous branch so we can release before the next full version.

Our current branching strategy is to develop in the trunk (or mainline as we call it), and create a branch to stabilize and release to production.  This branch can then be used to create hotfixes and other things while mainline can diverge for upcoming features.

What techniques can be used otherwise to mitigate a scenario such as the one(s) described above?

答:
I am far from a TFS expert, but I think you can merge siblings, and I think it is not a baseless merge.

We branched off our main branch (branch name "main") for a feature (branch name "feature"), then I needed some of the work in a branch that was also branched off the main branch (branch name "dev"). I would consider feature and dev branches to be siblings as they both came from the same parent. I merged feature to dev and all files (14000) were marked as merge, some were marked as merge,edit. I could not cancel (visual studio would just hang), so I accepted the merge. Then I merged dev to main, then I pulled main to feature, and again 14000 files were marked for merge. I was really upset, and afraid this would continue.

At this point we did a test project. We set up main, then branched dev and feature from main. We repeated the above steps with the same results. Once we completed the merge from main to feature, all future merges only showed the edited files.

After our little test I completed the merge from main to feature. And just like the test our merges now only show the edited files. We can go dev to feature, feature to main, main to dev, etc.

I did notice when branching all file dates were modified. Maybe this is an issue?

OwnerDisplayName: Joel Martinez

ContentLicense: CC BY-SA 2.5

Title: Cross-Branch merging in TFS?

LastEditorDisplayName: Joel Martinez

ContentLicense: CC BY-SA 4.0


问:
Magento: save custom address attribute in checkout
This is what i did in my website: Admin->Customers->Attributes->Manage Customer Address Attributes and add a new attribute , the user can see it in his/her profile, under My Addresses option, the new attribute can be edited and is saved when creating a new address, i also can see it in the backend, and edited, until here everything is ok, my problem is in the checkout, i already have the field in the billing and shipping forms and i want the new attribute to be saved when the user click "Place Order" button, but, checkout seems it doesn't know nothing about the new attribute, the attribute is not saved and if i save one value from the user profile checkout doesn't load it in the field.

what can i do here??

thanks

答:
After looking in the Magento's code and reading the wiki, I was able to complete it, my new attribute was saved in the address edit form in the profile, but was not saved when I enter it in the checkout form, that was because I need to override some Magento core files, the first step was adding the new attribute to app\code\core\Mage\Customer\etc\config.xml, I copied to app\code\core\Mycompany\Customer\etc\config.xml, as my new attribute code is rfc, I located the <fieldsets> entry and

```<code><customer_dataflow>
    ....
    <rfc><billing>1</billing><shipping>1</shipping></rfc>
</customer_dataflow>
</code>```

now I need to add the new attribute to the app\code\core\Mage\Customer\Model\Entity\Setup.php i did the same to override, copied to my local namespace, and in the function getDefaultEntities() i locate the

```<code>'customer_address'=>array(
    ....
            'rfc' => array(
            'label'         => 'RFC',
            'required'      => false,
            'sort_order'    => 135,
    ),
)
</code>```

now, I need to do also the same in app\code\core\Mage\Sales\etc\config.xml, but now should look like this

```<code><sales_copy_order_billing_address>
    .....
    <rfc><to_order>*</to_order></rfc>
</sales_copy_order_billing_address>

<sales_copy_order_shipping_address>
    ......
    <rfc><to_order>*</to_order></rfc>
</sales_copy_order_shipping_address>

<sales_convert_quote_address>
    ........
    <rfc><to_order_address>*</to_order_address><to_customer_address>*</to_customer_address></rfc>
</sales_convert_quote_address>

<sales_convert_order_address>
    .........
    <rfc><to_quote_address>*</to_quote_address></rfc>
</sales_convert_order_address>

<customer_address>
    .......
    <rfc><to_quote_address>*</to_quote_address></rfc>
</customer_address>
</code>```

Hope it can help someone else

Body:
After looking in the Magento's code and reading the wiki, I was able to complete it, my new attribute was saved in the address edit form in the profile, but was not saved when I enter it in the checkout form, that was because I need to override some Magento core files, the first step was adding the new attribute to app\code\core\Mage\Customer\etc\config.xml, I copied to app\code\core\Mycompany\Customer\etc\config.xml, as my new attribute code is rfc, I located the <fieldsets> entry and

<customer_dataflow>
    ....
    <rfc><billing>1</billing><shipping>1</shipping></rfc>
</customer_dataflow>

now I need to add the new attribute to the app\code\core\Mage\Customer\Model\Entity\Setup.php i did the same to override, copied to my local namespace, and in the function getDefaultEntities() i locate the

'customer_address'=>array(
    ....
            'rfc' => array(
            'label'         => 'RFC',
            'required'      => false,
            'sort_order'    => 135,
    ),
)

now, I need to do also the same in app\code\core\Mage\Sales\etc\config.xml, but now should look like this

<sales_copy_order_billing_address>
    .....
    <rfc><to_order>*</to_order></rfc>
</sales_copy_order_billing_address>

<sales_copy_order_shipping_address>
    ......
    <rfc><to_order>*</to_order></rfc>
</sales_copy_order_shipping_address>

<sales_convert_quote_address>
    ........
    <rfc><to_order_address>*</to_order_address><to_customer_address>*</to_customer_address></rfc>
</sales_convert_quote_address>

<sales_convert_order_address>
    .........
    <rfc><to_quote_address>*</to_quote_address></rfc>
</sales_convert_order_address>

<customer_address>
    .......
    <rfc><to_quote_address>*</to_quote_address></rfc>
</customer_address>

Hope it can help someone else


问:
Adding a set value to a cell with a macro
I have a value, which can be changed manually, but I want a button which I can click to add a value of 200 to that number. This might be a stupid question but I've been trying all afternoon. I don't want to change the formula of the cell, I just want it as a static value so I can do manual changes to that number not using the button I will assign this script to.</p>

答:
This script does what I needed:

```<code>function RSNW() {
  var spreadsheet = SpreadsheetApp.getActive();
  SpreadsheetApp.getActiveSheet().getRange('AS42').setValue(SpreadsheetApp.getActiveSheet().getRange('AS42').getValue() + 250);
};
</code>```

It adds 250 to the value I have in AS42.

Body:
This script does what I needed:

function RSNW() {
  var spreadsheet = SpreadsheetApp.getActive();
  SpreadsheetApp.getActiveSheet().getRange('AS42').setValue(SpreadsheetApp.getActiveSheet().getRange('AS42').getValue() + 250);
};

It adds 250 to the value I have in AS42.


问:
How to access the Grafana time interval range for DrillDown links to an ElasticSearch page
I'm trying to add a drilldown link to an Elastic search link in a Grafana chart. I'm able to use the variables that are already defined in my panel, but I also want to make use of the current time interval when creating the URL for elastic search.

I have tried using the following variables in the URL based on different online posts, hoping that they would be replaced by Grafana when the URL is clicked.

$__interval

$timeInterval

$interval

but, nonw have been converted to the time range value that is currently selected.

e.g.:
Url in Grafana:

https://elastic.local.dev/app/kibana#/discover?_g=(refreshInterval:(pause:!t,value:10000),time:(from:now-$__interval,mode:quick,to:now))&_a=(columns:!(_source),index:'logs-*',interval:auto,query:(language:lucene,query:'severity:FATAL%20AND%20%20environment:$environment'),sort:!('@timestamp',desc))

Expected Url when user clicks the chart:

https://elastic.local.dev/app/kibana#/discover?_g=(refreshInterval:(pause:!t,value:10000),time:(from:now-1h,mode:quick,to:now))&_a=(columns:!(_source),index:'logs-*',interval:auto,query:(language:lucene,query:'severity:FATAL%20AND%20%20environment:Development'),sort:!('@timestamp',desc))

Actual Url when user clicks the chart:

https://elastic.local.dev/app/kibana#/discover?_g=(refreshInterval:(pause:!t,value:10000),time:(from:now-$__interval,mode:quick,to:now))&_a=(columns:!(_source),index:'logs-*',interval:auto,query:(language:lucene,query:'severity:FATAL%20AND%20%20environment:Development'),sort:!('@timestamp',desc))

The $environment variable is being replaced as expected but the $__interval variable is not being replaced which causes the URL to not be parsed correctly by Elastic Search when trying to display the page.

答:
Possible starting from Grafana 6.0, use this snippet:

Url: "/dashboard-id/dashboard-name?var-variable1=${__cell}&from=$__from&to=$__to


问:
Attempting to use pyfftw - "The output array and input array dtypes do not correspond to a valid fftw scheme."
I am using pyfftw for a simple fft. I am unsure how to use pyfftw because I am getting the error:

```<code>KeyError                                  Traceback (most recent call last)
pyfftw\pyfftw.pyx in pyfftw.pyfftw.FFTW.__cinit__()

KeyError: (dtype('float64'), dtype('float64'))

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-31-dc32579f60f3> in <module>()
      3 start = time.time()
      4 b4 = numpy.zeros_like(a)
----> 5 fft = pyfftw.FFTW( a, b4, direction='FFTW_FORWARD', flags=('FFTW_MEASURE', ), threads=nthread, planning_timelimit=None )
      6 fft()
      7 end4 = time.time() - start

pyfftw\pyfftw.pyx in pyfftw.pyfftw.FFTW.__cinit__()

ValueError: Invalid scheme: The output array and input array dtypes do not correspond to a valid fftw scheme.
</code>```

This is the code im using:

```<code>import numpy as np
from scipy.signal import hilbert, chirp

duration = 1.0
fs = 400.0
samples = int(fs*duration)
t = np.arange(samples) / fs

signal = chirp(t, 20.0, t[-1], 100.0)
signal *= (1.0 + 0.5 * np.sin(2.0*np.pi*3.0*t) )

import time
import numpy
import pyfftw
import multiprocessing
nthread = multiprocessing.cpu_count()

a = signal

pyfftw.forget_wisdom()
start = time.time()
b4 = numpy.zeros_like(a)
fft = pyfftw.FFTW( a, b4, direction='FFTW_FORWARD', flags=('FFTW_MEASURE', ), threads=nthread, planning_timelimit=None )
fft()
end4 = time.time() - start

print(end4)
</code>```

Any insight on why this isnt working would be greatly appreciated

答:
You may want to use complex128 as the output type, since the DFT of a real-valued signal is complex-valued in general (unless the real-valued signal is symmetric).

See https://hgomersall.github.io/pyFFTW/pyfftw/pyfftw.html#scheme-table

Body:
I am using pyfftw for a simple fft. I am unsure how to use pyfftw because I am getting the error:

KeyError                                  Traceback (most recent call last)
pyfftw\pyfftw.pyx in pyfftw.pyfftw.FFTW.__cinit__()

KeyError: (dtype('float64'), dtype('float64'))

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-31-dc32579f60f3> in <module>()
      3 start = time.time()
      4 b4 = numpy.zeros_like(a)
----> 5 fft = pyfftw.FFTW( a, b4, direction='FFTW_FORWARD', flags=('FFTW_MEASURE', ), threads=nthread, planning_timelimit=None )
      6 fft()
      7 end4 = time.time() - start

pyfftw\pyfftw.pyx in pyfftw.pyfftw.FFTW.__cinit__()

ValueError: Invalid scheme: The output array and input array dtypes do not correspond to a valid fftw scheme.

This is the code im using:

import numpy as np
from scipy.signal import hilbert, chirp

duration = 1.0
fs = 400.0
samples = int(fs*duration)
t = np.arange(samples) / fs

signal = chirp(t, 20.0, t[-1], 100.0)
signal *= (1.0 + 0.5 * np.sin(2.0*np.pi*3.0*t) )

import time
import numpy
import pyfftw
import multiprocessing
nthread = multiprocessing.cpu_count()

a = signal

pyfftw.forget_wisdom()
start = time.time()
b4 = numpy.zeros_like(a)
fft = pyfftw.FFTW( a, b4, direction='FFTW_FORWARD', flags=('FFTW_MEASURE', ), threads=nthread, planning_timelimit=None )
fft()
end4 = time.time() - start

print(end4)

Any insight on why this isnt working would be greatly appreciated


问:
Slack @here mention in channel via Incoming webhook
So I have an alert channel that collects messages from slack via incoming webhook. It's one of many tools we use to monitor these couple of apps that normally run without issue, but if there is a problem we want to know right away so we can do something about it. I'm getting emails, etc. but I also want the channel wide slack messages.

What I'm trying to do seems simple enough, but it's not working. I want to trigger an @channel or @here message to alert all the users in the channel at the time, so if the error happens in an environment that matters everyone gets a notification. I'm following examples in the documentation using the <@ABC123> channel id but it's not translating into an @here directive, it's just plain text.

Either what I'm doing can't be done, or more likely I'm missing something somewhere or approaching this incorrectly. I'm guessing it's the latter, but at this point confirmation that I can't do what I'm trying to do is fine, I'll come up with something else.

答:
Found it

Apparently the convention for the channel alerts are <!channel>, not <@C123> as is with users or channel ids, or <#channel> with channel mentions (though that does work, just not as a channel wide alert). Hope this helps someone eventually.


问:
best way to get city name from google reverse geocoding api php
i am trying to get city name from google reverse geocoding api, my code is displaying full address of the location but i need only city. bellow is my code

```<code><?php
session_start();
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
    //Send request and receive json data by latitude and longitude
    $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
    $json = @file_get_contents($url);
    $data = json_decode($json);
    $status = $data->status;
    if($status=="OK"){
        //Get address from json data
        //$location = $data->results[0]->formatted_address;
        $location = $data->results[0]->address_components;

    }else{
        $location =  '';
    }
    //Print city
    $_SESSION['getgeoloc']=$location[6]->long_name;

    echo $location;
}
?>
</code>```

i tried below code to display city, but some times its showing zip code and sometimes city name

```<code>$_SESSION['getgeoloc']=$location[6]->long_name;
</code>```

is there any best way ?

答:
You can specify a result_type = locality in the query params like shown below.

For more information about filters, you can search for Optional parameters in a reverse Geocoding request documentation.

https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding

ContentLicense: CC BY-SA 3.0

Body:
i am trying to get city name from google reverse geocoding api, my code is displaying full address of the location but i need only city. bellow is my code

<?php
session_start();
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
    //Send request and receive json data by latitude and longitude
    $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
    $json = @file_get_contents($url);
    $data = json_decode($json);
    $status = $data->status;
    if($status=="OK"){
        //Get address from json data
        //$location = $data->results[0]->formatted_address;
        $location = $data->results[0]->address_components;

    }else{
        $location =  '';
    }
    //Print city
    $_SESSION['getgeoloc']=$location[6]->long_name;

    echo $location;
}
?>

i tried below code to display city, but some times its showing zip code and sometimes city name

$_SESSION['getgeoloc']=$location[6]->long_name;

is there any best way ?


问:
ObjC / iPhone dictionary grep?
I have a large number of strings in my iPhone app containing random combinations of letters, and I'd like to check each of these random strings against a dictionary. I'm looking for a way to grep each string with /usr/share/dict/words and return the result (or number of results) back to my app. Is this possible in an iPhone app?

Edit: Thanks for all the suggestions. Originally I wanted to execute a grep and ideally pipe the results back into my app, but after some more digging and playing around with NSTask it seems its not possible on an iPhone. I ended up loading all the words into a big NSDictionary with this approach:

NSString* allWords = [NSString stringWithContentsOfFile:@"/usr/share/dict/words" encoding:NSASCIIStringEncoding error:NULL];
NSArray* wordArray = [allWords componentsSeparatedByString:@"\n"];

答:
I think you could handle this with standard code, unless you are using regular expressions. In your question the term "grep" seems to just mean substring search from a list of words.

Assuming that you have access to the dictionary of words (like maybe it's included in the app bundle) try this:

```<code>NSString *dictString = [NSString stringWithContentsOfFile:pathToDictionary encoding:NSUTF8StringEncoding error:NULL];
NSArray *words = [dictString componentsSeparatedByString:@"\n"]; // maybe @"\r\n" ?

for (NSString *word in words)
{
       // do your comparison here
       NSRange wordRange = [myBigString rangeOfString:word];
       if (wordRange.location!=NSNotFound)
       {
            NSLog(@"It's peanut butter jelly time! [%@]", word);
       }
}
</code>```

Title: ObjC / iPhone dictionary grep?

Body:
I think you could handle this with standard code, unless you are using regular expressions. In your question the term "grep" seems to just mean substring search from a list of words.

Assuming that you have access to the dictionary of words (like maybe it's included in the app bundle) try this:

NSString *dictString = [NSString stringWithContentsOfFile:pathToDictionary encoding:NSUTF8StringEncoding error:NULL];
NSArray *words = [dictString componentsSeparatedByString:@"\n"]; // maybe @"\r\n" ?

for (NSString *word in words)
{
       // do your comparison here
       NSRange wordRange = [myBigString rangeOfString:word];
       if (wordRange.location!=NSNotFound)
       {
            NSLog(@"It's peanut butter jelly time! [%@]", word);
       }
}


问:
Dart 2.3 ignores breakpoints
I am developing a web app in Dart using Webstorm as IDE. After upgrading from Dart SDK 2.2 to Dart SDK 2.3 I noticed that all breakpoints I set in Webstorm are ignored (although the app seems to run properly in Chrome) That breakpoints are correctly marked as a "red circle" but unlike the previous SDK they miss the "tick" inside (which I think means they are not recognized by Chrome).

I tried to "repair cache" and "upgrade dependencies" but breakpoints still don't work.

That's the pubspec.yaml dev_dependencies:

```<code>dev_dependencies:
  build_runner: ^1.4.0
  build_test: ^0.10.7+3
  build_web_compilers: ^2.1.0

</code>```

Here is the "webdev serve" command:

```<code>/dart/2.3.1/dart-sdk/bin/pub global run webdev serve web:53321
</code>```

Here is the "webdev serve" command result:

```<code>[INFO] Serving `web` on http://localhost:53321
[INFO] Running build completed, took 351ms
[INFO] Caching finalized dependency graph completed, took 177ms
[INFO] Succeeded after 536ms with 0 outputs (0 actions)
</code>```

Here the versions of envolved softwares:

```<code>- O.S.: macOS High Sierra 10.13.6
- Chrome: 74.0.3729.169
- Webstorm: 2019.1 - Build 191.7141.49
- Dart SDK: 2.3.1
- Dart webdev: 2.0.5
</code>```

I'm trying to figure out if the issue is related to Webstorm, Dart SDK or Chrome. I don't exclude that I miss some new configuration due to the Dart SDK upgrade. Downgrading back to Dart SDK 2.2 everything works fine. Thank you for your hints.

答: The bug was in webdev 2.0.0 - 2.0.6. It is fixed in webdev 2.0.7. You may run pub global activate webdev to get the latest version. You might need to close/open the project in the IDE to get it working.

Title: Dart 2.3 ignores breakpoints

Body:
I am developing a web app in Dart using Webstorm as IDE. After upgrading from Dart SDK 2.2 to Dart SDK 2.3 I noticed that all breakpoints I set in Webstorm are ignored (although the app seems to run properly in Chrome) That breakpoints are correctly marked as a "red circle" but unlike the previous SDK they miss the "tick" inside (which I think means they are not recognized by Chrome).

I tried to "repair cache" and "upgrade dependencies" but breakpoints still don't work.

That's the pubspec.yaml dev_dependencies:

dev_dependencies:
  build_runner: ^1.4.0
  build_test: ^0.10.7+3
  build_web_compilers: ^2.1.0

Here is the "webdev serve" command:

/dart/2.3.1/dart-sdk/bin/pub global run webdev serve web:53321

Here is the "webdev serve" command result:

[INFO] Serving `web` on http://localhost:53321
[INFO] Running build completed, took 351ms
[INFO] Caching finalized dependency graph completed, took 177ms
[INFO] Succeeded after 536ms with 0 outputs (0 actions)

Here the versions of envolved softwares:

- O.S.: macOS High Sierra 10.13.6
- Chrome: 74.0.3729.169
- Webstorm: 2019.1 - Build 191.7141.49
- Dart SDK: 2.3.1
- Dart webdev: 2.0.5

I'm trying to figure out if the issue is related to Webstorm, Dart SDK or Chrome. I don't exclude that I miss some new configuration due to the Dart SDK upgrade. Downgrading back to Dart SDK 2.2 everything works fine. Thank you for your hints.


问:
How do I set distance between flexbox items?
To set the minimal distance between flexbox items I'm using margin: 0 5px on .item and margin: 0 -5px on container. This seems like a hack. Is there another property or method intended to accomplish this goal?

#box {
  display: flex;
  width: 100px;
  margin: 0 -5px;
}

.item {
  background: gray;
  width: 50px;
  height: 50px;
  margin: 0 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='box'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div></code>```

答:
Simple way of doing this is by adding margin-left and margin-right to the children div and adjust the margin value accordingly

```<code><div class="a">
  <div class="b"></div>
  <div class="b"></div>
  <div class="b"></div>
</div>
</code>```

css:

```<code>.a{
   display: flex;
   justify-content: center;
   background-color: black;
}

.b{
  height: 25px;
  width: 25px;
  background-color: grey;
  margin-left: 5px;
  margin-right: 5px;
}
</code>```

Body:
Simple way of doing this is by adding margin-left and margin-right to the children div and adjust the margin value accordingly

<div class="a">
  <div class="b"></div>
  <div class="b"></div>
  <div class="b"></div>
</div>

css:

.a{
   display: flex;
   justify-content: center;
   background-color: black;
}

.b{
  height: 25px;
  width: 25px;
  background-color: grey;
  margin-left: 5px;
  margin-right: 5px;
}


问:
GStreamer connection to VLC using GstRTSP library
I am trying to write a C application to connect with VLC RTSP (via RTP) stream and save frames as images.
I use the GStreamer RTSP library: https://gstreamer.freedesktop.org/documentation/gst-plugins-base-rtsp-1.0/index.html?gi-language=c

I have written some simple code presented below, but the app wait for the message from the VLC. I am not sure if it is a good way to connect but I am in stuck now. Maybe I should send something first to VLC but I do not know what and how to do this. Could anyone help or point some resources/examples how to use GStreamer RTSP?

```<code>#include <gstreamer-1.0/gst/rtsp/rtsp.h>
#include <stdio.h>

int main()
{
    GstRTSPUrl *gstUrl = NULL;
    const char* url = "rtsp://10.30.1.163:8554/test.sdp";
    if(gst_rtsp_url_parse(url, &gstUrl) == GST_RTSP_OK) {
        printf("URL PARSE");
        GstRTSPConnection *gstRTSPConnection = NULL;
        if(gst_rtsp_connection_create(gstUrl, &gstRTSPConnection) == GST_RTSP_OK) {
            printf("Connection created\n");
            GstRTSPMessage *message = NULL;
            gst_rtsp_message_new(&message);
            GstRTSPResult result = gst_rtsp_connection_connect_with_response(gstRTSPConnection, NULL, message);
            if(result == GST_RTSP_ETIMEOUT){
                printf("Timeout\n");
            } else if(result == GST_RTSP_OK) {
                printf("Connected\n");
                printf("%s\n", gst_rtsp_connection_get_ip(gstRTSPConnection));
                printf("Is tunelled: %d\n", gst_rtsp_connection_is_tunneled(gstRTSPConnection));
                gst_rtsp_connection_receive(gstRTSPConnection, message, NULL);
            }
        }
    }

    return 0;
}
</code>```

答:
Ok. I will handle this. The issue was I need to first send some message to the server according to RTSP protocol. The solution below (with some dump messages):</p>

```<code>#include <gstreamer-1.0/gst/rtsp/rtsp.h>
#include <stdio.h>

int main()
{
    GstRTSPUrl *gstUrl = NULL;
    const char* url = "rtsp://10.30.1.163:8554";
    if(gst_rtsp_url_parse(url, &gstUrl) == GST_RTSP_OK) {
        printf("URL PARSE");
        GstRTSPConnection *gstRTSPConnection = NULL;
        if(gst_rtsp_connection_create(gstUrl, &gstRTSPConnection) == GST_RTSP_OK) {
            printf("Connection created\n");
            GstRTSPMessage *message = NULL;
            gst_rtsp_message_new(&message);
            GstRTSPResult result = gst_rtsp_connection_connect_with_response(gstRTSPConnection, NULL, message);
            if(result == GST_RTSP_ETIMEOUT){
                printf("Timeout\n");
            } else if(result == GST_RTSP_OK) {
                printf("Connected\n");
                printf("%s\n", gst_rtsp_connection_get_ip(gstRTSPConnection));
                printf("Is tunelled: %d\n", gst_rtsp_connection_is_tunneled(gstRTSPConnection));

                gst_rtsp_message_new(&message);
                gst_rtsp_message_init_request(message, GST_RTSP_DESCRIBE, "rtsp://10.30.1.163:8554/test.sdp");
                gst_rtsp_message_add_header(message, GST_RTSP_HDR_CSEQ, "1");
                printf("Message Type %d", gst_rtsp_message_get_type(message));

                gst_rtsp_message_dump(message);

                if(gst_rtsp_connection_send(gstRTSPConnection, message, NULL) == GST_RTSP_OK){
                    printf("Message sent");
                }else {
                    printf("Message not sent");
                }
                gst_rtsp_connection_receive(gstRTSPConnection, message, NULL);

                gst_rtsp_message_dump(message);
            }
        }
    }

    return 0;
}
</code>```

Body:
I am trying to write a C application to connect with VLC RTSP (via RTP) stream and save frames as images.
I use the GStreamer RTSP library: https://gstreamer.freedesktop.org/documentation/gst-plugins-base-rtsp-1.0/index.html?gi-language=c

I have written some simple code presented below, but the app wait for the message from the VLC. I am not sure if it is a good way to connect but I am in stuck now. Maybe I should send something first to VLC but I do not know what and how to do this. Could anyone help or point some resources/examples how to use GStreamer RTSP?

#include <gstreamer-1.0/gst/rtsp/rtsp.h>
#include <stdio.h>

int main()
{
    GstRTSPUrl *gstUrl = NULL;
    const char* url = "rtsp://10.30.1.163:8554/test.sdp";
    if(gst_rtsp_url_parse(url, &gstUrl) == GST_RTSP_OK) {
        printf("URL PARSE");
        GstRTSPConnection *gstRTSPConnection = NULL;
        if(gst_rtsp_connection_create(gstUrl, &gstRTSPConnection) == GST_RTSP_OK) {
            printf("Connection created\n");
            GstRTSPMessage *message = NULL;
            gst_rtsp_message_new(&message);
            GstRTSPResult result = gst_rtsp_connection_connect_with_response(gstRTSPConnection, NULL, message);
            if(result == GST_RTSP_ETIMEOUT){
                printf("Timeout\n");
            } else if(result == GST_RTSP_OK) {
                printf("Connected\n");
                printf("%s\n", gst_rtsp_connection_get_ip(gstRTSPConnection));
                printf("Is tunelled: %d\n", gst_rtsp_connection_is_tunneled(gstRTSPConnection));
                gst_rtsp_connection_receive(gstRTSPConnection, message, NULL);
            }
        }
    }

    return 0;
}

Body:
Ok. I will handle this. The issue was I need to first send some message to the server according to RTSP protocol. The solution below (with some dump messages):

#include <gstreamer-1.0/gst/rtsp/rtsp.h>
#include <stdio.h>

int main()
{
    GstRTSPUrl *gstUrl = NULL;
    const char* url = "rtsp://10.30.1.163:8554";
    if(gst_rtsp_url_parse(url, &gstUrl) == GST_RTSP_OK) {
        printf("URL PARSE");
        GstRTSPConnection *gstRTSPConnection = NULL;
        if(gst_rtsp_connection_create(gstUrl, &gstRTSPConnection) == GST_RTSP_OK) {
            printf("Connection created\n");
            GstRTSPMessage *message = NULL;
            gst_rtsp_message_new(&message);
            GstRTSPResult result = gst_rtsp_connection_connect_with_response(gstRTSPConnection, NULL, message);
            if(result == GST_RTSP_ETIMEOUT){
                printf("Timeout\n");
            } else if(result == GST_RTSP_OK) {
                printf("Connected\n");
                printf("%s\n", gst_rtsp_connection_get_ip(gstRTSPConnection));
                printf("Is tunelled: %d\n", gst_rtsp_connection_is_tunneled(gstRTSPConnection));

                gst_rtsp_message_new(&message);
                gst_rtsp_message_init_request(message, GST_RTSP_DESCRIBE, "rtsp://10.30.1.163:8554/test.sdp");
                gst_rtsp_message_add_header(message, GST_RTSP_HDR_CSEQ, "1");
                printf("Message Type %d", gst_rtsp_message_get_type(message));

                gst_rtsp_message_dump(message);

                if(gst_rtsp_connection_send(gstRTSPConnection, message, NULL) == GST_RTSP_OK){
                    printf("Message sent");
                }else {
                    printf("Message not sent");
                }
                gst_rtsp_connection_receive(gstRTSPConnection, message, NULL);

                gst_rtsp_message_dump(message);
            }
        }
    }

    return 0;
}


问:
Add different text to the last line of a string - C# LINQ
I want to take an input string and add " ' + " to the end of each line except the last line, on the last line I want to add " ' ; "

The following allows me to add " ' + " to every line:

```<code>string[] outputArr = outputRaw
  .Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
  .Select((stringval, stringindex) => "'" + stringval + " ' + ")
  .ToArray();

this.Output = String.Join(Environment.NewLine, outputArr);
</code>```

Can this be adjusted to identify the last line and add different characters?

答:
I suggest moving " + " from Select into Join: we join lines with " + \r\n" and, finally, add ";" to the end:

```<code>string[] outputArr = outputRaw
   .Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
   .Select((stringval, stringindex) => $"'{stringval}'")
   .ToArray();

this.Output = String.Join(" + " + Environment.NewLine, outputArr) + ";";
</code>```

Body:
I want to take an input string and add " ' + " to the end of each line except the last line, on the last line I want to add " ' ; "

The following allows me to add " ' + " to every line:

string[] outputArr = outputRaw
  .Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
  .Select((stringval, stringindex) => "'" + stringval + " ' + ")
  .ToArray();

this.Output = String.Join(Environment.NewLine, outputArr);

Can this be adjusted to identify the last line and add different characters?

Body:
I suggest moving " + " from Select into Join: we join lines with " + \r\n" and, finally, add ";" to the end:

string[] outputArr = outputRaw
   .Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
   .Select((stringval, stringindex) => $"'{stringval}'")
   .ToArray();

this.Output = String.Join(" + " + Environment.NewLine, outputArr) + ";";


问:
In Java when one interface extends another, why would one redeclare a method in a subinterface?
I've been looking at the JMS API from J2EE and found a strange behavior where certain methods that are declared in an interface (e.g., createQueue in Session) are declared again in the subinterfaces such as QueueSession, and with identical documentation.

Since an subinterface "inherits" all the method declarations of the interface it inherits, and since the JavaDoc tool has no problem sorting out the JavaDocs of the subinterface and creating an "inherited operations" list, I can't figure out what this achieves.

The only think of is that initially the call was in Session, and then moved to QueueSession when the specific subclass was created, though then I would have expected to see something in the documentation of the upperclass. But this is just conjecture.

So the question is:
Is there a convincing reason to redeclare a method in a subinterface?

答:
I have never seen a good reasoning for this.  The best I have seen is that:

It makes it clear what it is without having to see the parent

It makes it easier to change what the class extends without having to figure out what interfaces it should implement

I don't like either suggestion.  I think the likely cause is that while the code was being written the interfaces were written before the abstract classes and the developers didn't bother to remove the duplicate implements.

Never underestimate the laziness of a developer :-)

In the end no harm is done except that at class load time it probably takes a non-noticeable fraction of time longer to load a class with duplicate interfaces.

OwnerDisplayName: Uri

OwnerDisplayName: TofuBeer


问:
PHP Regex dot matches new line alternative
I am come up with a regex to grab all text between 2 HTML tags. This is what I have so far:

<TAG[^>]*>(.*?)</TAG>

In practice, this should work perfectly. But executing it in PHP preg_replace with options: /ims results in the WHOLE string getting matched.

If I remove the /s tag, it works perfectly but the tags have newlines between them. Is there a better way on approaching this?

答:
I don't recommend use regex to match in full HTML, but, you can use the "dottal" flag:
/REGEXP/s

Example:

```<code>$str = "<tag>
fvox
</tag>";

preg_match_all('/<TAG[^>]*>(.*?)</TAG>/is', $str, $r);
print_r($r); //dump</code>```

Body:
I don't recommend use regex to match in full HTML, but, you can use the "dottal" flag:
/REGEXP/s

Example:

$str = "<tag>
fvox
</tag>";

preg_match_all('/<TAG[^>]*>(.*?)</TAG>/is', $str, $r);
print_r($r); //dump


问:
"Variadic enum cases are not supported" swift 5 error
I am getting Variadic enum cases are not supported error in following code. This was compiling and working fine in Swift4, but giving compile time error in Swift5, Xcode 10.2

```<code>enum ModelRule {
        case required(keys: String...) // error: Variadic enum cases are not supported
        case nonEmptyString(keys: String...) // error: Variadic enum cases are not supported
        case emptyString(key: String)
}
</code>```

while the message is very clear, I would like to know why would they remove perfectly working feature? Or am I missing something here?

Also, is there any better solution to above error than following ?
case required(keys: [String])

答:
Variadic parameter used to work on swift 4 but it wasn't intentionally.
Just use arrays

```<code>enum ModelRule {
    case required(keys: [String])
    case nonEmptyString(keys: [String])
    case emptyString(key: String)
}
</code>```

See Swift Release notes

Body:
I am getting Variadic enum cases are not supported error in following code. This was compiling and working fine in Swift4, but giving compile time error in Swift5, Xcode 10.2

enum ModelRule {
        case required(keys: String...) // error: Variadic enum cases are not supported
        case nonEmptyString(keys: String...) // error: Variadic enum cases are not supported
        case emptyString(key: String)
}

while the message is very clear, I would like to know why would they remove perfectly working feature? Or am I missing something here?

Also, is there any better solution to above error than following ?
case required(keys: [String])

Body:
Variadic parameter used to work on swift 4 but it wasn't intentionally.
Just use arrays

enum ModelRule {
    case required(keys: [String])
    case nonEmptyString(keys: [String])
    case emptyString(key: String)
}

See Swift Release notes


问:
then promise Angular 7 - 'then' does not exist on type 'void'
I am using the following function to update an array in Firestore:

component.ts

```<code>crearFavorito(key, e) {
    this.fs.addFavorito(key);
    this.snackBar.open(this.message, this.action, {
      duration: 3000,
    });
  }
</code>```

service.ts

```<code>addFavorito(key) {
    const user = firebase.auth().currentUser;
    this.afs.doc('eventos/' + key).update({
      favoritos: firebase.firestore.FieldValue.arrayUnion(user.uid)
    });
  }
</code>```

This works well when the user is authenticated, but when there is no user logged in I get the following error in the console:

ERROR TypeError: Cannot read property 'uid' of null

Given this what I want to do is redirect it to my login section or show a message that must be authenticated, then I tried the following:

component.ts

```<code>crearFavorito(key, e) {
    this.fs.addFavorito(key)
    .then(() => {
      this.snackBar.open(this.message, this.action, {
        duration: 3000,
      });
    }, error => console.error('error:', error));
  }
</code>```

But I get the following error in then Typescript:

'then' does not exist on type 'void'

Any idea how to achieve this?

答:
simply add return in front of the update call. Here is the updated code

```<code>addFavorito(key) {
  const user = firebase.auth().currentUser;
  return this.afs.doc('eventos/' + key).update({
    favoritos: firebase.firestore.FieldValue.arrayUnion(user.uid)
  });
}
</code>```

For the crearFavorito function to be able to handle the promise, addFavorito needs to return a promise first. Luckily, the document update function of Firebase already returns a promise. So, all you need to do is return it again.

Body:
I am using the following function to update an array in Firestore:

component.ts

crearFavorito(key, e) {
    this.fs.addFavorito(key);
    this.snackBar.open(this.message, this.action, {
      duration: 3000,
    });
  }

service.ts

addFavorito(key) {
    const user = firebase.auth().currentUser;
    this.afs.doc('eventos/' + key).update({
      favoritos: firebase.firestore.FieldValue.arrayUnion(user.uid)
    });
  }

This works well when the user is authenticated, but when there is no user logged in I get the following error in the console:

ERROR TypeError: Cannot read property 'uid' of null

Given this what I want to do is redirect it to my login section or show a message that must be authenticated, then I tried the following:

component.ts

crearFavorito(key, e) {
    this.fs.addFavorito(key)
    .then(() => {
      this.snackBar.open(this.message, this.action, {
        duration: 3000,
      });
    }, error => console.error('error:', error));
  }

But I get the following error in then Typescript:

'then' does not exist on type 'void'

Any idea how to achieve this?

Body:
simply add return in front of the update call. Here is the updated code

addFavorito(key) {
  const user = firebase.auth().currentUser;
  return this.afs.doc('eventos/' + key).update({
    favoritos: firebase.firestore.FieldValue.arrayUnion(user.uid)
  });
}

For the crearFavorito function to be able to handle the promise, addFavorito needs to return a promise first. Luckily, the document update function of Firebase already returns a promise. So, all you need to do is return it again.


问:
Insert statement with subquery which has inner join statement
I have 3 tables in my SQL Server database named College, University, OldSyllabus.

Table College has 1000 rows with columns such as DateOfJoining, studentName

Table University has 50 rows with columns such as DateOfCourseRevision, courseName

I need to write an insert statement to push records in table OldSyllabus by comparing University table DateOfCourseRevision column with College table DateOfJoining column

All records from College table to be inserted into OldSyllabus by comparing the DateOfCourseRevision <= DateOfJoining

Query:

```<code>INSERT INTO [OS].[OldSyllabus] (StudenName, Address)
VALUES
    ((SELECT C.Name
      FROM [COL].[College] AS c
      INNER JOIN [UNI].[University] AS u ON c.CourseName = u.CourseName
                                         AND c.Date <= u.Date),
     (SELECT C.Address
      FROM [COL].[College] AS c
      INNER JOIN [UNI].[University] AS u ON c.CourseName = u.CourseName
                                         AND c.Date <= u.Date))
</code>```

I get an error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

答:
What you're doing here, however, is mixing INSERT ...VALUES and INSERT...SELECT syntax. The documentation provides an example on how to perform a INSERT...SELECT statement: Inserting Data from Other Tables. You need to drop the parenthesis (()) around your SELECT, and remove the VALUES clause. So:

```<code>INSERT INTO [OS].[OldSyllabus] (StudenName) --Should that be StudentName?
SELECT C.Name
FROM [COL].[College] AS c
     INNER JOIN [UNI].[University] AS u ON c.CourseName = u.CourseName
                                       AND c.Date <= u.Date;
</code>```

Body:
I have 3 tables in my SQL Server database named College, University, OldSyllabus.

Table College has 1000 rows with columns such as DateOfJoining, studentName

Table University has 50 rows with columns such as DateOfCourseRevision, courseName

I need to write an insert statement to push records in table OldSyllabus by comparing University table DateOfCourseRevision column with College table DateOfJoining column

All records from College table to be inserted into OldSyllabus by comparing the DateOfCourseRevision <= DateOfJoining

Query:

INSERT INTO [OS].[OldSyllabus] (StudenName, Address)
VALUES
    ((SELECT C.Name
      FROM [COL].[College] AS c
      INNER JOIN [UNI].[University] AS u ON c.CourseName = u.CourseName
                                         AND c.Date <= u.Date),
     (SELECT C.Address
      FROM [COL].[College] AS c
      INNER JOIN [UNI].[University] AS u ON c.CourseName = u.CourseName
                                         AND c.Date <= u.Date))

I get an error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Body:
What you're doing here, however, is mixing INSERT ...VALUES and INSERT...SELECT syntax. The documentation provides an example on how to perform a INSERT...SELECT statement: Inserting Data from Other Tables. You need to drop the parenthesis (()) around your SELECT, and remove the VALUES clause. So:

INSERT INTO [OS].[OldSyllabus] (StudenName) --Should that be StudentName?
SELECT C.Name
FROM [COL].[College] AS c
     INNER JOIN [UNI].[University] AS u ON c.CourseName = u.CourseName
                                       AND c.Date <= u.Date;


问:
Should Builder.build() return a default state?
Using the Builder pattern there is always the question whether the fields do have a default value or not? I cannot find a reliable source where that's clearly defined...

The problem is readability: What is Car.Builder().build() returning? I always need to check the specific implementation of the Builder to see which default values are used. Shouldn't Builder be used to create complex objects which do not have a simple default state by definition?

An alternative would be to check whether all mandatory fields are set inside of the build() method:

```<code>fun build() : Car {
    return if (doors != null && hp != null) Car(doors, hp, color) // color can be null
    else throw IllegalArgumentException("Door count and HP is mandatory!")
}
</code>```

...or is this considered bad practice?

答:
I would not put default values into Car class, but instead put default values to concrete builders.

class SedanBuilder {
    var doors = 4
    var wheels = 4
    var driver = null // we have to set driver

    ... setters ...
    fun build() {

        return Car(wheels, doors, driver)
    }
}
```

<p>and another builder can use another default values</p>

<pre class="lang-kotlin prettyprint-override"><code>class SchumachersCarBuilder {
    var doors = 4
    var wheels = 4
    var driver = Person("Michael")

    ... setters ...
    fun build() {

        return Car(wheels, doors, driver)
    }
}
</code>```

And of course, you have to check all mandatory params inside Car constructor

Body:
Using the Builder pattern there is always the question whether the fields do have a default value or not? I cannot find a reliable source where that's clearly defined...

The problem is readability: What is Car.Builder().build() returning? I always need to check the specific implementation of the Builder to see which default values are used. Shouldn't Builder be used to create complex objects which do not have a simple default state by definition?

An alternative would be to check whether all mandatory fields are set inside of the build() method:

fun build() : Car {
    return if (doors != null && hp != null) Car(doors, hp, color) // color can be null
    else throw IllegalArgumentException("Door count and HP is mandatory!")
}

...or is this considered bad practice?

Body:
I would not put default values into Car class, but instead put default values to concrete builders.

class SedanBuilder {
    var doors = 4
    var wheels = 4
    var driver = null // we have to set driver

    ... setters ...
    fun build() {

        return Car(wheels, doors, driver)
    }
}

and another builder can use another default values

class SchumachersCarBuilder {
    var doors = 4
    var wheels = 4
    var driver = Person("Michael")

    ... setters ...
    fun build() {

        return Car(wheels, doors, driver)
    }
}

And of course, you have to check all mandatory params inside Car constructor


问:
Extract first few alphabets before numbers and skip the rest
I have a strange requirement where we want to extract first few alphabets in a string and skip the rest where there can be combination of alphabets and numbers.
e.g.

Text

```<code>1.  aaaa bbbb ccc 00110011 ddd eee ff 00 99
2.  bbbbbbbbbbbbbbbbbbbbbb 0123 azbe 999999999999999
3.  zfsfzzzzzzzzzz asasas 111 3333333 xxysys ddddd  9090909
4.  Returns the nth field within a delimited string 5555555555 99999999
</code>```

Output

```<code>1.  aaaa bbbb ccc
2.  bbbbbbbbbbbbbbbbbbbbbb
3.  zfsfzzzzzzzzzz asasas
4.  Returns the nth field within a delimited string
</code>```

We are using Hue/Impala and would like to extract all alphabets in first characters or all left characters before a number string starts.

Thank you

答:
If you are able to use regex (since you put it in as a tag) you can use the following to (match until numeric):</p>

```<code>^[^0-9]*
</code>```

Body:
I have a strange requirement where we want to extract first few alphabets in a string and skip the rest where there can be combination of alphabets and numbers.
e.g.

Text

1.  aaaa bbbb ccc 00110011 ddd eee ff 00 99
2.  bbbbbbbbbbbbbbbbbbbbbb 0123 azbe 999999999999999
3.  zfsfzzzzzzzzzz asasas 111 3333333 xxysys ddddd  9090909
4.  Returns the nth field within a delimited string 5555555555 99999999

Output

1.  aaaa bbbb ccc
2.  bbbbbbbbbbbbbbbbbbbbbb
3.  zfsfzzzzzzzzzz asasas
4.  Returns the nth field within a delimited string

We are using Hue/Impala and would like to extract all alphabets in first characters or all left characters before a number string starts.

Thank you

Body:
If you are able to use regex (since you put it in as a tag) you can use the following to (match until numeric):

^[^0-9]*


问:
Failure to set FSO = CreateObject with ExceltoWord! Add-in
I'm using the Excel Add-in ExceltoWord to auto-populate a Word Document from an Excel worksheet. I've followed the instructions from the original developer here.

I'm using the "I created generic bookmark indicators, in Word" and "I put bookmark indicators directly in cells - Left" options with "Delete the Word doc" at the end. When I save settings I get an MS Visual Basic error

Run-time error '429:' ActiveX component can't create object.

I've tried switching different formats of Excel sheet and Word Doc and Word Template as well as leaving the Word Doc closed and opened when saving the configuration.

```<code>Public Function validateFileFolderSelection(ByVal fName As String, fType As String, src As String, bFolderOnly As Boolean) As Boolean

'Dim FSO As FileSystemObject 'early binding
Dim FSO As Object 'late binding

    'Set FSO = New FileSystemObject 'early binding
    Set FSO = CreateObject("Scripting.FileSystemObject") 'late binding

    validateFileFolderSelection = True

    'Test for word or excel filename & that the file exists
    If Trim(fName) = vbNullString Then
        validateFileFolderSelection = False
    ElseIf bFolderOnly Then
        If Not FSO.FolderExists(fName) Then
            validateFileFolderSelection = False
        End If
    ElseIf Not FSO.fileExists(fName) Then
            validateFileFolderSelection = False
    End If

End Function
</code>```

VBA displays an error on Set FSO = CreateObject("Scripting.FileSystemObject") 'late binding.

答:
If you add a Reference to Microsoft Scripting Runtime (VBE > Tools > References...) then enable the "Early Binding" code that you currently have commented out, and your code will work.

To set the reference in the Visual Basic Editor (VBE) go to the Tools menu and select the References... function.

Then from the References dialog that opens, scroll until you locate Microsoft Scripting Runtime, and mark it and then click OK.

In your current code remove the comment marks on the two lines marked as "Early Binding" and apply comment marks on the two lines marked as "Late Binding".

The following is an edit to the original answer because, based on comments, you are continuing to have problems with using FSO (File System Object) code on your system.

Instead of using FSO the following VBA routine will determine if either a specified Directory or File exists. The routine is called "DoesItExist" and I have included an example routine that demonstrates how to call the "DoesItExist" routine.

```<code>Sub MyTestRoutine()
    'this first example tests if a specific file exists
    'including a "False" setting for the dirOnly variable is optional
    If DoesItExist("C:\Users\<userID>\Documents\Test\Mydoc.docx") Then
        Debug.Print "File Exists"
    Else
        Debug.Print "File Does Not Exist"
    End If
    'the next example tests if a directory exists,
    'the "True" setting for the dirOnly variable is required for directories
    If DoesItExist("C:\Users\<userID>\Documents\Test", True) Then
        Debug.Print "Directory Exists"
    Else
        Debug.Print "Directory Does Not Exist"
    End If
End Sub

Public Function DoesItExist(ByRef pathName As String, Optional ByRef dirOnly As Boolean) As Boolean
    'this routine checks if a file or folder exists on the system
    'it runs on either a Windows based version of Office or a Mac version
    'if Mac Office then only for the Office 365, 2016, 2019, or later)
    Select Case dirOnly
        Case True
            If Dir(pathName, vbDirectory) = vbNullString Then
                DoesItExist = False
            Else
                DoesItExist = True
            End If
        Case False
            If Dir(pathName, vbNormal) = vbNullString Then
                DoesItExist = False
            Else
                DoesItExist = True
            End If
    End Select
End Function
</code>```

Body:
I'm using the Excel Add-in ExceltoWord to auto-populate a Word Document from an Excel worksheet. I've followed the instructions from the original developer here.

I'm using the "I created generic bookmark indicators, in Word" and "I put bookmark indicators directly in cells - Left" options with "Delete the Word doc" at the end. When I save settings I get an MS Visual Basic error

Run-time error '429:' ActiveX component can't create object.

I've tried switching different formats of Excel sheet and Word Doc and Word Template as well as leaving the Word Doc closed and opened when saving the configuration.

Public Function validateFileFolderSelection(ByVal fName As String, fType As String, src As String, bFolderOnly As Boolean) As Boolean

'Dim FSO As FileSystemObject 'early binding
Dim FSO As Object 'late binding

    'Set FSO = New FileSystemObject 'early binding
    Set FSO = CreateObject("Scripting.FileSystemObject") 'late binding

    validateFileFolderSelection = True

    'Test for word or excel filename & that the file exists
    If Trim(fName) = vbNullString Then
        validateFileFolderSelection = False
    ElseIf bFolderOnly Then
        If Not FSO.FolderExists(fName) Then
            validateFileFolderSelection = False
        End If
    ElseIf Not FSO.fileExists(fName) Then
            validateFileFolderSelection = False
    End If

End Function

VBA displays an error on Set FSO = CreateObject("Scripting.FileSystemObject") 'late binding.

Body:
If you add a Reference to Microsoft Scripting Runtime (VBE > Tools > References...) then enable the "Early Binding" code that you currently have commented out, and your code will work.

To set the reference in the Visual Basic Editor (VBE) go to the Tools menu and select the References... function.

Then from the References dialog that opens, scroll until you locate Microsoft Scripting Runtime, and mark it and then click OK.

In your current code remove the comment marks on the two lines marked as "Early Binding" and apply comment marks on the two lines marked as "Late Binding".

The following is an edit to the original answer because, based on comments, you are continuing to have problems with using FSO (File System Object) code on your system.

Instead of using FSO the following VBA routine will determine if either a specified Directory or File exists. The routine is called "DoesItExist" and I have included an example routine that demonstrates how to call the "DoesItExist" routine.

Sub MyTestRoutine()
    'this first example tests if a specific file exists
    'including a "False" setting for the dirOnly variable is optional
    If DoesItExist("C:\Users\<userID>\Documents\Test\Mydoc.docx") Then
        Debug.Print "File Exists"
    Else
        Debug.Print "File Does Not Exist"
    End If
    'the next example tests if a directory exists,
    'the "True" setting for the dirOnly variable is required for directories
    If DoesItExist("C:\Users\<userID>\Documents\Test", True) Then
        Debug.Print "Directory Exists"
    Else
        Debug.Print "Directory Does Not Exist"
    End If
End Sub

Public Function DoesItExist(ByRef pathName As String, Optional ByRef dirOnly As Boolean) As Boolean
    'this routine checks if a file or folder exists on the system
    'it runs on either a Windows based version of Office or a Mac version
    'if Mac Office then only for the Office 365, 2016, 2019, or later)
    Select Case dirOnly
        Case True
            If Dir(pathName, vbDirectory) = vbNullString Then
                DoesItExist = False
            Else
                DoesItExist = True
            End If
        Case False
            If Dir(pathName, vbNormal) = vbNullString Then
                DoesItExist = False
            Else
                DoesItExist = True
            End If
    End Select
End Function


问:
How to change the color of fixed navigation links when it reaches a certain section?
I'm trying to figure out how to change the color of the links in my fixed navigation (placed on the side of the page) when it reaches a certain section on the page (because the background of that section is the same color as the links in my navigation).

I am a jQuery newbie, so I don't really know how to go about this. I tried this, naively thinking it might work (but, as you guessed it, it didn't):

```<code>if ($('.fixednav').offset().top == $('.intro-section').offset().top) {
    $('.fixednav a').css('color', '#ececef');
}
</code>```

If anyone could give me a hint, I'd be really grateful!

答:
Based on Godinall answer I have created more dynamic and reusable function.
You can define multiple sections elements classes / id as well as links from navigations.

JSFiddle http://jsfiddle.net/djstojadin/twmk1u4v/246/

Body:
I'm trying to figure out how to change the color of the links in my fixed navigation (placed on the side of the page) when it reaches a certain section on the page (because the background of that section is the same color as the links in my navigation).

I am a jQuery newbie, so I don't really know how to go about this. I tried this, naively thinking it might work (but, as you guessed it, it didn't):

if ($('.fixednav').offset().top == $('.intro-section').offset().top) {
    $('.fixednav a').css('color', '#ececef');
}

If anyone could give me a hint, I'd be really grateful!


问:
Conversion of string to integer, then again to string
I am on a project developing an app on Android. Here I have to find a sum between two numbers defined as Strings and then display them on a textview. But my app is crashing. Below is my code. Is it optimal?

```<code>      String price=Place_View.prices[spinner1.getSelectedItemPosition()];
            String fare=Cars.SUVFare[spinner2.getSelectedItemPosition()];
            String result="";
            int calc1=Integer.parseInt(price);
            int calc2=Integer.parseInt(fare);
            int calc3=calc1+calc2;
            result=Integer.toString(calc3);
            Price.setText(result);

        }
    });
</code>```

spinner1:

```<code>public class Place_View {
public static final String[] locName = {"Sivasagar", "Jorhat", "Tinsukia", "Mohanbari", "Pasighat", "Digboi", "Majuli"};

public static final String[] prices = {"2625.00","3200.00","2000.00","500.00","4000.00","2800.00","4000.00"};
}
</code>```

spinner 2:

```<code>public class Cars {
             public static final String[] SUV = {"Mahindra XUV", "Renault Duster", "Hyundai Creta", "Nissan Terrano", "Maruti Suzuki Brezza"};
                 public static final String[] SUVFare={"1000","800","800","750","650"};
}
</code>```

Now I have to add the values of the strings prices and SUVFare when selected one of the both and put them on the TextView Price. Don't know how to post logcat so put the classes I made custom.

答:
New answer

You're probably trying to do something like this:

```<code>String price = Place_View.prices[spinner1.getSelectedItemPosition()];
String fare = Cars.SUVFare[spinner2.getSelectedItemPosition()];
String result="";
float calc1=Float.parseFloat(price);   //Note: float
int calc2=Integer.parseInt(fare);
float calc3=calc1+calc2;               //Note: float
result=Float.toString(calc3);          //Note: Float
Price.setText(result);
</code>```

A full example:

```<code>public class MainActivity extends AppCompatActivity {

    TextView Price;
    Spinner spinner1;
    Spinner spinner2;

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

        Price = findViewById(R.id.tvPrice);
        spinner1 = findViewById(R.id.spinner1);
        spinner2 = findViewById(R.id.spinner2);

        ArrayAdapter<String> adapterLocation = new ArrayAdapter<String>
                (this, android.R.layout.simple_spinner_item, Place_View.locName);

        adapterLocation.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner1.setAdapter(adapterLocation);

        ArrayAdapter<String> adapterCar = new ArrayAdapter<String>
                (this, android.R.layout.simple_spinner_item, Cars.SUV);

        adapterCar.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner2.setAdapter(adapterCar);

        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                String price = Place_View.prices[spinner1.getSelectedItemPosition()];
                String fare = Cars.SUVFare[spinner2.getSelectedItemPosition()];
                String result="";
                float calc1=Float.parseFloat(price);
                int calc2=Integer.parseInt(fare);
                float calc3=calc1+calc2;
                result=Float.toString(calc3);
                Price.setText(result);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                String price = Place_View.prices[spinner1.getSelectedItemPosition()];
                String fare = Cars.SUVFare[spinner2.getSelectedItemPosition()];
                String result="";
                float calc1=Float.parseFloat(price);
                int calc2=Integer.parseInt(fare);
                float calc3=calc1+calc2;
                result=Float.toString(calc3);
                Price.setText(result);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

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

Old answer

As Quick learner commented, we could be more helpful if you would post the error in your logcat.

I have a couple of questions about your code.

Are you sure you want to use:

```<code>getSelectedItemPosition()
</code>```

Because this gives you the position of the clicked item (0 for the first item, 1 for the second, etc.)

```<code>getItemAtPosition(position)
</code>```

Above function will give you the value at the clicked position.

I do not completely understand what this line does

```<code>String price=Place_View.prices[spinner1.getSelectedItemPosition()];
</code>```

Are you referencing an array inside a view?

What is Price? And are you referencing it the right way?

Body:
I am on a project developing an app on Android. Here I have to find a sum between two numbers defined as Strings and then display them on a textview. But my app is crashing. Below is my code. Is it optimal?

      String price=Place_View.prices[spinner1.getSelectedItemPosition()];
            String fare=Cars.SUVFare[spinner2.getSelectedItemPosition()];
            String result="";
            int calc1=Integer.parseInt(price);
            int calc2=Integer.parseInt(fare);
            int calc3=calc1+calc2;
            result=Integer.toString(calc3);
            Price.setText(result);

        }
    });

spinner1:

public class Place_View {
public static final String[] locName = {"Sivasagar", "Jorhat", "Tinsukia", "Mohanbari", "Pasighat", "Digboi", "Majuli"};

public static final String[] prices = {"2625.00","3200.00","2000.00","500.00","4000.00","2800.00","4000.00"};
}

spinner 2:

public class Cars {
             public static final String[] SUV = {"Mahindra XUV", "Renault Duster", "Hyundai Creta", "Nissan Terrano", "Maruti Suzuki Brezza"};
                 public static final String[] SUVFare={"1000","800","800","750","650"};
}

Now I have to add the values of the strings prices and SUVFare when selected one of the both and put them on the TextView Price. Don't know how to post logcat so put the classes I made custom.

Body:
New answer

You're probably trying to do something like this:

String price = Place_View.prices[spinner1.getSelectedItemPosition()];
String fare = Cars.SUVFare[spinner2.getSelectedItemPosition()];
String result="";
float calc1=Float.parseFloat(price);   //Note: float
int calc2=Integer.parseInt(fare);
float calc3=calc1+calc2;               //Note: float
result=Float.toString(calc3);          //Note: Float
Price.setText(result);

A full example:

public class MainActivity extends AppCompatActivity {

    TextView Price;
    Spinner spinner1;
    Spinner spinner2;

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

        Price = findViewById(R.id.tvPrice);
        spinner1 = findViewById(R.id.spinner1);
        spinner2 = findViewById(R.id.spinner2);

        ArrayAdapter<String> adapterLocation = new ArrayAdapter<String>
                (this, android.R.layout.simple_spinner_item, Place_View.locName);

        adapterLocation.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner1.setAdapter(adapterLocation);

        ArrayAdapter<String> adapterCar = new ArrayAdapter<String>
                (this, android.R.layout.simple_spinner_item, Cars.SUV);

        adapterCar.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner2.setAdapter(adapterCar);

        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                String price = Place_View.prices[spinner1.getSelectedItemPosition()];
                String fare = Cars.SUVFare[spinner2.getSelectedItemPosition()];
                String result="";
                float calc1=Float.parseFloat(price);
                int calc2=Integer.parseInt(fare);
                float calc3=calc1+calc2;
                result=Float.toString(calc3);
                Price.setText(result);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                String price = Place_View.prices[spinner1.getSelectedItemPosition()];
                String fare = Cars.SUVFare[spinner2.getSelectedItemPosition()];
                String result="";
                float calc1=Float.parseFloat(price);
                int calc2=Integer.parseInt(fare);
                float calc3=calc1+calc2;
                result=Float.toString(calc3);
                Price.setText(result);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}

Old answer

As Quick learner commented, we could be more helpful if you would post the error in your logcat.

I have a couple of questions about your code.

Are you sure you want to use:

getSelectedItemPosition()

Because this gives you the position of the clicked item (0 for the first item, 1 for the second, etc.)

getItemAtPosition(position)

Above function will give you the value at the clicked position.

I do not completely understand what this line does

String price=Place_View.prices[spinner1.getSelectedItemPosition()];

Are you referencing an array inside a view?

What is Price? And are you referencing it the right way?


问:
Why the code doesn't recognize the assigned variable?
I am trying to write a program in Python 3 that takes an int year larger than 1970 as an input and returns the increase in temperature from 1970 until that year. The formulas and constants are given. Python throws me an error:

```<code>File "4.5.py", line 28, in <module>
    int_years = int_year - 1970
NameError: name 'int_year' is not defined
</code>```

I am a beginner in Python so I have browsed possible solutions, but could not find any working ones.

```<code>def user_input():
    while True:
        int_year = int(input("Please enter a year greater than 1970 " ))
        try:
            if int_year > 1970:
                break
            else:
                print("Please enter a year greater than 1970")
        except ValueError:
            print ("It is not a valid year. Try again. ")
    return int_year

"""CO2 level of January 1970"""
c0 = 325.03

"""Current levels of CO2"""
c1 = 411.97

"""Difference in CO2 levels between 1970 and now"""
differenceCO = c1-c0

"""The average CO2 increase per year since 1970"""
per_year_changedCO = ((differenceCO)/(2019-1970))

"""Diffrence in years between 1970 and user input year"""
int_years = int_year - 1970

"""A projected CO2 level in user input year"""
int_year_changedCO = c0+((int_years)*(per_year_changedCO))

"""A projected RF in any year"""
RF = 5.35*(math.log((int_year_changedCO)/(c0)))

"""Increase in temperature from 1970 to user input year"""
def predict_increase():
  temp_int_year = 0.5 * RF
  return temp_int_year

print(temp_int_year)
</code>```

I expect the program to recognize the variables I use in functions. Overall, I will appreciate any comments on the code.

答:
By the time you execute the line int_years = int_year - 1970, you haven't defined int_year in scope. The only place you've used it up to that point is within the user_input() function - but variables defined within functions are only defined within the functions - not outside of them. To get the value of int_year outside of the function, you need to call the function:

```<code>int_year = user_input()
int_years = int_year - 1970
</code>```

or simply do them both at once:

```<code>int_years = user_input() - 1970
</code>```

Body:
I am trying to write a program in Python 3 that takes an int year larger than 1970 as an input and returns the increase in temperature from 1970 until that year. The formulas and constants are given. Python throws me an error:

File "4.5.py", line 28, in <module>
    int_years = int_year - 1970
NameError: name 'int_year' is not defined

I am a beginner in Python so I have browsed possible solutions, but could not find any working ones.

def user_input():
    while True:
        int_year = int(input("Please enter a year greater than 1970 " ))
        try:
            if int_year > 1970:
                break
            else:
                print("Please enter a year greater than 1970")
        except ValueError:
            print ("It is not a valid year. Try again. ")
    return int_year

"""CO2 level of January 1970"""
c0 = 325.03

"""Current levels of CO2"""
c1 = 411.97

"""Difference in CO2 levels between 1970 and now"""
differenceCO = c1-c0

"""The average CO2 increase per year since 1970"""
per_year_changedCO = ((differenceCO)/(2019-1970))

"""Diffrence in years between 1970 and user input year"""
int_years = int_year - 1970

"""A projected CO2 level in user input year"""
int_year_changedCO = c0+((int_years)*(per_year_changedCO))

"""A projected RF in any year"""
RF = 5.35*(math.log((int_year_changedCO)/(c0)))

"""Increase in temperature from 1970 to user input year"""
def predict_increase():
  temp_int_year = 0.5 * RF
  return temp_int_year

print(temp_int_year)

I expect the program to recognize the variables I use in functions. Overall, I will appreciate any comments on the code.

Body:
By the time you execute the line int_years = int_year - 1970, you haven't defined int_year in scope. The only place you've used it up to that point is within the user_input() function - but variables defined within functions are only defined within the functions - not outside of them. To get the value of int_year outside of the function, you need to call the function:

int_year = user_input()
int_years = int_year - 1970

or simply do them both at once:

int_years = user_input() - 1970


问:
Use aggregation only on rows where count(ID) is greater than one
Hi I have the following table

Cash_table

```<code>ID          Cash   Rates
1           50   3
2           100  4
3           70   10
3           60   10
4           13   7
5           20   8
5           10   10
6           10   5
</code>```

What I want as a result is to cumulate all the entries that have a Count(id)>1 like this:

```<code>ID          New_Cash            New_Rates
1           50                  3
2           100                 4
3           (70+60)/(10+10)     10+10
4           13                  7
5           (20+10)/(8+10)      8+10
6           10                  5
</code>```

So I only want to change the rows where Count(id)>1 and leave the rest like it was.

For the rows with count(id)>1 I want to sum up the rates and take the sum of the cash and divide it by the sum of the rates. The Rates alone aren't a problem since I can sum them up and group by id and get the desired result.

The problem is with the cash column:

I am trying to do it with a case statement but it isn't working:

```<code>   select id, sum(rates) as new_rates, case
   when count(id)>1 then sum(cash)/nullif(sum(rates),0))
   else cash
   end as new_cash
   from Cash_table
   group by id
</code>```

答:
You only need group by id and aggregate:

```<code> select
   id,
   sum(cash) / (case count(*) when 1 then 1 else sum(rates) end) as new_cash,
   sum(rates) as new_rates
 from Cash_table
 group by id
 order by id
</code>```

See the demo.

Body:
Hi I have the following table

Cash_table

ID          Cash   Rates
1           50   3
2           100  4
3           70   10
3           60   10
4           13   7
5           20   8
5           10   10
6           10   5

What I want as a result is to cumulate all the entries that have a Count(id)>1 like this:

ID          New_Cash            New_Rates
1           50                  3
2           100                 4
3           (70+60)/(10+10)     10+10
4           13                  7
5           (20+10)/(8+10)      8+10
6           10                  5

So I only want to change the rows where Count(id)>1 and leave the rest like it was.

For the rows with count(id)>1 I want to sum up the rates and take the sum of the cash and divide it by the sum of the rates. The Rates alone aren't a problem since I can sum them up and group by id and get the desired result.

The problem is with the cash column:

I am trying to do it with a case statement but it isn't working:

   select id, sum(rates) as new_rates, case
   when count(id)>1 then sum(cash)/nullif(sum(rates),0))
   else cash
   end as new_cash
   from Cash_table
   group by id

Body:
You only need group by id and aggregate:

 select
   id,
   sum(cash) / (case count(*) when 1 then 1 else sum(rates) end) as new_cash,
   sum(rates) as new_rates
 from Cash_table
 group by id
 order by id

See the demo.


问:
logging in a table like pm2 with nodeJS
I want to format all of my script's logs into a table for clarity purposes. Kind of what pm2 (process manager 2) does atm for example.

As of today I use console.table(logs) where logs is an object of variables I want to keep track of. It works great but I want to get rid of the trailing \n that console.table includes.

I would want to do something like: process.stdout.write(table(logs)) where I don't have to create the table function myself.

I tried to find the source code of console.table to copy it and remove the trailing newline as a utils function without success. any idea?

答: The npm package c-log does a wonderful job at this : npm c-log </p>

Title: logging in a table like pm2 with nodeJS


答:
The problem is here:

return int_year

By inserting this instruction, you tell the interpreter to return the value int_year has at that moment. Any further usage of this variable leads to an error, because the variable is no longer defined

Title: Why the code doesn't recognize the assigned variable?


问:
Break iteration (each) in Svelte?
Is it possible to break iteration in Svelte or limit like in angular (ng-repeat="items in item | limitTo:4")?
For example:

```<code>{#each items as item, i}
  ...
  {#if i > 4}
    {:break}  <--- break here
  {/if}
  ...
{/each}
</code>```

答:
Svelte currently has no special syntax for breaks or ranges. (here's a pending proposal) A common idiom is to use a {length: N} object as the #each parameter, which usually performs better than creating new arrays every render.

{#each {length: 4} as _, i} {items[i]} {/each}

Here are some other patterns that work:

    {#each {length: 4} as _, i}
        {items[i]}
    {/each}

    {#each items.slice(0, 4) as item}
        {item}
    {/each}

    {#each filteredItems as item}
        {item}
    {/each}

    {#each filterItems(items) as item}
        {item}
    {/each}

```

Title: Break iteration (each) in Svelte?

Body:
Is it possible to break iteration in Svelte or limit like in angular (ng-repeat="items in item | limitTo:4")?
For example:

{#each items as item, i}
  ...
  {#if i > 4}
    {:break}  <--- break here
  {/if}
  ...
{/each}

Body:
Svelte currently has no special syntax for breaks or ranges. (here's a pending proposal) A common idiom is to use a {length: N} object as the #each parameter, which usually performs better than creating new arrays every render.

{#each {length: 4} as _, i} {items[i]} {/each}

Here are some other patterns that work:

<script>
    let items = ['a', 'b', 'c', 'd', 'e'];
    $: filteredItems = items.slice(0, 4);
    const filterItems = (i) => i.slice(0, 4);
</script>

<div>
    {#each {length: 4} as _, i}
        {items[i]}
    {/each}
</div>
<div>
    {#each items.slice(0, 4) as item}
        {item}
    {/each}
</div>
<div>
    {#each filteredItems as item}
        {item}
    {/each}
</div>
<div>
    {#each filterItems(items) as item}
        {item}
    {/each}
</div>


问:
Alternative to using subqueries in SQL statements?
I have two tables:

```<code>TableA: (a temporary table)
ItemId (int)

TableB:
ItemId (int), ParentID (int)
</code>```

I want to retrieve all items in Table A where the ParentID of any of the items in Table A doesn't exist as an ItemID. (i.e. I want to get the root of the items in TableA)

This query does what I want:

```<code>SELECT a.ItemID
FROM TableA a
INNER JOIN TableB b ON a.ItemId = b.ItemID
WHERE b.ParentID NOT IN ( SELECT * from TableA )
</code>```

as does this one:

```<code>SELECT b.ItemID
FROM TableB b
WHERE b.ItemID IN ( SELECT * FROM TableA)
AND b.ParentID NOT IN ( SELECT * FROM TableA )
</code>```

I am not satisfied with either of the queries, particularly because of the use of NOT IN/IN. Is there a way to do this without them? Perhaps a cleaner way that doesn't require subqueries?

Sample Data:

```<code>Table A
-------
2
3
5
6

Table B
--------
1 | NULL
2 | 1
3 | 1
4 | 3
5 | 3
6 | 3
</code>```

Desired Result:

```<code>2
3
</code>```

Thanks

答:
Take a look at Select all rows from one table that don't exist in another table to see 5 different ways to do this kind of query by using

NOT IN

NOT EXISTS

LEFT and RIGHT JOIN

OUTER APPLY (2005+)

EXCEPT (2005+)

Here is a script that you can run

```<code>CREATE TABLE #TableA( ItemId int)

INSERT #TableA values(1)
INSERT #TableA values(2)
INSERT #TableA values(3)
INSERT #TableA values(4)
INSERT #TableA values(5)
INSERT #TableA values(6)

CREATE TABLE #TableB( ItemId int, ParentID int)
INSERT #TableB values(1,1)
INSERT #TableB values(2,2)
INSERT #TableB values(4,3)
INSERT #TableB values(5,4)
</code>```

this will do it for parent

```<code>SELECT a.ItemID
FROM #TableA a
LEFT JOIN #TableB b ON a.ItemId = b.ParentID
WHERE b.ItemID IS NULL

SELECT a.ItemID
FROM #TableA a
WHERE NOT EXISTS (SELECT 1 FROM #TableB b WHERE a.ItemId = b.ParentID)
</code>```

Output

```<code>ItemID
5
6
</code>```

Body:
I have two tables:

TableA: (a temporary table)
ItemId (int)

TableB:
ItemId (int), ParentID (int)

I want to retrieve all items in Table A where the ParentID of any of the items in Table A doesn't exist as an ItemID. (i.e. I want to get the root of the items in TableA)

This query does what I want:

SELECT a.ItemID
FROM TableA a
INNER JOIN TableB b ON a.ItemId = b.ItemID
WHERE b.ParentID NOT IN ( SELECT * from TableA )

as does this one:

SELECT b.ItemID
FROM TableB b
WHERE b.ItemID IN ( SELECT * FROM TableA)
AND b.ParentID NOT IN ( SELECT * FROM TableA )

I am not satisfied with either of the queries, particularly because of the use of NOT IN/IN. Is there a way to do this without them? Perhaps a cleaner way that doesn't require subqueries?

Sample Data:

Table A
-------
2
3
5
6

Table B
--------
1 | NULL
2 | 1
3 | 1
4 | 3
5 | 3
6 | 3

Desired Result:

2
3

Thanks

Body:
Take a look at Select all rows from one table that don't exist in another table to see 5 different ways to do this kind of query by using

NOT IN

NOT EXISTS

LEFT and RIGHT JOIN

OUTER APPLY (2005+)

EXCEPT (2005+)

Here is a script that you can run

CREATE TABLE #TableA( ItemId int)

INSERT #TableA values(1)
INSERT #TableA values(2)
INSERT #TableA values(3)
INSERT #TableA values(4)
INSERT #TableA values(5)
INSERT #TableA values(6)

CREATE TABLE #TableB( ItemId int, ParentID int)
INSERT #TableB values(1,1)
INSERT #TableB values(2,2)
INSERT #TableB values(4,3)
INSERT #TableB values(5,4)

this will do it for parent

SELECT a.ItemID
FROM #TableA a
LEFT JOIN #TableB b ON a.ItemId = b.ParentID
WHERE b.ItemID IS NULL

SELECT a.ItemID
FROM #TableA a
WHERE NOT EXISTS (SELECT 1 FROM #TableB b WHERE a.ItemId = b.ParentID)

Output

ItemID
5
6


问:
How to do a running median of length 5
How can I calculate a running median of length 5?  I tried the smooth function but it only does running median of length 3.

答:
In base R from stats package for those who does not want to install additional packages :

```<code>runmed(1:100, 5)
</code>```

The parameter endrule allows to control strategy for the beginning and the end values.

```<code>runmed(1:10, 5, endrule = "keep")
> [1]  1  2  3  4  5  6  7  8  9 10

runmed(1:10, 5, endrule = "constant")
> [1] 3 3 3 4 5 6 7 8 8 8

runmed(1:10, 5, endrule = "median")
> [1]  1  2  3  4  5  6  7  8  9 10
</code>```

Title: How to do a running median of length 5

Body:
In base R from stats package for those who does not want to install additional packages :

runmed(1:100, 5)

The parameter endrule allows to control strategy for the beginning and the end values.

runmed(1:10, 5, endrule = "keep")
> [1]  1  2  3  4  5  6  7  8  9 10

runmed(1:10, 5, endrule = "constant")
> [1] 3 3 3 4 5 6 7 8 8 8

runmed(1:10, 5, endrule = "median")
> [1]  1  2  3  4  5  6  7  8  9 10


问:
String buffer fails to write data to database table
I am porting a mongo database over to a PostgreSQL one and I came across with an issue. I am using psycopg2's COPY_FROM, which takes as arguments a file object, the table to write to and other optional arguments. My original code looked like the following:

```<code>records = '\n'.join(','.join([row['id'], row['att1'], row['att3']]) for row in data)
fio = io.StringIO(records)
cursor.copy_from(fio, 'mytable', sep=',')
postgres.commit()
</code>```

The code above works fine but fails for columns containing commas (splits by commas). Thus, I want to escape all commas and other punctuation that may interfere. For this, I used Python's csv module which handles this and got to the following code:

```<code>fio = io.StringIO()
writer = csv.writer(fio)
writer.writerows([row['id'], row['att1'], row['att3']]) for row in data)
cursor.copy_from(fio, 'mytable', sep=',')
postgres.commit()
</code>```

Using the code above, mytable remains empty no matter what. I tried iterating fio after writing the rows and the content is the same as in the initial code snippet (using ','.join). I also checked the size of the object and it has about the same size in both snippets after writing the records.

What am I missing here? Why isn't the data being written to the table in the second example?

答:
After writing to fio you are at the end of the file. You need to return to the start for when it is read by psycopg2.

Easy modification, like so:

```<code>fio = io.StringIO()
writer = csv.writer(fio)
writer.writerows([row['id'], row['att1'], row['att3']]) for row in data)

fio.seek(0) # Return to beginning of file.

cursor.copy_from(fio, 'mytable', sep=',')
postgres.commit()
</code>```

Body:
I am porting a mongo database over to a PostgreSQL one and I came across with an issue. I am using psycopg2's COPY_FROM, which takes as arguments a file object, the table to write to and other optional arguments. My original code looked like the following:

records = '\n'.join(','.join([row['id'], row['att1'], row['att3']]) for row in data)
fio = io.StringIO(records)
cursor.copy_from(fio, 'mytable', sep=',')
postgres.commit()

The code above works fine but fails for columns containing commas (splits by commas). Thus, I want to escape all commas and other punctuation that may interfere. For this, I used Python's csv module which handles this and got to the following code:

fio = io.StringIO()
writer = csv.writer(fio)
writer.writerows([row['id'], row['att1'], row['att3']]) for row in data)
cursor.copy_from(fio, 'mytable', sep=',')
postgres.commit()

Using the code above, mytable remains empty no matter what. I tried iterating fio after writing the rows and the content is the same as in the initial code snippet (using ','.join). I also checked the size of the object and it has about the same size in both snippets after writing the records.

What am I missing here? Why isn't the data being written to the table in the second example?

Body:
After writing to fio you are at the end of the file. You need to return to the start for when it is read by psycopg2.

Easy modification, like so:

fio = io.StringIO()
writer = csv.writer(fio)
writer.writerows([row['id'], row['att1'], row['att3']]) for row in data)

fio.seek(0) # Return to beginning of file.

cursor.copy_from(fio, 'mytable', sep=',')
postgres.commit()