问:
bit data type returns -1
I am working on a web application in Visual Studio 2010. I am writing and reading to a database table using SQL Server 2008.

I have a database table, myTable with a column myColumn of datatype bit. I write to this column on the web app like so:

```<code>UPDATE myTable
SET myColumn = 1
</code>```

This works fine, and using SQL Server Management Studio I can see the column gets updated to TRUE as I would expect.

In another part of my web app I query the table like so:

```<code>sqlCmd.CommandText = "SELECT myColumn FROM myTable"

sqlRdr = sqlCmd.ExecuteReader()

While sqlRdr.Read
      myColumn = sqlRdr(0)
End While
</code>```

When I run this query, myColumn gets set to -1. How does this happen? According to Microsoft Documentation a bit is

An integer data type that can take a value of 1, 0, or NULL.

and

The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.

I do not understand how I am getting myColumn = -1 from this query.

答:
The numeric value of True is -1 ,False is 0</p>

```<code>Debug.Print(Val(True) & " " & Val(False))
</code>```

Title: bit data type returns -1

Body:
I am working on a web application in Visual Studio 2010. I am writing and reading to a database table using SQL Server 2008.

I have a database table, myTable with a column myColumn of datatype bit. I write to this column on the web app like so:

UPDATE myTable
SET myColumn = 1

This works fine, and using SQL Server Management Studio I can see the column gets updated to TRUE as I would expect.

In another part of my web app I query the table like so:

sqlCmd.CommandText = "SELECT myColumn FROM myTable"

sqlRdr = sqlCmd.ExecuteReader()

While sqlRdr.Read
      myColumn = sqlRdr(0)
End While

When I run this query, myColumn gets set to -1. How does this happen? According to Microsoft Documentation a bit is

An integer data type that can take a value of 1, 0, or NULL.

and

The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.

I do not understand how I am getting myColumn = -1 from this query.

Body:
The numeric value of True is -1 ,False is 0

Debug.Print(Val(True) & " " & Val(False))


来源: stackexchange

问:
Reference to another array by index
Is it possible to somehow get reference of one array by indexes in java like this pseudocode, for example:

```<code>array1 = [1,2,3,4,5,6,7,8] // size 8
array2 = [] // size 4
for(i=0 ; i<4 ; i ++)
{
  array2[i] = reference to array1[random(0,3)]
}
</code>```

so for example random numbers were 3 0 4 6

```<code>array2[0] = array1[3]
array2[1] = array1[0]
</code>```

and if you change array2[0] to 99 then array1[3]= 99 as well.

答:
It's not exactly possible, but you can fake it:

```<code>class Reference {

    private Object value;

    public Reference(Object value) {
        this.value = value;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value.toString();
    }

    public static Reference[] ofInts(int[] items) {
        Reference[] ret = new Reference[items.length];
        for(int i = 0; i < items.length; ++i) {
            ret[i] = new Reference(items[i]);
        }
        return ret;
    }
}
</code>```

Then you can use it like this:

```<code>int array1[] = new int[] {1,2,3,4,5,6,7,8};
Reference refArray1[] = Reference.ofInts(array1);

final int arr2Size = 4;
Reference refArray2[] = new Reference[arr2Size];
Random rand = new Random();

for(int i = 0; i < arr2Size; ++i) {
    int index = rand.nextInt(array1.length);
    refArray2[i] = refArray1[index];
}

System.out.println(Arrays.toString(refArray1));
System.out.println(Arrays.toString(refArray2));
System.out.println("---");

refArray2[0].setValue(99); // set reference value

System.out.println(Arrays.toString(refArray1));
System.out.println(Arrays.toString(refArray2));
</code>```

Sample output:

```<code>[1, 2, 3, 4, 5, 6, 7, 8]
[4, 6, 3, 3]
---
[1, 2, 3, 99, 5, 6, 7, 8]
[99, 6, 3, 3]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Reference to another array by index

Body:
Is it possible to somehow get reference of one array by indexes in java like this pseudocode, for example:

array1 = [1,2,3,4,5,6,7,8] // size 8
array2 = [] // size 4
for(i=0 ; i<4 ; i ++)
{
  array2[i] = reference to array1[random(0,3)]
}

so for example random numbers were 3 0 4 6

array2[0] = array1[3]
array2[1] = array1[0]

and if you change array2[0] to 99 then array1[3]= 99 as well.

Body:
It's not exactly possible, but you can fake it:

class Reference {

    private Object value;

    public Reference(Object value) {
        this.value = value;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value.toString();
    }

    public static Reference[] ofInts(int[] items) {
        Reference[] ret = new Reference[items.length];
        for(int i = 0; i < items.length; ++i) {
            ret[i] = new Reference(items[i]);
        }
        return ret;
    }
}

Then you can use it like this:

int array1[] = new int[] {1,2,3,4,5,6,7,8};
Reference refArray1[] = Reference.ofInts(array1);

final int arr2Size = 4;
Reference refArray2[] = new Reference[arr2Size];
Random rand = new Random();

for(int i = 0; i < arr2Size; ++i) {
    int index = rand.nextInt(array1.length);
    refArray2[i] = refArray1[index];
}

System.out.println(Arrays.toString(refArray1));
System.out.println(Arrays.toString(refArray2));
System.out.println("---");

refArray2[0].setValue(99); // set reference value

System.out.println(Arrays.toString(refArray1));
System.out.println(Arrays.toString(refArray2));

Sample output:

[1, 2, 3, 4, 5, 6, 7, 8]
[4, 6, 3, 3]
---
[1, 2, 3, 99, 5, 6, 7, 8]
[99, 6, 3, 3]


问:
Count distinct pairs of strings that contain at least one common character at the same position
Is there a more efficient way to count distinct pairs of strings in an array that have at least one common character at the same position. The strings will always have the same length of 3. For example,

"abc", acb": counts

"bun", "fun": counts

"xyz", "yzx": doesn't count

"one", "two": doesn't count

I've tried writing a function that checks if they match and then count them using for loops, but it doesn't seem to be so efficient, especially when the array is huge.

bool match(std::string a, std::string b) {
    for (int i = 0; i < 3; i++) {
        if (a.at(i) == b.at(i)) {
            return true;
        }
    }
    return false;
}

int main() {
    const int count = 100000;
    std::string strings[count] = {...};

    long long int matches = 0;
    for (int i = 0; i < count; i++) {
        for (int j = i + 1; j < count; j++) {
            if (match(strings[i], strings[j])) {
                matches++;
            }
        }
    }
}
```

So, is there a more efficient way to achieve this?

答:
Heres the list (assuming the strings has 3 chars):

is actual the only one that might not be already done by your compiler: pass the std::string by const&, so that you don't need to copy them every time you call the function

```<code>bool match(const std::string& a, const std::string& b){...}
</code>```

avoid useless branches in your code (can be optimized already by some branch prediction algorithm):

```<code> // from
if (match(strings[i], strings[j])) {
   matches++;
}
 // to
matches = matches + match(strings[i], strings[j];
</code>```

loop unrolling (which can been done already by your compiler):

```<code>bool match(std::string a, std::string b) {
    return a.at(0) == b.at(0) || a.at(1) == b.at(1) || a.at(2) == b.at(2);
}
</code>```

You can also try to parallelize those conditions (depends on architecture, can be done already by the compiler) using | and so all the conditions can be done in parallel by ALU, instead using | must be performed step by step (short circuit evaluation):

```<code>bool match(std::string a, std::string b) {
    return a.at(0) == b.at(0) | a.at(1) == b.at(1) | a.at(2) == b.at(2);
}
</code>```

Compile using the highest optimization (can increase the compilation time), using -O3

use pre-increment instead of post-increment (post increment will generate a second variable to return every time you use it, pre-increment no):

```<code>for (int i = 0; i < count; ++i) {
    for (int j = i + 1; j < count; ++j) {
    }
}
</code>```

by this line std::string strings[count] = {...}; I suppose you are using initializarer list, and so the computation can actually be performed at compile time if you use std::string_view and so at runtime there is no compilation to perform (this works only if the strings are known at compile time)

decrease cache misses, but this depends 100% on architecture

