问:
ScrollView can host only one direct child but it has only one
I keep getting this error whenever I start the activity.

Here's the complete stack trace:

```<code>Process: com.example, PID: 28799
                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.activity.EditProjectActivity}: java.lang.IllegalStateException: ScrollView can host only one direct child
                                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2689)
                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2754)
                                                                    at android.app.ActivityThread.access$900(ActivityThread.java:177)
                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                    at android.os.Looper.loop(Looper.java:145)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:5938)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at java.lang.reflect.Method.invoke(Method.java:372)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
                                                                 Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child
                                                                    at android.widget.ScrollView.addView(ScrollView.java:416)
                                                                    at android.view.LayoutInflater.rInflate(LayoutInflater.java:822)
                                                                    at android.view.LayoutInflater.rInflate(LayoutInflater.java:821)
                                                                    at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
                                                                    at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
                                                                    at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
                                                                    at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
                                                                    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                    at com.example.activity.EditProjectActivity.onCreate(EditProjectActivity.java:38)
                                                                    at android.app.Activity.performCreate(Activity.java:6288)
                                                                    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2642)
                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2754)
                                                                    at android.app.ActivityThread.access$900(ActivityThread.java:177)
                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                    at android.os.Looper.loop(Looper.java:145)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:5938)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at java.lang.reflect.Method.invoke(Method.java:372)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
</code>```

And this is the layout file

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".activity.EditProjectActivity"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    >
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:orientation="horizontal"
                    android:id="@+id/ep_layout_name"
                    >
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Project Name: "/>
                    <EditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="10dp"
                        android:id="@+id/ep_edit_name"/>
                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/ep_layout_name"
                    android:layout_marginTop="20dp"
                    android:layout_centerHorizontal="true"
                    android:orientation="vertical"
                    android:id="@+id/ep_layout_categories"
                    >
                    <ListView
                        android:id="@+id/ep_list_categories"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        />
                    <Button
                        android:id="@+id/ep_btn_add_category"
                        android:layout_width="100dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:text="Add"
                        android:onClick="onAddCategoryButtonClick"
                        />
                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/ep_layout_categories"
                    android:layout_marginTop="20dp"
                    android:layout_centerHorizontal="true"
                    android:orientation="vertical"
                    android:id="@+id/ep_layout_versions"
                    >
                    <ListView
                        android:id="@+id/ep_list_versions"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        />
                    <Button
                        android:id="@+id/ep_btn_add_version"
                        android:layout_width="100dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:text="Add"
                        android:onClick="onAddVersionButtonClick"
                        />
                </LinearLayout>
        </RelativeLayout>
    </ScrollView>
</RelativeLayout>
</code>```

I understand what the error means, and I've tried to solve it accordingly, but it still throws out the same exception.

The ScrollView has only one direct child and that is the RelativeLayout. I've also made it so that the ScrollView has a parent and is not the base view in case it was causing the exception but it didn't work.

答:
Do focus

If you are using ScrollView then it should contain only child layout
and that child can contain multiple child layout.

Scroll view should not contain parallel layout, if you have parallel
layout then you can keep into single parent layout, I am using
Linear layout and by using above explain approach working fine.

Attaching screen shot for your reference....

Body:
I keep getting this error whenever I start the activity.

Here's the complete stack trace:

Process: com.example, PID: 28799
                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.activity.EditProjectActivity}: java.lang.IllegalStateException: ScrollView can host only one direct child
                                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2689)
                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2754)
                                                                    at android.app.ActivityThread.access$900(ActivityThread.java:177)
                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                    at android.os.Looper.loop(Looper.java:145)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:5938)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at java.lang.reflect.Method.invoke(Method.java:372)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
                                                                 Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child
                                                                    at android.widget.ScrollView.addView(ScrollView.java:416)
                                                                    at android.view.LayoutInflater.rInflate(LayoutInflater.java:822)
                                                                    at android.view.LayoutInflater.rInflate(LayoutInflater.java:821)
                                                                    at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
                                                                    at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
                                                                    at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
                                                                    at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
                                                                    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                    at com.example.activity.EditProjectActivity.onCreate(EditProjectActivity.java:38)
                                                                    at android.app.Activity.performCreate(Activity.java:6288)
                                                                    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2642)
                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2754)
                                                                    at android.app.ActivityThread.access$900(ActivityThread.java:177)
                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                    at android.os.Looper.loop(Looper.java:145)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:5938)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at java.lang.reflect.Method.invoke(Method.java:372)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

And this is the layout file

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".activity.EditProjectActivity"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    >
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:orientation="horizontal"
                    android:id="@+id/ep_layout_name"
                    >
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Project Name: "/>
                    <EditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="10dp"
                        android:id="@+id/ep_edit_name"/>
                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/ep_layout_name"
                    android:layout_marginTop="20dp"
                    android:layout_centerHorizontal="true"
                    android:orientation="vertical"
                    android:id="@+id/ep_layout_categories"
                    >
                    <ListView
                        android:id="@+id/ep_list_categories"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        />
                    <Button
                        android:id="@+id/ep_btn_add_category"
                        android:layout_width="100dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:text="Add"
                        android:onClick="onAddCategoryButtonClick"
                        />
                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/ep_layout_categories"
                    android:layout_marginTop="20dp"
                    android:layout_centerHorizontal="true"
                    android:orientation="vertical"
                    android:id="@+id/ep_layout_versions"
                    >
                    <ListView
                        android:id="@+id/ep_list_versions"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        />
                    <Button
                        android:id="@+id/ep_btn_add_version"
                        android:layout_width="100dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:text="Add"
                        android:onClick="onAddVersionButtonClick"
                        />
                </LinearLayout>
        </RelativeLayout>
    </ScrollView>
</RelativeLayout>

I understand what the error means, and I've tried to solve it accordingly, but it still throws out the same exception.

The ScrollView has only one direct child and that is the RelativeLayout. I've also made it so that the ScrollView has a parent and is not the base view in case it was causing the exception but it didn't work.


来源: stackexchange

问:
Looking for stats on popularity of JavaScript libraries
Does anyone know if there's a site that tracks the popularity of the big/various JavaScript libraries?</p>

答: I think now that jQuery is shipping with Visual Studio you're going to see a huge jump in it's popularity.</p>

OwnerDisplayName: magenta

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Spencer Ruport


问:
How to find longitude and latitude for multiple addresses
I have a lots of adresses and want to find easier way to find their longitude and latitude?

Have anybody here some idea?

EDIT:
I do not want to find it in the app. I just need to convert them.

Thank you

答:
You require to use the forward geocoding API from Google to get the lat/Log from address.

iPad/iPhone forward geocoding API using Google gecoding service

ContentLicense: CC BY-SA 3.0


问:
Scalability vs elasticity
What is the difference between elasticity and scalability in cloud computing

I read from the book of T.Erl (if I have understand it correctly) that scalability is the ability of a resource to increase or decrease by demand, and that elasticity is the automatic scaling of a resource  by demand of a resource.

After some search on web (again if I have understand it correctly) the scalability is about adding or removing IT resources by demand, and the elasticity is about the same but for the virtual machines.
Which should I consider right?

答:
Scalability is the ability of a system to be able to support increased processing/traffic by increasing a system's resources (scaling up) or increasing the number of systems supporting the process (scaling out). To be scalable, the relationship between resources and supported processing needs to be linear. A system has poor scalability if it takes four times as many resources to support a 50% increase in the number of users. Some systems are not scalable because of bad or limited architecture. No matter the number of resources added, you will not get an improvement (or may even experience decreased support).

Elasticity is the ability to scale up/down and out/in as a response to the processing needs of the system. For example:

A shipping company may need to increase resources during a holiday season, then reduce them after the holiday.

A stock trading site may be very active during trading hours, but have very little traffic outside of exchange hours.

Because of elasticity, a company no longer has to maintain support for peak use at all times. Companies can improve user experience by increasing resources at peak usage, and reduce costs by reducing resources when they are no longer needed.

There are cloud offerings that include elasticity with no effort from the consumer. You will simply see changes in cost based on use. Other products require your input. In these cases, elasticity does include some automation to complete the task of adding/removing resources. Performing such steps manually would be prohibitive in many scenarios. However, the decision to increase/decrease resources does not necessarily need to be automated. This can be a complex decision, and the ROI of automating the decision needs to be considered.

Elasticity assumes scalability, but it is not a hard requirement. If a system has poor scalability, you can still scale to support traffic. However, the ROI will be terrible.

See the definition of elasticity from AWS and Azure below.

https://wa.aws.amazon.com/wat.concept.elasticity.en.html

https://azure.microsoft.com/en-us/overview/what-is-elastic-computing/

ContentLicense: CC BY-SA 4.0

Title: Scalability vs elasticity


问:
SQL DATETIME to Nodejs
I have my datetime SQL columns with all my data  in UTC, for example:

2020-05-31 16:59:35

But when I extract it from my app with this query:

```<code>select expdate
from tempbans
where banid = '${tempVars("banid")}'
</code>```

I get this output:

```<code>Sun May 31 2020 18:59:35 GMT+0200 (GMT+02:00)
</code>```

I know the local machine is on UTC+2 but I don't want it to auto-convert it for me, I want the output in my app to remain UTC.

What can I do?

Thanks.

答:
It is not the node part but .js part behaving like this. Maybe you should try converting your output before print it.

```<code>var datee = new Date('2020-05-31 16:59:35');
console.log(datee.getFullYear() + '-' +('0' + (datee.getMonth()+1)).slice(-2)+ '-' +  ('0' + datee.getDate()).slice(-2) + ' '+datee.getHours()+ ':'+('0' + (datee.getMinutes())).slice(-2)+ ':'+datee.getSeconds());
</code>```

jsfiddle

Extremely useful source : How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

Title: SQL DATETIME to Nodejs

Body:
I have my datetime SQL columns with all my data  in UTC, for example:

2020-05-31 16:59:35

But when I extract it from my app with this query:

select expdate
from tempbans
where banid = '${tempVars("banid")}'

I get this output:

Sun May 31 2020 18:59:35 GMT+0200 (GMT+02:00)

I know the local machine is on UTC+2 but I don't want it to auto-convert it for me, I want the output in my app to remain UTC.

What can I do?

Thanks.

Body:
It is not the node part but .js part behaving like this. Maybe you should try converting your output before print it.

var datee = new Date('2020-05-31 16:59:35');
console.log(datee.getFullYear() + '-' +('0' + (datee.getMonth()+1)).slice(-2)+ '-' +  ('0' + datee.getDate()).slice(-2) + ' '+datee.getHours()+ ':'+('0' + (datee.getMinutes())).slice(-2)+ ':'+datee.getSeconds());

jsfiddle

Extremely useful source : How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?


问:
What is the optimal way to start python scripts in Windows?
Since opening a console and typing "long\path\interpreter\python.exe" "long\path\project\script.py" or py "long\path\project\script.py" is bothersome, what's the best way so start a script?

The ones I have come up with:

putting the text in a bat script

copying the script to the folder

shortcut to the script

mklink soft and hard to the script from the folder

答: bat/shell scripts are usually the best way. If this is a script you'll be using often, you can also save the path to an environment var in cmd so you can just call something like python %MY_PATH%/script.py


问:
Calling functions from classes with inheritence
I'm sure i'm missing something with the class/inheritence understanding.
when i hit the submit button i get this error:

I tried many variations like changing the command in the button, changing masters, defining self.controller.

how can I make the submit button to work?

```<code>import tkinter as tk
import os

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry("650x500")
        self.title("Gil Shwartz GUI Project")
        menu = tk.Frame(self, height=250, width=10, bg="black")
        menu.pack(side=tk.LEFT, fill="both", anchor="w")
        container = tk.Frame(self, height=250, width=270, relief="flat")
        container.pack(side=tk.TOP, fill="both", expand=True)
        output = tk.LabelFrame(self, text="Output", height=150, padx=5, pady=5)
        output.pack(side=tk.BOTTOM, fill="both", anchor="s")

        menu.grid_columnconfigure(0, weight=0)
        menu.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(1, weight=1)

        self.frames = ["StartPage", "MainWelcome", "testPing", "PageOne", "PageTwo"]

        self.frames[0] = Menu(parent=menu, controller=self)
        self.frames[1] = MainWelcome(parent=container, controller=self)
        self.frames[2] = testPing(parent=container, controller=self)
        self.frames[3] = PageOne(parent=container, controller=self)
        self.frames[4] = PageTwo(parent=container, controller=self)

        self.frames[0].grid(row=0, column=0, sticky="nsew")
        self.frames[1].grid(row=0, column=0, sticky="nsew")
        self.frames[2].grid(row=0, column=0, sticky="nsew")
        self.frames[3].grid(row=0, column=0, sticky="nsew")
        self.frames[4].grid(row=0, column=0, sticky="nsew")

        self.show_frame(1)

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        print(frame)
        frame.tkraise()

