问:
Why is my repositoryPath ignored in Azure DevOps / TFS?
First of all, I have a NuGet.Config:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <config>
    <add key="repositoryPath" value=".\ExternalReferences\Packages" />
      <solution>
        <add key="disableSourceControlIntegration" value="true" />
      </solution>
  </config>
</configuration>
</code>```

In the root of my dev branch. It's job is, that every project in my dev branch restores the packages into \dev\ExternalReferences\Packages, which works fine localy.

Im trying to introduce Azure Pipelines via TFS (VisualStudio Team Services/DevOps) for my CI-Build.

However, TFS is restoring the packages into the wrong folder \dev\packages (where \dev is D:\a\9\s\) instead of \dev\ExternalReferences\Packages.

```<code>Acquired lock for the installation of Newtonsoft.Json 12.0.3
Installing Newtonsoft.Json 12.0.3.
Adding package 'Microsoft.Extensions.Logging.Abstractions.2.2.0' to folder 'D:\a\9\s\packages'
</code>```

This breaks the build later (Which expects the ExternalReferences\Packages):

```<code>PrepareForBuild:
  Creating directory "bin\Release\".
  Creating directory "obj\Release\".
ResolveAssemblyReferences:
  Primary reference "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL".
##[warning]C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(2110,5): Warning MSB3245: Could not resolve this reference. Could not locate the assembly "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(2110,5): warning MSB3245: Could not resolve this reference. Could not locate the assembly "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors. [D:\a\9\s\Conwell.WebServices.Google\Conwell.WebServices.Google.csproj]
</code>```

Any Idea how to make NuGet to restore to the correct directory?

I just created a standard Pipeline for the project type Asp.NET

答:
As a workaround I configured the directory directly:

Go to pipeline, and edit:

Go to NuGet restore, Advanced and Destination Directory:

I am still open to options, which would respect the NuGet.Config.

Body:
First of all, I have a NuGet.Config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <config>
    <add key="repositoryPath" value=".\ExternalReferences\Packages" />
      <solution>
        <add key="disableSourceControlIntegration" value="true" />
      </solution>
  </config>
</configuration>

In the root of my dev branch. It's job is, that every project in my dev branch restores the packages into \dev\ExternalReferences\Packages, which works fine localy.

Im trying to introduce Azure Pipelines via TFS (VisualStudio Team Services/DevOps) for my CI-Build.

However, TFS is restoring the packages into the wrong folder \dev\packages (where \dev is D:\a\9\s\) instead of \dev\ExternalReferences\Packages.

Acquired lock for the installation of Newtonsoft.Json 12.0.3
Installing Newtonsoft.Json 12.0.3.
Adding package 'Microsoft.Extensions.Logging.Abstractions.2.2.0' to folder 'D:\a\9\s\packages'

This breaks the build later (Which expects the ExternalReferences\Packages):

PrepareForBuild:
  Creating directory "bin\Release\".
  Creating directory "obj\Release\".
ResolveAssemblyReferences:
  Primary reference "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL".
##[warning]C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(2110,5): Warning MSB3245: Could not resolve this reference. Could not locate the assembly "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(2110,5): warning MSB3245: Could not resolve this reference. Could not locate the assembly "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors. [D:\a\9\s\Conwell.WebServices.Google\Conwell.WebServices.Google.csproj]

Any Idea how to make NuGet to restore to the correct directory?

I just created a standard Pipeline for the project type Asp.NET


来源: stackexchange

问:
Check if an array is sorted using Divide and Conquer
As question says, I need to write an algorithm in C or Python which uses Divide-And-Conquer to check if an array is sorted or not. I have a basic idea, but I can't seem to reach a definitive answer.
This is what I got so far, using pseudocode:

```<code>isSorted(array, start, end):
    if (len(array)) <= 1: return true
    if (end - start) == 1: return array[end] > array[start]
    middle = (end + start) // 2
    return isSorted(array, start, middle) && isSorted(array, middle, end)
</code>```

Would that do the trick? Or am I missing some border cases in which this algorithm wouldn't work?

答:
Found an answer to my own question, I was quite there but there were some problems that I was marked in the comments. One of them was that I didn't handle when there were duplicates in the array, and len(array) wouldn't work properly, since I never changed the array.

```<code>def isSorted(array, start, end):
    if start == end: return True
    if (end - start) == 1: return array[end] >= array[start]
    middle = (end + start) // 2
    return isSorted(array, start, middle) and isSorted(array, middle, end)
</code>```

That's programmed in Python, very close to the pseudocode above, and it works for the cases I made.

ContentLicense: CC BY-SA 4.0

Body:
As question says, I need to write an algorithm in C or Python which uses Divide-And-Conquer to check if an array is sorted or not. I have a basic idea, but I can't seem to reach a definitive answer.
This is what I got so far, using pseudocode:

isSorted(array, start, end):
    if (len(array)) <= 1: return true
    if (end - start) == 1: return array[end] > array[start]
    middle = (end + start) // 2
    return isSorted(array, start, middle) && isSorted(array, middle, end)

Would that do the trick? Or am I missing some border cases in which this algorithm wouldn't work?

Body:
Found an answer to my own question, I was quite there but there were some problems that I was marked in the comments. One of them was that I didn't handle when there were duplicates in the array, and len(array) wouldn't work properly, since I never changed the array.

def isSorted(array, start, end):
    if start == end: return True
    if (end - start) == 1: return array[end] >= array[start]
    middle = (end + start) // 2
    return isSorted(array, start, middle) and isSorted(array, middle, end)

That's programmed in Python, very close to the pseudocode above, and it works for the cases I made.


问:
SQL Getting the party with highest votes
I am trying to make a voting system through a SQL server, and I can't get it right. What I am trying to do is get the party with the highest amount of votes.

```<code>SELECT COUNT(*)
FROM Vote
    INNER JOIN Members ON Vote.Voted = Members.PartyName
WHERE (PartyName is the biggest one)
</code>```

I expect something like [DEMS][8], or at the very least, the party name of the party with the highest votes.

答:
Rather than using a WHERE clause you need to use whatever the syntax is for the top record in your SQL dialect. You also need to group by partijnaam. This is a bit of a guess as I don;t know your exact data structure.

Postgres/MySQL

```<code>SELECT PartijNaam, COUNT(*)
FROM stem
    INNER JOIN leden ON stem.Gestemt = Leden.lidnummer
GROUP BY PartijNaam
ORDER BY 2 DESC
LIMIT 1
</code>```

SQL Server

```<code>SELECT TOP 1 PartijNaam, COUNT(*)
FROM stem
    INNER JOIN leden ON stem.Gestemt = Leden.lidnummer
GROUP BY PartijNaam
ORDER BY 2 DESC
</code>```

Body:
I am trying to make a voting system through a SQL server, and I can't get it right. What I am trying to do is get the party with the highest amount of votes.

SELECT COUNT(*)
FROM Vote
    INNER JOIN Members ON Vote.Voted = Members.PartyName
WHERE (PartyName is the biggest one)

I expect something like [DEMS][8], or at the very least, the party name of the party with the highest votes.

Body:
Rather than using a WHERE clause you need to use whatever the syntax is for the top record in your SQL dialect. You also need to group by partijnaam. This is a bit of a guess as I don;t know your exact data structure.

Postgres/MySQL

SELECT PartijNaam, COUNT(*)
FROM stem
    INNER JOIN leden ON stem.Gestemt = Leden.lidnummer
GROUP BY PartijNaam
ORDER BY 2 DESC
LIMIT 1

SQL Server

SELECT TOP 1 PartijNaam, COUNT(*)
FROM stem
    INNER JOIN leden ON stem.Gestemt = Leden.lidnummer
GROUP BY PartijNaam
ORDER BY 2 DESC


问:
JavaScript Define Property in Terms of Method
Please note this question is not answered by
Self-references in object literals / initializers
as that question addresses defining properties in terms of other properites, not methods.

Also, How does the "this" keyword in Javascript act within an object literal? is too high-level a decription of the subject for me to be able to solve my use case.

In Python, I can do this:

```<code>class Test:
    def __init__(self):
        self.id = self.get_id()

    def get_id(self):
        return 10

t = Test()
print(t.id)
</code>```

Meaning an object property can be defined in terms of a method of the same object.

In JavaScript, it doesn't work:

```<code>var Test = {
  id : this.getId(),
  getId : function() {
    return 10;
  }
};
</code>```

Gives script.js:47 Uncaught TypeError: this.getId is not a function

I've tried defining the id after the method definition but that didn't work.

How do I do this in JavaScript please?

答:
The other answer (Evgeny Yudin) is simpler - but this is an alternative using classes that may add something to your understanding.</p>

```<code>class Test {
  constructor() {
    this.id = this.getId();
  }
  getId() {
    return 10;
  }
}

console.log((new Test()).id); //outputs 10
</code>```

Body:
Please note this question is not answered by
Self-references in object literals / initializers
as that question addresses defining properties in terms of other properites, not methods.

Also, How does the "this" keyword in Javascript act within an object literal? is too high-level a decription of the subject for me to be able to solve my use case.

In Python, I can do this:

class Test:
    def __init__(self):
        self.id = self.get_id()

    def get_id(self):
        return 10

t = Test()
print(t.id)

Meaning an object property can be defined in terms of a method of the same object.

In JavaScript, it doesn't work:

var Test = {
  id : this.getId(),
  getId : function() {
    return 10;
  }
};

Gives script.js:47 Uncaught TypeError: this.getId is not a function

I've tried defining the id after the method definition but that didn't work.

How do I do this in JavaScript please?

Body:
The other answer (Evgeny Yudin) is simpler - but this is an alternative using classes that may add something to your understanding.

class Test {
  constructor() {
    this.id = this.getId();
  }
  getId() {
    return 10;
  }
}

console.log((new Test()).id); //outputs 10


问:
C++ to Java Code Conversion
I have in C++

```<code>r.bits[k] &= 0xFF ^ msk;
</code>```

So in Java

```<code>r.bits[k] = r.bits[k] & 0xFF,
</code>```

but what is the meaning of the caret symbol? msk also will contain hexadecimal values.
I know the caret symbol is a type of pointer in C++ but not sure what it is doing here.
Please explain.

答:
The ^ is bitwise XOR.

For example:

```<code>1 ^ 1 = 0
2 ^ 1 = 3
0 ^ 1 = 1
</code>```

If you are using C++/CLI then it is also a kind of reference (handle).

ContentLicense: CC BY-SA 3.0

Title: C++ to Java Code Conversion

Body:
I have in C++

r.bits[k] &= 0xFF ^ msk;

So in Java

r.bits[k] = r.bits[k] & 0xFF,

but what is the meaning of the caret symbol? msk also will contain hexadecimal values.
I know the caret symbol is a type of pointer in C++ but not sure what it is doing here.
Please explain.

Body:
The ^ is bitwise XOR.

For example:

1 ^ 1 = 0
2 ^ 1 = 3
0 ^ 1 = 1

If you are using C++/CLI then it is also a kind of reference (handle).


问:
Java While loop condition isn't being exicuted
I'm working on a project for school but I can't figure out why my code isn't exiting when I type "zzz". it's probably simple and I'll likely feel dumb when I know what the problem is. here's my code: </p>

```<code>import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int counter = 0;
    String[] arr = new String[15];
    System.out.println("Enter item or type 'zzz' to quit");
    arr[0] = input.nextLine();
    counter++;

     do{
         arr[counter] = input.nextLine();
         if (input.equals("zzz")){
             System.out.println("bleh");
         }
         counter++;

     } while (!input.equals("zzz") && counter <= 14);

     Arrays.sort(arr);
     System.out.println("Array is " + Arrays.toString(arr));
}
</code>```

答:
Replace

```<code>if (arr[counter].equals("zzz")) {
    System.out.println("bleh");
}
counter++;
</code>```

with

```<code>if (arr[counter].equals("zzz")) {
    System.out.println("bleh");
} else {
    counter++;
}
</code>```

and

```<code>while (!input.equals("zzz") && counter <= 14)
</code>```

with

```<code>while (!arr[counter].equals("zzz") && counter <= 14)
</code>```

Explanation: zzz is a string which you have to compare with the input string stored in arr[counter].

Also, in order to avoid NullPointerException, you should perform sort operation on the copy of the array without any null element. Given below is the complete program:

```<code>import java.util.Arrays;
import java.util.Scanner;