inline the function (so that your program don't have to do a jump every time to call match):

```<code>// from:
bool match(const std::string& a, const std::string& b){...}
//to:
inline bool match(const std::string& a, const std::string& b){...}
</code>```

use operator[] instead of .at() because it does not make any kind of bounds checking

```<code>bool match(std::string a, std::string b) {
    return a[0] == b[0] | a[1] == b[1] | a[2] == b[2];
}
</code>```

Body:
Is there a more efficient way to count distinct pairs of strings in an array that have at least one common character at the same position. The strings will always have the same length of 3. For example,

"abc", acb": counts

"bun", "fun": counts

"xyz", "yzx": doesn't count

"one", "two": doesn't count

I've tried writing a function that checks if they match and then count them using for loops, but it doesn't seem to be so efficient, especially when the array is huge.

bool match(std::string a, std::string b) {
    for (int i = 0; i < 3; i++) {
        if (a.at(i) == b.at(i)) {
            return true;
        }
    }
    return false;
}

int main() {
    const int count = 100000;
    std::string strings[count] = {...};

    long long int matches = 0;
    for (int i = 0; i < count; i++) {
        for (int j = i + 1; j < count; j++) {
            if (match(strings[i], strings[j])) {
                matches++;
            }
        }
    }
}

So, is there a more efficient way to achieve this?

Body:
Heres the list (assuming the strings has 3 chars):

is actual the only one that might not be already done by your compiler: pass the std::string by const&, so that you don't need to copy them every time you call the function

bool match(const std::string& a, const std::string& b){...}

avoid useless branches in your code (can be optimized already by some branch prediction algorithm):

 // from
if (match(strings[i], strings[j])) {
   matches++;
}
 // to
matches = matches + match(strings[i], strings[j];

loop unrolling (which can been done already by your compiler):

bool match(std::string a, std::string b) {
    return a.at(0) == b.at(0) || a.at(1) == b.at(1) || a.at(2) == b.at(2);
}

You can also try to parallelize those conditions (depends on architecture, can be done already by the compiler) using | and so all the conditions can be done in parallel by ALU, instead using | must be performed step by step (short circuit evaluation):

bool match(std::string a, std::string b) {
    return a.at(0) == b.at(0) | a.at(1) == b.at(1) | a.at(2) == b.at(2);
}

Compile using the highest optimization (can increase the compilation time), using -O3

use pre-increment instead of post-increment (post increment will generate a second variable to return every time you use it, pre-increment no):

for (int i = 0; i < count; ++i) {
    for (int j = i + 1; j < count; ++j) {
    }
}

by this line std::string strings[count] = {...}; I suppose you are using initializarer list, and so the computation can actually be performed at compile time if you use std::string_view and so at runtime there is no compilation to perform (this works only if the strings are known at compile time)

decrease cache misses, but this depends 100% on architecture

inline the function (so that your program don't have to do a jump every time to call match):

// from:
bool match(const std::string& a, const std::string& b){...}
//to:
inline bool match(const std::string& a, const std::string& b){...}

use operator[] instead of .at() because it does not make any kind of bounds checking

bool match(std::string a, std::string b) {
    return a[0] == b[0] | a[1] == b[1] | a[2] == b[2];
}


问:
Am i disposing my ODBCConnection
I'm using a helper method like this:

```<code>    private OdbcCommand GetCommand(string sql)
    {
        string conString = "blah";
        var con = new OdbcConnection(conString);
        var cmd = new OdbcCommand(sql, con);
        return cmd;
    }
</code>```

Then i use it like this:

```<code>using (var cmd = GetCommand("select * from myTable")
{
    cmd.connection.open();
    using(var reader = cmd.ExecuteReader())
    {
    }
}
</code>```

Here is a second example:

```<code>    public static OdbcDataReader GetReader(string conString,string sql)
    {
        var cmd = GetCommand(conString, sql);
        cmd.Connection.Open();
        return cmd.ExecuteReader();
    }
</code>```

used like this:

```<code>     using(var reader = GetReader("blah","select * from blah")
    {
    }
</code>```

In these two cases, am i disposing of the connection and cmd objects? I think connection is not being disposed in the first, and neither connection nor cmd in the second, is that right?

Do i need to do i the long way to ensure correct disposal, or is there a shorter approach?

```<code>using (var con ...)
    using (var cmd)
        using (var reader)
</code>```

答:
In short, if it has Dispose, then you should call it.  You can't assume that another object will dispose of an object you pass it for you.

Disposing the command object, will not dispose the connection object, because you can use the connection again after you are done with the command.  Disposing of each is the best approach.

ContentLicense: CC BY-SA 3.0

Title: Am i disposing my ODBCConnection

Body:
I'm using a helper method like this:

    private OdbcCommand GetCommand(string sql)
    {
        string conString = "blah";
        var con = new OdbcConnection(conString);
        var cmd = new OdbcCommand(sql, con);
        return cmd;
    }

Then i use it like this:

using (var cmd = GetCommand("select * from myTable")
{
    cmd.connection.open();
    using(var reader = cmd.ExecuteReader())
    {
    }
}

Here is a second example:

    public static OdbcDataReader GetReader(string conString,string sql)
    {
        var cmd = GetCommand(conString, sql);
        cmd.Connection.Open();
        return cmd.ExecuteReader();
    }

used like this:

     using(var reader = GetReader("blah","select * from blah")
    {
    }

In these two cases, am i disposing of the connection and cmd objects? I think connection is not being disposed in the first, and neither connection nor cmd in the second, is that right?

Do i need to do i the long way to ensure correct disposal, or is there a shorter approach?

using (var con ...)
    using (var cmd)
        using (var reader)


问:
Contradictory reporting of total Process memory usage in C# Winforms app
EDIT: The bounty's expired, but if the community would like to award it to someone, then I choose Raful Chizkiyahu.

I have a memory leak in one of my C# Winforms programs, and I'd like to graph its memory usage over time to get a better understanding of what might be causing the leak. Problem is, none of the usual memory diagnostic commands match up with what the Task Manager is claiming as its consumed memory for that process. I assumed this was perhaps due to the app using unsafe/unmanaged code not being included in the total.

So to try and drill deeper, I created a new Winforms app, very simple, with just a timer to report the memory usage in realtime. I use 5 labels, each with various functions (mostly found from here): Environment.WorkingSet, GC.GetTotalMemory(false), GC.GetTotalMemory(true), Process.GetCurrentProcess().PrivateMemorySize64 and Process.GetCurrentProcess().WorkingSet64.

Surprisingly (or maybe not so, sigh), I still can't get any of these five numbers to match up with the Windows 10 Task Manager. Here's a screenshot:

So what I'm basically looking for is that 5.1MB number. How do I sneakily extract that hidden number from the .NET framework?

Here's the code I have in the Timer tick function:

```<code>private void timer1_Tick(object sender, EventArgs e)
{
    //Refresh();
    label1.Text = "Environment.WorkingSet: " +  Environment.WorkingSet ;
    label2.Text = "GC.GetTotalMemory(false): " +    GC.GetTotalMemory(false) ;
    label3.Text = "GC.GetTotalMemory(true): " + GC.GetTotalMemory(true) ;
    Process proc = Process.GetCurrentProcess();
    label4.Text = "proc.PrivateMemorySize64: " +    proc.PrivateMemorySize64 ;
    label5.Text = "proc.WorkingSet64: " +       proc.WorkingSet64 ;
    proc.Dispose();
}
</code>```

As might be evident, I tried with and without the Refresh() command to no avail.

EDIT: The bounty's expired, but if the community would like to award it to someone, then I choose Raful Chizkiyahu.

答:
You need better tooling, TaskManager will only give you approximate memory usage at a certain moment.

If you suspect a memory leak, the tried and true method is to take memory dumps(snapshots) of the application.

A snapshot should be taken at application startup, then at subsequent intervals. If memory rises slowly you will have to wait a bit between each snapshot. You can then compare the snapshots. This method allows you to analyze and compare object allocations, object counts, even unmanaged memory.

Microsoft has written a guide for the Memory Usage tool integrated into Visual Studio. In most cases this should suffice in identifying the leak.

If you find the integrated tooling limited, have a look at this SO question and others linked in the sidebar.

Body:
EDIT: The bounty's expired, but if the community would like to award it to someone, then I choose Raful Chizkiyahu.

I have a memory leak in one of my C# Winforms programs, and I'd like to graph its memory usage over time to get a better understanding of what might be causing the leak. Problem is, none of the usual memory diagnostic commands match up with what the Task Manager is claiming as its consumed memory for that process. I assumed this was perhaps due to the app using unsafe/unmanaged code not being included in the total.

So to try and drill deeper, I created a new Winforms app, very simple, with just a timer to report the memory usage in realtime. I use 5 labels, each with various functions (mostly found from here): Environment.WorkingSet, GC.GetTotalMemory(false), GC.GetTotalMemory(true), Process.GetCurrentProcess().PrivateMemorySize64 and Process.GetCurrentProcess().WorkingSet64.

Surprisingly (or maybe not so, sigh), I still can't get any of these five numbers to match up with the Windows 10 Task Manager. Here's a screenshot:

So what I'm basically looking for is that 5.1MB number. How do I sneakily extract that hidden number from the .NET framework?

Here's the code I have in the Timer tick function:

private void timer1_Tick(object sender, EventArgs e)
{
    //Refresh();
    label1.Text = "Environment.WorkingSet: " +  Environment.WorkingSet ;
    label2.Text = "GC.GetTotalMemory(false): " +    GC.GetTotalMemory(false) ;
    label3.Text = "GC.GetTotalMemory(true): " + GC.GetTotalMemory(true) ;
    Process proc = Process.GetCurrentProcess();
    label4.Text = "proc.PrivateMemorySize64: " +    proc.PrivateMemorySize64 ;
    label5.Text = "proc.WorkingSet64: " +       proc.WorkingSet64 ;
    proc.Dispose();
}

As might be evident, I tried with and without the Refresh() command to no avail.

EDIT: The bounty's expired, but if the community would like to award it to someone, then I choose Raful Chizkiyahu.


问:
How to Json Element is present or not using C# (With Newtonsoft NugetPackages)
I have Json file, where i am trying the parse the data of the json file for database update with some data contions, Currently i want to check an particular element exists or not.In my current Json data, Under the Operation Node the accessRef can exist in the file or may not exist completely.So how would check the condtion. Kindly suggest me.

Below is the Json file

```<code>{
   "PLMXML":{
      "language":"en-us",
      "time":"16:50:15",
      "schemaVersion":"6",
      "author":"Development(-2069033203)",
      "date":"2020-05-22",
      "Header":{
             "id":"id1",
             "traverseRootRefs":"#id6",
             "transferContext":"CLM"
          },
      "Operation":{
             "id":"id21",
             "name":"PD_Op2",
             "subType":"BS4_BaOP",
             "accessRefs":"#id18",
             "catalogueId":"70700000209604",
             "ApplicationRef":{
                "application":"Teamcenter",
                "label":"yDX58d4FIpN8QD",
                "version":"yDX58d4FIpN8QD"
             }
          }
      }
}
</code>```

Below the Code which i am trying perform

```<code>public void Readjsonfile(string jsondata)
{   var message = JsonConvert.DeserializeObject<plmxmldatamodel>(jsondata);
    Console.WriteLine("RootRef: " + message.PLMXML.Header.traverseRootRefs);
    Console.WriteLine("OccurenceId: "+message.PLMXML.ProductView.Operation.id);
// I want to check whtether is accessrefs is present or not inside the Operation element
}
//fuction1
public class Header
{       public string traverseRootRefs { get; set; }
}
//fuction2
public class Operation
{   public string id { get; set; }
    public string name { get; set; }
    public string subType { get; set; }
    public string accessRefs { get; set; }
    public string catalogueId { get; set; }
}
//fuction3
public class PLMXML
{
    public string language { get; set; }
    public Header Header { get; set; }
    public Operation Operation { get; set; }
}
//fuction4
public class plmxmldatamodel
{
    public PLMXML PLMXML { get; set; }
}
</code>```

答:
If empty/null value for accessRefs is a valid situation (i.e. ... "'accessRefs':, ...") then you can use JSON Path to check if it exists:

```<code>var jObj = JObject.Parse(jsondata);
if(jObj.SelectToken("$.PLMXML.Operation.accessRefs") != null)
{
    // do what you want to do if accessRefs exists
}
</code>```

Otherwise just check for message.PLMXML.ProductView.Operation.accessRefs not being null:

```<code>if(message.PLMXML.ProductView.Operation.accessRefs != null)
{
    // do what you want to do if accessRefs exists
}
</code>```

Body:
I have Json file, where i am trying the parse the data of the json file for database update with some data contions, Currently i want to check an particular element exists or not.In my current Json data, Under the Operation Node the accessRef can exist in the file or may not exist completely.So how would check the condtion. Kindly suggest me.

Below is the Json file

{
   "PLMXML":{
      "language":"en-us",
      "time":"16:50:15",
      "schemaVersion":"6",
      "author":"Development(-2069033203)",
      "date":"2020-05-22",
      "Header":{
             "id":"id1",
             "traverseRootRefs":"#id6",
             "transferContext":"CLM"
          },
      "Operation":{
             "id":"id21",
             "name":"PD_Op2",
             "subType":"BS4_BaOP",
             "accessRefs":"#id18",
             "catalogueId":"70700000209604",
             "ApplicationRef":{
                "application":"Teamcenter",
                "label":"yDX58d4FIpN8QD",
                "version":"yDX58d4FIpN8QD"
             }
          }
      }
}

Below the Code which i am trying perform

public void Readjsonfile(string jsondata)
{   var message = JsonConvert.DeserializeObject<plmxmldatamodel>(jsondata);
    Console.WriteLine("RootRef: " + message.PLMXML.Header.traverseRootRefs);
    Console.WriteLine("OccurenceId: "+message.PLMXML.ProductView.Operation.id);
// I want to check whtether is accessrefs is present or not inside the Operation element
}
//fuction1
public class Header
{       public string traverseRootRefs { get; set; }
}
//fuction2
public class Operation
{   public string id { get; set; }
    public string name { get; set; }
    public string subType { get; set; }
    public string accessRefs { get; set; }
    public string catalogueId { get; set; }
}
//fuction3
public class PLMXML
{
    public string language { get; set; }
    public Header Header { get; set; }
    public Operation Operation { get; set; }
}
//fuction4
public class plmxmldatamodel
{
    public PLMXML PLMXML { get; set; }
}

Body:
If empty/null value for accessRefs is a valid situation (i.e. ... "'accessRefs':, ...") then you can use JSON Path to check if it exists:

var jObj = JObject.Parse(jsondata);
if(jObj.SelectToken("$.PLMXML.Operation.accessRefs") != null)
{
    // do what you want to do if accessRefs exists
}

Otherwise just check for message.PLMXML.ProductView.Operation.accessRefs not being null:

if(message.PLMXML.ProductView.Operation.accessRefs != null)
{
    // do what you want to do if accessRefs exists
}


问:
Unexpected output in converting from long in C to long in C++ in VS?
I'm writing a program in C (with a school-specific IDE), then converting it to C++ in Visual Studio. The program in C takes a long variable as user input of 371449635398431 (using the school IDE and a unique compiler function called get_long)   When I copy this to Visual Studio, using cin >> instead of get_long, it interprets the long as 2147483647 unless I make it a long long in VS. Are longs in C different than longs in C++ (with longs in C being equivalent to long long in C++?), or  could a compiler mismatch be causing the issue? </p>

答:
When the first C Standard was written, it was common for compilers to interpret "long" as the shortest type with at least 32 bits.  When compilers added support for 64-bit types, it was common for "long long" to be the shortest type with at least 64 bits.  Treating things in this way meant that the lack of fixed-length types wasn't really a problem, since code needing a 32-bit type could use "long" on any platform that had a 32-bit integer type.

MSVC has always followed that convention, even when targeting 64-bit platforms.  Some other compilers, however, have decided to change the meaning that long had always had on microcomputer-based platforms, so that instead of long being 32 bits and long long being 64 bits, both would be 64-bit types.

Note, btw, that even on platforms where long and long long are both 64-bit types, they're not compatible with each other.  If one has some functions that operate on data identified via long*, and others that operate on data identified via long long*, both clang and gcc will assume that those pointers will never be used to access the same storage.


问:
Sqlite Query Error: Ambiguous Column Name?
I am running the following query on an sqlite3 database:

```<code>SELECT file.id AS fileID, file.path
FROM file
JOIN (SELECT tag_file_map.fileID,tag.tagname
   FROM tag_file_map, tag JOIN tag ON tag_file_map.tagID = tag.id)
ON tag_file_map.fileID = file.id
WHERE tag.tagname = 'tag1' AND tag.tagname= 'tag2';
</code>```

It gives me the following error: "ambiguous column name: tag.tagname"

Google seems to say that this error is produced when one or more tables share a column name and the specific table of the column is not specified. However, here, the table name IS specified. Plus, there is no other column with the name "tagname" in the entire database, so it shouldn't be ambiguous with or without the table name. Is this an sqlite problem, or is something off with my syntax?

答:
on you inner select, change

```<code>FROM tag_file_map, tag JOIN tag on tag_file_map....
</code>```

to

```<code>FROM tag_file_map JOIN tag on tag_file_map....
</code>```

Body:
I am running the following query on an sqlite3 database:

SELECT file.id AS fileID, file.path
FROM file
JOIN (SELECT tag_file_map.fileID,tag.tagname
   FROM tag_file_map, tag JOIN tag ON tag_file_map.tagID = tag.id)
ON tag_file_map.fileID = file.id
WHERE tag.tagname = 'tag1' AND tag.tagname= 'tag2';

It gives me the following error: "ambiguous column name: tag.tagname"

Google seems to say that this error is produced when one or more tables share a column name and the specific table of the column is not specified. However, here, the table name IS specified. Plus, there is no other column with the name "tagname" in the entire database, so it shouldn't be ambiguous with or without the table name. Is this an sqlite problem, or is something off with my syntax?

Body:
on you inner select, change

FROM tag_file_map, tag JOIN tag on tag_file_map....

to

FROM tag_file_map JOIN tag on tag_file_map....


问:
CSS banner not properly accommodating in page
I'm having a bit of CSS trouble with some banners.

I have two banners (not sticky) at the top and bottom of the page, the top banner works like a charm. I am having issues with the bottom banner.

The banner is not at the bottom of the page; here's what I've tried.

Wrapping my banner
 in the  tag - that didn't work.

Using position: relative;- now this sets the banner to the bottom of the page - but it doesn't extend the banner through all of the page and puts some kind of margin on the sides.

Setting it manually - but of course, only works for my screen.

Here's my CSS:

```<code>div#bannerbtm {
    position: absolute;
    bottom:0%;
    left:0;
  -webkit-animation: gradient 10s linear infinite alternate both;
          animation: gradient 10s linear infinite alternate both;
  width: 100%;
}
div#bannertop {
  position: absolute;
  top: 0;
  left: 0;
  -webkit-animation: gradient 10s linear infinite alternate both;
          animation: gradient 10s linear infinite alternate both;
  width: 100%;
}
</code>```

and, here's the relevant HTML:

```<code><body>

<div id="bannertop">
    <div id="banner-content"></div>
</div>

<div> <!-- Page Content --> </div>

<div id="bannerbtm">
    <div id="banner-content"></div>
</div>

</body>
</code>```

Thanks in advance for any and all input; this has been driving me nuts.

答:
Add this, so you banner will be absolute inside relative body.

```<code>html {
  height: 100%;
}
body {
  min-height: 100%;
  position: relative;
  margin: 0;
  padding: 0;
}
</code>```

Body:
I'm having a bit of CSS trouble with some banners.

I have two banners (not sticky) at the top and bottom of the page, the top banner works like a charm. I am having issues with the bottom banner.

The banner is not at the bottom of the page; here's what I've tried.

Wrapping my banner
 in the  tag - that didn't work.

Using position: relative;- now this sets the banner to the bottom of the page - but it doesn't extend the banner through all of the page and puts some kind of margin on the sides.

Setting it manually - but of course, only works for my screen.

Here's my CSS:

div#bannerbtm {
    position: absolute;
    bottom:0%;
    left:0;
  -webkit-animation: gradient 10s linear infinite alternate both;
          animation: gradient 10s linear infinite alternate both;
  width: 100%;
}
div#bannertop {
  position: absolute;
  top: 0;
  left: 0;
  -webkit-animation: gradient 10s linear infinite alternate both;
          animation: gradient 10s linear infinite alternate both;
  width: 100%;
}

and, here's the relevant HTML:

Thanks in advance for any and all input; this has been driving me nuts.

Body:
Add this, so you banner will be absolute inside relative body.

html {
  height: 100%;
}
body {
  min-height: 100%;
  position: relative;
  margin: 0;
  padding: 0;
}


问:
Android Studio 4.0 shortcuts changed
This week I updated to Android Studio 4.0, and one of the first things I noticed was that some of my favorite shortcuts like CMD+W has changed to CMD+F4 (which the touchbar wont actually show the F keys anymore), and also CMD+O changed to CMD+N.  Is there any way to get them back to what they were to set to in Android Studio 3?</p>

答:
For Mac users:

I went to:

~/Library/Preferences/Android Studio 4.0/options

and deleted keymap.xml, which I noticed was not present on the previous version folder.

It seems to have the shortcuts working as expected.

Title: Android Studio 4.0 shortcuts changed


问:
Pivot some rows to new columns in DataFrame
I'm after a pythonic and pandemic (from pandas, pun not intended =) way to pivot some rows in a dataframe into new columns.

My data has this format:

```<code>           dof  foo  bar  qux
idxA idxB
100  101     1   10   30   50
     101     2   11   31   51
     101     3   12   32   52
     102     1   13   33   53
     102     2   14   34   54
     102     3   15   35   55
200  101     1   16   36   56
     101     2   17   37   57
     101     3   18   38   58
     102     1   19   39   59
     102     2   20   40   60
     102     3   21   41   61
</code>```

The variables foo, bar and qux actually have 3 dimensional coordinates, which I would like to call foo1, foo2, foo3, bar1, ..., qux3. These are identified by the column dof. Each row represents one axis in 3D, dof == 1 is the x axis, dof == 2 the y axis and dof == 3 is the z axis.

So, here is the final dataframe I want:

```<code>           foo1  bar1  qux1  foo2  bar2  qux2  foo3  bar3  qux3
idxA idxB
100  101     10    30    50    11    31    51    12    32    52
     102     13    33    53    14    34    54    15    35    55
200  101     16    36    56    17    37    57    18    38    58
     102     19    39    59    20    40    60    21    41    61
</code>```

Question is: what is the best way to do that?

Here is what I have done.

A code to re-create my dataset in a dataframe:

```<code>import pandas as pd

data = [[100, 101, 1, 10, 30, 50],
        [100, 101, 2, 11, 31, 51],
        [100, 101, 3, 12, 32, 52],
        [100, 102, 1, 13, 33, 53],
        [100, 102, 2, 14, 34, 54],
        [100, 102, 3, 15, 35, 55],
        [200, 101, 1, 16, 36, 56],
        [200, 101, 2, 17, 37, 57],
        [200, 101, 3, 18, 38, 58],
        [200, 102, 1, 19, 39, 59],
        [200, 102, 2, 20, 40, 60],
        [200, 102, 3, 21, 41, 61],
        ]

df = pd.DataFrame(data=data, columns=['idxA', 'idxB', 'dof', 'foo', 'bar', 'qux'])
df.set_index(['idxA', 'idxB'], inplace=True)
</code>```

Code to do what I would like to do:

```<code>df2 = df[df.dof == 1].reset_index()[['idxA', 'idxB']]
df2.set_index(['idxA', 'idxB'], inplace=True)
for pivot in [1, 2, 3]:
    df2.loc[:, 'foo%d' % pivot] = df[df.dof == pivot]['foo']
    df2.loc[:, 'bar%d' % pivot] = df[df.dof == pivot]['bar']
    df2.loc[:, 'qux%d' % pivot] = df[df.dof == pivot]['qux']
</code>```

However I'm not too happy with these .loc calls and incremental column additions to the dataframe. I thought that pandas being awesome as it is would have a neater way of doing that. A one-liner would be super cool.

Body:
I'm after a pythonic and pandemic (from pandas, pun not intended =) way to pivot some rows in a dataframe into new columns.

My data has this format:

           dof  foo  bar  qux
idxA idxB
100  101     1   10   30   50
     101     2   11   31   51
     101     3   12   32   52
     102     1   13   33   53
     102     2   14   34   54
     102     3   15   35   55
200  101     1   16   36   56
     101     2   17   37   57
     101     3   18   38   58
     102     1   19   39   59
     102     2   20   40   60
     102     3   21   41   61

The variables foo, bar and qux actually have 3 dimensional coordinates, which I would like to call foo1, foo2, foo3, bar1, ..., qux3. These are identified by the column dof. Each row represents one axis in 3D, dof == 1 is the x axis, dof == 2 the y axis and dof == 3 is the z axis.

So, here is the final dataframe I want:

           foo1  bar1  qux1  foo2  bar2  qux2  foo3  bar3  qux3
idxA idxB
100  101     10    30    50    11    31    51    12    32    52
     102     13    33    53    14    34    54    15    35    55
200  101     16    36    56    17    37    57    18    38    58
     102     19    39    59    20    40    60    21    41    61

Question is: what is the best way to do that?

Here is what I have done.

A code to re-create my dataset in a dataframe:

import pandas as pd

data = [[100, 101, 1, 10, 30, 50],
        [100, 101, 2, 11, 31, 51],
        [100, 101, 3, 12, 32, 52],
        [100, 102, 1, 13, 33, 53],
        [100, 102, 2, 14, 34, 54],
        [100, 102, 3, 15, 35, 55],
        [200, 101, 1, 16, 36, 56],
        [200, 101, 2, 17, 37, 57],
        [200, 101, 3, 18, 38, 58],
        [200, 102, 1, 19, 39, 59],
        [200, 102, 2, 20, 40, 60],
        [200, 102, 3, 21, 41, 61],
        ]

df = pd.DataFrame(data=data, columns=['idxA', 'idxB', 'dof', 'foo', 'bar', 'qux'])
df.set_index(['idxA', 'idxB'], inplace=True)

Code to do what I would like to do:

df2 = df[df.dof == 1].reset_index()[['idxA', 'idxB']]
df2.set_index(['idxA', 'idxB'], inplace=True)
for pivot in [1, 2, 3]:
    df2.loc[:, 'foo%d' % pivot] = df[df.dof == pivot]['foo']
    df2.loc[:, 'bar%d' % pivot] = df[df.dof == pivot]['bar']
    df2.loc[:, 'qux%d' % pivot] = df[df.dof == pivot]['qux']

However I'm not too happy with these .loc calls and incremental column additions to the dataframe. I thought that pandas being awesome as it is would have a neater way of doing that. A one-liner would be super cool.

Body:
You can try df.pivot

df = df.pivot(columns='dof')
          foo         bar         qux
dof         1   2   3   1   2   3   1   2   3
idxA idxB
100  101   10  11  12  30  31  32  50  51  52
     102   13  14  15  33  34  35  53  54  55
200  101   16  17  18  36  37  38  56  57  58
     102   19  20  21  39  40  41  59  60  61

Now join using df.columns

df.columns = df.columns.map('{0[0]}{0[1]}'.format) #suggested by @YOBEN_S

          foo1  foo2  foo3  bar1  bar2  bar3  qux1  qux2  qux3
idxA idxB
100  101     10    11    12    30    31    32    50    51    52
     102     13    14    15    33    34    35    53    54    55
200  101     16    17    18    36    37    38    56    57    58
     102     19    20    21    39    40    41    59    60    61


问:
MVC Networking Swift
I have this Networking class that i declared in the Model .

```<code>class Networking {
    func response (url : String ) {
        guard let url = URL(string: url) else {return}
        URLSession.shared.dataTask(with: url, completionHandler: urlPathCompletionHandler(data:response:error:)).resume()
    }

    func urlPathCompletionHandler (data : Data?  , response: URLResponse? , error: Error? ) {
        guard let data = data else {return }
        do {
            let jsondecoder = JSONDecoder()
        }catch {
            print("Error \(error)")
        }
    }
}
</code>```

In the controller . I have an array of users i declared and i want the controller to call from the Model Networking class instead of doing the networking inside the controller. This is part of my controller:

```<code>var users = [Users]()
var networking : Networking()
@IBOutlet weak var tableview : UITableView!
override func viewDidLoad() {
    super.viewDidLoad()
    tableview.delegate = self
    tableview.dataSource = self

}
func getFromModel() {
  var vm = networking.response()
</code>```

}

I want a way of calling the networking class and return an array of users that i can set to the users array above and use it to populate the table view . If i wanted to do that inside the controller it would easy but i am not sure how i can return an array of users from the Model Networking class .

答:
You need to modify your Network class like this:

class Networking {
    func response<T: Codable>(url: String, completion: ((T) -> Void)?) {
        guard let url = URL(string: url) else {return}
        URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
            self.urlPathCompletionHandler(data: data, response: response, error: error, completion: completion)
        }).resume()
    }

    func urlPathCompletionHandler<T: Codable>(data : Data?  , response: URLResponse? , error: Error?, completion:   ((T) -> Void)?) {
        guard let data = data else { return }
        do {
            let jsondecoder = JSONDecoder()
            // Pseudo Code to decode users
            completion?(decodedObject)
        } catch {
            print("Error \(error)")
        }
    }
}
```

<p>And call it like this:</p>

<pre class="lang-swift prettyprint-override"><code>func getFromModel() {
    networking.response(url: <#T##String#>) { (users: [User]) in
        self.users = users
    }
}
</code>```

