问:
Find Duplicate Objects in JSON Array
I am relatively new to c# and need some guidance. I need to search through a large json array to find duplicate objects and list how many occurrences.

Sample Array

```<code>{
    "data":
        [
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          }

        ]
}
</code>```

I have been able to search through and find duplicate elements but not the complete object. The output should be:

```<code>{
    "result":
        [
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND",
            "objCount": 2
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV",
            "objCount": 3
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND",
            "objCount": 3
          }

        ]
}
</code>```

Any help to point me in the right direction would be great. Thanks in advance

答:
Another approach, with usage of anonymous classes:

using JsonDocument jsonDocument = JsonDocument.Parse(jsonString);

var output = jsonDocument.RootElement
    .GetProperty("data") // get root level "data" property
    .EnumerateArray()
    // create anonymous type on which C# will group list
    // this will work, because C# generates custom field comparing
    // Equals for anonymous types
    .GroupBy(e => new {
            date = e.GetProperty("date").GetString(),
            someID = e.GetProperty("someID").GetString(),
            someType1 = e.GetProperty("someType1").GetString(),
            someType2 = e.GetProperty("someType2").GetString(),
    }).Select(g => new {
            date = g.Key.date,
            someID = g.Key.someID,
            someType1 = g.Key.someType1,
            someType2 = g.Key.someType2,
            objCount = g.Count(),
    });

```

Title: Find Duplicate Objects in JSON Array

Body:
I am relatively new to c# and need some guidance. I need to search through a large json array to find duplicate objects and list how many occurrences.

Sample Array

{
    "data":
        [
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          }

        ]
}

I have been able to search through and find duplicate elements but not the complete object. The output should be:

{
    "result":
        [
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND",
            "objCount": 2
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV",
            "objCount": 3
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND",
            "objCount": 3
          }

        ]
}

Any help to point me in the right direction would be great. Thanks in advance


来源: stackexchange

问:
How to kill the pm2 --no-daemon process
I'm using pm2 as the process manager of Node.js.

In many cases, I think I will run it as a daemon process, but if you use it locally as debugging, I think that there are times when you use the --no-daemon option.

How do I end the process when moving pm2 with this --no-daemon option?

答:
One thing to add to the accepted answers. These commands only work for the current user. I had the same problem with a digitalocean droplet. I had logged in using "ubuntu" username, but I saw that the God Daemon is pointing to /home/nodejs/.pm2.

If this is the case, you need to switch to that user:
sudo su nodejs
And then run the pm2 kill commands from there.

ContentLicense: CC BY-SA 3.0

Title: How to kill the pm2 --no-daemon process

ContentLicense: CC BY-SA 4.0


问:
Manually draw boxplot using ggplot
I think my question is very similar to this one, the only difference being that I'd love to use ggplot (and the answer with ggplot was missing a tiny bit of detail).   I have data like this:

```<code>show<-structure(list(Median = c(20, 39, 21, 52, 45.5, 24, 36, 20, 134,
27, 44, 43), IQR = c(4, 74, 28, 51.5, 73.5, 18, 47.5, 26.5, 189.5,
46, 54, 61), FirstQuartile = c(`25%` = 19, `25%` = 24, `25%` = 12,
`25%` = 30.5, `25%` = 36.5, `25%` = 18, `25%` = 16.5, `25%` = 13,
`25%` = 53.5, `25%` = 15, `25%` = 24.5, `25%` = 27), ThirdQuartile = c(`75%` = 23,
`75%` = 98, `75%` = 40, `75%` = 82, `75%` = 110, `75%` = 36,
`75%` = 64, `75%` = 39.5, `75%` = 243, `75%` = 61, `75%` = 78.5,
`75%` = 88), Group = c("Program Director", "Editor", "Everyone",
"Board Director", "Board Director", "Program Director", "Editor",
"Everyone", "Board Director", "Everyone", "Editor", "Program Director"
), Decade = c("1980's", "1980's", "1980's", "1980's", "1990's",
"1990's", "1990's", "1990's", "2000's", "2000's", "2000's", "2000's"
)), row.names = c(NA, -12L), class = c("tbl_df", "tbl", "data.frame"
))
</code>```

And I would like to draw a graph like this:

With "group" as the color, instead of "fellowship".  The problem is, that graph was drawn from "complete" data (with 800ish rows), and I clearly only have summary data above.  I realize it won't be able to draw outliers but that is ok.  Any help would be appreciated!  I'm specifically struggling with how I would draw the ymin/max and the edges of the notch.  Thank you

答:
You can use geom_boxplot() with stat = "identity" and fill in the five boxplot numbers as aesthetics.

library(ggplot2)

# show <- structure(...) # omitted for previty

ggplot(show, aes(Decade, fill = Group)) +
  geom_boxplot(
    stat = "identity",
    aes(lower  = FirstQuartile,
        upper  = ThirdQuartile,
        middle = Median,
        ymin   = FirstQuartile - 1.5 * IQR, # optional
        ymax   = ThirdQuartile + 1.5 * IQR) # optional
  )
```
<p><img src="https://i.imgur.com/hUJQduN.png" alt="" /></p>
<p>As pointed out by jpsmith in the comments below, the <code>1.5 * IQR</code> rule becomes hairy if you don't have the range of the data. However, if you have information about the data extrema or the data domain, you can limit the whiskers as follows:</p>
```# Dummy values assuming data is >= 0 up to infinity
show$min <- 0
show$max <- Inf

ggplot(show, aes(Decade, fill = Group)) +
  geom_boxplot(
    stat = "identity",
    aes(lower  = FirstQuartile,
        upper  = ThirdQuartile,
        middle = Median,
        ymin   = pmax(FirstQuartile - 1.5 * IQR, min),
        ymax   = pmin(ThirdQuartile + 1.5 * IQR, max))
  )
```

Title: Manually draw boxplot using ggplot

Body:
I think my question is very similar to this one, the only difference being that I'd love to use ggplot (and the answer with ggplot was missing a tiny bit of detail).   I have data like this:

show<-structure(list(Median = c(20, 39, 21, 52, 45.5, 24, 36, 20, 134,
27, 44, 43), IQR = c(4, 74, 28, 51.5, 73.5, 18, 47.5, 26.5, 189.5,
46, 54, 61), FirstQuartile = c(`25%` = 19, `25%` = 24, `25%` = 12,
`25%` = 30.5, `25%` = 36.5, `25%` = 18, `25%` = 16.5, `25%` = 13,
`25%` = 53.5, `25%` = 15, `25%` = 24.5, `25%` = 27), ThirdQuartile = c(`75%` = 23,
`75%` = 98, `75%` = 40, `75%` = 82, `75%` = 110, `75%` = 36,
`75%` = 64, `75%` = 39.5, `75%` = 243, `75%` = 61, `75%` = 78.5,
`75%` = 88), Group = c("Program Director", "Editor", "Everyone",
"Board Director", "Board Director", "Program Director", "Editor",
"Everyone", "Board Director", "Everyone", "Editor", "Program Director"
), Decade = c("1980's", "1980's", "1980's", "1980's", "1990's",
"1990's", "1990's", "1990's", "2000's", "2000's", "2000's", "2000's"
)), row.names = c(NA, -12L), class = c("tbl_df", "tbl", "data.frame"
))

And I would like to draw a graph like this:

With "group" as the color, instead of "fellowship".  The problem is, that graph was drawn from "complete" data (with 800ish rows), and I clearly only have summary data above.  I realize it won't be able to draw outliers but that is ok.  Any help would be appreciated!  I'm specifically struggling with how I would draw the ymin/max and the edges of the notch.  Thank you

Body:
You can use geom_boxplot() with stat = "identity" and fill in the five boxplot numbers as aesthetics.

library(ggplot2)

# show <- structure(...) # omitted for previty

ggplot(show, aes(Decade, fill = Group)) +
  geom_boxplot(
    stat = "identity",
    aes(lower  = FirstQuartile,
        upper  = ThirdQuartile,
        middle = Median,
        ymin   = FirstQuartile - 1.5 * IQR, # optional
        ymax   = ThirdQuartile + 1.5 * IQR) # optional
  )

As pointed out by jpsmith in the comments below, the 1.5 * IQR rule becomes hairy if you don't have the range of the data. However, if you have information about the data extrema or the data domain, you can limit the whiskers as follows:

# Dummy values assuming data is >= 0 up to infinity
show$min <- 0
show$max <- Inf

ggplot(show, aes(Decade, fill = Group)) +
  geom_boxplot(
    stat = "identity",
    aes(lower  = FirstQuartile,
        upper  = ThirdQuartile,
        middle = Median,
        ymin   = pmax(FirstQuartile - 1.5 * IQR, min),
        ymax   = pmin(ThirdQuartile + 1.5 * IQR, max))
  )


问:
Not accurately read numeric number with a DataReader from SQLite
I got a problem where I can't read the data from my database correctly.

