问:
How to achieved multiple nested screens
Having trouble with my StackNavigator with two another screens in the nested, below are the nested stack I want to achieve.

```<code>Items
-Help (already achieve this nested)
    -Help Details
-Topup
    -Topup Details
-Services (I want to achieve something like this);
    -Service name (Babysitting)
        -service name details (Babysitting details)
</code>```

This is ony my DashboardNavigator

```<code>function DashboardNavigator() {
    return (
        <StackDashboard.Navigator initialRouteName="Dashboard">
            <StackDashboard.Screen name="Topup" component={TopupStack} options={navOptionHandler} />
            <StackDashboard.Screen name="Services" component={ServicesStack} options={navOptionHandler} />
            <StackDashboard.Screen name="BabySitting" component={BabySittingStack} options={navOptionHandler} />
        </StackDashboard.Navigator>
    )
}

function BabySittingStack() {
    <StackBabySitting.Navigator initialRouteName="BabySitting">
        <StackBabySitting.Screen name="BabySitting" component={BabySitting} options={navOptionHandler} />
        <StackBabySitting.Screen name="BabySittingDetails" component={BabySittingDetails} options={navOptionHandler} />
    </StackBabySitting.Navigator>
}

function ServicesStack() {
    return (
        <StackServices.Navigator initialRouteName="Services">
            <StackServices.Screen name="Services" component={Services} options={navOptionHandler} />
            <StackServices.Screen name="BabySitting" component={BabySittingStack} options={navOptionHandler} />
        </StackServices.Navigator>
    )
}
</code>```

This will be my screen that will go to my details screen

```<code><SafeAreaView>
            <TouchableOpacity style={styles.item} onPress={() => navigation.navigate('BabySittingDetails')}>
                <Text style={styles.title}>BabySitting</Text>
                <Image
                    style={styles.imageItem}
                    source={IMAGE.ICON_NEXT} resizeMode="contain" />
            </TouchableOpacity>
        </SafeAreaView>
</code>```

答:
I'm not sure this is your problem but BabySittingDetails is accessible in BabySittingStack. BabySittingStack and ServicesStack are at the same level, so you can't access babySittingdetails like that. You can test to move your BabySittingComponent inside your ServicesStack.

But I don't think you should get this kind of error with your current navigation architecture. If it does not solve your problem then please show us your BabySittingDetails component entirely and eventually reproduce your problem on a snack expo. You can use this boilerplate to reproduce your problem (ios is working fine as well as web, android have some trouble with stylesheet i don't know why).

Title: How to achieved multiple nested screens

Body:
Having trouble with my StackNavigator with two another screens in the nested, below are the nested stack I want to achieve.

Items
-Help (already achieve this nested)
    -Help Details
-Topup
    -Topup Details
-Services (I want to achieve something like this);
    -Service name (Babysitting)
        -service name details (Babysitting details)

This is ony my DashboardNavigator

function DashboardNavigator() {
    return (
        <StackDashboard.Navigator initialRouteName="Dashboard">
            <StackDashboard.Screen name="Topup" component={TopupStack} options={navOptionHandler} />
            <StackDashboard.Screen name="Services" component={ServicesStack} options={navOptionHandler} />
            <StackDashboard.Screen name="BabySitting" component={BabySittingStack} options={navOptionHandler} />
        </StackDashboard.Navigator>
    )
}

function BabySittingStack() {
    <StackBabySitting.Navigator initialRouteName="BabySitting">
        <StackBabySitting.Screen name="BabySitting" component={BabySitting} options={navOptionHandler} />
        <StackBabySitting.Screen name="BabySittingDetails" component={BabySittingDetails} options={navOptionHandler} />
    </StackBabySitting.Navigator>
}

function ServicesStack() {
    return (
        <StackServices.Navigator initialRouteName="Services">
            <StackServices.Screen name="Services" component={Services} options={navOptionHandler} />
            <StackServices.Screen name="BabySitting" component={BabySittingStack} options={navOptionHandler} />
        </StackServices.Navigator>
    )
}

This will be my screen that will go to my details screen

<SafeAreaView>
            <TouchableOpacity style={styles.item} onPress={() => navigation.navigate('BabySittingDetails')}>
                <Text style={styles.title}>BabySitting</Text>
                <Image
                    style={styles.imageItem}
                    source={IMAGE.ICON_NEXT} resizeMode="contain" />
            </TouchableOpacity>
        </SafeAreaView>


来源: stackexchange

问:
How to apply shadow to interior views in SwiftUI?
I have added a shadow around the VStack that holds my two text fields and a submit button. However, the shadow is also being applied to the two text fields inside the VStack.

Is there something I am missing here that is causing this to happen? I tried adding shadow(radius: 0) on the text fields, but it doesn't change anything. If I remove the padding and background from the text fields, then the shadow goes away.

var body: some View {
    VStack() {
        Spacer()

        VStack() {
            TextField($email, placeholder: Text("email"))
                .padding()
                .background(Color(red: 242 / 255, green: 242 / 255, blue: 242 / 255))

            SecureField($password, placeholder: Text("password"))
                .padding()
                .background(Color(red: 242 / 255, green: 242 / 255, blue: 242 / 255))

            Button(action: { self.login() }, label: { Text("Login").foregroundColor(Color.white) })
                .padding()
                .background(Color(red: 0, green: 116 / 255, blue: 217 / 255))
        }
        .padding()
        .background(Color.white)
        .shadow(radius: 10)

        Spacer()
    }
    .padding()
    .background(Color(red: 0, green: 116 / 255, blue: 217 / 255))
    .edgesIgnoringSafeArea(.all)
}
```

答:
For the user's who are struggling to have this work for RoundedRectangle, use:

```<code>HStack {
 // Your nested views
}
.overlay(
  RoundedRectangle(cornerRadius: 10)
   .stroke(Color.black.opacity(0.2), lineWidth: 1)
)
.background(
   RoundedRectangle(
     cornerRadius: 10
   )
   .foregroundColor(Color.white)
   .shadow(
     color: Color.black,
     radius: 5,
     x: 0,
     y: 0
   )
)
</code>```

The shadow is applied in the .background, RoundedRectagle element shadow.

While quite verbose, it's easy to read and the same principle can be applied to and from any other shape.

ContentLicense: CC BY-SA 4.0

Body:
For the user's who are struggling to have this work for RoundedRectangle, use:

HStack {
 // Your nested views
}
.overlay(
  RoundedRectangle(cornerRadius: 10)
   .stroke(Color.black.opacity(0.2), lineWidth: 1)
)
.background(
   RoundedRectangle(
     cornerRadius: 10
   )
   .foregroundColor(Color.white)
   .shadow(
     color: Color.black,
     radius: 5,
     x: 0,
     y: 0
   )
)

The shadow is applied in the .background, RoundedRectagle element shadow.

While quite verbose, it's easy to read and the same principle can be applied to and from any other shape.


问:
Changing an image with AJAX and Flask
I have an image file in HTML that I am trying to update with different images that come in, specifically the latest.
Here is the Flask Code:

```<code>@app.route('/uploads/update_file',  methods=['GET', 'POST'])
def update_file():
    print('update_file')
    list_of_files = glob.glob(staging_dir+'/*.jpg')
    if len(list_of_files) == 0:
        latest_file = ''
    latest_file = max(list_of_files, key=os.path.getctime)
    print('latest '+latest_file)
    splits = latest_file.split('/')
    file = splits[-1]
    return send_from_directory(directory=staging_dir, filename=file)
</code>```

In the java script I have:

```<code>  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>
       setInterval(ajaxCall,5000);

     function ajaxCall()
      {
          $.ajax({
                    type : 'GET',
                    url : "{{url_for('update_file')}}",
                    async: false,
                    success: function(data) {
                        document.getElementById("img").src = data;
                    },
                 });
      }
</script>
</code>```

What I see is update_file() gets called but send_from_directory never seems to return.  I assume so because update_file is only called once.  Any idea what is wrong or is this even the preferred way about going about this?

答:
Ok, so here is quick solution that does not make use of send_from_directory(), but it works.

I am basically using the same same code you have in your post. Removed the logic to check for the latest file( to keep this demo simple ).

```<code>@app.route('/uploads/update_file',  methods=['GET', 'POST'])
def update_file():
    item = ["static/img/"+item for item in os.listdir("static/img")]
    return random.choice(item)
