问:
MySQL how to fill missing dates in range?
I have a table with 2 columns, date and score. It has at most 30 entries, for each of the last 30 days one.

```<code>date      score
-----------------
1.8.2010  19
2.8.2010  21
4.8.2010  14
7.8.2010  10
10.8.2010 14
</code>```

My problem is that some dates are missing - I want to see:

```<code>date      score
-----------------
1.8.2010  19
2.8.2010  21
3.8.2010  0
4.8.2010  14
5.8.2010  0
6.8.2010  0
7.8.2010  10
...
</code>```

What I need from the single query is to get: 19,21,9,14,0,0,10,0,0,14... That means that the missing dates are filled with 0.

I know how to get all the values and in server side language iterating through dates and missing the blanks. But is this possible to do in mysql, so that I sort the result by date and get the missing pieces.

EDIT: In this table there is another column named UserID, so I have 30.000 users and some of them have the score in this table. I delete the dates every day if date < 30 days ago because I need last 30 days score for each user. The reason is I am making a graph of the user activity over the last 30 days and to plot a chart I need the 30 values separated by comma. So I can say in query get me the USERID=10203 activity and the query would get me the 30 scores, one for each of the last 30 days. I hope I am more clear now.

答:
Michael Conard answer is great but I needed intervals of 15 minutes where the time must always start at the top of every 15th minute:

```<code>SELECT a.Days
FROM (
    SELECT FROM_UNIXTIME( FLOOR( UNIX_TIMESTAMP() / (15 * 60) ) * (15 * 60)) - INTERVAL 15 * (a.a + (10 * b.a) + (100 * c.a)) MINUTE AS Days
    FROM       (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS a
    CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS b
    CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS c
) a
WHERE a.Days >= curdate() - INTERVAL 30 DAY
</code>```

This will set the current time to the previous round 15th minute:

```<code>FROM_UNIXTIME( FLOOR( UNIX_TIMESTAMP() / (15 * 60) ) * (15 * 60))
</code>```

And this will remove time with a 15 minute step:

```<code>- INTERVAL 15 * (a.a + (10 * b.a) + (100 * c.a)) MINUTE
</code>```

If there's a simpler way to do it, please let me know.

Body:
I have a table with 2 columns, date and score. It has at most 30 entries, for each of the last 30 days one.

date      score
-----------------
1.8.2010  19
2.8.2010  21
4.8.2010  14
7.8.2010  10
10.8.2010 14

My problem is that some dates are missing - I want to see:

date      score
-----------------
1.8.2010  19
2.8.2010  21
3.8.2010  0
4.8.2010  14
5.8.2010  0
6.8.2010  0
7.8.2010  10
...

What I need from the single query is to get: 19,21,9,14,0,0,10,0,0,14... That means that the missing dates are filled with 0.

I know how to get all the values and in server side language iterating through dates and missing the blanks. But is this possible to do in mysql, so that I sort the result by date and get the missing pieces.

EDIT: In this table there is another column named UserID, so I have 30.000 users and some of them have the score in this table. I delete the dates every day if date < 30 days ago because I need last 30 days score for each user. The reason is I am making a graph of the user activity over the last 30 days and to plot a chart I need the 30 values separated by comma. So I can say in query get me the USERID=10203 activity and the query would get me the 30 scores, one for each of the last 30 days. I hope I am more clear now.

Body:
Michael Conard answer is great but I needed intervals of 15 minutes where the time must always start at the top of every 15th minute:

SELECT a.Days
FROM (
    SELECT FROM_UNIXTIME( FLOOR( UNIX_TIMESTAMP() / (15 * 60) ) * (15 * 60)) - INTERVAL 15 * (a.a + (10 * b.a) + (100 * c.a)) MINUTE AS Days
    FROM       (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS a
    CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS b
    CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS c
) a
WHERE a.Days >= curdate() - INTERVAL 30 DAY

This will set the current time to the previous round 15th minute:

FROM_UNIXTIME( FLOOR( UNIX_TIMESTAMP() / (15 * 60) ) * (15 * 60))

And this will remove time with a 15 minute step:

- INTERVAL 15 * (a.a + (10 * b.a) + (100 * c.a)) MINUTE

If there's a simpler way to do it, please let me know.


来源: stackexchange

问:
Intellisense for C# not working in ASP.net project | Visual Studio 2017
I am making an ASP.Net application, but for some reason Intellisense is not working for the C# code. The Code is white and Errors are not shown as well. It is working great for HTML though. Does anybody know how to fix this?</p>

答:
1.Check if this workaround helps.
 After that, right-click project to unload and reload the project.

2.Also, I'm wondering if you've installed any vs extension recently, I suggest you can start VS in safe-mode to check if it helps.

3.And for now the latest version of VS2017 is 15.9.12, I suggest you update your vs to help reslove the issue.(Or repair vs)
 Hope it helps:)

ContentLicense: CC BY-SA 4.0


问:
Instead of using a hard coded values in JavaScript, is it possible to use a cron to do it?
It's probably easiest to understand by looking at this fiddle:

http://jsfiddle.net/TdBdW/1/ - apologies for the lack of css.

As you can see, for my dynamically generated dropdowns and textboxes I have a big list of hardcoded values. I would have liked to have pulled these straight from a database but the queries take too long to run for them to be used in real-time - i.e. when the user clicks on a drop-down or tries to type in the auto-complete box.

Instead what I would like to do is have the relevant queries run nightly using a cron job but the question is how to take the results of the query and put them into my javascript file.

Anyone have any ideas how to implement this?

Any help is greatly appreciated.

Martin

答:
You can first try to optimize your queries? If you run a cron job, I suppose you could write the results to a json or xml file on the server and pull that file using XHR (aka AJAX).

Alternatively you can design/create a table in the database containing the results of the cronned query, and pull your data from that table?

ContentLicense: CC BY-SA 3.0


问:
How to get an correspondent id through a model on rails console
I've trying to get the simple situation:

I have a Model called Company, inside Company I have companies and I have the following object: "state_id". I want to find the related companies that contain some id.

This is the only path that I can get the state_id. So, I am doing:

```<code>Company.all.each do |comp|
     comp.address.city.state_id
end
</code>```

It works! But when I do:

```<code>Company.all.each do |comp|
     comp.address.city.state_id = 27
     #or comp.address.city.state_id(27)
end
</code>```

it doesn't return the right data

I know that it simple, but unfortunately, I didn't getting the right output.

Thanks a lot!

答:
You can make it work with select method. Also, don't mix up == and = - the former one checks equality and the latter one assigns a value:

```<code>needed_companies = Company.all.select do |comp|
     comp.address.city.state_id == 27
end
</code>```

But it isn't a correct way, because you're loading all companies in memory and filtering it. Much better is to use SQL query (as in answer by Ursus) and return only needed companies from DB

Body:
I've trying to get the simple situation:

I have a Model called Company, inside Company I have companies and I have the following object: "state_id". I want to find the related companies that contain some id.

This is the only path that I can get the state_id. So, I am doing:

Company.all.each do |comp|
     comp.address.city.state_id
end

It works! But when I do:

Company.all.each do |comp|
     comp.address.city.state_id = 27
     #or comp.address.city.state_id(27)
end

it doesn't return the right data

I know that it simple, but unfortunately, I didn't getting the right output.

Thanks a lot!

Body:
You can make it work with select method. Also, don't mix up == and = - the former one checks equality and the latter one assigns a value:

needed_companies = Company.all.select do |comp|
     comp.address.city.state_id == 27
end

But it isn't a correct way, because you're loading all companies in memory and filtering it. Much better is to use SQL query (as in answer by Ursus) and return only needed companies from DB


问:
How do I update a series of user controls based on a collection of data structures?
I have a user control BookViewControl which contains only a StackPanel, I also have a control named BookInfoControl which contains two TextBlocks in a WrapPanel. In the Codebehind for BookViewControl I have an Observable collection (Books) of a Data Structure (named BookInfo which contains two string properties, one for the author and the other for the books name).

What I want is to set it up in such a way that when I add or remove an item to the observable collection (Books) the Stack Panel in BookViewControl would update by adding or removing an instance of the BookInfoControl (where txtName of BookInfoControl is bound to the corresponding BookInfo's BookName property, and the txtAuthor of BookInfoControl would be bound to the same BookInfos AuthorName property).

Thus my problem is two-fold:
1) How do I dynamically create / remove UserControls based on a collection.
2) How to do I add those controls to another Controls StackPanel.

I know that I can bind an instance of BookInfo and it's properties to an instance of BookInfoControls TextBlocks (either in XAMl with Text={Binding SomeDataMember.Path} or in the code behind with instanceName.SetBinding(new binding{ Source = SomeDataMember, Path = new PropertyPath("Path") }); ). However doing so wouldn't cause new members of my collection Books to create a new instance of BookInfoControl nor would it solve the issue of adding it to the StackPanel.

I also considered putting in a kludge to manage a secondary collection of BookInfoControls and then sync it by hand but this seems too messy and I believe there should be an easier and cleaner way with WPF.

BookViewControl.xaml

```<code><UserControl x:Class="GenericNamespace.BookViewControl "
             ... Default Generated Namespace Definitions ...
    >
    <Grid>
        <StackPanel x:Name="pnlCollectionOfBookInfos" />
    </Grid>
</UserControl>
</code>```

BookInfoControl.xaml

```<code><UserControl x:Class="GenericNamespace.BookInfoControl "
             ... Default Generated Namespace Definitions ...
    >
    <Grid>
        <WrapPanel>
            <TextBlock x:Name="txtName"/>
            <TextBlock x:Name="txtAuthor"/>
        </WrapPanel>
    </Grid>
</UserControl>
</code>```

BookInfo.cs

```<code>public class BookInfo
{
    public string AuthorName { get; set; } = "";
    public string BookName { get; set; } = "";
}
</code>```

BookViewControl.cs

```<code>    public partial class BookViewControl: UserControl
    {
        public ObservableCollection<BookInfo> Books { get; set; } = new ObservableCollection<BookInfo>();

        public BookViewControl()
        {
            this.DataContext = this;
            InitializeComponent();
        }
    }
</code>```

In the end, modifying Books should cause a BookInfoControl to be displayed or removed in the StackPanel of BookViewControl where the text properties of BookInfoControls TextBlocks reflect the properties exposed in BookInfo.

Edit: The following link is something I found following the answer I got here and goes more into depth about this subject, hopefully it'll be of use to the next person who asks this: https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/data-templating-overview

答:
Welcome to SO!

Whenever you want to render a collection of items in WPF using data binding you have to use an ItemsControl or one of it's derived controls:

