问:
MVC3 Razor routing from Area to Root
I have searched the site and cant find anything similar to my question. I am new to MVC so I may be asking a dumb question.

When the site is launched there are default Home and About buttons at the top. I added a new button that points to an Area, that works just fine.

When I hover over the Home and About buttons after I go to the View that is in my Area, they links on them show they are now pointing to my Area and not the root of my project.

How do I tell these buttons to still point to the root and not my Area?

Thanks for any help or words of wisdom someone will be providing.

答:
This is supposed to take you to root folder.

```<code> @Html.RenderAction("Action", "Controller", new { area = "" });
</code>```

Okay I forgot to ask you what the routes look like in your global.asax.cs file? I've got a similar setup, and here are my route definitions

```<code> routes.MapRoute(
            "Home", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home",
               action = "MaintainLists",
              id = UrlParameter.Optional } // Parameter defaults
        );

 routes.MapRoute(
            "Default",                             // Route name
            "{controller}/{action}/{id}",          // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // defaults
        );
</code>```

Title: MVC3 Razor routing from Area to Root

Body:
This is supposed to take you to root folder.

 @Html.RenderAction("Action", "Controller", new { area = "" });

Okay I forgot to ask you what the routes look like in your global.asax.cs file? I've got a similar setup, and here are my route definitions

 routes.MapRoute(
            "Home", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home",
               action = "MaintainLists",
              id = UrlParameter.Optional } // Parameter defaults
        );

 routes.MapRoute(
            "Default",                             // Route name
            "{controller}/{action}/{id}",          // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // defaults
        );


来源: stackexchange

问:
Increase in number and show that number in entry box
I created global variable name count </p>

```<code>import tkinter as tk
from tkinter import ttk
import os
from csv import DictWriter, DictReader

data_label_frame=tk.LabelFrame()
data_label_frame.pack()

LARGE_FONT = ('Verdana' , 16,'bold')
global count
count=0
class sea_of_btc(tk.Tk):
    def __init__(self , *args , **kwargs):

        tk.Tk.__init__(self, *args , **kwargs)
        container = tk.Frame(self)
        container.pack(side = "top" , fill = "both" , expand = True)

        container.grid_rowconfigure(0 , weight =1 )
        container.grid_columnconfigure(0 , weight =1)
        self.config(background='#FAEBEF')
        self.frames = {}

        for F in (start_page , page_one ):
            frame = F(container , self)
            self.frames [F] = frame
            frame.grid (row = 0 , column = 0 , sticky= "nsew")
        self.show_frame(start_page)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        return frame

class start_page(tk.Frame):
    def __init__(self , parent , controller ):
        tk.Frame.__init__(self, parent)
</code>```

<p>Here now I want that whenever register_func will be called there will be increase in number count and after that whenever I open the frame it show me that number in entry box and user can not change that number means that it just work for the serial number to show in entry box    </p>

```<code>class page_one (tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        registration_number = tk.Label(data_label_frame, text = 'Registration No :', font = LARGE_FONT)
        registration_number.grid(row=0,column=0,padx=5  , pady=5 , sticky =tk.W )

        registration_number_var=tk.StringVar()
        registration_number_entry = ttk.Entry(data_label_frame,width = 5, font=LARGE_FONT ,textvariable=registration_number_var,
                                              )

        registration_number_entry.grid(row =1, column =0,padx=10,pady=10 , ipady=5 , sticky=tk.E)

        def register_fucn():
            count += 1
            with open('new.csv', 'a', newline='') as data_file:
                dict_writer = DictWriter(data_file, fieldnames=['Registration No',
                                                               ])
        registar_btn = ttk.Button(data_label_frame , text ='Registar' ,command= register_fucn)
        registar_btn.grid(row=2 , column=1, sticky =tk.E , padx=10 , pady=10,ipady=5)
</code>```

答:
Try using global inside the function</p>

```<code>import tkinter as tk
from tkinter import ttk
import os
from csv import DictWriter, DictReader

data_label_frame=tk.LabelFrame()
data_label_frame.pack()

LARGE_FONT = ('Verdana' , 16,'bold')
count = 0
class sea_of_btc(tk.Tk):
    def __init__(self , *args , **kwargs):

        tk.Tk.__init__(self, *args , **kwargs)
        container = tk.Frame(self)
        container.pack(side = "top" , fill = "both" , expand = True)

        container.grid_rowconfigure(0 , weight =1 )
        container.grid_columnconfigure(0 , weight =1)
        self.config(background='#FAEBEF')
        self.frames = {}

        for F in (start_page , page_one ):
            frame = F(container , self)
            self.frames [F] = frame
            frame.grid (row = 0 , column = 0 , sticky= "nsew")
        self.show_frame(start_page)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        return frame

class start_page(tk.Frame):
    def __init__(self , parent , controller ):
        tk.Frame.__init__(self, parent)

class page_one (tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        registration_number = tk.Label(data_label_frame, text = 'Registration No :', font = LARGE_FONT)
        registration_number.grid(row=0,column=0,padx=5  , pady=5 , sticky =tk.W )

        registration_number_var=tk.StringVar()
        registration_number_entry = ttk.Entry(data_label_frame,width = 5, font=LARGE_FONT ,textvariable=registration_number_var,
                                              )

        registration_number_entry.grid(row =1, column =0,padx=10,pady=10 , ipady=5 , sticky=tk.E)

        def register_fucn():
            global count
            count += 1
            with open('new.csv', 'a', newline='') as data_file:
                dict_writer = DictWriter(data_file, fieldnames=['Registration No',
                                                               ])
        registar_btn = ttk.Button(data_label_frame , text ='Registar' ,command= register_fucn)
        registar_btn.grid(row=2 , column=1, sticky =tk.E , padx=10 , pady=10,ipady=5)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created global variable name count

import tkinter as tk
from tkinter import ttk
import os
from csv import DictWriter, DictReader

data_label_frame=tk.LabelFrame()
data_label_frame.pack()

LARGE_FONT = ('Verdana' , 16,'bold')
global count
count=0
class sea_of_btc(tk.Tk):
    def __init__(self , *args , **kwargs):

        tk.Tk.__init__(self, *args , **kwargs)
        container = tk.Frame(self)
        container.pack(side = "top" , fill = "both" , expand = True)

        container.grid_rowconfigure(0 , weight =1 )
        container.grid_columnconfigure(0 , weight =1)
        self.config(background='#FAEBEF')
        self.frames = {}

        for F in (start_page , page_one ):
            frame = F(container , self)
            self.frames [F] = frame
            frame.grid (row = 0 , column = 0 , sticky= "nsew")
        self.show_frame(start_page)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        return frame

class start_page(tk.Frame):
    def __init__(self , parent , controller ):
        tk.Frame.__init__(self, parent)

Here now I want that whenever register_func will be called there will be increase in number count and after that whenever I open the frame it show me that number in entry box and user can not change that number means that it just work for the serial number to show in entry box

class page_one (tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        registration_number = tk.Label(data_label_frame, text = 'Registration No :', font = LARGE_FONT)
        registration_number.grid(row=0,column=0,padx=5  , pady=5 , sticky =tk.W )

        registration_number_var=tk.StringVar()
        registration_number_entry = ttk.Entry(data_label_frame,width = 5, font=LARGE_FONT ,textvariable=registration_number_var,
                                              )

        registration_number_entry.grid(row =1, column =0,padx=10,pady=10 , ipady=5 , sticky=tk.E)

        def register_fucn():
            count += 1
            with open('new.csv', 'a', newline='') as data_file:
                dict_writer = DictWriter(data_file, fieldnames=['Registration No',
                                                               ])
        registar_btn = ttk.Button(data_label_frame , text ='Registar' ,command= register_fucn)
        registar_btn.grid(row=2 , column=1, sticky =tk.E , padx=10 , pady=10,ipady=5)

Body:
Try using global inside the function

import tkinter as tk
from tkinter import ttk
import os
from csv import DictWriter, DictReader

data_label_frame=tk.LabelFrame()
data_label_frame.pack()

LARGE_FONT = ('Verdana' , 16,'bold')
count = 0
class sea_of_btc(tk.Tk):
    def __init__(self , *args , **kwargs):

        tk.Tk.__init__(self, *args , **kwargs)
        container = tk.Frame(self)
        container.pack(side = "top" , fill = "both" , expand = True)

        container.grid_rowconfigure(0 , weight =1 )
        container.grid_columnconfigure(0 , weight =1)
        self.config(background='#FAEBEF')
        self.frames = {}

        for F in (start_page , page_one ):
            frame = F(container , self)
            self.frames [F] = frame
            frame.grid (row = 0 , column = 0 , sticky= "nsew")
        self.show_frame(start_page)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        return frame

class start_page(tk.Frame):
    def __init__(self , parent , controller ):
        tk.Frame.__init__(self, parent)

class page_one (tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        registration_number = tk.Label(data_label_frame, text = 'Registration No :', font = LARGE_FONT)
        registration_number.grid(row=0,column=0,padx=5  , pady=5 , sticky =tk.W )

        registration_number_var=tk.StringVar()
        registration_number_entry = ttk.Entry(data_label_frame,width = 5, font=LARGE_FONT ,textvariable=registration_number_var,
                                              )

        registration_number_entry.grid(row =1, column =0,padx=10,pady=10 , ipady=5 , sticky=tk.E)

        def register_fucn():
            global count
            count += 1
            with open('new.csv', 'a', newline='') as data_file:
                dict_writer = DictWriter(data_file, fieldnames=['Registration No',
                                                               ])
        registar_btn = ttk.Button(data_label_frame , text ='Registar' ,command= register_fucn)
        registar_btn.grid(row=2 , column=1, sticky =tk.E , padx=10 , pady=10,ipady=5)


问:
Time zone issue in Java
I am using this simple code to fetch the time zone ids of the current time zone that has been set in the system.

```<code>public class Main {

    public static void main(String[] args)
    {   TimeZone timezone = TimeZone.getDefault();
        System.out.println(timezone.getID());
    }
}
</code>```

I use the tzutil /g to determine the time zone and tzutil /s to set the timezone.
I have observed when time zone is set to Eastern Standard Time the above code returns id as America/New_York but when it is set to Eastern Standard Time_dstoff then I get id as GMT-05:00 which is undesirable. I want the output in the form of continent/city.

How would I get that?

答:
My first answer is that you shouldn’t care about the default time zone setting of your JVM. Your Java code shouldn’t rely on it anyway. The default setting can be changed at any time from another part of your program or another program running in the same JVM, so is fragile. Instead specify explicit time zone in your time zone sensitive operations.

If you still want to rely on the default, here’s hack to set it to some continent/city time zone if it happens to be the GMT-05:00 that you consider undesirable.

```<code>    ZoneId defaultZoneId = ZoneId.systemDefault();
    ZoneId desiredTimeZone = null;
    if (defaultZoneId.equals(ZoneId.of("GMT-05:00"))) {
        // Pick a date in summer
        LocalDate dateInSummer = Year.now().atMonthDay(MonthDay.of(Month.JULY, 7));
        DateTimeFormatter zoneFormatter = DateTimeFormatter.ofPattern("zzzz", Locale.ENGLISH);
        for (String zid : ZoneId.getAvailableZoneIds()) {
            ZoneId zone = ZoneId.of(zid);
            String timeZoneName = dateInSummer.atStartOfDay(zone).format(zoneFormatter);
            if (zid.startsWith("America/") && timeZoneName.equals("Eastern Standard Time")) {
                desiredTimeZone = zone;
                break;
            }
        }
    }

    System.out.println("Time zone: " + desiredTimeZone);