To give you an example, I got the important value that is in the database 6.69879289850025E-06, but I read 6.0 (which is not accurate since it's suppose to be way smaller) in the C# program.

Something similar happen to ImportantValue2 where the value that is in the database is -0,000158976621370616 and in my C# program I get 0,0.

```<code> public double ImportantValue1 { get; set; }
 public double ImportantValue2 { get; set; }
 public string Note { get; set; }

public MyObject(SQLiteDataReader reader)
        {
            ImportantValue1 = Convert.ToDouble(reader["important_value_1"]); //Value in the database is REAL
            ImportantValue2 = Convert.ToDouble(reader["important_value_2"]);//Value in the database is REAL
            Note = reader["note"].ToString(); //Value in the database is TEXT
        }
</code>```

Update

And this is how I call it.

```<code>using (SQLiteConnection c = new SQLiteConnection(connection))
{
    c.Open();
    using (SQLiteCommand cmd = new SQLiteCommand(sqlCommand, c))
    {
        using (SQLiteDataReader reader = cmd.ExecuteReader())
        {
            if (reader.Read())
            {
                objectFromBD = new MyObject(reader);
            }
        }
    }
}

</code>```

And the SQLite code

```<code>CREATE TABLE "table"(
    "id" INTEGER,
    "important_value_1" REAL NOT NULL,
    "important_value_2" REAL NOT NULL,
    "note" TEXT NOT NULL,

    PRIMARY KEY ("id" AUTOINCREMENT)
);
</code>```

Thank you for your help!

答:
Here is a temporary solution I got, but that is not efficient.

I saw that I can read a string with the reader, but I couldn't do it with a double. So I used reader.GetString(rowValue); and than I converted the string to a double using the fonction below.

```<code>public double StringToDoubleWithNotation(string value)
{
    return Convert.ToDouble(Decimal.Parse(value, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint));
}
</code>```

Now everything is fine, but I would prefer to see a better solution since doing 3 conversion is not that efficient.

Body:
I got a problem where I can't read the data from my database correctly.

To give you an example, I got the important value that is in the database 6.69879289850025E-06, but I read 6.0 (which is not accurate since it's suppose to be way smaller) in the C# program.

Something similar happen to ImportantValue2 where the value that is in the database is -0,000158976621370616 and in my C# program I get 0,0.

 public double ImportantValue1 { get; set; }
 public double ImportantValue2 { get; set; }
 public string Note { get; set; }

public MyObject(SQLiteDataReader reader)
        {
            ImportantValue1 = Convert.ToDouble(reader["important_value_1"]); //Value in the database is REAL
            ImportantValue2 = Convert.ToDouble(reader["important_value_2"]);//Value in the database is REAL
            Note = reader["note"].ToString(); //Value in the database is TEXT
        }

Update

And this is how I call it.

using (SQLiteConnection c = new SQLiteConnection(connection))
{
    c.Open();
    using (SQLiteCommand cmd = new SQLiteCommand(sqlCommand, c))
    {
        using (SQLiteDataReader reader = cmd.ExecuteReader())
        {
            if (reader.Read())
            {
                objectFromBD = new MyObject(reader);
            }
        }
    }
}

And the SQLite code

CREATE TABLE "table"(
    "id" INTEGER,
    "important_value_1" REAL NOT NULL,
    "important_value_2" REAL NOT NULL,
    "note" TEXT NOT NULL,

    PRIMARY KEY ("id" AUTOINCREMENT)
);

Thank you for your help!

Body:
Here is a temporary solution I got, but that is not efficient.

I saw that I can read a string with the reader, but I couldn't do it with a double. So I used reader.GetString(rowValue); and than I converted the string to a double using the fonction below.

public double StringToDoubleWithNotation(string value)
{
    return Convert.ToDouble(Decimal.Parse(value, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint));
}

Now everything is fine, but I would prefer to see a better solution since doing 3 conversion is not that efficient.


问:
Loop happens when trying to add string to a filename via AppleScript
I am trying to write an AppleScript that can add the current time to a folder's name.

```<code>on adding folder items to this_folder after receiving these_items
    repeat with this_item in these_items
        tell application "Finder"
            set t to (time string of (current date))
            set name of this_item to (t & " " & (name of this_item))
        end tell
    end repeat
end adding folder items to
</code>```

I have added the script as a Folder Action for a specific folder so it will automatically rename every folder that is being put into it. But when I add a folder to the one with the script as a Folder Action the time is being added repeatedly until the folder's name is too long to add more characters to it. How can I make it so the time is only being added once?

Thank you in advance!

答:
The problem is that every time the folder gets renamed, it triggers the Folder Actions to kick in again.  My solution would be to disable the Folder Actions when items get added to the trigger folder, then after the folders get renamed... re-enable folder actions.  This way the already re-named folders don't re-trigger the Folder Action to rename the already re-named folders.

This following AppleScript works for me.

```<code>on adding folder items to this_folder after receiving these_items
    set t to (time string of (current date))
    tell application "System Events"
        set folder actions enabled to false
        repeat with this_item in these_items
            set name of this_item to (t & " " & (name of this_item))
        end repeat
        set folder actions enabled to true
    end tell
end adding folder items to
</code>```

NOTE: It's good practice to use System Events instead of Finder, anytime you can.

Body:
I am trying to write an AppleScript that can add the current time to a folder's name.

on adding folder items to this_folder after receiving these_items
    repeat with this_item in these_items
        tell application "Finder"
            set t to (time string of (current date))
            set name of this_item to (t & " " & (name of this_item))
        end tell
    end repeat
end adding folder items to

I have added the script as a Folder Action for a specific folder so it will automatically rename every folder that is being put into it. But when I add a folder to the one with the script as a Folder Action the time is being added repeatedly until the folder's name is too long to add more characters to it. How can I make it so the time is only being added once?

Thank you in advance!

Body:
The problem is that every time the folder gets renamed, it triggers the Folder Actions to kick in again.  My solution would be to disable the Folder Actions when items get added to the trigger folder, then after the folders get renamed... re-enable folder actions.  This way the already re-named folders don't re-trigger the Folder Action to rename the already re-named folders.

This following AppleScript works for me.

on adding folder items to this_folder after receiving these_items
    set t to (time string of (current date))
    tell application "System Events"
        set folder actions enabled to false
        repeat with this_item in these_items
            set name of this_item to (t & " " & (name of this_item))
        end repeat
        set folder actions enabled to true
    end tell
end adding folder items to

NOTE: It's good practice to use System Events instead of Finder, anytime you can.


问:
Sort dict by multiple keys and with int and None data in python
so I have a dict :

```<code>marker_dict[experiment_id] = {'SM0012AQ': { 'chromosome' : 1, 'linkageGroup':8, 'positionCm' : 45,'qualityStatus' : 'A' },
 'SM0075AQ': { 'chromosome' : 1, 'linkageGroup': 7, 'positionCm' : ,'qualityStatus' : 'A' },
'SM0078BQ': { 'chromosome' : 3, 'linkageGroup': 78, 'positionCm' : 7,'qualityStatus' : 'B' },
'SM0079PQ': { 'chromosome' : 4, 'linkageGroup': , 'positionCm' : 80,'qualityStatus' : 'B' },
'SM0080BQ': { 'chromosome' : , 'linkageGroup': 78, 'positionCm' : 447,'qualityStatus' : 'T' }}
</code>```

I want to sort my dict on 'i.chromosome', 'i.linkageGroup' and 'i.positionCm'

What I am doing :

```<code>marker_list = sorted(marker_dict[experiment_id].values(), key=lambda i: (i.chromosome, i.linkageGroup, i.positionCm))
</code>```

And i got :

```<code>TypeError: '<' not supported between instances of 'Nonetype' and 'int'
</code>```

In python 2, they were doing :

```<code>markerList=sorted(markerDic.values(), key=operator.attrgetter('chromosome','linkageGroup','positionCm'))
</code>```

Could you help me please, I am lost !

答:
If all your values are greater than zero, you could use your original approach with or 0 to convert None values to zeroes and get then first in the sort order:

```<code>sorted(marker_dict[experiment_id].values(),
       key=lambda i: (i.chromosome or 0, i.linkageGroup or 0, i.positionCm or 0))
</code>```

Other wise you could write a small function to handle None values by converting the numbers to a tuple that prefixes the value with True/False depending on it not being None.

```<code>def None1st(*numbers): return [(n is not None,n or 0) for n in numbers]

sorted(marker_dict[experiment_id].values(),
       key=lambda i: None1st(i.chromosome, i.linkageGroup, i.positionCm))
</code>```

Body:
so I have a dict :

marker_dict[experiment_id] = {'SM0012AQ': { 'chromosome' : 1, 'linkageGroup':8, 'positionCm' : 45,'qualityStatus' : 'A' },
 'SM0075AQ': { 'chromosome' : 1, 'linkageGroup': 7, 'positionCm' : ,'qualityStatus' : 'A' },
'SM0078BQ': { 'chromosome' : 3, 'linkageGroup': 78, 'positionCm' : 7,'qualityStatus' : 'B' },
'SM0079PQ': { 'chromosome' : 4, 'linkageGroup': , 'positionCm' : 80,'qualityStatus' : 'B' },
'SM0080BQ': { 'chromosome' : , 'linkageGroup': 78, 'positionCm' : 447,'qualityStatus' : 'T' }}

I want to sort my dict on 'i.chromosome', 'i.linkageGroup' and 'i.positionCm'

What I am doing :

marker_list = sorted(marker_dict[experiment_id].values(), key=lambda i: (i.chromosome, i.linkageGroup, i.positionCm))

And i got :

TypeError: '<' not supported between instances of 'Nonetype' and 'int'

In python 2, they were doing :

markerList=sorted(markerDic.values(), key=operator.attrgetter('chromosome','linkageGroup','positionCm'))

Could you help me please, I am lost !

Body:
If all your values are greater than zero, you could use your original approach with or 0 to convert None values to zeroes and get then first in the sort order:

sorted(marker_dict[experiment_id].values(),
       key=lambda i: (i.chromosome or 0, i.linkageGroup or 0, i.positionCm or 0))

Other wise you could write a small function to handle None values by converting the numbers to a tuple that prefixes the value with True/False depending on it not being None.

def None1st(*numbers): return [(n is not None,n or 0) for n in numbers]

sorted(marker_dict[experiment_id].values(),
       key=lambda i: None1st(i.chromosome, i.linkageGroup, i.positionCm))


问:
Eclipse shortcut to automatically declare the class and variable from method return type
Does anybody know of a short cut in Eclipse that will put in the class and variable based on a method return type?

For e.g.

```<code>SomeClass{
  public AnotherClass getAnotherClass(){
  }
}

MainClass{
  someClassObj.getAnotherClass();// Short cut here to insert "AnotherClass anotherClass ="
}
</code>```

答:
I don't think there is one, considering:

it is generally considered "bad practice" to call a method returning a value without assigning this value to a variable.

And if you assign it, you have your AnotherClass anotherClass[=...] set in the code directly ;)

Even if you don't assign to a return value, you can move your mouse over the method to get its definition (including the return type).

Body:
Does anybody know of a short cut in Eclipse that will put in the class and variable based on a method return type?

For e.g.

SomeClass{
  public AnotherClass getAnotherClass(){
  }
}

MainClass{
  someClassObj.getAnotherClass();// Short cut here to insert "AnotherClass anotherClass ="
}


问:
Kotlin sealed class when expression not working in compose
I have following code:

```<code>sealed class ChooseCarState {
 data class ShowCarsState(val car: Int) : ChooseCarState()
 object ShowLoadingState : ChooseCarState()
 data class ShowError(val message: String) : ChooseCarState()
}
</code>```

when observe this sealed class from ViewModel in composable function:

```<code>@Composable
fun showCars(){
val state = viewModel.chooseCarState.collectAsState()
when(state.value){
    is ChooseCarState.ShowCarsState->{
        val car = (state.value as ChooseCarState.ShowCarsState).car
    }
    is ChooseCarState.ShowLoadingState->{

    }
    is ChooseCarState.ShowError ->{
        val message  = (state.value as ChooseCarState.ShowError).message
    }
  }
}
</code>```

I got ClassCastException, in spite of the fact that I am casting in is statement.

What could be a problem?

答:
The problem is that from the compiler's point of view, there is no guarantee that state.value will always return the same value, since it is not a final field.
You can solve this by assigning state.value to a variable which <s>you can then safely cast.</s> is then available for smart casts.

```<code>@Composable
fun showCars(){
val state = viewModel.chooseCarState.collectAsState()
when(val currentState = state.value){
    is ChooseCarState.ShowCarsState->{
        val car = currentState.car
    }
    is ChooseCarState.ShowLoadingState->{

    }
    is ChooseCarState.ShowError ->{
        val message  = currentState.message
    }
  }
}
</code>```

Body:
I have following code:

sealed class ChooseCarState {
 data class ShowCarsState(val car: Int) : ChooseCarState()
 object ShowLoadingState : ChooseCarState()
 data class ShowError(val message: String) : ChooseCarState()
}

when observe this sealed class from ViewModel in composable function:

@Composable
fun showCars(){
val state = viewModel.chooseCarState.collectAsState()
when(state.value){
    is ChooseCarState.ShowCarsState->{
        val car = (state.value as ChooseCarState.ShowCarsState).car
    }
    is ChooseCarState.ShowLoadingState->{

    }
    is ChooseCarState.ShowError ->{
        val message  = (state.value as ChooseCarState.ShowError).message
    }
  }
}

I got ClassCastException, in spite of the fact that I am casting in is statement.

What could be a problem?

Body:
The problem is that from the compiler's point of view, there is no guarantee that state.value will always return the same value, since it is not a final field.
You can solve this by assigning state.value to a variable which <s>you can then safely cast.</s> is then available for smart casts.

@Composable
fun showCars(){
val state = viewModel.chooseCarState.collectAsState()
when(val currentState = state.value){
    is ChooseCarState.ShowCarsState->{
        val car = currentState.car
    }
    is ChooseCarState.ShowLoadingState->{

    }
    is ChooseCarState.ShowError ->{
        val message  = currentState.message
    }
  }
}


问:
Python - How to access elements in a list of lists to get empty values
I'm reading in a csv file and need to parse it. I want to have a validation check that makes sure no cell/value in the file has any empty values. My problem is that I don't know how to check each element in a list in a list of lists

In essence, I have a sample file with headers STATE, COST, and ID

```<code>VA,2000,1
CA,1
NY,3784,1
</code>```

When parsing, I want a check that would throw an error on the second line since it's missing a value for the COST field.

Here is my code on how i'm approaching it:

```<code>with open('<hidden path url>', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    all_values = [line for line in csv_reader]
    headers = all_values[0]
    allocations = all_values[1:]

# Check for empty values
    if any(line == (None or '') for line in all_values):
        print("No column value can be empty")
    else:
        print("Success!")
</code>```

This is the result of print(all_values), aka the list of lists from which i'm trying to check each element for

```<code>[['state', 'cost', 'id'], ['VA', '2000' , '1'], ['CA', '', '1'], ['NY', '3784' , '1']]
</code>```

Going through the check should print "No column values can be empty" since there is an empty value in the row ['CA', '', '1']. I also don't want to define any extra function for the check.

Any help would be greatly appreciated!

答:
I was able to fix my problem! I created one big list that held all the elements in my list of lists and checked from there if any value was None or "".</p>
```<code>    flat_1 = [x for l in allocations for x in l] #flatten/unpack list of lists

    if any(e == None or e == '' for e in flat_1):
        print("No column values can be empty")
    else:
        print("No empty values")
</code>```

Body:
I'm reading in a csv file and need to parse it. I want to have a validation check that makes sure no cell/value in the file has any empty values. My problem is that I don't know how to check each element in a list in a list of lists

In essence, I have a sample file with headers STATE, COST, and ID

VA,2000,1
CA,1
NY,3784,1

When parsing, I want a check that would throw an error on the second line since it's missing a value for the COST field.

Here is my code on how i'm approaching it:

with open('<hidden path url>', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    all_values = [line for line in csv_reader]
    headers = all_values[0]
    allocations = all_values[1:]

# Check for empty values
    if any(line == (None or '') for line in all_values):
        print("No column value can be empty")
    else:
        print("Success!")

This is the result of print(all_values), aka the list of lists from which i'm trying to check each element for

[['state', 'cost', 'id'], ['VA', '2000' , '1'], ['CA', '', '1'], ['NY', '3784' , '1']]

Going through the check should print "No column values can be empty" since there is an empty value in the row ['CA', '', '1']. I also don't want to define any extra function for the check.

Any help would be greatly appreciated!

Body:
I was able to fix my problem! I created one big list that held all the elements in my list of lists and checked from there if any value was None or "".

    flat_1 = [x for l in allocations for x in l] #flatten/unpack list of lists

    if any(e == None or e == '' for e in flat_1):
        print("No column values can be empty")
    else:
        print("No empty values")


问:
Slideshow effect with Framer Motion
When some prop in my component changes in framer motion, I would like to fade that property out, then fade the "new" property value in?

Here's the timeline of the animation as I imagine it:

0: Prop Value Changes, old value start to fade out

.5: New value visible

1: New value finishes fading in

But the only way I see to do this with framer is to use Timeouts. Is there some way other than using timeouts to achieve this effect?

Codesandbox

import { motion } from "framer-motion";
import { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const [seconds, setSeconds] = useState(0);
  const [anim, setAnim] = useState("in");
  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds((seconds) => seconds + 1);
      setAnim("in");
      setTimeout(() => {
        setAnim("out");
      }, 500);
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  const variants = {
    out: {
      opacity: 0
    },
    in: {
      opacity: 1,
      transition: {
        duration: 0.5
      }
    }
  };

  return (
    <motion.div
      animate={anim}
      variants={variants}
      className="App"
      style={{ fontSize: 100 }}
    >
      {seconds}
    </motion.div>
  );
}

```

答:
You can do this with AnimatePresence.

Wrap your motion.div with an AnimatePresence tag, and use the seconds as a unique key for your div. The changing key will trigger AnimatePresence to animate the div in and out each time it changes (because new key means it's a different element).

To get this to work, you'll need to define your animations on the initial, animate, and exit props.

You'll also want to be sure to set the exitBeforeEnter prop on AnimatePresence so the fade out animation completes before the fade in starts.

Sandbox Example

```<code>export default function App() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds((seconds) => seconds + 1);
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  return (
    <AnimatePresence exitBeforeEnter>
      <motion.div
        initial={{opacity:0}}
        animate = {{opacity: 1, transition:{duration: 0.5}}}
        exit={{opacity: 0 }}

        className="App"
        style={{ fontSize: 100 }}
        key={seconds}
      >
        {seconds}
      </motion.div>
    </AnimatePresence>
  );
}
</code>```

Title: Slideshow effect with Framer Motion

Body:
You can do this with AnimatePresence.

Wrap your motion.div with an AnimatePresence tag, and use the seconds as a unique key for your div. The changing key will trigger AnimatePresence to animate the div in and out each time it changes (because new key means it's a different element).

To get this to work, you'll need to define your animations on the initial, animate, and exit props.

You'll also want to be sure to set the exitBeforeEnter prop on AnimatePresence so the fade out animation completes before the fade in starts.

Sandbox Example

export default function App() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds((seconds) => seconds + 1);
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  return (
    <AnimatePresence exitBeforeEnter>
      <motion.div
        initial={{opacity:0}}
        animate = {{opacity: 1, transition:{duration: 0.5}}}
        exit={{opacity: 0 }}

        className="App"
        style={{ fontSize: 100 }}
        key={seconds}
      >
        {seconds}
      </motion.div>
    </AnimatePresence>
  );
}


问:
How can I concatenate two JSON files to produce a single JSON result?
I am getting two results, one which is in form of json and the other just as text from different sources. I need to append the results together, I have tried some methods but seems I am not getting it right.

Here is my first code and the json result attached below

```<code>const posts = fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(json => console.log(json.slice(0, 2)))
</code>```

Here is the json result

```<code>[
  {
    userId: 1,
    id: 1,
    title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
    body: 'quia et suscipit\n' +
      'suscipit recusandae consequuntur expedita et cum\n' +
      'reprehenderit molestiae ut ut quas totam\n' +
      'nostrum rerum est autem sunt rem eveniet architecto'
  },
  {
    userId: 1,
    id: 2,
    title: 'qui est esse',
    body: 'est rerum tempore vitae\n' +
      'sequi sint nihil reprehenderit dolor beatae ea dolores neque\n' +
      'fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\n' +
      'qui aperiam non debitis possimus qui neque nisi nulla'
  }
]
</code>```

Here is the second code and the json result attached below

```<code>function generateNames(){
  for (let i = 0; i < 2; i++) {
    const playersName = fetch('https://www.balldontlie.io/api/v1/players?per_page=5')
      .then(response => response.json())
      .then(json => console.log(json['data'][i]['first_name']))
  }
}
generateNames()
</code>```

Here is the result

```<code>Ike
Ron
</code>```

What I am trying to achieve is something of this format

```<code>[
  {
    first_name: 'Ike',
    userId: 1,
    id: 1,
    title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
    body: 'quia et suscipit\n' +
      'suscipit recusandae consequuntur expedita et cum\n' +
      'reprehenderit molestiae ut ut quas totam\n' +
      'nostrum rerum est autem sunt rem eveniet architecto'
  },
  {
    first_name: 'Ron',
    id: 2,
    title: 'qui est esse',
    body: 'est rerum tempore vitae\n' +
      'sequi sint nihil reprehenderit dolor beatae ea dolores neque\n' +
      'fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\n' +
      'qui aperiam non debitis possimus qui neque nisi nulla'
  }
]
</code>```

答:
You will need to ensure that the data are combined once both sets of data have been fetched. Drawing on this answer you can do that like this:</p>
```<code>const fetchJson = url => fetch(url).then(r => r.json());
const [allPosts, allNames] = await Promise.all([fetchJson("https://jsonplaceholder.typicode.com/posts"), fetchJson("https://www.balldontlie.io/api/v1/players?per_page=5")]);
const combined = allPosts.slice(0, 2).map((post, index) => ({firstName: allNames.data[index].first_name, ...post}))
</code>```

Body:
I am getting two results, one which is in form of json and the other just as text from different sources. I need to append the results together, I have tried some methods but seems I am not getting it right.

Here is my first code and the json result attached below

const posts = fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(json => console.log(json.slice(0, 2)))

Here is the json result

[
  {
    userId: 1,
    id: 1,
    title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
    body: 'quia et suscipit\n' +
      'suscipit recusandae consequuntur expedita et cum\n' +
      'reprehenderit molestiae ut ut quas totam\n' +
      'nostrum rerum est autem sunt rem eveniet architecto'
  },
  {
    userId: 1,
    id: 2,
    title: 'qui est esse',
    body: 'est rerum tempore vitae\n' +
      'sequi sint nihil reprehenderit dolor beatae ea dolores neque\n' +
      'fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\n' +
      'qui aperiam non debitis possimus qui neque nisi nulla'
  }
]

Here is the second code and the json result attached below

function generateNames(){
  for (let i = 0; i < 2; i++) {
    const playersName = fetch('https://www.balldontlie.io/api/v1/players?per_page=5')
      .then(response => response.json())
      .then(json => console.log(json['data'][i]['first_name']))
  }
}
generateNames()

Here is the result

Ike
Ron

What I am trying to achieve is something of this format

[
  {
    first_name: 'Ike',
    userId: 1,
    id: 1,
    title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
    body: 'quia et suscipit\n' +
      'suscipit recusandae consequuntur expedita et cum\n' +
      'reprehenderit molestiae ut ut quas totam\n' +
      'nostrum rerum est autem sunt rem eveniet architecto'
  },
  {
    first_name: 'Ron',
    id: 2,
    title: 'qui est esse',
    body: 'est rerum tempore vitae\n' +
      'sequi sint nihil reprehenderit dolor beatae ea dolores neque\n' +
      'fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\n' +
      'qui aperiam non debitis possimus qui neque nisi nulla'
  }
]

Body:
You will need to ensure that the data are combined once both sets of data have been fetched. Drawing on this answer you can do that like this:

const fetchJson = url => fetch(url).then(r => r.json());
const [allPosts, allNames] = await Promise.all([fetchJson("https://jsonplaceholder.typicode.com/posts"), fetchJson("https://www.balldontlie.io/api/v1/players?per_page=5")]);
const combined = allPosts.slice(0, 2).map((post, index) => ({firstName: allNames.data[index].first_name, ...post}))


问:
add a constraint to ipywidgets.datepicker, only allow value between two dates
I'm using the DatePicker widget from ipywidgets. I was wondering if I could set some constraints for the day the user picks. Would it be possible to limit the user to only pick a day between datetime.date(2020, 2, 10) and datetime.date(2020, 2, 16)?

Currently my code looks like this:

```<code>dp = widgets.DatePicker(
    description='Pick a Date',
    disabled=False
)
</code>```

Many thanks in advance

答:
I had the same requirement. Didn't find anything in the official documentation, but I have found a hack using javascript to set the min and max tags on the generated html input box that works:

%matplotlib widget

import ipywidgets as widgets
from IPython.display import display, Javascript

date_picker = widgets.DatePicker(
    description='Pick a Date',
    disabled=False,
)
date_picker.add_class("start-date")

script = Javascript("\
                const query = '.start-date > input:first-of-type'; \
                document.querySelector(query).setAttribute('min', '2020-12-01'); \
                document.querySelector(query).setAttribute('max', '2021-01-01'); \
        ")

display(date_picker)
display(script)
```

Body:
I'm using the DatePicker widget from ipywidgets. I was wondering if I could set some constraints for the day the user picks. Would it be possible to limit the user to only pick a day between datetime.date(2020, 2, 10) and datetime.date(2020, 2, 16)?

Currently my code looks like this:

dp = widgets.DatePicker(
    description='Pick a Date',
    disabled=False
)

Many thanks in advance


问:
Clang matcher that hasGlobalStorage but is non-static
I was trying to compose a matcher that finds global variables that does not have static storage

This is what I have so far

```<code>varDecl(hasGlobalStorage(), isDefinition())
</code>```

Accoring to Clang AST Matcher Reference

hasGlobalStorage will also match static variables inside function bodies

I don't want to match 'y' variable

How do I do that?

答: You can use isLocalVarDecl method.</p>

Body:
I was trying to compose a matcher that finds global variables that does not have static storage

This is what I have so far

varDecl(hasGlobalStorage(), isDefinition())

Accoring to Clang AST Matcher Reference

hasGlobalStorage will also match static variables inside function bodies

I don't want to match 'y' variable

How do I do that?

Body: You can use isLocalVarDecl method.


问:
How do you prevent a re-created React component from losing state?
The example in this sandbox is a contrived example, but it illustrates the point.

Clicking the "Add column" button is supposed to add a new column. It works the first time, but doesn't work after that. You'll notice from the log that this issue has to do with the fact that columns is always in its original state. Therefore, a column is always being added to this original state, not the current state.

I imagine this issue is related to the fact that the column header is being re-created on each call to renderHeader, but I'm unsure about how to pass the state to the newly created header component.

答: I think this has to do with the way the closure for (params) => {...} captures the value of columns. At the same time, you have this strange circular thing going on: useState() returns columns and also uses columns in one of its parameters. You will need to find a way to break this circularity.


问:
Errno = 13 and how to debug this more efficiently?
I'm making an application and when i go from menu to an other activity that display image using the e3roid framework, i allways get this (logcat):

```<code>D/PhoneWindow( 1562): DebugMonitor class=com.recisio.kfandroid.gui.tab.KFFeaturedTab focus=false
E/copybit    ( 1562): Error opening frame buffer errno=13 (Permission denied)
D/PhoneWindow( 1562): DebugMonitor class=com.recisio.kfandroid.gui.player.KFPlayer focus=true
</code>```

I'm questionning myself about where does the error come?
Is there a way to know exactly where it happens?
May i have to ignore this?

Apparently, copybit is just an abstraction for a basic 2D blitter with support for rotation, scaling and color/pixelformat conversions.

But where it's strange it's that all the images loaded appears well on my screen.

Ok: I tried to change the way i was encoding the bmp I print like this:

```<code>return Bitmap.createBitmap(bitmap_width, bitmap_height, Bitmap.Config.RGB_565);
</code>```

but it doesn't solve the problem.

By printing several display infos everywhere in my code i realised that the error happens while loading the e3roid engine.

I'm going to look at the sources while waiting for more answers.

After some tests with printing a bmp i create before (valid), I get this

```<code>E/copybit ( 3274): Error opening frame buffer errno=13 (Permission denied)
D/dalvikvm( 3274): GC freed 3337 objects / 132024 bytes in 150ms
I/DEBUG   ( 1145): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
I/DEBUG   ( 1145): Build fingerprint: 'vodafone_fr/htc_buzz/buzz/buzz:2.1-update1/ERE27/183733:user/release-keys'
I/DEBUG   ( 1145): pid: 3274, tid: 3519  >>> com.recisio.kfandroid <<<
I/DEBUG   ( 1145): signal 11 (SIGSEGV), fault addr 00000000
I/DEBUG   ( 1145):  r0 46c62008  r1 00000000  r2 00100000  r3 00000018
I/DEBUG   ( 1145):  r4 4685fd10  r5 00000002  r6 46c62008  r7 0000000c
I/DEBUG   ( 1145):  r8 00000000  r9 4191fd20  10 00000de1  fp 002e4428
I/DEBUG   ( 1145):  ip 80000000  sp 4685fc98  lr acc9697b  pc afe0e060  cpsr a0000010
I/DEBUG   ( 1145):          #00  pc 0000e060  /system/lib/libc.so
I/DEBUG   ( 1145):          #01  pc 00016978  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145):          #02  pc 00016d5a  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145):          #03  pc 0002886c  /system/lib/libandroid_runtime.so
I/DEBUG   ( 1145):          #04  pc 0000f3f4  /system/lib/libdvm.so
I/DEBUG   ( 1145):
I/DEBUG   ( 1145): code around pc:
I/DEBUG   ( 1145): afe0e050 0a00000a e1530002 8202301c e1b0ce03
I/DEBUG   ( 1145): afe0e060 28b100f0 48b10300 28a000f0 48a00300
I/DEBUG   ( 1145): afe0e070 e3130004 1491a004 1480a004 e0422003
I/DEBUG   ( 1145):
I/DEBUG   ( 1145): code around lr:
I/DEBUG   ( 1145): acc96968 5c39008f 434b6936 435a1c30 f7ed6921
I/DEBUG   ( 1145): acc96978 e020e91a fef4f7ff 28001c05 480fd101
I/DEBUG   ( 1145): acc96988 69c2e01a 47901c31 1c2169ab 47981c28
I/DEBUG   ( 1145):
I/DEBUG   ( 1145): stack:
I/DEBUG   ( 1145):     4685fc58  001615b8  [heap]
I/DEBUG   ( 1145):     4685fc5c  00000800
I/DEBUG   ( 1145):     4685fc60  00000000
I/DEBUG   ( 1145):     4685fc64  acc97fdb  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145):     4685fc68  00301418  [heap]
I/DEBUG   ( 1145):     4685fc6c  acc9604d  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145):     4685fc70  00010002  [heap]
I/DEBUG   ( 1145):     4685fc74  00100000  [heap]
I/DEBUG   ( 1145):     4685fc78  00000200
I/DEBUG   ( 1145):     4685fc7c  00000200
I/DEBUG   ( 1145):     4685fc80  001615b8  [heap]
I/DEBUG   ( 1145):     4685fc84  acc95f3d  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145):     4685fc88  afe38e08  /system/lib/libc.so
I/DEBUG   ( 1145):     4685fc8c  afe0eed4  /system/lib/libc.so
I/DEBUG   ( 1145):     4685fc90  df002777
I/DEBUG   ( 1145):     4685fc94  e3a070ad
I/DEBUG   ( 1145): #00 4685fc98  00000002
I/DEBUG   ( 1145):     4685fc9c  46c62008
I/DEBUG   ( 1145):     4685fca0  0000000c
I/DEBUG   ( 1145):     4685fca4  00000000
I/DEBUG   ( 1145):     4685fca8  4191fd20
I/DEBUG   ( 1145):     4685fcac  00000de1
I/DEBUG   ( 1145):     4685fcb0  002e4428  [heap]
I/DEBUG   ( 1145):     4685fcb4  46c62008
I/DEBUG   ( 1145):     4685fcb8  4685fd10
I/DEBUG   ( 1145):     4685fcbc  acc9697b  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145): #01 4685fcc0  4106788c  /dev/ashmem/dalvik-LinearAlloc (deleted)
I/DEBUG   ( 1145):     4685fcc4  002e4428  [heap]
I/DEBUG   ( 1145):     4685fcc8  ad053c19  /system/lib/libdvm.so
I/DEBUG   ( 1145):     4685fccc  00000000
I/DEBUG   ( 1145):     4685fcd0  ad080f8c  /system/lib/libdvm.so
I/DEBUG   ( 1145):     4685fcd4  00300ea0  [heap]
I/DEBUG   ( 1145):     4685fcd8  00000200
I/DEBUG   ( 1145):     4685fcdc  001615cc  [heap]
I/DEBUG   ( 1145):     4685fce0  00000001
I/DEBUG   ( 1145):     4685fce4  acc96d5f  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145): debuggerd committing suicide to free the zombie!
I/DEBUG   ( 3535): debuggerd: May 28 2010 02:08:39
</code>```

What is this?

答: This can happen if you are using a not supported texture format. Try using a RGB565. Here you can find some info about the issue: http://code.google.com/p/processing/issues/detail?id=391</p>

Body:
I'm making an application and when i go from menu to an other activity that display image using the e3roid framework, i allways get this (logcat):

D/PhoneWindow( 1562): DebugMonitor class=com.recisio.kfandroid.gui.tab.KFFeaturedTab focus=false
E/copybit    ( 1562): Error opening frame buffer errno=13 (Permission denied)
D/PhoneWindow( 1562): DebugMonitor class=com.recisio.kfandroid.gui.player.KFPlayer focus=true

I'm questionning myself about where does the error come?
Is there a way to know exactly where it happens?
May i have to ignore this?

Apparently, copybit is just an abstraction for a basic 2D blitter with support for rotation, scaling and color/pixelformat conversions.

But where it's strange it's that all the images loaded appears well on my screen.

Ok: I tried to change the way i was encoding the bmp I print like this:

return Bitmap.createBitmap(bitmap_width, bitmap_height, Bitmap.Config.RGB_565);

but it doesn't solve the problem.

By printing several display infos everywhere in my code i realised that the error happens while loading the e3roid engine.

I'm going to look at the sources while waiting for more answers.

After some tests with printing a bmp i create before (valid), I get this

E/copybit ( 3274): Error opening frame buffer errno=13 (Permission denied)
D/dalvikvm( 3274): GC freed 3337 objects / 132024 bytes in 150ms
I/DEBUG   ( 1145): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
I/DEBUG   ( 1145): Build fingerprint: 'vodafone_fr/htc_buzz/buzz/buzz:2.1-update1/ERE27/183733:user/release-keys'
I/DEBUG   ( 1145): pid: 3274, tid: 3519  >>> com.recisio.kfandroid <<<
I/DEBUG   ( 1145): signal 11 (SIGSEGV), fault addr 00000000
I/DEBUG   ( 1145):  r0 46c62008  r1 00000000  r2 00100000  r3 00000018
I/DEBUG   ( 1145):  r4 4685fd10  r5 00000002  r6 46c62008  r7 0000000c
I/DEBUG   ( 1145):  r8 00000000  r9 4191fd20  10 00000de1  fp 002e4428
I/DEBUG   ( 1145):  ip 80000000  sp 4685fc98  lr acc9697b  pc afe0e060  cpsr a0000010
I/DEBUG   ( 1145):          #00  pc 0000e060  /system/lib/libc.so
I/DEBUG   ( 1145):          #01  pc 00016978  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145):          #02  pc 00016d5a  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145):          #03  pc 0002886c  /system/lib/libandroid_runtime.so
I/DEBUG   ( 1145):          #04  pc 0000f3f4  /system/lib/libdvm.so
I/DEBUG   ( 1145):
I/DEBUG   ( 1145): code around pc:
I/DEBUG   ( 1145): afe0e050 0a00000a e1530002 8202301c e1b0ce03
I/DEBUG   ( 1145): afe0e060 28b100f0 48b10300 28a000f0 48a00300
I/DEBUG   ( 1145): afe0e070 e3130004 1491a004 1480a004 e0422003
I/DEBUG   ( 1145):
I/DEBUG   ( 1145): code around lr:
I/DEBUG   ( 1145): acc96968 5c39008f 434b6936 435a1c30 f7ed6921
I/DEBUG   ( 1145): acc96978 e020e91a fef4f7ff 28001c05 480fd101
I/DEBUG   ( 1145): acc96988 69c2e01a 47901c31 1c2169ab 47981c28
I/DEBUG   ( 1145):
I/DEBUG   ( 1145): stack:
I/DEBUG   ( 1145):     4685fc58  001615b8  [heap]
I/DEBUG   ( 1145):     4685fc5c  00000800
I/DEBUG   ( 1145):     4685fc60  00000000
I/DEBUG   ( 1145):     4685fc64  acc97fdb  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145):     4685fc68  00301418  [heap]
I/DEBUG   ( 1145):     4685fc6c  acc9604d  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145):     4685fc70  00010002  [heap]
I/DEBUG   ( 1145):     4685fc74  00100000  [heap]
I/DEBUG   ( 1145):     4685fc78  00000200
I/DEBUG   ( 1145):     4685fc7c  00000200
I/DEBUG   ( 1145):     4685fc80  001615b8  [heap]
I/DEBUG   ( 1145):     4685fc84  acc95f3d  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145):     4685fc88  afe38e08  /system/lib/libc.so
I/DEBUG   ( 1145):     4685fc8c  afe0eed4  /system/lib/libc.so
I/DEBUG   ( 1145):     4685fc90  df002777
I/DEBUG   ( 1145):     4685fc94  e3a070ad
I/DEBUG   ( 1145): #00 4685fc98  00000002
I/DEBUG   ( 1145):     4685fc9c  46c62008
I/DEBUG   ( 1145):     4685fca0  0000000c
I/DEBUG   ( 1145):     4685fca4  00000000
I/DEBUG   ( 1145):     4685fca8  4191fd20
I/DEBUG   ( 1145):     4685fcac  00000de1
I/DEBUG   ( 1145):     4685fcb0  002e4428  [heap]
I/DEBUG   ( 1145):     4685fcb4  46c62008
I/DEBUG   ( 1145):     4685fcb8  4685fd10
I/DEBUG   ( 1145):     4685fcbc  acc9697b  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145): #01 4685fcc0  4106788c  /dev/ashmem/dalvik-LinearAlloc (deleted)
I/DEBUG   ( 1145):     4685fcc4  002e4428  [heap]
I/DEBUG   ( 1145):     4685fcc8  ad053c19  /system/lib/libdvm.so
I/DEBUG   ( 1145):     4685fccc  00000000
I/DEBUG   ( 1145):     4685fcd0  ad080f8c  /system/lib/libdvm.so
I/DEBUG   ( 1145):     4685fcd4  00300ea0  [heap]
I/DEBUG   ( 1145):     4685fcd8  00000200
I/DEBUG   ( 1145):     4685fcdc  001615cc  [heap]
I/DEBUG   ( 1145):     4685fce0  00000001
I/DEBUG   ( 1145):     4685fce4  acc96d5f  /system/lib/egl/libGLES_android.so
I/DEBUG   ( 1145): debuggerd committing suicide to free the zombie!
I/DEBUG   ( 3535): debuggerd: May 28 2010 02:08:39