public class StringSort2 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int counter = 0;
        String[] arr = new String[15];
        do {
            System.out.print("Enter item or type 'zzz' to quit: ");
            arr[counter] = input.nextLine();
            if (arr[counter].equals("zzz")) {
                System.out.println("bleh");
            } else {
                counter++;
            }
        } while (!"zzz".equals(arr[counter]) && counter <= 14);
        arr = Arrays.copyOf(arr, counter);
        Arrays.sort(arr);
        System.out.println("Array is " + Arrays.toString(arr));
    }
}
</code>```

A sample run:

```<code>Enter item or type 'zzz' to quit: a
Enter item or type 'zzz' to quit: b
Enter item or type 'zzz' to quit: c
Enter item or type 'zzz' to quit: zzz
bleh
Array is [a, b, c]
</code>```

Body:
I'm working on a project for school but I can't figure out why my code isn't exiting when I type "zzz". it's probably simple and I'll likely feel dumb when I know what the problem is. here's my code:

import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int counter = 0;
    String[] arr = new String[15];
    System.out.println("Enter item or type 'zzz' to quit");
    arr[0] = input.nextLine();
    counter++;

     do{
         arr[counter] = input.nextLine();
         if (input.equals("zzz")){
             System.out.println("bleh");
         }
         counter++;

     } while (!input.equals("zzz") && counter <= 14);

     Arrays.sort(arr);
     System.out.println("Array is " + Arrays.toString(arr));
}

Body:
Replace

if (arr[counter].equals("zzz")) {
    System.out.println("bleh");
}
counter++;

with

if (arr[counter].equals("zzz")) {
    System.out.println("bleh");
} else {
    counter++;
}

and

while (!input.equals("zzz") && counter <= 14)

with

while (!arr[counter].equals("zzz") && counter <= 14)

Explanation: zzz is a string which you have to compare with the input string stored in arr[counter].

Also, in order to avoid NullPointerException, you should perform sort operation on the copy of the array without any null element. Given below is the complete program:

import java.util.Arrays;
import java.util.Scanner;

public class StringSort2 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int counter = 0;
        String[] arr = new String[15];
        do {
            System.out.print("Enter item or type 'zzz' to quit: ");
            arr[counter] = input.nextLine();
            if (arr[counter].equals("zzz")) {
                System.out.println("bleh");
            } else {
                counter++;
            }
        } while (!"zzz".equals(arr[counter]) && counter <= 14);
        arr = Arrays.copyOf(arr, counter);
        Arrays.sort(arr);
        System.out.println("Array is " + Arrays.toString(arr));
    }
}

A sample run:

Enter item or type 'zzz' to quit: a
Enter item or type 'zzz' to quit: b
Enter item or type 'zzz' to quit: c
Enter item or type 'zzz' to quit: zzz
bleh
Array is [a, b, c]


问:
CSS: get color from angular
From jquery we can take the color from an element like this

```<code>$('#js-color-profile').find('.color-primary-50').css('color')
</code>```

in angular 2+ is any workaround to get the hex color?

答:
You can get it with vanilla js like this. The getPropertyValue is not necessary, but the getComputedStyle will return all css for the element, that's why I wrote it there.

```<code>getComputedStyle(element, null).getPropertyValue('color')
</code>```

or

```<code>getComputedStyle(element, null)['color']
</code>```

Title: CSS: get color from angular

Body:
From jquery we can take the color from an element like this

$('#js-color-profile').find('.color-primary-50').css('color')

in angular 2+ is any workaround to get the hex color?

Body:
You can get it with vanilla js like this. The getPropertyValue is not necessary, but the getComputedStyle will return all css for the element, that's why I wrote it there.

getComputedStyle(element, null).getPropertyValue('color')

or

getComputedStyle(element, null)['color']


问:
Pyodbc unable to execute proc in SQL Server 2008
Context: I have a Python function which is supposed to connect to SQL Server 2008 via Pyodbc and execute a stored procedure that parses an XML file and loads it to a table. I'm using Python 3.8.1 and I installed the updated ODBC Driver (ODBC Driver 13.1)

Here's the Pyhton function:

```<code>import pyodbc

def load_to_database():
    username = 'REDACTED'
    password = 'REDACTED'

    connection = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};"
                        "Server=REDACTED;"
                        "Database=REDACTED;"
                        "Username="+username+";"
                        "Password="+password+";"
                        "Trusted_Connection=yes;")
    connection_cursor = connection.cursor()

    executesp = """EXEC [REDACTED].[dbo].[get_cp_api_data_part_search]"""
    connection.autocommit = True
    connection_cursor.execute(executesp)
    connection.close()
load_to_database()
</code>```

Problem: The Python script appears to be successfully connecting to the database, and executes without any errors. BUT when I check the underlying database table, the data hasn't been loaded which to me indicates that the stored procedure isn't being executed. When I run the stored procedure manually it runs without any issue and loads the data.

Questions: Can someone please assist in troubleshooting tips and help me understand why the procedure isnt being executed? I suppose its possible the procedure is being executed but for whatever reason not all the SQL may be running? Or perhaps the cursor exits/returns once the EXEC calls in the procedure are made?

Here's the stored procedure in SQL Server:

IF OBJECT_ID('tempdb..##search') IS NOT NULL DROP TABLE ##earch

DECLARE @xml_data XML

--Use OPENROWSET to extract the data from the xml file.
SELECT @xml_data=O
FROM OPENROWSET(BULK N'C:\Users\eb\Desktop\Important Docs & Links\Important Documents\xml_data_removed_tags.xml', SINGLE_BLOB) as file_output(O)

--Variable below will be used to create a recognizeable XML document within SQL Server memory
DECLARE @xml_doc int

--Procedure below takes 2 parameters: 1) output parameter to store handle to xml document and 2) the xml document itself
EXEC sp_xml_preparedocument @xml_doc OUTPUT, @xml_data

--Function below parses the XML based on the hierarchy path used, list the attributes and elements you want to query
--Queried into temptable
SELECT *
INTO ##search
FROM OPENXML(@xml_doc,'REDACTED/*',2)
WITH (
        REDACTED nvarchar(10),
        REDACTED int,
        REDACTED int,
        REDACTED nvarchar(60),
        REDACTED nvarchar(10),
        REDACTED int,
        REDACTED nvarchar(30),
        REDACTED nvarchar(20),
        REDACTED nvarchar(20),
        REDACTED int,
        REDACTED nvarchar(5),
        REDACTED nvarchar(5),
        REDACTED int,
        REDACTED nvarchar(50)'REDACTED',
        REDACTED nvarchar(25)'REDACTED',
        REDACTED int 'REDACTED',
        REDACTED nvarchar(60) 'REDACTED',
        REDACTED int 'REDACTED',
        REDACTED nvarchar(50) 'REDACTED',
        REDACTED nvarchar(20) 'REDACTED'
        )

--This procedure removes the saved prepared xml document
```

答: @Parfait, you are correct -- the issue appears to be resolved when using a normal table instead of temp table. </p>

Body:
Context: I have a Python function which is supposed to connect to SQL Server 2008 via Pyodbc and execute a stored procedure that parses an XML file and loads it to a table. I'm using Python 3.8.1 and I installed the updated ODBC Driver (ODBC Driver 13.1)

Here's the Pyhton function:

import pyodbc

def load_to_database():
    username = 'REDACTED'
    password = 'REDACTED'

    connection = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};"
                        "Server=REDACTED;"
                        "Database=REDACTED;"
                        "Username="+username+";"
                        "Password="+password+";"
                        "Trusted_Connection=yes;")
    connection_cursor = connection.cursor()

    executesp = """EXEC [REDACTED].[dbo].[get_cp_api_data_part_search]"""
    connection.autocommit = True
    connection_cursor.execute(executesp)
    connection.close()
load_to_database()

Problem: The Python script appears to be successfully connecting to the database, and executes without any errors. BUT when I check the underlying database table, the data hasn't been loaded which to me indicates that the stored procedure isn't being executed. When I run the stored procedure manually it runs without any issue and loads the data.

Questions: Can someone please assist in troubleshooting tips and help me understand why the procedure isnt being executed? I suppose its possible the procedure is being executed but for whatever reason not all the SQL may be running? Or perhaps the cursor exits/returns once the EXEC calls in the procedure are made?

Here's the stored procedure in SQL Server:

IF OBJECT_ID('tempdb..##search') IS NOT NULL DROP TABLE ##earch

DECLARE @xml_data XML

--Use OPENROWSET to extract the data from the xml file.
SELECT @xml_data=O
FROM OPENROWSET(BULK N'C:\Users\eb\Desktop\Important Docs & Links\Important Documents\xml_data_removed_tags.xml', SINGLE_BLOB) as file_output(O)

--Variable below will be used to create a recognizeable XML document within SQL Server memory
DECLARE @xml_doc int

--Procedure below takes 2 parameters: 1) output parameter to store handle to xml document and 2) the xml document itself
EXEC sp_xml_preparedocument @xml_doc OUTPUT, @xml_data

--Function below parses the XML based on the hierarchy path used, list the attributes and elements you want to query
--Queried into temptable
SELECT *
INTO ##search
FROM OPENXML(@xml_doc,'REDACTED/*',2)
WITH (
        REDACTED nvarchar(10),
        REDACTED int,
        REDACTED int,
        REDACTED nvarchar(60),
        REDACTED nvarchar(10),
        REDACTED int,
        REDACTED nvarchar(30),
        REDACTED nvarchar(20),
        REDACTED nvarchar(20),
        REDACTED int,
        REDACTED nvarchar(5),
        REDACTED nvarchar(5),
        REDACTED int,
        REDACTED nvarchar(50)'REDACTED',
        REDACTED nvarchar(25)'REDACTED',
        REDACTED int 'REDACTED',
        REDACTED nvarchar(60) 'REDACTED',
        REDACTED int 'REDACTED',
        REDACTED nvarchar(50) 'REDACTED',
        REDACTED nvarchar(20) 'REDACTED'
        )