</code>```

On my JDK 11 I got:

Time zone: America/Panama

To set it as the default we unfortunately have to go through the poorly designed and otherwise long outdated TimeZone class:

```<code>    TimeZone.setDefault(TimeZone.getTimeZone(desiredTimeZone));
</code>```

There is one more reason to warn against using America/Panama or some other time zone ID instead of GMT-05:00: While Panama has been using offset -05:00 from GMT/UTC since some time in 1908, it hasn’t always, so for historic dates you will get incorrect times from using it.

According to timeanddate.com the places that use Eastern Standard Time all year (no summer time/DST) are:

Nunavut - Southampton Island only (Coral Harbour) (Canada) (America/Coral_Harbour time zone)

Quintana Roo (Mexico) (America/Cancun time zone)

Cayman Islands (America/Cayman)

Jamaica (America/Jamaica)

Panama (America/Panama)

My Java additionally lists America/Atikokan (also in Canada).

The list doesn’t include any place in the United States. I believe that none of the above have been using offset -05:00 always. That is to say, each of them has had a different offset at some point in history, and Java will use that different offset for historic dates.

So which time zone to use?

Edit: Andreas in a comment pointed out that neither Etc/GMT+5 nor SystemV/EST5 has the problem I mentioned about applying offsets to historic dates that are probably unexpected. So you may consider one of those. The pros of each are, as I see them:

```<code>                                    America/Xxx Etc/GMT+5 SystemV/EST5 GMT-05:00
Official IANA time zone?                Yes        Yes
With slash?                             Yes        Yes        Yes
Continent/city?                         Yes
Good for historical dates?                         Yes        Yes         Yes
Prints as EST/Eastern Standard Time?    Yes                   Yes
</code>```

(Your starting point, GMT-05:00, is only included for the comparison. And which ones are really good for historic dates of course depends on what you require for those.)

Links

EST – Eastern Standard Time / Eastern Time (Standard Time) on timeanddate.com.

List of tz database time zones

Title: Time zone issue in Java

Body:
I am using this simple code to fetch the time zone ids of the current time zone that has been set in the system.

public class Main {

    public static void main(String[] args)
    {   TimeZone timezone = TimeZone.getDefault();
        System.out.println(timezone.getID());
    }
}

I use the tzutil /g to determine the time zone and tzutil /s to set the timezone.
I have observed when time zone is set to Eastern Standard Time the above code returns id as America/New_York but when it is set to Eastern Standard Time_dstoff then I get id as GMT-05:00 which is undesirable. I want the output in the form of continent/city.

How would I get that?

Body:
My first answer is that you shouldn’t care about the default time zone setting of your JVM. Your Java code shouldn’t rely on it anyway. The default setting can be changed at any time from another part of your program or another program running in the same JVM, so is fragile. Instead specify explicit time zone in your time zone sensitive operations.

If you still want to rely on the default, here’s hack to set it to some continent/city time zone if it happens to be the GMT-05:00 that you consider undesirable.

    ZoneId defaultZoneId = ZoneId.systemDefault();
    ZoneId desiredTimeZone = null;
    if (defaultZoneId.equals(ZoneId.of("GMT-05:00"))) {
        // Pick a date in summer
        LocalDate dateInSummer = Year.now().atMonthDay(MonthDay.of(Month.JULY, 7));
        DateTimeFormatter zoneFormatter = DateTimeFormatter.ofPattern("zzzz", Locale.ENGLISH);
        for (String zid : ZoneId.getAvailableZoneIds()) {
            ZoneId zone = ZoneId.of(zid);
            String timeZoneName = dateInSummer.atStartOfDay(zone).format(zoneFormatter);
            if (zid.startsWith("America/") && timeZoneName.equals("Eastern Standard Time")) {
                desiredTimeZone = zone;
                break;
            }
        }
    }

    System.out.println("Time zone: " + desiredTimeZone);

On my JDK 11 I got:

Time zone: America/Panama

To set it as the default we unfortunately have to go through the poorly designed and otherwise long outdated TimeZone class:

    TimeZone.setDefault(TimeZone.getTimeZone(desiredTimeZone));

There is one more reason to warn against using America/Panama or some other time zone ID instead of GMT-05:00: While Panama has been using offset -05:00 from GMT/UTC since some time in 1908, it hasn’t always, so for historic dates you will get incorrect times from using it.

According to timeanddate.com the places that use Eastern Standard Time all year (no summer time/DST) are:

Nunavut - Southampton Island only (Coral Harbour) (Canada) (America/Coral_Harbour time zone)

Quintana Roo (Mexico) (America/Cancun time zone)

Cayman Islands (America/Cayman)

Jamaica (America/Jamaica)

Panama (America/Panama)

My Java additionally lists America/Atikokan (also in Canada).

The list doesn’t include any place in the United States. I believe that none of the above have been using offset -05:00 always. That is to say, each of them has had a different offset at some point in history, and Java will use that different offset for historic dates.

So which time zone to use?

Edit: Andreas in a comment pointed out that neither Etc/GMT+5 nor SystemV/EST5 has the problem I mentioned about applying offsets to historic dates that are probably unexpected. So you may consider one of those. The pros of each are, as I see them:

                                    America/Xxx Etc/GMT+5 SystemV/EST5 GMT-05:00
Official IANA time zone?                Yes        Yes
With slash?                             Yes        Yes        Yes
Continent/city?                         Yes
Good for historical dates?                         Yes        Yes         Yes
Prints as EST/Eastern Standard Time?    Yes                   Yes

(Your starting point, GMT-05:00, is only included for the comparison. And which ones are really good for historic dates of course depends on what you require for those.)

Links

EST – Eastern Standard Time / Eastern Time (Standard Time) on timeanddate.com.

List of tz database time zones


问:
Cannot implicitly convert string to Microsoft.Bot.Schema.Activity
I am working on Bot Framework, and want some help.

I want to show a new login card. For  that I am creating a new activity because I want Bot to show that login card when the chat loads.

I have this code with me:

As you can see in the above code, when I am writing:

```<code>Activity activity = turnContext.Activity.ToString()
</code>```

It gives me error stating:

Cannot implicitly convert from string to Microsoft.Bot.Schema.Activity.

To check if this works, I wrote:

```<code>Activity activity = (Activity)turnContext.Activity.ToString()
</code>```

but still no luck.

What am I missing here? And what is the correct method to create an activity??

答:
Check the property you are using: https://learn.microsoft.com/en-us/dotnet/api/microsoft.bot.builder.turncontext.activity?view=botbuilder-dotnet-stable#Microsoft_Bot_Builder_TurnContext_Activity

Gets the activity associated with this turn; or null when processing a proactive message.

So your code would build like this:

```<code>Activity activity = turnContext.Activity;
</code>```

Body:
I am working on Bot Framework, and want some help.

I want to show a new login card. For  that I am creating a new activity because I want Bot to show that login card when the chat loads.

I have this code with me:

As you can see in the above code, when I am writing:

Activity activity = turnContext.Activity.ToString()

It gives me error stating:

Cannot implicitly convert from string to Microsoft.Bot.Schema.Activity.

To check if this works, I wrote:

Activity activity = (Activity)turnContext.Activity.ToString()

but still no luck.

What am I missing here? And what is the correct method to create an activity??

Body:
Check the property you are using: https://learn.microsoft.com/en-us/dotnet/api/microsoft.bot.builder.turncontext.activity?view=botbuilder-dotnet-stable#Microsoft_Bot_Builder_TurnContext_Activity

Gets the activity associated with this turn; or null when processing a proactive message.

So your code would build like this:

Activity activity = turnContext.Activity;


问:
Why is file not being written to the internal storage?
I am trying to create a text file and fill it with some data. Exception is being generated as shown in the code below. The file isn't getting saved and exception is generated. What is wrong with my code?

```<code>import androidx.appcompat.app.AppCompatActivity;
import java.io.*;
import android.widget.Toast;

import android.os.Bundle;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String fileName = "thisdata.txt";
    String text = "8934759034850938450348509";

    try
    {
        FileWriter writer = new FileWriter(fileName,true);
        writer.append(text);
        writer.flush();
        writer.close();
        Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
    }
    catch(IOException e)
    {
        e.printStackTrace();
        Toast.makeText(this, "Data has not", Toast.LENGTH_SHORT).show();

    }

    }
}
</code>```

My manifest files have these two lines.

```<code> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</code>```

答:
In this code snippet you are not creating a file, but simply passing a random String as file name into the FileWriter's constructor.
If you want to create the file inside your own app (Accessible only by your app), you can create the file as below.Or if you are not sure where to create the file, pls refer this article from dev.android</p>

```<code> File file = new File(getFilesDir(),"thisdata.txt");
 String fileName = file.getAbsolutePath() ;
String text = "8934759034850938450348509";