class Menu(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.menu = controller

        button1 = tk.Button(self, text="Ping Test",
                            command=lambda: controller.show_frame(2))
        button2 = tk.Button(self, text="Page Two",
                            command=lambda: controller.show_frame(4))
        button3 = tk.Button(self, text="Quit",
                            command=lambda: Menu.terminate(self))

        button1.pack(fill="both", expand=True)
        button2.pack(fill="both", expand=True)
        button3.pack(fill="both", expand=True)
        button1.grid_columnconfigure(0, weight=1)
        button2.grid_columnconfigure(0, weight=0)
        button3.grid_rowconfigure(0, weight=0)

    def terminate(self):
        exit()

class MainWelcome(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.menu = controller

        label = tk.Label(self, text="Text 1", bg="yellow")
        label.pack(fill="x", expand=True)
        label = tk.Label(self, text="Text 2", bg="yellow")
        label.pack(fill="x")

class testPing(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.urlLabel = controller

        urlLabel = tk.Label(self, text="Enter URL : ", padx=5, pady=5)
        urlLabel.pack(anchor="w")
        urlInputBox = tk.Entry(self)
        urlInputBox.pack()
        urlInputBox.grid_columnconfigure(0, weight=0)

        clearLabel = tk.Label(self, text="Clear File?", padx=5, pady=5)
        clearLabel.pack(anchor="w")

        clearFile = tk.BooleanVar()
        clearFile.set(False)
        clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
                                           command=lambda: testPing.callback(clearFile.get()))
        clearFileRadioYes.pack(anchor="w")
        clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
                                          command=lambda: testPing.callback((clearFile.get())))
        clearFileRadioNo.pack(anchor="w")

        urlSubmitButton = tk.Button(self, text="Submit",
                                    command=lambda: testPing.pingURL(urlInputBox.get(),
                                                     testPing(clearFile.get())))
        urlSubmitButton.pack(side=tk.RIGHT, anchor="e")

    def callback(clearFile):
        print(clearFile) # Debugging Mode - check Radio box Var.

    def pingURL(self, host, clearFile):

        outputFrameLabel = tk.LabelFrame(self, text="Output", height=35, width=150,
                               padx=5, pady=5, relief="solid")
        outputFrameLabel.place(x=0, y=150)
        file = fr'c:/users/{os.getlogin()}/Desktop/ping.txt'
        label = tk.Label(outputLabel, text=f'Pinging {host} ...')
        label.grid(row=0, column=0)
        label.update()

        if clearFile == True:
            with open(file, 'w+') as output:
                output.truncate(0)
                sub.call(['ping', f'{host}'], stdout=output)

        else:
            with open(file, 'a') as output:
                sub.call(['ping', f'{host}'], stdout=output)

        output.close()
        label.configure(text=f'Ping to {host} complete!')
        # testPing.changeLabel(host)

    # def changeLabel(self, host):

        # myLabel = tk.Label.config(text=f"Ping to {host} Complete!")
        # myLabel.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", bg="red")
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to page 2",
                           command=lambda: controller.show_frame(2))
        button.pack()

class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", bg="blue")
        label.pack(side="top", fill="x", pady=10)
        # button = tk.Button(self, text="Go to the start page",
        #                    command=lambda: controller.show_frame(0))
        # button.pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()
</code>```

here's a pic of the main window so you'll get a visual idea as well.

答:
I think the error lies in the testPing class; in particular in these lines:

```<code>class testPing(tk.Frame):
...
        clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
                                           command=lambda: testPing.callback(clearFile.get()))
        clearFileRadioYes.pack(anchor="w")
        clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
                                          command=lambda: testPing.callback((clearFile.get())))
        clearFileRadioNo.pack(anchor="w")

        urlSubmitButton = tk.Button(self, text="Submit",
                                    command=lambda: testPing.pingURL(urlInputBox.get(),
                                                     testPing(clearFile.get())))
</code>```

You're inside testPing, so you should use self instead of using testPing explicitly. So, your code should be:

```<code>class testPing(tk.Frame):
...
        clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
                                           command=lambda: self.callback(clearFile.get()))
        clearFileRadioYes.pack(anchor="w")
        clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
                                          command=lambda: self.callback((clearFile.get())))
        clearFileRadioNo.pack(anchor="w")

        urlSubmitButton = tk.Button(self, text="Submit",
                                    command=lambda: self.pingURL(urlInputBox.get(),
                                                     clearFile.get()))