What is this?


答:
You can use the String.join() method.

```<code>System.out.println(String.join(",", listaOfQueues.get(i))+"\n");
</code>```

In fact you can use String.join() on any class that implements the Iterable interface.

Title: Print arraylist of queues separated by commas

Body:
I want to print the values of an arraylist that's filled with queues, but i want to do it separated by a comma.

This is what i'm doing to print the list:

for(int i=1;i<listaOfQueues.size();i++){
      System.out.println(listaOfQueues.get(i).toString()+"\n");
    }

This is my current output:

242424242424242525252525252526262626262626

272727272727272828282828282829292929292929

303030303030303131313131313132323232323232

333333333333333434343434343435353535353535

363636363636363737373737373738383838383838

393939393939394040404040404041414141414141

My desired output:

24,24,24,24,24,24,24,25,25,25,25,25,25,25,26,26,26,26,26,26,26

27,27,27,27,27,27,27,28,28,28,28,28,28,28,29,29,29,29,29,29,29

30,30,30,30,30,30,30,31,31,31,31,31,31,31,32,32,32,32,32,32,32

33,33,33,33,33,33,33,34,34,34,34,34,34,34,35,35,35,35,35,35,35

36,36,36,36,36,36,36,37,37,37,37,37,37,37,38,38,38,38,38,38,38