try
{
    FileWriter writer = new FileWriter(fileName,true);
    writer.append(text);
    writer.flush();
    writer.close();
    Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
    e.printStackTrace();
    Toast.makeText(this, "Data has not", Toast.LENGTH_SHORT).show();

}

}
</code>```

Body:
I am trying to create a text file and fill it with some data. Exception is being generated as shown in the code below. The file isn't getting saved and exception is generated. What is wrong with my code?

import androidx.appcompat.app.AppCompatActivity;
import java.io.*;
import android.widget.Toast;

import android.os.Bundle;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String fileName = "thisdata.txt";
    String text = "8934759034850938450348509";

    try
    {
        FileWriter writer = new FileWriter(fileName,true);
        writer.append(text);
        writer.flush();
        writer.close();
        Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
    }
    catch(IOException e)
    {
        e.printStackTrace();
        Toast.makeText(this, "Data has not", Toast.LENGTH_SHORT).show();

    }

    }
}

My manifest files have these two lines.

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Body:
In this code snippet you are not creating a file, but simply passing a random String as file name into the FileWriter's constructor.
If you want to create the file inside your own app (Accessible only by your app), you can create the file as below.Or if you are not sure where to create the file, pls refer this article from dev.android

 File file = new File(getFilesDir(),"thisdata.txt");
 String fileName = file.getAbsolutePath() ;
String text = "8934759034850938450348509";

try
{
    FileWriter writer = new FileWriter(fileName,true);
    writer.append(text);
    writer.flush();
    writer.close();
    Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
    e.printStackTrace();
    Toast.makeText(this, "Data has not", Toast.LENGTH_SHORT).show();

}

}


问:
Not getting correct path from root node to point
I am trying to find a path from the root node to a given point but ends up in getting an empty array.In the output I should get List of string of path id's from root to the given point. Please check below link for detailed description about problem.

Problem Statement

I have tried below code to get string id's.

```<code>public static List<String> findPathToNode(Node rootNode, Point toFind) {
    // @ToDo Implement this routine
    List<String> nodeList = new ArrayList<>();

    return getAllNodesForPoint(rootNode, toFind, nodeList);   }

  //Recursive function to loop through all nodes of tree and return empty LinkedList   // if point not found or NOT Empty with the path to the point, if point is found

  static List<String> getAllNodesForPoint(Node n, Point p, List<String> list) {
    list.add(n.getId());
    for (Node temp : n.getChildren()) {
      if (temp.getChildren().size() > 0) {
        if (isContained(temp, p)) {
          list.add(temp.getId());
          return list;
        } else {
          getAllNodesForPoint(temp, p, list);
        }
      } else {
        list = new LinkedList<>();
        list.add(n.getId());
      }
    }
    list = new ArrayList<>();
    return list;   }

  static boolean isContained(Node e, Point p){
    Point topLeft = new Point(e.getLeft(), e.getTop());
    Point topRight = new Point(e.getLeft()+e.getWidth(), e.getTop());
    Point bottomLeft = new Point(e.getLeft(), e.getTop()+e.getHeight());
    Point bottomRight = new Point(e.getLeft()+e.getWidth(), e.getTop()+e.getHeight());
    if(topLeft.getX()<p.getX()
            &&p.getX()<topRight.getX()
            &&topLeft.getY()<p.getY()
            &&bottomLeft.getY()>p.getY()){
      return true;
    }
    else{
      return false;
    }   }
</code>```

Thank you in advanced!!!

答:
Below is the code snippet that would do the job as stated in the Problem statement:</p>

```<code>private static void getPath(Node root, Point p, List<String> result) {
    if (root != null) {
        result.add(root.getId());
        List<Node> childNodes = root.getChildren();
        if (childNodes != null && !childNodes.isEmpty()) {
            Node child = null;
            for (Node node : childNodes) {
                if (isLeftBoundCondtionMet(node, p) && isTopBoundCondtionMet(node, p)) {
                    child = node;
                }
            }
            getPath(child, p, result);
        }
    }
}

public static Boolean isLeftBoundCondtionMet(Node root, Point p) {
    return root.getLeft() < p.getX() && (p.getX() < (root.getLeft() + root.getWidth()));
}

public static Boolean isTopBoundCondtionMet(Node root, Point p) {
    return root.getTop() < p.getY() && (p.getY() < (root.getTop() + root.getHeight()));
}
</code>```

Body:
I am trying to find a path from the root node to a given point but ends up in getting an empty array.In the output I should get List of string of path id's from root to the given point. Please check below link for detailed description about problem.

Problem Statement

I have tried below code to get string id's.

public static List<String> findPathToNode(Node rootNode, Point toFind) {
    // @ToDo Implement this routine
    List<String> nodeList = new ArrayList<>();

    return getAllNodesForPoint(rootNode, toFind, nodeList);   }

  //Recursive function to loop through all nodes of tree and return empty LinkedList   // if point not found or NOT Empty with the path to the point, if point is found

  static List<String> getAllNodesForPoint(Node n, Point p, List<String> list) {
    list.add(n.getId());
    for (Node temp : n.getChildren()) {
      if (temp.getChildren().size() > 0) {
        if (isContained(temp, p)) {
          list.add(temp.getId());
          return list;
        } else {
          getAllNodesForPoint(temp, p, list);
        }
      } else {
        list = new LinkedList<>();
        list.add(n.getId());
      }
    }
    list = new ArrayList<>();
    return list;   }

  static boolean isContained(Node e, Point p){
    Point topLeft = new Point(e.getLeft(), e.getTop());
    Point topRight = new Point(e.getLeft()+e.getWidth(), e.getTop());
    Point bottomLeft = new Point(e.getLeft(), e.getTop()+e.getHeight());
    Point bottomRight = new Point(e.getLeft()+e.getWidth(), e.getTop()+e.getHeight());
    if(topLeft.getX()<p.getX()
            &&p.getX()<topRight.getX()
            &&topLeft.getY()
p.getY()){
      return true;
    }
    else{
      return false;
    }   }

Thank you in advanced!!!

Body:
Below is the code snippet that would do the job as stated in the Problem statement:

private static void getPath(Node root, Point p, List<String> result) {
    if (root != null) {
        result.add(root.getId());
        List<Node> childNodes = root.getChildren();
        if (childNodes != null && !childNodes.isEmpty()) {
            Node child = null;
            for (Node node : childNodes) {
                if (isLeftBoundCondtionMet(node, p) && isTopBoundCondtionMet(node, p)) {
                    child = node;
                }
            }
            getPath(child, p, result);
        }
    }
}

public static Boolean isLeftBoundCondtionMet(Node root, Point p) {
    return root.getLeft() < p.getX() && (p.getX() < (root.getLeft() + root.getWidth()));
}

public static Boolean isTopBoundCondtionMet(Node root, Point p) {
    return root.getTop() < p.getY() && (p.getY() < (root.getTop() + root.getHeight()));
}


问:
I want to run a python file from php. The python file contains many package (such as torch, models etc.)
I want to run a python file from PHP. The python file contains many packages (such as torch, models, etc.). I can easily run it using the command line but while calling it from PHP using shell_exec it does not run.

The php files looks somewhat likes this:

$output = exec ('cd /home/prabhakar/Hackathon/Text_Speech/ ; conda activate neural_tts ; python quick_start.py -u --input_text "Hi?" ');
    echo $output."
";

```

<p>python file is:</p>

<pre class="lang-py prettyprint-override"><code>    import torch
    from models.fatchord_version import WaveRNN
    from utils import hparams as hp
    from utils.text.symbols import symbols
    from models.tacotron import Tacotron
    import argparse
    from utils.text import text_to_sequence
    from utils.display import save_attention, simple_table
    import zipfile, os

    os.makedirs('quick_start/tts_weights/', exist_ok=True)
    os.makedirs('quick_start/voc_weights/', exist_ok=True)

    zip_ref =
    zipfile.ZipFile('pretrained/ljspeech.wavernn.mol.800k.zip', 'r')
    zip_ref.extractall('quick_start/voc_weights/')
    zip_ref.close()

    zip_ref =
    zipfile.ZipFile('pretrained/ljspeech.tacotron.r2.180k.zip', 'r')
    zip_ref.extractall('quick_start/tts_weights/')
    zip_ref.close()

    if __name__ == "__main__":
        print("Hello World!!")
        exit()
</code>```

答: You might be using virtual environment. Try first activating the virtual environment through PHP and then running the python code.</p>

Body:
I want to run a python file from PHP. The python file contains many packages (such as torch, models, etc.). I can easily run it using the command line but while calling it from PHP using shell_exec it does not run.

The php files looks somewhat likes this:

$output = exec ('cd /home/prabhakar/Hackathon/Text_Speech/ ; conda activate neural_tts ; python quick_start.py -u --input_text "Hi?" ');
    echo $output."
";

python file is:

    import torch
    from models.fatchord_version import WaveRNN
    from utils import hparams as hp
    from utils.text.symbols import symbols
    from models.tacotron import Tacotron
    import argparse
    from utils.text import text_to_sequence
    from utils.display import save_attention, simple_table
    import zipfile, os

    os.makedirs('quick_start/tts_weights/', exist_ok=True)
    os.makedirs('quick_start/voc_weights/', exist_ok=True)

    zip_ref =
    zipfile.ZipFile('pretrained/ljspeech.wavernn.mol.800k.zip', 'r')
    zip_ref.extractall('quick_start/voc_weights/')
    zip_ref.close()

    zip_ref =
    zipfile.ZipFile('pretrained/ljspeech.tacotron.r2.180k.zip', 'r')
    zip_ref.extractall('quick_start/tts_weights/')
    zip_ref.close()

    if __name__ == "__main__":
        print("Hello World!!")
        exit()


问:
How to add arrows to scatterplot in r?
I have a 'fire' dataset that looks like this:

```<code>    species  THREATEN_1    Total_area   Area_remai
    a.         V.              30.        10
    b.         EN.             100.       50
    c.         V.              5.          2
</code>```

I want to create a scatterplot which shows the movement of habitat (i.e. from Total_area to Area_remai). Similar to the attached.

I have started the code, but don't know how to add the lines and movement:

```<code>    g <- ggplot(fires, aes(x = THREATEN_1, y = Total_area, color = THREATEN_1)) +
    geom_point(fill = "indianred") +
    labs(x = "Threatened status", y = "Extent of suitable habitat (Ha)")
    g + geom_jitter(aes(color = THREATEN_1), alpha = 0.25,
              position = position_jitter(width = 0.3)) +
    theme(legend.position = "none")
</code>```

答:
Here is a way to plot the arrows. Use geom_segment, argument arrow paying attention to the arrow(length, unit) settings.

```<code>library(ggplot2)

g <- ggplot(fires, aes(x = THREATEN_1, y = Total_area, color = THREATEN_1)) +
  geom_point() +
  labs(x = "Threatened status", y = "Extent of suitable habitat (Ha)")

g + geom_segment(aes(xend = THREATEN_1, yend = Area_remai),
                 arrow = arrow(length = unit(0.025, "npc"))) +
  scale_color_manual(values = c("indianred", "dodgerblue")) +
  theme_bw() +
  theme(legend.position = "none") +
  facet_wrap(~ THREATEN_1, scales = "free_x")
</code>```

jitter the data.

The code above will overplot the arrows, in the question it is asked to jitter the data set.

```<code>library(dplyr)

set.seed(1234)
fires %>%
  group_by(THREATEN_1) %>%
  mutate(THREATEN_1b = jitter(as.numeric(THREATEN_1), amount = 0.3/2)) %>%
  ggplot(aes(x = THREATEN_1b, y = Total_area, color = THREATEN_1)) +
  geom_point(aes(color = THREATEN_1), alpha = 0.25) +
  labs(x = "Threatened status", y = "Extent of suitable habitat (Ha)") -> g

g + geom_segment(aes(xend = THREATEN_1b, yend = Area_remai),
                 arrow = arrow(length = unit(0.025, "npc"))) +
  scale_color_manual(values = c("indianred", "dodgerblue")) +
  theme_bw() +
  theme(legend.position = "none",
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank()) +
  facet_wrap(~ THREATEN_1, scales = "free_x")