</code>```

Notice using self instead of testPing

Body:
I'm sure i'm missing something with the class/inheritence understanding.
when i hit the submit button i get this error:

I tried many variations like changing the command in the button, changing masters, defining self.controller.

how can I make the submit button to work?

import tkinter as tk
import os

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry("650x500")
        self.title("Gil Shwartz GUI Project")
        menu = tk.Frame(self, height=250, width=10, bg="black")
        menu.pack(side=tk.LEFT, fill="both", anchor="w")
        container = tk.Frame(self, height=250, width=270, relief="flat")
        container.pack(side=tk.TOP, fill="both", expand=True)
        output = tk.LabelFrame(self, text="Output", height=150, padx=5, pady=5)
        output.pack(side=tk.BOTTOM, fill="both", anchor="s")

        menu.grid_columnconfigure(0, weight=0)
        menu.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(1, weight=1)

        self.frames = ["StartPage", "MainWelcome", "testPing", "PageOne", "PageTwo"]

        self.frames[0] = Menu(parent=menu, controller=self)
        self.frames[1] = MainWelcome(parent=container, controller=self)
        self.frames[2] = testPing(parent=container, controller=self)
        self.frames[3] = PageOne(parent=container, controller=self)
        self.frames[4] = PageTwo(parent=container, controller=self)

        self.frames[0].grid(row=0, column=0, sticky="nsew")
        self.frames[1].grid(row=0, column=0, sticky="nsew")
        self.frames[2].grid(row=0, column=0, sticky="nsew")
        self.frames[3].grid(row=0, column=0, sticky="nsew")
        self.frames[4].grid(row=0, column=0, sticky="nsew")

        self.show_frame(1)

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        print(frame)
        frame.tkraise()

class Menu(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.menu = controller

        button1 = tk.Button(self, text="Ping Test",
                            command=lambda: controller.show_frame(2))
        button2 = tk.Button(self, text="Page Two",
                            command=lambda: controller.show_frame(4))
        button3 = tk.Button(self, text="Quit",
                            command=lambda: Menu.terminate(self))

        button1.pack(fill="both", expand=True)
        button2.pack(fill="both", expand=True)
        button3.pack(fill="both", expand=True)
        button1.grid_columnconfigure(0, weight=1)
        button2.grid_columnconfigure(0, weight=0)
        button3.grid_rowconfigure(0, weight=0)

    def terminate(self):
        exit()

class MainWelcome(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.menu = controller

        label = tk.Label(self, text="Text 1", bg="yellow")
        label.pack(fill="x", expand=True)
        label = tk.Label(self, text="Text 2", bg="yellow")
        label.pack(fill="x")

class testPing(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.urlLabel = controller

        urlLabel = tk.Label(self, text="Enter URL : ", padx=5, pady=5)
        urlLabel.pack(anchor="w")
        urlInputBox = tk.Entry(self)
        urlInputBox.pack()
        urlInputBox.grid_columnconfigure(0, weight=0)

        clearLabel = tk.Label(self, text="Clear File?", padx=5, pady=5)
        clearLabel.pack(anchor="w")

        clearFile = tk.BooleanVar()
        clearFile.set(False)
        clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
                                           command=lambda: testPing.callback(clearFile.get()))
        clearFileRadioYes.pack(anchor="w")
        clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
                                          command=lambda: testPing.callback((clearFile.get())))
        clearFileRadioNo.pack(anchor="w")

        urlSubmitButton = tk.Button(self, text="Submit",
                                    command=lambda: testPing.pingURL(urlInputBox.get(),
                                                     testPing(clearFile.get())))
        urlSubmitButton.pack(side=tk.RIGHT, anchor="e")

    def callback(clearFile):
        print(clearFile) # Debugging Mode - check Radio box Var.

    def pingURL(self, host, clearFile):

        outputFrameLabel = tk.LabelFrame(self, text="Output", height=35, width=150,
                               padx=5, pady=5, relief="solid")
        outputFrameLabel.place(x=0, y=150)
        file = fr'c:/users/{os.getlogin()}/Desktop/ping.txt'
        label = tk.Label(outputLabel, text=f'Pinging {host} ...')
        label.grid(row=0, column=0)
        label.update()

        if clearFile == True:
            with open(file, 'w+') as output:
                output.truncate(0)
                sub.call(['ping', f'{host}'], stdout=output)

        else:
            with open(file, 'a') as output:
                sub.call(['ping', f'{host}'], stdout=output)

        output.close()
        label.configure(text=f'Ping to {host} complete!')
        # testPing.changeLabel(host)

    # def changeLabel(self, host):

        # myLabel = tk.Label.config(text=f"Ping to {host} Complete!")
        # myLabel.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", bg="red")
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to page 2",
                           command=lambda: controller.show_frame(2))
        button.pack()

class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", bg="blue")
        label.pack(side="top", fill="x", pady=10)
        # button = tk.Button(self, text="Go to the start page",
        #                    command=lambda: controller.show_frame(0))
        # button.pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

here's a pic of the main window so you'll get a visual idea as well.

Body:
I think the error lies in the testPing class; in particular in these lines:

class testPing(tk.Frame):
...
        clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
                                           command=lambda: testPing.callback(clearFile.get()))
        clearFileRadioYes.pack(anchor="w")
        clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
                                          command=lambda: testPing.callback((clearFile.get())))
        clearFileRadioNo.pack(anchor="w")

        urlSubmitButton = tk.Button(self, text="Submit",
                                    command=lambda: testPing.pingURL(urlInputBox.get(),
                                                     testPing(clearFile.get())))

You're inside testPing, so you should use self instead of using testPing explicitly. So, your code should be:

class testPing(tk.Frame):
...
        clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
                                           command=lambda: self.callback(clearFile.get()))
        clearFileRadioYes.pack(anchor="w")
        clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
                                          command=lambda: self.callback((clearFile.get())))
        clearFileRadioNo.pack(anchor="w")

        urlSubmitButton = tk.Button(self, text="Submit",
                                    command=lambda: self.pingURL(urlInputBox.get(),
                                                     clearFile.get()))

Notice using self instead of testPing


问:
How do I modify the first label from 0.0 to 0 of the x axis in my graph?
I have tried to change 0.0 to 0 at the start of the x-axis when I have my graph.

My numerical data are:

```<code>x = 0.115, 0.234, 0.329, 0.443, 0.536, 0.654, 0.765, 0.846

y = 5.598, 7.6942, 9.1384, 11.2953, 12.4065, 15.736, 21.603, 31.4367

s = 0.05, 0.1, 0.16, 0.4, 0.32, 0.17, 0.09, 1.2
</code>```

The original data does not have x = 0, y = 0.
I make the commands to add it and make the graph automatically.
But the graph starts at 0.0 on the x-axis. How do I change 0.0 to 0 without affecting the rest of the numbers?

I have studied the following links ... but still have not succeeded ...
Modify tick label text
pyplot remove the digits of zero ( start from 0 not 0.00)

The commands I have are:

```<code>import pandas as pd
import matplotlib.pyplot as plt

datos = pd.read_csv('.name.csv')
print(datos)

datosSM1 = datos[0:0]
datosSM1.loc[0] = 0
datosSM2 = datos[0:]

datosSM = pd.concat([datosSM1, datosSM2])
print(datosSM)

x = datosSM['x']
y = datosSM['y']
ys = datosSM['s']

plt.errorbar(x,y, fmt = 'ko', label = 'datos',
         yerr = ys, ecolor='r' )
plt.axis([0, x.max()+0.02, 0, y.max()+(y.max()/10)])

plt.show()
</code>```

I really appreciate your help and attention.

答:
Really thank you very much, and excellent suggestions.
I think your code is better than the alternative I just wrote ...

```<code>    ax = plt.axes()
def format_func(value, tick_number):
    N = value
    if N == 0:
        return "0"
    else:
        return "{0:0.2}".format(N)

ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
</code>```

Thank you

Body:
I have tried to change 0.0 to 0 at the start of the x-axis when I have my graph.

My numerical data are:

x = 0.115, 0.234, 0.329, 0.443, 0.536, 0.654, 0.765, 0.846

y = 5.598, 7.6942, 9.1384, 11.2953, 12.4065, 15.736, 21.603, 31.4367

s = 0.05, 0.1, 0.16, 0.4, 0.32, 0.17, 0.09, 1.2

The original data does not have x = 0, y = 0.
I make the commands to add it and make the graph automatically.
But the graph starts at 0.0 on the x-axis. How do I change 0.0 to 0 without affecting the rest of the numbers?

I have studied the following links ... but still have not succeeded ...
Modify tick label text
pyplot remove the digits of zero ( start from 0 not 0.00)

The commands I have are:

import pandas as pd
import matplotlib.pyplot as plt

datos = pd.read_csv('.name.csv')
print(datos)

datosSM1 = datos[0:0]
datosSM1.loc[0] = 0
datosSM2 = datos[0:]

datosSM = pd.concat([datosSM1, datosSM2])
print(datosSM)

x = datosSM['x']
y = datosSM['y']
ys = datosSM['s']

plt.errorbar(x,y, fmt = 'ko', label = 'datos',
         yerr = ys, ecolor='r' )
plt.axis([0, x.max()+0.02, 0, y.max()+(y.max()/10)])

plt.show()

I really appreciate your help and attention.

Body:
Really thank you very much, and excellent suggestions.
I think your code is better than the alternative I just wrote ...

    ax = plt.axes()
def format_func(value, tick_number):
    N = value
    if N == 0:
        return "0"
    else:
        return "{0:0.2}".format(N)

ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))

Thank you


问:
Java to insert the input values into ArrayList and print sum of elements present at even index of the ArrayList using Iterator
I have written this code My Problem is it is taking the length. of array as input but not reading the elements of array We have to use iterator for reading all Inputs.</p>

```<code>import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.*;
public class arrayl {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        ArrayList < Integer > list = new ArrayList < Integer > ();
        System.out.println(" Enter the length of array :");