```<code><ItemsControl ItemsSource="{Binding Books}" />
</code>```

If you do this you'll see each book displayed as a string, you change that by declaring a DataTemplate for your Book type:

```<code><UserControl.Resources>

    <DataTemplate DataType="{x:Type local:BookInfo}">
        <local:BookInfoControl />
    </DataTemplate>

</UserControl.Resources>
</code>```

Body:
I have a user control BookViewControl which contains only a StackPanel, I also have a control named BookInfoControl which contains two TextBlocks in a WrapPanel. In the Codebehind for BookViewControl I have an Observable collection (Books) of a Data Structure (named BookInfo which contains two string properties, one for the author and the other for the books name).

What I want is to set it up in such a way that when I add or remove an item to the observable collection (Books) the Stack Panel in BookViewControl would update by adding or removing an instance of the BookInfoControl (where txtName of BookInfoControl is bound to the corresponding BookInfo's BookName property, and the txtAuthor of BookInfoControl would be bound to the same BookInfos AuthorName property).

Thus my problem is two-fold:
1) How do I dynamically create / remove UserControls based on a collection.
2) How to do I add those controls to another Controls StackPanel.

I know that I can bind an instance of BookInfo and it's properties to an instance of BookInfoControls TextBlocks (either in XAMl with Text={Binding SomeDataMember.Path} or in the code behind with instanceName.SetBinding(new binding{ Source = SomeDataMember, Path = new PropertyPath("Path") }); ). However doing so wouldn't cause new members of my collection Books to create a new instance of BookInfoControl nor would it solve the issue of adding it to the StackPanel.

I also considered putting in a kludge to manage a secondary collection of BookInfoControls and then sync it by hand but this seems too messy and I believe there should be an easier and cleaner way with WPF.

BookViewControl.xaml

<UserControl x:Class="GenericNamespace.BookViewControl "
             ... Default Generated Namespace Definitions ...
    >
    <Grid>
        <StackPanel x:Name="pnlCollectionOfBookInfos" />
    </Grid>
</UserControl>

BookInfoControl.xaml

<UserControl x:Class="GenericNamespace.BookInfoControl "
             ... Default Generated Namespace Definitions ...
    >
    <Grid>
        <WrapPanel>
            <TextBlock x:Name="txtName"/>
            <TextBlock x:Name="txtAuthor"/>
        </WrapPanel>
    </Grid>
</UserControl>

BookInfo.cs

public class BookInfo
{
    public string AuthorName { get; set; } = "";
    public string BookName { get; set; } = "";
}

BookViewControl.cs

    public partial class BookViewControl: UserControl
    {
        public ObservableCollection<BookInfo> Books { get; set; } = new ObservableCollection<BookInfo>();

        public BookViewControl()
        {
            this.DataContext = this;
            InitializeComponent();
        }
    }

In the end, modifying Books should cause a BookInfoControl to be displayed or removed in the StackPanel of BookViewControl where the text properties of BookInfoControls TextBlocks reflect the properties exposed in BookInfo.

Edit: The following link is something I found following the answer I got here and goes more into depth about this subject, hopefully it'll be of use to the next person who asks this: https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/data-templating-overview

Body:
Welcome to SO!

Whenever you want to render a collection of items in WPF using data binding you have to use an ItemsControl or one of it's derived controls:

<ItemsControl ItemsSource="{Binding Books}" />

If you do this you'll see each book displayed as a string, you change that by declaring a DataTemplate for your Book type:

<UserControl.Resources>

    <DataTemplate DataType="{x:Type local:BookInfo}">
        <local:BookInfoControl />
    </DataTemplate>

</UserControl.Resources>


问:
Faster way to convert large binary string to BigInteger
The code below is converting big binary string binaryAsString = "1010101011101011......." to BigInteger decimal but this is very slow, it takes very long time to finish. Is there any faster way to make this done? Before this I had a problem with converting BitArray to string. My first code take so long but I found new code which was much faster in a way I didn't imagine. I hope I can find a similarly faster way to do this, because it's really taking a long time.

I tried to use String whatever = Convert.ToString(binaryAsString, 2); but this is not working at all.

```<code>// converting the binary String to decimal
BigInteger Decimalvalue = 0;

foreach (char c in binaryAsString)
{
    Decimalvalue <<= 1;

    Decimalvalue += c == '1' ? 1 : 0;

}
</code>```

I would like to have faster code to do exactly what the code above should do.

答:
You can use an or operator rather than +.

Further, you can cache the big integer value of 1 (integers are boxed into a big integer)

```<code>BigInteger one = 1;
foreach (char c in s)
{
    integer <<= 1;
    if (c == '1')
        integer |= one;
}
</code>```

It's significantly faster in my tests.

Body:
The code below is converting big binary string binaryAsString = "1010101011101011......." to BigInteger decimal but this is very slow, it takes very long time to finish. Is there any faster way to make this done? Before this I had a problem with converting BitArray to string. My first code take so long but I found new code which was much faster in a way I didn't imagine. I hope I can find a similarly faster way to do this, because it's really taking a long time.

I tried to use String whatever = Convert.ToString(binaryAsString, 2); but this is not working at all.

// converting the binary String to decimal
BigInteger Decimalvalue = 0;

foreach (char c in binaryAsString)
{
    Decimalvalue <<= 1;

    Decimalvalue += c == '1' ? 1 : 0;

}

I would like to have faster code to do exactly what the code above should do.

Body:
You can use an or operator rather than +.

Further, you can cache the big integer value of 1 (integers are boxed into a big integer)

BigInteger one = 1;
foreach (char c in s)
{
    integer <<= 1;
    if (c == '1')
        integer |= one;
}

It's significantly faster in my tests.


问:
GMSPlacePickerViewController always return error - There is a per-IP or per-Referer restriction configured on your API key
hope everyone doing well.
I'm developing an iOS application which needs to share location through google maps and display map static image in a screen corresponding to the selected location.
I've done some researches and found GMSPlacePickerViewController is the best option. I've set up api key in google cloud platform and restricted it with app bundle ID and API restrictions (Maps SDk, Places API and Maps static API). I've enable billing for the account.
Now each time I going to GMSPlacePickerViewController, the map just loading and dismissing itself. It throws 2 errors.

1 - "The application's bundle identifier does not match one of the
    allowed iOS applications for the API key. See the developer's guide
    (https://developers.google.com/places/ios-sdk/start) for how to
    configure bundle restrictions on API keys."
2 - "There is a per-IP or per-Referer restriction configured on your
    API key and the request does not match these restrictions. Please
    use the Google Developers Console to update your API key
    configuration if request from this IP or referer should be
    allowed."

I don't know why this happened as I've set correct bundle ID and I generated credential as API key.

I request you to advice me to get out this and please tell me if there is any other better way to do this.

答:
Please note that the Place Picker has been deprecated as of January 29, 2019. This feature will be turned off on July 29, 2019, and will no longer be available after that date. Please note that the old users that used Places SDK for iOS/Android are the only one who can still use the Place Picker during the deprecation period. The use of Places SDK for both platforms are now through enabling Places API and does not support the use of Place Picker anymore. You may see the deprecation notice in https://developers.google.com/places/android-sdk/placepicker.

In addition to this, Google is conducting a review on what drives the users to use the Place Picker, if you are interested, kindly add your answer in the form mentioned in this issue.

Should you need further assistance, kindly file a support case via https://console.cloud.google.com/google/maps-apis/support in order to open personalized communication channel.


问:
white text stand out in the grey background
I have a div tag with background-color: #FFFFFF and opacity: 0.08. Inside it is a span tag with the colour white. What can I do to make the white text stand out in the grey background in the parent div? It seems that i cannot increase parent's opacity

答:
Just make it a fairly dark grey:

#background {
  background-color: #222222;
  text-align: center;
  vertical-align: middle;
}
#text {
  color: #FFFFFF;
  background-color: #444444;
}
body {
  font-family: sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="background" style="height: 100vh; width: 100vw;">
  <span id="text">Ngay Nhap Vien</span>
</div></code>```

Body:
Just make it a fairly dark grey:

#background {
  background-color: #222222;
  text-align: center;
  vertical-align: middle;
}
#text {
  color: #FFFFFF;
  background-color: #444444;
}
body {
  font-family: sans-serif;
}

<div id="background" style="height: 100vh; width: 100vw;">
  <span id="text">Ngay Nhap Vien</span>
</div>


问:
Having problems with writing a method to find the index of the biggest integer in my ArrayList
I am having problems in creating a method that will find the index of the biggest integer.

I have tried creating plenty of methods but I was only recently introduced to finding the index of a value in a list, and I still am unable to find the best, let alone a working way. By index I assumed that it is the position of the value within the list given (please correct me if I am wrong).

My Current Code:

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

public class FindBiggest2 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    ArrayList<Integer> integerList = new ArrayList<Integer>();

    System.out.println("Enter any amount integers (0 to stop): ");

    int integer = input.nextInt();
    while(integer != 0) {
        integerList.add(integer);
        integer = input.nextInt();
    }
    input.close();
    if(integerList.size() == 0) {
        System.out.println("list is empty");
        return;
    }
     System.out.println("\nThe integers entered are: ");
    // displaying ids
    for(int i=0; i<integerList.size(); i++)
        System.out.print(integerList.get(i)+" ");
        System.out.println();

    // finding biggest id
    int bInt = integerList.get(0); // initializing bid id with first element
    for(int i=1; i<integerList.size(); i++)
        if(bInt < integerList.get(i))
        bInt = integerList.get(i);

    System.out.println("The biggest integer in the array is: "+ bInt);
    }

}
</code>```

My current output (Example):

```<code>Enter any amount of integers (0 to stop):
1
2
3
4
5
6
0

The integers entered are:
1 2 3 4 5 6
The biggest integer in the array is: 6
</code>```

These are my requirements of my output:

The output of the program should firstly display all integers, and then
indicate the biggest integer among them as well as the index of the biggest integer in the 1D
array.

答:
So your index in this loop:

```<code>int bInt = integerList.get(0); // initializing bid id with first element
for(int i=1; i<integerList.size(); i++) // i = index
    if(bInt < integerList.get(i))
    bInt = integerList.get(i);
</code>```

would be i. Along with int bInt, you'll want an int maxIntegerIndex to hold that value until the for loop concludes.

One stylistic choice I'd suggest that you can feel free to ignore is using curly braces to explicitly declare what code is running in a loop / if statement. This will prevent issues later on in code reading and execution where it appears code should run but isn't. It'll save you a lot of time tracking down seemingly broken code down the road and costs almost nothing.

Body:
I am having problems in creating a method that will find the index of the biggest integer.

I have tried creating plenty of methods but I was only recently introduced to finding the index of a value in a list, and I still am unable to find the best, let alone a working way. By index I assumed that it is the position of the value within the list given (please correct me if I am wrong).

My Current Code:

import java.util.ArrayList;
import java.util.Scanner;

public class FindBiggest2 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    ArrayList<Integer> integerList = new ArrayList<Integer>();

    System.out.println("Enter any amount integers (0 to stop): ");

    int integer = input.nextInt();
    while(integer != 0) {
        integerList.add(integer);
        integer = input.nextInt();
    }
    input.close();
    if(integerList.size() == 0) {
        System.out.println("list is empty");
        return;
    }
     System.out.println("\nThe integers entered are: ");
    // displaying ids
    for(int i=0; i<integerList.size(); i++)
        System.out.print(integerList.get(i)+" ");
        System.out.println();

    // finding biggest id
    int bInt = integerList.get(0); // initializing bid id with first element
    for(int i=1; i<integerList.size(); i++)
        if(bInt < integerList.get(i))
        bInt = integerList.get(i);

    System.out.println("The biggest integer in the array is: "+ bInt);
    }

}