</code>```

Data.

```<code>fires <- read.table(text = "
species  THREATEN_1    Total_area   Area_remai
    a         V              30.        10
    b         EN             100.       50
    c         V              5.          2
", header = TRUE)
</code>```

Title: How to add arrows to scatterplot in r?

Body:
I have a 'fire' dataset that looks like this:

    species  THREATEN_1    Total_area   Area_remai
    a.         V.              30.        10
    b.         EN.             100.       50
    c.         V.              5.          2

I want to create a scatterplot which shows the movement of habitat (i.e. from Total_area to Area_remai). Similar to the attached.

I have started the code, but don't know how to add the lines and movement:

    g <- ggplot(fires, aes(x = THREATEN_1, y = Total_area, color = THREATEN_1)) +
    geom_point(fill = "indianred") +
    labs(x = "Threatened status", y = "Extent of suitable habitat (Ha)")
    g + geom_jitter(aes(color = THREATEN_1), alpha = 0.25,
              position = position_jitter(width = 0.3)) +
    theme(legend.position = "none")

Body:
Here is a way to plot the arrows. Use geom_segment, argument arrow paying attention to the arrow(length, unit) settings.

library(ggplot2)

g <- ggplot(fires, aes(x = THREATEN_1, y = Total_area, color = THREATEN_1)) +
  geom_point() +
  labs(x = "Threatened status", y = "Extent of suitable habitat (Ha)")

g + geom_segment(aes(xend = THREATEN_1, yend = Area_remai),
                 arrow = arrow(length = unit(0.025, "npc"))) +
  scale_color_manual(values = c("indianred", "dodgerblue")) +
  theme_bw() +
  theme(legend.position = "none") +
  facet_wrap(~ THREATEN_1, scales = "free_x")

jitter the data.

The code above will overplot the arrows, in the question it is asked to jitter the data set.

library(dplyr)

set.seed(1234)
fires %>%
  group_by(THREATEN_1) %>%
  mutate(THREATEN_1b = jitter(as.numeric(THREATEN_1), amount = 0.3/2)) %>%
  ggplot(aes(x = THREATEN_1b, y = Total_area, color = THREATEN_1)) +
  geom_point(aes(color = THREATEN_1), alpha = 0.25) +
  labs(x = "Threatened status", y = "Extent of suitable habitat (Ha)") -> g

g + geom_segment(aes(xend = THREATEN_1b, yend = Area_remai),
                 arrow = arrow(length = unit(0.025, "npc"))) +
  scale_color_manual(values = c("indianred", "dodgerblue")) +
  theme_bw() +
  theme(legend.position = "none",
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank()) +
  facet_wrap(~ THREATEN_1, scales = "free_x")

Data.

fires <- read.table(text = "
species  THREATEN_1    Total_area   Area_remai
    a         V              30.        10
    b         EN             100.       50
    c         V              5.          2
", header = TRUE)


问:
Adjusting top axis title and labels plots of plotmo::plot_glmnet in R
I use r package plotmo to visualize coefficient shrinkage of LASSO regression. By default, it add a top axis with title 'Degrees of Freedom'. How could I delete the top title or change the content of it? Generally, how could I adjust top axis (including title and axis labels) ploted by plotmo::plot_glmnet  ?

library(glmnet)
library(plotmo)
fit = glmnet(as.matrix(mtcars[-1]), mtcars[,1])
plot_glmnet(fit,xvar='lambda',label=7)
```

<p><img src="https://i.stack.imgur.com/ywiVZ.png" alt="enter image description here"></p>

<p>I've tried to use <code>mtext</code> and <code>axis</code> function, but it didn't work:</p>

```plot_glmnet(fit,xvar='lambda',label=7)
mtext('new top title', side=3)
```

答:
You can add a title on top of the "Degrees of Freedom" by providing the main argument that is given to the underlying call to plot:

plot_glmnet(fit,xvar='lambda',label=7, main = "new top title")
```

In response to the comment, you can't directly delete "Degrees of Freedom". If you look at the code for plot_glmnet, you can see it is hardcoded as toplab. You would need to manually adjust the code, either permanently with a fork of the package/function or each session by using trace(plot_glmnet, edit = T) and setting toplab = "new top title". You can find the relevant code section just near the bottom of the plot_glmnet code.

Body:
I use r package plotmo to visualize coefficient shrinkage of LASSO regression. By default, it add a top axis with title 'Degrees of Freedom'. How could I delete the top title or change the content of it? Generally, how could I adjust top axis (including title and axis labels) ploted by plotmo::plot_glmnet  ?

library(glmnet)
library(plotmo)
fit = glmnet(as.matrix(mtcars[-1]), mtcars[,1])
plot_glmnet(fit,xvar='lambda',label=7)

I've tried to use mtext and axis function, but it didn't work:

plot_glmnet(fit,xvar='lambda',label=7)
mtext('new top title', side=3)

Body:
You can add a title on top of the "Degrees of Freedom" by providing the main argument that is given to the underlying call to plot:

plot_glmnet(fit,xvar='lambda',label=7, main = "new top title")

In response to the comment, you can't directly delete "Degrees of Freedom". If you look at the code for plot_glmnet, you can see it is hardcoded as toplab. You would need to manually adjust the code, either permanently with a fork of the package/function or each session by using trace(plot_glmnet, edit = T) and setting toplab = "new top title". You can find the relevant code section just near the bottom of the plot_glmnet code.


问:
sed command is not working properly when using wildcard
I am trying to use 'sed' command to delete the last line of the files that matches the wildcard pattern given as command line argument and the move the file from that directory to the present directory. The code is as follow:

```<code>DIR="/home/usr_name/trash/"
for file in "$@"
    do
        if [ $file != "-h" ] //ignore this line
        then
            temp="$DIR$file"
            sed '$d' "$DIR$file"
            mv $temp .
        fi
    done
</code>```

The code is moving the file but its not executing the 'sed' command to delete the last line. Giving the wildcard as ab* , it gives the following error:

```<code>sed: can't read /home/usr_name/trash/ab*: No such file or directory
</code>```

Help me to figure out this situation.

答:
When you run

```<code>yourcript ab*
</code>```

the shell attempts to expand the wildcard in the current directory, then passes in the result as "$@". If there are no matches in the current directory, the expanded wildcard (in the shell's traditional default configuration) is now the literal string ab*, and no further wildcard expansion will be attempted.

(Bash has nullglob to change this behavior, so that a wildcard which doesn't match any files gets replaced with nothing; but that doesn't really help here.)

If the wildcard does match some files, chances are that those files won't exist in the other directory,
or (in the general case) that the files with those names will not be the files you actually wanted to process.

In the worst case, maybe there are some files in the current directory which match the wildcard and they all duplicate files with the same name in the destination directory. So if you have ab and abc both in the current directory and in the other directory, but the other directory also contains abecedary and abugida, your command will only process the first two, and you will receive no warning that the other two were never matched and processed.

Bottom line, probably rethink your approach to pass the full path to the files you want to process into the script; then, the rest is easy, and your script's behavior will be predictable, and consistent with how other file-processing utilities behave.

You'll still need to make sed actually modify each file. Just sed '$d' files will not change files, just print the modified contents to standard output. If you have sed -i, probably use that.

for file in "$@"
do
    # Note added quotes
    if [ "$file" != "-h" ] # ignore this line
    then
        sed -i '$d' "$file"
        mv "$file" .
    fi
done
```

<p>Usage:</p>

```yourscript /home/usr_name/trash/ab*
```

Body:
I am trying to use 'sed' command to delete the last line of the files that matches the wildcard pattern given as command line argument and the move the file from that directory to the present directory. The code is as follow:

DIR="/home/usr_name/trash/"
for file in "$@"
    do
        if [ $file != "-h" ] //ignore this line
        then
            temp="$DIR$file"
            sed '$d' "$DIR$file"
            mv $temp .
        fi
    done

The code is moving the file but its not executing the 'sed' command to delete the last line. Giving the wildcard as ab* , it gives the following error:

sed: can't read /home/usr_name/trash/ab*: No such file or directory

Help me to figure out this situation.

Body:
When you run

yourcript ab*

the shell attempts to expand the wildcard in the current directory, then passes in the result as "$@". If there are no matches in the current directory, the expanded wildcard (in the shell's traditional default configuration) is now the literal string ab*, and no further wildcard expansion will be attempted.

(Bash has nullglob to change this behavior, so that a wildcard which doesn't match any files gets replaced with nothing; but that doesn't really help here.)

If the wildcard does match some files, chances are that those files won't exist in the other directory,
or (in the general case) that the files with those names will not be the files you actually wanted to process.

In the worst case, maybe there are some files in the current directory which match the wildcard and they all duplicate files with the same name in the destination directory. So if you have ab and abc both in the current directory and in the other directory, but the other directory also contains abecedary and abugida, your command will only process the first two, and you will receive no warning that the other two were never matched and processed.

Bottom line, probably rethink your approach to pass the full path to the files you want to process into the script; then, the rest is easy, and your script's behavior will be predictable, and consistent with how other file-processing utilities behave.

You'll still need to make sed actually modify each file. Just sed '$d' files will not change files, just print the modified contents to standard output. If you have sed -i, probably use that.

for file in "$@"
do
    # Note added quotes
    if [ "$file" != "-h" ] # ignore this line
    then
        sed -i '$d' "$file"
        mv "$file" .
    fi
done

Usage:

yourscript /home/usr_name/trash/ab*


问:
Bulk administration using csv import to remove device from Azure AD list
I am trying to create a PowerShell script to cleanup Azure AD devices.
I figured I should probably find a combination of these:

```<code>Get-MsolDevice -all | select-object -Property Enabled, DeviceId, DisplayName, DeviceTrustType, ApproximateLastLogonTimestamp | export-csv C:\Temp\devicelist-summary.csv
</code>```

and

```<code>Import-Csv 'C:\Temp\devicelist-summary.csv' | ForEach-Object {}
</code>```

and

```<code>Remove-MsolDevice -DeviceId “device_ID_number” -Force
</code>```

Then ultimately depending on ApproximateLastLogonTimestamp I would remove them from the Azure AD device list.
Unfortunately I have few knowledge in coding so I am kind of stuck, I tried my best but it would be very helpful is someone could help me.
I think I am close to something here.
Thank you!!

答:
Are you logged on and do you receive the devices when running Get-MsolDevice?

If you do, you might want to do something like:

Get-MsolDevice -all | Where-Object {$_.ApproximateLastLogonTimestamp -gt $(Get-Date).AddDays(-180)} | Foreach-Object {Remove-MsolDevice -DeviceId $_.DeviceId -Force}
```

This saves you from creating a CSV file.

You might want to split the one-liner up in a few steps and then add a log on all the devices you delete.

Body:
I am trying to create a PowerShell script to cleanup Azure AD devices.
I figured I should probably find a combination of these:

Get-MsolDevice -all | select-object -Property Enabled, DeviceId, DisplayName, DeviceTrustType, ApproximateLastLogonTimestamp | export-csv C:\Temp\devicelist-summary.csv

and

Import-Csv 'C:\Temp\devicelist-summary.csv' | ForEach-Object {}

and

Remove-MsolDevice -DeviceId “device_ID_number” -Force

Then ultimately depending on ApproximateLastLogonTimestamp I would remove them from the Azure AD device list.
Unfortunately I have few knowledge in coding so I am kind of stuck, I tried my best but it would be very helpful is someone could help me.
I think I am close to something here.
Thank you!!

Body:
Are you logged on and do you receive the devices when running Get-MsolDevice?

If you do, you might want to do something like:

Get-MsolDevice -all | Where-Object {$_.ApproximateLastLogonTimestamp -gt $(Get-Date).AddDays(-180)} | Foreach-Object {Remove-MsolDevice -DeviceId $_.DeviceId -Force}

This saves you from creating a CSV file.

You might want to split the one-liner up in a few steps and then add a log on all the devices you delete.


问:
what are the steps to push changes to git from teamcity using windows agent
need steps to git push one file to specific branch in git </p>

```<code>git add -f %FileToCommit%
git commit -m "Adding file via build "
git push --force origin
</code>```

<p>but this code giving Host key verification failed. error </p>

答:
Under the account running those command (TeamCity is I believe your previous question), runs:

```<code>ssh git@github.com
</code>```

And type 'yes' when SSH asks for accepting the Host.

Then try again, and it should not give you "Host key verification" error anymore.

Body:
need steps to git push one file to specific branch in git

git add -f %FileToCommit%
git commit -m "Adding file via build "
git push --force origin

but this code giving Host key verification failed. error

Body:
Under the account running those command (TeamCity is I believe your previous question), runs:

ssh git@github.com

And type 'yes' when SSH asks for accepting the Host.

Then try again, and it should not give you "Host key verification" error anymore.


问:
`overflow:auto` doesn't hide scrollbar in mobile view
I have following CSS:

```<code>  .show_dropdown {
    max-height: 350px;
    overflow-y: auto;
  }
</code>```

in a mobile view the dropdown list is less than 350px and this should hide scrollbar because it is not necessary. However, in bigger screen it works fine and hide scroll when it is not needed.

Thanks for reading and helping

Full code can be find here

答: The issue is padding: 1.25rem 0; in nav > .navbar_list > a  if you inspect and check, if destop view padding-top and padding-bottom  for each a tag is 43px whereas in mobile view it's 56px which increasing the overall height of the list and resulting the scrollbar visibility.

Body:
I have following CSS:

  .show_dropdown {
    max-height: 350px;
    overflow-y: auto;
  }

in a mobile view the dropdown list is less than 350px and this should hide scrollbar because it is not necessary. However, in bigger screen it works fine and hide scroll when it is not needed.

Thanks for reading and helping

Full code can be find here


问:
STDOUT and STDERR out of order
I have a perl script which writes messages to STDOUT and STDERR (via print/croak statements), but I also redirect the STDOUT and STDERR to a logfile:

```<code>File::Tee::tee STDOUT, ">>", "$logFile" ;
File::Tee::tee STDERR, ">>", "$logFile" ;
</code>```

Now the output logfile has messages from STDOUT and STDERR displayed out of order. Also the actual output on terminal is also out of order. I have tried flushing the buffers (as recommended here: https://perl.plover.com/FAQs/Buffering.html) but it doesn't help:

```<code>select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;
</code>```

Does anyone know what I must do to see the output in order (I also tried additionally flushing the filehandle corresponding to $logfile, but its still the same)?

EDIT:

Thanks to all of you who have replied. A lot of the discussion over this ended up in comments, so I am going to list the few things which I tried based on feedback from all of you.

I already was flushing the STDOUT and STDERR before I used File::Tee. As @jimtut suspected, File::Tee was indeed the culprit - removing it restored the ordering on console. But I did want to redirect the STDOUT and STDERR.

@mob suggested using IO::Tee instead, but I haven't fully understood how to make that work they way I want in my code.

@briandfoy pointed out that there isn't a reliable way to ensure 2 seperate filehandles are seen in the correct order in realtime and also suggested using a logging routine which is the only place which can write to STDOUT/STDERR. @zimd further pointed out that File::Tee uses fork which is the heart of the issue since 2 processes cannot guarantee any order on output.

Since the File::Tee is to blame, I attempted to remove this from the code. I updated my logger function to print to STDOUT/STDERR as well as to additionally print to $log filehandle. Further for capturing the warns in the log, I did the following:

```<code>sub warning_handler {
  my $msg = $_[0] ;
  print STDERR $msg ;
  print $log $msg if defined $log ;
}
$SIG{__WARN__} = \&warning_handler ;
</code>```

This worked great for all of the code under my control. Everything was printing in order now both on console and logfile. However I realized I can't use this solution since I was also calling someone else's perl packages for some functionality and clearly I couldn't intercept the print/croak etc which wrote to STDOUT/STDERR within the 'off the shelf' package. So right now, I don't have a good solution. However I suspect if I can find someway to intercept STDOUT/STDERR within perl, I might be able to get what I need.

EDIT2:
I added my own answer which is probably the closest I got to solving the problem by modifying mob's solution of using IO::Tee instead of File::Tee, but even this misses some messages (though it fixes ordering).

EDIT3:
Finally found the 'solution'

```<code>use IO::Tee ;
use Capture::Tiny qw(capture);
...
...
select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;
open (my $log, ">", $logfilename) ;
*REALSTDOUT = *STDOUT ;
*REALSTDERR = *STDERR ;
*STDOUT = IO::Tee->new(\*REALSTDOUT, $log);
*STDERR = IO::Tee->new(\*REALSTDERR, $log);

# Regular Perl code here which sends output to STDOUT/STDERR
...
...
# system calls / calls to .so needs to be catpured
&log_streams(sub { &some_func_which_calls_shared_object() ; }) ;

sub log_streams {
    my ($cr, @args) = @_;  # code reference, with its arguments
    my ($out, $err, $exit) = capture { $cr->(@args) };

    if ($out) {
        print STDOUT $out;
    }
    if ($err) {
        print STDERR $err;
    }
}
</code>```

The use of IO::Tee ensures all perl generated outputs to console also go to logfile, and this happens immediately thereby updating the log and console in realtime. Since IO::Tee is changing the meaning of STDOUT/STDERR filehandles to now refer to the teed handles, it can only intercept stdio from perl statements, it misses sys calls since they bypass perl's STDOUT/STDERR handles. So we capture the syscall output and then use the log_streams routine to forward it to the now aliased STDOUT/STDERR streams. This creates a delay in the system call generated output showing up in log/terminal but there is no delay for perl generated output - i.e. best of both worlds. Do note that the ordering of stderr and stdout generated by an invocation of subroutine some_func_which_calls_shared_object is not preserved since in the log_streams routine, we first print to STDOUT and then to STDERR - as long as the system call is atomic and doesn't do much in terms of interleaving stdout/stderr messages we should be ok.
Appreciate solutions from briandfoy, mob and zimd whose answers I combined to arrive at this solution! Never thought it would require to go through this detail for what seems a very simple problem.

答:
Note   The first part is done via tie-d handles; solution in the second part uses Capture::Tiny

A bare-bones proof-of-concept for an approach using tie-d handles.

The package that ties a handle, by printing from it to a file and to (a copy of) STDOUT stream

```<code>package DupePrints;

use warnings;
use strict;
use feature 'say';

my $log = 't_tee_log.out';
open my $fh_out, '>', $log or die $!;  # for logging

# An independent copy of STDOUT (via dup2), for prints to terminal
open my $stdout, '>&', STDOUT or die $!;

sub TIEHANDLE { bless {} }

sub PRINT {
    my $self = shift;

    print $fh_out @_;
    print $stdout @_;
}

1;
</code>```

A program that uses it

```<code>use warnings;
use strict;
use feature 'say';

use DupePrints;
$| = 1;
tie *STDERR, 'DupePrints';
tie *STDOUT, 'DupePrints';

say "hi";

warn "\t==> ohno";

my $y;
my $x = $y + 7;

say "done";
</code>```

This prints to both the terminal and to t_tee_log.out the text

```
hi
        ==> ohno at main_DupePrints.pl line 14.
Use of uninitialized value $y in addition (+) at main_DupePrints.pl line 17.
done
```

See perltie and Tie::Handle, and this post with related examples, and perhaps this post

The logging to a file of STDOUT and STDERR streams (along with a copied printout) works across other modules that may be used in the main program, as well.

To also have "clean" prints, that don't get logged, copy the STDOUT handle in the main program, like it's done in the module, and print to that. If you need to use this in a more selective and sophisticated manner please modify as needed -- as it stands it is meant to be only a basic demo.

With the clarification in the question's edit, here is a different approach: wrap a call to Capture::Tiny, which captures all output from any code, and then manage the captured prints as needed

```<code>use warnings;
use strict;
use feature qw(say state);

use Capture::Tiny qw(capture);

sub log_streams {
    my ($cr, @args) = @_;  # code reference, with its arguments

    # Initialize "state" variable, so it runs once and stays open over calls
    state $fh_log = do {
        open my $fh, '>', 'tee_log.txt' or die $!;
        $fh;
    };

    my ($out, $err, $exit) = capture { $cr->(@args) };

    if ($out) {
        print $fh_log $out;
        print         $out;
    }
    if ($err) {
        print $fh_log $err;
        print         $err;
    }
}

log_streams( sub { say "hi" } );
log_streams( sub { warn "==> ohno" } );
log_streams( sub { my $y; my $x = $y + 7; } );

log_streams( sub { system('perl', '-wE', q(say "external perl one-liner")) } );

log_streams( sub { say "done" } );
</code>```

The downside of all this is that everything needs to run via that sub.  But then again, that's actually a good thing, even if sometimes inconvenient.

The state feature is used to "initialize" the filehandle because a variable declared as state is never re-initialized; so the file is opened only once, on the first call, and stays opened.

This is also a demo in need of completion.

Title: STDOUT and STDERR out of order

Body:
I have a perl script which writes messages to STDOUT and STDERR (via print/croak statements), but I also redirect the STDOUT and STDERR to a logfile:

File::Tee::tee STDOUT, ">>", "$logFile" ;
File::Tee::tee STDERR, ">>", "$logFile" ;

Now the output logfile has messages from STDOUT and STDERR displayed out of order. Also the actual output on terminal is also out of order. I have tried flushing the buffers (as recommended here: https://perl.plover.com/FAQs/Buffering.html) but it doesn't help:

select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;

Does anyone know what I must do to see the output in order (I also tried additionally flushing the filehandle corresponding to $logfile, but its still the same)?

EDIT:

Thanks to all of you who have replied. A lot of the discussion over this ended up in comments, so I am going to list the few things which I tried based on feedback from all of you.

I already was flushing the STDOUT and STDERR before I used File::Tee. As @jimtut suspected, File::Tee was indeed the culprit - removing it restored the ordering on console. But I did want to redirect the STDOUT and STDERR.

@mob suggested using IO::Tee instead, but I haven't fully understood how to make that work they way I want in my code.

@briandfoy pointed out that there isn't a reliable way to ensure 2 seperate filehandles are seen in the correct order in realtime and also suggested using a logging routine which is the only place which can write to STDOUT/STDERR. @zimd further pointed out that File::Tee uses fork which is the heart of the issue since 2 processes cannot guarantee any order on output.

Since the File::Tee is to blame, I attempted to remove this from the code. I updated my logger function to print to STDOUT/STDERR as well as to additionally print to $log filehandle. Further for capturing the warns in the log, I did the following:

sub warning_handler {
  my $msg = $_[0] ;
  print STDERR $msg ;
  print $log $msg if defined $log ;
}
$SIG{__WARN__} = \&warning_handler ;

This worked great for all of the code under my control. Everything was printing in order now both on console and logfile. However I realized I can't use this solution since I was also calling someone else's perl packages for some functionality and clearly I couldn't intercept the print/croak etc which wrote to STDOUT/STDERR within the 'off the shelf' package. So right now, I don't have a good solution. However I suspect if I can find someway to intercept STDOUT/STDERR within perl, I might be able to get what I need.

EDIT2:
I added my own answer which is probably the closest I got to solving the problem by modifying mob's solution of using IO::Tee instead of File::Tee, but even this misses some messages (though it fixes ordering).

EDIT3:
Finally found the 'solution'

use IO::Tee ;
use Capture::Tiny qw(capture);
...
...
select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;
open (my $log, ">", $logfilename) ;
*REALSTDOUT = *STDOUT ;
*REALSTDERR = *STDERR ;
*STDOUT = IO::Tee->new(\*REALSTDOUT, $log);
*STDERR = IO::Tee->new(\*REALSTDERR, $log);

# Regular Perl code here which sends output to STDOUT/STDERR
...
...
# system calls / calls to .so needs to be catpured
&log_streams(sub { &some_func_which_calls_shared_object() ; }) ;

sub log_streams {
    my ($cr, @args) = @_;  # code reference, with its arguments
    my ($out, $err, $exit) = capture { $cr->(@args) };

    if ($out) {
        print STDOUT $out;
    }
    if ($err) {
        print STDERR $err;
    }
}

The use of IO::Tee ensures all perl generated outputs to console also go to logfile, and this happens immediately thereby updating the log and console in realtime. Since IO::Tee is changing the meaning of STDOUT/STDERR filehandles to now refer to the teed handles, it can only intercept stdio from perl statements, it misses sys calls since they bypass perl's STDOUT/STDERR handles. So we capture the syscall output and then use the log_streams routine to forward it to the now aliased STDOUT/STDERR streams. This creates a delay in the system call generated output showing up in log/terminal but there is no delay for perl generated output - i.e. best of both worlds. Do note that the ordering of stderr and stdout generated by an invocation of subroutine some_func_which_calls_shared_object is not preserved since in the log_streams routine, we first print to STDOUT and then to STDERR - as long as the system call is atomic and doesn't do much in terms of interleaving stdout/stderr messages we should be ok.
Appreciate solutions from briandfoy, mob and zimd whose answers I combined to arrive at this solution! Never thought it would require to go through this detail for what seems a very simple problem.

Body:
Note   The first part is done via tie-d handles; solution in the second part uses Capture::Tiny

A bare-bones proof-of-concept for an approach using tie-d handles.

The package that ties a handle, by printing from it to a file and to (a copy of) STDOUT stream

package DupePrints;

use warnings;
use strict;
use feature 'say';

my $log = 't_tee_log.out';
open my $fh_out, '>', $log or die $!;  # for logging

# An independent copy of STDOUT (via dup2), for prints to terminal
open my $stdout, '>&', STDOUT or die $!;

sub TIEHANDLE { bless {} }

sub PRINT {
    my $self = shift;

    print $fh_out @_;
    print $stdout @_;
}

1;

A program that uses it

use warnings;
use strict;
use feature 'say';

use DupePrints;
$| = 1;
tie *STDERR, 'DupePrints';
tie *STDOUT, 'DupePrints';

say "hi";

warn "\t==> ohno";

my $y;
my $x = $y + 7;

say "done";

This prints to both the terminal and to t_tee_log.out the text

hi
        ==> ohno at main_DupePrints.pl line 14.
Use of uninitialized value $y in addition (+) at main_DupePrints.pl line 17.
done

See perltie and Tie::Handle, and this post with related examples, and perhaps this post

The logging to a file of STDOUT and STDERR streams (along with a copied printout) works across other modules that may be used in the main program, as well.

To also have "clean" prints, that don't get logged, copy the STDOUT handle in the main program, like it's done in the module, and print to that. If you need to use this in a more selective and sophisticated manner please modify as needed -- as it stands it is meant to be only a basic demo.

With the clarification in the question's edit, here is a different approach: wrap a call to Capture::Tiny, which captures all output from any code, and then manage the captured prints as needed

use warnings;
use strict;
use feature qw(say state);

use Capture::Tiny qw(capture);

sub log_streams {
    my ($cr, @args) = @_;  # code reference, with its arguments

    # Initialize "state" variable, so it runs once and stays open over calls
    state $fh_log = do {
        open my $fh, '>', 'tee_log.txt' or die $!;
        $fh;
    };

    my ($out, $err, $exit) = capture { $cr->(@args) };

    if ($out) {
        print $fh_log $out;
        print         $out;
    }
    if ($err) {
        print $fh_log $err;
        print         $err;
    }
}

log_streams( sub { say "hi" } );
log_streams( sub { warn "==> ohno" } );
log_streams( sub { my $y; my $x = $y + 7; } );

log_streams( sub { system('perl', '-wE', q(say "external perl one-liner")) } );

log_streams( sub { say "done" } );

The downside of all this is that everything needs to run via that sub.  But then again, that's actually a good thing, even if sometimes inconvenient.

The state feature is used to "initialize" the filehandle because a variable declared as state is never re-initialized; so the file is opened only once, on the first call, and stays opened.

This is also a demo in need of completion.


问:
Generate 6 digit random number in mysql
I want to generate random 6 digit number in mysql but sometime it generate only 5 digit.

UPDATE member SET updates = FLOOR(RAND() * 999999)

答:
You can generate random 6 digit number in mysql

```<code>UPDATE member SET updates = LPAD(FLOOR(RAND() * 999999.99), 6, '0');
+--------+
| Value  |
+--------+
| 499540 |
| 550607 |
| 254419 |
| 620272 |
| 338104 |
| 829705 |
+--------+
</code>```

or you can also random number generate in mysql 1 to 200 in increment form. you can change in place of 200 to **** as you like

```<code>UPDATE member SET updates = FLOOR(1 + (RAND() * 200));
    +--------+
    | Value  |
    +--------+
    | 1      |
    | 180    |
    | 50     |
    | 85     |
    | 33     |
    | 165    |
    +--------+
</code>```

ContentLicense: CC BY-SA 3.0

Title: Generate 6 digit random number in mysql

Body:
You can generate random 6 digit number in mysql

UPDATE member SET updates = LPAD(FLOOR(RAND() * 999999.99), 6, '0');
+--------+
| Value  |
+--------+
| 499540 |
| 550607 |
| 254419 |
| 620272 |
| 338104 |
| 829705 |
+--------+

or you can also random number generate in mysql 1 to 200 in increment form. you can change in place of 200 to **** as you like

UPDATE member SET updates = FLOOR(1 + (RAND() * 200));
    +--------+
    | Value  |
    +--------+
    | 1      |
    | 180    |
    | 50     |
    | 85     |
    | 33     |
    | 165    |
    +--------+


问:
Cant run a selenium python script with crontab
I have a python script that finds my grades in a webpage and sends me an email if any of my grades have been changed. Im now trying to run this script every hour with crontab.
The script works when running through terminal:

```<code>python3 /home/pi/Desktop/grades/script.py
</code>```

In my script, I am trying to run crontab with * * * * * python3 /home/pi/Desktop/grades/script.py

I also added the shell to use: SHELL=/bin/bash

When the script is ran through the IDLE, it cannot find the crontab directory to schedule the scipt. I have the PATH variable set, and I searched about this and nothing has worked.

答:
This could be couple of ways to handle this.
1. You must specify full path of python

```<code>* * * * * '/usr/bin/python3 /home/pi/Desktop/grades/script.py'
</code>```

2. You should put shebang line in your script, ref examples.

```<code>#!/usr/bin/env python3 or  #!/usr/bin/python3.
* * * * * /home/pi/Desktop/grades/script.py
</code>```

Body:
I have a python script that finds my grades in a webpage and sends me an email if any of my grades have been changed. Im now trying to run this script every hour with crontab.
The script works when running through terminal:

python3 /home/pi/Desktop/grades/script.py

In my script, I am trying to run crontab with * * * * * python3 /home/pi/Desktop/grades/script.py

I also added the shell to use: SHELL=/bin/bash

When the script is ran through the IDLE, it cannot find the crontab directory to schedule the scipt. I have the PATH variable set, and I searched about this and nothing has worked.

Body:
This could be couple of ways to handle this.
1. You must specify full path of python

* * * * * '/usr/bin/python3 /home/pi/Desktop/grades/script.py'

2. You should put shebang line in your script, ref examples.

#!/usr/bin/env python3 or  #!/usr/bin/python3.
* * * * * /home/pi/Desktop/grades/script.py


问:
Ionic app crash after adding use permission to config.xml file
By adding MODIFY_AUDIO_SETTINGS permission to config.xml, my app will crash after run.

```<code><edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/uses-permission" xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
</edit-config>
</code>```

Then run app:

```<code> ionic cordova run android -- device
</code>```

Also i try for ionic android permission

```<code> import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';

 this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.CAMERA).then(
  result =>console.log('Haspermission?',result.hasPermission),
  err =>this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.CAMERA)
);
</code>```

But no popup show to ask user for permission.
And in the end i used cordova permission directly

```<code>ionic cordova plugin add cordova-plugin-android-permissions