        int n = sc.nextInt();
        int array[] = new int[n];

        System.out.println("Enter List : ");

        for (Iterator < Integer > itr = list.iterator(); itr.hasNext();) {
            if (itr.next() != null) {

                while (itr.hasNext()) {
                    Integer thisInt = itr.next();
                    if (thisInt % 2 == 0) {
                        list.add(thisInt);
                    }
                    System.out.println(" Even Index Position Sum : ");

                }
            }

        }
    }

}
</code>```

答:
Your code has several problems according to the context you have asked.

You haven't added anything to the list yet using scanner. So, how can you get the values to be calculated?

Using two loops for iterating through the list and checking again, this does not seem correct.

Printing your final output inside the loop will print it several times.

So, here is the complete code:

```<code>import java.util.*;

public class arrayl {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        ArrayList<Integer> list = new ArrayList<>();
        System.out.println("Enter the length of array :");
        int n = sc.nextInt();

        System.out.println("Enter List : ");
        for (int i = 0; i < n; i++) {
            list.add(sc.nextInt());
        }

        Iterator<Integer> itr = list.iterator();
        int sum = 0;
        int count = 0;

        while (itr.hasNext()) {
            int val = itr.next();
            if (count % 2 == 0) {
                sum += val;
            }
            count++;
        }

        System.out.println("Even Index Position Sum : " + sum);
    }
}
</code>```

Body:
I have written this code My Problem is it is taking the length. of array as input but not reading the elements of array We have to use iterator for reading all Inputs.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.*;
public class arrayl {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        ArrayList < Integer > list = new ArrayList < Integer > ();
        System.out.println(" Enter the length of array :");

        int n = sc.nextInt();
        int array[] = new int[n];

        System.out.println("Enter List : ");

        for (Iterator < Integer > itr = list.iterator(); itr.hasNext();) {
            if (itr.next() != null) {

                while (itr.hasNext()) {
                    Integer thisInt = itr.next();
                    if (thisInt % 2 == 0) {
                        list.add(thisInt);
                    }
                    System.out.println(" Even Index Position Sum : ");

                }
            }

        }
    }

}

Body:
Your code has several problems according to the context you have asked.

You haven't added anything to the list yet using scanner. So, how can you get the values to be calculated?

Using two loops for iterating through the list and checking again, this does not seem correct.

Printing your final output inside the loop will print it several times.

So, here is the complete code:

import java.util.*;

public class arrayl {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        ArrayList<Integer> list = new ArrayList<>();
        System.out.println("Enter the length of array :");
        int n = sc.nextInt();

        System.out.println("Enter List : ");
        for (int i = 0; i < n; i++) {
            list.add(sc.nextInt());
        }

        Iterator<Integer> itr = list.iterator();
        int sum = 0;
        int count = 0;

        while (itr.hasNext()) {
            int val = itr.next();
            if (count % 2 == 0) {
                sum += val;
            }
            count++;
        }

        System.out.println("Even Index Position Sum : " + sum);
    }
}


问:
VSCode + C# (OmiSharp) not showing any errors
I'm trying to find out why i'm not getting any help by omisharp in my visual studio code.

I've tried reinstalling both application and my extensions and i'm still having the problem.

Any ideas on what i might be missing? something I need to install?

// Alex

答:
I solved my same problem clicking in the bottom right corner of VSCode, line sequence CRLF, changed to LF and then change again to CRLF.

After this, my problem was solved, but i need to make this every time a restart the computer.


问:
How to use another keystore in the same app on Google Play
We began to develop an app using Expo then push it to Google Play. It is still on Google Play now.

Recently, we decided to use react-native from scratch (without eject expo, it is a new project with the same functionalities with the old one, please don't ask me explain why, it is a hard decision from our team).

Now we try to upload a new release on the same project as the old one on Google Play and Google said that our app signing key has changed.

We know that is true but we don't know how to re-use the old keystore. In the old expo-project, we found a find name *.jks, but don't remember its password and its key alias.

We'd like to know if it is possible to change the app signing key on Google play, to be able to keep using the old project, instead of creating a new project.

Thank you very much!

答:
If you’ve lost your private upload key, or it’s been compromised, you can create a new one, and then ask your account owner to contact support to reset the key. make sure your account owner attaches the upload_certificate.pem file.

After that google support team would register the new upload key, you will receive an email, and then you can update your keystores and register your key with API providers.


问:
Global variable losing data in C?
I am trying to create a array of array of string where each row (if considered matrix) should have 3 strings of any length and a maximum of 10 rows

The data Structure is correct but I am very much surprised with the output I get in the global variable. So the matrix would act as the database to the program and hence kept in global space

```<code>#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

// Maximum buffer size needed
#define MAX_NUM_ITEMS 10
#define MAX_ITEM_PER_ROW 3
static char *array[MAX_NUM_ITEMS][MAX_ITEM_PER_ROW];

#define ITOA_BASE_N (sizeof(unsigned)*CHAR_BIT + 1)
char *itoa_base(char *, int , int);
#define TO_BASE(x,b) itoa_base((char [ITOA_BASE_N]){0} , (x), (b))

char *itoa_base(char *s, int x, int base) {
  s += ITOA_BASE_N - 1;
  *s = '\0';
  if (base >= 2 && base <= 36) {
    int x0 = x;
    do {
      *(--s) = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[abs(x % base)];
      x /= base;
    } while (x);
    if (x0 < 0) {
      *(--s) = '-';
    }
  }
  return s;
}