--This procedure removes the saved prepared xml document


问:
has_changed() missing 2 required positional arguments: 'initial' and 'data'
I'm trying to prevent the user from meddling with a hidden form field by checking in the view like so:

if form.fields["email"].has_changed():
    form.add_error(
        "email",
        ValidationError(
            "Email does not correspond to user", code="invalid_email",
        ),
    )
```

but I get the following TypeError:

has_changed() missing 2 required positional arguments: 'initial' and 'data'

At this point, form is a "bound form" which has gone through the user and a POST request, by the way.

Inspecting the function itself, it does seem to have two non-optional parameters, but the documentation does not mention these at all, and it's not too clear to me what I should pass anyway: if I have to provide the initial value and the new value myself, I could just compare those by myself with no need for this method. What am I missing?

It also occurred to me that I just need to set the field as disabled and any changed value would be ignored, but I'm still curious nonetheless.

答:
The fact that it is a bound form makes not much difference. The form.fields is a dictionary that maps strings on form fields. The has_changed method [GitHub] for a field is used by the form to determine if the value has indeed changed.

You can check if a value has changed, by inspecting the changed_data dictionary:

```<code>if 'email' in <b>form.changed_data</b>:
    form.add_error(
        "email",
        ValidationError(
            "Email does not correspond to user", code="invalid_email",
        ),
    )</code>```

Body:
I'm trying to prevent the user from meddling with a hidden form field by checking in the view like so:

if form.fields["email"].has_changed():
    form.add_error(
        "email",
        ValidationError(
            "Email does not correspond to user", code="invalid_email",
        ),
    )

but I get the following TypeError:

has_changed() missing 2 required positional arguments: 'initial' and 'data'

At this point, form is a "bound form" which has gone through the user and a POST request, by the way.

Inspecting the function itself, it does seem to have two non-optional parameters, but the documentation does not mention these at all, and it's not too clear to me what I should pass anyway: if I have to provide the initial value and the new value myself, I could just compare those by myself with no need for this method. What am I missing?

It also occurred to me that I just need to set the field as disabled and any changed value would be ignored, but I'm still curious nonetheless.

Body:
The fact that it is a bound form makes not much difference. The form.fields is a dictionary that maps strings on form fields. The has_changed method [GitHub] for a field is used by the form to determine if the value has indeed changed.

You can check if a value has changed, by inspecting the changed_data dictionary:

if 'email' in form.changed_data:
    form.add_error(
        "email",
        ValidationError(
            "Email does not correspond to user", code="invalid_email",
        ),
    )


问:
Invalid object name 'dbo.AspNetUsers' in Asp.NET MVC 5 Entity Framework
If you have an existing database, and you want to include ASP.NET Identity tables to it, you can face this error. You may not know how to integrate [AspNetRoles], [AspNetUserClaims], [AspNetUsers], [AspNetUserLogins] tables into your existing database when you start. Although there are a lot of resources about this topic, this answer tries to be short and to the point. You may want to use the Database-First approach in Entity Framework together with the ASP.NET Identity feature of ASP.NET MVC. This is a very short tutorial for dummies. I am sorry if my English is poor.

答: the fastest way is to recreate a new project and select the authentication to individual. And then use the old files to instead the new ones.</p>


问:
Which commands do work with LOOP-END LOOP statements in SPSS?
As you know there are at least 3 ways to loop procedures in SPSS:

DO REPEAT-END REPEAT

LOOP-END LOOP

!DO-!DOEND structure inside DEFINE-!ENDDEFINE macro definition.

Now I'm asking about the second option. This kind of loop is more simple to use yet its functionality is significantly lesser than especially inside !DO-!DOEND structure.

Does anybody know which commands do work with LOOP-END LOOP and which doesn't? I tried to find a complete list but I haven't found anything.

答:
Konrad,
As others have mentioned it is good to copnsult the SPSS Statistics Documentation.  In this case, the SPSS Statistics Command Syntax Reference Guide is the one I'd choose.

https://www.ibm.com/support/knowledgecenter/SSLVMB_26.0.0/statistics_reference_project_ddita/spss/base/syn_commands_and_program_states_procedures.html

Briefly, the looping constructs you've mentioned all operate on Transformational commands -- commands that alter the data but do not require a read of the data.  Transformations (e.g. COMPUTE, RECODE, SELECT IF, etc.) stack up in memory and take effect when an EXECUTE or a procedure command cause a data read.

If what you are looking to do is to iterate procedural commands (e.g. FREQUENCIES, REGRESSION, GGRAPH, etc.), that can be accomplished through the DEFINE--!ENDDEFINE command language, or better still through a Python script.

I hope this helps.


问:
how to get workgroup name in vba?
Is It possibly get this value?

答:
Unless your domain is more than one, you can retrieve by:

```<code>Environ("USERDNSDOMAIN") ' Or Environ("USERDOMAIN")
Environ("COMPUTERNAME")
</code>```

It's same value as output of set in command prompt.

Title: how to get workgroup name in vba?

Body: Is It possibly get this value?

Body:
Unless your domain is more than one, you can retrieve by:

Environ("USERDNSDOMAIN") ' Or Environ("USERDOMAIN")
Environ("COMPUTERNAME")

It's same value as output of set in command prompt.


问:
Slowly changing dimensions in HANA Views?
I am a newbie to HANA.Our org is planning to build a native datawarehouse on top of SAP HANA. Till date we have implemented SCD types using the ETL approach in SAP BODS. Wondering if some types of SCD's could be offloaded onto the HANA Studio by utilising the Views in HANA. Please help me in this regard.</p>

答:
This is a rather broad question that does not allow for a single correct answer.
With slowly changing dimensions (SCD) one tries to preserve data changes over time in a data warehouse. The idea is that changing “master”-data, e.g. which sales person is responsible for which sales region, can be correctly reflected in queries.
One approach (SCD type 2) uses validity timestamps for the records to indicate the time for which those were the valid information.
This approach can be implemented easily with HANA as all one needs to do is to add those validity timestamps to the dimension table. HANA 2 takes this a bit further by providing Bi-temporal history tables (system- and application time).
For this use case one could use the application time ranges in combination with the SELECT ... AS OF TIMESTAMP... feature. This will automatically filter the records that were valid at the provided point in time.
This is also supported with calculation views, CDS views and SQL views.

Whether or not that is improving upon your existing setup is a different question altogether.


问:
using spread syntax with ternary operator inside object literal
Consider following code, where one object is composed from two parts: values and their corresponding descriptions:

let flagConfigObj = {};

const features = {
  f1: {
    value: 1,
    type: 'type1'
  },
  f2: {
    value: 2,
    type: 'type2'
  }
};

let featuresDescription = {
  f1: {
    description: 'desc 1'
  },
  f2: {
    description: 'desc 2'
  }
};

Object.keys(features).forEach(key => {
  flagConfigObj[key] = {
    ...features[key],
    ...(featuresDescription[key] || { some: 'backup' })
  };
});

console.log(flagConfigObj);

```

<p>As you might notice, when composite is constructed, there is <code>||</code> operator preventing form spreading non-existing object and replacing it with some default templates. And so, output for this code will be:</p>

```{
  f1: { value: 1, type: 'type1', description: 'desc 1' },
  f2: { value: 2, type: 'type2', description: 'desc 2' }
}
```

<p>But when corresponding description field in <code>featuresDescription</code> is missing, it's replaced to:</p>

```{
  f1: { value: 1, type: 'type1', description: 'desc 1' },
  f2: { value: 2, type: 'type2', some: 'backup' }
}
```

<p><strong>The question</strong></p>

<p>How to replace <code>||</code> syntax with ternary operator <code>?:</code>?
I've tried some funny combinations like </p>

```featuresDescription[key] ? ...featuresDescription[key] : {some: 'backup'}
{featuresDescription[key]} ? ...featuresDescription[key] : {some: 'backup'}
```

But all of them gives syntax error, and I'm feeling now like just blindly randomizing positions of [,],},{,... instead of truly understanding it...

Any help as always is appreciated!

答:
I think this would work

...(featuresDescription[key] ? featuresDescription[key] : { some: 'backup' })
```

<p>full example: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let flagConfigObj = {};

const features = {
  f1: {
    value: 1,
    type: 'type1'
  },
  f2: {
    value: 2,
    type: 'type2'
  },
  f3: {
    value: 3,
    type: 'type3'
  }
};

let featuresDescription = {
  f1: {
    description: 'desc 1'
  },
  f2: {
    description: 'desc 2'
  },
};

Object.keys(features).forEach(key => {
  flagConfigObj[key] = {
    ...features[key],
    ...(featuresDescription[key] ? featuresDescription[key] : { some: 'backup' })
  };
});

console.log(flagConfigObj);</code>```

However, I still prefer using || as below

...(featuresDescription[key] || { some: 'backup' })
```

because it is simpler and not repetitive regarding featuresDescription[key]

Hope it helps

Body:
Consider following code, where one object is composed from two parts: values and their corresponding descriptions:

let flagConfigObj = {};

const features = {
  f1: {
    value: 1,
    type: 'type1'
  },
  f2: {
    value: 2,
    type: 'type2'
  }
};

let featuresDescription = {
  f1: {
    description: 'desc 1'
  },
  f2: {
    description: 'desc 2'
  }
};

Object.keys(features).forEach(key => {
  flagConfigObj[key] = {
    ...features[key],
    ...(featuresDescription[key] || { some: 'backup' })
  };
});

console.log(flagConfigObj);

As you might notice, when composite is constructed, there is || operator preventing form spreading non-existing object and replacing it with some default templates. And so, output for this code will be:

{
  f1: { value: 1, type: 'type1', description: 'desc 1' },
  f2: { value: 2, type: 'type2', description: 'desc 2' }
}

But when corresponding description field in featuresDescription is missing, it's replaced to:

{
  f1: { value: 1, type: 'type1', description: 'desc 1' },
  f2: { value: 2, type: 'type2', some: 'backup' }
}

The question

How to replace || syntax with ternary operator ?:?
I've tried some funny combinations like

featuresDescription[key] ? ...featuresDescription[key] : {some: 'backup'}
{featuresDescription[key]} ? ...featuresDescription[key] : {some: 'backup'}

But all of them gives syntax error, and I'm feeling now like just blindly randomizing positions of [,],},{,... instead of truly understanding it...

Any help as always is appreciated!

Body:
I think this would work

...(featuresDescription[key] ? featuresDescription[key] : { some: 'backup' })

full example:

let flagConfigObj = {};

const features = {
  f1: {
    value: 1,
    type: 'type1'
  },
  f2: {
    value: 2,
    type: 'type2'
  },
  f3: {
    value: 3,
    type: 'type3'
  }
};

let featuresDescription = {
  f1: {
    description: 'desc 1'
  },
  f2: {
    description: 'desc 2'
  },
};

Object.keys(features).forEach(key => {
  flagConfigObj[key] = {
    ...features[key],
    ...(featuresDescription[key] ? featuresDescription[key] : { some: 'backup' })
  };
});

console.log(flagConfigObj);

However, I still prefer using || as below

...(featuresDescription[key] || { some: 'backup' })

because it is simpler and not repetitive regarding featuresDescription[key]

Hope it helps


问:
How to use Regex in Oracle SQL request
I have this complex string in a database, which represents 4 elements separated by delimeters '|'

```<code>1944913|200010|157|4*
1944913|200085|157|1.22*
</code>```

NOTE: both lines of strings exist in the same database row. There could be up to 10 lines of strings in a single cell

I want an oracle sql command that, given either 200010 or 200085, returns either the 1st or second element next to it, like:

Given 200010, returns 157 or returns 4*
Given 200085, returns 157 or returns 1.22

How would I go about doing that?

答:
You can split this into columns easily.  So, I think something like this is pretty much what you want:</p>

```<code>select regexp_substr(col, '[^|]+', 1, 2) as val_2,
       regexp_substr(col, '[^|]+', 1, 3) as val_3,
       regexp_substr(col, '[^|]+', 1, 4) as val_4