declare var cordova:any
var permissions = cordova.plugins.permissions;
permissions.requestPermission(permissions.RECORD_AUDIO, successCallback, errorCallback);
</code>```

i can get permission of camera or record_audio
But requestPermission return false for MODIDY_AUDIO_SETTINGS permission.

```<code>permissions.requestPermission(permission.MODIDY_AUDIO_SETTINGS, success, error);

function error() {
    resolve(false);
}

function success(status) {
  if (status.hasPermission) {  // <-- status.hasPermission is false here
     resolve(true);
  } else {
    resolve(false);
  }
}
</code>```

90% solve========================>

after adding permission manually to AndroidManifest.xml.
application show popup to ask permisson now.
how can i add this permission to confix.xml instead of directly to AndroidManifest.xml?
as i said when i add this permission to config.xml. application wont start.

```<code><uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-feature android:name="android.hardware.microphone" android:required="true" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
</code>```

答:
The issue solved by adding permission to < config-file > tag.

inside config.xml:

```<code><platform name="android">
    ....
    <config-file parent="/manifest" target="AndroidManifest.xml" xmlns:android="http://schemas.android.com/apk/res/android">
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-feature android:name="android.hardware.camera" android:required="true" />
        <uses-feature android:name="android.hardware.microphone" android:required="true" />
        <uses-permission android:name="android.permission.RECORD_AUDIO" />
        <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    </config-file>
    ....