int main(void)
{

    int count = 0;
    for (int i = 0; i < MAX_NUM_ITEMS; i++){
        for (int j = 0; j < MAX_ITEM_PER_ROW; j++ ){
            ++count;
            array[i][j] = TO_BASE(count, 16);
        }
    }

    for (int i = 0; i < MAX_NUM_ITEMS; i++){
        for (int j = 0; j < MAX_ITEM_PER_ROW; j++ ){
            printf("%s ",array[i][j]);
        }
        printf("\n");
    }
    return 0;
}
</code>```

From my logic I should see
1 2 3
4 5 6
7 8 9 and so on and not E E E

can't understand why that is happening

答:
First, this:

```<code>(char [ITOA_BASE_N]){0}
</code>```

Does not get you a new instance of a character array, unlike say golang.  So, every time you call itoa(), you are calling it with the same character array.  Somewhat worse, the character array is occupying a reclaimable stack address [ its scope is only that inner loop ], so it can be over written with random stuff shortly after.  It is remarkably consistent though; I will give it that.

Changing the invocation to:

```<code>array[i][j] = strdup(TO_BASE(count, 16));
</code>```

and adding a #include  at the top produces the output you wanted.

If dynamic allocation is not permissible in your application, you will have to use a static allocation scheme, which you could make a bounded version of strdup like:

```<code>char *strnew(char *s) {
  static char strspace[ITOA_BASE_N * MAX_NUM_ITEMS * MAX_ITEM_PER_ROW ];
  static char *strnext = strspace;
  if (strlen(s) + strspace >= &strspace[sizeof strspace]) {
      s = "<error: out of space>"; /* something more clever is possible */
  } else {
      strcpy(strnext, s);
      s = strnext;
      strnext += strlen(strnext)+1;
  }
  return s;
}
</code>```

which you could substitute for strdup.  If you do the next person down the line a favour and use a more descriptive notion like MAX_STRING_SPACE which is based on the calculation; and rather than insert a "bad value", cause some sort of exception, I am sure they would appreciate it.

Title: Global variable losing data in C?

Body:
I am trying to create a array of array of string where each row (if considered matrix) should have 3 strings of any length and a maximum of 10 rows

The data Structure is correct but I am very much surprised with the output I get in the global variable. So the matrix would act as the database to the program and hence kept in global space

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

// Maximum buffer size needed
#define MAX_NUM_ITEMS 10
#define MAX_ITEM_PER_ROW 3
static char *array[MAX_NUM_ITEMS][MAX_ITEM_PER_ROW];

#define ITOA_BASE_N (sizeof(unsigned)*CHAR_BIT + 1)
char *itoa_base(char *, int , int);
#define TO_BASE(x,b) itoa_base((char [ITOA_BASE_N]){0} , (x), (b))

char *itoa_base(char *s, int x, int base) {
  s += ITOA_BASE_N - 1;
  *s = '\0';
  if (base >= 2 && base <= 36) {
    int x0 = x;
    do {
      *(--s) = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[abs(x % base)];
      x /= base;
    } while (x);
    if (x0 < 0) {
      *(--s) = '-';
    }
  }
  return s;
}

int main(void)
{

    int count = 0;
    for (int i = 0; i < MAX_NUM_ITEMS; i++){
        for (int j = 0; j < MAX_ITEM_PER_ROW; j++ ){
            ++count;
            array[i][j] = TO_BASE(count, 16);
        }
    }

    for (int i = 0; i < MAX_NUM_ITEMS; i++){
        for (int j = 0; j < MAX_ITEM_PER_ROW; j++ ){
            printf("%s ",array[i][j]);
        }
        printf("\n");
    }
    return 0;
}

From my logic I should see
1 2 3
4 5 6
7 8 9 and so on and not E E E

can't understand why that is happening

Body:
First, this:

(char [ITOA_BASE_N]){0}

Does not get you a new instance of a character array, unlike say golang.  So, every time you call itoa(), you are calling it with the same character array.  Somewhat worse, the character array is occupying a reclaimable stack address [ its scope is only that inner loop ], so it can be over written with random stuff shortly after.  It is remarkably consistent though; I will give it that.

Changing the invocation to:

array[i][j] = strdup(TO_BASE(count, 16));

and adding a #include  at the top produces the output you wanted.

If dynamic allocation is not permissible in your application, you will have to use a static allocation scheme, which you could make a bounded version of strdup like:

char *strnew(char *s) {
  static char strspace[ITOA_BASE_N * MAX_NUM_ITEMS * MAX_ITEM_PER_ROW ];
  static char *strnext = strspace;
  if (strlen(s) + strspace >= &strspace[sizeof strspace]) {
      s = "<error: out of space>"; /* something more clever is possible */
  } else {
      strcpy(strnext, s);
      s = strnext;
      strnext += strlen(strnext)+1;
  }
  return s;
}

which you could substitute for strdup.  If you do the next person down the line a favour and use a more descriptive notion like MAX_STRING_SPACE which is based on the calculation; and rather than insert a "bad value", cause some sort of exception, I am sure they would appreciate it.


问:
Tool to automatically generate documentation on elastic index
I have a project on Kibana/Elastic. I can see / manipulate the indices and see the fields and value types with GET <index>/_mapping.

Other members (in particular, managers) in my team do not have access to Kibana and I need to write some documentation for them. Basically, I need to give them a view on what's in the indices.

I find myself copy pasting and simplifying (removing some not so informative layers) the json-like output of GET <index>/_mapping. That's not a good process.

Is there a tool that automates this, and ensures synchronisation between the db and the documentation?

答:
I don't know of any tool that automates this. The simplest way, IMO, would be to create a single-page webapp which connects to ES and calls

```<code>GET _all/_mapping?format=yaml
</code>```

which will return something like

```<code>myindex:
  mappings:
    properties:
      date1:
        type: "date"
      date2:
        type: "date"
      date3:
        type: "date"
      status:
        type: "text"
        fields:
          keyword:
            type: "keyword"
            ignore_above: 256
</code>```

which is already more readable than JSON.

Going one step further, you could add a multi select dropdown to filter for specific fields, i.e.:

```<code>GET _all/_mapping/field/name,color?format=yaml
</code>```

which would return something along the lines of

```<code>online_shop:
  mappings:
    color:
      full_name: "color"
      mapping:
        color:
          type: "keyword"
    name:
      full_name: "name"
      mapping:
        name:
          type: "text"
          fields:
            keyword:
              type: "keyword"
</code>```

Body:
I don't know of any tool that automates this. The simplest way, IMO, would be to create a single-page webapp which connects to ES and calls

GET _all/_mapping?format=yaml

which will return something like

myindex:
  mappings:
    properties:
      date1:
        type: "date"
      date2:
        type: "date"
      date3:
        type: "date"
      status:
        type: "text"
        fields:
          keyword:
            type: "keyword"
            ignore_above: 256

which is already more readable than JSON.

Going one step further, you could add a multi select dropdown to filter for specific fields, i.e.:

GET _all/_mapping/field/name,color?format=yaml

which would return something along the lines of

online_shop:
  mappings:
    color:
      full_name: "color"
      mapping:
        color:
          type: "keyword"
    name:
      full_name: "name"
      mapping:
        name:
          type: "text"
          fields:
            keyword:
              type: "keyword"


问:
set a value of std::variant by index
I was trying to create something like the upcoming (if ever) std::expected using std::variant. I thought it would be very easy to something like that, yet maybe not optimal.

However, I faced some interesting exercise with std::variant and it is how to assign a value by an index? The only way how I got close to it is in the example below, which is maybe not too bad at the end, but still, looks quite weird at first glance. (yet I am not sure if it's general enough)

#include <variant>

template<typename ValueType, typename ErrorType>
class Expected
{

    std::variant<std::monostate, ValueType, ErrorType> data_;

public:
    const ValueType& GetValue()
    {
        return std::get<1>(data_);
    }

    void SetValue(auto&& value)
    {
        data_ = decltype(data_)(std::in_place_index_t<1>{}, std::forward<decltype(value)>(value));
    }

};

int main()
{
    Expected<bool, bool> e;
    e.SetValue(false);
    return e.GetValue();
}
```

<p>I also got an idea that some really thin wrapper class could help here, I suppose it could be written in a way, that it would be optimized out by the compiler.</p>

<pre class="lang-cpp prettyprint-override"><code>std::variant<std::monostate, ValueWrapper<ValueType>, ErrorType> data_;

</code>```

答:
The function you're looking for is variant::emplace. Your function becomes:

```<code>    void SetValue(auto&& value)
    {
        data_.template emplace<1>(std::forward<decltype(value)>(value));
    }
</code>```

Title: set a value of std::variant by index

Body:
I was trying to create something like the upcoming (if ever) std::expected using std::variant. I thought it would be very easy to something like that, yet maybe not optimal.

However, I faced some interesting exercise with std::variant and it is how to assign a value by an index? The only way how I got close to it is in the example below, which is maybe not too bad at the end, but still, looks quite weird at first glance. (yet I am not sure if it's general enough)

#include <variant>

template<typename ValueType, typename ErrorType>
class Expected
{

    std::variant<std::monostate, ValueType, ErrorType> data_;

public:
    const ValueType& GetValue()
    {
        return std::get<1>(data_);
    }

    void SetValue(auto&& value)
    {
        data_ = decltype(data_)(std::in_place_index_t<1>{}, std::forward<decltype(value)>(value));
    }

};

int main()
{
    Expected<bool, bool> e;
    e.SetValue(false);
    return e.GetValue();
}

I also got an idea that some really thin wrapper class could help here, I suppose it could be written in a way, that it would be optimized out by the compiler.

std::variant<std::monostate, ValueWrapper<ValueType>, ErrorType> data_;

Body:
The function you're looking for is variant::emplace. Your function becomes:

    void SetValue(auto&& value)
    {
        data_.template emplace<1>(std::forward<decltype(value)>(value));
    }


答:
The problem is here:

```<code>itoa_base((char [ITOA_BASE_N]){0} , (x), (b))
          ^^^^^^^^^^^^^^^^^^^^^^^
</code>```

you are allocating a temp array (on the stack) which is only valid up to the end of the containing expression statement.  So when the time comes to print them, the pointers you've stored in the matrix are dangling.  What the compiler ends up doing is reusing the same memory for every call, so the strings end up overwriting.

You could instead use a static matrix of arrays rather than pointers:

```<code>static char array[MAX_NUM_ITEMS][MAX_ITEM_PER_ROW][ITOA_BASE_N];
</code>```

then your call in the first loop becomes

```<code>itoa_base(array[i][j], count, 16);
</code>```

you'll also need to "fix" itoa_base so it puts the result in the front of the array rather than the back.  Obvious way is with a recursive loop like:

```<code>char *itoa_base(char *s, int x, int base) {
  if (base >= 2 && base <= 36) {
    if (x < 0) {
      *s++ = '-';
      x = -x; }
    if (x >= base)
      s = itoa_base(s, x/base, base);
    *s++ = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[x % base];
  }
  *s = '\0';
  return s;
}
</code>```

Title: Global variable losing data in C?

Body:
The problem is here:

itoa_base((char [ITOA_BASE_N]){0} , (x), (b))
          ^^^^^^^^^^^^^^^^^^^^^^^

you are allocating a temp array (on the stack) which is only valid up to the end of the containing expression statement.  So when the time comes to print them, the pointers you've stored in the matrix are dangling.  What the compiler ends up doing is reusing the same memory for every call, so the strings end up overwriting.

You could instead use a static matrix of arrays rather than pointers:

static char array[MAX_NUM_ITEMS][MAX_ITEM_PER_ROW][ITOA_BASE_N];

then your call in the first loop becomes

itoa_base(array[i][j], count, 16);

you'll also need to "fix" itoa_base so it puts the result in the front of the array rather than the back.  Obvious way is with a recursive loop like:

char *itoa_base(char *s, int x, int base) {
  if (base >= 2 && base <= 36) {
    if (x < 0) {
      *s++ = '-';
      x = -x; }
    if (x >= base)
      s = itoa_base(s, x/base, base);
    *s++ = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[x % base];
  }
  *s = '\0';
  return s;
}


问:
Adding DISTINCT to a UNION query
How do I get distinct title.id's from this:

```<code> SELECT Title.id, Title.title FROM titles as Title HAVING points > 0
 UNION ALL
 SELECT Title.id, Title.title FROM titles as Title HAVING points > 1