Title: MVC Networking Swift

Body:
I have this Networking class that i declared in the Model .

class Networking {
    func response (url : String ) {
        guard let url = URL(string: url) else {return}
        URLSession.shared.dataTask(with: url, completionHandler: urlPathCompletionHandler(data:response:error:)).resume()
    }

    func urlPathCompletionHandler (data : Data?  , response: URLResponse? , error: Error? ) {
        guard let data = data else {return }
        do {
            let jsondecoder = JSONDecoder()
        }catch {
            print("Error \(error)")
        }
    }
}

In the controller . I have an array of users i declared and i want the controller to call from the Model Networking class instead of doing the networking inside the controller. This is part of my controller:

var users = [Users]()
var networking : Networking()
@IBOutlet weak var tableview : UITableView!
override func viewDidLoad() {
    super.viewDidLoad()
    tableview.delegate = self
    tableview.dataSource = self

}
func getFromModel() {
  var vm = networking.response()

}

I want a way of calling the networking class and return an array of users that i can set to the users array above and use it to populate the table view . If i wanted to do that inside the controller it would easy but i am not sure how i can return an array of users from the Model Networking class .

Body:
You need to modify your Network class like this:

class Networking {
    func response<T: Codable>(url: String, completion: ((T) -> Void)?) {
        guard let url = URL(string: url) else {return}
        URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
            self.urlPathCompletionHandler(data: data, response: response, error: error, completion: completion)
        }).resume()
    }

    func urlPathCompletionHandler<T: Codable>(data : Data?  , response: URLResponse? , error: Error?, completion:   ((T) -> Void)?) {
        guard let data = data else { return }
        do {
            let jsondecoder = JSONDecoder()
            // Pseudo Code to decode users
            completion?(decodedObject)
        } catch {
            print("Error \(error)")
        }
    }
}