39,39,39,39,39,39,39,40,40,40,40,40,40,40,41,41,41,41,41,41,41

Any suggestions? Thanks

Body:
You can use the String.join() method.

System.out.println(String.join(",", listaOfQueues.get(i))+"\n");

In fact you can use String.join() on any class that implements the Iterable interface.


问:
No overload matches this call. React
I am using sidebar menu code and using const values to show and hide sidebar menu in website. But I am getting error for typesripting. Here is my code:

```<code>let Navigation = () => {

  const [sidebar, setSidebar] = React.useState(false);
  const showSidebar = () => setSidebar(!sidebar);
}

  return(

    <nav className="navbar-default navbar-static-side main-navigation" role="navigation">

      <div className="sidebar-collapse">
          <IconContext.Provider value={{ color: '#fff' }}>
            <Nav>
              <NavIcon to='#'>
                  <FaIcons.FaBars onClick={showSidebar} />
              </NavIcon>
            </Nav>
            <SidebarNav sidebar= {sidebar}>
              <SidebarWrap>
                <NavIcon to='#'>
                  <AiIcons.AiOutlineClose onClick={showSidebar} />
                </NavIcon>
                <NavIcon to='#'>
                    <img src={logo} width="70%" />
                </NavIcon>

              </SidebarWrap>
            </SidebarNav>
          </IconContext.Provider>
          </div>
    </nav>
  )

export default Navigation
</code>```