My current output (Example):

Enter any amount of integers (0 to stop):
1
2
3
4
5
6
0

The integers entered are:
1 2 3 4 5 6
The biggest integer in the array is: 6

These are my requirements of my output:

The output of the program should firstly display all integers, and then
indicate the biggest integer among them as well as the index of the biggest integer in the 1D
array.

Body:
So your index in this loop:

int bInt = integerList.get(0); // initializing bid id with first element
for(int i=1; i<integerList.size(); i++) // i = index
    if(bInt < integerList.get(i))
    bInt = integerList.get(i);

would be i. Along with int bInt, you'll want an int maxIntegerIndex to hold that value until the for loop concludes.

One stylistic choice I'd suggest that you can feel free to ignore is using curly braces to explicitly declare what code is running in a loop / if statement. This will prevent issues later on in code reading and execution where it appears code should run but isn't. It'll save you a lot of time tracking down seemingly broken code down the road and costs almost nothing.


问:
CSS inner id selectors
I've got below id selectors in a CSS file. Headerphoto and logo-box are inner id-selectors of header id. Do I really need to add those two as inner id-selectors? I can add them as just normal id selectors. What is the best way of doing this? What are the pros and cons?

Thank you!

```<code>/* Header styles */
#header {
    position: relative;
    height: 176px;
    text-align: left;
    margin: 0; padding: 0;
    background: #FFF;
}

#header #headerphoto {
    position: absolute;
    right: 15px ; top: 15px;
    width: 455px;
    height: 156px;
    background: #FFF url(headerphoto.jpg) no-repeat;
}

#header #logo-box {
    position: absolute;
    left: 15px ; top: 15px;
    width: 280px;
    height: 156px;
    background:#1c1e27;
}
</code>```

答:
It doesn't matter as long as only one of #headerphoto and #logo-box exist on each page and you're sure the structure for these three elements will be the same.

It only really matters to add the #header ID if, on some pages, #headerphoto and #logo-box appear in elements that don't have id="header", your stylesheet is used by all these pages, and you want the styles to apply if and only if these elements are in that one. But in such a case, that'd make your page structure rather inconsistent, wouldn't it?

Regarding performance, whether it's faster, slower or the same to nest ID selectors, I don't care, and neither should you, the stylesheet author, since ID selectors are already the fastest anyway.

Title: CSS inner id selectors

Body:
I've got below id selectors in a CSS file. Headerphoto and logo-box are inner id-selectors of header id. Do I really need to add those two as inner id-selectors? I can add them as just normal id selectors. What is the best way of doing this? What are the pros and cons?

Thank you!

/* Header styles */
#header {
    position: relative;
    height: 176px;
    text-align: left;
    margin: 0; padding: 0;
    background: #FFF;
}

#header #headerphoto {
    position: absolute;
    right: 15px ; top: 15px;
    width: 455px;
    height: 156px;
    background: #FFF url(headerphoto.jpg) no-repeat;
}

#header #logo-box {
    position: absolute;
    left: 15px ; top: 15px;
    width: 280px;
    height: 156px;
    background:#1c1e27;
}


问:
Deny static content for unauthorized users using web.config
In my asp.net MVC application I have tried to deny unauthorized users from an html file inside a sub folder. But it is not working as expected. Below is the web.config section which used right now.

```<code><configuration>

<system.web>
  <compilation debug="true" targetFramework="4.5" />
  <authentication mode="Forms">
    <forms loginUrl="~/" defaultUrl="~/" slidingExpiration="true" timeout="60">
    </forms>
  </authentication>
  <authorization>
    <deny users="?" />
  </authorization>
</system.web>

<location path="Docs/help/index.html">
  <system.web>
    <authorization>
      <deny users="?" />
    </authorization>
  </system.web>
</location>

</configuration>
</code>```

I think the global deny users will block all unauthorized access for all the pages, otherwise we should give specific permission. Please correct me If I am wrong.

But in my case even http://siteurl.com/Docs/help/index.html still able to access for an unauthorze user.

IIS - 7.5 , .NET - 4.5, MVC - 4

Please help me to resolve this issue.

MG

答:
You can put a new Web.config in the folder that needs the permissions applied. Inside it do something like this

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</configuration>
</code>```

Or you might need to wrap the <authorization> tag with a <security> tag.

If that doesn't work for you, try to do it via IIS Manager and see how it does it, then copy that.

Body:
In my asp.net MVC application I have tried to deny unauthorized users from an html file inside a sub folder. But it is not working as expected. Below is the web.config section which used right now.

<configuration>

<system.web>
  <compilation debug="true" targetFramework="4.5" />
  <authentication mode="Forms">
    <forms loginUrl="~/" defaultUrl="~/" slidingExpiration="true" timeout="60">
    </forms>
  </authentication>
  <authorization>
    <deny users="?" />
  </authorization>
</system.web>

<location path="Docs/help/index.html">
  <system.web>
    <authorization>
      <deny users="?" />
    </authorization>
  </system.web>
</location>

</configuration>

I think the global deny users will block all unauthorized access for all the pages, otherwise we should give specific permission. Please correct me If I am wrong.

But in my case even http://siteurl.com/Docs/help/index.html still able to access for an unauthorze user.

IIS - 7.5 , .NET - 4.5, MVC - 4

Please help me to resolve this issue.

MG

Body:
You can put a new Web.config in the folder that needs the permissions applied. Inside it do something like this

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</configuration>

Or you might need to wrap the <authorization> tag with a <security> tag.

If that doesn't work for you, try to do it via IIS Manager and see how it does it, then copy that.


问:
Why are 0d arrays in Numpy considered scalar?
In a sense, this already has an excellent answer:

One should not think too hard about it. It's ultimately better for the mental health and longevity of the individual.

Mental health and longevity are of course nice, but what about this individual's pride which took another hit trying to be clever and cruelly being denied by numpy:

Consider the following where we start with some byte data:

```<code>a = np.linspace(0,255,6, dtype=np.uint8)
a
# array([  0,  51, 102, 153, 204, 255], dtype=uint8)
</code>```

Let's assume we want to add something and promote the type, so it does not wrap around. With a scalar, this does not work:

```<code>b = np.uint16(1)

a + b
# array([  1,  52, 103, 154, 205,   0], dtype=uint8)
</code>```

But with an array, it does:

```<code>c = np.ones(1, np.uint16)

a + c
# array([  1,  52, 103, 154, 205, 256], dtype=uint16)
</code>```

So I thought let's make an array.

```<code>b[...]
# array(1, dtype=uint16)
np.isscalar(b[...])
# False
</code>```

But, alas:

```<code>a + b[...]
# array([  1,  52, 103, 154, 205,   0], dtype=uint8)
</code>```

Why does this 0d array behave like a scalar here?

答:
https://docs.scipy.org/doc/numpy/reference/ufuncs.html#casting-rules

last paragraph:

Mixed scalar-array operations use a different set of casting rules that ensure that a scalar cannot “upcast” an array unless the scalar is of a fundamentally different kind of data (i.e., under a different hierarchy in the data-type hierarchy) than the array. This rule enables you to use scalar constants in your code (which, as Python types, are interpreted accordingly in ufuncs) without worrying about whether the precision of the scalar constant will cause upcasting on your large (small precision) array.

I take this to mean that the following expressions have the same effect:

```<code>In [56]: np.add(a,1)
Out[56]: array([  1,  52, 103, 154, 205,   0], dtype=uint8)
In [57]: np.add(a,np.array(1))
Out[57]: array([  1,  52, 103, 154, 205,   0], dtype=uint8)
</code>```

For this to be true, a 0d cannot "upcast".  But a list behaves like a 1d array, and does "upcast"

```<code>In [60]: np.add(a,[1])
Out[60]: array([  1,  52, 103, 154, 205, 256])
In [61]: np.add(a,np.array([1]))
Out[61]: array([  1,  52, 103, 154, 205, 256])
</code>```

https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html

Array scalars include np.uint8(1) etc.

The array scalar objects have an array priority of NPY_SCALAR_PRIORITY (-1,000,000.0).

```<code>In [67]: np.uint8(1).__array_priority__
Out[67]: -1000000.0
In [68]: np.array(1,'uint8').__array_priority__
Out[68]: 0.0
</code>```

Array scalars have exactly the same methods as arrays. The default behavior of these methods is to internally convert the scalar to an equivalent 0-dimensional array and to call the corresponding array method.

np.isscalar does:

```<code>        (isinstance(num, generic)
        or type(num) in ScalarType
        or isinstance(num, numbers.Number))