And call it like this:

func getFromModel() {
    networking.response(url: <#T##String#>) { (users: [User]) in
        self.users = users
    }
}


问:
Invoking a Lambda function every 5 seconds

My problem

I'd like to invoke an AWS Lambda function every 5 seconds, for some monitoring purposes.

According to the docs,

Rate frequencies of less than one minute are not supported.

What have I tried

STFW.

My Question

Can I autonomously invoke an AWS Lambda function every 5 seconds?

答:
Here's the full take in serverless with a step function executing every second - forever and a day:

```<code>service:
  name: your-service

plugins:
  - serverless-python-requirements
  - serverless-step-functions
  - serverless-pseudo-parameters

custom:
  pythonRequirements:
    dockerizePip: non-linux
  region: eu-west-1
  stage: dev

package:
  exclude:
    - node_modues/**
    - venv/**

provider:
  name: aws
  iamManagedPolicies:
    - arn:aws:iam::aws:policy/AWSStepFunctionsFullAccess
    - arn:aws:iam::aws:policy/AWSLambdaFullAccess
  runtime: python3.7
  versionFunctions: false
  region: ${self:custom.region}
  stage: ${self:custom.stage}
  environment:
    PUSH_FUNCTION: arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:${self:service}-${self:custom.stage}-push
functions:

  schedulerStart:
    handler: scheduler.start
    events:
      - schedule: rate(1 minute)
    environment:
      STATEMACHINE_ARN: ${self:resources.Outputs.SchedulerStateMachine.Value}

  scheduler:
    handler: scheduler.handle

  push:
    handler: scheduler.push

stepFunctions:
  stateMachines:
    everySecond:
      name: SchedulerStateMachine
      definition:
        Comment: "Step Function invoked every minute"
        StartAt: ConfigureCount
        States:
          ConfigureCount:
            Type: Pass
            Result:
              index: 0
              count: 60
            ResultPath: "$.iterator"
            Next: "Iterator"
          Iterator:
            Type: Task
            Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:${self:service}-${self:custom.stage}-scheduler"
            ResultPath: "$.iterator"
            Next: "IsCountReached"
          IsCountReached:
            Type: Choice
            Choices:
              - Variable: "$.iterator.continue"
                BooleanEquals: true
                Next: "Wait"
            Default: "Done"
          Wait:
            Type: Wait
            Seconds: 1
            Next: "Iterator"
          Done:
            Type: Pass
            End: true

resources:
  Outputs:
    SchedulerStateMachine:
      Description: The ARN of the state machine
      Value:
        Ref: SchedulerStateMachine

</code>```

scheduler.py

```<code>import os

import boto3

lambda_client = boto3.client('lambda')
step_functions_client = boto3.client('stepfunctions')

def start(event, context):
    step_functions_client.start_execution(stateMachineArn=os.environ['STATEMACHINE_ARN'])
    return {}

def handle(event, context):
    index = event['iterator']['index'] + 1
    lambda_client.invoke(
        FunctionName=os.environ['PUSH_FUNCTION'],
        InvocationType='Event'
    )
    return {
        'index': index,
        'continue': index < event['iterator']['count'],
        'count': event['iterator']['count']
    }

def push(event, context):
    print("Executed every seconds!")
    return{}

</code>```

Body:
Here's the full take in serverless with a step function executing every second - forever and a day:

service:
  name: your-service

plugins:
  - serverless-python-requirements
  - serverless-step-functions
  - serverless-pseudo-parameters

custom:
  pythonRequirements:
    dockerizePip: non-linux
  region: eu-west-1
  stage: dev