</code>```

This is my folder structure :

This is the output:

Let me know if that works for you

Title: Changing an image with AJAX and Flask

Body:
I have an image file in HTML that I am trying to update with different images that come in, specifically the latest.
Here is the Flask Code:

@app.route('/uploads/update_file',  methods=['GET', 'POST'])
def update_file():
    print('update_file')
    list_of_files = glob.glob(staging_dir+'/*.jpg')
    if len(list_of_files) == 0:
        latest_file = ''
    latest_file = max(list_of_files, key=os.path.getctime)
    print('latest '+latest_file)
    splits = latest_file.split('/')
    file = splits[-1]
    return send_from_directory(directory=staging_dir, filename=file)

In the java script I have:

What I see is update_file() gets called but send_from_directory never seems to return.  I assume so because update_file is only called once.  Any idea what is wrong or is this even the preferred way about going about this?

Body:
Ok, so here is quick solution that does not make use of send_from_directory(), but it works.

I am basically using the same same code you have in your post. Removed the logic to check for the latest file( to keep this demo simple ).

@app.route('/uploads/update_file',  methods=['GET', 'POST'])
def update_file():
    item = ["static/img/"+item for item in os.listdir("static/img")]
    return random.choice(item)

This is my folder structure :

This is the output:

Let me know if that works for you


问:
In Python, how can I combine a set of tuples from a list of given tuples without using itertools?
Given a list as follows:

[(1, 2), (3, 4, 5), (6,)]

I know it's very easy to combine the list of tuples by using itertools.

(1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 3, 6), (2, 4, 6), (2, 5, 6)

But how can I solve it without using itertools?

答:
```<code> [(x, y, 6) for x in (1, 2) for y in (3, 4, 5)]
</code>```

Also see Get the cartesian product of a series of lists? for more general solutions

Body:
 [(x, y, 6) for x in (1, 2) for y in (3, 4, 5)]

Also see Get the cartesian product of a series of lists? for more general solutions


问:
Min, Max, Average of n distinct top/low values and plotting them with time series data on the same graph in R
I am dealing with a large time series data set (with almost 100K records) with unix timestamp. I need min, mean, max, avg_of_lowest_n, avg_of_top_n from the value column. I can get min, mean, max as follows:

```<code>tapply(df$value, df$pattern, min)
tapply(df$value, df$pattern, mean)
tapply(df$value, df$pattern, max)
</code>```

Now, I need to get the mean of the lowest n distinct values and top n distinct values in two other columns for each pattern (group). I can get the mean of the lowest and top n (say 5 values) from the following, but I think the mean is not calculated by distinct 5 values for each group (pattern), and here I need to know, how can I do that.

```<code>setDT(df_stat) #requires Data.table
df_n[order(value)][, list(mean_of_low_5=mean(value[1:5])), by=pattern]
df_n[order(-value)][, list(mean_of_top_5=mean(value[1:5])), by=pattern]
</code>```

Any simple way of doing this is highly appreciated.

Sample data-

```<code>df <- structure(list(pattern = c(462L, 462L, 462L, 462L, 462L, 462L,
462L, 462L, 462L, 462L, 462L, 463L, 463L, 463L, 463L, 463L, 463L,
463L, 463L, 463L, 463L, 463L, 463L, 463L, 463L, 464L, 464L, 464L,
464L, 464L, 464L, 464L, 464L, 464L, 464L, 464L, 464L, 464L, 465L,
465L, 465L, 465L, 465L, 466L, 466L, 466L, 466L, 466L, 466L, 466L,
466L, 466L, 466L, 466L, 466L, 961L, 961L, 961L, 961L, 961L, 961L,
961L), value = c(5.8e+10, 4.35e+10, 3.96e+10, 3.6e+10, 3.48e+10,
3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 1e+09,
1e+09, 1e+09, 1e+09, 1e+09, 1e+09, 1e+09, 1e+09, 1e+09, 1e+09,
1e+09, 1e+09, 1e+09, 1e+09, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10,
3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10,
3.3e+10, 3.3e+10, 3e+10, 3e+10, 3e+10, 3e+10, 3e+10, 3.3e+10,
3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10,
3.3e+10, 3.2e+10, 3.2e+10, 3.2e+10, 2.6e+10, 2.6e+10, 2.6e+10,
2.6e+10, 2.6e+10, 2.6e+10, 2.6e+10), timestamp = c(1590604157L,
1590604157L, 1590604157L, 1590604157L, 1590604157L, 1590604157L,
1590604157L, 1590604157L, 1590604157L, 1590604157L, 1590604157L,
1590604170L, 1590604170L, 1590604170L, 1590604170L, 1590604170L,
1590604170L, 1590604170L, 1590604170L, 1590604170L, 1590604170L,
1590604170L, 1590604170L, 1590604170L, 1590604170L, 1590604213L,
1590604213L, 1590604213L, 1590604213L, 1590604213L, 1590604213L,
1590604213L, 1590604213L, 1590604213L, 1590604213L, 1590604213L,
1590604213L, 1590604213L, 1590604226L, 1590604226L, 1590604226L,
1590604226L, 1590604226L, 1590604239L, 1590604239L, 1590604239L,
1590604239L, 1590604239L, 1590604239L, 1590604239L, 1590604239L,
1590604239L, 1590604239L, 1590604239L, 1590604239L, 1590610895L,
1590610895L, 1590610895L, 1590610895L, 1590610895L, 1590610895L,
1590610895L)), class = "data.frame", row.names = c(NA, -62L))
</code>```

答:
You can do all the calculation in one pipe using dplyr :

```<code>library(dplyr)

df %>%
  group_by(pattern) %>%
  summarise(min_val = min(value),
            max_val = max(value),
            mean_val = mean(value),
            lowest_n_val = mean(head(unique(sort(value)), 5)),
            highest_n_val = mean(tail(unique(sort(value)), 5)))
</code>```

You can add na.rm. =TRUE in all the above functions if you have NA in your data.

Body:
I am dealing with a large time series data set (with almost 100K records) with unix timestamp. I need min, mean, max, avg_of_lowest_n, avg_of_top_n from the value column. I can get min, mean, max as follows:

tapply(df$value, df$pattern, min)
tapply(df$value, df$pattern, mean)
tapply(df$value, df$pattern, max)

Now, I need to get the mean of the lowest n distinct values and top n distinct values in two other columns for each pattern (group). I can get the mean of the lowest and top n (say 5 values) from the following, but I think the mean is not calculated by distinct 5 values for each group (pattern), and here I need to know, how can I do that.

setDT(df_stat) #requires Data.table
df_n[order(value)][, list(mean_of_low_5=mean(value[1:5])), by=pattern]
df_n[order(-value)][, list(mean_of_top_5=mean(value[1:5])), by=pattern]

Any simple way of doing this is highly appreciated.

Sample data-

df <- structure(list(pattern = c(462L, 462L, 462L, 462L, 462L, 462L,
462L, 462L, 462L, 462L, 462L, 463L, 463L, 463L, 463L, 463L, 463L,
463L, 463L, 463L, 463L, 463L, 463L, 463L, 463L, 464L, 464L, 464L,
464L, 464L, 464L, 464L, 464L, 464L, 464L, 464L, 464L, 464L, 465L,
465L, 465L, 465L, 465L, 466L, 466L, 466L, 466L, 466L, 466L, 466L,
466L, 466L, 466L, 466L, 466L, 961L, 961L, 961L, 961L, 961L, 961L,
961L), value = c(5.8e+10, 4.35e+10, 3.96e+10, 3.6e+10, 3.48e+10,
3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 1e+09,
1e+09, 1e+09, 1e+09, 1e+09, 1e+09, 1e+09, 1e+09, 1e+09, 1e+09,
1e+09, 1e+09, 1e+09, 1e+09, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10,
3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10,
3.3e+10, 3.3e+10, 3e+10, 3e+10, 3e+10, 3e+10, 3e+10, 3.3e+10,
3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10, 3.3e+10,
3.3e+10, 3.2e+10, 3.2e+10, 3.2e+10, 2.6e+10, 2.6e+10, 2.6e+10,
2.6e+10, 2.6e+10, 2.6e+10, 2.6e+10), timestamp = c(1590604157L,
1590604157L, 1590604157L, 1590604157L, 1590604157L, 1590604157L,
1590604157L, 1590604157L, 1590604157L, 1590604157L, 1590604157L,
1590604170L, 1590604170L, 1590604170L, 1590604170L, 1590604170L,
1590604170L, 1590604170L, 1590604170L, 1590604170L, 1590604170L,
1590604170L, 1590604170L, 1590604170L, 1590604170L, 1590604213L,
1590604213L, 1590604213L, 1590604213L, 1590604213L, 1590604213L,
1590604213L, 1590604213L, 1590604213L, 1590604213L, 1590604213L,
1590604213L, 1590604213L, 1590604226L, 1590604226L, 1590604226L,
1590604226L, 1590604226L, 1590604239L, 1590604239L, 1590604239L,
1590604239L, 1590604239L, 1590604239L, 1590604239L, 1590604239L,
1590604239L, 1590604239L, 1590604239L, 1590604239L, 1590610895L,
1590610895L, 1590610895L, 1590610895L, 1590610895L, 1590610895L,
1590610895L)), class = "data.frame", row.names = c(NA, -62L))

Body:
You can do all the calculation in one pipe using dplyr :

library(dplyr)

df %>%
  group_by(pattern) %>%
  summarise(min_val = min(value),
            max_val = max(value),
            mean_val = mean(value),
            lowest_n_val = mean(head(unique(sort(value)), 5)),
            highest_n_val = mean(tail(unique(sort(value)), 5)))

You can add na.rm. =TRUE in all the above functions if you have NA in your data.


问:
How to alternate output between two lists?
I am trying to output which card a player gets as the card is being handed out. My idea was to output each card by alternating from the two lists. I have included an example below.

```<code>Ex.
List1 = [Banana,Cherry,Orange,Apple,Tomato]
List2 = [Blue,Red,Orange,Yellow,Grey,Purple]

Output:

    Banana
    Blue
    Cherry
    Red
    Orange
    Yellow...
</code>```

This is what I have so far.

```<code>for card in player_A:
    print("Player A is dealt= ",card,"")
for card in Player_B:
    print("Player B is dealt=",card,"")
</code>```

How can I go about doing that?

答:
Use zip to alternate between the two lists.

```<code>for a, b in zip(List1, List2):
  print(f'Player A is dealt= {a}')
  print(f'Playber B is dealt= {b}')
</code>```

Output

```<code>Player A is dealt= Banana
Playber B is dealt= Blue
Player A is dealt= Cherry
Playber B is dealt= Red
Player A is dealt= Orange
Playber B is dealt= Orange
Player A is dealt= Apple
Playber B is dealt= Yellow
Player A is dealt= Tomato
Playber B is dealt= Grey
</code>```

Body:
I am trying to output which card a player gets as the card is being handed out. My idea was to output each card by alternating from the two lists. I have included an example below.

Ex.
List1 = [Banana,Cherry,Orange,Apple,Tomato]
List2 = [Blue,Red,Orange,Yellow,Grey,Purple]

Output:

    Banana
    Blue
    Cherry
    Red
    Orange
    Yellow...

This is what I have so far.

for card in player_A:
    print("Player A is dealt= ",card,"")
for card in Player_B:
    print("Player B is dealt=",card,"")

How can I go about doing that?

Body:
Use zip to alternate between the two lists.

for a, b in zip(List1, List2):
  print(f'Player A is dealt= {a}')
  print(f'Playber B is dealt= {b}')

Output

Player A is dealt= Banana
Playber B is dealt= Blue
Player A is dealt= Cherry
Playber B is dealt= Red
Player A is dealt= Orange
Playber B is dealt= Orange
Player A is dealt= Apple
Playber B is dealt= Yellow
Player A is dealt= Tomato
Playber B is dealt= Grey


问:
WCF Service Still Callable When Windows Service Has Been Stopped
I have written a windows service in C# .NET. This windows service contains a WCF service. I then use a new ServiceHost in the OnStart of the windows service to listen for messages for the WCF service. And close this ServiceHost in the OnStop.

When the service is running I can call the WCF service just fine. However, I then stop the service but can still call the WCF service. I wasn't expecting this to happen. What is going on?

OnStart and OnStop code is below

```<code>    protected override void OnStart(string[] args)
    {
        if (serviceHost != null)
        {
            serviceHost.Close();
        }

        serviceHost = new ServiceHost(typeof(MyService));

        // Open the ServiceHostBase to create listeners and start
        // listening for messages.
        serviceHost.Open();
    }

    protected override void OnStop()
    {
        if (serviceHost != null)
        {
            serviceHost.Close();
            serviceHost = null;
        }
    }