from t;
</code>```

Title: How to use Regex in Oracle SQL request

Body:
I have this complex string in a database, which represents 4 elements separated by delimeters '|'

1944913|200010|157|4*
1944913|200085|157|1.22*

NOTE: both lines of strings exist in the same database row. There could be up to 10 lines of strings in a single cell

I want an oracle sql command that, given either 200010 or 200085, returns either the 1st or second element next to it, like:

Given 200010, returns 157 or returns 4*
Given 200085, returns 157 or returns 1.22

How would I go about doing that?

Body:
You can split this into columns easily.  So, I think something like this is pretty much what you want:

select regexp_substr(col, '[^|]+', 1, 2) as val_2,
       regexp_substr(col, '[^|]+', 1, 3) as val_3,
       regexp_substr(col, '[^|]+', 1, 4) as val_4

from t;


问:
xlmhg 2.5.4 has requirement plotly>=3, but you'll have plotly 2.7.0 which is incompatible
I tried to install celseq2 in my Ubuntu system.

```<code>ERROR: xlmhg 2.5.4 has requirement plotly>=3, but you'll have plotly 2.7.0 which is incompatible.
</code>```

答:
```<code>li@lion-Desktop-590-p0xxx:~$ pip install plotly
</code>```

Body:
I tried to install celseq2 in my Ubuntu system.

ERROR: xlmhg 2.5.4 has requirement plotly>=3, but you'll have plotly 2.7.0 which is incompatible.


问:
Solving differential equation in R - deSolve
I have an equation as below;

```<code>dN/dt = N(t)G(t)
</code>```

G(t) is given by the equation: dG/dt = a * G
 How do I solve this in R, using ode function from deSolve package?

答:
As dario already mentioned, the question lacks some details. Nevertheless, let's try an answer. If we assume that a < 0, the model looks like the ode formulation of Gompertz growth:

```<code>dN/dt = N * G
dG/dt = a * G
</code>```

This can then be solved as:

```<code>library(deSolve)

model <- function(t, y, p) {
  with(as.list(c(y, p)), {
    dN <-  N * G
    dG <-  a * G
    list(c(dN, dG))
  })
}

y      <- c(N = 1, G = 1)
parms  <- c(a = -0.1)
times  <- seq(0, 100)
out <- ode(y, times, model, parms)
plot(out)
</code>```

Body:
I have an equation as below;

dN/dt = N(t)G(t)

G(t) is given by the equation: dG/dt = a * G
 How do I solve this in R, using ode function from deSolve package?

Body:
As dario already mentioned, the question lacks some details. Nevertheless, let's try an answer. If we assume that a < 0, the model looks like the ode formulation of Gompertz growth:

dN/dt = N * G
dG/dt = a * G

This can then be solved as:

library(deSolve)

model <- function(t, y, p) {
  with(as.list(c(y, p)), {
    dN <-  N * G
    dG <-  a * G
    list(c(dN, dG))
  })
}

y      <- c(N = 1, G = 1)
parms  <- c(a = -0.1)
times  <- seq(0, 100)
out <- ode(y, times, model, parms)
plot(out)


问:
Iterate over list to get values in a specified sequence
I had an initial tuple, over which I was trying to iterate to perform further calculations. However, I end up having an error "too many values to unpack" which was solved by following suggestions from this question asked previously(Python - too many values to unpack). However, right now after converting it to a list, I have another error 'list' object has no attribute 'reshape'.

My code looks like this:

```<code>Z=[([A,3],[A1,6])]  #A and A1 are 2x2 matrices
y=[]
for data,label in Z:

    x = data.reshape((4,))
    y.append(int(label))
</code>```

I can understand the cause of the error. In this case, I want the loop to run two times (because I have two sets of data [A-3,A1-6]) and data, label to be: A, 3 and A1, 6. But it is being misread as data = [A,3] and label = [A1,6].

What would be the proper way to loop through this list and generate data the way I want?

N.B: The Z doesn't need to be a list, I can change it to a tuple if that makes life easier.

答:
The tuple is inside a list. You're just iterating over the list, but not over the tuple elements. You need nested loops.

```<code>for t in Z:
    for data, label in t:
        x = data.reshape(4,)
        y.append(int(label))
</code>```

You don't need the nested loops if you get rid of the list.

```<code>Z=([A,3],[A1,6])  #A and A1 are 2x2 matrices
y=[]
for data,label in Z:
    x = data.reshape((4,))
    y.append(int(label))
</code>```

Body:
I had an initial tuple, over which I was trying to iterate to perform further calculations. However, I end up having an error "too many values to unpack" which was solved by following suggestions from this question asked previously(Python - too many values to unpack). However, right now after converting it to a list, I have another error 'list' object has no attribute 'reshape'.

My code looks like this:

Z=[([A,3],[A1,6])]  #A and A1 are 2x2 matrices
y=[]
for data,label in Z:

    x = data.reshape((4,))
    y.append(int(label))

I can understand the cause of the error. In this case, I want the loop to run two times (because I have two sets of data [A-3,A1-6]) and data, label to be: A, 3 and A1, 6. But it is being misread as data = [A,3] and label = [A1,6].

What would be the proper way to loop through this list and generate data the way I want?

N.B: The Z doesn't need to be a list, I can change it to a tuple if that makes life easier.

Body:
The tuple is inside a list. You're just iterating over the list, but not over the tuple elements. You need nested loops.

for t in Z:
    for data, label in t:
        x = data.reshape(4,)
        y.append(int(label))

You don't need the nested loops if you get rid of the list.

Z=([A,3],[A1,6])  #A and A1 are 2x2 matrices
y=[]
for data,label in Z:
    x = data.reshape((4,))
    y.append(int(label))


问:
Localize iOS Info.plist Privacy Strings
I want to localize the privacy strings from the Runner's info.plist file, but fail to find how. In the official documentation (https://flutter.dev/docs/development/accessibility-and-localization/internationalization) at the very end is stated to add a key named "*eLocalizations**", but I don't see that if I try to add some new key to the plist (having the top item selected like written in the docs).

Any idea what I'm doing wrong? Please see attached what I see in Xcode when I add a new key.

答: One way is to create an InfoPlist.strings file and localize that. The Info.plist will pull the appropriate translation from these files.

Title: Localize iOS Info.plist Privacy Strings


问:
Reading from Kafka with Scala Spark2 Streaming
I need to connect to Kafka and read data from it (after that I have to write in ElasticSearch Database), but for now, I just want to read and print data..

I am newbie with both Kafka and Scala, and reading in internet I have coded this:

```<code>//spark
import org.apache.spark._
import org.apache.spark.streaming._

//kafka
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.kafka010._
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe

object Main extends App{

val master = "local[2]"
val hostname = ""

val conf = new SparkConf().setAppName("KafkaConnection").setMaster(master)
val sc = SparkContext.getOrCreate(conf)
val ssc = new StreamingContext(sc, Seconds(1))

val kafkaParams = Map[String, Object](
  "bootstrap.servers" -> "localhost:9092,anotherhost:9092",
  "key.deserializer" -> classOf[StringDeserializer],
  "value.deserializer" -> classOf[StringDeserializer],
  "group.id" -> "IRC",
  "auto.offset.reset" -> "latest",
  "enable.auto.commit" -> (false: java.lang.Boolean)
)

val topics = Array("topicA", "topicB")
val stream = KafkaUtils.createDirectStream[String, String](
  ssc,  PreferConsistent,  Subscribe[String, String](topics, kafkaParams))

stream.map(record => (record.key, record.value))

val offsetRanges = Array(
  // topic, partition, inclusive starting offset, exclusive ending offset
  OffsetRange("test", 0, 0, 100),
  OffsetRange("test", 1, 0, 100)
)

val rdd = KafkaUtils.createRDD[String, String](
    ssc, kafkaParams, offsetRanges, PreferConsistent)

}

