问:
Why am I getting 'NameError: name 'alarmthresh5' not defined in code with Function and Thread
I am a beginner and am getting this error when I run my code in main_odroid.py:

'NameError: name 'alarmthresh5' is not defined'

When i run this code:

```<code>from threading import Thread

def func3():
    Import main_odroid
    global alarmthresh5
    alarmthresh5 = 1.45 * stddev2

[...]
if floats[1] > alarmthresh5:
   wpi.digitalWrite(1, 1)
[...]
Thread(target = func3).start()
[...]
</code>```

[...] means the rest of the (irrelevant) code that I excluded for clarity.

I used the search function and tried different answers but it did not solve the problem.
Thanks I and I am interested in your answers.

EDIT: scope of variable alarmthresh5 is global i think, because I typed 'global alarmthresh5' in func3.

EDIT2: The entire code

```<code>import subprocess
from subprocess import Popen, PIPE
import os
import odroid_wiringpi as wpi
from collections import deque
import time
import datetime
from threading import Thread
from math import sqrt

sysdamping = 10
freqdamping = 14
totalbins = 2000

#Functions
def average(p): return sum(p) / float(len(p))
def variance(p): return list(map(lambda x: (x - average(p))**2, p))
def std_dev(p): return sqrt(average(variance(p)))

wpi.wiringPiSetup()
wpi.pinMode(1, 1)
wpi.pinMode(5, 1)
wpi.pinMode(27, 1)
wpi.pinMode(31, 1)
wpi.pinMode(23, 1)
wpi.pinMode(11, 1)
wpi.digitalWrite(23, 0)
wpi.digitalWrite(11, 0)
wpi.pinMode(2, 1)
wpi.pinMode(7, 1)
wpi.digitalWrite(2, 0)
wpi.digitalWrite(7, 0)

wpi.pinMode(9, 1)
wpi.digitalWrite(9, 0)
time.sleep(0.1)

wpi.pullUpDnControl(30, 2)

os.system("killall -9 soapy_power -q")
time.sleep(0.1)

def func2():
    exec(open("/home/odroid/rtl-power-fftw/build/deactiveer.py").read())

def func3():
    import main_odroid
    global alarmthresh1
    global alarmthresh2
    global alarmthresh3
    global alarmthresh4
    global alarmthresh5
    global Lijst
    alarmthresh1 = (average(rolling[i]) + 1.45 * stddev2)
    alarmthresh2 = alarmthresh1 + 2
    alarmthresh3 = alarmthresh2 + 2
    alarmthresh4 = alarmthresh3 + 2
    alarmthresh5 = alarmthresh4 + 2
    Lijst = [381843000.0, 382242000.0, 382245000.0, 382248000.0, 382254000.0, 382257000.0, 382305000.0, 382308000.0, 382320000.0, 382323000.0, 382326000.0, 382389000.0, 382392000.0, 382557000.0, 382560000.0, 382671000.0, 383157000.0, 383454000.0, 383457000.0, 383469000.0, 383472000.0, 383997000.0, 384000000.0, 384003000.0, 384006000.0]

def func4():
    import main_odroid
    global stddev2
    stddev2 = std_dev(sweep)

def func1():
    cmd = ["/home/odroid/.local/bin/soapy_power", "-f", "433M", "-r", "6M", "--force-rate", "-q", "-c", "-b", "2000", "-F", "rtl_power_fftw"]
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)

    rolling = []
    i = 0
    rolling_avg = deque([])

    sweep = deque([], maxlen=1500)
    stddev = 12
    totalbins = 2000

    # Let's see what's going on with rtl_power_fftw
    for line in iter(p.stdout.readline, b''):
        #Ignore garbage output
        if not (b'#' in line or not line.strip()):
            floats = list(map(float, line.split()))

            # Create 2D array
            if len(rolling) < totalbins:
                rolling.append(deque([]))
            rolling[i].append(floats[1])
            sweep.append(floats[1])
            # Let's start filtering...

            if len(rolling[i]) >= freqdamping:
                rolling[i].popleft()
                print("ref 5")
                input_state3 = wpi.digitalRead(9)

                if floats[1] > alarmthresh5 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst:   # Led 5
                    wpi.digitalWrite(1, 1)
                    if input_state3 == 0:
                        wpi.digitalWrite(9, 1) # Buzzer proxy
                        wpi.digitalWrite(31, 1) # Buzzer ON
                        print(round(floats[0]), round(floats[1]), alarmthresh5, "ref2")
                        Thread(target = func2).start()
                if floats[1] > alarmthresh1 and floats[0] in [380310000.0, 381444000.0, 381579000.0, 381780000.0, 381783000.0, 382110000.0, 382836000.0, 382881000.0, 382884000.0, 382887000.0, 382890000.0, 382893000.0, 383037000.0, 383085000.0, 383340000.0, 383460000.0, 384258000.0, 384261000.0, 384264000.0]:
                    if input_state3 == 0:
                        wpi.digitalWrite(9, 1) # Buzzer proxy
                        wpi.digitalWrite(31, 1) # Buzzer ON
                        print(round(floats[0]), round(floats[1]), alarmthresh1, "ref1")
                        Thread(target = func2).start()

                if floats[1] > alarmthresh4 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst:     # Led 4
                    wpi.digitalWrite(7, 1)
                if floats[1] > alarmthresh3 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst:     # Led 3
                    wpi.digitalWrite(23, 1)
                if floats[1] > alarmthresh2 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst:     # Led 2
                    wpi.digitalWrite(5, 1)
                if floats[1] > alarmthresh1 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst:     # Led 1
                    input_state = wpi.digitalRead(27)
                    if input_state == 0:
                        wpi.digitalWrite(27, 1)
                        Thread(target = func2).start()

            # Increment or reset indexer (i)
            if i < totalbins - i: i = i + 1
            else:
                i = 0
                Thread(target = func4).start()  # Set stddev2
                Thread(target = func3).start()  # Set alarmthresh1 - alarmthresh5
                print("ref 6")

    p.stdout.close()
    p.wait()
Thread(target = func1).start()
</code>```

Ref 6 prints before ref 5, so func3 is started before alarmthresh5 is called.

答: Can you specify scope of variable alarmthresh5. Try to add variable in function definition only, something like this: def func3(alarmthresh5=valueyouwantotput)</p>

Body:
I am a beginner and am getting this error when I run my code in main_odroid.py:

'NameError: name 'alarmthresh5' is not defined'

When i run this code:

from threading import Thread

def func3():
    Import main_odroid
    global alarmthresh5
    alarmthresh5 = 1.45 * stddev2

[...]
if floats[1] > alarmthresh5:
   wpi.digitalWrite(1, 1)
[...]
Thread(target = func3).start()
[...]

[...] means the rest of the (irrelevant) code that I excluded for clarity.

I used the search function and tried different answers but it did not solve the problem.
Thanks I and I am interested in your answers.

EDIT: scope of variable alarmthresh5 is global i think, because I typed 'global alarmthresh5' in func3.

EDIT2: The entire code

import subprocess
from subprocess import Popen, PIPE
import os
import odroid_wiringpi as wpi
from collections import deque
import time
import datetime
from threading import Thread
from math import sqrt

sysdamping = 10
freqdamping = 14
totalbins = 2000

#Functions
def average(p): return sum(p) / float(len(p))
def variance(p): return list(map(lambda x: (x - average(p))**2, p))
def std_dev(p): return sqrt(average(variance(p)))

wpi.wiringPiSetup()
wpi.pinMode(1, 1)
wpi.pinMode(5, 1)
wpi.pinMode(27, 1)
wpi.pinMode(31, 1)
wpi.pinMode(23, 1)
wpi.pinMode(11, 1)
wpi.digitalWrite(23, 0)
wpi.digitalWrite(11, 0)
wpi.pinMode(2, 1)
wpi.pinMode(7, 1)
wpi.digitalWrite(2, 0)
wpi.digitalWrite(7, 0)

wpi.pinMode(9, 1)
wpi.digitalWrite(9, 0)
time.sleep(0.1)

wpi.pullUpDnControl(30, 2)

os.system("killall -9 soapy_power -q")
time.sleep(0.1)

def func2():
    exec(open("/home/odroid/rtl-power-fftw/build/deactiveer.py").read())