But I am getting error for,

```<code>No overload matches this call.
  Overload 1 of 2, '(props: Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, "slot" | "style" | "title" | "children" | ... 250 more ... | "onTransitionEndCapture"> & { ...; }, "ref" | ... 254 more ... | "onTransitionEndCapture"> & Partial<...>, "ref" | ... 254 more ... | "onTransitionEndCapture"> & { ...; } & { ...; }): ReactElement<...>', gave the following error.
    Type '{ children: Element; sidebar: boolean; }' is not assignable to type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, "slot" | ... 253 more ... | "onTransitionEndCapture"> & { ...; }, "ref" | ... 254 more ... | "onTransitionEndCapture"> & Partial<...>, "ref" | ... 254 more ... | "onTransitionEndCapture"> & { ...; } & { ...; }'.
      Property 'sidebar' does not exist on type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, "slot" | ... 253 more ... | "onTransitionEndCapture"> & { ...; }, "ref" | ... 254 more ... | "onTransitionEndCapture"> & Partial<...>, "ref" | ... 254 more ... | "onTransitionEndCapture"> & { ...; } & { ...; }'.
  Overload 2 of 2, '(props: StyledComponentPropsWithAs<"nav", any, {}, never, "nav">): ReactElement<StyledComponentPropsWithAs<"nav", any, {}, never, "nav">, string | ... 1 more ... | (new (props: any) => Component<...>)>', gave the following error.
    Type '{ children: Element; sidebar: boolean; }' is not assignable to type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, "slot" | ... 253 more ... | "onTransitionEndCapture"> & { ...; }, "ref" | ... 254 more ... | "onTransitionEndCapture"> & Partial<...>, "ref" | ... 254 more ... | "onTransitionEndCapture"> & { ...; } & { ...; }'.
      Property 'sidebar' does not exist on type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, "slot" | ... 253 more ... | "onTransitionEndCapture"> & { ...; }, "ref" | ... 254 more ... | "onTransitionEndCapture"> & Partial<...>, "ref" | ... 254 more ... | "onTransitionEndCapture"> & { ...; } & { ...; }'.  TS2769
</code>```