</code>```

答:
Does your OnStop method look something like this:

```<code>protected override void OnStop()
{
  if (serviceHost != null)
  {
      try {
          serviceHost.Close();
      }catch{
          //could throw an exception if it is in a bad state
      }finally{
          serviceHost = null;
      }
  }
}
</code>```

Second thing to check is that your OnStop is being called, it will not call stop if CanStop flag is false.

ContentLicense: CC BY-SA 3.0

Body:
I have written a windows service in C# .NET. This windows service contains a WCF service. I then use a new ServiceHost in the OnStart of the windows service to listen for messages for the WCF service. And close this ServiceHost in the OnStop.

When the service is running I can call the WCF service just fine. However, I then stop the service but can still call the WCF service. I wasn't expecting this to happen. What is going on?

OnStart and OnStop code is below

    protected override void OnStart(string[] args)
    {
        if (serviceHost != null)
        {
            serviceHost.Close();
        }

        serviceHost = new ServiceHost(typeof(MyService));

        // Open the ServiceHostBase to create listeners and start
        // listening for messages.
        serviceHost.Open();
    }

    protected override void OnStop()
    {
        if (serviceHost != null)
        {
            serviceHost.Close();
            serviceHost = null;
        }
    }

Body:
Does your OnStop method look something like this:

protected override void OnStop()
{
  if (serviceHost != null)
  {
      try {
          serviceHost.Close();
      }catch{
          //could throw an exception if it is in a bad state
      }finally{
          serviceHost = null;
      }
  }
}

Second thing to check is that your OnStop is being called, it will not call stop if CanStop flag is false.


问:
spread nav bar across whole page

I am doing some responsive CSS and I want to have something like this:

```<code><body>
<nav>
<ul>
 <li>Asd</li>
 <li>sdf</li>
</ul>
</nav>
<table>
 (Some wide table goes here)
</table>
</code>```

I defined the nav as a bar on top of the page(=horizontal bar).
With small screens (when the table is too big) , the horizontal scrolling bar appears.

My problem is, that when I scroll horizontaly, the nav bar goes to left and leaves a blank space on right side. I just want it to be visible, to keep the impression of bar. Are there any ideas how to do it?

I know, one of them would be position:fixed, so the nav keeps fixed, but that would also mean the nav will be fixed even with verticall scroll, which I don't want.

I just want it to be simply as wide as the whole page (not just as wide as screen), while also being possible to scroll vertically. (It quite doesn't matter to me if the nav content scroll too when horizontal scroll occurs or if the nav content just gets scrolled and there is just nav background (and nav border and so on))

EDIT: http://imageshack.us/photo/my-images/39/201302202145541024x600s.png/

答:
I'm not sure if I understand you fully, but I think the solution to your problem would be to use CSS to set an overflow: hidden parameter.

You can do this with a
  ```
</div>
</div>
</p>

<p>Otherwise, you could add it directly using inline CSS with a style attribute, which doesn't take up as much space but only applies to that specific table (and not all tables on a page). For example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <table style="overflow:hidden">
   (Some wide table goes here)
  </table>
</body></code>```

Title: spread nav bar across whole page

Body:
I am doing some responsive CSS and I want to have something like this:

Asd

sdf

 (Some wide table goes here)

I defined the nav as a bar on top of the page(=horizontal bar).
With small screens (when the table is too big) , the horizontal scrolling bar appears.

My problem is, that when I scroll horizontaly, the nav bar goes to left and leaves a blank space on right side. I just want it to be visible, to keep the impression of bar. Are there any ideas how to do it?

I know, one of them would be position:fixed, so the nav keeps fixed, but that would also mean the nav will be fixed even with verticall scroll, which I don't want.

I just want it to be simply as wide as the whole page (not just as wide as screen), while also being possible to scroll vertically. (It quite doesn't matter to me if the nav content scroll too when horizontal scroll occurs or if the nav content just gets scrolled and there is just nav background (and nav border and so on))

EDIT: http://imageshack.us/photo/my-images/39/201302202145541024x600s.png/

Body:
I'm not sure if I understand you fully, but I think the solution to your problem would be to use CSS to set an overflow: hidden parameter.

You can do this with a <style> tag in the <head> of your internal/external CSS, like so:

<head>
  <style>
    table {
      display: flex;
      overflow: hidden;
    }
  </style>
</head>

Otherwise, you could add it directly using inline CSS with a style attribute, which doesn't take up as much space but only applies to that specific table (and not all tables on a page). For example:

<body>
  <table style="overflow:hidden">
   (Some wide table goes here)
  </table>
</body>


问:
Establishing VPN connection sets NetworkCapabilities.TRANSPORT_WIFI to false?
As the old way of detecting wifi connection (getNetworkInfo) is deprecated in android, I am trying to migrate my app to the latest way, below is what I have for now (in Kotlin):

```<code>fun isWifiConnected(context: Context): Boolean {
    val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
    cm?.activeNetwork?.let { network ->
        cm.getNetworkCapabilities(network)?.let { capability ->
            return capability.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
        }
    }
    return false
}
</code>```

It works well until I get vpn connected (on my samsung s8 + shadowsocks), the capability in above code no longer has TRANSPORT_WIFI transport, but TRANSPORT_VPN instead. And if I connect vpn without wifi then get wifi connected, isWifiConnected returns true again (capability has both TRANSPORT_WIFI and TRANSPORT_VPN in this case).

It seems that the previous transport capabilities would all be reset to false when vpn connection gets established, which sounds like a bug to me, why having one new capability needs to reset old capabilities?

I was hoping this is just a bug of my vpn app (shadowsocks) but I tested same cases on my pixel 2 + shadowsocks, which works quite fine, isWifiConnected returns true as long as wifi is connected, no matter having vpn or not.

So this is a Samsung bug?

答:
The solution works well so far:</p>

```<code>fun isWifiEnabled(context: Context): Boolean {
    val wm = context.getSystemService(Context.WIFI_SERVICE) as WifiManager?
    return wm?.isWifiEnabled ?: false
}
</code>```

Body:
As the old way of detecting wifi connection (getNetworkInfo) is deprecated in android, I am trying to migrate my app to the latest way, below is what I have for now (in Kotlin):

fun isWifiConnected(context: Context): Boolean {
    val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
    cm?.activeNetwork?.let { network ->
        cm.getNetworkCapabilities(network)?.let { capability ->
            return capability.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
        }
    }
    return false
}

It works well until I get vpn connected (on my samsung s8 + shadowsocks), the capability in above code no longer has TRANSPORT_WIFI transport, but TRANSPORT_VPN instead. And if I connect vpn without wifi then get wifi connected, isWifiConnected returns true again (capability has both TRANSPORT_WIFI and TRANSPORT_VPN in this case).

It seems that the previous transport capabilities would all be reset to false when vpn connection gets established, which sounds like a bug to me, why having one new capability needs to reset old capabilities?

I was hoping this is just a bug of my vpn app (shadowsocks) but I tested same cases on my pixel 2 + shadowsocks, which works quite fine, isWifiConnected returns true as long as wifi is connected, no matter having vpn or not.

So this is a Samsung bug?

Body:
The solution works well so far:

fun isWifiEnabled(context: Context): Boolean {
    val wm = context.getSystemService(Context.WIFI_SERVICE) as WifiManager?
    return wm?.isWifiEnabled ?: false
}


问:
PHP dom parser: How to get element count only if it comes after another element?
I'm trying to get a count of how many images are on an HTML page sprinkled throughout an article but I do not want to count the image if it comes before the text of the article begins. The problem is the classes are exactly the same, so I can't use that to help me, and not every article is even going to start with an image. So the HTML might look like this:

```<code><img class="image-asset" src="image.jpg">
<p>First line</p>
<p>Second line</p>
<img class="image-asset" src="second_image.jpg">
<p>Third line</p>
<img class="image-asset" src="third_image.jpg">
</code>```

In this instance, I want to only count the second and third images. Here's my code, which is successfully counting every image at the moment:

```<code>$photoCount = count($html->find('div.image-asset'));
</code>```

答:
I believe you are looking for something along these lines:

```<code>$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$target = $xpath->query('//img[preceding-sibling::p]');
echo count($target), PHP_EOL;
//and just to be on the safe side:
foreach ($target as $t) {
    echo $t->ownerDocument->saveHTML($t), PHP_EOL;
};
</code>```

Output:

```<code>2
<img class="image-asset" src="second_image.jpg">
<img class="image-asset" src="third_image.jpg">
</code>```

Body:
I'm trying to get a count of how many images are on an HTML page sprinkled throughout an article but I do not want to count the image if it comes before the text of the article begins. The problem is the classes are exactly the same, so I can't use that to help me, and not every article is even going to start with an image. So the HTML might look like this:

First line

Second line

Third line

In this instance, I want to only count the second and third images. Here's my code, which is successfully counting every image at the moment:

$photoCount = count($html->find('div.image-asset'));

Body:
I believe you are looking for something along these lines:

$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$target = $xpath->query('//img[preceding-sibling::p]');
echo count($target), PHP_EOL;
//and just to be on the safe side:
foreach ($target as $t) {
    echo $t->ownerDocument->saveHTML($t), PHP_EOL;
};

Output:

2
<img class="image-asset" src="second_image.jpg">
<img class="image-asset" src="third_image.jpg">


问:
JSON_EXTRACT() Query returns NULL
Hello i have a question about mysql json_extract function.

```<code>DROP TABLE IF EXISTS `db`.`PacJSON`;
CREATE TABLE PacJSON SELECT  * FROM PAC;
ALTER TABLE PacJSON ADD COLUMN hc JSON DEFAULT NULL;
UPDATE `db`.`PacJSON`
SET `hc`='[{"estado":"1"},{"descripcion":"name1"},{"estudio": "name2"}, {"url":"name3"},{"idpaciente":"11"},{"idmedico":"6"},{"fecha_hc":"2019-05-2"}]'
WHERE idUsuario=11;
</code>```

The query below is returning a null value when it should return 6.
Can somebody tell me what am i doing wrong?

```<code>SELECT idUsuario,PacJSON.hc ,JSON_UNQUOTE(JSON_EXTRACT(hc ,'$."idmedico"')) AS "idmedico"
 FROM PacJson;
</code>```

Thanks!

答:
Your hc value contains an array of objects, so you need to use a path which reflects that i.e. $[*].idmedico. Note that double quotes should not be used in the path.

```<code>SELECT idUsuario,
       hc,
       JSON_UNQUOTE(JSON_EXTRACT(hc ,'$[*].idmedico')) AS idmedico