def func3():
    import main_odroid
    global alarmthresh1
    global alarmthresh2
    global alarmthresh3
    global alarmthresh4
    global alarmthresh5
    global Lijst
    alarmthresh1 = (average(rolling[i]) + 1.45 * stddev2)
    alarmthresh2 = alarmthresh1 + 2
    alarmthresh3 = alarmthresh2 + 2
    alarmthresh4 = alarmthresh3 + 2
    alarmthresh5 = alarmthresh4 + 2
    Lijst = [381843000.0, 382242000.0, 382245000.0, 382248000.0, 382254000.0, 382257000.0, 382305000.0, 382308000.0, 382320000.0, 382323000.0, 382326000.0, 382389000.0, 382392000.0, 382557000.0, 382560000.0, 382671000.0, 383157000.0, 383454000.0, 383457000.0, 383469000.0, 383472000.0, 383997000.0, 384000000.0, 384003000.0, 384006000.0]

def func4():
    import main_odroid
    global stddev2
    stddev2 = std_dev(sweep)

def func1():
    cmd = ["/home/odroid/.local/bin/soapy_power", "-f", "433M", "-r", "6M", "--force-rate", "-q", "-c", "-b", "2000", "-F", "rtl_power_fftw"]
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)

    rolling = []
    i = 0
    rolling_avg = deque([])

    sweep = deque([], maxlen=1500)
    stddev = 12
    totalbins = 2000

    # Let's see what's going on with rtl_power_fftw
    for line in iter(p.stdout.readline, b''):
        #Ignore garbage output
        if not (b'#' in line or not line.strip()):
            floats = list(map(float, line.split()))

            # Create 2D array
            if len(rolling) < totalbins:
                rolling.append(deque([]))
            rolling[i].append(floats[1])
            sweep.append(floats[1])
            # Let's start filtering...

            if len(rolling[i]) >= freqdamping:
                rolling[i].popleft()
                print("ref 5")
                input_state3 = wpi.digitalRead(9)

                if floats[1] > alarmthresh5 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst:   # Led 5
                    wpi.digitalWrite(1, 1)
                    if input_state3 == 0:
                        wpi.digitalWrite(9, 1) # Buzzer proxy
                        wpi.digitalWrite(31, 1) # Buzzer ON
                        print(round(floats[0]), round(floats[1]), alarmthresh5, "ref2")
                        Thread(target = func2).start()
                if floats[1] > alarmthresh1 and floats[0] in [380310000.0, 381444000.0, 381579000.0, 381780000.0, 381783000.0, 382110000.0, 382836000.0, 382881000.0, 382884000.0, 382887000.0, 382890000.0, 382893000.0, 383037000.0, 383085000.0, 383340000.0, 383460000.0, 384258000.0, 384261000.0, 384264000.0]:
                    if input_state3 == 0:
                        wpi.digitalWrite(9, 1) # Buzzer proxy
                        wpi.digitalWrite(31, 1) # Buzzer ON
                        print(round(floats[0]), round(floats[1]), alarmthresh1, "ref1")
                        Thread(target = func2).start()

                if floats[1] > alarmthresh4 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst:     # Led 4
                    wpi.digitalWrite(7, 1)
                if floats[1] > alarmthresh3 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst:     # Led 3
                    wpi.digitalWrite(23, 1)
                if floats[1] > alarmthresh2 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst:     # Led 2
                    wpi.digitalWrite(5, 1)
                if floats[1] > alarmthresh1 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst:     # Led 1
                    input_state = wpi.digitalRead(27)
                    if input_state == 0:
                        wpi.digitalWrite(27, 1)
                        Thread(target = func2).start()

            # Increment or reset indexer (i)
            if i < totalbins - i: i = i + 1
            else:
                i = 0
                Thread(target = func4).start()  # Set stddev2
                Thread(target = func3).start()  # Set alarmthresh1 - alarmthresh5
                print("ref 6")

    p.stdout.close()
    p.wait()
Thread(target = func1).start()

Ref 6 prints before ref 5, so func3 is started before alarmthresh5 is called.


来源: stackexchange

问:
Backend framework choices for React Native
I want to develop an android app that is based on server-client system. I want to develop both backend and android client. It's 2020 and there has already many frameworks developed to provide server side missions to programs.

My question is

What are the trending backend technologies in android world (from database to REST API frameworks), with reasons? For now, I have 2 framework/library on my mind. Spring and Node.js. Google Firebase are also in that list.

I also have another question

Suppose that I made a backend project and want to deploy it on a real server (development made on localhost). What choices should be made ?
For example, I made my development on Mysql and Springboot framework, should that server provide support for MySql and Java ? What is the procedure to deploy both database and backend application ?

Thanks.

答:
You can develop web server using ExpressJs in Node, or using Django/Flask in Python, using golang, PHP Laravel or Codeignitor and many more. It all depends on which language you're already familiar with and which is the best for your use case. Frontend framework has very less to nothing to do with which back end to chose.

Answer to second question.
You can deploy your app in AWS, DigitalOcean, GCP etc. They'll provide VPS and other options to host your application and will make it accessible to outer world using IP or domain, however you configure it. You can install and self manage the DBs in the virtual system you have or you can use Managed database solutions provided by cloud platform, which has a pricing but is easier to manage.

PS: Both your questions were very broad and more of a opinion based answerable questions, it's better to ask these type of questions in platforms like Quora where you can get very detailed answers. Anyways, good luck with your project :)

ContentLicense: CC BY-SA 4.0


问:
Storing single data values in the database
I wanted to know what the best way is to store single data values in a database. Values you only need one field of.

I have a couple of ideas.

Storing all fields in a single_data_table with a id, key and value column.

Storing it as a json object in the database.

Storing it as an array in the database.

Which one is the best way? Or might there even be better ways?

Or is it just easier to keep single data values as static data on the webpage?

答:
At my current job we use a separate settings table for that, with two columns: key and value. And then there's a simple function to retrieve or save a setting:

```<code>function setting($key, $value = null){
    $setting = DB::table('settings')->where('key', $key)->first();
    if(is_null($value)){
        return $setting->value ?? null;
    }

    if(isset($setting)){
        $setting->value = $value;
    }else{
        $setting = $setting ?: new stdClass();
        $setting->key = $key;
        $setting->value = $value;
    }

    DB::table('settings')->insertOrReplace((array) $setting);
    return true;
}
</code>```

It is used like so:

```<code>$phone = setting('phone'); // Get the phone setting
$url = setting('url', 'http://example.com'); // Set url setting
</code>```

Body:
At my current job we use a separate settings table for that, with two columns: key and value. And then there's a simple function to retrieve or save a setting:

function setting($key, $value = null){
    $setting = DB::table('settings')->where('key', $key)->first();
    if(is_null($value)){
        return $setting->value ?? null;
    }

    if(isset($setting)){
        $setting->value = $value;
    }else{
        $setting = $setting ?: new stdClass();
        $setting->key = $key;
        $setting->value = $value;
    }

    DB::table('settings')->insertOrReplace((array) $setting);
    return true;
}

It is used like so:

$phone = setting('phone'); // Get the phone setting
$url = setting('url', 'http://example.com'); // Set url setting


问:
Calculate Equation From Seperate Tables Data
I'm working on my senior High School Project and am reaching out to the community for help! (As my teacher doesn't know the answer to my question).

I have a simple "Products" table as shown below:

I also have a "Orders" table shown below:

Is there a way I can create a field in the "Orders" table named "Total Cost", and make that automaticly calculate the total cost from all the products selected?

答:
Firstly, I would advise against storing calculated values, and would also strongly advise against using calculated fields in tables. In general, calculations should be performed by queries.

I would also strongly advise against the use of multivalued fields, as your images appear to show.

In general, when following the rules of database normalisation, most sales databases are structured in a very similar manner, containing with the following main tables (amongst others):

Products (aka Stock Items)

Customers

Order Header

Order Line (aka Order Detail)

A good example for you to learn from would be the classic Northwind sample database provided free of charge as a template for MS Access.

With the above structure, observe that each table serves a purpose with each record storing information pertaining to a single entity (whether it be a single product, single customer, single order, or single order line).

For example, you might have something like:

Products

Primary Key: Prd_ID

+--------+-----------+-----------+
| Prd_ID | Prd_Desc  | Prd_Price |
+--------+-----------+-----------+
|      1 | Americano | $8.00     |
|      2 | Mocha     | $6.00     |
|      3 | Latte     | $5.00     |
+--------+-----------+-----------+
```

<h3>Customers</h3>

<ul>
<li>Primary Key: <code>Cus_ID</code></li>
</ul>

<pre class="lang-none prettyprint-override"><code>+--------+--------------+
| Cus_ID |   Cus_Name   |
+--------+--------------+
|      1 | Joe Bloggs   |
|      2 | Robert Smith |
|      3 | Lee Mac      |
+--------+--------------+
</code>```