</code>```

There is more to the query but this should be enough to go on.

答:
Just remove the ALL. Some flavors allow adding DISTINCT instead of ALL to be more explicit, but that's redundant having that the default is always to filter our duplicates.

MySQL - http://dev.mysql.com/doc/refman/5.0/en/union.html

MSSQL - http://msdn.microsoft.com/en-us/library/ms180026.aspx

ORACLE - https://docs.oracle.com/cd/B28359_01/server.111/b28286/queries004.htm

PostgreSQL - http://www.postgresql.org/docs/8.3/interactive/queries-union.html

etc.

Title: Adding DISTINCT to a UNION query

Body:
How do I get distinct title.id's from this:

 SELECT Title.id, Title.title FROM titles as Title HAVING points > 0
 UNION ALL
 SELECT Title.id, Title.title FROM titles as Title HAVING points > 1

There is more to the query but this should be enough to go on.


问:
i have created two templates one inside the project and another inside the app and error is coming template does not exist

**views.py

from django.shortcuts import render from django.urls import
reverse_lazy from django.http import HttpResponse from
django.views.generic import (View,TemplateView,
                                ListView,DetailView,
                                CreateView,DeleteView,
                                UpdateView) from . import models

Create your views here.

Original Function View:

#

def index(request):

return render(request,'index.html')

#
#

Pretty simple right? class IndexView(TemplateView):

```<code># Just set this Class Object Attribute to the template page.
# template_name = 'app_name/site.html'
template_name = 'index.html'
def get_context_data(self,**kwargs):
    context  = super().get_context_data(**kwargs)
    context['injectme'] = "Basic Injection!"
    return context class SchoolListView(ListView):
# If you don't pass in this attribute,
# Django will auto create a context name
# for you with object_list!
# Default would be 'school_list'
# Example of making your own:
# context_object_name = 'schools'
model = models.School class SchoolDetailView(DetailView):
context_object_name = 'school_details'
model = models.School
template_name = 'basic_app/school_detail.html' class SchoolCreateView(CreateView):
fields = ("name","principal","location")
model = models.School class SchoolUpdateView(UpdateView):
fields = ("name","principal")
model = models.School class SchoolDeleteView(DeleteView):
model = models.School
success_url = reverse_lazy("basic_app:list") class CBView(View):
def get(self,request):
    return HttpResponse('Class Based Views are Cool!')
</code>```

urls.py of application

from django.urls import path from . import views app_name =
'basic_app' urlpatterns = [
    path('',views.SchoolListView.as_view(),name='list'),
    ]

[list of files in project][1]

List item

urls.py of project from django.contrib import admin from
django.urls import path, include from basic_app import views
urlpatterns = [
path('',views.IndexView.as_view()),
path('admin/',admin.site.urls,name='admin'),
path('basic_app/',include('basic_app.urls',namespace='basic_app')),
]

settings.py """ Django settings for advcbv project. Generated by
'django-admin startproject' using Django 2.0.5. For more information
on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/ For the full
list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os

Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR =

os.path.dirname(os.path.dirname(os.path.abspath(file)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'template')

Quick-start development settings - unsuitable for production

See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=f%ns04d@z9na8xh(kfo8v8aa-v2p0bcn^jukrh4dm_^=zq70$'

SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = []

Application definition INSTALLED_APPS = [

```<code>'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'basic_app.apps.BasicAppConfig', ] MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'advcbv.urls' TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [TEMPLATE_DIR,],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
}, ] WSGI_APPLICATION = 'advcbv.wsgi.application'
</code>```

Database

https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = {

```<code>'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
} }
</code>```

Password validation

https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    }, ]

Internationalization

https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ =

True

Static files (CSS, JavaScript, Images)

https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/'**

[1]: https://i.stack.imgur.com/bYtk9.png

答:
You have to dell Django that there exist more templates in your apps/dir like so:

Settings.py

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
                os.path.join(BASE_DIR, 'templates'),
                os.path.join(BASE_DIR, 'My_App/templates'), # root to your apps templates
                 ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
</code>```

Body:
**views.py

from django.shortcuts import render from django.urls import
reverse_lazy from django.http import HttpResponse from
django.views.generic import (View,TemplateView,
                                ListView,DetailView,
                                CreateView,DeleteView,
                                UpdateView) from . import models

Create your views here.

Original Function View:

#

def index(request):

return render(request,'index.html')

#
#

Pretty simple right? class IndexView(TemplateView):

# Just set this Class Object Attribute to the template page.
# template_name = 'app_name/site.html'
template_name = 'index.html'
def get_context_data(self,**kwargs):
    context  = super().get_context_data(**kwargs)
    context['injectme'] = "Basic Injection!"
    return context class SchoolListView(ListView):
# If you don't pass in this attribute,
# Django will auto create a context name
# for you with object_list!
# Default would be 'school_list'
# Example of making your own:
# context_object_name = 'schools'
model = models.School class SchoolDetailView(DetailView):
context_object_name = 'school_details'
model = models.School
template_name = 'basic_app/school_detail.html' class SchoolCreateView(CreateView):
fields = ("name","principal","location")
model = models.School class SchoolUpdateView(UpdateView):
fields = ("name","principal")
model = models.School class SchoolDeleteView(DeleteView):
model = models.School
success_url = reverse_lazy("basic_app:list") class CBView(View):
def get(self,request):
    return HttpResponse('Class Based Views are Cool!')

urls.py of application

from django.urls import path from . import views app_name =
'basic_app' urlpatterns = [
    path('',views.SchoolListView.as_view(),name='list'),
    ]

[list of files in project][1]

List item

urls.py of project from django.contrib import admin from
django.urls import path, include from basic_app import views
urlpatterns = [
path('',views.IndexView.as_view()),
path('admin/',admin.site.urls,name='admin'),
path('basic_app/',include('basic_app.urls',namespace='basic_app')),
]