FROM PacJSON
</code>```

Output:

```<code>["6"]
</code>```

Note that because hc is an array, JSON_EXTRACT returns one too. If you know there's only one idmedico value in the JSON, you can use JSON_EXTRACT again on that result to get the actual numeric value:

```<code>SELECT idUsuario,
       hc,
       JSON_UNQUOTE(JSON_EXTRACT(JSON_EXTRACT(hc ,'$[*].idmedico'), '$[0]')) AS idmedico
FROM PacJSON
</code>```

Output:

```<code>6
</code>```

Demo on dbfiddle

Title: JSON_EXTRACT() Query returns NULL

Body:
Hello i have a question about mysql json_extract function.

DROP TABLE IF EXISTS `db`.`PacJSON`;
CREATE TABLE PacJSON SELECT  * FROM PAC;
ALTER TABLE PacJSON ADD COLUMN hc JSON DEFAULT NULL;
UPDATE `db`.`PacJSON`
SET `hc`='[{"estado":"1"},{"descripcion":"name1"},{"estudio": "name2"}, {"url":"name3"},{"idpaciente":"11"},{"idmedico":"6"},{"fecha_hc":"2019-05-2"}]'
WHERE idUsuario=11;

The query below is returning a null value when it should return 6.
Can somebody tell me what am i doing wrong?

SELECT idUsuario,PacJSON.hc ,JSON_UNQUOTE(JSON_EXTRACT(hc ,'$."idmedico"')) AS "idmedico"
 FROM PacJson;

Thanks!

Body:
Your hc value contains an array of objects, so you need to use a path which reflects that i.e. $[*].idmedico. Note that double quotes should not be used in the path.

SELECT idUsuario,
       hc,
       JSON_UNQUOTE(JSON_EXTRACT(hc ,'$[*].idmedico')) AS idmedico
FROM PacJSON

Output:

["6"]

Note that because hc is an array, JSON_EXTRACT returns one too. If you know there's only one idmedico value in the JSON, you can use JSON_EXTRACT again on that result to get the actual numeric value:

SELECT idUsuario,
       hc,
       JSON_UNQUOTE(JSON_EXTRACT(JSON_EXTRACT(hc ,'$[*].idmedico'), '$[0]')) AS idmedico
FROM PacJSON

Output:

6

Demo on dbfiddle


问:
No name was provided for external module
I created a data library, then tried to include the data library into another created library. Built fine, but received - "No name was provided for external module 'my-data' in output.globals – guessing 'myData'". What am I missing?

Complete steps to re-create.

ng new test-project --create=application=false

cd test-project

npm audit fix

ng g library my-data

ng g library my-core

ng g application address-book

ng build my-data

Then in my-core.module add import { MyDataModule } from 'my-data';

Then in my-core.module add imports: [MyDataModule]

ng build my-core

my-core.module.ts

```<code>import { NgModule } from '@angular/core';
import { MyCoreComponent } from './my-core.component';
import { MyDataModule } from 'my-data';

@NgModule({
  declarations: [MyCoreComponent],
  imports: [MyDataModule],
  exports: [MyCoreComponent]
})
export class MyCoreModule { }
</code>```

After build get "No name was provided for external module 'my-data' in output.globals – guessing 'myData'"

答:
for anyone else coming here for this error and the above seems tedious to do OR you are just wondering what you changed to make you need this all of a sudden like me.

In my case (in order to make jest work) I had changed the following in tsconfig:

```<code>  "compilerOptions": {
    "module": "commonjs",
    "target": "esnext",
  "angularCompilerOptions": {
    "preserveWhitespaces": false
  }
</code>```

back to:

```<code>  "compilerOptions": {
    "module": "esnext",
    "target": "es5"
}
</code>```

I have no idea why this works, still reading through the rabbit hole provided by the above answerer and I am still trying to get both jest tests to work and my library to build.  Anyway, I hope this helps someone.

Body:
I created a data library, then tried to include the data library into another created library. Built fine, but received - "No name was provided for external module 'my-data' in output.globals – guessing 'myData'". What am I missing?

Complete steps to re-create.

ng new test-project --create=application=false

cd test-project

npm audit fix

ng g library my-data

ng g library my-core

ng g application address-book

ng build my-data

Then in my-core.module add import { MyDataModule } from 'my-data';

Then in my-core.module add imports: [MyDataModule]

ng build my-core

my-core.module.ts

import { NgModule } from '@angular/core';
import { MyCoreComponent } from './my-core.component';
import { MyDataModule } from 'my-data';

@NgModule({
  declarations: [MyCoreComponent],
  imports: [MyDataModule],
  exports: [MyCoreComponent]
})
export class MyCoreModule { }

After build get "No name was provided for external module 'my-data' in output.globals – guessing 'myData'"

Body:
for anyone else coming here for this error and the above seems tedious to do OR you are just wondering what you changed to make you need this all of a sudden like me.

In my case (in order to make jest work) I had changed the following in tsconfig:

  "compilerOptions": {
    "module": "commonjs",
    "target": "esnext",
  "angularCompilerOptions": {
    "preserveWhitespaces": false
  }

back to:

  "compilerOptions": {
    "module": "esnext",
    "target": "es5"
}

I have no idea why this works, still reading through the rabbit hole provided by the above answerer and I am still trying to get both jest tests to work and my library to build.  Anyway, I hope this helps someone.


问:
Regex java to check for starting [ and ending ] but could have \t\r\n at start and end
I need to check that a String starts with [ and ends with ] but allowing whitespace before/after the square brackets.

I could use trim(), then check the end characters, but the String can be very long (more than 100,000 chars) so it could be expensive to create a new trimmed String. I want to know what is the best approach that gives reasonable performance given the large String size.

Sample input that should pass:

```<code>"\t\n\r      [  (very long string) ] \t \r \n"
</code>```

Using regex, I have the following expression, but don't know if it is absolutely correct or not, or if it will perform well.

```<code>(^|\s+)\[((.*)|\s)+\]($|\s+)
</code>```

What is the best approach for solving this?

答:
Here is a fast JavaScript version, can be easily applied to Java as well:

var result = /^\s*\[[^\]]*\]\s*$/.test('\t\n\r    [...very long string...] \t \r \n');
console.log('result: ' + result);```

Notes on this regex:

use anchors (^ and $) to allow only leading & trailing white-space

use \s* instead of \s+ because with the latter you need an OR test for empty white-space

use a fast [^\]]* to avoid the expensive .* regex with backtracking

Body:
I need to check that a String starts with [ and ends with ] but allowing whitespace before/after the square brackets.

I could use trim(), then check the end characters, but the String can be very long (more than 100,000 chars) so it could be expensive to create a new trimmed String. I want to know what is the best approach that gives reasonable performance given the large String size.

Sample input that should pass:

"\t\n\r      [  (very long string) ] \t \r \n"

Using regex, I have the following expression, but don't know if it is absolutely correct or not, or if it will perform well.

(^|\s+)\[((.*)|\s)+\]($|\s+)

What is the best approach for solving this?

Body:
Here is a fast JavaScript version, can be easily applied to Java as well:

var result = /^\s*\[[^\]]*\]\s*$/.test('\t\n\r    [...very long string...] \t \r \n');
console.log('result: ' + result);

Notes on this regex:

use anchors (^ and $) to allow only leading & trailing white-space

use \s* instead of \s+ because with the latter you need an OR test for empty white-space

use a fast [^\]]* to avoid the expensive .* regex with backtracking


问:
How to re-run a fail Nunit Test 2.6.2
I am trying to Re-run failed Nunit tests, mainly because of flackiness with selenium.

```<code>    [TearDown]
    public virtual void TearDown()
    {
        var testName = TestContext.CurrentContext.Test.FullName.Replace("Server.Tests.", string.Empty);

        if (TestContext.CurrentContext.Result.Status == TestStatus.Passed)
            return;
        else if (_testFailure < 3) {
            _testFailure++;
            Console.WriteLine($"\n {testName} {TestContext.CurrentContext.Result.Status}... Retrying attempt {_testFailure}");
            DbReloader.LoadUnitTestData(DbFactory);
            TestExecutionContext.CurrentContext.CurrentTest.Run(new NullListener(), TestFilter.Empty);

        }
        BrowserDriver.GetScreenshot()
                     .SaveAsFile($"{testName}.fail.png", ImageFormat.Png);
    }
</code>```

The problem is after the test runs again, it will continue with the tear down of the test as the original test failed. How do I override the TestContext.CurrentContext.Result with my retried test results?

答:
Unfortunately, the RetryAttribute is only available in NUnit 3. To put things into perspective, it has been around quite a while, having been implemented in 2015. Are there reasons you can't upgrade the version of NUnit you are using?

If circumstances force you to keep using such an old  version (2012) of NUnit, it would not be difficult to implement your own RetryAttriute. The definition could live in your test assembly itself and reference the version of NUnit you are using.

You could model such an attribute after the existing V2 RepeatAttribute and also take some hints from the RetryAttribute in NUnit 3. The latter, however, is based on an entirely different set of interfaces so can't be used without modification.

There is no easy way to effectively rerun tests from a TearDown method because the test isn't over until the TearDown method completes. It would actually be easier to modify NUnit 2.6.2 itself.

To sum up, in order of easiest to most difficult, you can choose

To upgrade to NUnit 3

To add a custom RetryAttribute

To modify NUnit 2.6.2

Title: How to re-run a fail Nunit Test 2.6.2

Body:
I am trying to Re-run failed Nunit tests, mainly because of flackiness with selenium.

    [TearDown]
    public virtual void TearDown()
    {
        var testName = TestContext.CurrentContext.Test.FullName.Replace("Server.Tests.", string.Empty);

        if (TestContext.CurrentContext.Result.Status == TestStatus.Passed)
            return;
        else if (_testFailure < 3) {
            _testFailure++;
            Console.WriteLine($"\n {testName} {TestContext.CurrentContext.Result.Status}... Retrying attempt {_testFailure}");
            DbReloader.LoadUnitTestData(DbFactory);
            TestExecutionContext.CurrentContext.CurrentTest.Run(new NullListener(), TestFilter.Empty);

        }
        BrowserDriver.GetScreenshot()
                     .SaveAsFile($"{testName}.fail.png", ImageFormat.Png);
    }

The problem is after the test runs again, it will continue with the tear down of the test as the original test failed. How do I override the TestContext.CurrentContext.Result with my retried test results?