in line ,

```<code> <SidebarNav sidebar= {sidebar}>
</code>```

It dosn't allow me to use sidebar in tag.

答:
This error comes from a type difference between what you give to Sidebar and what Sibar is expecting.

Is your Sibar component is typed like this

```<code>interface Props {
  sidebar: boolean;
}

const Sidebar:FC<Props> = ({sidebar}: Props) => {
  ...yourCode
}
</code>```

Title: No overload matches this call. React

Body:
I am using sidebar menu code and using const values to show and hide sidebar menu in website. But I am getting error for typesripting. Here is my code:

let Navigation = () => {

  const [sidebar, setSidebar] = React.useState(false);
  const showSidebar = () => setSidebar(!sidebar);
}

  return(

          <IconContext.Provider value={{ color: '#fff' }}>

              <NavIcon to='#'>
                  <FaIcons.FaBars onClick={showSidebar} />
              </NavIcon>

            <SidebarNav sidebar= {sidebar}>
              <SidebarWrap>
                <NavIcon to='#'>
                  <AiIcons.AiOutlineClose onClick={showSidebar} />
                </NavIcon>
                <NavIcon to='#'>

                </NavIcon>

              </SidebarWrap>
            </SidebarNav>
          </IconContext.Provider>

  )

export default Navigation

But I am getting error for,

No overload matches this call.
  Overload 1 of 2, '(props: Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, "slot" | "style" | "title" | "children" | ... 250 more ... | "onTransitionEndCapture"> & { ...; }, "ref" | ... 254 more ... | "onTransitionEndCapture"> & Partial<...>, "ref" | ... 254 more ... | "onTransitionEndCapture"> & { ...; } & { ...; }): ReactElement<...>', gave the following error.
    Type '{ children: Element; sidebar: boolean; }' is not assignable to type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, "slot" | ... 253 more ... | "onTransitionEndCapture"> & { ...; }, "ref" | ... 254 more ... | "onTransitionEndCapture"> & Partial<...>, "ref" | ... 254 more ... | "onTransitionEndCapture"> & { ...; } & { ...; }'.
      Property 'sidebar' does not exist on type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, "slot" | ... 253 more ... | "onTransitionEndCapture"> & { ...; }, "ref" | ... 254 more ... | "onTransitionEndCapture"> & Partial<...>, "ref" | ... 254 more ... | "onTransitionEndCapture"> & { ...; } & { ...; }'.
  Overload 2 of 2, '(props: StyledComponentPropsWithAs<"nav", any, {}, never, "nav">): ReactElement

Body:
This error comes from a type difference between what you give to Sidebar and what Sibar is expecting.

Is your Sibar component is typed like this

interface Props {
  sidebar: boolean;
}

const Sidebar:FC<Props> = ({sidebar}: Props) => {
  ...yourCode
}


问:
The `start` argument could not be matched to a location related to the index of the data
I don't know why my 'start' pred won't work. I added some edits to pd.to_datetime but they didn't work.

This is my code:

```<code>pred = results.get_prediction(start=pd.to_datetime('2018-06-01'), dynamic=False)
pred_ci = pred.conf_int()
ax = y['2015':].plot(label='observed')
pred.predicted_mean.plot(ax=ax, label='One-step ahead Forecast', alpha=.7, figsize=(14, 4))
ax.fill_between(pred_ci.index,
                pred_ci.iloc[:, 0],
                pred_ci.iloc[:, 1], color='k', alpha=.2)
ax.set_xlabel('Date')
ax.set_ylabel('Retail_sold')
plt.legend()
plt.show()
</code>```

and the log of my error always refers to my time format, I had to resample my data before, from daily data to monthly data before I started the analysis of the data and workaround the data, but I don't know why my data can't be read using pd.todatetime.