</code>```

np.isscalar recommends using np.ndim(x) == 0.  This first checks for a .ndim attribute (which would be the case for 0d arrays), and failing that, tries np.asarray(x).ndim.  So in that sense, anything that can be made into a 0d array qualifies as 'scalar'.  That may be too broad, since a dictionary counts: npdim({}).

Body:
In a sense, this already has an excellent answer:

One should not think too hard about it. It's ultimately better for the mental health and longevity of the individual.

Mental health and longevity are of course nice, but what about this individual's pride which took another hit trying to be clever and cruelly being denied by numpy:

Consider the following where we start with some byte data:

a = np.linspace(0,255,6, dtype=np.uint8)
a
# array([  0,  51, 102, 153, 204, 255], dtype=uint8)

Let's assume we want to add something and promote the type, so it does not wrap around. With a scalar, this does not work:

b = np.uint16(1)

a + b
# array([  1,  52, 103, 154, 205,   0], dtype=uint8)

But with an array, it does:

c = np.ones(1, np.uint16)

a + c
# array([  1,  52, 103, 154, 205, 256], dtype=uint16)

So I thought let's make an array.

b[...]
# array(1, dtype=uint16)
np.isscalar(b[...])
# False

But, alas:

a + b[...]
# array([  1,  52, 103, 154, 205,   0], dtype=uint8)

Why does this 0d array behave like a scalar here?

Body:
https://docs.scipy.org/doc/numpy/reference/ufuncs.html#casting-rules

last paragraph:

Mixed scalar-array operations use a different set of casting rules that ensure that a scalar cannot “upcast” an array unless the scalar is of a fundamentally different kind of data (i.e., under a different hierarchy in the data-type hierarchy) than the array. This rule enables you to use scalar constants in your code (which, as Python types, are interpreted accordingly in ufuncs) without worrying about whether the precision of the scalar constant will cause upcasting on your large (small precision) array.

I take this to mean that the following expressions have the same effect:

In [56]: np.add(a,1)
Out[56]: array([  1,  52, 103, 154, 205,   0], dtype=uint8)
In [57]: np.add(a,np.array(1))
Out[57]: array([  1,  52, 103, 154, 205,   0], dtype=uint8)

For this to be true, a 0d cannot "upcast".  But a list behaves like a 1d array, and does "upcast"

In [60]: np.add(a,[1])
Out[60]: array([  1,  52, 103, 154, 205, 256])
In [61]: np.add(a,np.array([1]))
Out[61]: array([  1,  52, 103, 154, 205, 256])

https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html

Array scalars include np.uint8(1) etc.

The array scalar objects have an array priority of NPY_SCALAR_PRIORITY (-1,000,000.0).

In [67]: np.uint8(1).__array_priority__
Out[67]: -1000000.0
In [68]: np.array(1,'uint8').__array_priority__
Out[68]: 0.0

Array scalars have exactly the same methods as arrays. The default behavior of these methods is to internally convert the scalar to an equivalent 0-dimensional array and to call the corresponding array method.

np.isscalar does:

        (isinstance(num, generic)
        or type(num) in ScalarType
        or isinstance(num, numbers.Number))

np.isscalar recommends using np.ndim(x) == 0.  This first checks for a .ndim attribute (which would be the case for 0d arrays), and failing that, tries np.asarray(x).ndim.  So in that sense, anything that can be made into a 0d array qualifies as 'scalar'.  That may be too broad, since a dictionary counts: npdim({}).


问:
Trouble shooting Oracle Form Builder error FRM-10044
I'm trying to create & save a new form using Oracle Form builder however, I get the error FRM-10044: Cannot create file.

The same thing happens when I open and save an existing form (.fmb)

I've check the folder permissions where the form is being save, it has read write access.

I've tried saving it into a differ folder and also tried creating a new folder but it still throws the same error.

I'm able to create and save a word, excel document in the new or existing folders (as mentioned-above) without any issues.

I suspect it could be something to do with the Windows Registry or System Configuration settings because I had recently shutdown/disabled so of the services in the System Configuration (using
msconfig.exe). Unfortunately, I don't remember all the options that were modified.

I've gone through numerous discussion forums, but still no luck.

Any help is appreciated.

Thanks in Advance

答: I've experienced the same thing. But in my case, i compiled the form on server side. The error appeared because it was remote-controlled by more than 1 person. One of the remote session was possibly locking the file creation. So I logged off the other session and try to use 1 session only when compiling the form. This happens sometimes when we're using an OS with multiuser and multisession capability.</p>


问:
CMake cannot follow symbolic links
Update: turns out the problem is not related to the Jenkins agent but to CMake. It is easily reproducible from the command line.
It was reported here once before:
CMake cannot follow symlinks on Windows 10
However, the problem is not OS-related. We encounter it on Linux also.

I'm debugging the following error:

```<code>CMake Error at C:/jenkins/trial/workspace/WWB6-6.13.0/wwb-Pilot_Build_BB/wwb6/build/cmake_install.cmake:48 (file):
 file INSTALL cannot read symlink
  "C:/jenkins/trial/workspace/WWB6-6.13.0/wwb6-Build-Pilot-Windows/wwb6/wwb6/HelpFiles"
to duplicate at
  "C:/jenkins/trial/workspace/WWB6-6.13.0/wwb6-Build-Pilot-Windows/wwb6/build/_CPack_Packages/win64/NSIS/WWB6 Setup/./Help".
</code>```

The relevant line in the make file is:

```<code>file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/./Help" TYPE DIRECTORY FILES "C:/jenkins/trial/workspace/WWB6-6.13.0/wwb-Pilot_Build_BB/wwb6/wwb6/HelpFiles/")
</code>```

The intent is to copy the contents of the HelpFiles directory into a new directory "Help" in the workspace. The HelpFiles directory in this scenario is a symbolic link to another directory in the source repository:

```<code>Directory of C:\jenkins\trial\workspace\WWB6-6.13.0\wwb6-Build-Pilot-Windows\wwb6\wwb6
05/17/2019  03:09 PM    <SYMLINKD>     HelpFiles [..\helpwwb6]
</code>```

Traversing this symlink from the command line works fine:

```<code>C:\jenkins\trial\workspace\WWB6-6.13.0\wwb6-Build-Pilot-Windows\wwb6\wwb6>cd HelpFiles
C:\jenkins\trial\workspace\WWB6-6.13.0\wwb6-Build-Pilot-Windows\wwb6\wwb6\HelpFiles>
</code>```

Anyone know of a workaround for this problem? The version of CMake we're running is 3.12.0.

答:
Fortunately, there's an easy (although not elegant) workaround for this: replace the symlink with the real path in the CMakeLists file:

```<code>install ( DIRECTORY ${CMAKE_SOURCE_DIR}/../helpwwb6/
      DESTINATION ${BINARY_INSTALL_LOCATION}/Help
      COMPONENT Runtime
      PATTERN ".svn" EXCLUDE
      PATTERN ".git" EXCLUDE
    )
</code>```

Would rather see CMake work with symlinks though.

Title: CMake cannot follow symbolic links

Body:
Update: turns out the problem is not related to the Jenkins agent but to CMake. It is easily reproducible from the command line.
It was reported here once before:
CMake cannot follow symlinks on Windows 10
However, the problem is not OS-related. We encounter it on Linux also.

I'm debugging the following error:

CMake Error at C:/jenkins/trial/workspace/WWB6-6.13.0/wwb-Pilot_Build_BB/wwb6/build/cmake_install.cmake:48 (file):
 file INSTALL cannot read symlink
  "C:/jenkins/trial/workspace/WWB6-6.13.0/wwb6-Build-Pilot-Windows/wwb6/wwb6/HelpFiles"
to duplicate at
  "C:/jenkins/trial/workspace/WWB6-6.13.0/wwb6-Build-Pilot-Windows/wwb6/build/_CPack_Packages/win64/NSIS/WWB6 Setup/./Help".

The relevant line in the make file is:

file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/./Help" TYPE DIRECTORY FILES "C:/jenkins/trial/workspace/WWB6-6.13.0/wwb-Pilot_Build_BB/wwb6/wwb6/HelpFiles/")

The intent is to copy the contents of the HelpFiles directory into a new directory "Help" in the workspace. The HelpFiles directory in this scenario is a symbolic link to another directory in the source repository:

Directory of C:\jenkins\trial\workspace\WWB6-6.13.0\wwb6-Build-Pilot-Windows\wwb6\wwb6
05/17/2019  03:09 PM    <SYMLINKD>     HelpFiles [..\helpwwb6]

Traversing this symlink from the command line works fine:

C:\jenkins\trial\workspace\WWB6-6.13.0\wwb6-Build-Pilot-Windows\wwb6\wwb6>cd HelpFiles
C:\jenkins\trial\workspace\WWB6-6.13.0\wwb6-Build-Pilot-Windows\wwb6\wwb6\HelpFiles>

Anyone know of a workaround for this problem? The version of CMake we're running is 3.12.0.

Body:
Fortunately, there's an easy (although not elegant) workaround for this: replace the symlink with the real path in the CMakeLists file:

install ( DIRECTORY ${CMAKE_SOURCE_DIR}/../helpwwb6/
      DESTINATION ${BINARY_INSTALL_LOCATION}/Help
      COMPONENT Runtime
      PATTERN ".svn" EXCLUDE
      PATTERN ".git" EXCLUDE
    )

Would rather see CMake work with symlinks though.


问:
Creating new data object set from multiple nested arrays
I've have a complex data structure with multiple nested arrays in place.

Below is the current structure

```<code>var contentData = {
  data: {
    content: [
      {
        type: "column",
        sections: [
          {
            sub: [
              {
                type: "heading-1",
                text: "Heading Text"
              }
            ]
          }
        ]
      },
      {
        type: "acc-item",
        sections: [
          {
            sub: [
              {
                type: "heading-1",
                text: "Heading Text"
              },
              {
                type: "ordered-item",
                text: "Item 1"
              },
              {
                type: "unordered-item",
                text: "Item 2"
              }
            ]
          }
        ]
      },
      {
        type: "acc-item",
        sections: [
          {
            sub: [
              {
                type: "heading-1",
                text: "Heading Text 2"
              }
            ]
          }
        ]
      }
    ]
  }
}
</code>```

So What I wanted is,

I wanted to group all the ordered-item & unordered-item into a new object like {type: 'list', items:[all list items]}.

I need to extract all items which are inside sub and push it to new object embedded and it should placed in the root level like below,

{type:"acc-item",embedded:[{type:"heading-1",text:"Heading Text 2"}]};

So What I've done so far,

I can able to group acc-item, but not the ordered-item & unordered-item.

So my final expected result should like this,

```<code>[{
  "type": "column",
  "embedded": [
    {
      "type": "heading-1",
      "text": "Heading Text"
    }
  ]
},
{
  "type": "acc-group",
  "items": [
    {
      "type": "acc-item",
      "embedded": [
        {
          "type": "heading-1",
          "text": "Heading Text"
        },
        {
          "type": "list",
          "items": [
            {
              "type": "ordered-item",
              "text": "Item 1"
            },
            {
              "type": "unordered-item",
              "text": "Item 2"
            }
          ]
        }
      ]
    },
    {
      "type": "acc-item",
      "embedded": [
        {
          "type": "heading-1",
          "text": "Heading Text 2"
        }
      ]
    }
  ]
}]
</code>```

Below is my code,

var group,contentData={data:{content:[{type:"column",sections:[{sub:[{type:"heading-1",text:"Heading Text"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"Heading Text"},{type:"ordered-item",text:"Item 1"},{type:"unordered-item",text:"Item 2"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"Heading Text 2"}]}]}]}},types=[["list",["ordered-item","unordered-item"]],["accordion",["acc-item"]]];

var result = contentData.data.content.reduce((r, o) => {
  var type = (types.find(({ 1: values }) => values.indexOf(o.type) > -1)|| {})[0];
  if (!type) {
    r.push(o);
    group = undefined;
    return r;
  }
  if (!group || group.type !== type) {
    group = { type, items: [] };
    r.push(group);
  }
  group.items.push(o);
  return r;
}, []);

document.body.innerHTML = '```' + JSON.stringify(result, null, '  ') + '```';```