问:
2d histogram: Get result of full nbins x nbins
I am using matplotlib's hist2d function to make a 2d histogram of data that I have, however I am having trouble interpreting the result.

Here is the plot I have:

This was created using the line:

```<code>hist = plt.hist2d(X, Y, (160,160), norm=mpl.colors.LogNorm(vmin=1, vmax=20))
</code>```

This returns a 2d array of (160, 160), as well as the bin edges etc.

In the plot there are bins which have a high frequency of values (yellow bins). I would like to be able to get the results of this histogram and filter out the bins that have low values, preserving the high bins. But I would expect there to be 160*160 values, but I can only find 160 X and 160 Y values.

What I would like to do is essentially filter out the more dense data from the less dense data. If this means representing the data as a single value (a bin), then that is ok.

Am I misinterpreting the function or am I not accessing the data results correctly? I have tried with spicy also but the results seem to be in the same or similar format.

答:
Not sure if this is what you wanted.

The hist2d docs specify that the function returns a tuple of size 4, where the first item h is a heatmap.

This h will have the same shape as bins.

You can capture the output (it will still plot), and use argwhere to find coordinates where values exceed, say, the 90th percentile:

h, xedges, yedges, img = hist = plt.hist2d(X, Y, bins=(160,160), norm=mpl.colors.LogNorm(vmin=1, vmax=20))

print(list(np.argwhere(h > np.percentile(h, 90))))
```

Body:
I am using matplotlib's hist2d function to make a 2d histogram of data that I have, however I am having trouble interpreting the result.

Here is the plot I have:

This was created using the line:

hist = plt.hist2d(X, Y, (160,160), norm=mpl.colors.LogNorm(vmin=1, vmax=20))

This returns a 2d array of (160, 160), as well as the bin edges etc.

In the plot there are bins which have a high frequency of values (yellow bins). I would like to be able to get the results of this histogram and filter out the bins that have low values, preserving the high bins. But I would expect there to be 160*160 values, but I can only find 160 X and 160 Y values.

What I would like to do is essentially filter out the more dense data from the less dense data. If this means representing the data as a single value (a bin), then that is ok.

Am I misinterpreting the function or am I not accessing the data results correctly? I have tried with spicy also but the results seem to be in the same or similar format.


问:
How should I implement an Auth handler that takes effect on response?
I wish to implement an Auth handler for requests that handles authentication with an OAuth Authorization server to allow the following:

```<code>import requests

requests.get(url, auth=KeycloakAuth())
</code>```

What I've done so far is to apply a response hook when KeycloakAuth is called, so that when the client redirects the caller to Keycloak, the hook will see the Keycloak login page, post the credentials to Keycloak and get redirected back to the client.

However, this does not work for a POST, as requests makes a POST to Keycloak's login page instead of a GET due to the redirect. Keycloak doesn't return the login form in response to a POST and this fails.

I considered checking for the redirect in the response hook so that I can modify the redirect to do a GET to Keycloak instead, but it seems like requests' implementation of redirects bypasses all the hooks.

答:
After poking into this a bit more, I believe this may be the wrong question to ask.

I was seeking a solution where, regardless of the original HTTP method used on the client (GET, POST, HEAD, etc), the library would automatically login to Keycloak, and then "replay" the original request to the client and make it effectively transparent to the user of the library.

However, this can't possibly work with OAuth 2.0 without further state management on either the part of the library or the client, due to the redirecting.

Suppose the original request was a POST, with some data. After finding that the user is not logged in, the User-Agent will be redirected to the Authorization Server for authentication.

This means that the original request's POST data will be lost, removing the opportunity for any replay, upon the User-Agent being redirected back to the client after authentication.

With some state management, the POST data could be stored for replay - it doesn't make sense to store the data on the server side since the data could be arbitrarily large, which leaves us with the user of the library to do the state management.

However, that amount of state management should probably not belong in a library, since the library will have to handle lots of cases to guarantee only-once delivery of the request, for example, which would be expected by the user of the requests library.

As such, this Auth handler is probably not something we can implement in a library.

Body:
I wish to implement an Auth handler for requests that handles authentication with an OAuth Authorization server to allow the following:

import requests

requests.get(url, auth=KeycloakAuth())

What I've done so far is to apply a response hook when KeycloakAuth is called, so that when the client redirects the caller to Keycloak, the hook will see the Keycloak login page, post the credentials to Keycloak and get redirected back to the client.

However, this does not work for a POST, as requests makes a POST to Keycloak's login page instead of a GET due to the redirect. Keycloak doesn't return the login form in response to a POST and this fails.

I considered checking for the redirect in the response hook so that I can modify the redirect to do a GET to Keycloak instead, but it seems like requests' implementation of redirects bypasses all the hooks.


问:
HTK HSGen [+8250] error?
I want to use the HTK toolbox for digit recognition. so I downloaded it and read the instruction about how to use it! But when I want to use the HSGen I encounter with this error:

```<code>ERROR [+8250] ReadLattice: 23 Arcs unseen and 15 Nodes unseen
ERROR [+3410] GenSentences: ReadLattice failed
FATAL ERROR - Terminating program HSGen
</code>```

So the steps I did is as follows:

make a grammer, my file content is exactly as it is stored in a file named gram:

```<code>    $digit = ONE|TWO|THREE|FOUR|FIVE|SIX|SEVEN|EIGHT|NINE|ZERO;

    (SENT-START ($digit) SENT-END)
</code>```

Using HParse command to make a network for this grammar, its content is(stored in a file named wdnet) :

    I=0    W=!NULL

    I=1    W=!NULL

    I=10   W=SEVEN

    I=11   W=EIGHT

    I=12   W=NINE

    I=13   W=ZERO

    I=14   W=SENT-END

    I=2    W=SENT-START

    I=3    W=ONE

    I=4    W=!NULL

    I=5    W=TWO

    I=6    W=THREE

    I=7    W=FOUR

    I=8    W=FIVE

    I=9    W=SIX

    J=0     S=14   E=1

    J=1     S=0    E=2

    J=10    S=11   E=4

    J=11    S=12   E=4

    J=12    S=13   E=4

    J=13    S=2    E=5

    J=14    S=2    E=6

    J=15    S=2    E=7

    J=16    S=2    E=8

    J=17    S=2    E=9

    J=18    S=2    E=10

    J=19    S=2    E=11

    J=2     S=2    E=3

    J=20    S=2    E=12

    J=21    S=2    E=13

    J=22    S=4    E=14

    J=3     S=3    E=4

    J=4     S=5    E=4

    J=5     S=6    E=4

    J=6     S=7    E=4

    J=7     S=8    E=4

    J=8     S=9    E=4

    J=9     S=10   E=4

    N=15   L=23

    VERSION=1.0

I have a word list file named as wlist2, its content is:

```<code>    EIGHT
    FIVE
    FOUR
    NINE
    ONE
    SENT-END
    SENT-START
    SEVEN
    SIX
    THREE
    TWO
    ZERO
</code>```

I use the HDMan command to build the dictionary file:

```<code>    HDMan -m -w wlist2 -n monophones -l dlog2 dict2 mbeep2
</code>```

which mbeep2 is my dictionary that contains the pronounciations for each word in my wlist2. the ouput file is created in the file named dict2.

When using HSGen with this command:

```<code>    HSGen -l -n 200 wdnet dict2 > testprompets
</code>```

I got this error:

```<code>ERROR [+8250] ReadLattice: 23 Arcs unseen and 15 Nodes unseen
ERROR [+3410] GenSentences: ReadLattice failed
FATAL ERROR - Terminating program HSGen
</code>```

I search the error number but coudln't find a related solution! Can anyone help?

Thanks.

答: The variable I and J in your wdnet should put in order</p>

Title: HTK HSGen [+8250] error?

Body:
I want to use the HTK toolbox for digit recognition. so I downloaded it and read the instruction about how to use it! But when I want to use the HSGen I encounter with this error:

ERROR [+8250] ReadLattice: 23 Arcs unseen and 15 Nodes unseen
ERROR [+3410] GenSentences: ReadLattice failed
FATAL ERROR - Terminating program HSGen

So the steps I did is as follows:

make a grammer, my file content is exactly as it is stored in a file named gram:

    $digit = ONE|TWO|THREE|FOUR|FIVE|SIX|SEVEN|EIGHT|NINE|ZERO;

    (SENT-START ($digit) SENT-END)

Using HParse command to make a network for this grammar, its content is(stored in a file named wdnet) :

    I=0    W=!NULL

    I=1    W=!NULL

    I=10   W=SEVEN

    I=11   W=EIGHT

    I=12   W=NINE

    I=13   W=ZERO

    I=14   W=SENT-END

    I=2    W=SENT-START

    I=3    W=ONE

    I=4    W=!NULL

    I=5    W=TWO

    I=6    W=THREE

    I=7    W=FOUR

    I=8    W=FIVE

    I=9    W=SIX

    J=0     S=14   E=1

    J=1     S=0    E=2

    J=10    S=11   E=4

    J=11    S=12   E=4

    J=12    S=13   E=4

    J=13    S=2    E=5

    J=14    S=2    E=6

    J=15    S=2    E=7

    J=16    S=2    E=8

    J=17    S=2    E=9

    J=18    S=2    E=10

    J=19    S=2    E=11

    J=2     S=2    E=3

    J=20    S=2    E=12

    J=21    S=2    E=13

    J=22    S=4    E=14

    J=3     S=3    E=4

    J=4     S=5    E=4

    J=5     S=6    E=4

    J=6     S=7    E=4

    J=7     S=8    E=4

    J=8     S=9    E=4

    J=9     S=10   E=4

    N=15   L=23

    VERSION=1.0

I have a word list file named as wlist2, its content is:

    EIGHT
    FIVE
    FOUR
    NINE
    ONE
    SENT-END
    SENT-START
    SEVEN
    SIX
    THREE
    TWO
    ZERO

I use the HDMan command to build the dictionary file:

    HDMan -m -w wlist2 -n monophones -l dlog2 dict2 mbeep2

which mbeep2 is my dictionary that contains the pronounciations for each word in my wlist2. the ouput file is created in the file named dict2.

When using HSGen with this command:

    HSGen -l -n 200 wdnet dict2 > testprompets

I got this error:

ERROR [+8250] ReadLattice: 23 Arcs unseen and 15 Nodes unseen
ERROR [+3410] GenSentences: ReadLattice failed
FATAL ERROR - Terminating program HSGen

I search the error number but coudln't find a related solution! Can anyone help?

Thanks.


问:
How to make custom buttons with different color?
```<code><?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
     <gradient android:startColor="#4CC417" android:endColor="#7C4124" android:angle="270"/>
    <corners android:bottomRightRadius="7dp" android:bottomLeftRadius="7dp" android:topLeftRadius="7dp" android:topRightRadius="7dp"/>
 </shape>