```<code>---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 1546300800000000000

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2896             try:
-> 2897                 return self._engine.get_loc(key)
   2898             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

KeyError: Timestamp('2019-01-01 00:00:00')

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 1546300800000000000

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
11 frames
pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

KeyError: Timestamp('2019-01-01 00:00:00')

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

KeyError: Timestamp('2019-01-01 00:00:00')

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/statsmodels/tsa/base/tsa_model.py in _get_prediction_index(self, start, end, index, silent)
    522             start, start_index, start_oos = self._get_index_label_loc(start)
    523         except KeyError:
--> 524             raise KeyError('The `start` argument could not be matched to a'
    525                            ' location related to the index of the data.')
    526         if end is None:

KeyError: 'The `start` argument could not be matched to a location related to the index of the data.'
</code>```

I used Google Colab and Python 3.7.

Does anyone have the solution of my problem?

答:
you can try the following:</p>
```<code>predictions = results.predict(start=train_data.shape[0],end=(train_data.shape[0]+test_data.shape[0]-1), dynamic=False)
</code>```

Body:
I don't know why my 'start' pred won't work. I added some edits to pd.to_datetime but they didn't work.

This is my code:

pred = results.get_prediction(start=pd.to_datetime('2018-06-01'), dynamic=False)
pred_ci = pred.conf_int()
ax = y['2015':].plot(label='observed')
pred.predicted_mean.plot(ax=ax, label='One-step ahead Forecast', alpha=.7, figsize=(14, 4))
ax.fill_between(pred_ci.index,
                pred_ci.iloc[:, 0],
                pred_ci.iloc[:, 1], color='k', alpha=.2)
ax.set_xlabel('Date')
ax.set_ylabel('Retail_sold')
plt.legend()
plt.show()

and the log of my error always refers to my time format, I had to resample my data before, from daily data to monthly data before I started the analysis of the data and workaround the data, but I don't know why my data can't be read using pd.todatetime.

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 1546300800000000000

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2896             try:
-> 2897                 return self._engine.get_loc(key)
   2898             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

KeyError: Timestamp('2019-01-01 00:00:00')

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 1546300800000000000

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
11 frames
pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

KeyError: Timestamp('2019-01-01 00:00:00')

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

KeyError: Timestamp('2019-01-01 00:00:00')

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/statsmodels/tsa/base/tsa_model.py in _get_prediction_index(self, start, end, index, silent)
    522             start, start_index, start_oos = self._get_index_label_loc(start)
    523         except KeyError:
--> 524             raise KeyError('The `start` argument could not be matched to a'
    525                            ' location related to the index of the data.')
    526         if end is None:

KeyError: 'The `start` argument could not be matched to a location related to the index of the data.'

I used Google Colab and Python 3.7.

Does anyone have the solution of my problem?

Body:
you can try the following:

predictions = results.predict(start=train_data.shape[0],end=(train_data.shape[0]+test_data.shape[0]-1), dynamic=False)


问:
Unable to Debug Lambda locally in Rider
I'm using Jetbrains Rider with Mock Lambda Test Tool and for some reason I am unable to Debug my code with the tool - the Debug button in Rider is just greyed out:

Here is my Run/Debug Configuration:

And this is my launchSettings.json file:

The Mock Lambda Test Tool launches fine in the browser fine when just clicking "Run", but can't Debug in that mode.

Any help or pointers would be great

答:
my launchSettings.json seems like the following,

```<code>{
"profiles": {
"Mock Lambda Test Tool vs2022": {
  "commandName": "Executable",
  "commandLineArgs": "--port 5050",
  "workingDirectory": ".\\bin\\$(Configuration)\\netcoreapp3.1",
  "executablePath": "%USERPROFILE%\\.dotnet\\tools\\dotnet-lambda-test-tool-3.1.exe",
  "environmentVariables": {
    "TABLE_PREFIX": "dev"
  }
},
"Mock Lambda Test Tool Rider": {
  "commandName": "Executable",
  "commandLineArgs": "--port 5050",
  "workingDirectory": "$(ProjectDir)",
  "executablePath": "%USERPROFILE%\\.dotnet\\tools\\.store\\amazon.lambda.testtool-3.1\\0.11.4\\amazon.lambda.testtool-3.1\\0.11.4\\tools\\netcoreapp3.1\\any\\Amazon.Lambda.TestTool.BlazorTester.dll",
  "environmentVariables": {
    "TABLE_PREFIX": "dev"
  }
}
}
}
</code>```

And it works like a charm with Rider

Title: Unable to Debug Lambda locally in Rider

Body:
my launchSettings.json seems like the following,

{
"profiles": {
"Mock Lambda Test Tool vs2022": {
  "commandName": "Executable",
  "commandLineArgs": "--port 5050",
  "workingDirectory": ".\\bin\\$(Configuration)\\netcoreapp3.1",
  "executablePath": "%USERPROFILE%\\.dotnet\\tools\\dotnet-lambda-test-tool-3.1.exe",
  "environmentVariables": {
    "TABLE_PREFIX": "dev"
  }
},
"Mock Lambda Test Tool Rider": {
  "commandName": "Executable",
  "commandLineArgs": "--port 5050",
  "workingDirectory": "$(ProjectDir)",
  "executablePath": "%USERPROFILE%\\.dotnet\\tools\\.store\\amazon.lambda.testtool-3.1\\0.11.4\\amazon.lambda.testtool-3.1\\0.11.4\\tools\\netcoreapp3.1\\any\\Amazon.Lambda.TestTool.BlazorTester.dll",
  "environmentVariables": {
    "TABLE_PREFIX": "dev"
  }
}
}
}

And it works like a charm with Rider


问:
"Runtime error Exception has been thrown by the target of an invocation" from Script task
I have a SSIS package with a script task, I get the following error when i try to run it in my local system. It works fine for my collegues as well as in production. However, I am not able to run it locally, to test. I keep a debug point in the main method, but it is never reached, I get the error before it goes to main method.

I am using VS 2010, .Net framework 4.5.

The script task does compile. I get the following messages SSIS package "..\Test.dtsx" starting. Error: 0x1 at Test: Exception has been thrown by the target of an invocation. Task failed: Test SSIS package "..\Test.dtsx" finished: Success. The program '[2552] DtsDebugHost.exe: DTS' has exited with code 0 (0x0).

The following is the code:

```<code>public void Main()
{
try
{
 LogMessages("Update Bug package execution started at :: " + DateTime.Now.ToLongTimeString());
 LogMessages("Loading package configuration values to local variables.");

strDBConn = Dts.Variables["User::DBConnection"] != null ? Dts.Variables["User::DBConnection"].Value.ToString() : string.Empty;
strTPCUrl = Dts.Variables["User::TPCUrl"] != null ? Dts.Variables["User::TPCUrl"].Value.ToString() : string.Empty;

TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl));
WorkItemStore objWIS = new WorkItemStore(objTPC);
WorkItemCollection objWIC = objWIS.Query("SELECT...");

foreach (WorkItem wi in objWIC)
{
}

}
catch(Exception ex)
{
}
</code>```

When I commented the code from TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl)); The script executes successfully. However, if i keep TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl)); and comment the rest, i get the exception.
I do have access to the URL.

I am using Microsoft.TeamFoundation.Client.dll and Microsoft.TeamFoundation.WorkItemTracking.Client.dll, in my script task. However the dll version in the package is 10.0, and the version of the dll in my GAC is 12.0. Would that cause a problem?

答:
After not having any luck with the other answers here, I finally found that in my package, the problem was that I had created a new variable but not carried its name across into my new copy of the C# script. The variables were the ones to be used as connection string expressions. So it was ultimately a matter of changing:

```<code>Dts.Variables["Exists"].Value = File.Exists(Dts.Variables["OldSSISPackageVariableName"].Value.ToString());
</code>```

to:

```<code>Dts.Variables["Exists"].Value = File.Exists(Dts.Variables["NewSSISPackageVariableName"].Value.ToString());
</code>```

Once I kept them in sync, it worked fine.

Body:
I have a SSIS package with a script task, I get the following error when i try to run it in my local system. It works fine for my collegues as well as in production. However, I am not able to run it locally, to test. I keep a debug point in the main method, but it is never reached, I get the error before it goes to main method.

I am using VS 2010, .Net framework 4.5.

The script task does compile. I get the following messages SSIS package "..\Test.dtsx" starting. Error: 0x1 at Test: Exception has been thrown by the target of an invocation. Task failed: Test SSIS package "..\Test.dtsx" finished: Success. The program '[2552] DtsDebugHost.exe: DTS' has exited with code 0 (0x0).

The following is the code:

public void Main()
{
try
{
 LogMessages("Update Bug package execution started at :: " + DateTime.Now.ToLongTimeString());
 LogMessages("Loading package configuration values to local variables.");

strDBConn = Dts.Variables["User::DBConnection"] != null ? Dts.Variables["User::DBConnection"].Value.ToString() : string.Empty;
strTPCUrl = Dts.Variables["User::TPCUrl"] != null ? Dts.Variables["User::TPCUrl"].Value.ToString() : string.Empty;

TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl));
WorkItemStore objWIS = new WorkItemStore(objTPC);
WorkItemCollection objWIC = objWIS.Query("SELECT...");

foreach (WorkItem wi in objWIC)
{
}

}
catch(Exception ex)
{
}

When I commented the code from TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl)); The script executes successfully. However, if i keep TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl)); and comment the rest, i get the exception.
I do have access to the URL.

I am using Microsoft.TeamFoundation.Client.dll and Microsoft.TeamFoundation.WorkItemTracking.Client.dll, in my script task. However the dll version in the package is 10.0, and the version of the dll in my GAC is 12.0. Would that cause a problem?

Body:
After not having any luck with the other answers here, I finally found that in my package, the problem was that I had created a new variable but not carried its name across into my new copy of the C# script. The variables were the ones to be used as connection string expressions. So it was ultimately a matter of changing:

Dts.Variables["Exists"].Value = File.Exists(Dts.Variables["OldSSISPackageVariableName"].Value.ToString());

to:

Dts.Variables["Exists"].Value = File.Exists(Dts.Variables["NewSSISPackageVariableName"].Value.ToString());

Once I kept them in sync, it worked fine.


问:
Why we need <HTML> tag in html?
I searched before but I couldn't get a logical answer.
I want to know what's the use of < HTML > tag in HTML?
Why do we use this tag and how is this useful?</p>

答:
You don't. Look at the specification. It says:

An html element's start tag can be omitted if the first thing inside the html element is not a comment.

An html element's end tag can be omitted if the html element is not immediately followed by a comment.

That said, if you don't have it, you can't put a lang attribute that applies to the whole document on it.

Title: Why we need <HTML> tag in html?

Body:
I searched before but I couldn't get a logical answer.
I want to know what's the use of  tag in HTML?
Why do we use this tag and how is this useful?


问:
Generic styled component Icon
I am styling my react component with styled-components. I want an icon component that can be used in different places just by changing size, colour props etc. I also want to pass icons names as props for different places. I am succeeded to change the size and colour but don't know how to pass the icon name as per requirement.

Here is my generic icon component:

```<code>     import React from "react";
        import { ReactSVG } from "react-svg";
        import styled, { css } from "styled-components";
        import { FaUserTie } from 'react-icons/fa';

        const StyledSVGIcon = styled(FaUserTie)`
          svg {
            fill: black;
            ${({ size }) =>
                size &&
                css`
                width: ${size};
                height: ${size};
              `}
            ${({ transform }) =>
                transform &&
                css`
                transform: ${transform};
              `}
            path {
              ${({ color }) =>
                color &&
                css`
                  fill: ${color};
                `}
            }
          }
        `;

        const GenIcon = props => {
            return (
                <StyledSVGIcon
                    src={`/icons/${props.name}.svg`}
                    color={props.color}
                    size={props.size}
                    transform={props.transform}
                />
            );
        };

    export default GenIcon;
</code>```

And I want to use it like this:

```<code> <GenIcon
          name="FaUserNurse"
          color="red"
          size="16px"
      />
</code>```

But the GenIcon component is not working. please help me where I am doing wrong. the icon could be any kind like svg or any other react icon library.

答:
Try this out, you're close:

```<code>import React from "react";
import { ReactSVG } from "react-svg";
import styled, { css } from "styled-components";
import { FaUserTie, FaDocker } from "react-icons/fa";

const IconStyler = styled.span`
 color: ${(props) => props.color};
 & svg {
  ${(props) =>
   props.small &&
    css`
     width: 14px !important;
     height: 14px !important;
   `}
 ${(props) =>
  props.med &&
  css`
    width: 20px !important;
    height: 20px !important;
  `}
 ${(props) =>
  props.large &&
  css`
    width: 28px !important;
    height: 28px !important;
  `}
 }

`;

  const Icon = ({ children, ...props }) => {
   return <IconStyler {...props}>{children}</IconStyler>;
  };

const GenIcon = () => {
  return (
   <div>
     <h5>Any Icon</h5>
      <div>
       <Icon color="blue" small>
        <FaUserTie />
       </Icon>
      </div>
      <div>
        <Icon color="orange" large>
        <FaDocker />
        </Icon>
      </div>
   </div>
  );
};

export default GenIcon;
</code>```

Here's a sandbox link: https://codesandbox.io/s/flamboyant-allen-60ho1?file=/src/GenIcon.js

Title: Generic styled component Icon

Body:
I am styling my react component with styled-components. I want an icon component that can be used in different places just by changing size, colour props etc. I also want to pass icons names as props for different places. I am succeeded to change the size and colour but don't know how to pass the icon name as per requirement.

Here is my generic icon component:

     import React from "react";
        import { ReactSVG } from "react-svg";
        import styled, { css } from "styled-components";
        import { FaUserTie } from 'react-icons/fa';

        const StyledSVGIcon = styled(FaUserTie)`
          svg {
            fill: black;
            ${({ size }) =>
                size &&
                css`
                width: ${size};
                height: ${size};
              `}
            ${({ transform }) =>
                transform &&
                css`
                transform: ${transform};
              `}
            path {
              ${({ color }) =>
                color &&
                css`
                  fill: ${color};
                `}
            }
          }
        `;

        const GenIcon = props => {
            return (

Body:
Try this out, you're close:

import React from "react";
import { ReactSVG } from "react-svg";
import styled, { css } from "styled-components";
import { FaUserTie, FaDocker } from "react-icons/fa";

const IconStyler = styled.span`
 color: ${(props) => props.color};
 & svg {
  ${(props) =>
   props.small &&
    css`
     width: 14px !important;
     height: 14px !important;
   `}
 ${(props) =>
  props.med &&
  css`
    width: 20px !important;
    height: 20px !important;
  `}
 ${(props) =>
  props.large &&
  css`
    width: 28px !important;
    height: 28px !important;
  `}
 }

`;

  const Icon = ({ children, ...props }) => {
   return <IconStyler {...props}>{children}</IconStyler>;
  };

const GenIcon = () => {
  return (
   <div>
     <h5>Any Icon</h5>
      <div>
       <Icon color="blue" small>
        <FaUserTie />
       </Icon>
      </div>
      <div>
        <Icon color="orange" large>
        <FaDocker />
        </Icon>
      </div>
   </div>
  );
};

export default GenIcon;

Here's a sandbox link: https://codesandbox.io/s/flamboyant-allen-60ho1?file=/src/GenIcon.js


问:
Confluent Error: set environment variable CONFLUENT_HOME
I have installed confluent-7.0.0 on ubuntu 20.04.Followed the official documentation https://docs.confluent.io/platform/current/quickstart/ce-docker-quickstart.html .
I have added the path of confluent_home as shown below in .bashrc file.:

```<code>export PATH=/home/abc/confluent-7.0.0/bin:$PATH
export PATH=$PATH:$CONFLUENT_HOME/bin
</code>```

And run the command source  ~/.bashrc.
Now the problem is when I have started my services first time by confluent local services start it has up the services of zookeeper,kafka,schema registry,kafka-rest,connect and ksql but while starting control center it has aborted the operation.
And now when I am running this command  confluent local services start it is giving the following error:

```<code>The local commands are intended for a single-node development environment only,
NOT for production usage. https://docs.confluent.io/current/cli/index.html

Error: set environment variable CONFLUENT_HOME
</code>```

Which else environment variable do I have to set and how?

答:
This is what you need</p>
```<code>export CONFLUENT_HOME=/home/abc/confluent-7.0.0
export PATH=$CONFLUENT_HOME/bin:$PATH
</code>```

Body:
I have installed confluent-7.0.0 on ubuntu 20.04.Followed the official documentation https://docs.confluent.io/platform/current/quickstart/ce-docker-quickstart.html .
I have added the path of confluent_home as shown below in .bashrc file.:

export PATH=/home/abc/confluent-7.0.0/bin:$PATH
export PATH=$PATH:$CONFLUENT_HOME/bin

And run the command source  ~/.bashrc.
Now the problem is when I have started my services first time by confluent local services start it has up the services of zookeeper,kafka,schema registry,kafka-rest,connect and ksql but while starting control center it has aborted the operation.
And now when I am running this command  confluent local services start it is giving the following error:

The local commands are intended for a single-node development environment only,
NOT for production usage. https://docs.confluent.io/current/cli/index.html

Error: set environment variable CONFLUENT_HOME

Which else environment variable do I have to set and how?

Body:
This is what you need

export CONFLUENT_HOME=/home/abc/confluent-7.0.0
export PATH=$CONFLUENT_HOME/bin:$PATH


问:
How to sort a f.select?
```<code><%= f.select(:company_id, Company.all.collect {|company| [company.name, company.id]}) %>
</code>```

How can i sort this from A-Z?

答:
```<code><%= f.select :company_id, Company.all.collect{|company| [company.name, company.id]}.sort_by{|a, b| a} %>
</code>```

Or

```<code><%= f.select :company_id, Company.all.collect{|company| [company.name, company.id]}.sort{|a, b| a[0] <=> b[0]} %>
</code>```

UPD

Or just <%= f.select :company_id, Company.all.map{ |c| [c.name, c.id] }.sort %> – Phrogz

Title: How to sort a f.select?

Body:
<%= f.select(:company_id, Company.all.collect {|company| [company.name, company.id]}) %>

How can i sort this from A-Z?

Body:
<%= f.select :company_id, Company.all.collect{|company| [company.name, company.id]}.sort_by{|a, b| a} %>

Or

<%= f.select :company_id, Company.all.collect{|company| [company.name, company.id]}.sort{|a, b| a[0] <=> b[0]} %>

UPD

Or just <%= f.select :company_id, Company.all.map{ |c| [c.name, c.id] }.sort %> – Phrogz


问:
A RenderFlex overflowed bottom flutter
when I run the project it shows A RenderFlex overflowed on the bottom

A RenderFlex overflowed by 6.7 pixels on the bottom.

答:
Try below code hope its helpful to you. add your Column inside SingleChildScrollView

Refer my answer here also

```<code>SingleChildScrollView(
   child:Column(
     children:[
      //Declare Your Widgets Here
     ],
   ),
),
</code>```

Title: A RenderFlex overflowed bottom flutter

Body:
Try below code hope its helpful to you. add your Column inside SingleChildScrollView

Refer my answer here also

SingleChildScrollView(
   child:Column(
     children:[
      //Declare Your Widgets Here
     ],
   ),
),