</code>```

But I don't know how to continue. What do I need now? Also, do you know any public Kafka Broker/topic which I can use to read from it?

Thank you in advance!

答:
What do I need now?

Try running the code. spark-submit or run the main method.

do you know any public Kafka Broker/topic which I can use to read from it?

That would be insecure, so no. Start your own brokers locally following Kafka quickstart official guides.

Your code currently reads from a topic called test

Body:
I need to connect to Kafka and read data from it (after that I have to write in ElasticSearch Database), but for now, I just want to read and print data..

I am newbie with both Kafka and Scala, and reading in internet I have coded this:

//spark
import org.apache.spark._
import org.apache.spark.streaming._

//kafka
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.kafka010._
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe

object Main extends App{

val master = "local[2]"
val hostname = ""

val conf = new SparkConf().setAppName("KafkaConnection").setMaster(master)
val sc = SparkContext.getOrCreate(conf)
val ssc = new StreamingContext(sc, Seconds(1))

val kafkaParams = Map[String, Object](
  "bootstrap.servers" -> "localhost:9092,anotherhost:9092",
  "key.deserializer" -> classOf[StringDeserializer],
  "value.deserializer" -> classOf[StringDeserializer],
  "group.id" -> "IRC",
  "auto.offset.reset" -> "latest",
  "enable.auto.commit" -> (false: java.lang.Boolean)
)

val topics = Array("topicA", "topicB")
val stream = KafkaUtils.createDirectStream[String, String](
  ssc,  PreferConsistent,  Subscribe[String, String](topics, kafkaParams))

stream.map(record => (record.key, record.value))

val offsetRanges = Array(
  // topic, partition, inclusive starting offset, exclusive ending offset
  OffsetRange("test", 0, 0, 100),
  OffsetRange("test", 1, 0, 100)
)

val rdd = KafkaUtils.createRDD[String, String](
    ssc, kafkaParams, offsetRanges, PreferConsistent)

}

But I don't know how to continue. What do I need now? Also, do you know any public Kafka Broker/topic which I can use to read from it?

Thank you in advance!


问:
MonoBehavior methods doesn't shown at visual studio 2019
I have a strange problem with my Scripts in Unity/Visual studio
none of the monoBehavior Methods will be shown in VS editor! i mean VS doesn't recognize them for example when i want to use "OnTriggerEnter2D" the editor doesn't recognize it.
also i tried to open scripts with MonoDevelop but didn't help.

Unity version: 5.6.7f1 pro

Visual studio version: 2019 Enterprise

```<code>public class Score : MonoBehaviour {
    // Use this for initialization
    void Start() {
    }

    // Update is called once per frame
    void Update() {
        Debug.Log("Test!");
    }
    void OnTriggerEnter(){}   //  this line isn't recognized by intellisense
}
</code>```

答:
Had a big fight with the OnTriggerEnter this evening + night :)
Solved : use VS 2017 !!!

From a post Ive read it seems to be a Unity issue, haha !

explanation :
  (https://developercommunity.visualstudio.com/content/problem/663323/visual-studios-2019-intellisense-not-recognizing-u.html)

Body:
I have a strange problem with my Scripts in Unity/Visual studio
none of the monoBehavior Methods will be shown in VS editor! i mean VS doesn't recognize them for example when i want to use "OnTriggerEnter2D" the editor doesn't recognize it.
also i tried to open scripts with MonoDevelop but didn't help.

Unity version: 5.6.7f1 pro

Visual studio version: 2019 Enterprise

public class Score : MonoBehaviour {
    // Use this for initialization
    void Start() {
    }

    // Update is called once per frame
    void Update() {
        Debug.Log("Test!");
    }
    void OnTriggerEnter(){}   //  this line isn't recognized by intellisense
}


问:
Stuck on Paper-Scissors-Rock game
While loop iterates two times every time, and CPU only scores point when choosing 'S' for scissors. Another question is, how do I make it toupper and where do I add that function? I have to use characters 'r','s', and 'p', instead of 1,2,3 to accept user input. Not sure how to proceed to fix this</p>

```<code>#include <stdlib.h>
#include<time.h>

int main () {

   char player1;
   int player2;
   int userScore = 0, cpuScore = 0;
   player2 = rand ( ) % 3 + 1;
   srand ((int) time (NULL));

int count = 0;
while(count <= 10) {
  printf("\nEnter p for Paper, r for rock, or S for scissor: ");
  scanf("%c", &player1);
   switch(player1) {
      case 'P' :
       if(player1 == 'P' && player2 == 1) {
         printf("Draw!");
         break;
       } else if(player1 == 'P' && player2 == 2) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'R':
         if(player1 == 'R' && player2 == 2) {
         printf("Draw!");
         break;
       } else if(player1 == 'R' && player2 == 3) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'S':
        if(player1 == 'S' && player2 == 3) {
         printf("Draw!");
         break;
       } else if(player1 == 'S' && player2 == 1) {
         userScore++;
         break;
         printf("User won this one!");
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      default :
         printf("\nInvalid Input");
         break;
   }
   printf("\nUser Score: %d", userScore);
   printf("\nCPU Score: %d", cpuScore);
   count++;
}
   if(userScore == cpuScore) {
     printf("\nDraw game!");
   } else if(userScore > cpuScore) {
     printf("\nYou win!");
   } else {
     printf("\nCPU wins!");
   }
   return 0;
} ```
</code>```

答:
Try this:

```<code>#include <stdio.h>
#include <stdlib.h>
int main () {
   char player1;
   int player2;
   int userScore = 0, cpuScore = 0;
   srand ((int) time (NULL));
   int count = 0;
   while(count != 10) {
       printf("Enter p for Paper, r for rock, or S for scissor:\n");
       fgets(&player1, 80, stdin);
       player2 = rand ( ) % 4;
       if(player1 == 'P' && player2 == 1) {
         printf("Draw!\n");
       }if(player1 == 'P' && player2 == 2) {
        userScore++;
        printf("User won this one!\n");
       }if(player1 == 'P' && player2 == 3){
         cpuScore++;
         printf("CPU won this one!\n");
       }
       if(player1 == 'R' && player2 == 2) {
         printf("Draw!\n");
       }if(player1 == 'R' && player2 == 3) {
         userScore++;
         printf("User won this one!\n");
       }if(player1 == 'R' && player2 == 1){
         cpuScore++;
         printf("CPU won this one!\n");
       }
       if(player1 == 'S' && player2 == 3) {
         printf("Draw!\n");
       }if(player1 == 'S' && player2 == 1) {
         userScore++;
         printf("User won this one!\n");
       }if(player1 == 'S' && player2 == 2){
         cpuScore++;
         printf("CPU won this one!\n");
       }
       if(player1!='S' || player1!='R' || player1!='P'){
         printf("Invalid Input\n");
       }
    printf("User Score: %d\n", userScore);
    printf("CPU Score: %d\n", cpuScore);
    count++;
}
   if(userScore == cpuScore) {
     printf("Draw game!\n");
   } else if(userScore > cpuScore) {
     printf("You win!\n");
   } else {
     printf("CPU wins!\n");
   }
   return 0;
}
</code>```

I should also add that this program is sensitive. For example, inputting 'r' will not work but 'R' will. Change this at your discretion.

Title: Stuck on Paper-Scissors-Rock game

Body:
While loop iterates two times every time, and CPU only scores point when choosing 'S' for scissors. Another question is, how do I make it toupper and where do I add that function? I have to use characters 'r','s', and 'p', instead of 1,2,3 to accept user input. Not sure how to proceed to fix this

#include <stdlib.h>
#include<time.h>

int main () {

   char player1;
   int player2;
   int userScore = 0, cpuScore = 0;
   player2 = rand ( ) % 3 + 1;
   srand ((int) time (NULL));

int count = 0;
while(count <= 10) {
  printf("\nEnter p for Paper, r for rock, or S for scissor: ");
  scanf("%c", &player1);
   switch(player1) {
      case 'P' :
       if(player1 == 'P' && player2 == 1) {
         printf("Draw!");
         break;
       } else if(player1 == 'P' && player2 == 2) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'R':
         if(player1 == 'R' && player2 == 2) {
         printf("Draw!");
         break;
       } else if(player1 == 'R' && player2 == 3) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'S':
        if(player1 == 'S' && player2 == 3) {
         printf("Draw!");
         break;
       } else if(player1 == 'S' && player2 == 1) {
         userScore++;
         break;
         printf("User won this one!");
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      default :
         printf("\nInvalid Input");
         break;
   }
   printf("\nUser Score: %d", userScore);
   printf("\nCPU Score: %d", cpuScore);
   count++;
}
   if(userScore == cpuScore) {
     printf("\nDraw game!");
   } else if(userScore > cpuScore) {
     printf("\nYou win!");
   } else {
     printf("\nCPU wins!");
   }
   return 0;
} ```

Body:
Try this:

#include <stdio.h>
#include <stdlib.h>
int main () {
   char player1;
   int player2;
   int userScore = 0, cpuScore = 0;
   srand ((int) time (NULL));
   int count = 0;
   while(count != 10) {
       printf("Enter p for Paper, r for rock, or S for scissor:\n");
       fgets(&player1, 80, stdin);
       player2 = rand ( ) % 4;
       if(player1 == 'P' && player2 == 1) {
         printf("Draw!\n");
       }if(player1 == 'P' && player2 == 2) {
        userScore++;
        printf("User won this one!\n");
       }if(player1 == 'P' && player2 == 3){
         cpuScore++;
         printf("CPU won this one!\n");
       }
       if(player1 == 'R' && player2 == 2) {
         printf("Draw!\n");
       }if(player1 == 'R' && player2 == 3) {
         userScore++;
         printf("User won this one!\n");
       }if(player1 == 'R' && player2 == 1){
         cpuScore++;
         printf("CPU won this one!\n");
       }
       if(player1 == 'S' && player2 == 3) {
         printf("Draw!\n");
       }if(player1 == 'S' && player2 == 1) {
         userScore++;
         printf("User won this one!\n");
       }if(player1 == 'S' && player2 == 2){
         cpuScore++;
         printf("CPU won this one!\n");
       }
       if(player1!='S' || player1!='R' || player1!='P'){
         printf("Invalid Input\n");
       }
    printf("User Score: %d\n", userScore);
    printf("CPU Score: %d\n", cpuScore);
    count++;
}
   if(userScore == cpuScore) {
     printf("Draw game!\n");
   } else if(userScore > cpuScore) {
     printf("You win!\n");
   } else {
     printf("CPU wins!\n");
   }
   return 0;
}

I should also add that this program is sensitive. For example, inputting 'r' will not work but 'R' will. Change this at your discretion.


问:
C++ to Java Code Conversion
I have in C++

```<code>r.bits[k] &= 0xFF ^ msk;
</code>```

So in Java

```<code>r.bits[k] = r.bits[k] & 0xFF,
</code>```

but what is the meaning of the caret symbol? msk also will contain hexadecimal values.
I know the caret symbol is a type of pointer in C++ but not sure what it is doing here.
Please explain.

答: The carat symbol is the xor operator see here</p>

Title: C++ to Java Code Conversion

Body:
I have in C++

r.bits[k] &= 0xFF ^ msk;

So in Java

r.bits[k] = r.bits[k] & 0xFF,

but what is the meaning of the caret symbol? msk also will contain hexadecimal values.
I know the caret symbol is a type of pointer in C++ but not sure what it is doing here.
Please explain.


问:
How to implement User Alerts when users signup using auth Firebase in Flutter
Hello I'm trying to find out how to implement alerts when users are trying to login or signup to my app.

The below code is my "auth-service-dart' page and I am trying to display the message error that shows in the console from (print(e)) per the code below to my signup page where I have the signup button, so the result I want is the app shows alerts if the users make errors like adding an email that was already added or wrong email.

```<code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class AuthService {
  static final _auth = FirebaseAuth.instance;

  static final _firestore = Firestore.instance;

  static void signUpUser(
      BuildContext context, String name, String email, String password) async {
    try {
      AuthResult authResult = await _auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
      FirebaseUser signedInUser = authResult.user;
      if (signedInUser != null) {
        _firestore.collection('/users').document(signedInUser.uid).setData({
          'name': name,
          'email': email,
          'profileImageUrl': '',
        });
        Navigator.pushReplacementNamed(context, signedInUser.uid);
        //Provider.of<UserData>(context).currentUserId = signedInUser.uid;
        //Navigator.pop(context);
      }
    } catch (e) {
      print(e);
    }
  }

  static void logout() {
    _auth.signOut();
    //Navigator.pushReplacementNamed(context, LoginScreen.id);
  }

  static void login(String email, String password) async {
    try {
      await _auth.signInWithEmailAndPassword(email: email, password: password);
    } catch (e) {
      print(e);
    }
  }
}
</code>```

答:
you can use the showDialog provided by flutter;
here is a simple code for that in your widget

```<code> showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Error happend'),
          content: Text(// your errro code here),
          actions: <Widget>[
            MaterialButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              color: Theme.of(context).primaryColor,
              child: Text(language['ok']),
            ),
          ],
        );
      },
    );