</code>```

This is my custom button xml. I want to modify the code to get two or more colors.

答: A gradient from startColor to endColor already gives 2 colors. A center color can be added by using android:centerColor="#hexcode".

Body:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
     <gradient android:startColor="#4CC417" android:endColor="#7C4124" android:angle="270"/>
    <corners android:bottomRightRadius="7dp" android:bottomLeftRadius="7dp" android:topLeftRadius="7dp" android:topRightRadius="7dp"/>
 </shape>

This is my custom button xml. I want to modify the code to get two or more colors.


问:
How to add limit and offset to sql query?
I have this sql query but it does not work:

```<code>SELECT u.id, u.first_name, u.last_name
, m.media_link, g_m.member_type
FROM Group_Members g_m
LEFT JOIN Users u
  ON g_m.user_id = u.id
LEFT JOIN Media m
  ON u.id = m.user_id
WHERE g_m.group_id = ?
AND m.position = ?
AND m.type = ?
ORDER BY u.first_name ASC LIMIT ?, 50;
</code>```

This is the error I get

get memberFound error: Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''0', 50' at line 1
GET /group_members?group_id=6&offset=0

Can anyone help, not sure how to add limit and offset correctly, this query worked without the Limit/offset add...

This is mysql and nodejs.

答:
I don't see any syntax errors in your SQL.

Use a setInt method for the LIMIT question mark.

```<code>SELECT
  u.id,
  u.first_name,
  u.last_name,
  m.media_link,
  g_m.member_type
FROM
  Group_Members g_m
  LEFT JOIN Users u ON g_m.user_id = u.id
  LEFT JOIN Media m ON u.id = m.user_id
WHERE
  g_m.group_id = ?
  AND m.position = ?
  AND m.type = ?
ORDER BY
  u.first_name ASC
LIMIT
  ?, 50;
</code>```

Body:
I have this sql query but it does not work:

SELECT u.id, u.first_name, u.last_name
, m.media_link, g_m.member_type
FROM Group_Members g_m
LEFT JOIN Users u
  ON g_m.user_id = u.id
LEFT JOIN Media m
  ON u.id = m.user_id
WHERE g_m.group_id = ?
AND m.position = ?
AND m.type = ?
ORDER BY u.first_name ASC LIMIT ?, 50;

This is the error I get

get memberFound error: Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''0', 50' at line 1
GET /group_members?group_id=6&offset=0

Can anyone help, not sure how to add limit and offset correctly, this query worked without the Limit/offset add...

This is mysql and nodejs.

Body:
I don't see any syntax errors in your SQL.

Use a setInt method for the LIMIT question mark.

SELECT
  u.id,
  u.first_name,
  u.last_name,
  m.media_link,
  g_m.member_type
FROM
  Group_Members g_m
  LEFT JOIN Users u ON g_m.user_id = u.id
  LEFT JOIN Media m ON u.id = m.user_id
WHERE
  g_m.group_id = ?
  AND m.position = ?
  AND m.type = ?
ORDER BY
  u.first_name ASC
LIMIT
  ?, 50;


问:
Error: Unable to 'pub upgrade' flutter tool. Retrying in five seconds
Log:

E:\Flutter>flutter doctor Checking Dart SDK version... Downloading
Dart SDK from Flutter engine ead227f a... Unzipping Dart SDK...
Updating flutter tool... Error: Unable to 'pub upgrade' flutter tool.
Retrying in five seconds...

Waiting for 0 seconds, press CTRL+C to quit ... Error: Unable to 'pub
upgrade' flutter tool. Retrying in five seconds...

Waiting for 0 seconds, press CTRL+C to quit ... Error: Unable to 'pub
upgrade' flutter tool. Retrying in five seconds...

Waiting for 0 seconds, press CTRL+C to quit ... Error: Unable to 'pub
upgrade' flutter tool. Retrying in five seconds...

Waiting for 0 seconds, press CTRL+C to quit ... Error: Unable to 'pub
upgrade' flutter tool. Retrying in five seconds...

Waiting for 0 seconds, press CTRL+C to quit ... Error: Unable to 'pub
upgrade' flutter tool. Retrying in five seconds...

答: Just delete the cache folder in flutter/bin and run flutter doctor again!!


问:
Unable to load MySQL database via entity framework in VS 2019
I know that there are a lot of questions in different communities. I have tried each and everything but still unable to load my database via the entity framework. The database I am using in MySQL and I am trying to load it using Entity Framework. But the window crashes from below window

I have installed all the latest versions as said here.

Below is my app.config

```<code> <entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.10.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
  </provider></providers>
</code>```

PS: I am using the console application.

Any help would be highly appreciated

答:
You shouldn't have MySql.Data.Entity installed. Uninstall that and replace it with MySql.Data.EntityFramework instead.

For more information, see the final comment on https://bugs.mysql.com/bug.php?id=90114.

Body:
I know that there are a lot of questions in different communities. I have tried each and everything but still unable to load my database via the entity framework. The database I am using in MySQL and I am trying to load it using Entity Framework. But the window crashes from below window

I have installed all the latest versions as said here.

Below is my app.config

 <entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.10.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
  </provider></providers>

PS: I am using the console application.

Any help would be highly appreciated


问:
How do I read from the terminal in Python?
I just want to use os.system("dir") and also be able to save the text outputted to a variable.  I tried using sys.stdout.read() but running sys.stdout.readable() returns False.  Do you know how I can read from the terminal?

答:
There is a bit of confusion here about the different streams, and possibly a better way to do things.

For the specific case of dir, you can replace the functionality you want with the os.listdir function, or better yet os.scandir.

For the more general case, you will not be able to read an arbitrary stdout stream. If you want to do that, you'll have to set up a subprocess whose I/O streams you control. This is not much more complicated than using os.system. you can use subprocess.run, for example:

```<code>content = subprocess.run("dir", stdout=subprocess.PIPE, check=True).stdout
</code>```

The object returned by run has a stdout attribute that contains everything you need.

Body:
There is a bit of confusion here about the different streams, and possibly a better way to do things.

For the specific case of dir, you can replace the functionality you want with the os.listdir function, or better yet os.scandir.

For the more general case, you will not be able to read an arbitrary stdout stream. If you want to do that, you'll have to set up a subprocess whose I/O streams you control. This is not much more complicated than using os.system. you can use subprocess.run, for example:

content = subprocess.run("dir", stdout=subprocess.PIPE, check=True).stdout

The object returned by run has a stdout attribute that contains everything you need.


问:
how to make a video from extracted frames?
I extracted the video frames into a folder called "images". After getting images saved in my folder, I use the following code to create the video again. I get the video but the frames are ordered randomly, how can I arrange them in sequential order? thanks for the post

```<code>import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))

cv2.destroyAllWindows()
video.release()
</code>```

please advise, how do I fix this? I'd like the videos to be at the same rate as the original video, and frames to be in sequential order.

答:
It seems you need natural sorting, so try natsort library:

```<code>from natsort import natsorted

images = natsorted(images)
</code>```

Install using pip:

```<code>pip install natsort
</code>```

Body:
I extracted the video frames into a folder called "images". After getting images saved in my folder, I use the following code to create the video again. I get the video but the frames are ordered randomly, how can I arrange them in sequential order? thanks for the post

import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))

cv2.destroyAllWindows()
video.release()

please advise, how do I fix this? I'd like the videos to be at the same rate as the original video, and frames to be in sequential order.

Body:
It seems you need natural sorting, so try natsort library:

from natsort import natsorted

images = natsorted(images)

Install using pip:

pip install natsort


问:
Why does my array -count method return zero after adding an element?
I have class like the following

```<code>@interface Node : NSObject {

NSString* description;
NSString* ae;
NSString* ip;
NSString*  port;
}

@property ( nonatomic , retain ) NSString* description;
@property ( nonatomic , retain ) NSString* ae;
@property ( nonatomic , retain ) NSString* ip;
@property ( nonatomic , retain ) NSString* port;

@end

#import "Node.h"

@implementation Node

@synthesize description,ae,ip,port;

@end
</code>```

I want to create nsmutablearray of it So I do the following

```<code>NSMutableArray* nodesArray ;
nodesArray = [[NSMutableArray alloc] init];

Node * insertedNode =[[Node alloc]init] ;
insertedNode.description =@"test";
insertedNode.ae =@"test" ;
insertedNode.ip =@"test";
insertedNode.port =@"test";

[nodesArray addObject: insertedNode] ;