</platform>
</code>```

unplug/plug again usb device or reset adb server and re run the application

```<code>ionic cordova run android --device
</code>```

and now, application show popup when sending request for permission.

Body:
By adding MODIFY_AUDIO_SETTINGS permission to config.xml, my app will crash after run.

<edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/uses-permission" xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
</edit-config>

Then run app:

 ionic cordova run android -- device

Also i try for ionic android permission

 import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';

 this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.CAMERA).then(
  result =>console.log('Haspermission?',result.hasPermission),
  err =>this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.CAMERA)
);

But no popup show to ask user for permission.
And in the end i used cordova permission directly

ionic cordova plugin add cordova-plugin-android-permissions

declare var cordova:any
var permissions = cordova.plugins.permissions;
permissions.requestPermission(permissions.RECORD_AUDIO, successCallback, errorCallback);

i can get permission of camera or record_audio
But requestPermission return false for MODIDY_AUDIO_SETTINGS permission.

permissions.requestPermission(permission.MODIDY_AUDIO_SETTINGS, success, error);

function error() {
    resolve(false);
}

function success(status) {
  if (status.hasPermission) {  // <-- status.hasPermission is false here
     resolve(true);
  } else {
    resolve(false);
  }
}

90% solve========================>

after adding permission manually to AndroidManifest.xml.
application show popup to ask permisson now.
how can i add this permission to confix.xml instead of directly to AndroidManifest.xml?
as i said when i add this permission to config.xml. application wont start.

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-feature android:name="android.hardware.microphone" android:required="true" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

Body:
The issue solved by adding permission to < config-file > tag.

inside config.xml:

<platform name="android">
    ....
    <config-file parent="/manifest" target="AndroidManifest.xml" xmlns:android="http://schemas.android.com/apk/res/android">
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-feature android:name="android.hardware.camera" android:required="true" />
        <uses-feature android:name="android.hardware.microphone" android:required="true" />
        <uses-permission android:name="android.permission.RECORD_AUDIO" />
        <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    </config-file>
    ....
</platform>

unplug/plug again usb device or reset adb server and re run the application

ionic cordova run android --device

and now, application show popup when sending request for permission.


问:
minikube show dns as Kubedns when it is coredns
I installed minikube on my mac. I see that I have CoreDNS service that is in use with minikube. I confirmed that by checking the coredns pod logs where my dns queries are ending. Why does the cluster info say that I am using Kube-dns when it is actually CoreDNS. Is it something that I could ignore as it looks plainly naming issue!!

my cluster info is as follows:

```<code>$ kubectl cluster-info
Kubernetes master is running at https://192.168.64.2:8443
KubeDNS is running at https://192.168.64.2:8443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
</code>```

CoreDNS pod logs

```<code>2020-02-14T14:33:49.106Z [INFO] 172.17.0.4:46239 - 734 "A IN hello-world-77b74d7cc8-6t5wt.default.svc.cluster.local. udp 72 false 512" NXDOMAIN qr,aa,rd 165 0.000177567s
2020-02-14T17:10:21.597Z [INFO] 172.17.0.4:52399 - 22998 "A IN hello-world-77b74d7cc8-6t5wt.cluster.local.default.svc.cluster.local. udp 86 false 512" NXDOMAIN qr,aa,rd 179 0.008847724s
2020-02-14T17:10:21.605Z [INFO] 172.17.0.4:59674 - 3370 "A IN hello-world-77b74d7cc8-6t5wt.cluster.local.cluster.local. udp 74 false 512" NXDOMAIN qr,aa,rd 167 0.000221285s
2020-02-14T17:10:21.606Z [INFO] 172.17.0.4:39439 - 62070 "A IN hello-world-77b74d7cc8-6t5wt.cluster.local. udp 60 false 512" NXDOMAIN qr,aa,rd 153 0.000156948s
2020-02-14T17:10:30.699Z [INFO] 172.17.0.4:42925 - 36746 "A IN hello-world-77b74d7cc8-6t5wt.svc.cluster.local.cluster.local. udp 78 false 512" NXDOMAIN qr,aa,rd 171 0.00038
</code>```

Minikube version

```<code>$ minikube version
minikube version: v1.5.2
commit: 792dbf92a1de583fcee76f8791cff12e0c9440ad-dirty
</code>```

The interface listing shows information below:

```<code>$ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 5a:2f:e8:1f:d2:c6 brd ff:ff:ff:ff:ff:ff
    inet 192.168.64.2/24 brd 192.168.64.255 scope global dynamic eth0
       valid_lft 55045sec preferred_lft 55045sec
    inet6 fe80::582f:e8ff:fe1f:d2c6/64 scope link
       valid_lft forever preferred_lft forever