</code>```

Body:
Hello I'm trying to find out how to implement alerts when users are trying to login or signup to my app.

The below code is my "auth-service-dart' page and I am trying to display the message error that shows in the console from (print(e)) per the code below to my signup page where I have the signup button, so the result I want is the app shows alerts if the users make errors like adding an email that was already added or wrong email.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class AuthService {
  static final _auth = FirebaseAuth.instance;

  static final _firestore = Firestore.instance;

  static void signUpUser(
      BuildContext context, String name, String email, String password) async {
    try {
      AuthResult authResult = await _auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
      FirebaseUser signedInUser = authResult.user;
      if (signedInUser != null) {
        _firestore.collection('/users').document(signedInUser.uid).setData({
          'name': name,
          'email': email,
          'profileImageUrl': '',
        });
        Navigator.pushReplacementNamed(context, signedInUser.uid);
        //Provider.of<UserData>(context).currentUserId = signedInUser.uid;
        //Navigator.pop(context);
      }
    } catch (e) {
      print(e);
    }
  }

  static void logout() {
    _auth.signOut();
    //Navigator.pushReplacementNamed(context, LoginScreen.id);
  }

  static void login(String email, String password) async {
    try {
      await _auth.signInWithEmailAndPassword(email: email, password: password);
    } catch (e) {
      print(e);
    }
  }
}

Body:
you can use the showDialog provided by flutter;
here is a simple code for that in your widget

 showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Error happend'),
          content: Text(// your errro code here),
          actions: <Widget>[
            MaterialButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              color: Theme.of(context).primaryColor,
              child: Text(language['ok']),
            ),
          ],
        );
      },
    );


问:
Object p not found when running gbm()
I am aware of the question GBM: Object 'p' not found; however it did not contain sufficient information to allow the stack to answer. I don't believe this is a duplicate as I've followed what was indicated in this question and the linked duplicate Error in R gbm function when cv.folds > 0 which, does not describe the same error.

I have been sure to follow the recommendation of leaving out any columns that were not used in the model.

This error appears when the cv.folds is greater than 0:
object 'p' not found

From what I can see, setting cv.folds to 0 is not producing meaningful outputs.I have attempted different distributions, fractions, trees etc. I'm confident I've parameterized something incorrectly but I can't for the life of me see what it is.

Model and output:

```<code>model_output <- gbm(formula = ign ~ . ,
                  distribution = "bernoulli",
                  var.monotone = rep(0,9),
                  data = model_sample,
                  train.fraction = 0.50,
                  n.cores = 1,
                  n.trees = 150,
                  cv.folds = 1,
                  keep.data = T,
                  verbose=T)
Iter   TrainDeviance   ValidDeviance   StepSize   Improve
     1           nan             nan     0.1000       nan
     2           nan             nan     0.1000       nan
     3           nan             nan     0.1000       nan
     4           nan             nan     0.1000       nan
     5           nan             nan     0.1000       nan
     6           nan             nan     0.1000       nan
     7           nan             nan     0.1000       nan
     8           nan             nan     0.1000       nan
     9           nan             nan     0.1000       nan
    10           nan             nan     0.1000       nan
    20           nan             nan     0.1000       nan
    40           nan             nan     0.1000       nan
    60           nan             nan     0.1000       nan
    80           nan             nan     0.1000       nan
   100           nan             nan     0.1000       nan
   120           nan             nan     0.1000       nan
   140           nan             nan     0.1000       nan
   150           nan             nan     0.1000       nan