[insertedNode release];
</code>```

then I print the count using

```<code>NSLog(@"%d",[nodesArray count] ) ;
</code>```

but it always always return 0

any suggestion to solve that

Best regards

答:
Perhaps NodesArray is failing to initialize? You could try testing to see if it is nil after you initialize it. (at [[NSMutableArray alloc] init])

Adding an object to a nil NSMutableArray * would fail silently, and [nil count] will always return zero.

(No idea why it would fail to initialize, but I can't imagine anything else causing the behavior you're describing.)

Body:
I have class like the following

@interface Node : NSObject {

NSString* description;
NSString* ae;
NSString* ip;
NSString*  port;
}

@property ( nonatomic , retain ) NSString* description;
@property ( nonatomic , retain ) NSString* ae;
@property ( nonatomic , retain ) NSString* ip;
@property ( nonatomic , retain ) NSString* port;

@end

#import "Node.h"

@implementation Node

@synthesize description,ae,ip,port;

@end

I want to create nsmutablearray of it So I do the following

NSMutableArray* nodesArray ;
nodesArray = [[NSMutableArray alloc] init];

Node * insertedNode =[[Node alloc]init] ;
insertedNode.description =@"test";
insertedNode.ae =@"test" ;
insertedNode.ip =@"test";
insertedNode.port =@"test";

[nodesArray addObject: insertedNode] ;

[insertedNode release];

then I print the count using

NSLog(@"%d",[nodesArray count] ) ;

but it always always return 0

any suggestion to solve that

Best regards


问:
How to find a whole word in a sentence in Python?
Say I have a sentence

```<code>sent = "Luxred is a great,awesome and amazing but, they make a lot of money too"
ents = ['L'Oreal', 'Maybelline', 'Garnier Natural', 'Luxred', 'Lux']
</code>```

The sentences will be like this. The sentences will have commas and other words too. I want to find the exact word match for Luxred. It shouldn't match for Lux either and also want the starting index & ending index of the word. Here it is (0, 5). The sentence might change and the search words might come in between etc. How do I do this ?

Already tried using find.

```<code>def annotFinal (label, entities, sentences) :
finaldict = []
for sent in sentences :
    sent = str(sent).lower()
    inner_list = []
    for ent in entities :
        if (sent.find(ent) != -1) :
            inner_tup = (sent.find(ent), sent.find(ent) + len(ent), label)
            inner_list.append(inner_tup)
    inner_dict={'entities': sorted(inner_list, key=lambda x: x[0])}
    finaldict.append((sent, inner_dict))
return finaldict
</code>```

答:
You use the find method:

```<code>>>> sent = "Luxred is a great,awesome and amazing but, they make a lot of money too"
>>> sent.find("Luxred")
0
</code>```

Body:
Say I have a sentence

sent = "Luxred is a great,awesome and amazing but, they make a lot of money too"
ents = ['L'Oreal', 'Maybelline', 'Garnier Natural', 'Luxred', 'Lux']

The sentences will be like this. The sentences will have commas and other words too. I want to find the exact word match for Luxred. It shouldn't match for Lux either and also want the starting index & ending index of the word. Here it is (0, 5). The sentence might change and the search words might come in between etc. How do I do this ?

Already tried using find.

def annotFinal (label, entities, sentences) :
finaldict = []
for sent in sentences :
    sent = str(sent).lower()
    inner_list = []
    for ent in entities :
        if (sent.find(ent) != -1) :
            inner_tup = (sent.find(ent), sent.find(ent) + len(ent), label)
            inner_list.append(inner_tup)
    inner_dict={'entities': sorted(inner_list, key=lambda x: x[0])}
    finaldict.append((sent, inner_dict))
return finaldict

Body:
You use the find method:

>>> sent = "Luxred is a great,awesome and amazing but, they make a lot of money too"
>>> sent.find("Luxred")
0


问:
inline functions and forward references
At https://www.studytonight.com/cpp/inline-functions.php they are explaining inline functions

All the inline functions are evaluated by the compiler, at the end of class declaration.

```<code>class ForwardReference
{
    int i;
    public:
    // call to undeclared function
    int f()
    {
        return g()+10;
    }
    int g()
    {
        return i;
    }
};

int main()
{
    ForwardReference fr;
    fr.f();
}
</code>```

At the end they say :
"You must be thinking that this will lead to compile time error, but in this case it will work, because no inline function in a class is evaluated until the closing braces of class declaration."

......

why should one expect a compile time error? is it because no value for i has been set? If so, could someone explain better why it works, I don't get what's the point here, if the member functions are inline or not wouldn't it work the same?

答:
What they are hinting at here, for why someone might expect a compile error, is the fact that although g is written below/after f, f can still reference it with no error.

If you were to move them out of the class and define+declare them at the same time then you would see the compile error (since f cannot see any g).

i.e.

```<code>int f(){
    return g() + 10;
}

int g(){
    return 32;
}

int main(){
    return f();
}
</code>```

See for yourself on compiler explorer.

Title: inline functions and forward references

Body:
At https://www.studytonight.com/cpp/inline-functions.php they are explaining inline functions

All the inline functions are evaluated by the compiler, at the end of class declaration.

class ForwardReference
{
    int i;
    public:
    // call to undeclared function
    int f()
    {
        return g()+10;
    }
    int g()
    {
        return i;
    }
};

int main()
{
    ForwardReference fr;
    fr.f();
}

At the end they say :
"You must be thinking that this will lead to compile time error, but in this case it will work, because no inline function in a class is evaluated until the closing braces of class declaration."

......

why should one expect a compile time error? is it because no value for i has been set? If so, could someone explain better why it works, I don't get what's the point here, if the member functions are inline or not wouldn't it work the same?

Body:
What they are hinting at here, for why someone might expect a compile error, is the fact that although g is written below/after f, f can still reference it with no error.

If you were to move them out of the class and define+declare them at the same time then you would see the compile error (since f cannot see any g).

i.e.

int f(){
    return g() + 10;
}

int g(){
    return 32;
}

int main(){
    return f();
}

See for yourself on compiler explorer.


答:
The book is explicitly pointing out to you "no inline function in a class is evaluated until the closing braces of class declaration". Outside of a class declaration, with ordinary functions, this fails:

```<code>int f()
{
    return g()+10;
}
int g()
{
    return 0;
}
</code>```

Try to compile a C++ source file containing just this, and nothing more, and see for yourself.

In C++, all functions must be declared before use. Since g() is not declared, this is ill-formed and your compiler will reject it. g() must be declared before it's referenced:

```<code>int g();

int f()
{
    return g()+10;
}
int g()
{
    return 0;
}
</code>```

This does not applly to inline class method because, as your book explains, they are effectively evaluated when the class declaration is complete. At that point both f() and g() methods are declared, and the reference from f() to g() is well-formed.

Title: inline functions and forward references

Body:
The book is explicitly pointing out to you "no inline function in a class is evaluated until the closing braces of class declaration". Outside of a class declaration, with ordinary functions, this fails:

int f()
{
    return g()+10;
}
int g()
{
    return 0;
}

Try to compile a C++ source file containing just this, and nothing more, and see for yourself.

In C++, all functions must be declared before use. Since g() is not declared, this is ill-formed and your compiler will reject it. g() must be declared before it's referenced:

int g();

int f()
{
    return g()+10;
}
int g()
{
    return 0;
}

This does not applly to inline class method because, as your book explains, they are effectively evaluated when the class declaration is complete. At that point both f() and g() methods are declared, and the reference from f() to g() is well-formed.


问:
Create Multiplatform docker image without pushing each image with separate tag
I tried to create a Multiplatform docker image using this docker blog post https://www.docker.com/blog/multi-platform-docker-builds/

And it worked fine but as a result I got several images (eg. Multiplatform with tag:latest, and one for each platform - :amd64, :arm64 etc.)

But for example in ubuntu official registry (https://hub.docker.com/_/ubuntu) they have only one Multiplatform image with tag :latest and no other images.

How did they do it?

答:
Ok, I figured out how to do it. I need to make my image Official Docker Image

https://docs.docker.com/docker-hub/official_images/


问:
from C++ to C#
What are good c++ to C# articles/tutorial or books?
I am reading http://msdn.microsoft.com/en-us/magazine/cc301520.aspx and will read http://andymcm.com/csharpfaq.htm and http://www.ondotnet.com/pub/a/dotnet/2002/02/11/csharp_traps.html afterwards. Have any of you read any good books for ppl who have a strong understanding of programming && || C++ on the C# language (and libraries)?</p>

答:
Absolutely the best place to find information about C# is MSDN.

I recommend you follow the C# tutorials listed here: C# Tutorials on MSDN

I was also a C++ dev before I started doing C#. Those tutorials will get you up to speed.

Read about .NET as well.

Also, I forgot to mention the specification:

C# Language Specification on MSDN

It's worth reading through so you know some of the not-so-obvious differences between C# and C++ (for example, structs are pass by value whereas classes are pass by ref), and usage of 'out', 'ref', and other keywords. Just an example :).

ContentLicense: CC BY-SA 2.5

Title: from C++ to C#

LastEditorDisplayName: strager


问:
How can I make a loop that keeps going based on user input
for a class I have to make a simple program that allows a user to enter the weight of a package and then it tells the user the shipping price associated with that weight. It's not required for the homework but I am trying to add a do-while loop that asks the user to enter the letter y at the end of the loop if they would like to enter another weight and then the while section tests if the keepGoing variable is equal to y to restart the loop. I don't know why but no matter what the user enters, the loop does not restart. Even if the user enters y the program just ends, can anyone help please.
import java.util.Scanner;</p>

```<code>public class HwkChp4 {

    static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args) {

        double packageWeight;
        double underTwo = 1.10;
        double twoToSix = 2.20;
        double sixToTen = 3.70;
        double overTen = 3.80;
        String msg1 = "How much does the package weigh?";
        String msg2 = "The shipping cost is ";
        String keepGoing = "y";

        packageWeight = getDouble(msg1);

        do {
            if(packageWeight <= 2) {
                System.out.println(msg2 + "$" + underTwo);
            }

            if(packageWeight > 2 && packageWeight <= 6) {
                System.out.println(msg2 + "$" + twoToSix);
            }

            if(packageWeight > 6 && packageWeight <= 10) {
                System.out.println(msg2 + "$" + sixToTen);
            }

            if(packageWeight > 10) {
                System.out.println(msg2 + "$" + overTen);
            }
            System.out.println("Please enter y if you would like to enter another weight");
            System.out.println("otherwise please enter n");
            keepGoing = keyboard.next();
        } while (keepGoing == "y");

    }

    public static double getDouble(String msg1) {
        double decimal;
        System.out.println(msg1);
        decimal = keyboard.nextFloat();
        return decimal;
    }
}
</code>```

答:
In Java, equality can only be tested using the == operator on primitive data types (int, char, boolean, etc., basically data types that start lowercase). Strings and other data types are stored much differently and the == operator calls the variables memory addresses, rather than the data they hold. Therefore, you cannot use the the equality operator as no matter how hard you try, keepGoing will always be stored in a different memory address than "y" or any other variable you would try to set it to. (Unless of course you set them both to the same reference on purpose, but that would always result in true). So what you need to do is use String's builtin equals() function as is written below:

TLDR: Change keepGoing == y to keepGoing.equals(y)

Body:
for a class I have to make a simple program that allows a user to enter the weight of a package and then it tells the user the shipping price associated with that weight. It's not required for the homework but I am trying to add a do-while loop that asks the user to enter the letter y at the end of the loop if they would like to enter another weight and then the while section tests if the keepGoing variable is equal to y to restart the loop. I don't know why but no matter what the user enters, the loop does not restart. Even if the user enters y the program just ends, can anyone help please.
import java.util.Scanner;

public class HwkChp4 {

    static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args) {

        double packageWeight;
        double underTwo = 1.10;
        double twoToSix = 2.20;
        double sixToTen = 3.70;
        double overTen = 3.80;
        String msg1 = "How much does the package weigh?";
        String msg2 = "The shipping cost is ";
        String keepGoing = "y";

        packageWeight = getDouble(msg1);

        do {
            if(packageWeight <= 2) {
                System.out.println(msg2 + "$" + underTwo);
            }

            if(packageWeight > 2 && packageWeight <= 6) {
                System.out.println(msg2 + "$" + twoToSix);
            }

            if(packageWeight > 6 && packageWeight <= 10) {
                System.out.println(msg2 + "$" + sixToTen);
            }

            if(packageWeight > 10) {
                System.out.println(msg2 + "$" + overTen);
            }
            System.out.println("Please enter y if you would like to enter another weight");
            System.out.println("otherwise please enter n");
            keepGoing = keyboard.next();
        } while (keepGoing == "y");

    }

    public static double getDouble(String msg1) {
        double decimal;
        System.out.println(msg1);
        decimal = keyboard.nextFloat();
        return decimal;
    }
}


问:
Application Insight : Javascript SDK
I have noticed that the user location reported via Application Insight is very unreliable.
It is reporting my location in different state, Whereas when using WhatisMyIP it is able to accurately report my location.

Why such a difference with Application Insight ?

Here is what Appliction Insight Reports:

Here is the accurate location reported by WhatIsMyIP

答:
Application insights uses the GeoLite2 from MaxMind for IP and geolocation lookup.

And I tested it at my side by using GeoLite2 and also use WhatIsMyIP, they show me the different locations. So I guess the database for these 2 tools may different and cause this issue.

Hope it can help you.

Title: Application Insight : Javascript SDK


问:
Var type string and not int
Why is the var type still str in Case 1?. Shouldn't it be int?
In Case 2 when I'm not using the function it changes to int.

```<code>#CASE 1
num1=str()