Order Header

Primary Key: Ord_ID

Foreign Keys: Ord_Cust

+--------+----------+------------+
| Ord_ID | Ord_Cust |  Ord_Date  |
+--------+----------+------------+
|      1 |        1 | 2020-02-16 |
|      2 |        1 | 2020-01-15 |
|      3 |        2 | 2020-02-15 |
+--------+----------+------------+
```

<h3>Order Line</h3>

<ul>
<li>Primary Key: <code>Orl_Order</code> + <code>Orl_Line</code></li>
<li>Foreign Keys: <code>Orl_Order</code>, <code>Orl_Prod</code></li>
</ul>

<pre class="lang-none prettyprint-override"><code>+-----------+----------+----------+---------+
| Orl_Order | Orl_Line | Orl_Prod | Orl_Qty |
+-----------+----------+----------+---------+
|         1 |        1 |        1 |       2 |
|         1 |        2 |        3 |       1 |
|         2 |        1 |        2 |       1 |
|         3 |        1 |        1 |       4 |
|         3 |        2 |        3 |       2 |
+-----------+----------+----------+---------+
</code>```

You might also opt to store the product description & price on the order line records, so that these are retained at the point of sale, as the information in the Products table is likely to change over time.

Body:
Firstly, I would advise against storing calculated values, and would also strongly advise against using calculated fields in tables. In general, calculations should be performed by queries.

I would also strongly advise against the use of multivalued fields, as your images appear to show.

In general, when following the rules of database normalisation, most sales databases are structured in a very similar manner, containing with the following main tables (amongst others):

Products (aka Stock Items)

Customers

Order Header

Order Line (aka Order Detail)

A good example for you to learn from would be the classic Northwind sample database provided free of charge as a template for MS Access.

With the above structure, observe that each table serves a purpose with each record storing information pertaining to a single entity (whether it be a single product, single customer, single order, or single order line).

For example, you might have something like:

Products

Primary Key: Prd_ID

+--------+-----------+-----------+
| Prd_ID | Prd_Desc  | Prd_Price |
+--------+-----------+-----------+
|      1 | Americano | $8.00     |
|      2 | Mocha     | $6.00     |
|      3 | Latte     | $5.00     |
+--------+-----------+-----------+

Customers

Primary Key: Cus_ID

+--------+--------------+
| Cus_ID |   Cus_Name   |
+--------+--------------+
|      1 | Joe Bloggs   |
|      2 | Robert Smith |
|      3 | Lee Mac      |
+--------+--------------+

Order Header

Primary Key: Ord_ID

Foreign Keys: Ord_Cust

+--------+----------+------------+
| Ord_ID | Ord_Cust |  Ord_Date  |
+--------+----------+------------+
|      1 |        1 | 2020-02-16 |
|      2 |        1 | 2020-01-15 |
|      3 |        2 | 2020-02-15 |
+--------+----------+------------+

Order Line

Primary Key: Orl_Order + Orl_Line

Foreign Keys: Orl_Order, Orl_Prod

+-----------+----------+----------+---------+
| Orl_Order | Orl_Line | Orl_Prod | Orl_Qty |
+-----------+----------+----------+---------+
|         1 |        1 |        1 |       2 |
|         1 |        2 |        3 |       1 |
|         2 |        1 |        2 |       1 |
|         3 |        1 |        1 |       4 |
|         3 |        2 |        3 |       2 |
+-----------+----------+----------+---------+

You might also opt to store the product description & price on the order line records, so that these are retained at the point of sale, as the information in the Products table is likely to change over time.


问:
How to get background color of div?
I have a div I want when user clicks on this div the background color of div should be display in alert box using jquery only ?

答:
```<code>$('div').click(function() {
   alert($(this).css('background-color'));
});
</code>```

jsFiddle.

ContentLicense: CC BY-SA 3.0

Title: How to get background color of div?

Body:
$('div').click(function() {
   alert($(this).css('background-color'));
});

jsFiddle.


问:
Compare strings of a column in a dataframe with a set of words in a list
I have a dataframe with a single column full_text containing tweets and there is a list negative containing negative words. I want to create a new column that returns a boolean value if the negative words are found in the tweets as 1 and 0 if not found.

答:
Ok, let's assume we have a dataframe data and list negative_words like this:

```<code>data = pd.DataFrame({
    'Tweets' : ['This is bad', 'This is terrible', 'This is good', 'This is great'],
})

negative_words = ['bad', 'terrible']
</code>```

We can then do something like:

1) We can use a lambda function with any:

```<code># create lambda with any:
data['Negative'] = data.apply(lambda x: True if any(word in x.Tweets for word in negative_words) else False, axis=1)
</code>```

And will get:

```<code>             Tweets  Negative
0       This is bad      True
1  This is terrible      True
2      This is good     False
3     This is great     False
</code>```

Body:
Ok, let's assume we have a dataframe data and list negative_words like this:

data = pd.DataFrame({
    'Tweets' : ['This is bad', 'This is terrible', 'This is good', 'This is great'],
})

negative_words = ['bad', 'terrible']

We can then do something like:

1) We can use a lambda function with any:

# create lambda with any:
data['Negative'] = data.apply(lambda x: True if any(word in x.Tweets for word in negative_words) else False, axis=1)

And will get:

             Tweets  Negative
0       This is bad      True
1  This is terrible      True
2      This is good     False
3     This is great     False


问:
Why runnung mvn clean install command (on a Spring Boot project) I obtain unit test failure also if I commented out these methods to skip tests?
I am not working with Spring\Spring Boot from several years and I am starting a project with this technology so I have some doubts.

I am working on a simple project retrieved from GIT and starting working on it implementing my functionality. It works fine but I have the following doubts.

From command line (into the root directory of my project) I compile it using the command:

```<code>mvn clean install
</code>```

in order to delete the previous version of my application and then compile, test & package again my application.

Then I start my application by this command:

```<code>mvn spring-boot:run
</code>```

And the application correctly starts:

It starts without problem. My doubt is in the previous phase when I perform the mvn clean install command. It performs also the unit tests defined inside the project but all test failed. And here the strange behavior.

I obtain exception like this:

```<code>Running com.springboot.excelapi.integration.ExcelResourceUnitTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.001 sec <<< FAILURE! - in com.springboot.excelapi.integration.ExcelResourceUnitTest
initializationError(com.springboot.excelapi.integration.ExcelResourceUnitTest)  Time elapsed: 0 sec  <<< ERROR!
java.lang.Exception: No runnable methods
        at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:191)
        at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128)
        at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
        at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
        at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:138)
        at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
        at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
        at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
        at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
        at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
        at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
        at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
        at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
</code>```

and at the end of the Maven install phase I have the following summary that says that all the tests are failed:

```<code>Tests run: 4, Failures: 0, Errors: 2, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  11.251 s
[INFO] Finished at: 2020-02-16T19:24:02+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test (default-test) on project excel-api: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\nobil\Documents\workspace-sts-3.9.11.RELEASE\spring-boot-excel-api-master.zip_expanded\spring-boot-excel-api-master\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code>```

The strange thing is that I commented out all the test methods into my JUnit classes. For example the previous error is related to this test class:

```<code>package com.springboot.excelapi.integration;

import java.io.IOException;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.springboot.excelapi.Application;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class })
@WebAppConfiguration
@ActiveProfiles(profiles = { "no-liquibase" })
public class ExcelResourceUnitTest {

    /*
    @Test
    public void processCompVibrAndTempoExcelTabTest()
    {
        final ExcelService excelService = new ExcelService();

        try {
            excelService.processCompVibrAndTempExcelTab();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    */

}
</code>```

as you can see this class contains a single test method that is commented out.

So why when I perform the mvn clean install command it seems that it is trying to execute test method that at the moment are disabled by commenting out it?

答:
If you don’t want to run the test use @Ignore on class or single test method.

It seems that there are still tests that run (4 tests as maven summarizes)
so all-in-all probably you shouldn’t always run mvn -DskipTests clean install or at least not always run it because you’ll still want the working tests to run.

Now as for the error, you should have at least one public method annotated with @Test so leave the method but comment out its content (again, IMO its better to use @Ignore as I’ve said before)

Body:
I am not working with Spring\Spring Boot from several years and I am starting a project with this technology so I have some doubts.

I am working on a simple project retrieved from GIT and starting working on it implementing my functionality. It works fine but I have the following doubts.

From command line (into the root directory of my project) I compile it using the command:

mvn clean install

in order to delete the previous version of my application and then compile, test & package again my application.

Then I start my application by this command:

mvn spring-boot:run

And the application correctly starts:

It starts without problem. My doubt is in the previous phase when I perform the mvn clean install command. It performs also the unit tests defined inside the project but all test failed. And here the strange behavior.

I obtain exception like this:

Running com.springboot.excelapi.integration.ExcelResourceUnitTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.001 sec <<< FAILURE! - in com.springboot.excelapi.integration.ExcelResourceUnitTest
initializationError(com.springboot.excelapi.integration.ExcelResourceUnitTest)  Time elapsed: 0 sec  <<< ERROR!
java.lang.Exception: No runnable methods
        at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:191)
        at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128)
        at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
        at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
        at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:138)
        at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
        at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
        at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
        at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
        at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
        at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
        at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
        at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)

and at the end of the Maven install phase I have the following summary that says that all the tests are failed:

Tests run: 4, Failures: 0, Errors: 2, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  11.251 s
[INFO] Finished at: 2020-02-16T19:24:02+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test (default-test) on project excel-api: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\nobil\Documents\workspace-sts-3.9.11.RELEASE\spring-boot-excel-api-master.zip_expanded\spring-boot-excel-api-master\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

The strange thing is that I commented out all the test methods into my JUnit classes. For example the previous error is related to this test class:

package com.springboot.excelapi.integration;

import java.io.IOException;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.springboot.excelapi.Application;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class })
@WebAppConfiguration
@ActiveProfiles(profiles = { "no-liquibase" })
public class ExcelResourceUnitTest {

    /*
    @Test
    public void processCompVibrAndTempoExcelTabTest()
    {
        final ExcelService excelService = new ExcelService();

        try {
            excelService.processCompVibrAndTempExcelTab();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    */

}

as you can see this class contains a single test method that is commented out.

So why when I perform the mvn clean install command it seems that it is trying to execute test method that at the moment are disabled by commenting out it?


问:
FloatingActionButton OnClickListener not working
There are no Errors what so ever. However, you can see that it's being clicked on the animation. The Java code is being called from a child activity where its parent activity is MyMainActivity.

I will also include the github for the project just incase someone wanted to try it.

```<code>FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fav_button);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Log.v("CLICKED","");
        }
    });
</code>```

The layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.lopic.movies.DetailActivity">

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/activity_detail"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <TextView
                android:id="@+id/original_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center"
                android:textAppearance="@style/TextAppearance.AppCompat.SearchResult.Title"
                android:textSize="24sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/poster"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:adjustViewBounds="true" />

                <LinearLayout

                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:paddingLeft="5dp">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/vote_avg"
                        android:textAppearance="@android:style/TextAppearance.Medium" />

                    <TextView
                        android:id="@+id/vote_avg"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/release_date"
                        android:textAppearance="@android:style/TextAppearance.Medium" />

                    <TextView
                        android:id="@+id/release_date"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

                    <LinearLayout
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                        <Button
                            android:id="@+id/trailer_button"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingRight="5dp"
                            android:text="Watch Trailer" />
                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>

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

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/Overview"
                    android:textAppearance="@android:style/TextAppearance.Medium" />

                <TextView
                    android:id="@+id/overview"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
            </LinearLayout>
        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fav_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:src="@drawable/ic_favorite_border_white_24px"
        android:clickable="true"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
Sorry, I don't have enough reputations for commenting.

I've put this in my onCreate()

```<code>@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    FloatingActionButton floatingactionbutton = findViewById(R.id.main_FloatingActionButton_addDate);
    floatingactionbutton.bringToFront();
    floatingactionbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}
</code>```

and it doesn't work, when I said AndroidStudio "run". So I did the same with onResume() and everything is working fine. Thanks to Amit

Body:
There are no Errors what so ever. However, you can see that it's being clicked on the animation. The Java code is being called from a child activity where its parent activity is MyMainActivity.

I will also include the github for the project just incase someone wanted to try it.

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fav_button);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Log.v("CLICKED","");
        }
    });

The layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.lopic.movies.DetailActivity">

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/activity_detail"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <TextView
                android:id="@+id/original_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center"
                android:textAppearance="@style/TextAppearance.AppCompat.SearchResult.Title"
                android:textSize="24sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/poster"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:adjustViewBounds="true" />

                <LinearLayout

                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:paddingLeft="5dp">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/vote_avg"
                        android:textAppearance="@android:style/TextAppearance.Medium" />

                    <TextView
                        android:id="@+id/vote_avg"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/release_date"
                        android:textAppearance="@android:style/TextAppearance.Medium" />

                    <TextView
                        android:id="@+id/release_date"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

                    <LinearLayout
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                        <Button
                            android:id="@+id/trailer_button"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingRight="5dp"
                            android:text="Watch Trailer" />
                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>

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

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/Overview"
                    android:textAppearance="@android:style/TextAppearance.Medium" />

                <TextView
                    android:id="@+id/overview"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
            </LinearLayout>
        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fav_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:src="@drawable/ic_favorite_border_white_24px"
        android:clickable="true"/>

</android.support.design.widget.CoordinatorLayout>

Body:
Sorry, I don't have enough reputations for commenting.

I've put this in my onCreate()

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    FloatingActionButton floatingactionbutton = findViewById(R.id.main_FloatingActionButton_addDate);
    floatingactionbutton.bringToFront();
    floatingactionbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

and it doesn't work, when I said AndroidStudio "run". So I did the same with onResume() and everything is working fine. Thanks to Amit


问:
SwiftUI IPadOS app change text based on orientation
I'd like to change Text displayed based on device orientation. A visual will describe what I am trying to achieve better :)

Here is landscape mode
And here is portrait mode

I'd like to display a short format for the month name in portrait mode and have found various posts describing how to achieve this by detecting device orientation. I also found that this is not in the best practice category so wondering if there is a better way.
Code is just a VStack with two Text components inside a ScrollView.

答:
I would change the accepted answer a little bit to instead use .onReceive:

.onReceive(NotificationCenter.Publisher(center: .default, name: UIDevice.orientationDidChangeNotification)) { _ in
  self.orientation = UIDevice.current.orientation
}
```

This should handle unsubscribing automatically.

Body:
I would change the accepted answer a little bit to instead use .onReceive:

.onReceive(NotificationCenter.Publisher(center: .default, name: UIDevice.orientationDidChangeNotification)) { _ in
  self.orientation = UIDevice.current.orientation
}

This should handle unsubscribing automatically.


问:
How to abbreviate "number of <items>" in source code?
I'm new to learning Java and I'm bad at English but I try my best to write good, understandable source code.

I want to make variables to save the "number of cars" or "number of items". How do I abbreviate "number of ..." without using symbols like # that don't work in a source code?

Thanks

答:
You have several choices to do that

numberOfItems (verbose, but clear in meaning)

numItems (it's ok)

itemCount (probably, the best — what I'd have used)

items (shortest, but can't know if it is an integer or a list of items)


问:
PHP: set class array properties with a string as the propertyname
I have a class with a property that is an array:

```<code>  class NewObject {
    public $Props = array();
  }

  $obj = new NewObject();

  $obj->Props[0] = 'a';
  $obj->Props[1] = 'b';
</code>```

Now I want to change the values of Props, not directly, but with a variable 'propertyname':
This DOES work for single string properties but not for arrays, because the key N is interpreted as the Nth letter of the STRING 'Props' instead of the Nth value in the array!

```<code>  $propertyname = 'Props';

  $obj->$propertyname[0] ='c';   //doesnt work as expected, it tries to set $obj->P now, it seems
  $obj->$propertyname[1] ='d';
</code>```

Any way to solve this ?

Body:
I have a class with a property that is an array:

  class NewObject {
    public $Props = array();
  }

  $obj = new NewObject();

  $obj->Props[0] = 'a';
  $obj->Props[1] = 'b';

Now I want to change the values of Props, not directly, but with a variable 'propertyname':
This DOES work for single string properties but not for arrays, because the key N is interpreted as the Nth letter of the STRING 'Props' instead of the Nth value in the array!

  $propertyname = 'Props';

  $obj->$propertyname[0] ='c';   //doesnt work as expected, it tries to set $obj->P now, it seems
  $obj->$propertyname[1] ='d';

Any way to solve this ?

Body: $obj->{$propertyname}[0] ='c';


问:
Why not all the values in one columns not converted
I have inserted csv file to sql server and doing now casting. there is One column contains value like (166742.9659) as nvarchar and i wanted to convert it to decimal.
my query was like this

```<code>CAST([amount] AS decimal(18,2))     AS [amount]
</code>```

I got the following message:

Error converting data type nvarchar to numeric

then i tried the query just to see which values aws not converted

```<code>TRY_CAST([amount] AS decimal(18,2))     AS [amount]
</code>```

then i got number of NULL values. When i checked this values in the original csv file i found that those numbers have the same format of the value which have been converted successfully.
for example:
this number 17011343.12 was successfully converted
this number **166742.9659 ** get null value

so is there anybody please can understand what happened ??

答:
```<code>declare @t table
(
id int identity,
a nvarchar(100)
);