package:
  exclude:
    - node_modues/**
    - venv/**

provider:
  name: aws
  iamManagedPolicies:
    - arn:aws:iam::aws:policy/AWSStepFunctionsFullAccess
    - arn:aws:iam::aws:policy/AWSLambdaFullAccess
  runtime: python3.7
  versionFunctions: false
  region: ${self:custom.region}
  stage: ${self:custom.stage}
  environment:
    PUSH_FUNCTION: arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:${self:service}-${self:custom.stage}-push
functions:

  schedulerStart:
    handler: scheduler.start
    events:
      - schedule: rate(1 minute)
    environment:
      STATEMACHINE_ARN: ${self:resources.Outputs.SchedulerStateMachine.Value}

  scheduler:
    handler: scheduler.handle

  push:
    handler: scheduler.push

stepFunctions:
  stateMachines:
    everySecond:
      name: SchedulerStateMachine
      definition:
        Comment: "Step Function invoked every minute"
        StartAt: ConfigureCount
        States:
          ConfigureCount:
            Type: Pass
            Result:
              index: 0
              count: 60
            ResultPath: "$.iterator"
            Next: "Iterator"
          Iterator:
            Type: Task
            Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:${self:service}-${self:custom.stage}-scheduler"
            ResultPath: "$.iterator"
            Next: "IsCountReached"
          IsCountReached:
            Type: Choice
            Choices:
              - Variable: "$.iterator.continue"
                BooleanEquals: true
                Next: "Wait"
            Default: "Done"
          Wait:
            Type: Wait
            Seconds: 1
            Next: "Iterator"
          Done:
            Type: Pass
            End: true

resources:
  Outputs:
    SchedulerStateMachine:
      Description: The ARN of the state machine
      Value:
        Ref: SchedulerStateMachine

scheduler.py

import os

import boto3

lambda_client = boto3.client('lambda')
step_functions_client = boto3.client('stepfunctions')

def start(event, context):
    step_functions_client.start_execution(stateMachineArn=os.environ['STATEMACHINE_ARN'])
    return {}

def handle(event, context):
    index = event['iterator']['index'] + 1
    lambda_client.invoke(
        FunctionName=os.environ['PUSH_FUNCTION'],
        InvocationType='Event'
    )
    return {
        'index': index,
        'continue': index < event['iterator']['count'],
        'count': event['iterator']['count']
    }

def push(event, context):
    print("Executed every seconds!")
    return{}


问:
How to make cells in UITableView not turn blue?
I am using a UITableView and the cells I am using in this view should do nothing when I click them. I can't turn off UserInteraction though because then I am not able to click on the accessory (detailDisclosureButton). So how can I make them stop turning blue and still allow them to click on the accessory?</p>

答:
```<code> tableView.allowsSelection = NO;
</code>```

Body: tableView.allowsSelection = NO;


问:
Currency convertor using two functions
I am trying to make a currency convertor using two functions in one program but for some reason my program either gets this error:

```<code>line 23, in Input1
    print(amount+"Won equals to "+totalamount+" USD")
TypeError: unsupported operand type(s) for +: 'float' and 'str'
</code>```

Or does not print anything after putting the 'Option' and 'Amount'. This is my program:

```<code>print("Please choose which currency you want to convert:")
print("A - Korean Won to US Dollar (Exchange Rate: 0.000905)")
print("B - Korean Won to Euro (Exchange Rate: 0.000807350908)")
print("C - Korean Won to Japanese Yen (Exchange Rate: 0.0919061643)")
print("D - Korean Won to Chinese RMB (Exchange Rate: 0.00603703605)")
print("E - Quit")

usd = 0.000905
eur = 0.000807350908
yen = 0.0919061643
rmb = 0.00603703605

def main():
    option =input("Enter your option: ")
    if option== "E":
        exit()
    amount =float(input("Enter the amoutn in Korean Won: "))
    Input1(option, amount)

def Input1(option,amount):
    if option == "A":
        totalamount = (amount * usd)
        print(amount+"Won equals to "+totalamount+" USD")
    elif option== "B":
        totalamount = (amount * eur)
        print (amount+"Won equals to "+totalamount+" Euro")
    elif option== "C":
        totalamount = (amount * yen)
        print (amount+"Won equals to "+totalamount+" Yen")
    elif option== "D":
        totalamount = (amount * rmb)
        print (amount+"Won equals to "+totalamount+" Chinese RMB")
    else:
            print("You entered an invalid input.")
    return option,amount

main()
</code>```

Can you guys give me tips to fix my program? I am still learning python and any help would be greatly appreciated. Thank you so much!

答:
You just need to typecast amount and totalamount variable that is currently float into string

```<code>print(str(amount)+"Won equals to "+str(totalamount)+" USD")
</code>```

Or use you use format function

```<code>print("{} Won equals to {} USD ".format(amount, totalamount))
</code>```

And i think format function is better option

Title: Currency convertor using two functions

Body:
I am trying to make a currency convertor using two functions in one program but for some reason my program either gets this error:

line 23, in Input1
    print(amount+"Won equals to "+totalamount+" USD")
TypeError: unsupported operand type(s) for +: 'float' and 'str'

Or does not print anything after putting the 'Option' and 'Amount'. This is my program:

print("Please choose which currency you want to convert:")
print("A - Korean Won to US Dollar (Exchange Rate: 0.000905)")
print("B - Korean Won to Euro (Exchange Rate: 0.000807350908)")
print("C - Korean Won to Japanese Yen (Exchange Rate: 0.0919061643)")
print("D - Korean Won to Chinese RMB (Exchange Rate: 0.00603703605)")
print("E - Quit")

usd = 0.000905
eur = 0.000807350908
yen = 0.0919061643
rmb = 0.00603703605

def main():
    option =input("Enter your option: ")
    if option== "E":
        exit()
    amount =float(input("Enter the amoutn in Korean Won: "))
    Input1(option, amount)

def Input1(option,amount):
    if option == "A":
        totalamount = (amount * usd)
        print(amount+"Won equals to "+totalamount+" USD")
    elif option== "B":
        totalamount = (amount * eur)
        print (amount+"Won equals to "+totalamount+" Euro")
    elif option== "C":
        totalamount = (amount * yen)
        print (amount+"Won equals to "+totalamount+" Yen")
    elif option== "D":
        totalamount = (amount * rmb)
        print (amount+"Won equals to "+totalamount+" Chinese RMB")
    else:
            print("You entered an invalid input.")
    return option,amount

main()

Can you guys give me tips to fix my program? I am still learning python and any help would be greatly appreciated. Thank you so much!

Body:
You just need to typecast amount and totalamount variable that is currently float into string

print(str(amount)+"Won equals to "+str(totalamount)+" USD")

Or use you use format function

print("{} Won equals to {} USD ".format(amount, totalamount))

And i think format function is better option


问:
pycharm can not open image file
I am trying to code a python calculator ,here is my code

```<code>main.py:
import pygame
import os
import Item
global items

one = Item.Item('/images/numbers/1.png',       "1",       200, 200) # here is where you specify the image file name ( must be exact!)
two = Item.Item('/images/numbers/2.png',       "2",       200, 200) # here is where you specify the image file name ( must be exact!)
three = Item.Item('/images/numbers/3.png',       "3",       200, 200) # here is where you specify the image file name ( must be exact!)
four = Item.Item('/images/numbers/4.png',       "4",       200, 200) # here is where you specify the image file name ( must be exact!)
five = Item.Item('/images/numbers/5.png',       "5",       200, 200) # here is where you specify the image file name ( must be exact!)
six = Item.Item('/images/numbers/6.png',       "6",       200, 200) # here is where yo specify the image file name ( must be exact!)
seven = Item.Item('/images/numbers/7.png',       "7",       200, 200) # here is where you specify the image file name ( must be exact!)
eight = Item.Item('/images/numbers/8.jpg',       "8",       200, 200)# here is where you specify the image file name ( must be exact!)
nine = Item.Item('/images/numbers/9.png',       "9",       200, 200)# here is where you specify the image file name ( must be exact!)
ten = Item.Item('/images/numbers/0.jpg',       "0",       200, 200)# here is where you specify the image file name ( must be exact!)
plus = Item.Item('/images/sim/+.png',       "+",       200, 200)# here is where you specify the image file name ( must be exact!)
minus = Item.Item('/images/sim/-.png',       "-",       200, 200
</code>```

and here is item.py:

```<code>import pygame
import os
global items

items = pygame.sprite.Group()

class Item(pygame.sprite.Sprite):
    global hide

    # the constructor
    def __init__(self, img_name, name, x, y):
        pygame.sprite.Sprite.__init__(self, items)
        self.image = pygame.image.load(os.path.join(img_name))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.name = name;
        self.hide = False

    # to display on game panel
    def display(self, surface):
        if self.hide == False:
            surface.blit(self.image, self.rect)
</code>```

but when i run it on pycharm it comes up with this :

```<code>/usr/local/bin/python3.7 /Users/oscar/Desktop/python_calculator/main.py
pygame 1.9.6
Traceback (most recent call last):
Hello from the pygame community. https://www.pygame.org/contribute.html
  File "/Users/oscar/Desktop/python_calculator/main.py", line 8, in <module>
    one = Item.Item('/images/numbers/1.png',       "1",       200, 200) # here is where you specify the image file name ( must be exact!)
  File "/Users/oscar/Desktop/python_calculator/Item.py", line 14, in __init__
    self.image = pygame.image.load(os.path.join(img_name))
pygame.error: Couldn't open /images/numbers/1.png

Process finished with exit code 1
</code>```

i have pygame download and i have tried to run somebody else's code with is very similar and it works an not find out out why
Please help me
Thanks

答: since python support only .gif extension of file so change the file format.</p>

Title: pycharm can not open image file

Body:
I am trying to code a python calculator ,here is my code

main.py:
import pygame
import os
import Item
global items

one = Item.Item('/images/numbers/1.png',       "1",       200, 200) # here is where you specify the image file name ( must be exact!)
two = Item.Item('/images/numbers/2.png',       "2",       200, 200) # here is where you specify the image file name ( must be exact!)
three = Item.Item('/images/numbers/3.png',       "3",       200, 200) # here is where you specify the image file name ( must be exact!)
four = Item.Item('/images/numbers/4.png',       "4",       200, 200) # here is where you specify the image file name ( must be exact!)
five = Item.Item('/images/numbers/5.png',       "5",       200, 200) # here is where you specify the image file name ( must be exact!)
six = Item.Item('/images/numbers/6.png',       "6",       200, 200) # here is where yo specify the image file name ( must be exact!)
seven = Item.Item('/images/numbers/7.png',       "7",       200, 200) # here is where you specify the image file name ( must be exact!)
eight = Item.Item('/images/numbers/8.jpg',       "8",       200, 200)# here is where you specify the image file name ( must be exact!)
nine = Item.Item('/images/numbers/9.png',       "9",       200, 200)# here is where you specify the image file name ( must be exact!)
ten = Item.Item('/images/numbers/0.jpg',       "0",       200, 200)# here is where you specify the image file name ( must be exact!)
plus = Item.Item('/images/sim/+.png',       "+",       200, 200)# here is where you specify the image file name ( must be exact!)
minus = Item.Item('/images/sim/-.png',       "-",       200, 200

and here is item.py:

import pygame
import os
global items

items = pygame.sprite.Group()

class Item(pygame.sprite.Sprite):
    global hide

    # the constructor
    def __init__(self, img_name, name, x, y):
        pygame.sprite.Sprite.__init__(self, items)
        self.image = pygame.image.load(os.path.join(img_name))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.name = name;
        self.hide = False

    # to display on game panel
    def display(self, surface):
        if self.hide == False:
            surface.blit(self.image, self.rect)

but when i run it on pycharm it comes up with this :

/usr/local/bin/python3.7 /Users/oscar/Desktop/python_calculator/main.py
pygame 1.9.6
Traceback (most recent call last):
Hello from the pygame community. https://www.pygame.org/contribute.html
  File "/Users/oscar/Desktop/python_calculator/main.py", line 8, in <module>
    one = Item.Item('/images/numbers/1.png',       "1",       200, 200) # here is where you specify the image file name ( must be exact!)
  File "/Users/oscar/Desktop/python_calculator/Item.py", line 14, in __init__
    self.image = pygame.image.load(os.path.join(img_name))
pygame.error: Couldn't open /images/numbers/1.png

Process finished with exit code 1

i have pygame download and i have tried to run somebody else's code with is very similar and it works an not find out out why
Please help me
Thanks


问:
Adding sprite in PIXI Particles Container using Vue.js
I have a problem adding a Sprite to my PIXI Particles container in Vue.js. This works when I run PIXI only inside a script, but somehow in Vuejs every new PIXI.Sprite.from("../assets/plainSquare.png") don't show

My goal is to generate a static grid of square this way:

setup() {
    // making a 30 x 16 grid of tiles
    const columns = 30;
    const rows = 16;
    for (let i = 0; i < columns * rows; i++) {
        const square = PIXI.Sprite.from("../assets/plainSquare.png");
        square.width = square.height = 25;
        square.x = (i % columns) * 32;
        square.y = Math.floor(i / columns) * 32;
        // add squares to stage
        this.container.addChild(square);
    }
}
```

If you need, here is the full codesanbox: https://codesandbox.io/s/pixi-sprite-loading-cn7re?file=/src/App.vue

答:
Use require for get the image:

PIXI.Sprite.from( require("./assets/plainSquare.png"));
```

Body:
I have a problem adding a Sprite to my PIXI Particles container in Vue.js. This works when I run PIXI only inside a script, but somehow in Vuejs every new PIXI.Sprite.from("../assets/plainSquare.png") don't show

My goal is to generate a static grid of square this way:

setup() {
    // making a 30 x 16 grid of tiles
    const columns = 30;
    const rows = 16;
    for (let i = 0; i < columns * rows; i++) {
        const square = PIXI.Sprite.from("../assets/plainSquare.png");
        square.width = square.height = 25;
        square.x = (i % columns) * 32;
        square.y = Math.floor(i / columns) * 32;
        // add squares to stage
        this.container.addChild(square);
    }
}

If you need, here is the full codesanbox: https://codesandbox.io/s/pixi-sprite-loading-cn7re?file=/src/App.vue


问:
Python While loop not iterating variable only print commands
Background context - I'm making a peculiar clock that will display the time via WS2812B pixels and learning as I go!

I have a dictionary that will contain the commands being sent to the pixels as below

```<code>hourvalues = {1: "Hour One",
              2: "Hour Two"}
</code>```

etc etc up to 24
And the main document contains the loop:

```<code>while True:
    print(hourvalues[hour])
    sleep(1)
</code>```

This works wonderfully for now with print (as a test) and I get a word every second. However, if I change the dictionary to

```<code>hourvalues = {1: print("Hour One"),
              2: Print("Hour Two")}
</code>```

and the body to

```<code>while True:
    hourvalues[hour]
    sleep(1)
</code>```

in order to represent the final thing where it will be sending a command, not printing a line, I get just a single word, and that's it.

What am I doing wrong?

This is my first post, be gentle! Thanks all

答:
Since you call the print function when you build the dictionary, it will print out the value at that time, and then store the return value (None) in the actual dictionary.

Instead, you want to create a dictionary of functions that will print the given string when called.  The lambda expression is useful for cases like this where you want to build a small function to use in one spot:

```<code>hour_actions = {
    1: lambda: print("Hour One"),
    2: lambda: print("Hour Two")
}

while True:
    hour_actions[hour]()
    sleep(1)
</code>```

Note that you need to use () to actually call the function that you get from the dictionary!

Body:
Background context - I'm making a peculiar clock that will display the time via WS2812B pixels and learning as I go!

I have a dictionary that will contain the commands being sent to the pixels as below

hourvalues = {1: "Hour One",
              2: "Hour Two"}

etc etc up to 24
And the main document contains the loop:

while True:
    print(hourvalues[hour])
    sleep(1)

This works wonderfully for now with print (as a test) and I get a word every second. However, if I change the dictionary to

hourvalues = {1: print("Hour One"),
              2: Print("Hour Two")}

and the body to

while True:
    hourvalues[hour]
    sleep(1)

in order to represent the final thing where it will be sending a command, not printing a line, I get just a single word, and that's it.

What am I doing wrong?

This is my first post, be gentle! Thanks all

Body:
Since you call the print function when you build the dictionary, it will print out the value at that time, and then store the return value (None) in the actual dictionary.

Instead, you want to create a dictionary of functions that will print the given string when called.  The lambda expression is useful for cases like this where you want to build a small function to use in one spot:

hour_actions = {
    1: lambda: print("Hour One"),
    2: lambda: print("Hour Two")
}

while True:
    hour_actions[hour]()
    sleep(1)

Note that you need to use () to actually call the function that you get from the dictionary!


问:
HTML Form to Email + 3rd Party Form Backend Platform
I have created a form using Webflow and used Getform.io for the endpoint URL for the backend platform.

Everything is working perfectly fine with all the data capturing and file uploads.

However, I am trying to make the form to send an email to user's inbox with the data capture from the form together with the file uploaded.

How can this be done using PHP or any relevant method??

So now it is as below:

Form A (created in Webflow, Getform.io endpoint URL using POST method, have file upload capability)

I need Form A to be able to send an email to user's inbox too with data and file uploaded.

Any ideas?

答: I think you could use palabra.io to do this. We have a tutorial just for Webflow you can read here: https://blog.palabra.io/how-to-send-a-confirmation-email-when-someone-submits-a-webflow-form (I'm the builder btw).</p>


问:
Copy, paste to new map & remove line break
The task is: Copy values in a specific range, open a new excel workbook, paste those values and remove all line breaks in column B in the new workbook. Currently I struggle hard with managing this in VBA.

```<code>Sub RemoveBreaks()
Dim Text As String

Range("A1:C3").Copy
Workbooks.Add
ActiveWorkbook.Sheets(1).Range("A1").Select
ActiveSheet.Paste

Text = Sheets(1).Range("B:B").Replace(Str(10), "")
End Sub
</code>```

For some crazy reason I currently do not understand this code actually works on 1 PC but does not do anything on a different PC. Any idea why or how can i fix this?

When I add:

```<code>Range("B:B") = Text
</code>```

I only get the value "true" in column B in the new workbook sheet.

Thank you very much for your help, much appriciated!
Best regards

答:
Remove:

```<code>Text = Sheets(1).Range("B:B").Replace(Str(10), "")
</code>```

And use:

```<code>Range("B:B").Replace vbNewLine, ""
</code>```

instead. Many thanks to BigBen for the help!

Body:
The task is: Copy values in a specific range, open a new excel workbook, paste those values and remove all line breaks in column B in the new workbook. Currently I struggle hard with managing this in VBA.

Sub RemoveBreaks()
Dim Text As String

Range("A1:C3").Copy
Workbooks.Add
ActiveWorkbook.Sheets(1).Range("A1").Select
ActiveSheet.Paste

Text = Sheets(1).Range("B:B").Replace(Str(10), "")
End Sub

For some crazy reason I currently do not understand this code actually works on 1 PC but does not do anything on a different PC. Any idea why or how can i fix this?

When I add:

Range("B:B") = Text

I only get the value "true" in column B in the new workbook sheet.

Thank you very much for your help, much appriciated!
Best regards

Body:
Remove:

Text = Sheets(1).Range("B:B").Replace(Str(10), "")

And use:

Range("B:B").Replace vbNewLine, ""

instead. Many thanks to BigBen for the help!


问:
How do I add PayPal Smart Buttons to a Chrome Extension?
I thought that it would be an easy 2 line integration as seen here. But after adding the correct CSP in order to allow in line executions, the behavior is not as intended. The window pops up and closes immediately.

Here is my popup.html

            <title>Quick Launcher</title>
            <link rel="stylesheet" href="style.css" />

My chrome

```

<p>manifest.json</p>

```{
    "manifest_version": 2,
    "name": "Quick Launcher",
    "description": "Smart links organizer. Create collection of related links or add urls of different environments(uat, prod) of various deployed apps",
    "version": "1.2.10",
    "icons": {
    },
    "browser_action": {
      "default_icon": {
      },
      "default_popup": "popup.html"
    },
    "content_security_policy": "script-src 'self' https://www.paypal.com 'sha256-U2vsCzUQ797LcHkgCQJsOSAJxY/+LTdJONJ+wacPXrI='; object-src 'self' https://www.paypal.com 'sha256-U2vsCzUQ797LcHkgCQJsOSAJxY/+LTdJONJ+wacPXrI='; script-src-elem 'self' https://www.paypal.com 'sha256-U2vsCzUQ797LcHkgCQJsOSAJxY/+LTdJONJ+wacPXrI='",
    "background": {
      "scripts": [
        "background.js"
      ]
    },
    "permissions": ["tabs", "activeTab"]
  }
```

答:
that is just initializing the SDK. You have to do a few things:

replace the client-id=sb with your own client id.

https://developer.paypal.com/docs/api/overview/#get-credentials

create an empty
 and reference this div by id in the render() method

Add the appropriate callback functions to create and complete an order.

ex.

```<code>paypal.Buttons({
    createOrder: function(data, actions) {
      // This function sets up the details of the transaction, including the amount and line item details.
      return actions.order.create({
        purchase_units: [{
          amount: {
            value: '0.01'
          }
        }]
      });
    },
    onApprove: function(data, actions) {
      // This function captures the funds from the transaction.
      return actions.order.capture().then(function(details) {
        // This function shows a transaction success message to your buyer.
        alert('Transaction completed by ' + details.payer.name.given_name);
      });
    }
  }).render('#paypal-button-container');
  //This function displays Smart Payment Buttons on your web page.
</code>```

https://developer.paypal.com/docs/checkout/integrate/#

Thanks!

Body:
I thought that it would be an easy 2 line integration as seen here. But after adding the correct CSP in order to allow in line executions, the behavior is not as intended. The window pops up and closes immediately.

Here is my popup.html

            <title>Quick Launcher</title>
            <link rel="stylesheet" href="style.css" />

My chrome

manifest.json

{
    "manifest_version": 2,
    "name": "Quick Launcher",
    "description": "Smart links organizer. Create collection of related links or add urls of different environments(uat, prod) of various deployed apps",
    "version": "1.2.10",
    "icons": {
    },
    "browser_action": {
      "default_icon": {
      },
      "default_popup": "popup.html"
    },
    "content_security_policy": "script-src 'self' https://www.paypal.com 'sha256-U2vsCzUQ797LcHkgCQJsOSAJxY/+LTdJONJ+wacPXrI='; object-src 'self' https://www.paypal.com 'sha256-U2vsCzUQ797LcHkgCQJsOSAJxY/+LTdJONJ+wacPXrI='; script-src-elem 'self' https://www.paypal.com 'sha256-U2vsCzUQ797LcHkgCQJsOSAJxY/+LTdJONJ+wacPXrI='",
    "background": {
      "scripts": [
        "background.js"
      ]
    },
    "permissions": ["tabs", "activeTab"]
  }

Body:
that is just initializing the SDK. You have to do a few things:

replace the client-id=sb with your own client id.

https://developer.paypal.com/docs/api/overview/#get-credentials

create an empty <div> and reference this div by id in the render() method

Add the appropriate callback functions to create and complete an order.

ex.

paypal.Buttons({
    createOrder: function(data, actions) {
      // This function sets up the details of the transaction, including the amount and line item details.
      return actions.order.create({
        purchase_units: [{
          amount: {
            value: '0.01'
          }
        }]
      });
    },
    onApprove: function(data, actions) {
      // This function captures the funds from the transaction.
      return actions.order.capture().then(function(details) {
        // This function shows a transaction success message to your buyer.
        alert('Transaction completed by ' + details.payer.name.given_name);
      });
    }
  }).render('#paypal-button-container');
  //This function displays Smart Payment Buttons on your web page.

https://developer.paypal.com/docs/checkout/integrate/#

Thanks!


问:
What is the most efficient way to call a function on a 2D ndarray of coordinates?
I have a ndarray of size (M, N, 3). It holds M x N points, each of which is identified by its x, y, and z coordinates. I also have a function 'foo'. 'foo' takes in a point as a ndarray of size (, 3). Is there a faster way to call 'foo' on each of the M x N points in my array than to use two nested for loops?

So far, this is what I have tried. My array is the variable 'sample_array'.

```<code>num_rows = sample_array.shape[0]
num_columns = sample_array.shape[1]
solution = np.zeros((num_rows, num_columns))

for row in range(num_rows):
   for column in range(num_columns):
      point = sample_array[row, column]
      solution[row, column] = foo(point)
</code>```

I found this answer, which describes using these two solutions:

```<code>np.vectorize(foo)
np.array(map(foo, sample_array))
</code>```

However, I am not sure how to specify that I don't want the function mapped to every one of the M x N x 3 floats. Instead, I would like it to map the function to be called on each of the M x N (, 3) ndarrays.

Thank you!

答:
A way to use map is:

```<code>solution = np.array(list(map(foo, sample_array.reshape(-1,3)) ))\
             .reshape(sample_array.shape[:2])
</code>```

Body:
I have a ndarray of size (M, N, 3). It holds M x N points, each of which is identified by its x, y, and z coordinates. I also have a function 'foo'. 'foo' takes in a point as a ndarray of size (, 3). Is there a faster way to call 'foo' on each of the M x N points in my array than to use two nested for loops?

So far, this is what I have tried. My array is the variable 'sample_array'.

num_rows = sample_array.shape[0]
num_columns = sample_array.shape[1]
solution = np.zeros((num_rows, num_columns))

for row in range(num_rows):
   for column in range(num_columns):
      point = sample_array[row, column]
      solution[row, column] = foo(point)

I found this answer, which describes using these two solutions:

np.vectorize(foo)
np.array(map(foo, sample_array))

However, I am not sure how to specify that I don't want the function mapped to every one of the M x N x 3 floats. Instead, I would like it to map the function to be called on each of the M x N (, 3) ndarrays.

Thank you!

Body:
A way to use map is:

solution = np.array(list(map(foo, sample_array.reshape(-1,3)) ))\
             .reshape(sample_array.shape[:2])


问:
Divide two lists of matrices where the ith matrix element in one list is divided by the ith matrix element in the second list
I have two lists of matrices. Here is an example of their structure:

```<code>list1<- list(structure(c(1, 2, 7, 1, 3, 0, 0, 0, 1, 4, 1, 3, 2, 3, 4,
6, 0, 0, 0, 3, 3), .Dim = c(7L, 3L), .Dimnames = list(c("lepA",
"lepB", "lepC", "lepD", "lepE", "lepF", "lepG"), NULL)), structure(c(1,
3, 7, 1, 3, 2, 3, 4, 6, 4, 1, 3, 3, 3), .Dim = c(7L, 2L), .Dimnames = list(
c("lepA", "lepB", "lepC", "lepD", "lepE", "lepF", "lepG"),
NULL)), structure(c(5, 8, 7, 1, 3, 3, 3), .Dim = c(7L, 1L
), .Dimnames = list(c("lepA", "lepB", "lepC", "lepD", "lepE",
"lepF", "lepG"), NULL)))

list2<-list(structure(c(6, 1, 51, 13, 15, 0, 0, 0, 6, 50, 13, 15, 6,
5, 5, 9, 0, 0, 0, 7, 5), .Dim = c(7L, 3L), .Dimnames = list(c("lepA",
"lepB", "lepC", "lepD", "lepE", "lepF", "lepG"), NULL)), structure(c(6,
7, 51, 13, 15, 6, 5, 5, 9, 50, 13, 15, 7, 5), .Dim = c(7L, 2L
), .Dimnames = list(c("lepA", "lepB", "lepC", "lepD", "lepE",
"lepF", "lepG"), NULL)), structure(c(11, 10, 51, 13, 15, 7, 5
), .Dim = c(7L, 1L), .Dimnames = list(c("lepA", "lepB", "lepC",
"lepD", "lepE", "lepF", "lepG"), NULL)))
</code>```

I need to divide each element of each matrix in a list with the corresponding element in the matching matrix in the second list. It's as though the two lists of matrices should be one list of arrays and the dividend is calculated for each array element. The result would be:

```<code>list<- list(list1[[1]]/list2[[1]], list1[[2]]/list2[[2]], list1[[3]]/list2[[3]])
</code>```

I tried:

```<code>list1/list2
</code>```

答:
We can use seq_along with lapply

```<code>lapply(seq_along(list1), function(i) list1[[i]]/list2[[i]])
</code>```

Body:
I have two lists of matrices. Here is an example of their structure:

list1<- list(structure(c(1, 2, 7, 1, 3, 0, 0, 0, 1, 4, 1, 3, 2, 3, 4,
6, 0, 0, 0, 3, 3), .Dim = c(7L, 3L), .Dimnames = list(c("lepA",
"lepB", "lepC", "lepD", "lepE", "lepF", "lepG"), NULL)), structure(c(1,
3, 7, 1, 3, 2, 3, 4, 6, 4, 1, 3, 3, 3), .Dim = c(7L, 2L), .Dimnames = list(
c("lepA", "lepB", "lepC", "lepD", "lepE", "lepF", "lepG"),
NULL)), structure(c(5, 8, 7, 1, 3, 3, 3), .Dim = c(7L, 1L
), .Dimnames = list(c("lepA", "lepB", "lepC", "lepD", "lepE",
"lepF", "lepG"), NULL)))

list2<-list(structure(c(6, 1, 51, 13, 15, 0, 0, 0, 6, 50, 13, 15, 6,
5, 5, 9, 0, 0, 0, 7, 5), .Dim = c(7L, 3L), .Dimnames = list(c("lepA",
"lepB", "lepC", "lepD", "lepE", "lepF", "lepG"), NULL)), structure(c(6,
7, 51, 13, 15, 6, 5, 5, 9, 50, 13, 15, 7, 5), .Dim = c(7L, 2L
), .Dimnames = list(c("lepA", "lepB", "lepC", "lepD", "lepE",
"lepF", "lepG"), NULL)), structure(c(11, 10, 51, 13, 15, 7, 5
), .Dim = c(7L, 1L), .Dimnames = list(c("lepA", "lepB", "lepC",
"lepD", "lepE", "lepF", "lepG"), NULL)))

I need to divide each element of each matrix in a list with the corresponding element in the matching matrix in the second list. It's as though the two lists of matrices should be one list of arrays and the dividend is calculated for each array element. The result would be:

list<- list(list1[[1]]/list2[[1]], list1[[2]]/list2[[2]], list1[[3]]/list2[[3]])

I tried:

list1/list2

Body:
We can use seq_along with lapply

lapply(seq_along(list1), function(i) list1[[i]]/list2[[i]])


问:
Microsoft Teams Message extension without popup/extra params
I want to have a message extension that simply sends the message text to the message handler. So when the user clicks the message extension from the (...) menu, that is it, no other input/step is necessary.

It appears that Microsoft forces you to have some additional parameters.

Is there a way to get around this and simply send the message content without additional parameters?

答:
@Subhasish-MSFT I was able to get the desired functionality by removing the parameter values, and setting fetchTask to false. So now when a user clicks on the message extension, there is no popup presented to the user.

```<code>"composeExtensions": [
    {
        "botId": "--Bot Id Here--",
        "canUpdateConfiguration": true,
        "commands": [
            {
                "id": "commandId",
                "type": "action",
                "title": "Command Title",
                "description": "",
                "initialRun": true,
                "fetchTask": false,
                "context": [
                    "message"
                ]
            }
        ]
    }
],
</code>```

Body:
@Subhasish-MSFT I was able to get the desired functionality by removing the parameter values, and setting fetchTask to false. So now when a user clicks on the message extension, there is no popup presented to the user.

"composeExtensions": [
    {
        "botId": "--Bot Id Here--",
        "canUpdateConfiguration": true,
        "commands": [
            {
                "id": "commandId",
                "type": "action",
                "title": "Command Title",
                "description": "",
                "initialRun": true,
                "fetchTask": false,
                "context": [
                    "message"
                ]
            }
        ]
    }
],


问:
My saga function is not being called at all when calling my action?
I joined a big/medium project, I am having a hard time creating my first redux-saga-action things, it is going to be a lot of code since they are creating a lot of files to make things readable.

So I call my action in my componentDidMount, the action is being called because I have the alert :

```<code>export const fetchDataRequest = () => {
  alert("actions data");
  return ({
    type: FETCH_DATA_REQUEST
  })
};

export const fetchDataSuccess = data => ({
  type: FETCH_DATA_SUCCESS,
  payload: {
    data,
  },
});
</code>```

This is my history saga : ( when I call the action with this type, The function get executed )

```<code>export default function* dataSaga() {
    // their takeEverymethods
    yield takeEvery(FETCH_DATA_REQUEST, fetchData);
}
</code>```

This is what has to be called : ( I am trying to fill my state with data in a json file : mock )

```<code>export default function* fetchTronconsOfCircuit() {

    try {

        // Cal to api
        const client = yield call(RedClient);
        const data = yield call(client.fetchSomething);

        // mock
        const history = data === "" ? "" : fakeDataFromMock;
        console.log("history : ");
        console.log(history);

        if (isNilOrEmpty(history)) return null;

        yield put(fetchDataSuccess({ data: history }));
    } catch (e) {
        yield put(addErr(e));
    }
}
</code>```

And this is my root root saga :

```<code>export default function* sagas() {

  // many other spawn(somethingSaga);
  yield spawn(historySaga);

}
</code>```

and here is the reducer :

```<code>const fetchDataSuccess = curry(({ data }, state) => ({
  ...state,
  myData: data,
}));

const HistoryReducer = createSwitchReducer(initialState, [
  [FETCH_DATA_SUCCESS, fetchDataSuccess],
]);
</code>```

The method createSwitchReducer is a method created by the team to create easily a reducer instead of creating a switch and passing the action.type in params etc, their method is working fine, and I did exactly what they do for others.

Am I missing something ?

I feel like I did everything right but the saga is not called, which means it is trivial problem, the connection between action and saga is a common problem I just could not figure where is my problem.

I do not see the console.log message in the console, I added an alert before the try-catch but got nothing too, but alert inside action is being called.

Any help would be really really appreciated.

答:
```<code>yield takeEvery(FETCH_DATA_REQUEST, fetchData);
</code>```

should be

```<code>yield takeEvery(FETCH_DATA_REQUEST, fetchTronconsOfCircuit);
</code>```

Body:
I joined a big/medium project, I am having a hard time creating my first redux-saga-action things, it is going to be a lot of code since they are creating a lot of files to make things readable.

So I call my action in my componentDidMount, the action is being called because I have the alert :

export const fetchDataRequest = () => {
  alert("actions data");
  return ({
    type: FETCH_DATA_REQUEST
  })
};

export const fetchDataSuccess = data => ({
  type: FETCH_DATA_SUCCESS,
  payload: {
    data,
  },
});

This is my history saga : ( when I call the action with this type, The function get executed )

export default function* dataSaga() {
    // their takeEverymethods
    yield takeEvery(FETCH_DATA_REQUEST, fetchData);
}

This is what has to be called : ( I am trying to fill my state with data in a json file : mock )

export default function* fetchTronconsOfCircuit() {

    try {

        // Cal to api
        const client = yield call(RedClient);
        const data = yield call(client.fetchSomething);

        // mock
        const history = data === "" ? "" : fakeDataFromMock;
        console.log("history : ");
        console.log(history);

        if (isNilOrEmpty(history)) return null;

        yield put(fetchDataSuccess({ data: history }));
    } catch (e) {
        yield put(addErr(e));
    }
}

And this is my root root saga :

export default function* sagas() {

  // many other spawn(somethingSaga);
  yield spawn(historySaga);

}

and here is the reducer :

const fetchDataSuccess = curry(({ data }, state) => ({
  ...state,
  myData: data,
}));

const HistoryReducer = createSwitchReducer(initialState, [
  [FETCH_DATA_SUCCESS, fetchDataSuccess],
]);

The method createSwitchReducer is a method created by the team to create easily a reducer instead of creating a switch and passing the action.type in params etc, their method is working fine, and I did exactly what they do for others.

Am I missing something ?

I feel like I did everything right but the saga is not called, which means it is trivial problem, the connection between action and saga is a common problem I just could not figure where is my problem.

I do not see the console.log message in the console, I added an alert before the try-catch but got nothing too, but alert inside action is being called.

Any help would be really really appreciated.

Body:
yield takeEvery(FETCH_DATA_REQUEST, fetchData);

should be

yield takeEvery(FETCH_DATA_REQUEST, fetchTronconsOfCircuit);


问:
Where to get Oracle and JobID?
I am working on making a smart contract using Chainlink oracles, and I’ve run into this issue. I have an API call that I want to make, but I’m not sure which nodes/oracles I should call. They give some sample nodes, but if I understand the technology properly, I should be able to call my own nodes. Where can I find this information? I know it needs to return a bytes32.</p>

```<code>Oracle = // TODO
JOB = // TODO
function requestJoke() public
  {
    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
    req.add("get", "https://sv443.net/jokeapi/v2/joke/Any");
    req.add("path", "joke");
    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
  }
</code>```

答:
To make a chainlink oracle request, you can use any oracle that has a job that can return a bytes32.

You can look for and find Oracle contract address and Job IDs on sites such as market.link. The other important thing to note is that each Ethereum network (mainnet, ropsten, kovan, etc) each have different ID and addresses. You'll also need to differentiate between a GET and a POST request, you can also see the chainlink docs for more information.

An easy one would be to use the Alpha Chain oracles.

```<code>// A get request for bytes32 on Ropsten
address ORACLE = 0xB36d3709e22F7c708348E225b20b13eA546E6D9c;
bytes32 JOBID = "de6ad2f87c6b42679777dc658a93705c";

// This JOBID returns a bytes32 object
</code>```

Title: Where to get Oracle and JobID?

Body:
I am working on making a smart contract using Chainlink oracles, and I’ve run into this issue. I have an API call that I want to make, but I’m not sure which nodes/oracles I should call. They give some sample nodes, but if I understand the technology properly, I should be able to call my own nodes. Where can I find this information? I know it needs to return a bytes32.

Oracle = // TODO
JOB = // TODO
function requestJoke() public
  {
    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
    req.add("get", "https://sv443.net/jokeapi/v2/joke/Any");
    req.add("path", "joke");
    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
  }

Body:
To make a chainlink oracle request, you can use any oracle that has a job that can return a bytes32.

You can look for and find Oracle contract address and Job IDs on sites such as market.link. The other important thing to note is that each Ethereum network (mainnet, ropsten, kovan, etc) each have different ID and addresses. You'll also need to differentiate between a GET and a POST request, you can also see the chainlink docs for more information.

An easy one would be to use the Alpha Chain oracles.

// A get request for bytes32 on Ropsten
address ORACLE = 0xB36d3709e22F7c708348E225b20b13eA546E6D9c;
bytes32 JOBID = "de6ad2f87c6b42679777dc658a93705c";

// This JOBID returns a bytes32 object


问:
Is there a way to pass data between 2 cell renderers in ag grid?
I have 2 cell renderers in 2 coulmns of my ag grid. 1st column is action column. 2nd column is a dropdown containing data options.

Dynamically, based on the selection of data from dropdown in 2nd column, i want to change / toggle the action icons in the 1st column. Is this possible?

I have used cellrendererframework for both cell renderers.

答:
Yes, it is possible!

First of all, you should add refresh() method to you cell-dropdown.component

It will look like:

```<code>public refresh(params): boolean {
    params.api.redrawRows();

    return true;
}
</code>```

After new selection have been selected it calls the method refresh() and the first column will redraw

I have created exapmle with your case:

We have dropdown of gender and based on changed selection -  name of the first column will change

For gender column is used cellRenderFrameWork

for the first column (name) is used simple inline cellRender and looks like

```<code>  { field: 'name', cellRenderer: params => {
    return params.data.gender === "Female" ? params.value : 'Roman'
  } },
</code>```

working example: https://plnkr.co/edit/HT5fgs0VV5PqErWH

Body:
Yes, it is possible!

First of all, you should add refresh() method to you cell-dropdown.component

It will look like:

public refresh(params): boolean {
    params.api.redrawRows();

    return true;
}

After new selection have been selected it calls the method refresh() and the first column will redraw

I have created exapmle with your case:

We have dropdown of gender and based on changed selection -  name of the first column will change

For gender column is used cellRenderFrameWork

for the first column (name) is used simple inline cellRender and looks like

  { field: 'name', cellRenderer: params => {
    return params.data.gender === "Female" ? params.value : 'Roman'
  } },

working example: https://plnkr.co/edit/HT5fgs0VV5PqErWH


问:
Selecting individual documents/objects from MongoDB collection that's in a loop?
I'm not sure how to word this exactly...but basically in my code I am looping through my MongoDB collection using forEach and displaying the objects within them with ejs in a table. I want to make it so that when a user clicks on one of those objects, it takes them to a page with details for just the item they selected, but can't do that because they are displayed via a loop.

For example:
My collection, called stores, has objects like environment, store, and version. When I display them with a loop, this is how I do it:

                Environment
                Store Name
                Code Version

        <% stores.forEach(function(store){ %>

                 <%= store.environment %>
                 <%= store.store %>
                 <%= store.version %>

        <% }); %>

```

<p>and the resulting table looks something like this:</p>

```Environment | Store Name   | Code Version
-----------------------------------------
QA1         | Oakdale      | 2019.09
QA2         | Westminster  | 2020.03
QA3         | Garden Grove | 2020.05
```

I want the user to be able to click on, for example, QA1 and it will direct them to another page for details on QA1. My question is, with the code being displayed as a group via <%= store.environment %>, how do I create a link on JUST QA1, or just QA2? Right now if I put a link in the same td as <%= store.environment %>, that link shows up in every instance of environment.

Is there maybe a way through jQuery or something to select the specific environments?

答:
Yes, you can, you'll just have to check the environment property, or whatever property you're using to define if should show the link.

Here's a quick example of how you could do that:

            Environment
            Store Name
            Code Version

    <% stores.forEach(function(store){ %>

                <% if (store.environment === "QA1") { %>
                   <%= store.environment %>
                <% } else { %>
                   <%= store.environment %>
               <% } %>

             <%= store.store %>
             <%= store.version %>

    <% }); %>

```

Sorry for any code mistake, I'm doing direct from StackOverflow.

Body:
I'm not sure how to word this exactly...but basically in my code I am looping through my MongoDB collection using forEach and displaying the objects within them with ejs in a table. I want to make it so that when a user clicks on one of those objects, it takes them to a page with details for just the item they selected, but can't do that because they are displayed via a loop.

For example:
My collection, called stores, has objects like environment, store, and version. When I display them with a loop, this is how I do it:

                Environment
                Store Name
                Code Version

        <% stores.forEach(function(store){ %>

                 <%= store.environment %>
                 <%= store.store %>
                 <%= store.version %>

        <% }); %>

and the resulting table looks something like this:

Environment | Store Name   | Code Version
-----------------------------------------
QA1         | Oakdale      | 2019.09
QA2         | Westminster  | 2020.03
QA3         | Garden Grove | 2020.05

I want the user to be able to click on, for example, QA1 and it will direct them to another page for details on QA1. My question is, with the code being displayed as a group via <%= store.environment %>, how do I create a link on JUST QA1, or just QA2? Right now if I put a link in the same td as <%= store.environment %>, that link shows up in every instance of environment.

Is there maybe a way through jQuery or something to select the specific environments?

Body:
Yes, you can, you'll just have to check the environment property, or whatever property you're using to define if should show the link.

Here's a quick example of how you could do that:

<table>
        <tr>
            <th>Environment</th>
            <th>Store Name</th>
            <th>Code Version</th>
        </tr>
    <% stores.forEach(function(store){ %>
        <tr>
            <td>
                <% if (store.environment === "QA1") { %>
                   <a href="/your-url"><%= store.environment %></a>
                <% } else { %>
                   <%= store.environment %>
               <% } %>
            </td>
            <td> <%= store.store %> </td>
            <td> <%= store.version %> </td>
        </tr>
    <% }); %>
</table>

Sorry for any code mistake, I'm doing direct from StackOverflow.


问:
Checking Duplicate Records in Table Where Id is Identity
In my table, ID is primary key field and identity column.
I want to check duplicate records.
(Certainly duplicate records do not have same ID)

And do not have date fields same.

How do I check this.

Extra Detail: I have 10 columns with 1 ID, 2 Date, and other 3 string, 3 Int, 1 bit.

Thansk in Advance.

答:
Please use GROUP BY to group similar records and HAVING to specify condition on them.</p>

```<code>select count(string1), count(string2),count(string3),count(int1), count(int2),count(int3),count(bit1)
from table1
group by string1, string2, string3, int1, int2, int3, bit1
having count(string1) > 1 and count(string2) > 1 and count(string3) > 1 and count(int1) > 1 and count(int2) > 1 and count(int3) > 1 and count(bit1) > 1
</code>```

Body:
Please use GROUP BY to group similar records and HAVING to specify condition on them.

select count(string1), count(string2),count(string3),count(int1), count(int2),count(int3),count(bit1)
from table1
group by string1, string2, string3, int1, int2, int3, bit1
having count(string1) > 1 and count(string2) > 1 and count(string3) > 1 and count(int1) > 1 and count(int2) > 1 and count(int3) > 1 and count(bit1) > 1


问:
n-iter for the kmedoids in the pyclustering library in PyPI?
How can I access the attribute of the number of iterations performed until convergence for the kmedoids as implemented in the pyclustering library in PyPI?

In the Scikit Learn implementation of KMeans, it provides access to 4 attributes:

cluster_centers_

labels_

inertia_

n_iter_

Where n_iter_ is the number of iterations required to converge on the solution as required by the parameters supplied to the algorithm.

In the very useful set of algorithms in the Pyclustering Library, the series of clustering algorithms similar to KMeans are useful. I am interested in one in particular kmedoids, but an answer for the other KMeans-similar algorithms I think would be generally useful.

For kmediods, there is no access to an attribute like n_iter_. Thus the question.

答:
You can do this with itermax argument.

Have a look at the pyclustering docs: https://pyclustering.github.io/docs/0.9.3/html/d0/dd3/classpyclustering_1_1cluster_1_1kmedoids_1_1kmedoids.html#a698b7a2df2358221e705012973df44a6

[in]  **kwargs

  Arbitrary keyword arguments (available arguments:
  'metric', 'data_type', 'itermax').

Example:

```<code>kmedoids_instance = kmedoids(dm, initial_medoids,
    tolerance = 0.001,
    ccore = True,
    metric = distance_metric(type_metric.MINKOWSKI, degree=2),
    data_type = 'distance_matrix',
    itermax = 1000
)
</code>```

Or you pass an unpacked dictionary as arguments:

```<code>metric = distance_metric(type_metric.MINKOWSKI, degree=2)
kwargs = {'metric': metric, 'data_type': 'distance_matrix', 'itermax': 1000}
kmedoids_instance = kmedoids(dm, initial_medoids,
    tolerance = 0.001,
    ccore = True,
    **kwargs
)
</code>```

Body:
You can do this with itermax argument.

Have a look at the pyclustering docs: https://pyclustering.github.io/docs/0.9.3/html/d0/dd3/classpyclustering_1_1cluster_1_1kmedoids_1_1kmedoids.html#a698b7a2df2358221e705012973df44a6

[in]  **kwargs

  Arbitrary keyword arguments (available arguments:
  'metric', 'data_type', 'itermax').

Example:

kmedoids_instance = kmedoids(dm, initial_medoids,
    tolerance = 0.001,
    ccore = True,
    metric = distance_metric(type_metric.MINKOWSKI, degree=2),
    data_type = 'distance_matrix',
    itermax = 1000
)

Or you pass an unpacked dictionary as arguments:

metric = distance_metric(type_metric.MINKOWSKI, degree=2)
kwargs = {'metric': metric, 'data_type': 'distance_matrix', 'itermax': 1000}
kmedoids_instance = kmedoids(dm, initial_medoids,
    tolerance = 0.001,
    ccore = True,
    **kwargs
)