</code>```

Minimum data to generate error used to be here, however once the suggest by @StupidWolf is employed it is too small, the suggestion below will get passed the initial error. Subsequent errors are occurring and solutions will be posted here upon discovery.

答:
It's not meant to deal with the situation someone sets cv.folds = 1. By definition, k fold means splitting the data into k parts, training on 1 part and testing on the other.. So I am not so sure what is 1 -fold cross validation, and if you look at the code for gbm, at line 437

```<code>  if(cv.folds > 1) {
    cv.results <- gbmCrossVal(cv.folds = cv.folds, nTrain = nTrain,
    ....
    p <- cv.results$predictions
}
</code>```

It makes the predictions and when it collects the results into gbm, line 471:

```<code>  if (cv.folds > 0) {
    gbm.obj$cv.fitted <- p
  }
</code>```

So if cv.folds ==1, p is not calculated, but it is > 0 hence you get the error.

Below is a reproducible example:

```<code>library(MASS)
test = Pima.tr
test$type = as.numeric(test$type)-1

model_output <- gbm(type~ . ,
                  distribution = "bernoulli",
                  var.monotone = rep(0,7),
                  data = test,
                  train.fraction = 0.5,
                  n.cores = 1,
                  n.trees = 30,
                  cv.folds = 1,
                  keep.data = TRUE,
                  verbose=TRUE)
</code>```

gives me the error object 'p' not found

Set it to cv.folds = 2, and it runs smoothly....

```<code>model_output <- gbm(type~ . ,
                  distribution = "bernoulli",
                  var.monotone = rep(0,7),
                  data = test,
                  train.fraction = 0.5,
                  n.cores = 1,
                  n.trees = 30,
                  cv.folds = 2,
                  keep.data = TRUE,
                  verbose=TRUE)
</code>```

Title: Object p not found when running gbm()

Body:
I am aware of the question GBM: Object 'p' not found; however it did not contain sufficient information to allow the stack to answer. I don't believe this is a duplicate as I've followed what was indicated in this question and the linked duplicate Error in R gbm function when cv.folds > 0 which, does not describe the same error.

I have been sure to follow the recommendation of leaving out any columns that were not used in the model.

This error appears when the cv.folds is greater than 0:
object 'p' not found

From what I can see, setting cv.folds to 0 is not producing meaningful outputs.I have attempted different distributions, fractions, trees etc. I'm confident I've parameterized something incorrectly but I can't for the life of me see what it is.

Model and output:

model_output <- gbm(formula = ign ~ . ,
                  distribution = "bernoulli",
                  var.monotone = rep(0,9),
                  data = model_sample,
                  train.fraction = 0.50,
                  n.cores = 1,
                  n.trees = 150,
                  cv.folds = 1,
                  keep.data = T,
                  verbose=T)
Iter   TrainDeviance   ValidDeviance   StepSize   Improve
     1           nan             nan     0.1000       nan
     2           nan             nan     0.1000       nan
     3           nan             nan     0.1000       nan
     4           nan             nan     0.1000       nan
     5           nan             nan     0.1000       nan
     6           nan             nan     0.1000       nan
     7           nan             nan     0.1000       nan
     8           nan             nan     0.1000       nan
     9           nan             nan     0.1000       nan
    10           nan             nan     0.1000       nan
    20           nan             nan     0.1000       nan
    40           nan             nan     0.1000       nan
    60           nan             nan     0.1000       nan
    80           nan             nan     0.1000       nan
   100           nan             nan     0.1000       nan
   120           nan             nan     0.1000       nan
   140           nan             nan     0.1000       nan
   150           nan             nan     0.1000       nan

Minimum data to generate error used to be here, however once the suggest by @StupidWolf is employed it is too small, the suggestion below will get passed the initial error. Subsequent errors are occurring and solutions will be posted here upon discovery.

Body:
It's not meant to deal with the situation someone sets cv.folds = 1. By definition, k fold means splitting the data into k parts, training on 1 part and testing on the other.. So I am not so sure what is 1 -fold cross validation, and if you look at the code for gbm, at line 437

  if(cv.folds > 1) {
    cv.results <- gbmCrossVal(cv.folds = cv.folds, nTrain = nTrain,
    ....
    p <- cv.results$predictions
}

It makes the predictions and when it collects the results into gbm, line 471:

  if (cv.folds > 0) {
    gbm.obj$cv.fitted <- p
  }

So if cv.folds ==1, p is not calculated, but it is > 0 hence you get the error.

Below is a reproducible example:

library(MASS)
test = Pima.tr
test$type = as.numeric(test$type)-1

model_output <- gbm(type~ . ,
                  distribution = "bernoulli",
                  var.monotone = rep(0,7),
                  data = test,
                  train.fraction = 0.5,
                  n.cores = 1,
                  n.trees = 30,
                  cv.folds = 1,
                  keep.data = TRUE,
                  verbose=TRUE)

gives me the error object 'p' not found

Set it to cv.folds = 2, and it runs smoothly....

model_output <- gbm(type~ . ,
                  distribution = "bernoulli",
                  var.monotone = rep(0,7),
                  data = test,
                  train.fraction = 0.5,
                  n.cores = 1,
                  n.trees = 30,
                  cv.folds = 2,
                  keep.data = TRUE,
                  verbose=TRUE)


问:
Incomplete type error (E0409, E0070, E0515)
In my code Main.cpp I have the following shown below. The issue I am running into us with tuple<int, int, int>
I keep getting these three errors

function "sPA" returns incomplete type "trie", incomplete type is not allowed, and
cannot convert to incomplete class "trie"

What am I doing wrong here to make this error?

```<code> // Main.cpp
 #include <iostream>
 #include <string>
 using namespace std;

 typedef pair<int, int> int_pair;
 typedef tuple<int, int, int> trie;

 int_pair sum_and_product(int a, int b) {
     return int_pair(a + b, a * b);
 }

 trie sPA(int a, int b, int c) {
     trie t{ a + b + c,a * b * c,((a + b + c) / 3) };
     return t;
 }

 void consuming_templates() {
     int a = 2, b = 3, c = 4;
     auto results = sum_and_product(a,b);
     cout << "sum = " << results.first << "|product = " << results.second << endl;
     auto r2 = sPA(a, b, c);
 }

int main(int argc, char* argv[]) {

    consuming_templates();

    return 0;
}
</code>```

答:
idclev 463035818 and M.M has posted the comment to answer my question

You need to do #include <tuple> and #include <utility>

Body:
In my code Main.cpp I have the following shown below. The issue I am running into us with tuple<int, int, int>
I keep getting these three errors

function "sPA" returns incomplete type "trie", incomplete type is not allowed, and
cannot convert to incomplete class "trie"

What am I doing wrong here to make this error?

 // Main.cpp
 #include <iostream>
 #include <string>
 using namespace std;

 typedef pair<int, int> int_pair;
 typedef tuple<int, int, int> trie;

 int_pair sum_and_product(int a, int b) {
     return int_pair(a + b, a * b);
 }

 trie sPA(int a, int b, int c) {
     trie t{ a + b + c,a * b * c,((a + b + c) / 3) };
     return t;
 }

 void consuming_templates() {
     int a = 2, b = 3, c = 4;
     auto results = sum_and_product(a,b);
     cout << "sum = " << results.first << "|product = " << results.second << endl;
     auto r2 = sPA(a, b, c);
 }

int main(int argc, char* argv[]) {

    consuming_templates();

    return 0;
}


问:
Incorrect date value when loading xlsx file to table using pymysql and xlrd
(Very) beginner python user here. I'm trying to load an xlsx file into a MySQL table using xlrd and pymysql python libraries and I'm getting an error:

pymysql.err.InternalError: (1292, "Incorrect date value: '43500' for column 'invoice_date' at row 1")

The datatype for invoice_date for my table is DATE. The format for this field on my xlsx file is also Date. Things work fine if I change the table datatype to varchar, but I'd prefer to have the data load into my table as a date instead of converting after the fact. Any ideas as to why I'm getting this error? It appears that xlrd or pymysql is reading '2/4/2019' in my xlxs file as '43500' and mysql is rejecting it due to a datatype mismatch.

```<code>import xlrd
import pymysql as MySQLdb

# Open workbook and define first sheet
book = xlrd.open_workbook("2019_Complete.xlsx")
sheet = book.sheet_by_index(0)

# MySQL connection
database = MySQLdb.connect (host="localhost", user="root",passwd="password", db="vendor")

# Get cursor, which is used to traverse the databse, line by line
cursor = database.cursor()

# INSERT INTO SQL query
query = """insert into table values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""

# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r in range(1, sheet.nrows):
    lp = sheet.cell(r,0).value
    pallet_lp = sheet.cell(r,1).value
    bol = sheet.cell(r,2).value
    invoice_date = sheet.cell(r,3).value
    date_received = sheet.cell(r,4).value
    date_repaired = sheet.cell(r,5).value
    time_in_repair = sheet.cell(r,6).value
    date_shipped = sheet.cell(r,7).value
    serial_number = sheet.cell(r,8).value
    upc = sheet.cell(r,9).value
    product_type = sheet.cell(r,10).value
    product_description = sheet.cell(r,11).value
    repair_code = sheet.cell(r,12).value
    condition = sheet.cell(r,13).value
    repair_cost = sheet.cell(r,14).value
    parts_cost = sheet.cell(r,15).value
    total_cost = sheet.cell(r,16).value
    repair_notes = sheet.cell(r,17).value
    repair_cap = sheet.cell(r,18).value
    complaint = sheet.cell(r,19).value
    delta = sheet.cell(r,20).value

    # Assign values from each row
    values = (lp, pallet_lp, bol, invoice_date, date_received, date_repaired, time_in_repair, date_shipped, serial_number, upc, product_type, product_description, repair_code, condition, repair_cost, parts_cost, total_cost, repair_notes, repair_cap, complaint, delta)

    # Execute sql Query
    cursor.execute(query, values)

# Close the cursor
cursor.close()

# Commit the transaction
database.commit()

# Close the database connection
database.close()

# Print results
print ("")
columns = str(sheet.ncols)
rows = str(sheet.nrows)
print ("I just imported " + columns + " columns and " + rows + " rows to MySQL!")
</code>```

答:
You can see this answer for a more detailed explanation, but basically Excel treats dates as a number relative to 1899-12-31, and so to convert your date value to an actual date you need to convert that number into an ISO format date which MySQL will accept. You can do that using date.fromordinal and date.isoformat. For example:

```<code>dval = 43500
d = date.fromordinal(dval + 693594)
print(d.isoformat())
</code>```

Output:

```<code>2019-02-04
</code>```

Body:
(Very) beginner python user here. I'm trying to load an xlsx file into a MySQL table using xlrd and pymysql python libraries and I'm getting an error:

pymysql.err.InternalError: (1292, "Incorrect date value: '43500' for column 'invoice_date' at row 1")

The datatype for invoice_date for my table is DATE. The format for this field on my xlsx file is also Date. Things work fine if I change the table datatype to varchar, but I'd prefer to have the data load into my table as a date instead of converting after the fact. Any ideas as to why I'm getting this error? It appears that xlrd or pymysql is reading '2/4/2019' in my xlxs file as '43500' and mysql is rejecting it due to a datatype mismatch.

import xlrd
import pymysql as MySQLdb

# Open workbook and define first sheet
book = xlrd.open_workbook("2019_Complete.xlsx")
sheet = book.sheet_by_index(0)

# MySQL connection
database = MySQLdb.connect (host="localhost", user="root",passwd="password", db="vendor")

# Get cursor, which is used to traverse the databse, line by line
cursor = database.cursor()

# INSERT INTO SQL query
query = """insert into table values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""

# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r in range(1, sheet.nrows):
    lp = sheet.cell(r,0).value
    pallet_lp = sheet.cell(r,1).value
    bol = sheet.cell(r,2).value
    invoice_date = sheet.cell(r,3).value
    date_received = sheet.cell(r,4).value
    date_repaired = sheet.cell(r,5).value
    time_in_repair = sheet.cell(r,6).value
    date_shipped = sheet.cell(r,7).value
    serial_number = sheet.cell(r,8).value
    upc = sheet.cell(r,9).value
    product_type = sheet.cell(r,10).value
    product_description = sheet.cell(r,11).value
    repair_code = sheet.cell(r,12).value
    condition = sheet.cell(r,13).value
    repair_cost = sheet.cell(r,14).value
    parts_cost = sheet.cell(r,15).value
    total_cost = sheet.cell(r,16).value
    repair_notes = sheet.cell(r,17).value
    repair_cap = sheet.cell(r,18).value
    complaint = sheet.cell(r,19).value
    delta = sheet.cell(r,20).value

    # Assign values from each row
    values = (lp, pallet_lp, bol, invoice_date, date_received, date_repaired, time_in_repair, date_shipped, serial_number, upc, product_type, product_description, repair_code, condition, repair_cost, parts_cost, total_cost, repair_notes, repair_cap, complaint, delta)

    # Execute sql Query
    cursor.execute(query, values)

# Close the cursor
cursor.close()

# Commit the transaction
database.commit()

# Close the database connection
database.close()

# Print results
print ("")
columns = str(sheet.ncols)
rows = str(sheet.nrows)
print ("I just imported " + columns + " columns and " + rows + " rows to MySQL!")

Body:
You can see this answer for a more detailed explanation, but basically Excel treats dates as a number relative to 1899-12-31, and so to convert your date value to an actual date you need to convert that number into an ISO format date which MySQL will accept. You can do that using date.fromordinal and date.isoformat. For example:

dval = 43500
d = date.fromordinal(dval + 693594)
print(d.isoformat())

Output:

2019-02-04


问:
Is it possible to test if a specific key is pressed using FreePascal?
I would like to be able to write a FreePascal function such as:

```<code>function KeyIsPressed(ch: char): boolean;
</code>```

which returns true if and only if the key corresponding to the character ch is pressed at the time of execution.  This function should allow for constructs such as:

```<code>if KeyIsPressed('a') and KeyIsPressed('b') and not KeyIsPressed('c') then ...
</code>```

evidently returning true if and only if both 'a' and 'b' are pressed and 'c' is not pressed.

FYI, I am running:

```<code>Free Pascal Compiler version 3.0.4+dfsg-18ubuntu2 [2018/08/29] for x86_64
Copyright (c) 1993-2017 by Florian Klaempfl and others
</code>```

PS1: I do not care if the keyboard buffer starts filling up or not, a problem one could deal with separately afterwards.

PS2: I did notice similar questions regarding other programing languages, but unfortunately these are of no use for Pascal.

答:
Just look at the implementation of units Crt and/or keyboard. They do those things. But they capture keyboard data from stdin which is already "cooked".

It is hard getting around this. To find out which keyboard combos are hard to make try the "teach keys" functionality of the textmode IDE which basically shows "keyboard" unit functionality

Body:
I would like to be able to write a FreePascal function such as:

function KeyIsPressed(ch: char): boolean;

which returns true if and only if the key corresponding to the character ch is pressed at the time of execution.  This function should allow for constructs such as:

if KeyIsPressed('a') and KeyIsPressed('b') and not KeyIsPressed('c') then ...

evidently returning true if and only if both 'a' and 'b' are pressed and 'c' is not pressed.

FYI, I am running:

Free Pascal Compiler version 3.0.4+dfsg-18ubuntu2 [2018/08/29] for x86_64
Copyright (c) 1993-2017 by Florian Klaempfl and others

PS1: I do not care if the keyboard buffer starts filling up or not, a problem one could deal with separately afterwards.

PS2: I did notice similar questions regarding other programing languages, but unfortunately these are of no use for Pascal.


问:
what library does LED belong to in Pspice?
I am a student and new to Pspice, I am given the following example circuit

and asked to created the following circuit,

which I have this

I think I have my circuit designed correctly. However, I am having trouble with finding the correct diode. I have tried different library such as diode, ediode, diode_bridge, on_diode and infineon, but the diodes from these library don't give a current of 20mA(typically lower than that). I also tried to find discrete.olb, however it's not in my capture library.... Is there any other library contains the 2legs led like the diodes in example circuit?I think the reason why I am not getting 20mA is because of the diode?

答: As can be seen here on the PSPICE website, you should be able to find all of the LED models in the Optoelectronics->LEDs library. </p>


问:
Facebook newbie - can't login to application - gettin an error with no helpful information
I'm trying to implement my first Facebook application, and I'm stuck on the very first coding step.

I created an application on the Facebook website, I got my application ID and I'm doing an ASP.NET app to test the authentication. It has just one line:

```
Response.Redirect(
"https://www.facebook.com/dialog/oauth?client_id=MYAPPID&redirect_uri=localhost");
```

When I run it, it redirects to facebook and I get:

An error occurred with MYAPPNAME. Please try again later.

It fetches the app name, so the ID is correct and there is very little else that I could have got wrong :-)

I also tried using other URLs instead of localhost, and I'm currently arranging for a VPS to try it with a publicly deployed web app in case it doesn't work with a local one.

Searching only found me lots of posts complaining about similar issues - but not the same one. I found this question that looks quite similar, but the confirmed answer speaks about editing FB.init() which is I guess part of some SDK, so not applicable for me.

答:
Your redirect uri must be a url that is within the domain that you configured in your application set up. As noted in the documentation.

"The redirect_uri must be within the same domain as the Site URL you specify in Web site tab of the Developer App"

Body:
I'm trying to implement my first Facebook application, and I'm stuck on the very first coding step.

I created an application on the Facebook website, I got my application ID and I'm doing an ASP.NET app to test the authentication. It has just one line:

Response.Redirect(
"https://www.facebook.com/dialog/oauth?client_id=MYAPPID&redirect_uri=localhost");

When I run it, it redirects to facebook and I get:

An error occurred with MYAPPNAME. Please try again later.

It fetches the app name, so the ID is correct and there is very little else that I could have got wrong :-)

I also tried using other URLs instead of localhost, and I'm currently arranging for a VPS to try it with a publicly deployed web app in case it doesn't work with a local one.

Searching only found me lots of posts complaining about similar issues - but not the same one. I found this question that looks quite similar, but the confirmed answer speaks about editing FB.init() which is I guess part of some SDK, so not applicable for me.


问:
Typescript calling HTML id to change value
HTML

```<code><span id="IDs"> hello </span>
</code>```

.TS

```<code>changeID(){
  // call IDs and change value

}
</code>```