settings.py """ Django settings for advcbv project. Generated by
'django-admin startproject' using Django 2.0.5. For more information
on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/ For the full
list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os

Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR =

os.path.dirname(os.path.dirname(os.path.abspath(file)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'template')

Quick-start development settings - unsuitable for production

See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=f%ns04d@z9na8xh(kfo8v8aa-v2p0bcn^jukrh4dm_^=zq70$'

SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = []

Application definition INSTALLED_APPS = [

'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'basic_app.apps.BasicAppConfig', ] MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'advcbv.urls' TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [TEMPLATE_DIR,],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
}, ] WSGI_APPLICATION = 'advcbv.wsgi.application'

Database

https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = {

'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
} }

Password validation

https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    }, ]

Internationalization

https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ =

True

Static files (CSS, JavaScript, Images)

https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/'**

[1]: https://i.stack.imgur.com/bYtk9.png

Body:
You have to dell Django that there exist more templates in your apps/dir like so:

Settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
                os.path.join(BASE_DIR, 'templates'),
                os.path.join(BASE_DIR, 'My_App/templates'), # root to your apps templates
                 ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]


问:
Can you translate this into ggplot?
So basically, I would like to use ggplot function geom_line + geom_point to create the same plots but with fancier graphics.

```<code>> a
          V1        V2        V3
1  0.8224887 0.7882316 0.7596440
2  0.7892779 0.7604186 0.7409430
3  0.8254516 0.8257800 0.8014778
4  0.8268519 0.7887464 0.7887322
5  0.8226651 0.7981079 0.7934783

plot(6:10, a$V1, type="l", xlab="Folds", ylab="Accuracy", col="Blue",ylim=c(0.7,0.9))
par(new=TRUE)
plot(6:10, a$V2, type="l", xlab="Folds", ylab="Accuracy", col="Orange",ylim=c(0.7,0.9))
par(new=TRUE)
plot(6:10, a$V3, type="l", xlab="Folds", ylab="Accuracy", col="Green",ylim=c(0.7,0.9))

</code>```

My main goal is to get a legend that helps to distinguish each variable.

I tried to plot just the first line:

```<code>ggplot(data = a)+
  theme_classic()+
  geom_line(aes(x=6:10, y = a$V1, color = "blue"))
</code>```

The problem is that i don't even get the color I want.

Thanks for reading and helping!

答:
```<code>library (dplyr)
library (ggplot2)

a <- data.frame(
V1=rnorm(5),
V2=rnorm(5),
V3=rnorm(5),
Folds = 6:10) # make some example data

a %>%
tidyr::gather(key,value,-Folds) %>% #get data in long format for ggplot
ggplot(.,aes(x = Folds,y = value,y,col = key))+
geom_line() + # add line
geom_point() + # add points
scale_color_manual("My Variables",values = c("blue","orange","green")) + #change colours
theme_classic()
</code>```

Title: Can you translate this into ggplot?

Body:
So basically, I would like to use ggplot function geom_line + geom_point to create the same plots but with fancier graphics.

> a
          V1        V2        V3
1  0.8224887 0.7882316 0.7596440
2  0.7892779 0.7604186 0.7409430
3  0.8254516 0.8257800 0.8014778
4  0.8268519 0.7887464 0.7887322
5  0.8226651 0.7981079 0.7934783

plot(6:10, a$V1, type="l", xlab="Folds", ylab="Accuracy", col="Blue",ylim=c(0.7,0.9))
par(new=TRUE)
plot(6:10, a$V2, type="l", xlab="Folds", ylab="Accuracy", col="Orange",ylim=c(0.7,0.9))
par(new=TRUE)
plot(6:10, a$V3, type="l", xlab="Folds", ylab="Accuracy", col="Green",ylim=c(0.7,0.9))

My main goal is to get a legend that helps to distinguish each variable.

I tried to plot just the first line:

ggplot(data = a)+
  theme_classic()+
  geom_line(aes(x=6:10, y = a$V1, color = "blue"))

The problem is that i don't even get the color I want.

Thanks for reading and helping!


问:
Bson Document to Json in Java
This is my code:

```<code>MongoDBSingleton dbSingleton = MongoDBSingleton.getInstance();
MongoDatabase db;

try {
    db = dbSingleton.getTestdb();
    MongoIterable<String> mg = db.listCollectionNames();
    MongoCursor<String> iterator=mg.iterator();

    while (iterator.hasNext()) {
        MongoCollection<Document> table = db.getCollection(iterator.next());

        for (Document doc: table.find()) {
            System.out.println(doc.toJson());
        }
    }

}
</code>```

This the output of toJson:

```<code>"modified" : { "$date" : 1475789185087}
</code>```

This is my output of toString:

```<code>{"modified":"Fri Oct 07 02:56:25 IST 2016"}
</code>```

I want String date format in Json, how to do it?

答:
I used following

```<code>try {

            MongoDatabase db = mongoClient.getDatabase("dbname");

            MongoCollection<Document> collection = db.getCollection("nameofcollect");

            Gson gson = new Gson();

            ArrayList<JsonObject> array = new ArrayList<JsonObject>();

            String jsonString = null;
            /*WARNING Gson lib serialize string ->means add slash if you convert "json string" into "json string"*/
            for (Document doc : collection.find()) {
                 jsonString = gson.toJson(doc);
                 array.add(new Gson().fromJson(jsonString, JsonObject.class));
            }

            //String finalarry = gson.toJson(array);

            Map<Object, ArrayList<JsonObject>> seedMap = new HashMap<Object, ArrayList<JsonObject>>();
            // String encode = coCoRy.encryptAndEncode(jsonString);
            seedMap.put("seed", array);
            String seedJsonString = gson.toJson(seedMap);

            mongoClient.close();

            return seedJsonString;

        } catch (MongoException | ClassCastException e) {
            e.printStackTrace();
            return null;
        }
</code>```

Result will be like following

```<code>{
    "seed": [
        {
            "_id": {
                "timestamp": 1590914828,
                "counter": 10457170,
                "randomValue1": 5587428,
                "randomValue2": -25784
            },
            "FIR_EVID_NUM": "3436345346",
            "FIR_REG_NUM": "89678967",
            "LOGIN_ID": "pc_admin",
            "MEDIA_PATH": "C:\\Users\\ALPHAMALE\\Documents\\ShareX\\Screenshots\\2020-05\\1590211570.png"
        },
        {
            "_id": {
                "timestamp": 1590924463,
                "counter": 7254997,
                "randomValue1": 5012578,
                "randomValue2": 24700
            },
            "FIR_EVID_NUM": "999999",
            "FIR_REG_NUM": "888888",
            "LOGIN_ID": "32323",
            "MEDIA_PATH": "C:/uploads/c46847c7e2d130ffd746c789c0f0932e.png"
        }
    ]
}
</code>```

Title: Bson Document to Json in Java

Body:
This is my code:

MongoDBSingleton dbSingleton = MongoDBSingleton.getInstance();
MongoDatabase db;

try {
    db = dbSingleton.getTestdb();
    MongoIterable<String> mg = db.listCollectionNames();
    MongoCursor<String> iterator=mg.iterator();

    while (iterator.hasNext()) {
        MongoCollection<Document> table = db.getCollection(iterator.next());

        for (Document doc: table.find()) {
            System.out.println(doc.toJson());
        }
    }

}

This the output of toJson:

"modified" : { "$date" : 1475789185087}

This is my output of toString:

{"modified":"Fri Oct 07 02:56:25 IST 2016"}

I want String date format in Json, how to do it?

Body:
I used following

try {

            MongoDatabase db = mongoClient.getDatabase("dbname");

            MongoCollection<Document> collection = db.getCollection("nameofcollect");

            Gson gson = new Gson();

            ArrayList<JsonObject> array = new ArrayList<JsonObject>();

            String jsonString = null;
            /*WARNING Gson lib serialize string ->means add slash if you convert "json string" into "json string"*/
            for (Document doc : collection.find()) {
                 jsonString = gson.toJson(doc);
                 array.add(new Gson().fromJson(jsonString, JsonObject.class));
            }

            //String finalarry = gson.toJson(array);

            Map<Object, ArrayList<JsonObject>> seedMap = new HashMap<Object, ArrayList<JsonObject>>();
            // String encode = coCoRy.encryptAndEncode(jsonString);
            seedMap.put("seed", array);
            String seedJsonString = gson.toJson(seedMap);

            mongoClient.close();

            return seedJsonString;

        } catch (MongoException | ClassCastException e) {
            e.printStackTrace();
            return null;
        }

Result will be like following

{
    "seed": [
        {
            "_id": {
                "timestamp": 1590914828,
                "counter": 10457170,
                "randomValue1": 5587428,
                "randomValue2": -25784
            },
            "FIR_EVID_NUM": "3436345346",
            "FIR_REG_NUM": "89678967",
            "LOGIN_ID": "pc_admin",
            "MEDIA_PATH": "C:\\Users\\ALPHAMALE\\Documents\\ShareX\\Screenshots\\2020-05\\1590211570.png"
        },
        {
            "_id": {
                "timestamp": 1590924463,
                "counter": 7254997,
                "randomValue1": 5012578,
                "randomValue2": 24700
            },
            "FIR_EVID_NUM": "999999",
            "FIR_REG_NUM": "888888",
            "LOGIN_ID": "32323",
            "MEDIA_PATH": "C:/uploads/c46847c7e2d130ffd746c789c0f0932e.png"
        }
    ]
}


问:
Error: <toHaveBeenCalled> : Expected a spy, but got Function in Jamsine
I'm new to Unit testing in Angular using Jasmine and Karma. I've written a spec file but I'm getting an error. Let me first show what I've done so far. I've created a custom component:

TimeselectorComponent

```<code>startRange = moment('12-01-01');
endRange = moment ('12-12-01');

modes= ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];

date = new Date();
currentYear = this.date.getFullYear(); // or simply currentYear = 2020;

@ViewChild('primaryMonthPicker') primaryMonthPicker: MonthpickerComponent; // a child component

primaryDropDown(startRange, endRange) {
    if (this.primaryMode === this.modes[0]) {
        this.initCalendarYear(this.primaryMonthPicker, this.currentYear);
    } else if (this.primaryMode === this.modes[1]) {
        this.initYearToDate(this.primaryMonthPicker, this.currentYear);
    } else if (this.primaryMode === this.modes[2]) {
        this.initRollingYear(this.primaryMonthPicker, this.currentYear);
    }
}
</code>```

In the above code MonthpickerComponent is another custom component which is the only child component of TimeselectorComponent.

I just want to check when primaryDropDown is called then initCalendarYear should also be called. Here's the spec file:

```<code>import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { TimeselectorComponent } from './timeselector.component';
...

describe('TimeselectorComponent', () => {
    let fixture: ComponentFixture<TimeselectorComponent>;

    @Component({
        selector: 'app-monthpicker',
        template: '<div></div>'
    })
    class FakeMonthpickerComponent {
        // methods of MonthpickerComponent
    }

    let MODES = [];

    beforeEach(async(() => {
        MODES = ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];
        TestBed.configureTestingModule({
            declarations: [FakeMonthpickerComponent, TimeselectorComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TimeselectorComponent);
    });

    // other test cases that are passing

    // need help with this test case
    it('should call initCalendarYear when primaryDropDown is called', () => {
      const startRange=moment('2020-01-01');
      const endRange= moment('2020-12-01');
      spyOn(fixture.componentInstance, 'initCalendarYear');
      fixture.componentInstance.primaryMode=MODES[0];
      fixture.componentInstance.primaryDropDown(startRange, endRange);
     expect(fixture.componentInstance.initCalendarYear).toHaveBeenCalled();
  });
});
</code>```

But I'm getting this error:

I have to test whether correct method is called for associated if-else statement. Please help me.

Here's the stackblitz.

答:
```<code>import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { TimeselectorComponent } from './timeselector.component';
import { Component, NO_ERRORS_SCHEMA } from '@angular/core';
var moment = require('moment/moment')

describe('TimeselectorComponent', () => {
    let fixture: ComponentFixture<TimeselectorComponent>;

    @Component({
        selector: 'app-monthpicker',
        template: '<div></div>'
    })
    class FakeMonthpickerComponent {
        // methods of MonthpickerComponent
    }

    let MODES = [];

    beforeEach(async(() => {
        MODES = ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];
        TestBed.configureTestingModule({
            declarations: [FakeMonthpickerComponent, TimeselectorComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TimeselectorComponent);
    });

    // other test cases that are passing

    // need help with this test case
    it('should call initCalendarYear when primaryDropDown is called', () => {
      const startRange=moment('2020-01-01');
      const endRange= moment('2020-12-01');
      spyOn(fixture.componentInstance, 'initCalendarYear');
      fixture.componentInstance.primaryMode=MODES[0];
      fixture.componentInstance.primaryDropDown(startRange, endRange);
     expect(fixture.componentInstance.initCalendarYear).toHaveBeenCalled();
  });
});
</code>```

The above game me success :-

Body:
I'm new to Unit testing in Angular using Jasmine and Karma. I've written a spec file but I'm getting an error. Let me first show what I've done so far. I've created a custom component:

TimeselectorComponent

startRange = moment('12-01-01');
endRange = moment ('12-12-01');

modes= ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];

date = new Date();
currentYear = this.date.getFullYear(); // or simply currentYear = 2020;

@ViewChild('primaryMonthPicker') primaryMonthPicker: MonthpickerComponent; // a child component

primaryDropDown(startRange, endRange) {
    if (this.primaryMode === this.modes[0]) {
        this.initCalendarYear(this.primaryMonthPicker, this.currentYear);
    } else if (this.primaryMode === this.modes[1]) {
        this.initYearToDate(this.primaryMonthPicker, this.currentYear);
    } else if (this.primaryMode === this.modes[2]) {
        this.initRollingYear(this.primaryMonthPicker, this.currentYear);
    }
}

In the above code MonthpickerComponent is another custom component which is the only child component of TimeselectorComponent.

I just want to check when primaryDropDown is called then initCalendarYear should also be called. Here's the spec file:

import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { TimeselectorComponent } from './timeselector.component';
...

describe('TimeselectorComponent', () => {
    let fixture: ComponentFixture<TimeselectorComponent>;

    @Component({
        selector: 'app-monthpicker',
        template: '

'
    })
    class FakeMonthpickerComponent {
        // methods of MonthpickerComponent
    }

    let MODES = [];

    beforeEach(async(() => {
        MODES = ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];
        TestBed.configureTestingModule({
            declarations: [FakeMonthpickerComponent, TimeselectorComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TimeselectorComponent);
    });

    // other test cases that are passing

    // need help with this test case
    it('should call initCalendarYear when primaryDropDown is called', () => {
      const startRange=moment('2020-01-01');
      const endRange= moment('2020-12-01');
      spyOn(fixture.componentInstance, 'initCalendarYear');
      fixture.componentInstance.primaryMode=MODES[0];
      fixture.componentInstance.primaryDropDown(startRange, endRange);
     expect(fixture.componentInstance.initCalendarYear).toHaveBeenCalled();
  });
});

But I'm getting this error:

I have to test whether correct method is called for associated if-else statement. Please help me.

Here's the stackblitz.

Body:
import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { TimeselectorComponent } from './timeselector.component';
import { Component, NO_ERRORS_SCHEMA } from '@angular/core';
var moment = require('moment/moment')

describe('TimeselectorComponent', () => {
    let fixture: ComponentFixture<TimeselectorComponent>;

    @Component({
        selector: 'app-monthpicker',
        template: '<div></div>'
    })
    class FakeMonthpickerComponent {
        // methods of MonthpickerComponent
    }

    let MODES = [];

    beforeEach(async(() => {
        MODES = ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];
        TestBed.configureTestingModule({
            declarations: [FakeMonthpickerComponent, TimeselectorComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TimeselectorComponent);
    });

    // other test cases that are passing

    // need help with this test case
    it('should call initCalendarYear when primaryDropDown is called', () => {
      const startRange=moment('2020-01-01');
      const endRange= moment('2020-12-01');
      spyOn(fixture.componentInstance, 'initCalendarYear');
      fixture.componentInstance.primaryMode=MODES[0];
      fixture.componentInstance.primaryDropDown(startRange, endRange);
     expect(fixture.componentInstance.initCalendarYear).toHaveBeenCalled();
  });
});

The above game me success :-


问:
error C2027: use of undefined type GUITHREADINFO
during build with Visual Studio C++ I get this error:

```<code>error C2027: use of undefined type 'rectAnalyzer::GUITHREADINFO'
</code>```

the function rectAnalyzer is the following:

```<code>DWORD WINAPI rectAnalyzer(LPVOID param)
{
MSG msg;
PARAM_PASSED *p = (PARAM_PASSED*) param;
std::ostringstream ss;
std::wstring str;
PGUITHREADINFO g = (PGUITHREADINFO) malloc(sizeof(struct GUITHREADINFO));

if(p)
{
    ss << "rectAnalyzer: entering thread " << p->index << "->" << p->parentThreadId << std::endl;
    str = string2wideString(ss.str().c_str());
    OutputDebugString(str.c_str());
    PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
    if(WaitForSingleObject(hStartEvent,INFINITE) != WAIT_OBJECT_0)
        return 1;
    ss << "rectAnalyzer: thread " << p->index << " sending WM_APP" << std::endl;
    str = string2wideString(ss.str().c_str());
    OutputDebugString(str.c_str());
    if(!GetGUIThreadInfo(p->parentThreadId, g))
    {
        ss << "rectAnalyzer: unable to get GUI thread info" << std::endl;
        str = string2wideString(ss.str().c_str());
        OutputDebugString(str.c_str());
    }
    while(!PostMessage(g->hwndActive, WM_APP, (WPARAM) 0, (LPARAM) 0))
    {
        ss << "rectAnalyzer: thread " << p->index << " unable to send WM_APP" << std::endl;
        str = string2wideString(ss.str().c_str());
        OutputDebugString(str.c_str());
        Sleep(1);
    }
    free(p);
}
else
{
    ss << "rectAnalyzer: cannot get p" << std::endl;
    str = string2wideString(ss.str().c_str());
    OutputDebugString(str.c_str());
}

return 0;
}
</code>```

I've included also WinUser.h or Windows.h but with no result.

答: Try using sizeof(GUITHREADINFO) instead of sizeof(struct GUITHREADINFO)

Body:
during build with Visual Studio C++ I get this error:

error C2027: use of undefined type 'rectAnalyzer::GUITHREADINFO'

the function rectAnalyzer is the following:

DWORD WINAPI rectAnalyzer(LPVOID param)
{
MSG msg;
PARAM_PASSED *p = (PARAM_PASSED*) param;
std::ostringstream ss;
std::wstring str;
PGUITHREADINFO g = (PGUITHREADINFO) malloc(sizeof(struct GUITHREADINFO));

if(p)
{
    ss << "rectAnalyzer: entering thread " <
index << "->" <
parentThreadId << std::endl;
    str = string2wideString(ss.str().c_str());
    OutputDebugString(str.c_str());
    PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
    if(WaitForSingleObject(hStartEvent,INFINITE) != WAIT_OBJECT_0)
        return 1;
    ss << "rectAnalyzer: thread " <
index << " sending WM_APP" << std::endl;
    str = string2wideString(ss.str().c_str());
    OutputDebugString(str.c_str());
    if(!GetGUIThreadInfo(p->parentThreadId, g))
    {
        ss << "rectAnalyzer: unable to get GUI thread info" << std::endl;
        str = string2wideString(ss.str().c_str());
        OutputDebugString(str.c_str());
    }
    while(!PostMessage(g->hwndActive, WM_APP, (WPARAM) 0, (LPARAM) 0))
    {
        ss << "rectAnalyzer: thread " <
index << " unable to send WM_APP" << std::endl;
        str = string2wideString(ss.str().c_str());
        OutputDebugString(str.c_str());
        Sleep(1);
    }
    free(p);
}
else
{
    ss << "rectAnalyzer: cannot get p" << std::endl;
    str = string2wideString(ss.str().c_str());
    OutputDebugString(str.c_str());
}

return 0;
}

I've included also WinUser.h or Windows.h but with no result.