def suma():

    num1=int(7)

suma()

print(type(num1)) # <class 'str'>

#CASE 2
num1=str()
num1=7

print(type(num1)) # <class 'int'>
</code>```

答:
You're not modifying the variable, rather creating a new num1 in the function's namespace. If you want to reference the outer variable you'd need to put global num1 inside of the suma function definition.

```<code>>>> num1 = '1'
>>> def suma():
...   num1 = 45345
...
>>> suma()
>>> num1
'1'
>>> def suma():
...     global num1
...     num1 = 4234
...
>>> suma()
>>> num1
4234
</code>```

This answer is the best on SO I've seen around global variables: https://stackoverflow.com/a/423596/5180047

Just realized the comment also answered what I've already said above, whoops! I'll leave this here anyways. Hopefully it's helpful.

Title: Var type string and not int

Body:
Why is the var type still str in Case 1?. Shouldn't it be int?
In Case 2 when I'm not using the function it changes to int.

#CASE 1
num1=str()

def suma():

    num1=int(7)

suma()

print(type(num1)) # <class 'str'>

#CASE 2
num1=str()
num1=7

print(type(num1)) # <class 'int'>

Body:
You're not modifying the variable, rather creating a new num1 in the function's namespace. If you want to reference the outer variable you'd need to put global num1 inside of the suma function definition.

>>> num1 = '1'
>>> def suma():
...   num1 = 45345
...
>>> suma()
>>> num1
'1'
>>> def suma():
...     global num1
...     num1 = 4234
...
>>> suma()
>>> num1
4234

This answer is the best on SO I've seen around global variables: https://stackoverflow.com/a/423596/5180047

Just realized the comment also answered what I've already said above, whoops! I'll leave this here anyways. Hopefully it's helpful.


问:
ionic 3 / ionic 4 ItemReorder, reordering is not working on the simulator browser
ionic have nice feature of ItemReorder. Sample code is like following

```<code><ion-list reorder="true" (ionItemReorder)="reorderItems($event)">
  <ion-item *ngFor="let item of listOfItems">
    <ion-label>
      {{item}}
    </ion-label>
  </ion-item>
    </ion-list>

reorderItems(event) {
    let element = this.listOfItems[event.from];
    this.listOfItems.splice(event.from, 1);
    this.listOfItems.splice(event.to, 0, element);
}
</code>```

After some time, re-ordering (when you drag & reorder an item) will not work on the browser (http://localhost:4200).

答:
Solution: Close the browser and reopen again on new browser / Incognito mode, then the reordering function will work.

I have simulated and figured out that the browsers are not fully supported for this feature. So re-launching on a new window will solve this issue.

Body:
ionic have nice feature of ItemReorder. Sample code is like following

<ion-list reorder="true" (ionItemReorder)="reorderItems($event)">
  <ion-item *ngFor="let item of listOfItems">
    <ion-label>
      {{item}}
    </ion-label>
  </ion-item>
    </ion-list>

reorderItems(event) {
    let element = this.listOfItems[event.from];
    this.listOfItems.splice(event.from, 1);
    this.listOfItems.splice(event.to, 0, element);
}

After some time, re-ordering (when you drag & reorder an item) will not work on the browser (http://localhost:4200).


问:
asp.net objectdatasource pass parameter from control as well as textbox
I have configured a GridView to fill data by an ObjectDataSource. This ObjectDataSource requires only one parameter which is bound to a DropDownList. This all works well.

When i load the page, it fills the DropDownList and whatever field is displayed in this DropDownListis passed as a parameter to the ObjectDataSource which further fills the GridView.

Now, i want to enhance the functionality and have a TextBox and Button next to this DropDownList. I want to give my user the option to either select a value from the DropDownList, OR TYPE IT IN THE TextBox AND PRESS ENTER TO UPDATE THE GridView.

Any idea how to do it?

I have tried dataSource.Selecting event. but it isn't working the way i want it to be.
please help

答:
This is a rough sample but basically what you can do is instead of creating a control parameter you can create a session parameter or something similar:

So when you click enter it will use the textbox value or when you change the dropdownlist it will use the dropdownlist's value.

You can also have radio button's giving the user the option to specify from where he want's the value.

```<code><asp:DropDownList ID="ddl" runat="server" AutoPostBack="true"
        onselectedindexchanged="ddl_SelectedIndexChanged"></asp:DropDownList>
        <asp:TextBox ID="txt" runat="server"></asp:TextBox>

        <asp:Button runat="server" Text="ClickMe" ID="btnOne" OnClick="btnOne_Click"/>

    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server">
        <SelectParameters>
            <asp:SessionParameter SessionField="ObjectParameterName" />
        </SelectParameters>
    </asp:ObjectDataSource>
</code>```

Code Behind:

```<code>    protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
        var ddl = (DropDownList)sender;
        Session["ObjectParameterName"] = ddl.SelectedValue;
        ObjectDataSource1.Select();
    }

    protected void btnOne_Click(object sender, EventArgs e)
    {
        var ddl = (DropDownList)sender;
        Session["ObjectParameterName"] = txt.Text;
        ObjectDataSource1.Select();
    }
</code>```

EDIT AFTERTHOUGHT

You can also instead of assigning the parameter to a session field, just set the objectdatasource's parameter directly (Barring Exception handling).

```<code>    protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
        var ddl = (DropDownList)sender;
        ObjectDataSource1.SelectParameters.Add(new Parameter() {Name="Name",DefaultValue=ddl.SelectedValue });
    }
</code>```

Body:
This is a rough sample but basically what you can do is instead of creating a control parameter you can create a session parameter or something similar:

So when you click enter it will use the textbox value or when you change the dropdownlist it will use the dropdownlist's value.

You can also have radio button's giving the user the option to specify from where he want's the value.

<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true"
        onselectedindexchanged="ddl_SelectedIndexChanged"></asp:DropDownList>
        <asp:TextBox ID="txt" runat="server"></asp:TextBox>

        <asp:Button runat="server" Text="ClickMe" ID="btnOne" OnClick="btnOne_Click"/>

    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server">
        <SelectParameters>
            <asp:SessionParameter SessionField="ObjectParameterName" />
        </SelectParameters>
    </asp:ObjectDataSource>

Code Behind:

    protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
        var ddl = (DropDownList)sender;
        Session["ObjectParameterName"] = ddl.SelectedValue;
        ObjectDataSource1.Select();
    }

    protected void btnOne_Click(object sender, EventArgs e)
    {
        var ddl = (DropDownList)sender;
        Session["ObjectParameterName"] = txt.Text;
        ObjectDataSource1.Select();
    }

EDIT AFTERTHOUGHT

You can also instead of assigning the parameter to a session field, just set the objectdatasource's parameter directly (Barring Exception handling).

    protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
        var ddl = (DropDownList)sender;
        ObjectDataSource1.SelectParameters.Add(new Parameter() {Name="Name",DefaultValue=ddl.SelectedValue });
    }


问:
For lib pcapplusplus, why there is no matchSubnet() for ipv6 address
For ipv4 address, I can use matchSubnet() checks whether the address matches a subnet.

But for ipv6, how can I do this?

答:
That's a good point, this feature doesn't currently exist in PcapPlusPlus.

I saw you opened a GitHub issue for that: https://github.com/seladb/PcapPlusPlus/issues/444

Let's follow up on it there.


问:
Use of Application ID URI in Azure Active Directory app
I have an Azure app service X(which has an ASP.NET web api project published to it) that I have configured with Y AAD app thru Advanced Authentication(using Y's client id in it). Now I also have another Z AAD app, which I want to use in OAuth 2.0 flow of POSTMAN.

The problem is when I'm providing Y's client id and resource id as Y's application id URI, I'm getting "Client is requesting token for itself." To avoid this I am replacing resource id with Application(client) id(the GUID) and it works find. Why?

Also, if I use Z's client id and Y's resource id URI, it doesnt work but it works when I use the GUI. So why is the application id URI required, what is the point of it if I can't use it?

答:
I think you may be misunderstanding something. lets be a little more concrete.
lets simplify a bit, you have WebAPI A with App Registration A. and you have a Client App Registration B.

First you set up WebAPI A to do whatever it needs, if it needs access to graph for example, then in API Permissions, you give it that access. then you either set up WebAPI A with an app secret or user flow
Finally you go to expose an API which is where the Application ID URI comes in, this is ONLY to allow Client B to access webAPI A. You only set this in App Reg A, you do not enter anything regarding this into WebAPI App Service. You do not need resource IDs in your web api, unless you are trying to access other apis, like graph for example.

then say you are trying to get Client B to use the webAPI, so in your App Registration B, you add an API Permission -> My APIs -> Select the scope you created just before.
then in Client B, that is where you set resource IDs, because you need to get a token that has access to web API.

I hope that clarifies a bit for you.
also here's a sample of a simple client to webapi flow, it's not 100% identical to yours since you're on an app service, but its essentially the same.
https://github.com/Azure-Samples/ms-identity-javascript-angular-spa-aspnetcore-webapi