In TypeScript how do I change the content of id IDs that's in my HTML inside my .TS?

答:
You can write basic js technically, but with type of course.

```<code>changeId() {
  let element: HTMLElement = document.getElementById('id');
  element.id = newId;
}
</code>```

or just

```<code>changeId() {
  document.getElementById('id').id = newId;
}
</code>```

Body:
HTML

 hello

.TS

changeID(){
  // call IDs and change value

}

In TypeScript how do I change the content of id IDs that's in my HTML inside my .TS?

Body:
You can write basic js technically, but with type of course.

changeId() {
  let element: HTMLElement = document.getElementById('id');
  element.id = newId;
}

or just

changeId() {
  document.getElementById('id').id = newId;
}


问:
How to solve this loop problem in python flask?
I try to loop through every article and show it in web page but this is what happens..

My python code:

```<code>@app.route('/scrapper')
def scrapper():

    response = requests.get('http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=api-key')

    data = response.json()
    articles = data['articles']

    for i in range(len(articles)):
        myarticles = articles[i]

    return render_template('news.html', myarticles=myarticles)
</code>```

And this is how it looks like in html:

```<code><body>
{% for info in myarticles %}
    <h2>Title: {{myarticles.title}}  </h2>
    <p>Author: {{myarticles.author}}  </p>
    <p>Url: {{myarticles.url}}  </p>
    <p>Content: {{myarticles.content}} </p>
    <p>Date: {{myarticles.publishedAt}} </p>
{% endfor %}
</body>
</code>```

This returns only one article but many times, as in this photo.
This is my very first project like that so please, be forgiving.

EDIT:
I deleted loop and passed like you said. But now i got nothing, just empty page
like that.

答:
Your problem is this:

```<code>for i in range(len(articles)):
    myarticles = articles[i]
</code>```

myarticles will always point to the last article inside your list articles.

Since in your template you're already looping over the articles, just pass in articles.

```<code>return render_template('news.html', myarticles=articles)
</code>```

Forgot to also mention, you need to actually use the looped article:

```<code><body>
{% for info in myarticles %}
    <h2>Title: {{myarticles.title}}  </h2>
    <p>Author: {{myarticles.author}}  </p>
    <p>Url: {{myarticles.url}}  </p>
    <p>Content: {{myarticles.content}} </p>
    <p>Date: {{myarticles.publishedAt}} </p>
{% endfor %}
</body>
</code>```

This is wrong because you're not using info, which has the data for each individual article.

You need to change it to:

```<code><body>
{% for info in myarticles %}
    <h2>Title: {{info.title}}  </h2>
    <p>Author: {{info.author}}  </p>
    <p>Url: {{info.url}}  </p>
    <p>Content: {{info.content}} </p>
    <p>Date: {{info.publishedAt}} </p>
{% endfor %}
</body>
</code>```

Body:
I try to loop through every article and show it in web page but this is what happens..

My python code:

@app.route('/scrapper')
def scrapper():

    response = requests.get('http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=api-key')

    data = response.json()
    articles = data['articles']

    for i in range(len(articles)):
        myarticles = articles[i]

    return render_template('news.html', myarticles=myarticles)

And this is how it looks like in html:

{% for info in myarticles %}

Title: {{myarticles.title}}

Author: {{myarticles.author}}

Url: {{myarticles.url}}

Content: {{myarticles.content}}

Date: {{myarticles.publishedAt}}

{% endfor %}

This returns only one article but many times, as in this photo.
This is my very first project like that so please, be forgiving.

EDIT:
I deleted loop and passed like you said. But now i got nothing, just empty page
like that.

Body:
Your problem is this:

for i in range(len(articles)):
    myarticles = articles[i]

myarticles will always point to the last article inside your list articles.

Since in your template you're already looping over the articles, just pass in articles.

return render_template('news.html', myarticles=articles)

Forgot to also mention, you need to actually use the looped article:

<body>
{% for info in myarticles %}
    <h2>Title: {{myarticles.title}}  </h2>
    <p>Author: {{myarticles.author}}  </p>
    <p>Url: {{myarticles.url}}  </p>
    <p>Content: {{myarticles.content}} </p>
    <p>Date: {{myarticles.publishedAt}} </p>
{% endfor %}
</body>

This is wrong because you're not using info, which has the data for each individual article.

You need to change it to:

<body>
{% for info in myarticles %}
    <h2>Title: {{info.title}}  </h2>
    <p>Author: {{info.author}}  </p>
    <p>Url: {{info.url}}  </p>
    <p>Content: {{info.content}} </p>
    <p>Date: {{info.publishedAt}} </p>
{% endfor %}
</body>


问:
Getting message from kafka topic
I have a properties file for JDBC Kafka connect. Where the topic.prefix=test-mysql-jdbc-

As per my knowledge when we run the standalone connector -

$ /usr/bin/connect-standalone /etc/schema-registry/connect-avro-standalone.properties/etc/kafka-connect-jdbc/source-quickstart-mysql.properties

A topic is created named test-mysql-jdbc-

Now I create the consumer

$ /usr/bin/kafka-avro-console-consumer -–topic test-mysql-jdbc-students --zookeeper localhost:2181 --from-beginning

and I get JSON data successfully..

Now What I did is I deleted the kafka logs(which deleted all the topics) but when I am repeating the same process, The topic with same name is created but I am not getting any data in the consumer. If I change the topic.prefix to something new. I get the data again. Please Explain

答:
and I get JSON data successfully

You're actually getting deserialized Avro (shown as JSON)

I deleted the kafka logs(which deleted all the topics)

Sounds like you didn't delete any Zookeeper data, so the topic metadata still exists.

Title: Getting message from kafka topic


问:
How to save group of shapes as JPG image?
I place a number of shapes on an image using VBA and want to save the whole group as a JPG.

```<code>Sub SaveImageTEST()
    ActiveSheet.Shapes.Range(Array("Picture 1")).SaveAsPicture "worldmap.jpg"
End Sub
</code>```

The idea is to visualize data on a map:

答:
The best that I could come up with is to export as pdf, hopes this helps.</p>

```<code>Sub SaveImage()
    'On Error Resume Next
    Set ws = ActiveSheet
    Set shp = ws.Shapes.Range(Array("Picture 1"))

    Set ch = ws.ChartObjects.Add(shp.Left, shp.Top, shp.Width, shp.Height)
    shp.Select
    Selection.Copy

    ch.Chart.Paste
    Set tt = ch.Chart

    'tt.ExportAsFixedFormat Type:=xlTypePDF, Filename:="c:\outputFileName"
    tt.Export Filename:="C:\test.png", filtername:="PNG"

    ch.Delete

End Sub
</code>```

Body:
I place a number of shapes on an image using VBA and want to save the whole group as a JPG.

Sub SaveImageTEST()
    ActiveSheet.Shapes.Range(Array("Picture 1")).SaveAsPicture "worldmap.jpg"
End Sub

The idea is to visualize data on a map:

Body:
The best that I could come up with is to export as pdf, hopes this helps.

Sub SaveImage()
    'On Error Resume Next
    Set ws = ActiveSheet
    Set shp = ws.Shapes.Range(Array("Picture 1"))

    Set ch = ws.ChartObjects.Add(shp.Left, shp.Top, shp.Width, shp.Height)
    shp.Select
    Selection.Copy

    ch.Chart.Paste
    Set tt = ch.Chart

    'tt.ExportAsFixedFormat Type:=xlTypePDF, Filename:="c:\outputFileName"
    tt.Export Filename:="C:\test.png", filtername:="PNG"

    ch.Delete

End Sub


问:
Why the UI elements disappear in seconds in Xcode 11.3?
I am coding a single view page IOS app in swift for learning in Xcode 11.3 on macOS Catalina. There are a button, a text field and a label elements on the page. Here is the code of ViewController.swift:

```<code>import UIKit
import LiquidCore

class ViewController: UIViewController {

    var txt = "text field"
    @IBOutlet weak var Text: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    func showText() {
        Text.text = txt
    }

    @IBAction func clickButton(_ sender: UIButton) {

        let url = LCMicroService.bundle("example")
        let service = LCMicroService(url: url)
        service?.start()

        txt = "LC started"
        showText()
    }

}
</code>```

Here is the preview of the UI page:

The problem I am having is that all 3 UI elements disappear automatically in about 5 seconds after being shown on launch screen. There are view life cycles for a page but I don't have any of those in my code. What's wrong here?

答:
This is basic of swift, I hope you designed it on LaunchScreen.storyboard which acts as the Splash screen of the application.

Your problem is you designed your view in LaunchScreen.storyboard so it stayed only for 5 seconds, now the solution is design your view in Main.storyboard so that you will see your UIControls or UIElements.

Hope it helps.

Body:
I am coding a single view page IOS app in swift for learning in Xcode 11.3 on macOS Catalina. There are a button, a text field and a label elements on the page. Here is the code of ViewController.swift:

import UIKit
import LiquidCore

class ViewController: UIViewController {

    var txt = "text field"
    @IBOutlet weak var Text: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    func showText() {
        Text.text = txt
    }

    @IBAction func clickButton(_ sender: UIButton) {

        let url = LCMicroService.bundle("example")
        let service = LCMicroService(url: url)
        service?.start()

        txt = "LC started"
        showText()
    }

}

Here is the preview of the UI page:

The problem I am having is that all 3 UI elements disappear automatically in about 5 seconds after being shown on launch screen. There are view life cycles for a page but I don't have any of those in my code. What's wrong here?


问:
Playframework inserting wrong date in database
I'm having a strage problem. In my form I'm using the jQuery datetime picker. This generates a string like 05/23/2011 07:33.

In my java code i'm using DateFormat to create a date object out of that string:

```<code>    System.out.println(execute);
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy kk:mm");
    Date date = null;
    try {
        date = df.parse(execute);
    } catch (ParseException e) {
        e.printStackTrace();
    }
</code>```

(execute is the string which contains the date).
In the console, println() is showing the right date. And I'm using that date object when I write an instane of a Model to the database. But once I call the save() function (from the model), the timestamp that is inserted in the database is completely wrong.

In this case it is: 2012-11-05 07:33:00 The time is correct, but the date is sometimes more than a year off!

Any ideas what's causing this?

答: I had a similar issue as the jQuery date time picker was using a different formatting for the date than my Java code, and that changed the date to be saved. Check it :)</p>

Body:
I'm having a strage problem. In my form I'm using the jQuery datetime picker. This generates a string like 05/23/2011 07:33.

In my java code i'm using DateFormat to create a date object out of that string:

    System.out.println(execute);
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy kk:mm");
    Date date = null;
    try {
        date = df.parse(execute);
    } catch (ParseException e) {
        e.printStackTrace();
    }

(execute is the string which contains the date).
In the console, println() is showing the right date. And I'm using that date object when I write an instane of a Model to the database. But once I call the save() function (from the model), the timestamp that is inserted in the database is completely wrong.

In this case it is: 2012-11-05 07:33:00 The time is correct, but the date is sometimes more than a year off!

Any ideas what's causing this?