答:
The Array.prototype and Object.prototype methods are perfect for this kind of thing.

And you're right that this is some complicated kind of logic.

I would suggest that you definitely need some unit tests for this, and try break in to separate pieces.

Here's how I'm thinking I'd do it.

1. Group By the type to create your groups..

I'm actually creating a more generic solution that you've asked for here. That is,  I'm not just grouping the 'acc-item', but everything.

I did a quick search for 'array group by javascript' and it gives us this answer which suggests using Array.reduce, so let's do that.

```<code>    const groupedData = contentData.data.content.reduce((acc, cur) => {
        //Check if this indexed array already exists, if not create it.
        const currentArray = (acc[`${cur.type}-group`] && acc[`${cur.type}-group`].items) || [];

        return {
          ...acc,
          [`${cur.type}-group`]: {
              type: `${cur.type}-group`,
              items: [...currentArray, cur]
          }
        }
    }, {});
</code>```

2. Now for each of those items, we need to look at their subs, and group just the list items.

To do this, we basically want to find all the `item -> sections -> sub -> types and filter them into two arrays. A quick google on how to create two arrays using a filter gives me this answer.

First though, we need to flatten that sections-> subs thing, so lets just do that.

```<code>function flattenSectionsAndSubs(item) {
    return {
        type: item.type,
        subs: item.sections.reduce((acc, cur) => ([...acc, ...cur.sub]), [])
    };
}
</code>```

And I'll just copy paste that partition function in:

```<code>function partition(array, isValid) {
  return array.reduce(([pass, fail], elem) => {
    return isValid(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]];
  }, [[], []]);
}

    const listTypes = ['ordered-item', 'unordered-item'];
    function createEmbeddedFromItem(item) {
        const [lists, nonLists] = partition(item.subs, (v) => listTypes.includes(v.type);

      return {
         type: item.type,
         embedded: [
             ...nonLists,
             {
                type: "list",
                items: lists
             }
         ]
      }
    }

</code>```

Putting this all together and we get.

const contentData = {
  data: {
    content: [{
        type: "column",
        sections: [{
          sub: [{
            type: "heading-1",
            text: "Heading Text"
          }]
        }]
      },
      {
        type: "acc-item",
        sections: [{
          sub: [{
              type: "heading-1",
              text: "Heading Text"
            },
            {
              type: "ordered-item",
              text: "Item 1"
            },
            {
              type: "unordered-item",
              text: "Item 2"
            }
          ]
        }]
      },
      {
        type: "acc-item",
        sections: [{
          sub: [{
            type: "heading-1",
            text: "Heading Text 2"
          }]
        }]
      }
    ]
  }
}

function partition(array, isValid) {
  return array.reduce(([pass, fail], elem) => {
    return isValid(elem) ? [
      [...pass, elem], fail
    ] : [pass, [...fail, elem]];
  }, [
    [],
    []
  ]);
}

function flattenSectionsAndSubs(item) {
  return {
    type: item.type,
    subs: item.sections.reduce((acc, cur) => ([...acc, ...cur.sub]), [])
  };
}

const listTypes = ['ordered-item', 'unordered-item'];

function createEmbeddedFromItem(item) {
  const [lists, nonLists] = partition(item.subs, (v) => listTypes.includes(v.type));

    return {
      type: item.type,
      embedded: [
        ...nonLists,
        {
          type: "list",
          items: lists
        }
      ]
    }
  }

  const groupedData = contentData.data.content.reduce((acc, cur) => {
    //Check if this indexed array already exists, if not create it.
    const currentArray = (acc[`${cur.type}-group`] && acc[`${cur.type}-group`].items) || [];

    const flattenedItem = flattenSectionsAndSubs(cur);
    const embeddedItem = createEmbeddedFromItem(flattenedItem);
    return {
      ...acc,
      [`${cur.type}-group`]: {
          type: `${cur.type}-group`,
          items: [...currentArray, embeddedItem]
      }
    }
  }, {});

  console.log(groupedData);```

Now this doesn't exactly match what you've asked for - but it should probably work.

You can add your own bits into only add a list item, if the array isn't empty, and to stop the column from being in its own group.

The thing is - tbh it seems like a little bit of a red flag that you would create an array of items that don't having matching structures, which is why I've done it this way.

Body:
I've have a complex data structure with multiple nested arrays in place.

Below is the current structure

var contentData = {
  data: {
    content: [
      {
        type: "column",
        sections: [
          {
            sub: [
              {
                type: "heading-1",
                text: "Heading Text"
              }
            ]
          }
        ]
      },
      {
        type: "acc-item",
        sections: [
          {
            sub: [
              {
                type: "heading-1",
                text: "Heading Text"
              },
              {
                type: "ordered-item",
                text: "Item 1"
              },
              {
                type: "unordered-item",
                text: "Item 2"
              }
            ]
          }
        ]
      },
      {
        type: "acc-item",
        sections: [
          {
            sub: [
              {
                type: "heading-1",
                text: "Heading Text 2"
              }
            ]
          }
        ]
      }
    ]
  }
}

So What I wanted is,

I wanted to group all the ordered-item & unordered-item into a new object like {type: 'list', items:[all list items]}.

I need to extract all items which are inside sub and push it to new object embedded and it should placed in the root level like below,

{type:"acc-item",embedded:[{type:"heading-1",text:"Heading Text 2"}]};

So What I've done so far,

I can able to group acc-item, but not the ordered-item & unordered-item.

So my final expected result should like this,

[{
  "type": "column",
  "embedded": [
    {
      "type": "heading-1",
      "text": "Heading Text"
    }
  ]
},
{
  "type": "acc-group",
  "items": [
    {
      "type": "acc-item",
      "embedded": [
        {
          "type": "heading-1",
          "text": "Heading Text"
        },
        {
          "type": "list",
          "items": [
            {
              "type": "ordered-item",
              "text": "Item 1"
            },
            {
              "type": "unordered-item",
              "text": "Item 2"
            }
          ]
        }
      ]
    },
    {
      "type": "acc-item",
      "embedded": [
        {
          "type": "heading-1",
          "text": "Heading Text 2"
        }
      ]
    }
  ]
}]

Below is my code,

var group,contentData={data:{content:[{type:"column",sections:[{sub:[{type:"heading-1",text:"Heading Text"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"Heading Text"},{type:"ordered-item",text:"Item 1"},{type:"unordered-item",text:"Item 2"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"Heading Text 2"}]}]}]}},types=[["list",["ordered-item","unordered-item"]],["accordion",["acc-item"]]];

var result = contentData.data.content.reduce((r, o) => {
  var type = (types.find(({ 1: values }) => values.indexOf(o.type) > -1)|| {})[0];
  if (!type) {
    r.push(o);
    group = undefined;
    return r;
  }
  if (!group || group.type !== type) {
    group = { type, items: [] };
    r.push(group);
  }
  group.items.push(o);
  return r;
}, []);

document.body.innerHTML = '
' + JSON.stringify(result, null, '  ') + '
';

Body:
The Array.prototype and Object.prototype methods are perfect for this kind of thing.

And you're right that this is some complicated kind of logic.

I would suggest that you definitely need some unit tests for this, and try break in to separate pieces.

Here's how I'm thinking I'd do it.

1. Group By the type to create your groups..

I'm actually creating a more generic solution that you've asked for here. That is,  I'm not just grouping the 'acc-item', but everything.

I did a quick search for 'array group by javascript' and it gives us this answer which suggests using Array.reduce, so let's do that.

    const groupedData = contentData.data.content.reduce((acc, cur) => {
        //Check if this indexed array already exists, if not create it.
        const currentArray = (acc[`${cur.type}-group`] && acc[`${cur.type}-group`].items) || [];

        return {
          ...acc,
          [`${cur.type}-group`]: {
              type: `${cur.type}-group`,
              items: [...currentArray, cur]
          }
        }
    }, {});

2. Now for each of those items, we need to look at their subs, and group just the list items.

To do this, we basically want to find all the `item -> sections -> sub -> types and filter them into two arrays. A quick google on how to create two arrays using a filter gives me this answer.

First though, we need to flatten that sections-> subs thing, so lets just do that.

function flattenSectionsAndSubs(item) {
    return {
        type: item.type,
        subs: item.sections.reduce((acc, cur) => ([...acc, ...cur.sub]), [])
    };
}

And I'll just copy paste that partition function in:

function partition(array, isValid) {
  return array.reduce(([pass, fail], elem) => {
    return isValid(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]];
  }, [[], []]);
}

    const listTypes = ['ordered-item', 'unordered-item'];
    function createEmbeddedFromItem(item) {
        const [lists, nonLists] = partition(item.subs, (v) => listTypes.includes(v.type);

      return {
         type: item.type,
         embedded: [
             ...nonLists,
             {
                type: "list",
                items: lists
             }
         ]
      }
    }

Putting this all together and we get.

const contentData = {
  data: {
    content: [{
        type: "column",
        sections: [{
          sub: [{
            type: "heading-1",
            text: "Heading Text"
          }]
        }]
      },
      {
        type: "acc-item",
        sections: [{
          sub: [{
              type: "heading-1",
              text: "Heading Text"
            },
            {
              type: "ordered-item",
              text: "Item 1"
            },
            {
              type: "unordered-item",
              text: "Item 2"
            }
          ]
        }]
      },
      {
        type: "acc-item",
        sections: [{
          sub: [{
            type: "heading-1",
            text: "Heading Text 2"
          }]
        }]
      }
    ]
  }
}

function partition(array, isValid) {
  return array.reduce(([pass, fail], elem) => {
    return isValid(elem) ? [
      [...pass, elem], fail
    ] : [pass, [...fail, elem]];
  }, [
    [],
    []
  ]);
}

function flattenSectionsAndSubs(item) {
  return {
    type: item.type,
    subs: item.sections.reduce((acc, cur) => ([...acc, ...cur.sub]), [])
  };
}

const listTypes = ['ordered-item', 'unordered-item'];

function createEmbeddedFromItem(item) {
  const [lists, nonLists] = partition(item.subs, (v) => listTypes.includes(v.type));

    return {
      type: item.type,
      embedded: [
        ...nonLists,
        {
          type: "list",
          items: lists
        }
      ]
    }
  }

  const groupedData = contentData.data.content.reduce((acc, cur) => {
    //Check if this indexed array already exists, if not create it.
    const currentArray = (acc[`${cur.type}-group`] && acc[`${cur.type}-group`].items) || [];

    const flattenedItem = flattenSectionsAndSubs(cur);
    const embeddedItem = createEmbeddedFromItem(flattenedItem);
    return {
      ...acc,
      [`${cur.type}-group`]: {
          type: `${cur.type}-group`,
          items: [...currentArray, embeddedItem]
      }
    }
  }, {});

  console.log(groupedData);

Now this doesn't exactly match what you've asked for - but it should probably work.

You can add your own bits into only add a list item, if the array isn't empty, and to stop the column from being in its own group.

The thing is - tbh it seems like a little bit of a red flag that you would create an array of items that don't having matching structures, which is why I've done it this way.


问:
python multiprocessing workers till response 200
good day, I am new in python, i've tried my best to build code below:

```<code>import http.client
import random
import string
import multiprocessing

def worker():
    """worker function"""
    if res.status == 200:
        print("Valid key found: " + key + " Got status: ", + res.status)
    elif res.status == 302:
        print("invalid key! " + key + "!")
    return

def randomStringDigits(stringLength=6):
    """Generate a random string of letters and digits """
    lettersAndDigits = string.ascii_letters + string.digits
    return ''.join(random.choice(lettersAndDigits) for i in range(stringLength))

key = randomStringDigits(14);

conn = http.client.HTTPSConnection("www.pra1ser.com", timeout=10)

payload = "comment_text=%40asnikuwait1%20test2&replied_to_comment_id="

headers = {
    'cookie': "md5=5; prm_124024574287414=base_domain=api.pra1ser.com; csrftoken=5es0TEJiV6JOOjEzqyAfyeyN1FtnRIi1; session=CVzZzZz%3A" + key + "%3A8;",
    'x-csrftoken': "5es0TEJiV6JOOjEzqyAfyeyN1FtnRIi1",
    'content-type': "application/x-www-form-urlencoded"
    }

conn.request("POST", "/web/comments/2050815839087051573/add/", payload, headers)

res = conn.getresponse()
data = res.read()

#print(data.decode("utf-8"))
#print(headers)
#print(res.status)

if __name__ == '__main__':
    jobs = []
    for i in range(100):
        p = multiprocessing.Process(target=worker)
        jobs.append(p)
        p.start()
</code>```

I'd like to make it work multiprocessing with 100 workers infinite till it get response "200" from server, then it break.

I've tried while true, but i break the code, lot of errors. and i've tried to infinite loop but with failed attempt.

i wish somebody can helps me out please.

Thank you,
regards.
pra1

答:
When you are using multiprocess it is not necessary (and maybe could slow down the whole thing) to use a loop, the easiest way to implement the multiprocess you want would be with a with statement, I am not capable of trying this since I don't know the real site you are trying to get to but it should look something like this:

```<code>from concurrent.futures import ThreadPoolExecutor

...
...

def worker(con):
    """worker function"""
    while res.status != 200:
        res = conn.getresponse()
        if res.status == 200:
            return "Valid key found: " + key + " Got status: ", + res.status
        elif res.status == 302:
            print( "invalid key! " + key + "!")

...

with ThreadPoolExecutor(max_workers=100) as pool:
        results = pool.map(worker, res)

</code>```

Body:
good day, I am new in python, i've tried my best to build code below:

import http.client
import random
import string
import multiprocessing

def worker():
    """worker function"""
    if res.status == 200:
        print("Valid key found: " + key + " Got status: ", + res.status)
    elif res.status == 302:
        print("invalid key! " + key + "!")
    return

def randomStringDigits(stringLength=6):
    """Generate a random string of letters and digits """
    lettersAndDigits = string.ascii_letters + string.digits
    return ''.join(random.choice(lettersAndDigits) for i in range(stringLength))

key = randomStringDigits(14);

conn = http.client.HTTPSConnection("www.pra1ser.com", timeout=10)

payload = "comment_text=%40asnikuwait1%20test2&replied_to_comment_id="

headers = {
    'cookie': "md5=5; prm_124024574287414=base_domain=api.pra1ser.com; csrftoken=5es0TEJiV6JOOjEzqyAfyeyN1FtnRIi1; session=CVzZzZz%3A" + key + "%3A8;",
    'x-csrftoken': "5es0TEJiV6JOOjEzqyAfyeyN1FtnRIi1",
    'content-type': "application/x-www-form-urlencoded"
    }

conn.request("POST", "/web/comments/2050815839087051573/add/", payload, headers)

res = conn.getresponse()
data = res.read()

#print(data.decode("utf-8"))
#print(headers)
#print(res.status)

if __name__ == '__main__':
    jobs = []
    for i in range(100):
        p = multiprocessing.Process(target=worker)
        jobs.append(p)
        p.start()

I'd like to make it work multiprocessing with 100 workers infinite till it get response "200" from server, then it break.

I've tried while true, but i break the code, lot of errors. and i've tried to infinite loop but with failed attempt.

i wish somebody can helps me out please.

Thank you,
regards.
pra1

Body:
When you are using multiprocess it is not necessary (and maybe could slow down the whole thing) to use a loop, the easiest way to implement the multiprocess you want would be with a with statement, I am not capable of trying this since I don't know the real site you are trying to get to but it should look something like this:

from concurrent.futures import ThreadPoolExecutor

...
...

def worker(con):
    """worker function"""
    while res.status != 200:
        res = conn.getresponse()
        if res.status == 200:
            return "Valid key found: " + key + " Got status: ", + res.status
        elif res.status == 302:
            print( "invalid key! " + key + "!")

...

with ThreadPoolExecutor(max_workers=100) as pool:
        results = pool.map(worker, res)


问:
How yield works in Inorder traversal with recursive generator?
I am learning about recursive generators and found this program on web.

I undertand the recursive version of In-Order traversal but i am having trouble understanding recursive generator.

Specifically i am not able to understand

why 'yield x'  is written in for loop?

Why 'yield x' is not collected in final list?

I have tried to dubug the generator and added the watch but i found that recursive call execute multiple time 'yield x' and it's not collected in final result.

```<code>class Tree:
    def __init__(self, label, left=None, right=None):
        self.label = label
        self.left = left
        self.right = right

    def __repr__(self, level=0, indent="    "):
        s = level*indent + repr(self.label)
        if self.left:
            s = s + "\\n" + self.left.__repr__(level+1, indent)
        if self.right:
            s = s + "\\n" + self.right.__repr__(level+1, indent)
        return s

    def __iter__(self):
        return inorder(self)

def tree(list):
    n = len(list)
    if n == 0:
        return []
    i = n // 2
    return Tree(list[i], tree(list[:i]), tree(list[i + 1:]))

# Recursive Generator
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x
        yield t.label
        for x in inorder(t.right):
            yield x

</code>```

Role of yield x inside for loop.

答:
Maybe what you don't understand is how the generator works? The generator is different from the iterator, it is not directly calculating the worthy collection, it is dynamically getting all the values. If the result of inorder(t.left) is not traversed by a for loop, then yield inorder(t.left) will return the entire generator created for t.left. Because your entire inorder function is a generator.

Unfortunately, I have not been able to find a specific description document. This is a description based on my experience. Others are welcome to make corrections to my opinion. If someone can provide a specific official description, welcome to add

Body:
I am learning about recursive generators and found this program on web.

I undertand the recursive version of In-Order traversal but i am having trouble understanding recursive generator.

Specifically i am not able to understand

why 'yield x'  is written in for loop?

Why 'yield x' is not collected in final list?

I have tried to dubug the generator and added the watch but i found that recursive call execute multiple time 'yield x' and it's not collected in final result.

class Tree:
    def __init__(self, label, left=None, right=None):
        self.label = label
        self.left = left
        self.right = right

    def __repr__(self, level=0, indent="    "):
        s = level*indent + repr(self.label)
        if self.left:
            s = s + "\\n" + self.left.__repr__(level+1, indent)
        if self.right:
            s = s + "\\n" + self.right.__repr__(level+1, indent)
        return s

    def __iter__(self):
        return inorder(self)

def tree(list):
    n = len(list)
    if n == 0:
        return []
    i = n // 2
    return Tree(list[i], tree(list[:i]), tree(list[i + 1:]))

# Recursive Generator
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x
        yield t.label
        for x in inorder(t.right):
            yield x

Role of yield x inside for loop.


问:
How to push values to local storage?
I have the following code in js. if I use static array everything works fine. Else I get:

Uncaught TypeError: myArray.push is not a function

```<code>function test(){
var myArray =  localStorage.getItem('articles')  ;
//myArray=[1,4,5];
needle = 2    ,
myArray.push(needle);
localStorage.setItem('articles', JSON.stringify(myArray))
console.log(localStorage.getItem('articles'));
}
</code>```

答:
Since you're stringifying it, you need to parse it out of the string format to use push:

```<code>var myArray = JSON.parse(localStorage.getItem("articles"));
</code>```

Title: How to push values to local storage?

Body:
I have the following code in js. if I use static array everything works fine. Else I get:

Uncaught TypeError: myArray.push is not a function

function test(){
var myArray =  localStorage.getItem('articles')  ;
//myArray=[1,4,5];
needle = 2    ,
myArray.push(needle);
localStorage.setItem('articles', JSON.stringify(myArray))
console.log(localStorage.getItem('articles'));
}

Body:
Since you're stringifying it, you need to parse it out of the string format to use push:

var myArray = JSON.parse(localStorage.getItem("articles"));


问:
"No symbols have been loaded for this document." But they have!
As you can notice

Symbols are been correctly loaded.

I just created a view GetCompanies.cshtml using the AddView shortlink

But, no matter what I do, I can't debug in the View.

What I did so far:

Close and Open Solution

Close and open Visual Studio

Shutdown all ASP.NET Development Server's

Deleted all Symbol Libraries .pdb

Clean Solution

Re-Build Solution

did not (yet) shutdown Windows 7 x64 :-/

答:
I am finding the same behavior from time to time when debugging silverlight. My solution is to clean the browser's cache (on latest IE click on the wheel button, Developer tools), as it sometimes will cache the binary files and not load the new ones.

Perhaps is could be the same with your views?


问:
WeChat Mini-program: How to print log to console?
I'm trying to print variable in the console, For this I have the configuration below. the first method works fine, but not the second method containing an argument.

In index.wxml file, I have:

```<code><button onclick='test1'>Button 1</button>
<button onclick='test2("bar")'>Button 1</button>
</code>```

In index.js, I have:

```<code>Page({
  test1 {
    console.log('foo')
  },
  test2(v) {
    console.log('foo: ' + v)
  },
})
</code>```

What's wrong with the second method ?

答:
I know that it's been a while since you asked this question and maybe you don't need an answer anymore, but I ran into this problem too, so probably others will too.

Page is a function that takes a json object as input. So you should rewrite index.js like this:

Page({
  test1 : function() {
    console.log('foo')
  },
  test2 : function(v) {
    console.log('foo: ' + v)
  },
})
```

The documentation for the Page class is hard to find, and as far as I can tell, they haven't translated it. It exists here in Chinese.

Even though those are technically anonymous functions, you can use the keys of the json object in your wxml file as if they were functions. Your wxml file is basically right, but I'm not sure that onclick actually works. Try bindtap or bindchange.

This page has Tencent's english documentation of how to handle events in the WXML. I hope this helps someone!

Body:
I'm trying to print variable in the console, For this I have the configuration below. the first method works fine, but not the second method containing an argument.

In index.wxml file, I have:

<button onclick='test1'>Button 1</button>
<button onclick='test2("bar")'>Button 1</button>

In index.js, I have:

Page({
  test1 {
    console.log('foo')
  },
  test2(v) {
    console.log('foo: ' + v)
  },
})

What's wrong with the second method ?

Body:
I know that it's been a while since you asked this question and maybe you don't need an answer anymore, but I ran into this problem too, so probably others will too.

Page is a function that takes a json object as input. So you should rewrite index.js like this:

Page({
  test1 : function() {
    console.log('foo')
  },
  test2 : function(v) {
    console.log('foo: ' + v)
  },
})

The documentation for the Page class is hard to find, and as far as I can tell, they haven't translated it. It exists here in Chinese.

Even though those are technically anonymous functions, you can use the keys of the json object in your wxml file as if they were functions. Your wxml file is basically right, but I'm not sure that onclick actually works. Try bindtap or bindchange.

This page has Tencent's english documentation of how to handle events in the WXML. I hope this helps someone!


问:
Calculate the shortest decimal number that is approximated by a given float
The python floating point docs (eg https://docs.python.org/3/tutorial/floatingpoint.html) state

Interestingly, there are many different decimal numbers that share the same nearest approximate binary fraction. For example, the numbers 0.1 and 0.10000000000000001 and 0.1000000000000000055511151231257827021181583404541015625 are all approximated by 3602879701896397 / 2 ** 55. Since all of these decimal values share the same approximation, any one of them could be displayed while still preserving the invariant eval(repr(x)) == x.

Historically, the Python prompt and built-in repr() function would choose the one with 17 significant digits, 0.10000000000000001. Starting with Python 3.1, Python (on most systems) is now able to choose the shortest of these and simply display 0.1.

Is there a way I can get that shortest representation as a decimal.Decimal (or other exact representation)?

Obviously one way would be decimal.Decimal(repr(0.1)) but I'm wondering if there is something explicit that doesn't rely on the vague "on most systems" caveat and possibly is available as a package that would work with earlier version of python.

(Also, functions that do this in other languages may be of interest if there is nothing in python, as this is really a general floating point question)

答:
The following may be useful:

Python provides PyOS_double_to_string, but the code comment  says this is only used if _Py_dg_dtoa is not available.

_Py_dg_dtoa is available in the source but I'm not sure if it can be accessed publicly. (In particular, it would be nice if there was a way to 'prove' that a the python interpreter we are using is using this internally). This function has detailed documentation about the way the string conversion is done, and it explains which flags to use to get the shortest decimal representation. If this was available from the interpreter this might be the best option as using it directly would give certainty about what was happening.

The implementation of Errol can be found on git and the paper found here has references to many other implementations along with a summary of their pros and cons.

Any one of the float -> string methods mentioned above would be a reasonable way to proceed, as would the standard repr method but it will require digging into the implementation details to be sure that a particular method guarantees to give you what you a looking for.


问:
Are there any better ways to check this condition in Java 8?
I need to simplify following code in java.  Are there any way to using set and do this ?</p>

```<code>      if (!(((AdministrativeState.PLANNED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.MISSED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.SKIPPED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.SELF_ADMINISTERED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
(AdministrativeState.SELF_ADMINISTERED_BY_RANGE == dispensingOccasionModel.getOccasionDTO().getAdminState())) &&
        isSpecialDoseType(doseDetail))
</code>```

答:
Using Set, you can initialize the valid enum types and perform a contains as @shmosel also pointed out in the comments :

```<code>Set<AdministrativeState> administrativeStates = Set.of(PLANNED, MISSED, SKIPPED, SELF_ADMINISTERED, SELF_ADMINISTERED_BY_RANGE)
if (!administrativeStates.contains(dispensingOccasionModel.getOccasionDTO().getAdminState())
        || !isSpecialDoseType(doseDetail))
</code>```

Body:
I need to simplify following code in java.  Are there any way to using set and do this ?

      if (!(((AdministrativeState.PLANNED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.MISSED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.SKIPPED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.SELF_ADMINISTERED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
(AdministrativeState.SELF_ADMINISTERED_BY_RANGE == dispensingOccasionModel.getOccasionDTO().getAdminState())) &&
        isSpecialDoseType(doseDetail))

Body:
Using Set, you can initialize the valid enum types and perform a contains as @shmosel also pointed out in the comments :

Set<AdministrativeState> administrativeStates = Set.of(PLANNED, MISSED, SKIPPED, SELF_ADMINISTERED, SELF_ADMINISTERED_BY_RANGE)
if (!administrativeStates.contains(dispensingOccasionModel.getOccasionDTO().getAdminState())
        || !isSpecialDoseType(doseDetail))


问:
ConnectionRefusedError when trying to connect to Gremlin Server using Python
I am trying to use gremlin with python with gremlinpython package. I am getting the following error. Can anyone tell me how to solve this ? Any help is appreciated.        </p>

```<code>Traceback (most recent call last):
      File "C:/Users/Yash/IdeaProjects/new/gremlin.py", line 10, in <module>
        g = graph.traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g'))
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\driver_remote_connection.py", line 45, in __init__
        password=password)
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\client.py", line 76, in __init__
        self._fill_pool()
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\client.py", line 88, in _fill_pool
        conn = self._get_connection()
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\client.py", line 101, in _get_connection
        self._transport_factory, self._executor, self._pool)
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\connection.py", line 40, in __init__
        self.connect()
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\connection.py", line 46, in connect
        self._transport.connect(self._url)
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\tornado\transport.py", line 33, in connect
        lambda: websocket.websocket_connect(url))
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tornado\ioloop.py", line 458, in run_sync
        return future_cell[0].result()
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tornado\concurrent.py", line 238, in result
        raise_exc_info(self._exc_info)
      File "<string>", line 4, in raise_exc_info
    ConnectionRefusedError: [Errno 10061] Unknown error
</code>```

答: check your configration,set the host as ip not hostname</p>

Body:
I am trying to use gremlin with python with gremlinpython package. I am getting the following error. Can anyone tell me how to solve this ? Any help is appreciated.

Traceback (most recent call last):
      File "C:/Users/Yash/IdeaProjects/new/gremlin.py", line 10, in <module>
        g = graph.traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g'))
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\driver_remote_connection.py", line 45, in __init__
        password=password)
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\client.py", line 76, in __init__
        self._fill_pool()
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\client.py", line 88, in _fill_pool
        conn = self._get_connection()
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\client.py", line 101, in _get_connection
        self._transport_factory, self._executor, self._pool)
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\connection.py", line 40, in __init__
        self.connect()
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\connection.py", line 46, in connect
        self._transport.connect(self._url)
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gremlin_python\driver\tornado\transport.py", line 33, in connect
        lambda: websocket.websocket_connect(url))
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tornado\ioloop.py", line 458, in run_sync
        return future_cell[0].result()
      File "C:\Users\Yash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tornado\concurrent.py", line 238, in result
        raise_exc_info(self._exc_info)
      File "<string>", line 4, in raise_exc_info
    ConnectionRefusedError: [Errno 10061] Unknown error


问:
how format date to multiple fields in the model in the rails app?
I have a form in rails that has a date field with input mask with format mm/dd/yyyy, but at the moment to save it, I am getting an error because of the format in the model is dd/mm/yyyy. I found a solution that maybe can work.

```<code> def organization_date=(val)
   date = Date.strptime(val, “%m/%d/%Y”) if val.present?
   write_attribute(:organization_date, date)
 end
</code>```

but I need one solution more elegant because I have more field of type date, and I can't do that for each field and updating the format to input mask to dd/mm/yyyy is not an option either because the client's requirement is that it be in the format mm/dd/yyyy

I am using Rails 6.0 beta

I'm grateful for any ideas that help solve this problem

答:
In your config/initializers/ create date_format.rb:

```<code># Date
Date::DATE_FORMATS[:default] = "%m/%d/%Y"
</code>```

Then restart the rails server..

Body:
I have a form in rails that has a date field with input mask with format mm/dd/yyyy, but at the moment to save it, I am getting an error because of the format in the model is dd/mm/yyyy. I found a solution that maybe can work.

 def organization_date=(val)
   date = Date.strptime(val, “%m/%d/%Y”) if val.present?
   write_attribute(:organization_date, date)
 end

but I need one solution more elegant because I have more field of type date, and I can't do that for each field and updating the format to input mask to dd/mm/yyyy is not an option either because the client's requirement is that it be in the format mm/dd/yyyy

I am using Rails 6.0 beta

I'm grateful for any ideas that help solve this problem

Body:
In your config/initializers/ create date_format.rb:

# Date
Date::DATE_FORMATS[:default] = "%m/%d/%Y"

Then restart the rails server..


问:
Unable to use chromedriver in Selenium after providing path of chrome driver
import option is not displaying

I have provided the chromedriver path but I am unable import
"import org.openqa.selenium.chrome.ChromeDriver;" this command. Please provide a solution

答: You need to add selenium jars before you try to execute any selenium script.  It seems you only added java jars. </p>


问:
How to filter number and string in object array
i want to filter employee details.. in that i have select option containing both number and string... i can filter string in the object but cant make it number... please guide me</p>

```<code>        <select id="endDate" onchange="sortEDate()">
            <option value="All Years">All Years</option>
            <option value="Past Years">Past Years</option>
            <option value="Present">Present</option>
        </select>
        <p id="demo1"></p>
</code>```

```<code>const employees = [
    { firstname: "Dav", start: 2013, end: 2018 },
    { firstname: "Gemmy", start: 2016, end: "Present" }
]
function sortEDate() {
    const filterDate = [];
    let cDate = document.getElementById("endDate").value;
    employees.forEach(function(item, index, array) {
        if (item.end === cDate) {
            filterDate.push(item);
        }
    });

    let fDate = "<table>";
    filterDate.forEach(function(filterDate) {
        fDate += "<tr>";
        fDate += "<td>" + filterDate.firstname + "</td>";
        fDate += "<td>" + filterDate.start + "</td>";
        fDate += "<td>" + filterDate.end + "</td>";
        fDate += "</tr>";
    });
    fDate += "</table>";
    document.getElementById("demo1").innerHTML = fDate;

    let allEducation = document.getElementById("endDate").value;
    if (allEducation === "All Years") {
        showEmployees();
    }
}
</code>```

答:
I made some changes to make this work as expected. I used label as well as value for the option elements as well as passed the actual selected value to the select onchange handler. Also I loaded the items on load on the body which you can remove I just wanted them to be loaded when the page loads etc. Since you are not using jQuery it is on the onload event handler etc.

const employees = [{
    firstname: "Dav",
    start: 2013,
    end: 2018
  },
  {
    firstname: "Gemmy",
    start: 2016,
    end: "Present"
  }
]

function filterDates(sel) {
  let filterDate = []
  sel = sel || "All"
  filterDate.push(...employees.filter(function(obj) {
    switch (sel) {
      case "All":
        return true  // return all
      case "Past":
        return obj.end < new Date().getFullYear() // just past years
      case "Present":
        return obj.end === 'Present'
    }
  }))

  let fDate = "
";
  filterDate.forEach(function(filterDate) {
    fDate += "
";
    fDate += "" + filterDate.firstname + "	";
    fDate += "" + filterDate.start + "	";
    fDate += "" + filterDate.end + "	";
    fDate += "
";
  });
  fDate += "
";
  document.getElementById("demo1").innerHTML = fDate;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body onload="filterDates()">
  <select id="endDate" onchange="filterDates(this.value);">
    <option label="All Years" value="All">All Years</option>
    <option label="Past Years" value="Past">Past Years</option>
    <option label="Present" value="Present">Present</option>
  </select>
  <p id="demo1"></p>
  <body/></code>```

The key is the filtering which I did not want to change too much so I left how you ware doing it for the most part with the exception that now it uses Array.filter and a switch internally to know how to filter based on the selected option.

Body:
i want to filter employee details.. in that i have select option containing both number and string... i can filter string in the object but cant make it number... please guide me

        <select id="endDate" onchange="sortEDate()">
            <option value="All Years">All Years</option>
            <option value="Past Years">Past Years</option>
            <option value="Present">Present</option>
        </select>

const employees = [
    { firstname: "Dav", start: 2013, end: 2018 },
    { firstname: "Gemmy", start: 2016, end: "Present" }
]
function sortEDate() {
    const filterDate = [];
    let cDate = document.getElementById("endDate").value;
    employees.forEach(function(item, index, array) {
        if (item.end === cDate) {
            filterDate.push(item);
        }
    });

    let fDate = "
";
    filterDate.forEach(function(filterDate) {
        fDate += "
";
        fDate += "" + filterDate.firstname + "	";
        fDate += "" + filterDate.start + "	";
        fDate += "" + filterDate.end + "	";
        fDate += "
";
    });
    fDate += "
";
    document.getElementById("demo1").innerHTML = fDate;

    let allEducation = document.getElementById("endDate").value;
    if (allEducation === "All Years") {
        showEmployees();
    }
}

Body:
I made some changes to make this work as expected. I used label as well as value for the option elements as well as passed the actual selected value to the select onchange handler. Also I loaded the items on load on the body which you can remove I just wanted them to be loaded when the page loads etc. Since you are not using jQuery it is on the onload event handler etc.

const employees = [{
    firstname: "Dav",
    start: 2013,
    end: 2018
  },
  {
    firstname: "Gemmy",
    start: 2016,
    end: "Present"
  }
]

function filterDates(sel) {
  let filterDate = []
  sel = sel || "All"
  filterDate.push(...employees.filter(function(obj) {
    switch (sel) {
      case "All":
        return true  // return all
      case "Past":
        return obj.end < new Date().getFullYear() // just past years
      case "Present":
        return obj.end === 'Present'
    }
  }))

  let fDate = "<table>";
  filterDate.forEach(function(filterDate) {
    fDate += "<tr>";
    fDate += "<td>" + filterDate.firstname + "</td>";
    fDate += "<td>" + filterDate.start + "</td>";
    fDate += "<td>" + filterDate.end + "</td>";
    fDate += "</tr>";
  });
  fDate += "</table>";
  document.getElementById("demo1").innerHTML = fDate;
}

<body onload="filterDates()">
  <select id="endDate" onchange="filterDates(this.value);">
    <option label="All Years" value="All">All Years</option>
    <option label="Past Years" value="Past">Past Years</option>
    <option label="Present" value="Present">Present</option>
  </select>
  <p id="demo1"></p>
  <body/>

The key is the filtering which I did not want to change too much so I left how you ware doing it for the most part with the exception that now it uses Array.filter and a switch internally to know how to filter based on the selected option.


问:
How to collect turbine stream from a Standalone Turbine Stream application
Similar with this post, I created another turbine stream based application to collect hystrix stream from other applications.

Spring Boot: 2.0.4.RELEASE, Spring Cloud: Finchley.SR1

The application class:

```<code>@SpringBootApplication
@EnableDiscoveryClient
@EnableTurbineStream
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
</code>```

The maven dependencies:

```<code><dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-turbine-stream</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
</code>```

The application config file is:

```<code>server:
  port: 8989
spring:
  application:
    name: hystrix-turbine-stream

management:
  endpoints:
    web.exposure.include: '*'
</code>```

When I explore the source codes of @EanbleTurbineStream, and found TurbineController expose a Flux to the  root '/' endpiont.

But when I tried to explore http://localhost:8989 in the Hystrix Dashboard, found it did not work as expected.

Update: When I tried to access the turbine stream application, and got:

```<code>curl http://localhost:8989
data:{"type":"ping"}

data:{"type":"ping"}

data:{"type":"ping"}

data:{"type":"ping"}
</code>```

In the application console(logging), there is some log shown as:

```<code>: Registering MessageChannel turbineStreamInput
</code>```

But I can not see the there are some message sent to this channel in my client app.

Here is the sample codes of my turbine stream application

Update2: Got it worked, I used a outdated spring-cloud-starter-netflix-hystrix-stream (which is existed in v2.0.0M2, but not existed in the final RELEASE version) in my client app, when I used  spring-cloud-starter-netflix-hystrix and spring-cloud-netflix-hystrix-stream combination in the client app, it worked well.

答: You should set properties on client app project: spring.cloud.stream.bindings.hystrixStreamOutput.destination=springCloudHystrixStream

Body:
Similar with this post, I created another turbine stream based application to collect hystrix stream from other applications.

Spring Boot: 2.0.4.RELEASE, Spring Cloud: Finchley.SR1

The application class:

@SpringBootApplication
@EnableDiscoveryClient
@EnableTurbineStream
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

The maven dependencies:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-turbine-stream</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

The application config file is:

server:
  port: 8989
spring:
  application:
    name: hystrix-turbine-stream

management:
  endpoints:
    web.exposure.include: '*'

When I explore the source codes of @EanbleTurbineStream, and found TurbineController expose a Flux to the  root '/' endpiont.

But when I tried to explore http://localhost:8989 in the Hystrix Dashboard, found it did not work as expected.

Update: When I tried to access the turbine stream application, and got:

curl http://localhost:8989
data:{"type":"ping"}

data:{"type":"ping"}

data:{"type":"ping"}

data:{"type":"ping"}

In the application console(logging), there is some log shown as:

: Registering MessageChannel turbineStreamInput

But I can not see the there are some message sent to this channel in my client app.

Here is the sample codes of my turbine stream application

Update2: Got it worked, I used a outdated spring-cloud-starter-netflix-hystrix-stream (which is existed in v2.0.0M2, but not existed in the final RELEASE version) in my client app, when I used  spring-cloud-starter-netflix-hystrix and spring-cloud-netflix-hystrix-stream combination in the client app, it worked well.


问:
white text stand out in the grey background
I have a div tag with background-color: #FFFFFF and opacity: 0.08. Inside it is a span tag with the colour white. What can I do to make the white text stand out in the grey background in the parent div? It seems that i cannot increase parent's opacity

答:
Or you should be able to get this effect by using rgba() notation:

div{
  background-color: rgba(255, 255, 255, 0.08);
}

span {
  color: #fff;
}
```


问:
Image : Dynamic path for local images
Beginner with React Native here.

I'm working on a small App which needs to display an image according to a random number. For exemple if I got 203, I want to display the image Project/img/203.png (random number is between 1 and 726)

The first thing I tried was require(dynamicPath), after reading documentation I understood that was not a good way to do it and I don't want to require each 726 image staticly.
Then I tried with the uri syntax :

//Executed from Project/components/ folder
loadImage(number){
  imgUri = '../img/'+number.toString()+'.png'
  return(
    <Image source={{uri: imgUri}} />
)
```

The application does launch but there is no image displayed (even with height/width style set).
Examples I had seen with uri syntax were about images recieved from a web URL so I'm not sure it allows to get it from a local storage, but i can not find another way to get the image.

答:
Switch case is garbage.
Use template literals.</p>

```<code>loadImage(number){
  imgPath = `../img/${number.toString()}.png`
  return(
    <Image source={require(imgPath)} />
)
</code>```

Title: Image : Dynamic path for local images

Body:
Beginner with React Native here.

I'm working on a small App which needs to display an image according to a random number. For exemple if I got 203, I want to display the image Project/img/203.png (random number is between 1 and 726)

The first thing I tried was require(dynamicPath), after reading documentation I understood that was not a good way to do it and I don't want to require each 726 image staticly.
Then I tried with the uri syntax :

//Executed from Project/components/ folder
loadImage(number){
  imgUri = '../img/'+number.toString()+'.png'
  return(
    <Image source={{uri: imgUri}} />
)

The application does launch but there is no image displayed (even with height/width style set).
Examples I had seen with uri syntax were about images recieved from a web URL so I'm not sure it allows to get it from a local storage, but i can not find another way to get the image.

Body:
Switch case is garbage.
Use template literals.

loadImage(number){
  imgPath = `../img/${number.toString()}.png`
  return(
    <Image source={require(imgPath)} />
)