</code>```

When did a ssh to minikube I see that the process and the

```<code>$ sudo ps aux | grep dns
root      2541 12.8  4.3 1357844 86832 ?       Ssl  10:11  83:44 /var/lib/minikube/binaries/v1.16.2/kubelet --authorization-mode=Webhook --bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --cgroup-driver=cgroupfs --client-ca-file=/var/lib/minikube/certs/ca.crt --cluster-dns=10.96.0.10 --cluster-domain=cluster.local --config=/var/lib/kubelet/config.yaml --container-runtime=docker --fail-swap-on=false --hostname-override=minikube --kubeconfig=/etc/kubernetes/kubelet.conf --node-ip=192.168.64.2 --pod-manifest-path=/etc/kubernetes/manifests
root      3565  0.4  1.1 146036 23192 ?        Ssl  10:11   3:14 /coredns -conf /etc/coredns/Corefile
root      3572  0.4  1.1 146036 22768 ?        Ssl  10:11   3:07 /coredns -conf /etc/coredns/Corefile
docker   12531  0.0  0.0  11408   556 pts/0    S+   21:03   0:00 grep dns
</code>```

When I look at the pods running

```<code>$ kubectl get pods -n kube-system
NAME                               READY   STATUS    RESTARTS   AGE
coredns-5644d7b6d9-mkcgk           1/1     Running   1          70d
coredns-5644d7b6d9-q4jr9           1/1     Running   1          70d
etcd-minikube                      1/1     Running   2          70d
kube-addon-manager-minikube        1/1     Running   1          70d
kube-apiserver-minikube            1/1     Running   2          70d
kube-controller-manager-minikube   1/1     Running   2          26h
kube-proxy-7qp8b                   1/1     Running   1          70d
kube-scheduler-minikube            1/1     Running   5          70d
storage-provisioner                1/1     Running   3          70d
</code>```

Update after I looked at the deployment manifest of CoreDNS following Shahed's answer

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "3"
  creationTimestamp: "2019-12-06T19:47:59Z"
  generation: 5
  labels:
    k8s-app: kube-dns
  name: coredns
  namespace: kube-system
  resourceVersion: "10113"
  selfLink: /apis/apps/v1/namespaces/kube-system/deployments/coredns
  uid: ba1ef689-fe70-4e48-9e6f-5f659226722f
spec:
  progressDeadlineSeconds: 600
  replicas: 2
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      k8s-app: kube-dns
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        k8s-app: kube-dns
    spec:
      containers:
      - args:
        - -conf
        - /etc/coredns/Corefile
        image: k8s.gcr.io/coredns:1.6.2
        imagePullPolicy: IfNotPresent
        livenessProbe:
          failureThreshold: 5
          httpGet:
            path: /health
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 60
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 5
        name: coredns
        ports:
        - containerPort: 53
</code>```

答:
CoreDNS is default from Kubernetes 1.11. For previous installations, it was kube-dns.

So, as per your terminal outputs, those are right. Your minikube is using CoreDNS  pods for the services.

Is it something that I could ignore as it looks plainly naming issue!!

You are absolutely correct. It is a naming issue.

It has been done for the sake of compatibility so that the existing clients can still use the service name kube-dns to reach the service after moving to CoreDNS from kube-dns.

Body:
I installed minikube on my mac. I see that I have CoreDNS service that is in use with minikube. I confirmed that by checking the coredns pod logs where my dns queries are ending. Why does the cluster info say that I am using Kube-dns when it is actually CoreDNS. Is it something that I could ignore as it looks plainly naming issue!!

my cluster info is as follows:

$ kubectl cluster-info
Kubernetes master is running at https://192.168.64.2:8443
KubeDNS is running at https://192.168.64.2:8443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

CoreDNS pod logs

2020-02-14T14:33:49.106Z [INFO] 172.17.0.4:46239 - 734 "A IN hello-world-77b74d7cc8-6t5wt.default.svc.cluster.local. udp 72 false 512" NXDOMAIN qr,aa,rd 165 0.000177567s
2020-02-14T17:10:21.597Z [INFO] 172.17.0.4:52399 - 22998 "A IN hello-world-77b74d7cc8-6t5wt.cluster.local.default.svc.cluster.local. udp 86 false 512" NXDOMAIN qr,aa,rd 179 0.008847724s
2020-02-14T17:10:21.605Z [INFO] 172.17.0.4:59674 - 3370 "A IN hello-world-77b74d7cc8-6t5wt.cluster.local.cluster.local. udp 74 false 512" NXDOMAIN qr,aa,rd 167 0.000221285s
2020-02-14T17:10:21.606Z [INFO] 172.17.0.4:39439 - 62070 "A IN hello-world-77b74d7cc8-6t5wt.cluster.local. udp 60 false 512" NXDOMAIN qr,aa,rd 153 0.000156948s
2020-02-14T17:10:30.699Z [INFO] 172.17.0.4:42925 - 36746 "A IN hello-world-77b74d7cc8-6t5wt.svc.cluster.local.cluster.local. udp 78 false 512" NXDOMAIN qr,aa,rd 171 0.00038

Minikube version

$ minikube version
minikube version: v1.5.2
commit: 792dbf92a1de583fcee76f8791cff12e0c9440ad-dirty

The interface listing shows information below:

$ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 5a:2f:e8:1f:d2:c6 brd ff:ff:ff:ff:ff:ff
    inet 192.168.64.2/24 brd 192.168.64.255 scope global dynamic eth0
       valid_lft 55045sec preferred_lft 55045sec
    inet6 fe80::582f:e8ff:fe1f:d2c6/64 scope link
       valid_lft forever preferred_lft forever

When did a ssh to minikube I see that the process and the

$ sudo ps aux | grep dns
root      2541 12.8  4.3 1357844 86832 ?       Ssl  10:11  83:44 /var/lib/minikube/binaries/v1.16.2/kubelet --authorization-mode=Webhook --bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --cgroup-driver=cgroupfs --client-ca-file=/var/lib/minikube/certs/ca.crt --cluster-dns=10.96.0.10 --cluster-domain=cluster.local --config=/var/lib/kubelet/config.yaml --container-runtime=docker --fail-swap-on=false --hostname-override=minikube --kubeconfig=/etc/kubernetes/kubelet.conf --node-ip=192.168.64.2 --pod-manifest-path=/etc/kubernetes/manifests
root      3565  0.4  1.1 146036 23192 ?        Ssl  10:11   3:14 /coredns -conf /etc/coredns/Corefile
root      3572  0.4  1.1 146036 22768 ?        Ssl  10:11   3:07 /coredns -conf /etc/coredns/Corefile
docker   12531  0.0  0.0  11408   556 pts/0    S+   21:03   0:00 grep dns