insert into @t(a) values (cast(0xfeff3100320033002E003400350036003700 as nvarchar(100)));

insert into @t(a)
select top 1000 replace(left(newid(), 13), '-', '.')
from master.dbo.spt_values;

select a, try_cast(a as decimal(18,5)) as trycast,
    try_cast(
      cast(
        convert(varbinary(max),
        '0x' + cast('' as xml).query('
        let $str := xs:string(xs:hexBinary(sql:column("bincol")))
        for $p in (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25)[. <= string-length($str) div 4] (: max input length=25 :)
        let $s := substring($str, 4*($p - 1)+1, 4) [. = ("3000" , "3100", "3200", "3300", "3400", "3500", "3600", "3700", "3800", "3900", "2E00")] (: keep only digits and dot :)
        return <a>{$s}</a>').value('.', 'nvarchar(max)'), 1)
      as nvarchar(max)) --string, containing digits and dot(s)
    as decimal(18,5) --...conversion will fail for multiple dots
    ) as purgeddecimal
from
(
    select id, a, cast(a as varbinary(max)) as bincol
    from @t
) as t
order by id;
</code>```

Body:
I have inserted csv file to sql server and doing now casting. there is One column contains value like (166742.9659) as nvarchar and i wanted to convert it to decimal.
my query was like this

CAST([amount] AS decimal(18,2))     AS [amount]

I got the following message:

Error converting data type nvarchar to numeric

then i tried the query just to see which values aws not converted

TRY_CAST([amount] AS decimal(18,2))     AS [amount]

then i got number of NULL values. When i checked this values in the original csv file i found that those numbers have the same format of the value which have been converted successfully.
for example:
this number 17011343.12 was successfully converted
this number **166742.9659 ** get null value

so is there anybody please can understand what happened ??


问:
How to add multiple modules with -add-modules
I would like to add multiple modules through the VM options in NetBeans. Currently i have just added 1 module( javafx.controls).

Here is the directory that has all the modules including the one already added.

Does anyone know the separating delimiter?

答:
You can use the comma character: ,

The documentation says:

```<code>--add-modules <module name>[,<module name>...]
              root modules to resolve in addition to the initial module.
              <module name> can also be ALL-DEFAULT, ALL-SYSTEM,
              ALL-MODULE-PATH.
</code>```

Body:
You can use the comma character: ,

The documentation says:

--add-modules <module name>[,<module name>...]
              root modules to resolve in addition to the initial module.
              <module name> can also be ALL-DEFAULT, ALL-SYSTEM,
              ALL-MODULE-PATH.


问:
Python itertools permutations without repetitions
I have a string show the step going in m x n grid like this problem:
https://leetcode.com/problems/unique-paths/

```<code>step = 'DDRR'
</code>```

D mean go Down and R mean go to Right
I want to show permutations without replacement, and i found the itertools built-in on Python.But it's say:

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values.

So that when I using itertools.permutation(step,4), it's contain many replications.

```<code>>>> itertools.permutations(step,4)
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')
</code>```

I want something like:

```<code>('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('R', 'R', 'D', 'D')
</code>```

I found some answer using set(itertools.permutations(step,4)), but because apply set() method, the itertools.permutation() method still calculate all possibilities. Is there anyway to avoid it, or is there any built-in function can do permutation without repetitions in Python?

答: Try using itertools.combinationss(step,4) instead of itertools.permutations(step,4)</p>

Body:
I have a string show the step going in m x n grid like this problem:
https://leetcode.com/problems/unique-paths/

step = 'DDRR'

D mean go Down and R mean go to Right
I want to show permutations without replacement, and i found the itertools built-in on Python.But it's say:

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values.

So that when I using itertools.permutation(step,4), it's contain many replications.

>>> itertools.permutations(step,4)
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')

I want something like:

('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('R', 'R', 'D', 'D')

I found some answer using set(itertools.permutations(step,4)), but because apply set() method, the itertools.permutation() method still calculate all possibilities. Is there anyway to avoid it, or is there any built-in function can do permutation without repetitions in Python?


问:
Proper caching frequently used data
not quite sure if this question is good to ask on Stackoverflow or not.

Im currently creating a webpage that would use Mongodb logic, and redis. ( with node.js )

when user are on a page, the backend will get asked to get their user details every 5 seconds.

when retrieving this that frequently, should i get it / store it in the redis, or the mongoDB? need it for some sort of caching.

the reason is that its every 5 sec, is because it could be some changes to it that needs to be reflected backend.

each user would have their details as username, password,  money, and 25 other values.

How should i approach this, to make less heavy if i were just using MongoDB alone?

example:

```<code>function calledEvery5Sec(userid) {
 // get from Mongodb...
}
</code>```

or

```<code>function CalledEverySec(userid) {
// get from redis if its avaliable there, else load from mongodb).
}
</code>```

答:
Use TTL index for the fields you want to store for a short period of time
For that using $out or $merge create a new tmp collection and fetch details from it .

Can you post sample document.

Title: Proper caching frequently used data

Body:
not quite sure if this question is good to ask on Stackoverflow or not.

Im currently creating a webpage that would use Mongodb logic, and redis. ( with node.js )

when user are on a page, the backend will get asked to get their user details every 5 seconds.

when retrieving this that frequently, should i get it / store it in the redis, or the mongoDB? need it for some sort of caching.

the reason is that its every 5 sec, is because it could be some changes to it that needs to be reflected backend.

each user would have their details as username, password,  money, and 25 other values.

How should i approach this, to make less heavy if i were just using MongoDB alone?

example:

function calledEvery5Sec(userid) {
 // get from Mongodb...
}

or

function CalledEverySec(userid) {
// get from redis if its avaliable there, else load from mongodb).
}


问:
Why can some but not all Letsencrypt websites not be read?
After some webserver updates today the script I use that loads data from one of my websites stopped working! The website uses Letsencrypt for SSL.

I tried to read all kind of websites that use Letsencrypt (see code below), including Letsencrypt.org itself. Some work, some don't. I would like to know what is going on. Anyone?

```<code>        public Form1()
    {
        InitializeComponent();

        //string site = "https://www.rtl.nl/";  // <-- Not a LetsEncrypt SSL certificate, runs fine
        //string site = "https://weblog.west-wind.com/"; // <-- LetsEncrypt SSL certificate, runs fine.
        //string site = "https://www.c-sharpcorner.com/";  // <-- LetsEncrypt SSL certificate, runs fine
        //string site = "https://letsencrypt.org/"; // <-- LetsEncrypt SSL certificate, results in exception!
        //string site = "https://www.shopify.com/"; // <-- LetsEncrypt SSL certificate, results in exception!
        //string site = "https://keenetic.com/en"; // <-- LetsEncrypt SSL certificate, runs fine
        string site = "https://unraid.net/"; // <-- LetsEncrypt SSL certificate, results in exception!

        HttpWebRequest myWeb = (HttpWebRequest)WebRequest.Create(site);
        string myPage = "";

        try
        {
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.CheckCertificateRevocationList = false;
            WebResponse myResponse = myWeb.GetResponse();
            Stream myStream = myResponse.GetResponseStream();
            StreamReader myReader = new StreamReader(myStream);
            myPage = myReader.ReadToEnd().ToString();
            textBox1.Text = "Runs fine!";
        }
        catch (Exception ex)
        {
            textBox1.Text = "SSL/TLS Exception!";
        }
    }
</code>```

答:
The code above was compiled in VS 2015 (quite old!)
I tried it in VS 2017 and all sites run fine.

TLS 1.3 is probably the cause for the exceptions.
I'll move to VS 2019 tonight! :-)

Thanks Dirk and Stefan for solving this.

Body:
After some webserver updates today the script I use that loads data from one of my websites stopped working! The website uses Letsencrypt for SSL.

I tried to read all kind of websites that use Letsencrypt (see code below), including Letsencrypt.org itself. Some work, some don't. I would like to know what is going on. Anyone?

        public Form1()
    {
        InitializeComponent();

        //string site = "https://www.rtl.nl/";  // <-- Not a LetsEncrypt SSL certificate, runs fine
        //string site = "https://weblog.west-wind.com/"; // <-- LetsEncrypt SSL certificate, runs fine.
        //string site = "https://www.c-sharpcorner.com/";  // <-- LetsEncrypt SSL certificate, runs fine
        //string site = "https://letsencrypt.org/"; // <-- LetsEncrypt SSL certificate, results in exception!
        //string site = "https://www.shopify.com/"; // <-- LetsEncrypt SSL certificate, results in exception!
        //string site = "https://keenetic.com/en"; // <-- LetsEncrypt SSL certificate, runs fine
        string site = "https://unraid.net/"; // <-- LetsEncrypt SSL certificate, results in exception!

        HttpWebRequest myWeb = (HttpWebRequest)WebRequest.Create(site);
        string myPage = "";

        try
        {
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.CheckCertificateRevocationList = false;
            WebResponse myResponse = myWeb.GetResponse();
            Stream myStream = myResponse.GetResponseStream();
            StreamReader myReader = new StreamReader(myStream);
            myPage = myReader.ReadToEnd().ToString();
            textBox1.Text = "Runs fine!";
        }
        catch (Exception ex)
        {
            textBox1.Text = "SSL/TLS Exception!";
        }
    }


问:
How to toggle the visibility of different TextView's in the same activity
I have 3 cards that are showing on a screen of my app. When a user clicks a card, the card should expand to show the text. I want to achieve this by toggling the visibility of the text view within the clicked card. The very first card on the page works as expected, but none of the other cards function properly. How do I achieve the desired behaviour?

here is my kotlin class:

```<code>private lateinit var thruHist: TextView
private lateinit var esHist: TextView
private lateinit var bayHist: TextView

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // this tells the app which layout to associate with this class
    setContentView(R.layout.activity_workhistory)

    // now connect each view to a variable for manipulation
    thruHist = findViewById(R.id.thruHistory)
    esHist = findViewById(R.id.esHistory)
    bayHist = findViewById(R.id.bayHistory)
}

fun openBay(view: View) {
    if (bayHist.visibility === View.VISIBLE) {
        bayHist.visibility = View.GONE
    } else bayHist.visibility = View.VISIBLE
}

fun openEs(view: View) {
    if (esHist.visibility === View.VISIBLE) {
        esHist.visibility = View.GONE
    } else esHist.visibility = View.VISIBLE
}

fun openThru(view: View) {
    if (thruHist.visibility === View.VISIBLE) {
        thruHist.visibility = View.GONE
    } else thruHist.visibility = View.VISIBLE
}
</code>```

Here is my content layout XML file:

```<code>    <androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_margin="15dp"
    android:onClick="openBay"
    app:cardElevation="2dp"
    app:cardCornerRadius="8dp"
    >
          <TextView
            android:id="@+id/bayHistory"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:text="Worked here blabbity blah blah" />
 </androidx.cardview.widget.CardView>

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_margin="15dp"
    android:onClick="openEs"
    app:cardElevation="2dp"
    app:cardCornerRadius="8dp"
    >
          <TextView
            android:id="@+id/esHistory"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:text="Worked here blabbity blah blah" />
 </androidx.cardview.widget.CardView>

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_margin="15dp"
    android:onClick="openThru"
    app:cardElevation="2dp"
    app:cardCornerRadius="8dp"
    >
        <TextView
            android:id="@+id/thruHistory"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:text="Worked here blabbity blah blah" />
 </androidx.cardview.widget.CardView>
</code>```

I've condensed the code for readability and to also highlight the issue that I am trying to resolve.

I am new to android so feedback would be appreciated. Thanks in advance.

答:
I used a LinearLayout with vertical orientation, and works as expected, on click the texts are visible, I did not do any change to your activity, the gradle dependency for the cardview is     implementation 'androidx.cardview:cardview:1.0.0'

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
              xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
              android:layout_height="match_parent" android:orientation="vertical">
    <androidx.cardview.widget.CardView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
            android:layout_height="120dp"
            android:layout_margin="15dp"
            android:onClick="openBay"
            app:cardElevation="2dp"
            app:cardCornerRadius="8dp">
        <TextView
                android:id="@+id/bayHistory"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone"
                android:text="Worked here blabbity blah blah"/>
    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="120dp"
            android:layout_margin="15dp"
            android:onClick="openEs"
            app:cardElevation="2dp"
            app:cardCornerRadius="8dp">
        <TextView
                android:id="@+id/esHistory"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone"
                android:text="Worked here blabbity blah blah"/>
    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="120dp"
            android:layout_margin="15dp"
            android:onClick="openThru"
            app:cardElevation="2dp"
            app:cardCornerRadius="8dp">
        <TextView
                android:id="@+id/thruHistory"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone"
                android:text="Worked here blabbity blah blah"/>
    </androidx.cardview.widget.CardView>
</LinearLayout>
</code>```

Body:
I have 3 cards that are showing on a screen of my app. When a user clicks a card, the card should expand to show the text. I want to achieve this by toggling the visibility of the text view within the clicked card. The very first card on the page works as expected, but none of the other cards function properly. How do I achieve the desired behaviour?

here is my kotlin class:

private lateinit var thruHist: TextView
private lateinit var esHist: TextView
private lateinit var bayHist: TextView

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // this tells the app which layout to associate with this class
    setContentView(R.layout.activity_workhistory)

    // now connect each view to a variable for manipulation
    thruHist = findViewById(R.id.thruHistory)
    esHist = findViewById(R.id.esHistory)
    bayHist = findViewById(R.id.bayHistory)
}

fun openBay(view: View) {
    if (bayHist.visibility === View.VISIBLE) {
        bayHist.visibility = View.GONE
    } else bayHist.visibility = View.VISIBLE
}

fun openEs(view: View) {
    if (esHist.visibility === View.VISIBLE) {
        esHist.visibility = View.GONE
    } else esHist.visibility = View.VISIBLE
}

fun openThru(view: View) {
    if (thruHist.visibility === View.VISIBLE) {
        thruHist.visibility = View.GONE
    } else thruHist.visibility = View.VISIBLE
}

Here is my content layout XML file:

    <androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_margin="15dp"
    android:onClick="openBay"
    app:cardElevation="2dp"
    app:cardCornerRadius="8dp"
    >
          <TextView
            android:id="@+id/bayHistory"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:text="Worked here blabbity blah blah" />
 </androidx.cardview.widget.CardView>

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_margin="15dp"
    android:onClick="openEs"
    app:cardElevation="2dp"
    app:cardCornerRadius="8dp"
    >
          <TextView
            android:id="@+id/esHistory"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:text="Worked here blabbity blah blah" />
 </androidx.cardview.widget.CardView>

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_margin="15dp"
    android:onClick="openThru"
    app:cardElevation="2dp"
    app:cardCornerRadius="8dp"
    >
        <TextView
            android:id="@+id/thruHistory"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:text="Worked here blabbity blah blah" />
 </androidx.cardview.widget.CardView>

I've condensed the code for readability and to also highlight the issue that I am trying to resolve.

I am new to android so feedback would be appreciated. Thanks in advance.

Body:
I used a LinearLayout with vertical orientation, and works as expected, on click the texts are visible, I did not do any change to your activity, the gradle dependency for the cardview is     implementation 'androidx.cardview:cardview:1.0.0'

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
              xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
              android:layout_height="match_parent" android:orientation="vertical">
    <androidx.cardview.widget.CardView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
            android:layout_height="120dp"
            android:layout_margin="15dp"
            android:onClick="openBay"
            app:cardElevation="2dp"
            app:cardCornerRadius="8dp">
        <TextView
                android:id="@+id/bayHistory"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone"
                android:text="Worked here blabbity blah blah"/>
    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="120dp"
            android:layout_margin="15dp"
            android:onClick="openEs"
            app:cardElevation="2dp"
            app:cardCornerRadius="8dp">
        <TextView
                android:id="@+id/esHistory"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone"
                android:text="Worked here blabbity blah blah"/>
    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="120dp"
            android:layout_margin="15dp"
            android:onClick="openThru"
            app:cardElevation="2dp"
            app:cardCornerRadius="8dp">
        <TextView
                android:id="@+id/thruHistory"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone"
                android:text="Worked here blabbity blah blah"/>
    </androidx.cardview.widget.CardView>
</LinearLayout>


问:
Visual Studio 2008 is not dettecting errors on the fly
My Visual Studio at work is not detecting errors on the fly... I just can see errors when I build my solution.

Does anyone know how can I configure this? Intellisense is working just fine, but this error detection on the fly isn't.

Thanks!!

答: I think you need Service Pack 1 for this, but even then whether errors get detected depends on the type of error: syntax errors are picked up okay, but (e.g.) a class not implementing an interface requires a rebuild.</p>

OwnerDisplayName: AndreMiranda

ContentLicense: CC BY-SA 2.5


问:
php - populate bootstrap-4 modal with data from Datatables(server side)
I have a PHP program with a datatable (Server Side !!):

Each row has a button (“Manage”) which, when clicked, opens up a Bootstrap 4 modal:

I need to populate the modal's 2 elements with the data in the row containing the button which was clicked.

Any hint would be greatly appreciated.

HTML :

```<code><body>
<div id="manageModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="manageAccountModal" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content border border-dark">
            <form id="manageModalForm" name="manageModalForm" action="" method="POST" role="form" class="p-2 needs-validation" novalidate>
                <div class="modal-body">
                    <div>
                        Id<a id="accUserId" name="accUserId" class="form-control"></a>
                        <br>
                    </div>
                    <div class="form-group">
                        User Name<input id="accUserName" name="accUserName" type="text" class="form-control">
                    </div>
                </div>
                <div id="manageModalActions" class="modal-footer myLightPurpleBgColor rounded">
                    <div class="col-8">
                        <div class="row">
                            <div class="col-4">
                                <button type="button" class="btn btn-secondary text-light border border-dark myBigBtn font-weight-bold" data-dismiss="modal"><h7>Cancel</h7></button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="container-fluid">
    <div class="jumbotron jumbotron-fluid mr-n2 ml-n2 mb-n2 rounded bg-secondary">
        <div class="container">
            <div class="row">
                <div class="col-lg-12 col-lg-offset-2 myMargTop20 bg-white rounded">
                    <table id="example" class="display table table-bordered table-hover dt-responsive nowrap rounded" cellspacing="0" width="100%">
                        <br>
                        <thead>
                            <tr>
                                <th>Manage</th>
                                <th>Id</th>
                                <th>User Name</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Javascript :

```<code><script>
    $(document).ready(function() {
        $('#example').dataTable({
            'scrollX': true,
            'pagingType': 'numbers',
            'processing': true,
            'serverSide': true,
            'ajax': 'datatablesServerSide.php',
            "columnDefs": [{"render": createManageButtonFunc, "data": null, "targets": [0]}],
        });
    });
    function createManageButtonFunc() {
        return '<button id="manageBtn" type="button" class="btn btn-success btn-xs" data-toggle="modal" data-target="#manageModal">Manage</button>';
    }
</script>
</code>```

datatablesServerSide.php :

```<code><?php
$table = "users";
$primaryKey = "usrId";
$columns = array(
  array("db" => "usrId", "dt" => 1),
  array("db" => "usrName", "dt" => 2)
);
$sql_details = array(
  "user" => "root",
  "pass" => "",
  "db"   => "a_my_project",
  "host" => "localhost"
);
require( "ssp_with_UTF8.class.php" );
echo json_encode(
  SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
</code>```

答:
SOLVED !<br>
Change my Javascript to the following and it works :  </p>

```<code>    <script>
    $(document).ready(function() {
        // ==============  ==============
        var jsTable = $('#example').DataTable({ // added:   var jsTable =
        // $('#example').dataTable({
            'scrollX': true,
            'pagingType': 'numbers',
            'processing': true,
            'serverSide': true,
            'ajax': 'datatablesServerSide.php',
            "columnDefs": [{"render": createManageButtonFunc, "data": null, "targets": [0]}],
        });
        // ============== Next 7 lines were added ==============
        $('#example').on('click', 'tr', function(){
            // var jsData = jsTable.fnGetData(this);  <== fnGetData deprecated!!!
            jsTable = $('#example').DataTable();
            var jsData = jsTable.row(this).data();
            $('#accUserId').text(jsData[1]);
            $('#accUserName').val(jsData[2]);
        })
        // =====================================================
    });
    function createManageButtonFunc() {
        return '<button id="manageBtn" type="button" class="btn btn-success btn-xs" data-toggle="modal" data-target="#manageModal">Manage</button>';
    }
</script>
</code>```

Body:
I have a PHP program with a datatable (Server Side !!):

Each row has a button (“Manage”) which, when clicked, opens up a Bootstrap 4 modal:

I need to populate the modal's 2 elements with the data in the row containing the button which was clicked.

Any hint would be greatly appreciated.

HTML :

            <form id="manageModalForm" name="manageModalForm" action="" method="POST" role="form" class="p-2 needs-validation" novalidate>

                        Id

                        User Name<input id="accUserName" name="accUserName" type="text" class="form-control">

                                <button type="button" class="btn btn-secondary text-light border border-dark myBigBtn font-weight-bold" data-dismiss="modal"><h7>Cancel</h7></button>

            </form>

                                Manage
                                Id
                                User Name

Javascript :

datatablesServerSide.php :

<?php
$table = "users";
$primaryKey = "usrId";
$columns = array(
  array("db" => "usrId", "dt" => 1),
  array("db" => "usrName", "dt" => 2)
);
$sql_details = array(
  "user" => "root",
  "pass" => "",
  "db"   => "a_my_project",
  "host" => "localhost"
);
require( "ssp_with_UTF8.class.php" );
echo json_encode(
  SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);

Body:
SOLVED !

Change my Javascript to the following and it works :

    <script>
    $(document).ready(function() {
        // ==============  ==============
        var jsTable = $('#example').DataTable({ // added:   var jsTable =
        // $('#example').dataTable({
            'scrollX': true,
            'pagingType': 'numbers',
            'processing': true,
            'serverSide': true,
            'ajax': 'datatablesServerSide.php',
            "columnDefs": [{"render": createManageButtonFunc, "data": null, "targets": [0]}],
        });
        // ============== Next 7 lines were added ==============
        $('#example').on('click', 'tr', function(){
            // var jsData = jsTable.fnGetData(this);  <== fnGetData deprecated!!!
            jsTable = $('#example').DataTable();
            var jsData = jsTable.row(this).data();
            $('#accUserId').text(jsData[1]);
            $('#accUserName').val(jsData[2]);
        })
        // =====================================================
    });
    function createManageButtonFunc() {
        return '<button id="manageBtn" type="button" class="btn btn-success btn-xs" data-toggle="modal" data-target="#manageModal">Manage</button>';
    }
</script>


问:
How can I use regex to find data between quotation marks?
I need to extract data which is between the single quotes.

```<code>"request='fgj234fgj9da41c76a8bc7d470kjykl89a5d'>"
</code>```

I did try:
^"request="'*' but doesn;t work

答:
```<code><script>
const x="request='fgj234fgj9da41c76a8bc7d470kjykl89a5d'>"
const y=x.match(/'(.)+'/g)
alert(y)
</script>
</code>```

This is going to return all those strings between quotes(' ').
(.)+ indicates at least one character should be there between quotes(' ')
/...../g here g indicates search throughout the string

Body:
I need to extract data which is between the single quotes.

"request='fgj234fgj9da41c76a8bc7d470kjykl89a5d'>"

I did try:
^"request="'*' but doesn;t work

Body:
<script>
const x="request='fgj234fgj9da41c76a8bc7d470kjykl89a5d'>"
const y=x.match(/'(.)+'/g)
alert(y)
</script>

This is going to return all those strings between quotes(' ').
(.)+ indicates at least one character should be there between quotes(' ')
/...../g here g indicates search throughout the string


问:
NSWindow contentView not cover full window size - macOS & SwiftUI
I'm starting a new macOS app with SwiftUI but I have a big problem.
The app needs a full size contentView (underneath titleBar) but I can't accomplish. On a new project using Storyboards works fine, but with SwiftUI not.

My code:

Result:

And it should look like this:

Any ideas?
Thanks!

答:
I just used the following variant in AppDelegate, the content of ContentView and others can be any

```<code>func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Create the SwiftUI view that provides the window contents.
    let contentView = ContentView()
        .edgesIgnoringSafeArea(.top) // to extend entire content under titlebar

    // Create the window and set the content view.
    window = NSWindow(
        contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
        styleMask: [.titled, .closable, .miniaturizable, .texturedBackground, .resizable, .fullSizeContentView],
        backing: .buffered, defer: false)
    window.center()
    window.setFrameAutosaveName("Main Window")

    window.titlebarAppearsTransparent = true // as stated
    window.titleVisibility = .hidden         // no title - all in content

    window.contentView = NSHostingView(rootView: contentView)
    window.makeKeyAndOrderFront(nil)
}
</code>```

Body:
I just used the following variant in AppDelegate, the content of ContentView and others can be any

func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Create the SwiftUI view that provides the window contents.
    let contentView = ContentView()
        .edgesIgnoringSafeArea(.top) // to extend entire content under titlebar

    // Create the window and set the content view.
    window = NSWindow(
        contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
        styleMask: [.titled, .closable, .miniaturizable, .texturedBackground, .resizable, .fullSizeContentView],
        backing: .buffered, defer: false)
    window.center()
    window.setFrameAutosaveName("Main Window")

    window.titlebarAppearsTransparent = true // as stated
    window.titleVisibility = .hidden         // no title - all in content

    window.contentView = NSHostingView(rootView: contentView)
    window.makeKeyAndOrderFront(nil)
}


问:
How to make a condition for onclick loader when user don't completed all fields in form
I have a problem with the form, there is some information in the form and a photo to upload. The time to send the form is different depending on the weight of the file, if it is ~ 3MB it's ok, however if someone uses the mobile version they use the camera in the phone and then the photo can weigh up to 7MB - then the loading time is too long and the user is confused. Therefore I used a simple loader on onclick and the same with onload on the next page, works great, unless someone don't fill the field in the form, then the loader covers the whole page and turns forever. How can I make the condition that the loader appears on oncick only if all fields are completed correctly?

There's form:

```<code><div id="preloader" aria-busy="true" aria-label="Loading, please wait." role="progressbar"><img class="icon" src="https://raziraz.github.io/codepen/img/bolt.svg">
</div>

    <main id="site" role="main">
    <script  src="./preloaderr.js"></script>

        <h2>Dodaj nową licencję</h2>
        <form method="POST" action="Licencja_Użytkownik_Dodawanie_Skrypt.php" enctype="multipart/form-data">
        <input type="hidden" name="login" value="$login">

        <div id="inputtitle">Prześlij zdjęcie</div>
        <input type="file" name="licencja_plik" required>
        </br>

        <div id="inputtitle">Numer licencji</div>
        <input type="text" name="Numer_Licencji"  placeholder="Numer licencji" required></br>

        <div id="inputtitle">Numer wypisu</div>
        <input type="text" name="Numer_Wypisu"  placeholder="Numer wypisu" required></br>

        <div id="inputtitle">Miasto</div>
        <input type="text" name="Miasto_Licencji"  placeholder="Miasto" required></br>

        <div id="inputtitle">Numer rejestracyjny</div>
        <input type="text" name="Numer_Rejestracyjny"  placeholder="Numer rejestracyjny" required></br>

        <div id="inputtitle">Licencja ważna do:</div>
        <input type="date" name="Licencja_Do"  placeholder="05-02-2020" required></br>

        <div id="containera">
        <div id="right">

        <button type="submit" class="buttondodaj" onclick="teest(); window.parent.parent.scrollTo(0,0)">
        Dodaj   <i class="fas fa-arrow-right"></i>
        </button>

        </form></div>

        <form method="GET" action="Licencja_Użytkownik.php" >
        <input type="hidden" name="login" value="$login">

        <div id="left">

        <button type="submit" class="buttonanuluj">
        <i class="fas fa-arrow-left"></i>   Anuluj
        </button>

        </form>
        </div>
        </div>
    </main>

</code>```

There's js preloader and loader:

```<code>
function preloader() {
  var preloader = document.getElementById("preloader");
  preloader.style.opacity = "0";
  preloader.setAttribute("aria-busy", "false");
  document.getElementById("site").style.opacity = "1";
}
window.onload = preloader;

function teest() {
  var preloader = document.getElementById("preloader");
  preloader.style.opacity = "1";
  preloader.setAttribute("aria-busy", "false");
  document.getElementById("site").style.opacity = "0";

}
</code>```

I will be grateful for the hints :).

答:
Thank you faso-dev!
For now it's work pretty good, but here's a small mistake, I need to do it like this:

Button (need onclick):

```<code>   <button type="submit" id="submitBtn" class="buttondodaj" onclick="teest();
   window.parent.parent.scrollTo(0,0)">
   Dodaj   <i class='fas fa-arrow-right'></i>
   </button>";
</code>```

Script: (it was good ! :) )

```<code>function teest() {
    const isNotEmpty = () => {
    let flag = true;

     document
        .querySelectorAll("input")
        .forEach(input => flag =  input.value !== "" && flag);
      return flag;
    };

    document.getElementById('submitBtn').addEventListener('click',e => {
      let flag = isNotEmpty();
      if(!flag) {
        e.preventDefault();
        return;
      }
      var preloader = document.getElementById("preloader");
      preloader.style.opacity = "1";
      preloader.setAttribute("aria-busy", "false");
      document.getElementById("site").style.opacity = "0";
    })
    }
</code>```

I leave it for the next generations ^^. Thanks a lot faso-dev!

Body:
I have a problem with the form, there is some information in the form and a photo to upload. The time to send the form is different depending on the weight of the file, if it is ~ 3MB it's ok, however if someone uses the mobile version they use the camera in the phone and then the photo can weigh up to 7MB - then the loading time is too long and the user is confused. Therefore I used a simple loader on onclick and the same with onload on the next page, works great, unless someone don't fill the field in the form, then the loader covers the whole page and turns forever. How can I make the condition that the loader appears on oncick only if all fields are completed correctly?

There's form:

Dodaj nową licencję

        <form method="POST" action="Licencja_Użytkownik_Dodawanie_Skrypt.php" enctype="multipart/form-data">
        <input type="hidden" name="login" value="$login">

Prześlij zdjęcie

        <input type="file" name="licencja_plik" required>

Numer licencji

        <input type="text" name="Numer_Licencji"  placeholder="Numer licencji" required>

Numer wypisu

        <input type="text" name="Numer_Wypisu"  placeholder="Numer wypisu" required>

Miasto

        <input type="text" name="Miasto_Licencji"  placeholder="Miasto" required>

Numer rejestracyjny

        <input type="text" name="Numer_Rejestracyjny"  placeholder="Numer rejestracyjny" required>

Licencja ważna do:

        <input type="date" name="Licencja_Do"  placeholder="05-02-2020" required>

        <button type="submit" class="buttondodaj" onclick="teest(); window.parent.parent.scrollTo(0,0)">
        Dodaj
        </button>

        </form>

        <form method="GET" action="Licencja_Użytkownik.php" >
        <input type="hidden" name="login" value="$login">

        <button type="submit" class="buttonanuluj">
           Anuluj
        </button>

        </form>

There's js preloader and loader:

function preloader() {
  var preloader = document.getElementById("preloader");
  preloader.style.opacity = "0";
  preloader.setAttribute("aria-busy", "false");
  document.getElementById("site").style.opacity = "1";
}
window.onload = preloader;

function teest() {
  var preloader = document.getElementById("preloader");
  preloader.style.opacity = "1";
  preloader.setAttribute("aria-busy", "false");
  document.getElementById("site").style.opacity = "0";

}

I will be grateful for the hints :).

Body:
Thank you faso-dev!
For now it's work pretty good, but here's a small mistake, I need to do it like this:

Button (need onclick):

   <button type="submit" id="submitBtn" class="buttondodaj" onclick="teest();
   window.parent.parent.scrollTo(0,0)">
   Dodaj&nbsp;&nbsp;&nbsp;<i class='fas fa-arrow-right'></i>
   </button>";

Script: (it was good ! :) )

function teest() {
    const isNotEmpty = () => {
    let flag = true;

     document
        .querySelectorAll("input")
        .forEach(input => flag =  input.value !== "" && flag);
      return flag;
    };

    document.getElementById('submitBtn').addEventListener('click',e => {
      let flag = isNotEmpty();
      if(!flag) {
        e.preventDefault();
        return;
      }
      var preloader = document.getElementById("preloader");
      preloader.style.opacity = "1";
      preloader.setAttribute("aria-busy", "false");
      document.getElementById("site").style.opacity = "0";
    })
    }

I leave it for the next generations ^^. Thanks a lot faso-dev!


问:
What characters do you send to a "Generic/Text Only" printer to print bolded and underlined characters?
I need to print a report for a project I'm working on. I'm already printing it, but some formatting is missing (bold, underline) that is used to emphasize and differentiate certain areas.

The printer is installed as "Generic/Text Only" (required by the client). I've been googling for a while now, and haven't found a way to send the right characters to make the text bolded and underlined from code.

How can I print bold and underline characters in a generic text only printer by code?

答: Have you tried ESC+E to start bold and ESC+F to finish it?