When I look at the pods running

$ kubectl get pods -n kube-system
NAME                               READY   STATUS    RESTARTS   AGE
coredns-5644d7b6d9-mkcgk           1/1     Running   1          70d
coredns-5644d7b6d9-q4jr9           1/1     Running   1          70d
etcd-minikube                      1/1     Running   2          70d
kube-addon-manager-minikube        1/1     Running   1          70d
kube-apiserver-minikube            1/1     Running   2          70d
kube-controller-manager-minikube   1/1     Running   2          26h
kube-proxy-7qp8b                   1/1     Running   1          70d
kube-scheduler-minikube            1/1     Running   5          70d
storage-provisioner                1/1     Running   3          70d

Update after I looked at the deployment manifest of CoreDNS following Shahed's answer

apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "3"
  creationTimestamp: "2019-12-06T19:47:59Z"
  generation: 5
  labels:
    k8s-app: kube-dns
  name: coredns
  namespace: kube-system
  resourceVersion: "10113"
  selfLink: /apis/apps/v1/namespaces/kube-system/deployments/coredns
  uid: ba1ef689-fe70-4e48-9e6f-5f659226722f
spec:
  progressDeadlineSeconds: 600
  replicas: 2
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      k8s-app: kube-dns
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        k8s-app: kube-dns
    spec:
      containers:
      - args:
        - -conf
        - /etc/coredns/Corefile
        image: k8s.gcr.io/coredns:1.6.2
        imagePullPolicy: IfNotPresent
        livenessProbe:
          failureThreshold: 5
          httpGet:
            path: /health
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 60
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 5
        name: coredns
        ports:
        - containerPort: 53


问:
Efficient method for converting strings inside dataframes into arrays
I'm working with a dataset of multiple CSV tables. One of these tables which consists of two columns has floating-point arrays with 512 elements in the form of strings. The table is quite large, so I was wondering if there is any efficient method for transforming them into actual arrays in the form of columns, instead of simply iterating over the records.

The shape of the original Table: (A few million records, 2)

The desired output shape: (A few million records, 513)
Or maybe (A few million records, 2) but now the second column contains NumPy arrays and not strings.

答:
So, basically what you want is to convert the strings stored in the pandas dataframe having values of some floating points, like '1.05' to be converted into an array of numpy.

Well you can convert these strings to float as follows:

```<code>df['col1'] = df['col1'].astype(float)
</code>```

And then you can convert the whole dataframe into numpy array as follows:

```<code>array = df.to_numpy()
</code>```

Body:
So, basically what you want is to convert the strings stored in the pandas dataframe having values of some floating points, like '1.05' to be converted into an array of numpy.

Well you can convert these strings to float as follows:

df['col1'] = df['col1'].astype(float)

And then you can convert the whole dataframe into numpy array as follows:

array = df.to_numpy()


问:
Where can I learn jQuery? Is it worth it?
I've had a lot of good experiences learning about web development on w3schools.com. It's hit or miss, I know, but the PHP and CSS sections specifically have proven very useful for reference.

Anyway, I was wondering if there was a similar site for jQuery. I'm interested in learning, but I need it to be online/searchable, so I can refer back to it easily when I need the information in the future.

Also, as a brief aside, is jQuery worth learning? Or should I look at different JavaScript libraries? I know Jeff uses jQuery on Stack Overflow and it seems to be working well.

Thanks!

Edit: jQuery's website has a pretty big list of tutorials, and a seemingly comprehensive documentation page. I haven't had time to go through it all yet, has anyone else had experience with it?

Edit 2: It seems Google is now hosting the jQuery libraries. That should give jQuery a pretty big advantage in terms of publicity.

Also, if everyone uses a single unified aQuery library hosted at the same place, it should get cached for most Internet users early on and therefore not impact the download footprint of your site should you decide to use it.

2 Months Later...

Edit 3: I started using jQuery on a project at work recently and it is great to work with! Just wanted to let everyone know that I have concluded it is ABSOLUTELY worth it to learn and use jQuery.

Also, I learned almost entirely from the Official jQuery documentation and tutorials. It's very straightforward.

10 Months Later...

jQuery is a part of just about every web app I've made since I initially wrote this post. It makes progressive enhancement a breeze, and helps make the code maintainable.

Also, all the jQuery plug-ins are an invaluable resource!

3 Years Later...

Still using jQuery just about every day. I now author jQuery plug-ins and consult full time. I'm primarily a Djangonaut but I've done several javascript only contracts with jQuery. It's a life saver.

From one jQuery user to another... You should look at templating with jQuery (or underscore -- see below).

Other things I've found valuable in addition to jQuery (with estimated portion of projects I use it on):

jQuery Form Plugin (95%)

jQuery Form Example Plugin (75%)

jQuery UI (70%)

Underscore.js (80%)

CoffeeScript (30%)

Backbone.js (10%)

答:
jQuery worths learning!!! I recommend reading "Learning jQuery" and "jQuery in Action". Both books are great with expalanation and examples. The next step is to actually use it to do something. You will find official http://docs.jquery.com docummentation very useful. I use it as a reference, google it all the time :)

Also "Learning jQuery" blog mensioned by Sean is also very useful. Also jQuery HowTo is also has a great collection of jQuery code snippets.

OwnerDisplayName: Jim Robert

LastEditorDisplayName: Jim Robert

OwnerDisplayName: Uzbekjon

ContentLicense: CC BY-SA 2.5


问:
Pushing data from socket.io into array
I have the following problem that I cant seem to work out. I'm trying to get an array of arrays from my socket.io emitter that is structured like follows:

```<code>[ [{...},{...},{...}] , [{...},{...}] , [{...}] ]
</code>```

Instead I get this:

I need all the arrays in one master array so that I can render bootstrap cards for each sub array.

Client side code:

```<code>const socket = io("http://localhost:5000");

    socket.on('data', (dta) => {
        handleData(dta.data);
    })

    function handleData(data) {
      const masterArray= [];
        masterArray.push(data);
        console.log(masterArray);
    }
</code>```

Server side code:

```<code>for(let i = 0 ; i < alarmpanels.length ; i++) {
const ElkClient = elkClient.ElkClient;
    let client = new ElkClient({
        connection: {
          name: alarmpanels[i].name,
          host: alarmpanels[i].host,
          port: alarmpanels[i].port,
          secure: alarmpanels[i].secure,
          zones: alarmpanels[i].zones
     }
  });

  connectClient(client);
}

  async function connectClient(client) {
    await client.connect();
    const zonesArray = client.options.connection.zones;
    const arr = [];
      try {
        const clhost = client.options.connection.host;
        const clport = client.options.connection.port;
        const clsecure = client.options.connection.secure;
        let data = await client.getArmingStatus();
        for (i = 0 ; i < zonesArray.length ; i ++) {
        const armUpState = await data.areas[i].armUpState;
        const clName = client.options.connection.name;
        const zoneName = zonesArray[i].name;
        const siteName = zonesArray[i].site;
        const clzone = zonesArray[i].zone;
        const totalPanels = zonesArray[i].length;

        const info = new PanelStatus(clhost, clport ,clsecure, clzone, siteName, clName, zoneName, armUpState, totalPanels);
        arr.push(info);
        }

      io.on('connection', (socket, req) => {
          socket.emit('data', {data: arr});
        })

      }
      catch (err) {
        console.log("Connection Lost!");
      }

    }
</code>```

答:
If you can use es2020, you can use Array.flat()

let startingArray = [
  [{
    entry1: 1,
    entry2: 2,
    entry3: 3
  }, {
    entry4: 4,
    entry5: 5,
    entry6: 6
  }, {
    entry7: 7,
    entry8: 8,
    entry9: 9
  }],
  [{
    entry10: 10,
    entry11: 11,
    entry12: 12
  }, {
    entry13: 13,
    entry14: 14,
    entry15: 15
  }],
  [{
    entry16: 16,
    entry17: 17,
    entry18: 18
  }]
]

const flattened = startingArray.flat()

console.log('startingArray', startingArray)
console.log('flattened', flattened)```

Title: Pushing data from socket.io into array

Body:
I have the following problem that I cant seem to work out. I'm trying to get an array of arrays from my socket.io emitter that is structured like follows:

[ [{...},{...},{...}] , [{...},{...}] , [{...}] ]

Instead I get this:

I need all the arrays in one master array so that I can render bootstrap cards for each sub array.

Client side code:

const socket = io("http://localhost:5000");

    socket.on('data', (dta) => {
        handleData(dta.data);
    })

    function handleData(data) {
      const masterArray= [];
        masterArray.push(data);
        console.log(masterArray);
    }

Server side code:

for(let i = 0 ; i < alarmpanels.length ; i++) {
const ElkClient = elkClient.ElkClient;
    let client = new ElkClient({
        connection: {
          name: alarmpanels[i].name,
          host: alarmpanels[i].host,
          port: alarmpanels[i].port,
          secure: alarmpanels[i].secure,
          zones: alarmpanels[i].zones
     }
  });

  connectClient(client);
}

  async function connectClient(client) {
    await client.connect();
    const zonesArray = client.options.connection.zones;
    const arr = [];
      try {
        const clhost = client.options.connection.host;
        const clport = client.options.connection.port;
        const clsecure = client.options.connection.secure;
        let data = await client.getArmingStatus();
        for (i = 0 ; i < zonesArray.length ; i ++) {
        const armUpState = await data.areas[i].armUpState;
        const clName = client.options.connection.name;
        const zoneName = zonesArray[i].name;
        const siteName = zonesArray[i].site;
        const clzone = zonesArray[i].zone;
        const totalPanels = zonesArray[i].length;

        const info = new PanelStatus(clhost, clport ,clsecure, clzone, siteName, clName, zoneName, armUpState, totalPanels);
        arr.push(info);
        }

      io.on('connection', (socket, req) => {
          socket.emit('data', {data: arr});
        })

      }
      catch (err) {
        console.log("Connection Lost!");
      }

    }


问:
How to fix issue with Azure Web App Services return Error 503
We have deployed in Azure Portal some app services under a free plan. The apps seem to be healthy and were working without problems until today. Suddenly all of them are returning an Error 503 "The service is unavailable.".

Under one of the services in Diagnose and fix problems in azure portal I checked CPU, Memory, Port usage and everything looks healthy.

Any ideas on how to fix the issue?
Could that be Microsoft maintenance and after some hours the sites are working normally again?

答: After 5 hours the services were up again. Probably it was a maintenance issue. So after no indication that my services have a problem, waiting some hours was the solution. Maybe this site that displays the azure status could be helpful for those that run into this problem.</p>