问:
How to get base url with jquery or javascript?
In joomla php there I can use $this->baseurl to get the base path, but I wanted to get the base path in jquery.

The base path may be any of the following example:

```<code>http://www.example.com/
http://localhost/example
http://www.example.com/sub/example
</code>```

The example may also change.

答:
You mentioned that the example.com may change so I suspect that actually you need the base url just to be able to use relative path notation for your scripts. In this particular case there is no need to use scripting - instead add the base tag to your header:

```<code><head>
  <base href="http://www.example.com/">
</head>
</code>```

I usually generate the link via PHP.

Body:
In joomla php there I can use $this->baseurl to get the base path, but I wanted to get the base path in jquery.

The base path may be any of the following example:

http://www.example.com/
http://localhost/example
http://www.example.com/sub/example

The example may also change.

Body:
You mentioned that the example.com may change so I suspect that actually you need the base url just to be able to use relative path notation for your scripts. In this particular case there is no need to use scripting - instead add the base tag to your header:

<head>
  <base href="http://www.example.com/">
</head>

I usually generate the link via PHP.


来源: stackexchange

问:
OData, DataServiceClientException: Unauthorized
I'm developing (as a totally no-C#-guy) a web app which communicates with an external data source over OData (server B, some windows 2k12 machine).
The web app runs (is about to run) on an IIS (server A, another windows 2k12 machine), the OData source is a Dynamics NAV 2015 service (the first mentioned windows 2k12 machine, server B).
I'm developing it in VS2013 and if I'm running this locally (meaning: without publishing it, only running it within the local express IIS) it works without any problems at all.
But as soon as I publish it to the target IIS (server A) I'm getting:

An error occurred while processing this request. ---> >System.Data.Services.Client.DataServiceClientException: Unauthorized
    at System.Data.Services.Client.QueryResult.ExecuteQuery()
    at System.Data.Services.Client.DataServiceRequest.Execute[TElement]>(DataServiceContext context, QueryComponents queryComponents)
    --- End of inner exception stack trace ---

This is esentially the piece of code which deals with the OData call:

```<code>ODataOrders.NAV odata = new ODataOrders.NAV(new Uri(serviceUri));
System.Net.NetworkCredential nc = new
System.Net.NetworkCredential(_oDataUsername, _oDataUserPassword, _oDataDomain);
odata.Credentials = nc;
DataServiceQuery<ODataOrders.Orders> query =
odata.CreateQuery<ODataOrders.Orders>("Orders");
orderList = query.Execute().ToList();  // "Unauthorized" is being thrown here
</code>```

It looks like the credentials are being sent/accepted if running from local IIS. And if running from the target (production) server A, the credentials are being somehow lost/overwritten? I really don't know now...
Server A and Server B are in the same domain. My development environment isn't - I can even connect from home through VPN to my work domain and launch my local IIS and still be able to get that request done (the request goes through my local IIS and reaches the Dynamics NAV service so the data is being actually fetched).
Any help would be appreciated...
EDIT
It's Dynamics NAV 2015 CU11.

答:
After some serious hours of reading, programming and trying I've stumbled upon a post here which gave me an idea.
And guess what? It worked - somehow...

Instead of:

```<code>    System.Net.NetworkCredential(_oDataUsername, _oDataUserPassword, _oDataDomain);
</code>```

I submitted only:

```<code>    System.Net.NetworkCredential(_oDataUsername, _oDataUserPassword);
</code>```

I turns out somehow the domain caused the call not to be authorized (401 error).

ContentLicense: CC BY-SA 3.0

Body:
I'm developing (as a totally no-C#-guy) a web app which communicates with an external data source over OData (server B, some windows 2k12 machine).
The web app runs (is about to run) on an IIS (server A, another windows 2k12 machine), the OData source is a Dynamics NAV 2015 service (the first mentioned windows 2k12 machine, server B).
I'm developing it in VS2013 and if I'm running this locally (meaning: without publishing it, only running it within the local express IIS) it works without any problems at all.
But as soon as I publish it to the target IIS (server A) I'm getting:

An error occurred while processing this request. ---> >System.Data.Services.Client.DataServiceClientException: Unauthorized
    at System.Data.Services.Client.QueryResult.ExecuteQuery()
    at System.Data.Services.Client.DataServiceRequest.Execute[TElement]>(DataServiceContext context, QueryComponents queryComponents)
    --- End of inner exception stack trace ---

This is esentially the piece of code which deals with the OData call:

ODataOrders.NAV odata = new ODataOrders.NAV(new Uri(serviceUri));
System.Net.NetworkCredential nc = new
System.Net.NetworkCredential(_oDataUsername, _oDataUserPassword, _oDataDomain);
odata.Credentials = nc;
DataServiceQuery<ODataOrders.Orders> query =
odata.CreateQuery<ODataOrders.Orders>("Orders");
orderList = query.Execute().ToList();  // "Unauthorized" is being thrown here

It looks like the credentials are being sent/accepted if running from local IIS. And if running from the target (production) server A, the credentials are being somehow lost/overwritten? I really don't know now...
Server A and Server B are in the same domain. My development environment isn't - I can even connect from home through VPN to my work domain and launch my local IIS and still be able to get that request done (the request goes through my local IIS and reaches the Dynamics NAV service so the data is being actually fetched).
Any help would be appreciated...
EDIT
It's Dynamics NAV 2015 CU11.

Body:
After some serious hours of reading, programming and trying I've stumbled upon a post here which gave me an idea.
And guess what? It worked - somehow...

Instead of:

    System.Net.NetworkCredential(_oDataUsername, _oDataUserPassword, _oDataDomain);

I submitted only:

    System.Net.NetworkCredential(_oDataUsername, _oDataUserPassword);

I turns out somehow the domain caused the call not to be authorized (401 error).


问:
Hash distribution on identity column
Creating a table in Azure SQL Data Warehouse, I would like to make a hash distribution on an identity column, but get an error that

```<code>Cannot insert explicit value for identity column in table 'Table_ff4d8c5d544f4e26a31dbe71b44851cb_11' when IDENTITY_INSERT is set to OFF.
</code>```

Is this not possible? And if not, why? And is there a work-around? (And where does this odd table name come from?)

Thanks!

答:
You cannot use an IDENTITY column as the hash distributed column in your table.
https://learn.microsoft.com/en-us/azure/sql-data-warehouse/sql-data-warehouse-tables-identity#limitations

In SQLDW the name you give to your table is its logical name not its physical name. Logical metadata such as table names is maintained centrally on the control node so that operations such as table renames are quick and painless. However, SQLDW is still bound by the rules of table creation - we need to make sure the table name is unique both now and in the future. Therefore the physical names contain guids to deliver that uniqueness.

Saying that, the error you have here is not ideal. It would be helpful if you can post a repro so that we can improve the experience for you.

You are also welcome to post a feature request on our uservoice channel for hash distribution on the IDENTITY column. https://feedback.azure.com/forums/307516-sql-data-warehouse

Title: Hash distribution on identity column

Body:
Creating a table in Azure SQL Data Warehouse, I would like to make a hash distribution on an identity column, but get an error that

Cannot insert explicit value for identity column in table 'Table_ff4d8c5d544f4e26a31dbe71b44851cb_11' when IDENTITY_INSERT is set to OFF.

Is this not possible? And if not, why? And is there a work-around? (And where does this odd table name come from?)

Thanks!


问:
Difference between adobe printing properties in Linux and Windows
I work on Linux and I've made a report as the costumer wanted on iReport. It has some properties like "ignore pagination". I tested and retested a bunch of times and it has everything on its right position.

But my costumer has Windows and when I tried to print it on there, it's completely different. Even on adobe printing properties where I switch 2 attributes. One to not rotate and centralize and the other to get the page size of the document I've just created(because it makes only one page(ignore pagination attribute) and I'm printing on a Dot Matrix Printer, so it has that paper that "never ends")

Any idea of what could I do on Windows to print it correctly? What attribute on Windows would be the same as those that I'm reseting on Linux, etc.

答: Be sure that the drivers are using the same printer "language" on each system (I forget the technical name)- postscript, pcl, etc.. and version..  You can check the Linux system via CUPS and the Windows one via the printer driver properties. </p>

ContentLicense: CC BY-SA 2.5


问:
Java : Need to get the same functionality of the Integer.toHexString() with a String parameter and not an Int parameter due to NumberFormat Exception
I have this line of Java code that will throw NumberFormatException if the number represented as a String is above 2,147,483,647.

Because:

The int data type is a 32-bit signed two's complement integer. It has
  a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647

Code Throwing the NumberFormatException:

```<code>String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException
</code>```

How can I get the same functionality of theInteger.toHexString() with a String parameter and not an int parameter due to NumberFormatException?

答:
Use Integer.parseUnsignedInt

When the number is above 2^31 but below 2^32, thus in the negative int range,
you can do:

```<code>int n = Integer.parseUnsignedInt("CAFEBABE", 16);
</code>```

(I used hexadecimal here, as it is easier to see that above we are just in that range.)

However 9_999_999_999 is above the unsigned int range too.

Body:
I have this line of Java code that will throw NumberFormatException if the number represented as a String is above 2,147,483,647.

Because:

The int data type is a 32-bit signed two's complement integer. It has
  a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647

Code Throwing the NumberFormatException:

String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException

How can I get the same functionality of theInteger.toHexString() with a String parameter and not an int parameter due to NumberFormatException?

Body:
Use Integer.parseUnsignedInt

When the number is above 2^31 but below 2^32, thus in the negative int range,
you can do:

int n = Integer.parseUnsignedInt("CAFEBABE", 16);

(I used hexadecimal here, as it is easier to see that above we are just in that range.)

However 9_999_999_999 is above the unsigned int range too.


问:
How to make Robolectric Test for AlertDialog
I am new to robolectric and I am trying to make a test for a button that creates an AlertDialog. When the button is clicked, an AlertDialog is made with a positive button that I want to click using Robolectric, and test if it launches an activity. Here is the code for the button:

```<code>newUserButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
            builder.setTitle(context.getResources().getString(R.string.start_title_message))
                    .setMessage(getResources().getString(R.string.start_dialog_message));
            builder.setPositiveButton(getString(R.string.start_confirm_message), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    startActivityForResult(new Intent(StartActivity.this, AvatarRoomActivity.class), 0);
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });
            AlertDialog dialog = builder.create();
            ColorDrawable drawable = new ColorDrawable(Color.WHITE);
            drawable.setAlpha(200);
            dialog.getWindow().setBackgroundDrawable(drawable);
            dialog.show();
        }
    });
</code>```

Does anyone know how I can test clicking the positive button, then launching AvatarRoomActivity? Thanks in advance and hope to hear from someone soon.

答:
Let's forget the newUserButton for a while. It is not relevant to the problem.

You will need to expose the AlertDialog object so that it is accessible in unit test code. So I assume you activity have such a method in StartActivity:

```<code>AlertDialog showDialog() {

    AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
    builder.setTitle("This is title")
            .setMessage("Dialog Message");
    builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            startActivityForResult(new Intent(this, AvatarRoomActivity.class), 0);
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });
    AlertDialog dialog = builder.create();
    dialog.show();

    return dialog;

}
</code>```

then the click event of newUserButton just invoke this method.

Then we have the test case like this:

```<code>@Test
public void testLaunchAvatarRoomWhenConfirm() {

    StartActivity startActivity = Robolectric.buildActivity(StartActivity.class).create().get();

    AlertDialog dialog = startActivity.showDialog();

    // Key part 1 : simulate button click in unit test
    Button confirm = dialog.getButton(Dialog.BUTTON_POSITIVE);
    confirm.performClick();

    // Key part 2 : Check that startActivityForResult is invoke
    ShadowActivity shadowActivity = shadowOf(startActivity);
    ShadowActivity.IntentForResult intentForResult = shadowActivity.getNextStartedActivityForResult();

    // assert that the proper request to start activity is sent
    ComponentName nextActivity = intentForResult.intent.getComponent();
    assertEquals(".AvatarRoomActivity", nextActivity.getShortClassName());

}
</code>```

This test method verify that when the dialog's positive button is clicked, startActivityForResult is invoked with proper activity class name.

So the remaining problem is how do we ensure the activity is really resolved and launched. Normally I would stop at this point for testing of alert dialog actions. Whether the intent can be resolved and start activity property is out of the scope of this particular test case.

Body:
I am new to robolectric and I am trying to make a test for a button that creates an AlertDialog. When the button is clicked, an AlertDialog is made with a positive button that I want to click using Robolectric, and test if it launches an activity. Here is the code for the button:

newUserButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
            builder.setTitle(context.getResources().getString(R.string.start_title_message))
                    .setMessage(getResources().getString(R.string.start_dialog_message));
            builder.setPositiveButton(getString(R.string.start_confirm_message), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    startActivityForResult(new Intent(StartActivity.this, AvatarRoomActivity.class), 0);
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });
            AlertDialog dialog = builder.create();
            ColorDrawable drawable = new ColorDrawable(Color.WHITE);
            drawable.setAlpha(200);
            dialog.getWindow().setBackgroundDrawable(drawable);
            dialog.show();
        }
    });

Does anyone know how I can test clicking the positive button, then launching AvatarRoomActivity? Thanks in advance and hope to hear from someone soon.

Body:
Let's forget the newUserButton for a while. It is not relevant to the problem.

You will need to expose the AlertDialog object so that it is accessible in unit test code. So I assume you activity have such a method in StartActivity:

AlertDialog showDialog() {

    AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
    builder.setTitle("This is title")
            .setMessage("Dialog Message");
    builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            startActivityForResult(new Intent(this, AvatarRoomActivity.class), 0);
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });
    AlertDialog dialog = builder.create();
    dialog.show();

    return dialog;

}

then the click event of newUserButton just invoke this method.

Then we have the test case like this:

@Test
public void testLaunchAvatarRoomWhenConfirm() {

    StartActivity startActivity = Robolectric.buildActivity(StartActivity.class).create().get();

    AlertDialog dialog = startActivity.showDialog();

    // Key part 1 : simulate button click in unit test
    Button confirm = dialog.getButton(Dialog.BUTTON_POSITIVE);
    confirm.performClick();

    // Key part 2 : Check that startActivityForResult is invoke
    ShadowActivity shadowActivity = shadowOf(startActivity);
    ShadowActivity.IntentForResult intentForResult = shadowActivity.getNextStartedActivityForResult();

    // assert that the proper request to start activity is sent
    ComponentName nextActivity = intentForResult.intent.getComponent();
    assertEquals(".AvatarRoomActivity", nextActivity.getShortClassName());

}

This test method verify that when the dialog's positive button is clicked, startActivityForResult is invoked with proper activity class name.

So the remaining problem is how do we ensure the activity is really resolved and launched. Normally I would stop at this point for testing of alert dialog actions. Whether the intent can be resolved and start activity property is out of the scope of this particular test case.


问:
show a picker after a button press event

Hi everyone, I am working on a crossplatform app that will allow the user to select first from a list.view and then from a picker. the listview works fine, and now I am working on the picker but I have run into a problem.

I have seem the implementation "picker.SelectedIndexChanged += (sender, args) => " used to handle the selection of a new element on the list but I am having an issue with the sender on this. the error is "Error CS0136 A local or parameter named 'sender' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter."

I understand that this error is related to the parameter sender from the even handler parameter in the func itself but since I am not declaring a new variable sender, how is this throwing an error? below is the code ( just a mock for now. this is the basic implementation but the content of the picker will change depending on what was selected on the listview.)

```<code>private void Button_Pressed(object sender, EventArgs e)
    {
        Picker picker = new Picker
        {
            Title = "Select SubUnit",
            VerticalOptions = LayoutOptions.Center
        };

       string[] list = new string[] { "1", "2", "3", "4", "5" } ;

        foreach(string subunit in list)
        {
            picker.Items.Add(subunit);
        }

        picker.Focus();

        picker.SelectedIndexChanged += (sender, args) =>
        {
            if (picker.SelectedIndex == -1)
            {
              //ToDo. Prob unnecessary to handle.
            }
            else
            {
                string selectedSub = picker.Items[picker.SelectedIndex];
            }
        };

    }
</code>```

I expect the picker to come into focus and allow the user to select an element after the button is pressed. any ideas?

right now, the only error is the syntax error I get on the sender object, and technically the picker not coming into focus but I am sure I can figure that one out once I get this to compile.

答:
you are already using sender in the current scope

```<code>private void Button_Pressed(object sender, EventArgs e)
</code>```

you need to renamed the other instance of sender to something unique

```<code>picker.SelectedIndexChanged += (s, args) =>
</code>```

Body:
Hi everyone, I am working on a crossplatform app that will allow the user to select first from a list.view and then from a picker. the listview works fine, and now I am working on the picker but I have run into a problem.

I have seem the implementation "picker.SelectedIndexChanged += (sender, args) => " used to handle the selection of a new element on the list but I am having an issue with the sender on this. the error is "Error CS0136 A local or parameter named 'sender' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter."

I understand that this error is related to the parameter sender from the even handler parameter in the func itself but since I am not declaring a new variable sender, how is this throwing an error? below is the code ( just a mock for now. this is the basic implementation but the content of the picker will change depending on what was selected on the listview.)

private void Button_Pressed(object sender, EventArgs e)
    {
        Picker picker = new Picker
        {
            Title = "Select SubUnit",
            VerticalOptions = LayoutOptions.Center
        };

       string[] list = new string[] { "1", "2", "3", "4", "5" } ;

        foreach(string subunit in list)
        {
            picker.Items.Add(subunit);
        }

        picker.Focus();

        picker.SelectedIndexChanged += (sender, args) =>
        {
            if (picker.SelectedIndex == -1)
            {
              //ToDo. Prob unnecessary to handle.
            }
            else
            {
                string selectedSub = picker.Items[picker.SelectedIndex];
            }
        };

    }

I expect the picker to come into focus and allow the user to select an element after the button is pressed. any ideas?

right now, the only error is the syntax error I get on the sender object, and technically the picker not coming into focus but I am sure I can figure that one out once I get this to compile.

Body:
you are already using sender in the current scope

private void Button_Pressed(object sender, EventArgs e)

you need to renamed the other instance of sender to something unique

picker.SelectedIndexChanged += (s, args) =>


问:
Setting value of Entry using tkinter, MVC and Observables
I am trying to build a simple GUI using tkinter to read in CSV's and then run some text mining functions. I am having difficulty understand tkinter's callback function. The following code was created using this ToyMVC code.

I am able to get the GUI to pop up but am having trouble getting the rightmost Entry widget (variable name = finalPathEntry) to update with the user-inputted text from the left Widget once the user presses the button.

I would greatly appreciate any advice on how to move forward and what I am doing wrong.

Best,

```<code>import tkinter as tk

class Observable:
    def __init__(self, initialValue=None):
        self.data = initialValue
        self.callbacks = {}

def addCallback(self, func):
    self.callbacks[func] = 1

def delCallback(self, func):
    del self.callback[func]

def _docallbacks(self):
    for func in self.callbacks:
         func(self.data)

def set(self, data):
    self.data = data
    self._docallbacks()

def get(self):
    return self.data

def unset(self):
    self.data = None

class Model:
    def __init__(self):
        self.csvPath = Observable("")

    def addPath(self, value):
        self.csvPath.set(self.csvPath.get())

class View(tk.Toplevel):
    def __init__(self, master):
        tk.Toplevel.__init__(self, master)
        self.protocol('WM_DELETE_WINDOW', self.master.destroy)
        tk.Label(self, text='Please input path to CSV').pack(side='left')

        self.pathEntry = tk.Entry(self, width=50)
        self.pathEntry.pack(side='left')
        self.addButton = tk.Button(self, text='Read CSV', width=8)
        self.addButton.pack(side='left')
        self.path = tk.StringVar()
        self.finalPathEntry = tk.Entry(self, width = 30, textvariable = self.path)
        self.finalPathEntry.pack(side='left')

    def setPath(self, value):
        self.path.set(str(value))

class Controller:
    def __init__(self, root):
        self.model = Model()
        self.model.csvPath.addCallback(self.pathChanged)
        self.view1 = View(root)
        self.view1.minsize(width = 500, height = 500)
        self.view1.addButton.config(command=self.addPath)
        self.pathChanged(self.model.csvPath.get())

    def addPath(self):
        self.model.addPath(self.view1.pathEntry.get())

    def pathChanged(self, val):
        self.view1.setPath(val)

if __name__ == '__main__':
    root = tk.Tk()
    root.withdraw()
    app = Controller(root)
    root.mainloop()
</code>```

EDIT: Using the answer below, I have fixed my code. Here is the updated and working snippet:

```<code>import tkinter as tk

class Observable:
    def __init__(self, initialValue = None):
        self.data = initialValue
        self.callbacks = {}

    def addCallback(self, func):
        self.callbacks[func] = 1

    def delCallback(self, func):
        del self.callback[func]

    def _docallbacks(self):
        for func in self.callbacks:
            func(self.data)

    def set(self, data):
        self.data = data
        self._docallbacks()

    def get(self):
        return self.data

    def unset(self):
        self.data = None

class Model:
    def __init__(self):
        self.csvPath = Observable("")

    def addPath(self, value):
        self.csvPath.set(self.csvPath.get())

class View(tk.Toplevel):
    def __init__(self, master):
        tk.Toplevel.__init__(self, master)
        self.protocol('WM_DELETE_WINDOW', self.master.destroy)
        tk.Label(self, text='Please input path to CSV').pack(side='left')
        self.pathEntry = tk.Entry(self, width=50)
        self.pathEntry.pack(side='left')
        self.addButton = tk.Button(self, text='Read CSV', width=8)
        self.addButton.pack(side='left')
        self.path = tk.StringVar()
        self.finalPathEntry = tk.Entry(self, width = 30, textvariable = self.path)
        self.finalPathEntry.pack(side='left')

    def setPath(self, value):
        self.path.set(str(value))

class Controller:
    def __init__(self, root):
        self.model = Model()
        self.model.csvPath.addCallback(self.pathChanged)
        self.view1 = View(root)
        self.view1.minsize(width = 500, height = 500)
        self.view1.addButton.config(command = self.addPath)
        self.pathChanged(self.model.csvPath.get())

    def addPath(self):
        self.model.addPath(self.view1.pathEntry.get())

    def pathChanged(self, val):
        self.view1.setPath(val)

if __name__ == '__main__':
    root = tk.Tk()
    root.withdraw()
    app = Controller(root)
    root.mainloop()
</code>```

答:
One thing about this code seems obvious: The functions beginning at

```<code>def addcallback(self, func):
</code>```

until

```<code>def unset(self):
</code>```

are not part of the Observable class. So the "self" argument is not what you expect it to be. You should indent these functions.

Body:
I am trying to build a simple GUI using tkinter to read in CSV's and then run some text mining functions. I am having difficulty understand tkinter's callback function. The following code was created using this ToyMVC code.

I am able to get the GUI to pop up but am having trouble getting the rightmost Entry widget (variable name = finalPathEntry) to update with the user-inputted text from the left Widget once the user presses the button.

I would greatly appreciate any advice on how to move forward and what I am doing wrong.

Best,

import tkinter as tk

class Observable:
    def __init__(self, initialValue=None):
        self.data = initialValue
        self.callbacks = {}

def addCallback(self, func):
    self.callbacks[func] = 1

def delCallback(self, func):
    del self.callback[func]

def _docallbacks(self):
    for func in self.callbacks:
         func(self.data)

def set(self, data):
    self.data = data
    self._docallbacks()

def get(self):
    return self.data

def unset(self):
    self.data = None

class Model:
    def __init__(self):
        self.csvPath = Observable("")

    def addPath(self, value):
        self.csvPath.set(self.csvPath.get())

class View(tk.Toplevel):
    def __init__(self, master):
        tk.Toplevel.__init__(self, master)
        self.protocol('WM_DELETE_WINDOW', self.master.destroy)
        tk.Label(self, text='Please input path to CSV').pack(side='left')

        self.pathEntry = tk.Entry(self, width=50)
        self.pathEntry.pack(side='left')
        self.addButton = tk.Button(self, text='Read CSV', width=8)
        self.addButton.pack(side='left')
        self.path = tk.StringVar()
        self.finalPathEntry = tk.Entry(self, width = 30, textvariable = self.path)
        self.finalPathEntry.pack(side='left')

    def setPath(self, value):
        self.path.set(str(value))

class Controller:
    def __init__(self, root):
        self.model = Model()
        self.model.csvPath.addCallback(self.pathChanged)
        self.view1 = View(root)
        self.view1.minsize(width = 500, height = 500)
        self.view1.addButton.config(command=self.addPath)
        self.pathChanged(self.model.csvPath.get())

    def addPath(self):
        self.model.addPath(self.view1.pathEntry.get())

    def pathChanged(self, val):
        self.view1.setPath(val)

if __name__ == '__main__':
    root = tk.Tk()
    root.withdraw()
    app = Controller(root)
    root.mainloop()

EDIT: Using the answer below, I have fixed my code. Here is the updated and working snippet:

import tkinter as tk

class Observable:
    def __init__(self, initialValue = None):
        self.data = initialValue
        self.callbacks = {}

    def addCallback(self, func):
        self.callbacks[func] = 1

    def delCallback(self, func):
        del self.callback[func]

    def _docallbacks(self):
        for func in self.callbacks:
            func(self.data)

    def set(self, data):
        self.data = data
        self._docallbacks()

    def get(self):
        return self.data

    def unset(self):
        self.data = None

class Model:
    def __init__(self):
        self.csvPath = Observable("")

    def addPath(self, value):
        self.csvPath.set(self.csvPath.get())

class View(tk.Toplevel):
    def __init__(self, master):
        tk.Toplevel.__init__(self, master)
        self.protocol('WM_DELETE_WINDOW', self.master.destroy)
        tk.Label(self, text='Please input path to CSV').pack(side='left')
        self.pathEntry = tk.Entry(self, width=50)
        self.pathEntry.pack(side='left')
        self.addButton = tk.Button(self, text='Read CSV', width=8)
        self.addButton.pack(side='left')
        self.path = tk.StringVar()
        self.finalPathEntry = tk.Entry(self, width = 30, textvariable = self.path)
        self.finalPathEntry.pack(side='left')

    def setPath(self, value):
        self.path.set(str(value))

class Controller:
    def __init__(self, root):
        self.model = Model()
        self.model.csvPath.addCallback(self.pathChanged)
        self.view1 = View(root)
        self.view1.minsize(width = 500, height = 500)
        self.view1.addButton.config(command = self.addPath)
        self.pathChanged(self.model.csvPath.get())

    def addPath(self):
        self.model.addPath(self.view1.pathEntry.get())

    def pathChanged(self, val):
        self.view1.setPath(val)

if __name__ == '__main__':
    root = tk.Tk()
    root.withdraw()
    app = Controller(root)
    root.mainloop()

Body:
One thing about this code seems obvious: The functions beginning at

def addcallback(self, func):

until

def unset(self):

are not part of the Observable class. So the "self" argument is not what you expect it to be. You should indent these functions.


问:
Div with the heigh of 100% extends beyond the visible area of the page
Seems to be a very basic concept but I do not understand why when I set the div's height to 100% it extends beyond the visible area of the page. My page is like this:

<!DOCTYPE html>

```

When I open it in the browser, the browser adds a vertical scroller to the page and my div extends beyond the bottom:

If I scroll down a little, I do see the bottom of the div:

But why does my div with the height of 100% extends beyond the bottom of the page?

答:
That's because there is a default margin on the body when using code snippets on SO. I don't know if your problem is with code snippets only, but generally speaking, you probably have some margin (or padding or similar) around some element, which pushes the div down.

body {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en-US" style="height: 100%;">

<head></head>

<body style="height: 100%;">
  <div style="height: 100%; background-color: red"> </div>
</body>

</html></code>```

Body:
Seems to be a very basic concept but I do not understand why when I set the div's height to 100% it extends beyond the visible area of the page. My page is like this:

<!DOCTYPE html>

When I open it in the browser, the browser adds a vertical scroller to the page and my div extends beyond the bottom:

If I scroll down a little, I do see the bottom of the div:

But why does my div with the height of 100% extends beyond the bottom of the page?

Body:
That's because there is a default margin on the body when using code snippets on SO. I don't know if your problem is with code snippets only, but generally speaking, you probably have some margin (or padding or similar) around some element, which pushes the div down.

body {
  margin: 0;
}

<!DOCTYPE html>
<html lang="en-US" style="height: 100%;">

<head></head>

<body style="height: 100%;">
  <div style="height: 100%; background-color: red">&nbsp;</div>
</body>

</html>


问:
React: How to use same component twice in same page but loading one script tag for both just one time
I created a react component that I want to use twice(or more) inside my page, and I need to load a script tag for it inside the head of my page but just once! I mean even if I use the component twice or more in the page it should add the script tag just once in the head.
The Problem is that this script tag should be absolutely a part of the component and not statically inserted in the head of my page.

Can anyone help me to make the magic happens? Thanks a lot in advance!

答:
You can give react-helmet a try for managing changes to your  from within React components.

In particular, you can check this example where rendering the same element four times only adds the script tag once.

For completeness, the relevant code from the example (although the interesting part is to see how it executes):

```<code>import { Helmet } from "react-helmet";

function ComponentWithHeader() {
  return (
    <div>
      <div>Oh hi</div>
      <Helmet>
        <script src="fake-url.js" />
      </Helmet>
    </div>
  );
}

const App = () => (
  <div>
    <ComponentWithHeader />
    <ComponentWithHeader />
    <ComponentWithHeader />
    <ComponentWithHeader />
  </div>
);
</code>```

Body:
You can give react-helmet a try for managing changes to your <head> from within React components.

In particular, you can check this example where rendering the same element four times only adds the script tag once.

For completeness, the relevant code from the example (although the interesting part is to see how it executes):

import { Helmet } from "react-helmet";

function ComponentWithHeader() {
  return (
    <div>
      <div>Oh hi</div>
      <Helmet>
        <script src="fake-url.js" />
      </Helmet>
    </div>
  );
}

const App = () => (
  <div>
    <ComponentWithHeader />
    <ComponentWithHeader />
    <ComponentWithHeader />
    <ComponentWithHeader />
  </div>
);


问:
Symfony 3 Validate embedded entities dynamically
I am writing several forms with symfony 3. My form is very like the given example in the symfony reference:

http://symfony.com/doc/current/reference/constraints/Valid.html
I also have an user and an embedded address-entity. My configuration is done via yml:

PARENT User:

```<code>// src/Entity/User.php
namespace App\Entity;

class User
{
    protected $firstName;
    protected $lastName;
    protected $address;

    protected $mailOptIn;
}
</code>```

CHILD Address:

```<code>// src/Entity/Address.php
namespace App\Entity;

class Address
{
    protected $street;
    protected $zipCode;
}
</code>```

YML:

```<code># config/validator/validation.yaml
App\Entity\Address:
    properties:
        street:
            - NotBlank:  { groups: [group01, group02] }
        zipCode:
            - NotBlank:  { groups: [group01, group02] }
            - Length: { min: 3, groups: [group01, group02] }

App\Entity\User:
    properties:
        firstName:
            - NotBlank: ~
            - Length:
                min: 4
        lastName:
            - NotBlank: ~
        address:
            - Valid: { groups: [group01, group02] }
</code>```

BUT in some cases (depending on other fields in the parent-user-entity) it is
not necessary to validate the embedded address-entity.

Now I've read a lot about callback and getter-validators, but my problem is, that I do not know, how to handle this. Another part which makes the case even more complex for me is, that i need to use validation-groups (https://symfony.com/doc/current/form/validation_groups.html ) in the address entity, due to the fact, that i validate about 20 countries, where each of them has its own validation fields.

Can anybody give me hint, how to go on? The address-validation with the groups works perfectly, i think i just need to implement some cool magic stuff in the parent-user-entity, right?

UPDATE:

I just added TWO things:

in class USER -> protected $mailOptIn

in YML-User -> address: -Valid: { groups: [group01, group02] }

The validation with the valid-key works.

What I want to implement now is, that the address-validation is only done, if the user has set mailOptIn to true, because only in that case, I need the address.
Please note, that i do need groups for the address-validation, depending on what country the given address is placed.

答:
The documentation might not be so clear in this case, but you have to add the Valid: ~ key on it, like:

```<code>App\Entity\User:
properties:
    firstName:
        - NotBlank: ~
        - Length:
            min: 4
    lastName:
        - NotBlank: ~
    address:
        - Valid: ~
</code>```

Body:
I am writing several forms with symfony 3. My form is very like the given example in the symfony reference:

http://symfony.com/doc/current/reference/constraints/Valid.html
I also have an user and an embedded address-entity. My configuration is done via yml:

PARENT User:

// src/Entity/User.php
namespace App\Entity;

class User
{
    protected $firstName;
    protected $lastName;
    protected $address;

    protected $mailOptIn;
}

CHILD Address:

// src/Entity/Address.php
namespace App\Entity;

class Address
{
    protected $street;
    protected $zipCode;
}

YML:

# config/validator/validation.yaml
App\Entity\Address:
    properties:
        street:
            - NotBlank:  { groups: [group01, group02] }
        zipCode:
            - NotBlank:  { groups: [group01, group02] }
            - Length: { min: 3, groups: [group01, group02] }

App\Entity\User:
    properties:
        firstName:
            - NotBlank: ~
            - Length:
                min: 4
        lastName:
            - NotBlank: ~
        address:
            - Valid: { groups: [group01, group02] }

BUT in some cases (depending on other fields in the parent-user-entity) it is
not necessary to validate the embedded address-entity.

Now I've read a lot about callback and getter-validators, but my problem is, that I do not know, how to handle this. Another part which makes the case even more complex for me is, that i need to use validation-groups (https://symfony.com/doc/current/form/validation_groups.html ) in the address entity, due to the fact, that i validate about 20 countries, where each of them has its own validation fields.

Can anybody give me hint, how to go on? The address-validation with the groups works perfectly, i think i just need to implement some cool magic stuff in the parent-user-entity, right?

UPDATE:

I just added TWO things:

in class USER -> protected $mailOptIn

in YML-User -> address: -Valid: { groups: [group01, group02] }

The validation with the valid-key works.

What I want to implement now is, that the address-validation is only done, if the user has set mailOptIn to true, because only in that case, I need the address.
Please note, that i do need groups for the address-validation, depending on what country the given address is placed.

Body:
The documentation might not be so clear in this case, but you have to add the Valid: ~ key on it, like:

App\Entity\User:
properties:
    firstName:
        - NotBlank: ~
        - Length:
            min: 4
    lastName:
        - NotBlank: ~
    address:
        - Valid: ~


问:
Remove ™ ® using xslt
HI I have a scenario where I need to remove special characters as well as Latin Characters. I was able to strip out Latin and few special characters. But for some reason, ™ is getting converted to TM. How do I remove that using xslt? Here is my code and function

```<code> <Last_Name xtt:fixedLength="30" xtt:required="true" xtt:severity="error" xtt:align="left"><xsl:value-of select="lancet:stripSpecialChars(replace(normalize-unicode(translate(wd:Last_Name, ',', ''), 'NFKD'), '⁄', '/'))"/></Last_Name>
</code>```

function

```<code><xsl:function name="lancet:stripSpecialChars">
<xsl:param name="string" />
<xsl:variable name="AllowedSymbols" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789()*%$#@!~<>™,.?[]=- +   /\ '"/>
<xsl:value-of select="replace(normalize-unicode($string, 'NFKD'), '\P{IsBasicLatin}', '')"/>
</code>```

What am I expecting?

INPUT: DEâ€™ERIKA

OUTPUT: (Right Now with my code) -> DEATMERIKA

EXPECTED OUTPUT: DEAERIKA (My code is eliminating Latin characters and few symbols)

答:
You're seeing these characters because you are using the incorrect code page somewhere: the input XML is encoded as UTF-8 but the display system assumes ASCII instead. The solution is to perform a conversion or to make the display applcation use UTF-8.

Do not delete the â€™ characters! If a user enters e.g. a letter with an accent (ï) that is not present in the ASCII code page, the system will render something like â€™.

Specifically, â€™ is a right single quote. So the user input was:

DE'ERIKA (which is a valid name in many languages).

Rendering this as DEERIKA or (worse) DEATMERIKA is incorrect!

If you remove these characters, you're deleting part of the input. That's like proposing to change your name to "Gop Nadu" because your system can't render the 'i'.

Related question that explains what happens

Title: Remove ™ ® using xslt

Body:
HI I have a scenario where I need to remove special characters as well as Latin Characters. I was able to strip out Latin and few special characters. But for some reason, ™ is getting converted to TM. How do I remove that using xslt? Here is my code and function

 <Last_Name xtt:fixedLength="30" xtt:required="true" xtt:severity="error" xtt:align="left"><xsl:value-of select="lancet:stripSpecialChars(replace(normalize-unicode(translate(wd:Last_Name, ',', ''), 'NFKD'), '⁄', '/'))"/></Last_Name>

function

<xsl:function name="lancet:stripSpecialChars">
<xsl:param name="string" />
<xsl:variable name="AllowedSymbols" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789()*%$#@!~<>™,.?[]=- +   /\ '"/>
<xsl:value-of select="replace(normalize-unicode($string, 'NFKD'), '\P{IsBasicLatin}', '')"/>

What am I expecting?

INPUT: DEâ€™ERIKA

OUTPUT: (Right Now with my code) -> DEATMERIKA

EXPECTED OUTPUT: DEAERIKA (My code is eliminating Latin characters and few symbols)


问:
Unit test succeeds in debug mode but fails when running it normally
Why does my unit test succeed in debug mode but fail when running it normally?</p>

```<code>public class ExecutorServiceTest extends MockitoTestCase{
  private int numThreads;
  private ExecutorService pool;
  private volatile boolean interruptedBitSet;

  @Override
  public void setUp() {
    numThreads = 5;
    pool = Executors.newFixedThreadPool(numThreads);
  }

class TaskChecksForInterruptedBit implements Callable<String> {
    @Override
    public String call() throws Exception {
      interruptedBitSet = false;
      while (!Thread.currentThread().isInterrupted()) {
      }
      interruptedBitSet = Thread.currentThread().isInterrupted();
      return "blah";
    }
  }

public void testCancelSetsInterruptedBitInCallable() throws Exception {
    interruptedBitSet = false;
    final Future<String> future =
        pool.submit(new TaskChecksForInterruptedBit());
    final boolean wasJustCancelled = future.cancel(true);
    assertTrue(wasJustCancelled);

    // Give time for the thread to notice the interrupted bit and set the flag
    Thread.sleep(5000);

    // This succeeds when stepping through w/ a debugger, but fails when running
    // the test straight. WHY?
    assertTrue(interruptedBitSet);

    assertTrue(future.isDone());
    assertTrue(future.isCancelled());
  }
}
</code>```

答: I was having a similar issue while running a homework assignment from an online course. The grader program from the course which I added to the build path used JUnit4, my version of Eclipse added JUnit5 to any new test cases. I've created a new Java Project and added JUnit5 to the build bath for my test cases without the grader and it fixed it for me. Hope this helps.</p>

Body:
Why does my unit test succeed in debug mode but fail when running it normally?

public class ExecutorServiceTest extends MockitoTestCase{
  private int numThreads;
  private ExecutorService pool;
  private volatile boolean interruptedBitSet;

  @Override
  public void setUp() {
    numThreads = 5;
    pool = Executors.newFixedThreadPool(numThreads);
  }

class TaskChecksForInterruptedBit implements Callable<String> {
    @Override
    public String call() throws Exception {
      interruptedBitSet = false;
      while (!Thread.currentThread().isInterrupted()) {
      }
      interruptedBitSet = Thread.currentThread().isInterrupted();
      return "blah";
    }
  }

public void testCancelSetsInterruptedBitInCallable() throws Exception {
    interruptedBitSet = false;
    final Future<String> future =
        pool.submit(new TaskChecksForInterruptedBit());
    final boolean wasJustCancelled = future.cancel(true);
    assertTrue(wasJustCancelled);

    // Give time for the thread to notice the interrupted bit and set the flag
    Thread.sleep(5000);

    // This succeeds when stepping through w/ a debugger, but fails when running
    // the test straight. WHY?
    assertTrue(interruptedBitSet);

    assertTrue(future.isDone());
    assertTrue(future.isCancelled());
  }
}


问:
MVC4: Two radio buttons for a single boolean model property
I'm attempting to find the correct Razor syntax for mutually exclusive radio buttons that both reflect the value of a boolean property on my model.  My model has this:

```<code>public bool IsFemale{ get; set; }
</code>```

I would like to display this with two radio buttons, one "Male" and the other "Female," but everything I've tried so far has not reflected the actual value of the IsFemale property on the model.  Currently, I have this:

```<code>@Html.RadioButtonFor(model => model.IsFemale, !Model.IsFemale) Male
@Html.RadioButtonFor(model => model.IsFemale, Model.IsFemale) Female
</code>```

This seems to persist the value correctly if I change and update, but does not mark the correct value as checked.  I'm sure this is something stupid, but I'm stuck.

答:
In MVC 6 (ASP.NET Core) this can also be achieved with tag helpers:</p>

```<code><label>
    <input type="radio" asp-for="IsFemale" value="false" /> Male
</label>
<label>
    <input type="radio" asp-for="IsFemale" value="true" /> Female
</label>
</code>```

Body:
I'm attempting to find the correct Razor syntax for mutually exclusive radio buttons that both reflect the value of a boolean property on my model.  My model has this:

public bool IsFemale{ get; set; }

I would like to display this with two radio buttons, one "Male" and the other "Female," but everything I've tried so far has not reflected the actual value of the IsFemale property on the model.  Currently, I have this:

@Html.RadioButtonFor(model => model.IsFemale, !Model.IsFemale) Male
@Html.RadioButtonFor(model => model.IsFemale, Model.IsFemale) Female

This seems to persist the value correctly if I change and update, but does not mark the correct value as checked.  I'm sure this is something stupid, but I'm stuck.

Body:
In MVC 6 (ASP.NET Core) this can also be achieved with tag helpers:

<label>
    <input type="radio" asp-for="IsFemale" value="false" /> Male
</label>
<label>
    <input type="radio" asp-for="IsFemale" value="true" /> Female
</label>


问:
Input in thymeleaf, different value and label
I'm quite new to the Thymeleaf and came across some problem that I cannot resolve by myself. I'm creating a view where user will be able to fill the survey, answer to some questions which can be closed (only A,B, C, D allowed) or open (user inputs his own text). I came to the idea that passing letters A, B, C or D as answers (instead of long strings) will be quicker and better for me and sadly I have no idea how to achieve it using inputs in forms  and thymeleaf. For example, this is question :
which one is better?
(radio box) answer first,
(radio box) answer second,
(radio box) answer third,
(radio box) answer fourth

All I want to achieve is when user picks for example answer first we will get as a value 'A' instead of whole label.

答:
Radio buttons already work as you've described.  The value is what is saved to the database and the  can have whatever text you want (unrelated to the value).

```<code><label><input name="question1" type="radio" value="A" /> answer first</label>
<label><input name="question1" type="radio" value="B" /> answer second</label>
<label><input name="question1" type="radio" value="C" /> answer third</label>
<label><input name="question1" type="radio" value="D" /> answer fourth</label>
</code>```

Body:
Radio buttons already work as you've described.  The value is what is saved to the database and the <label> can have whatever text you want (unrelated to the value).

<label><input name="question1" type="radio" value="A" /> answer first</label>
<label><input name="question1" type="radio" value="B" /> answer second</label>
<label><input name="question1" type="radio" value="C" /> answer third</label>
<label><input name="question1" type="radio" value="D" /> answer fourth</label>


问:
MySQL Update Query?
As my project gathers pace I have noticed that some users are inputting Aircraft Models incorrectly - (field is "model") for instance as -

737-8AS
737-8k3
757-222
etc

What I want to do via a query is to run through these and add a leading "B", for instance the above would be changed to:

B737-8AS
B737-8k3
B757-222

What I have in my daily update script is -

/* Set Boeings */
UPDATEspottingSETmodel='B707-%' WHEREmodelLIKE '707-%';
UPDATEspottingSETmodel='B717-%' WHEREmodelLIKE '717-%';
UPDATEspottingSETmodel='B727-%' WHEREmodelLIKE '727-%';
UPDATEspottingSETmodel='B737-%' WHEREmodelLIKE '737-%';
UPDATEspottingSETmodel='B747-%' WHEREmodelLIKE '747-%';
UPDATEspottingSETmodel='B757-%' WHEREmodelLIKE '757-%';
UPDATEspottingSETmodel='B767-%' WHEREmodelLIKE '767-%';
UPDATEspottingSETmodel='B777-%' WHEREmodelLIKE '777-%';
UPDATEspottingSETmodel='B787-%' WHEREmodelLIKE '787-%';

This does edit the data to give the leading "B" but it then drops everything after the B737-

where "737-8AS/W" becomes "B737-" where it should be "B737-8AS/W"

I am guessing this is something simple I am missing.

答:
% is just a wild-card character; the update statement doesn't 'know' what the wildcard matched in the where clause. You'll want to include the actual current value in the update statement, something like:</p>

```<code>UPDATE spotting SET model = CONCAT('B',model) WHERE model LIKE '707-%';
</code>```

ContentLicense: CC BY-SA 4.0

Title: MySQL Update Query?

Body:
% is just a wild-card character; the update statement doesn't 'know' what the wildcard matched in the where clause. You'll want to include the actual current value in the update statement, something like:

UPDATE spotting SET model = CONCAT('B',model) WHERE model LIKE '707-%';


问:
Convert 2D Shape to 1D Space (Shape Classification. )
I'm looking for a example of code/library using Python to convert a 2D shape to 1D space based on following steps:

Find the centroid of the shape.

By choosing the centroid as a reference origin, unwrap the outer contour counterclockwise to turn it into a distance signal that is composed of all between each boundary pixel and the centroid (like the image)

Thank you!

答:
I did something like this a while back for fun, inspired by a Kaggle competition on leaf classification. I used opencv for finding the contours of the images. Below is the code for python 2.7. See here for the orientation of the returned contour. You may have to adapt it for your needs, specifically the thresholding part. Hope this helps.

```<code>import cv2
import numpy as np
import matplotlib.pyplot as plt

def shape_desc(im):
    # threshold image
    _, bw = cv2.threshold(im, 128, 255, cv2.THRESH_BINARY)
    # find contours
    contours, hierarchy = cv2.findContours(im.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    # extract largest contour
    largest_idx = np.argmax([len(contours[i]) for i in range(0, len(contours))])
    # get (x,y) coordinates
    x = np.array([contours[largest_idx][i][0][0] for i in range(0, len(contours[largest_idx]))], dtype = np.float).reshape((len(contours[largest_idx]), 1))
    y = np.array([contours[largest_idx][i][0][1] for i in range(0, len(contours[largest_idx]))], dtype = np.float).reshape((len(contours[largest_idx]), 1))
    # find the centroid
    m = cv2.moments(np.array([[x[i][0], y[i][0]] for i in range(0, len(x))]).reshape((-1, 1 ,2)).astype(np.int32))
    x_bar = m['m10']/m['m00']
    y_bar = m['m01']/m['m00']

    x_1 = np.array([i[0] for i in x])
    y_1 = np.array([i[0] for i in y])
    # take the centroid as the reference
    x = x_1 - x_bar
    y = y_1 - y_bar

    return np.sqrt(x*x + y*y)
</code>```

Here are the results of applying this for the following images that are similar in shape. Note that the images and plots have been rescaled.

```<code>filename = '19.jpg'
im = cv2.imread(filename, 0)

desc = shape_desc(im)
plt.stem(desc)
</code>```

Body:
I did something like this a while back for fun, inspired by a Kaggle competition on leaf classification. I used opencv for finding the contours of the images. Below is the code for python 2.7. See here for the orientation of the returned contour. You may have to adapt it for your needs, specifically the thresholding part. Hope this helps.

import cv2
import numpy as np
import matplotlib.pyplot as plt

def shape_desc(im):
    # threshold image
    _, bw = cv2.threshold(im, 128, 255, cv2.THRESH_BINARY)
    # find contours
    contours, hierarchy = cv2.findContours(im.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    # extract largest contour
    largest_idx = np.argmax([len(contours[i]) for i in range(0, len(contours))])
    # get (x,y) coordinates
    x = np.array([contours[largest_idx][i][0][0] for i in range(0, len(contours[largest_idx]))], dtype = np.float).reshape((len(contours[largest_idx]), 1))
    y = np.array([contours[largest_idx][i][0][1] for i in range(0, len(contours[largest_idx]))], dtype = np.float).reshape((len(contours[largest_idx]), 1))
    # find the centroid
    m = cv2.moments(np.array([[x[i][0], y[i][0]] for i in range(0, len(x))]).reshape((-1, 1 ,2)).astype(np.int32))
    x_bar = m['m10']/m['m00']
    y_bar = m['m01']/m['m00']

    x_1 = np.array([i[0] for i in x])
    y_1 = np.array([i[0] for i in y])
    # take the centroid as the reference
    x = x_1 - x_bar
    y = y_1 - y_bar

    return np.sqrt(x*x + y*y)

Here are the results of applying this for the following images that are similar in shape. Note that the images and plots have been rescaled.

filename = '19.jpg'
im = cv2.imread(filename, 0)

desc = shape_desc(im)
plt.stem(desc)


问:
Draggable left side of screen (JQuery)
I'm wondering if someone can help me work out the offset of left side of the screen. I've currently got the right side done and you can see the example below. However I want the same for left side with the text saying "Not Interested".

Could someone please point me in the right direction or help me out achieve this?

Also if anyone wants to give feedback on my current code, if they have any better way of doing this.

$(document).ready(function(){
    var currentDiff;
    var currentOpacity;

    $("#event_container .content .card").draggable({
        drag: function(el, ui){
            var cardWidth = $(this).width();
            var bodyWidth = $("body");
            var rightOverlay = $(this).offset().left + (cardWidth * .6);
            var leftOverlay = ($(this).offset().left - cardWidth) / 6;
            if(rightOverlay > cardWidth){
                var widthDiff = rightOverlay - cardWidth;

                if(!$("#interested-message").is(":visible")){
                    currentDiff = 0;
                    currentOpacity = 0;
                }
                if(widthDiff > 175){
                   if(currentDiff === 0){
                       currentOpacity = 0.1;
                       $("#interested-message").addClass("interested").css("opacity", currentOpacity).text("Interested").show();
                       currentDiff = widthDiff;
                   } else if((currentDiff + 20) > currentDiff) {
                       if(currentOpacity !== 1){
                           currentOpacity = currentOpacity + 0.1;
                           $("#interested-message").addClass("interested").css("opacity", currentOpacity);
                            currentDiff = widthDiff;
                       }
                   }
                } else {
                    $("#interested-message").css("opacity", 0).hide().text("....");
                }
            } else {
                $("#interested-message").css("opacity", 0).hide().text("....");
            }

            if(leftOverlay > cardWidth){
                var widthDiff = leftOverlay - cardWidth;
                console.log(widthDiff);
            } else {
                console.log(leftOverlay);
            }
        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#interested-message{
    display: none;
    position: absolute;
    width: auto;
    padding: 5px 15px!important;
    z-index: 100;
    border-radius: 6px;
    font-size: 30px;
    top: calc(45% - 100px);
    left: calc(25% - 100px);
    opacity: 0;
}
#interested-message.interested{
    display: block;
    border: 2px solid #0b9c1e;
    color: #0b9c1e;
}
#interested-message.not-interested{
    display: block;
    border: 2px solid #d93838;
    color: #d93838;
}

#body{
  width: 250px;
  height: 600px;
  max-width: 250px;
  max-height: 600px;
  border: 2px solid black;
  overflow: hidden;
}

#event_container{
  height: 100%;
  width: 100%;
  background: lightblue;
  padding: 50px;
}

#event_container .content{
  position: relative;
}
#event_container .content .card{
  border: 2px solid black;
}</code>```

....

          Test card

```

答:
If anyone is interested, I've come up with the answer myself. I've also re wrote some of my code and enhanced it to look a little neater.

the -230 in if(widthDiff < -230) could be dynamically added, and also the 105 in if(widthDiff > 105). I've not added this for the example.

Complete version:

$(document).ready(function(){
    var currentDiff;
    var currentOpacity;
    var interested = false;
    var notInterested = false;
    $("#event_container .content .card").each(function(){
        $(this).draggable({
            drag: function(el, ui){
                var cardWidth = $(this).width();
                var rightOverlay = $(this).offset().left + (cardWidth * .6);
                var widthDiff = rightOverlay - cardWidth;
                if(widthDiff < -230){
                    notInterested($(this));
                } else if(widthDiff > 105){
                    interested($(this));
                } else {
                    reset($(this));
                }
                function notInterested(ele){
                    $("#interested-message").addClass("not-interested").text("Not Interested").show();
                    ele.draggable( "option", "revert", false);
                    notInterested = true;
                }
                function interested(ele){
                    $("#interested-message").addClass("interested").text("Interested").show();
                    ele.draggable( "option", "revert", false);
                    interested = true;
                }
                function reset(ele){
                    $("#interested-message").removeClass("interested").removeClass("not-interested").hide().text("....");
                    ele.draggable( "option", "revert", true);
                    interested = false;
                    notInterested = false;
                }
            }
        });
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#interested-message{
    display: none;
    position: absolute;
    width: auto;
    padding: 5px 15px!important;
    z-index: 100;
    border-radius: 6px;
    font-size: 30px;
    top: calc(45% - 100px);
    left: calc(30% - 100px);
}
#interested-message.interested{
    display: block;
    border: 2px solid #0b9c1e;
    color: #0b9c1e;
}
#interested-message.not-interested{
    display: block;
    border: 2px solid #d93838;
    color: #d93838;
}

#body{
  width: 250px;
  height: 600px;
  max-width: 250px;
  max-height: 600px;
  border: 2px solid black;
  overflow: hidden;
  margin-left: 50px;
}

#event_container{
  height: 100%;
  width: 100%;
  background: lightblue;
  padding: 50px;
}

#event_container .content{
  position: relative;
}
#event_container .content .card{
  border: 2px solid black;
}</code>```

....

          Test card

```

Title: Draggable left side of screen (JQuery)

Body:
I'm wondering if someone can help me work out the offset of left side of the screen. I've currently got the right side done and you can see the example below. However I want the same for left side with the text saying "Not Interested".

Could someone please point me in the right direction or help me out achieve this?

Also if anyone wants to give feedback on my current code, if they have any better way of doing this.

$(document).ready(function(){
    var currentDiff;
    var currentOpacity;

    $("#event_container .content .card").draggable({
        drag: function(el, ui){
            var cardWidth = $(this).width();
            var bodyWidth = $("body");
            var rightOverlay = $(this).offset().left + (cardWidth * .6);
            var leftOverlay = ($(this).offset().left - cardWidth) / 6;
            if(rightOverlay > cardWidth){
                var widthDiff = rightOverlay - cardWidth;

                if(!$("#interested-message").is(":visible")){
                    currentDiff = 0;
                    currentOpacity = 0;
                }
                if(widthDiff > 175){
                   if(currentDiff === 0){
                       currentOpacity = 0.1;
                       $("#interested-message").addClass("interested").css("opacity", currentOpacity).text("Interested").show();
                       currentDiff = widthDiff;
                   } else if((currentDiff + 20) > currentDiff) {
                       if(currentOpacity !== 1){
                           currentOpacity = currentOpacity + 0.1;
                           $("#interested-message").addClass("interested").css("opacity", currentOpacity);
                            currentDiff = widthDiff;
                       }
                   }
                } else {
                    $("#interested-message").css("opacity", 0).hide().text("....");
                }
            } else {
                $("#interested-message").css("opacity", 0).hide().text("....");
            }

            if(leftOverlay > cardWidth){
                var widthDiff = leftOverlay - cardWidth;
                console.log(widthDiff);
            } else {
                console.log(leftOverlay);
            }
        }
    });
});

#interested-message{
    display: none;
    position: absolute;
    width: auto;
    padding: 5px 15px!important;
    z-index: 100;
    border-radius: 6px;
    font-size: 30px;
    top: calc(45% - 100px);
    left: calc(25% - 100px);
    opacity: 0;
}
#interested-message.interested{
    display: block;
    border: 2px solid #0b9c1e;
    color: #0b9c1e;
}
#interested-message.not-interested{
    display: block;
    border: 2px solid #d93838;
    color: #d93838;
}

#body{
  width: 250px;
  height: 600px;
  max-width: 250px;
  max-height: 600px;
  border: 2px solid black;
  overflow: hidden;
}

#event_container{
  height: 100%;
  width: 100%;
  background: lightblue;
  padding: 50px;
}

#event_container .content{
  position: relative;
}
#event_container .content .card{
  border: 2px solid black;
}

....

          Test card

Body:
If anyone is interested, I've come up with the answer myself. I've also re wrote some of my code and enhanced it to look a little neater.

the -230 in if(widthDiff < -230) could be dynamically added, and also the 105 in if(widthDiff > 105). I've not added this for the example.

Complete version:

$(document).ready(function(){
    var currentDiff;
    var currentOpacity;
    var interested = false;
    var notInterested = false;
    $("#event_container .content .card").each(function(){
        $(this).draggable({
            drag: function(el, ui){
                var cardWidth = $(this).width();
                var rightOverlay = $(this).offset().left + (cardWidth * .6);
                var widthDiff = rightOverlay - cardWidth;
                if(widthDiff < -230){
                    notInterested($(this));
                } else if(widthDiff > 105){
                    interested($(this));
                } else {
                    reset($(this));
                }
                function notInterested(ele){
                    $("#interested-message").addClass("not-interested").text("Not Interested").show();
                    ele.draggable( "option", "revert", false);
                    notInterested = true;
                }
                function interested(ele){
                    $("#interested-message").addClass("interested").text("Interested").show();
                    ele.draggable( "option", "revert", false);
                    interested = true;
                }
                function reset(ele){
                    $("#interested-message").removeClass("interested").removeClass("not-interested").hide().text("....");
                    ele.draggable( "option", "revert", true);
                    interested = false;
                    notInterested = false;
                }
            }
        });
    });
});

#interested-message{
    display: none;
    position: absolute;
    width: auto;
    padding: 5px 15px!important;
    z-index: 100;
    border-radius: 6px;
    font-size: 30px;
    top: calc(45% - 100px);
    left: calc(30% - 100px);
}
#interested-message.interested{
    display: block;
    border: 2px solid #0b9c1e;
    color: #0b9c1e;
}
#interested-message.not-interested{
    display: block;
    border: 2px solid #d93838;
    color: #d93838;
}

#body{
  width: 250px;
  height: 600px;
  max-width: 250px;
  max-height: 600px;
  border: 2px solid black;
  overflow: hidden;
  margin-left: 50px;
}

#event_container{
  height: 100%;
  width: 100%;
  background: lightblue;
  padding: 50px;
}

#event_container .content{
  position: relative;
}
#event_container .content .card{
  border: 2px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="body">

<div id="event_container">
    <div id="interested-message">....</div>
    <div class="content">

        <div class="card">

          Test card

        </div>
    </div>
</div>

</div>


问:
How to add data attributes to
 elements and then access it from CSS?
Is it possible to add some data attributes to a
 element and then access them from CSS?

For instance, I've tried

```<code>figure { margin: 0 attr(data-margin %); }
</code>```

with

```<code><figure data-margin="15">...</figure>
</code>```

but it doesn't work.

Is there another way without using JS?

EDIT: I don't think my question is a duplicate. In fact, I'm looking for an alternative way to do this.

My goal is to decorate some elements in a page with attributes that then the end user can access and make use of by writing some CSS code.
If that's impossible, I'll just ask them to write JS code, but that would be less safe, I think.

(The end users are ML researchers. I'm sure they can handle some CSS or JS code.)

答:
You can do it:

.test {
    display: inline-block;
    background-color: gray;
    width: attr(data-width px);
}

.test:after {
    content: attr(data-name);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='test' data-name=" - CONTENT" data-width="200">teste</div></code>```

but it does not work in Chrome: https://developer.mozilla.org/en-US/docs/Web/CSS/attr

Title: How to add data attributes to <figure> elements and then access it from CSS?

Body:
Is it possible to add some data attributes to a
 element and then access them from CSS?

For instance, I've tried

figure { margin: 0 attr(data-margin %); }

with

...

but it doesn't work.

Is there another way without using JS?

EDIT: I don't think my question is a duplicate. In fact, I'm looking for an alternative way to do this.

My goal is to decorate some elements in a page with attributes that then the end user can access and make use of by writing some CSS code.
If that's impossible, I'll just ask them to write JS code, but that would be less safe, I think.

(The end users are ML researchers. I'm sure they can handle some CSS or JS code.)

Body:
You can do it:

.test {
    display: inline-block;
    background-color: gray;
    width: attr(data-width px);
}

.test:after {
    content: attr(data-name);
}

<div class='test' data-name=" - CONTENT" data-width="200">teste</div>

but it does not work in Chrome: https://developer.mozilla.org/en-US/docs/Web/CSS/attr


问:
Convert base64 String to an Image that's compatible with OpenCV
I'm trying to convert a base64 representation of a JPEG to an image that can be used with OpenCV. The catch is that I'd like to be able to do this without having to physically save the photo (I'd like it to remain in memory). Is there an updated way of accomplishing this?

I'm using python 3.6.2 and OpenCV 3.3

Here is a partial example of the type of input I'm trying to convert:

/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAA....

I've already tried the solutions provided by these questions, but keep getting the same "bad argument type for built-in operation" error:

Read a base 64 encoded image from memory using OpenCv python library

How to decode jpg image from memory?

Python: Alternate way to covert from base64 string to opencv

答:
Here an example for python 3.6 that uses imageio instead of PIL. It first loads an image and converts it to a b64_string. This string can then be sent around and the image reconstructed as follows:</p>

```<code>import base64
import io
import cv2
from imageio import imread
import matplotlib.pyplot as plt

filename = "yourfile.jpg"
with open(filename, "rb") as fid:
    data = fid.read()

b64_bytes = base64.b64encode(data)
b64_string = b64_bytes.decode()

# reconstruct image as an numpy array
img = imread(io.BytesIO(base64.b64decode(b64_string)))

# show image
plt.figure()
plt.imshow(img, cmap="gray")

# finally convert RGB image to BGR for opencv
# and save result
cv2_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
cv2.imwrite("reconstructed.jpg", cv2_img)
plt.show()
</code>```

Body:
Here an example for python 3.6 that uses imageio instead of PIL. It first loads an image and converts it to a b64_string. This string can then be sent around and the image reconstructed as follows:

import base64
import io
import cv2
from imageio import imread
import matplotlib.pyplot as plt

filename = "yourfile.jpg"
with open(filename, "rb") as fid:
    data = fid.read()

b64_bytes = base64.b64encode(data)
b64_string = b64_bytes.decode()

# reconstruct image as an numpy array
img = imread(io.BytesIO(base64.b64decode(b64_string)))

# show image
plt.figure()
plt.imshow(img, cmap="gray")

# finally convert RGB image to BGR for opencv
# and save result
cv2_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
cv2.imwrite("reconstructed.jpg", cv2_img)
plt.show()


问:
Performing ImageGrab on tkinter Screen

I am trying to save a tkinter screen to a file (to later convert into a video).

I can't get the correct position of the canvas for using ImageGrab.

My relevant imports are:

```<code>import tkinter
import pyscreenshot as ImageGrab
</code>```

I am trying to save the screen using (after drawing the screen):

```<code>grab = ImageGrab.grab(bbox=canvas.bbox())
ImageGrab.grab_to_file(fileName,grab)
</code>```

I don't know how to get the canvas position for using "ImageGrab.grab".

Is there any way to get the bounding box for the whole canvas, so as to later use ImageGrab to store a screenshot?

---Edit------------------------------------------------------------------

Solution:

```<code>box = (canvas.winfo_rootx(),canvas.winfo_rooty(),canvas.winfo_rootx()+canvas.winfo_width(),canvas.winfo_rooty() + canvas.winfo_height())
grab = ImageGrab.grab(bbox = box)
grab.save(file_path)
</code>```

答:
You have methods like winfo_x(), winfo_y() to get position inside parent widget (it doesn't have to be main window), and winfo_rootx(), winfo_rooty() to get position on screen.

Effbot.org: Basic Widget Methods

Code displays canvas' position on screen and inside parent Frame

```<code>import tkinter as tk

def callback():
    print('  root.geometry:', root.winfo_geometry())
    print('canvas.geometry:', canvas.winfo_geometry())
    print('canvas.width :', canvas.winfo_width())
    print('canvas.height:', canvas.winfo_height())
    print('canvas.x:', canvas.winfo_x())
    print('canvas.y:', canvas.winfo_y())
    print('canvas.rootx:', canvas.winfo_rootx())
    print('canvas.rooty:', canvas.winfo_rooty())

root = tk.Tk()

tk.Label(root, text='SOME WIDGETS IN ROOT').pack()

frame = tk.Frame(root)
frame.pack()

tk.Label(frame, text='SOME WIDGETS IN FRAME').pack()

canvas = tk.Canvas(frame, bg='green')
canvas.pack()

print('\n--- before mainloop start---\n')
callback()

print('\n--- after mainloop start ---\n')
root.after(100, callback)

root.mainloop()
</code>```

Example result

```<code>--- before mainloop start ---

  root.geometry: 1x1+0+0
canvas.geometry: 1x1+0+0
canvas.width : 1
canvas.height: 1
canvas.x: 0
canvas.y: 0
canvas.rootx: 0
canvas.rooty: 0

--- after mainloop start ---

  root.geometry: 380x303+770+462
canvas.geometry: 380x267+0+18
canvas.width : 380
canvas.height: 267
canvas.x: 0
canvas.y: 18
canvas.rootx: 770
canvas.rooty: 498
</code>```

Title: Performing ImageGrab on tkinter Screen

Body:
I am trying to save a tkinter screen to a file (to later convert into a video).

I can't get the correct position of the canvas for using ImageGrab.

My relevant imports are:

import tkinter
import pyscreenshot as ImageGrab

I am trying to save the screen using (after drawing the screen):

grab = ImageGrab.grab(bbox=canvas.bbox())
ImageGrab.grab_to_file(fileName,grab)

I don't know how to get the canvas position for using "ImageGrab.grab".

Is there any way to get the bounding box for the whole canvas, so as to later use ImageGrab to store a screenshot?

---Edit------------------------------------------------------------------

Solution:

box = (canvas.winfo_rootx(),canvas.winfo_rooty(),canvas.winfo_rootx()+canvas.winfo_width(),canvas.winfo_rooty() + canvas.winfo_height())
grab = ImageGrab.grab(bbox = box)
grab.save(file_path)

Body:
You have methods like winfo_x(), winfo_y() to get position inside parent widget (it doesn't have to be main window), and winfo_rootx(), winfo_rooty() to get position on screen.

Effbot.org: Basic Widget Methods

Code displays canvas' position on screen and inside parent Frame

import tkinter as tk

def callback():
    print('  root.geometry:', root.winfo_geometry())
    print('canvas.geometry:', canvas.winfo_geometry())
    print('canvas.width :', canvas.winfo_width())
    print('canvas.height:', canvas.winfo_height())
    print('canvas.x:', canvas.winfo_x())
    print('canvas.y:', canvas.winfo_y())
    print('canvas.rootx:', canvas.winfo_rootx())
    print('canvas.rooty:', canvas.winfo_rooty())

root = tk.Tk()

tk.Label(root, text='SOME WIDGETS IN ROOT').pack()

frame = tk.Frame(root)
frame.pack()

tk.Label(frame, text='SOME WIDGETS IN FRAME').pack()

canvas = tk.Canvas(frame, bg='green')
canvas.pack()

print('\n--- before mainloop start---\n')
callback()

print('\n--- after mainloop start ---\n')
root.after(100, callback)

root.mainloop()

Example result

--- before mainloop start ---

  root.geometry: 1x1+0+0
canvas.geometry: 1x1+0+0
canvas.width : 1
canvas.height: 1
canvas.x: 0
canvas.y: 0
canvas.rootx: 0
canvas.rooty: 0

--- after mainloop start ---

  root.geometry: 380x303+770+462
canvas.geometry: 380x267+0+18
canvas.width : 380
canvas.height: 267
canvas.x: 0
canvas.y: 18
canvas.rootx: 770
canvas.rooty: 498


问:
Changing type under lambda in Coq
I encountered a situation where setoid rewriting does not work because convertible types are not matched by the tactic. The workaround I came up with does not work under lambda. Looking for suggestions:

```<code>Require Import Setoid Morphisms Relations.

(* Sample definitions *)
Record S {i o: nat} : Type.
Definition C {i o: nat} (f: @S i o):  @S i o. Admitted.
Definition B {o:nat} (z:nat): @S (o+o) o. Admitted.

(* Relations *)
Parameter R: forall {i o}, relation (@S i o).
Instance R_proper {i o}: Proper (R ==> R ==> iff) (@R i o). Admitted.
Definition Rext {i o} := pointwise_relation nat (@R i o).

(* Sample rewriting lemma *)
Lemma Rewrite (x:nat): forall z, R (C (@B x z)) (B z). Admitted.

Ltac Type_Fix :=
  match goal with
  | [ |- context G [ (@C (Datatypes.S _) ?o (@B ?o ?z))] ] =>
    let G' := context G[(@C (o+o) o (@B o z))] in change G'
  end.

(* Simple case. Works with workaround *)
Theorem Foo (p:nat): R (@C 2 1 (@B 1 p)) (@C 2 1 (@B 1 p)).
Proof.
  Fail setoid_rewrite Rewrite.
  repeat Type_Fix.
  repeat setoid_rewrite Rewrite.
Admitted.

(* Now try under lambda. Does not work! *)
Theorem Bar (p:nat): Rext (fun z => @C 2 1 (@B 1 z)) (fun z => @C 2 1 (@B 1 z)).
Proof.
  Fail setoid_rewrite Rewrite.
  Fail Type_Fix.
Admitted.
</code>```

In both Foo and Bar direct application of setoid_rewrite fails. The problem is that type of C (B p) is @S 2 1 while our rewriting lemma expects @C (1+1) 1. In Foo I was able to fix this via LTAC. However, this fix does not work under lambda in Bar.

答:
Here are three solutions:

Flip the order of your arguments, to help setoid_rewrite pick up the right terms even though it's using left-to-right inference.

Your example becomes:

```<code>Require Import Coq.Setoids.Setoid Coq.Classes.Morphisms Coq.Relations.Relations.

(* Sample definitions *)
Record S {o i: nat} : Type.
Definition C {o i: nat} (f: @S o i):  @S o i. Admitted.
Definition B {o:nat} (z:nat): @S o (o+o). Admitted.

(* Relations *)
Parameter R: forall {o i}, relation (@S o i).
Definition Rext {o i} := pointwise_relation nat (@R o i).

(* Sample rewriting lemma *)
Lemma Rewrite (x:nat): forall z, R (C (@B x z)) (B z). Admitted.

Global Instance R_Proper {o i} : Proper (R ==> R ==> Basics.flip Basics.impl) (@R o i).
Proof.
Admitted.

(* Simple case. Works with workaround *)
Theorem Foo (p:nat): R (@C 1 2 (@B 1 p)) (@C 1 2 (@B 1 p)).
Proof.
  setoid_rewrite Rewrite.
Admitted.

Global Instance Rext_Proper {o i}
  : Proper
      ((pointwise_relation nat R)
         ==> (pointwise_relation nat R)
         ==> Basics.flip Basics.impl) (@Rext o i).
Proof.
Admitted.

(* Now try under lambda. Does not work! *)
Theorem Bar (p:nat): Rext (fun z => @C 1 2 (@B 1 z)) (fun z => @C 1 2 (@B 1 z)).
Proof.
  setoid_rewrite Rewrite.
Admitted.
</code>```

Make Type_Fix smarter.

You could do this instead:

```<code>Ltac Type_Fix :=
  progress
    repeat match goal with
           | [ |- context G [@C _ ?o] ]
             => progress let G' := context G[@C (o+o) o] in change G'
           end.
</code>```

This version only requires that the o argument to C not be a binder, and allows the f argument to be a binder.  I've replaced Datatypes.S _ with _ and used progress to ensure that we find places where it makes sense to change; this makes the tactic more general and allows it to fix other representations as well (for example, @C 0 0).

Use match to fill in the relevant argument to Rewrite.

You could replace setoid_rewrite Rewrite with something like

```<code>  match goal with
  | [ |- context[C (@B ?x _)] ]
    => setoid_rewrite (Rewrite x)
  end.
</code>```

Title: Changing type under lambda in Coq

Body:
I encountered a situation where setoid rewriting does not work because convertible types are not matched by the tactic. The workaround I came up with does not work under lambda. Looking for suggestions:

Require Import Setoid Morphisms Relations.

(* Sample definitions *)
Record S {i o: nat} : Type.
Definition C {i o: nat} (f: @S i o):  @S i o. Admitted.
Definition B {o:nat} (z:nat): @S (o+o) o. Admitted.

(* Relations *)
Parameter R: forall {i o}, relation (@S i o).
Instance R_proper {i o}: Proper (R ==> R ==> iff) (@R i o). Admitted.
Definition Rext {i o} := pointwise_relation nat (@R i o).

(* Sample rewriting lemma *)
Lemma Rewrite (x:nat): forall z, R (C (@B x z)) (B z). Admitted.

Ltac Type_Fix :=
  match goal with
  | [ |- context G [ (@C (Datatypes.S _) ?o (@B ?o ?z))] ] =>
    let G' := context G[(@C (o+o) o (@B o z))] in change G'
  end.

(* Simple case. Works with workaround *)
Theorem Foo (p:nat): R (@C 2 1 (@B 1 p)) (@C 2 1 (@B 1 p)).
Proof.
  Fail setoid_rewrite Rewrite.
  repeat Type_Fix.
  repeat setoid_rewrite Rewrite.
Admitted.

(* Now try under lambda. Does not work! *)
Theorem Bar (p:nat): Rext (fun z => @C 2 1 (@B 1 z)) (fun z => @C 2 1 (@B 1 z)).
Proof.
  Fail setoid_rewrite Rewrite.
  Fail Type_Fix.
Admitted.

In both Foo and Bar direct application of setoid_rewrite fails. The problem is that type of C (B p) is @S 2 1 while our rewriting lemma expects @C (1+1) 1. In Foo I was able to fix this via LTAC. However, this fix does not work under lambda in Bar.

Body:
Here are three solutions:

Flip the order of your arguments, to help setoid_rewrite pick up the right terms even though it's using left-to-right inference.

Your example becomes:

Require Import Coq.Setoids.Setoid Coq.Classes.Morphisms Coq.Relations.Relations.

(* Sample definitions *)
Record S {o i: nat} : Type.
Definition C {o i: nat} (f: @S o i):  @S o i. Admitted.
Definition B {o:nat} (z:nat): @S o (o+o). Admitted.

(* Relations *)
Parameter R: forall {o i}, relation (@S o i).
Definition Rext {o i} := pointwise_relation nat (@R o i).

(* Sample rewriting lemma *)
Lemma Rewrite (x:nat): forall z, R (C (@B x z)) (B z). Admitted.

Global Instance R_Proper {o i} : Proper (R ==> R ==> Basics.flip Basics.impl) (@R o i).
Proof.
Admitted.

(* Simple case. Works with workaround *)
Theorem Foo (p:nat): R (@C 1 2 (@B 1 p)) (@C 1 2 (@B 1 p)).
Proof.
  setoid_rewrite Rewrite.
Admitted.

Global Instance Rext_Proper {o i}
  : Proper
      ((pointwise_relation nat R)
         ==> (pointwise_relation nat R)
         ==> Basics.flip Basics.impl) (@Rext o i).
Proof.
Admitted.

(* Now try under lambda. Does not work! *)
Theorem Bar (p:nat): Rext (fun z => @C 1 2 (@B 1 z)) (fun z => @C 1 2 (@B 1 z)).
Proof.
  setoid_rewrite Rewrite.
Admitted.

Make Type_Fix smarter.

You could do this instead:

Ltac Type_Fix :=
  progress
    repeat match goal with
           | [ |- context G [@C _ ?o] ]
             => progress let G' := context G[@C (o+o) o] in change G'
           end.

This version only requires that the o argument to C not be a binder, and allows the f argument to be a binder.  I've replaced Datatypes.S _ with _ and used progress to ensure that we find places where it makes sense to change; this makes the tactic more general and allows it to fix other representations as well (for example, @C 0 0).

Use match to fill in the relevant argument to Rewrite.

You could replace setoid_rewrite Rewrite with something like

  match goal with
  | [ |- context[C (@B ?x _)] ]
    => setoid_rewrite (Rewrite x)
  end.


问:
Which is the most secure and fast way of transferring large amount of data (SQL Server backup files) to Azure Blob or Azure VM hosting SQL
I am considering options apart from Azure Import Export.

The data is more than 2Tb. but divided into multiple files. I would have 8-10 files ranging from 30Gb to 500Gb And we can use certificates for any web service that can be utilized for this transfer.

AzCopy is usually recommended for transfer of data upto 100GB or less.

Azure Data Factory, Data management Gateway by creating a pipeline and gateway and transferring data.

Please do suggest if there is any other way to do this transfer.

答:
Based on my experience, Azcopy will provide you the best performance and is recommended even when data size is greater than 20 TB. Read this following KB article for more information.

One thing you should determine is which datacenter provides the lower BLOB storage latency based on your location. Use this URL for that purpose. The lower the values you get on that URL, the better.


问:
Angular response is undefined
Trying to retrieve using angular the json found at: "https://api.github.com/users/angular", more precisely the id property from that json.
Any thoughts on why this fails (in debug mode I get a

'response is not defined'

):

```<code><html ng-app="myViewer">
<head>
<script data-require="angular.js@*" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script>
</head>

<body ng-controller="MyController">
    {{ result.id }}
    {{ err }}
</body>

<script type="text/javascript">
(function() {

    var app = angular.module("myViewer", []);

    var MyController = function($scope, $http)
    {
        $http.get("https://api.github.com/users/angular")
        .then(function1, onerr);

        var function1 = function(response)
        {
            $scope.result = response.data;
        }
        var onerr = function(reason)
        {
            $scope.err = "nightmare";
        }

    }

    app.controller("MyController", ["$scope", "$http", MyController]);
}());

</script>
</html>
</code>```

I expect the result to be the id that you can see by copying that link in your browser.

答:
try this i think you have incorrectly defined the controller as mycontroller and it should be SecondController  instead.</p>

```<code> app.controller("MyController", ["$scope", "$http", SecondController ]);
</code>```

Title: Angular response is undefined

Body:
Trying to retrieve using angular the json found at: "https://api.github.com/users/angular", more precisely the id property from that json.
Any thoughts on why this fails (in debug mode I get a

'response is not defined'

):

    {{ result.id }}
    {{ err }}

I expect the result to be the id that you can see by copying that link in your browser.

Body:
try this i think you have incorrectly defined the controller as mycontroller and it should be SecondController  instead.

 app.controller("MyController", ["$scope", "$http", SecondController ]);


问:
Nested thread groups
There are 4 thread groups that run different tests simultaneously (mostly http requests). In one thread group I need to run two http requests at once. How to do it? JMeter is not allowing to nest thread groups.</p>

答:
If you need to run 2 requests at once for the same thread (VIrtual User) , you need to use this plugin:

https://github.com/Blazemeter/jmeter-bzm-plugins/blob/master/parallel/Parallel.md

You can install it with plugin manager.

Title: Nested thread groups


问:
Ansible API 2.3.2.0 tags passed to playbook but doesn't run task with tag
I am successfully passing the tag because the playbook is only running the task I have assign tags: always

The task that is assign the tag I am passing, doesn't run.

Three tasks for testing:

```<code>  - name: debug if tag was provided
    debug: var=tags
    tags: always

  - name: if tag restart was provided
    debug: var=tags
    tags: restart

  - name: if no tag was provided
    debug: var=tags
</code>```

Only the first task runs when I pass 'restart' as the tag, all three tasks run when no tag is provided.  I want the middle guy to run when restart is provided.

Is there a way to see what the playbook is seeing as the tag?

The output for the debug is:

```<code>{
    "tags": "VARIABLE IS NOT DEFINED!"
}
</code>```

Here is how I am sending the tag via the api

```<code>Options = namedtuple('Options', ['connection',  'forks', 'become', 'become_method', 'become_user', 'check',
                                 'listhosts', 'listtasks', 'listtags', 'syntax', 'module_path', 'diff', 'tags'])
options = Options(connection='ssh', forks=5, become=None, become_method=None, become_user=None, check=False,
                  listhosts=False, listtasks=False, listtags=False, syntax=False, module_path="", diff=True, tags=_tag)

PlaybookExecutor(playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager,
                            loader=loader, options=options, passwords=passwords)
</code>```

_tag is a string

答:
always is a special tag.

There is a special always tag that will always run a task, unless specifically skipped (--skip-tags always)

So use a different tag name for the first task if you don't want it to run if you specify the restart tag.

Body:
I am successfully passing the tag because the playbook is only running the task I have assign tags: always

The task that is assign the tag I am passing, doesn't run.

Three tasks for testing:

  - name: debug if tag was provided
    debug: var=tags
    tags: always

  - name: if tag restart was provided
    debug: var=tags
    tags: restart

  - name: if no tag was provided
    debug: var=tags

Only the first task runs when I pass 'restart' as the tag, all three tasks run when no tag is provided.  I want the middle guy to run when restart is provided.

Is there a way to see what the playbook is seeing as the tag?

The output for the debug is:

{
    "tags": "VARIABLE IS NOT DEFINED!"
}

Here is how I am sending the tag via the api

Options = namedtuple('Options', ['connection',  'forks', 'become', 'become_method', 'become_user', 'check',
                                 'listhosts', 'listtasks', 'listtags', 'syntax', 'module_path', 'diff', 'tags'])
options = Options(connection='ssh', forks=5, become=None, become_method=None, become_user=None, check=False,
                  listhosts=False, listtasks=False, listtags=False, syntax=False, module_path="", diff=True, tags=_tag)

PlaybookExecutor(playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager,
                            loader=loader, options=options, passwords=passwords)

_tag is a string


问:
How to get the file name,modified date of the uploaded file in angular 4?
Html File:

```<code><label class="import-file">
   <input type="file"  accept=".doc,.pdf" hidden required>
</label>
</code>```

Thanks in advance.

答:
To get the modified date:</p>

```<code>let modifiedDate= file.lastModifiedDate;
</code>```

Body:
Html File:

   <input type="file"  accept=".doc,.pdf" hidden required>

Thanks in advance.

Body:
To get the modified date:

let modifiedDate= file.lastModifiedDate;


问:
How to find the second minimum number without using arrays or loops
I tried to write a program that receive from the user 5 integers and print the second minimum number.

Here is a sample of what I've tried:

```<code>#include <iostream>
using namespace std;
int main () {
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
if (a>b && a<c && a<d && a<e)
    cout<<a<<endl;
if (b>a && b<c && b<d && b<e)
    cout<<b<<endl;
if (c>a && c<b && c<d && c<e)
    cout<<c<<endl;
if (d>a && d<b && d<c && d<e)
    cout <<d<<endl;
if (e>a && e<b && e<c && e<d)
cout <<e<<endl;
return 0;

}
</code>```

When I enter 1 2 3 4 5 it prints the second minimum, but when I enter

5 4 3 2 1 Nothing will print on the screen. What am I doing wrong with this? Is there any other way to write my program?

答:
The problem you have with your logic is that you do not enforce yourself to print only 1 item, and at least one item.
By using the 'else' part of the if/else syntax, you will ensure that only one branch can ever be hit.  You can then follow this up with just an else at the end, as you know all other conditions are false.

Once you've done this, you'll see that you print the last value, (1) rather than the expected (4).  This is because your logic regarding how to find the 2nd lowest is wrong.  b>a is false for the case 5,4...

Note:
Every employed engineer, ever, would make this a loop in a std::vector / std::array, and I would suggest you point your teacher to this post because encouraging loops is a good thing rather than bad.

Something like

```<code>vector<int> data;
for (int i=0; i<5; ++i) {
    int t;
    cin >> t;
    data.push_back(t);
}
std::nth_element(data.begin(), data.begin()+1, data.end(), std::greater<int>());
cout << data[1];
</code>```

Body:
I tried to write a program that receive from the user 5 integers and print the second minimum number.

Here is a sample of what I've tried:

#include <iostream>
using namespace std;
int main () {
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
if (a>b && a<c && a<d && a<e)
    cout<<a<<endl;
if (b>a && b<c && b<d && b<e)
    cout<<b<<endl;
if (c>a && c<b && c<d && c<e)
    cout<<c<<endl;
if (d>a && d<b && d<c && d<e)
    cout <<d<<endl;
if (e>a && e<b && e<c && e<d)
cout <<e<<endl;
return 0;

}

When I enter 1 2 3 4 5 it prints the second minimum, but when I enter

5 4 3 2 1 Nothing will print on the screen. What am I doing wrong with this? Is there any other way to write my program?

Body:
The problem you have with your logic is that you do not enforce yourself to print only 1 item, and at least one item.
By using the 'else' part of the if/else syntax, you will ensure that only one branch can ever be hit.  You can then follow this up with just an else at the end, as you know all other conditions are false.

Once you've done this, you'll see that you print the last value, (1) rather than the expected (4).  This is because your logic regarding how to find the 2nd lowest is wrong.  b>a is false for the case 5,4...

Note:
Every employed engineer, ever, would make this a loop in a std::vector / std::array, and I would suggest you point your teacher to this post because encouraging loops is a good thing rather than bad.

Something like

vector<int> data;
for (int i=0; i<5; ++i) {
    int t;
    cin >> t;
    data.push_back(t);
}
std::nth_element(data.begin(), data.begin()+1, data.end(), std::greater<int>());
cout << data[1];


问:
how to get shared value proportion by each row in r
```<code>type<-c("111","111","111","222","222","222","222","333","333","333","444","444","444")

location<-c("aaa","bbb","ccc","aaa","bbb","ddd","eee","aaa","ccc","ddd","ccc","ddd","fff")

datafr1 <- data.frame(type,location)
</code>```

I want the result like this.(don't need to be a format like this.)

```<code>           222     333    444
111      0.66%    0.66%   0.33%
</code>```

and 222, 333, 444 too.
Find the shared values and then get proportion of intersection.

Can you help me?!!

Body:
type<-c("111","111","111","222","222","222","222","333","333","333","444","444","444")

location<-c("aaa","bbb","ccc","aaa","bbb","ddd","eee","aaa","ccc","ddd","ccc","ddd","fff")

datafr1 <- data.frame(type,location)

I want the result like this.(don't need to be a format like this.)

           222     333    444
111      0.66%    0.66%   0.33%

and 222, 333, 444 too.
Find the shared values and then get proportion of intersection.

Can you help me?!!

Body:
We can do a crossproduct on the table output of 'datafr1', then divide each row by the maximum value of the output

m1 <- tcrossprod(table(datafr1))
m1/matrixStats::rowMaxs(m1)
#      type
#type        111       222       333       444
#  111 1.0000000 0.6666667 0.6666667 0.3333333
#  222 0.5000000 1.0000000 0.5000000 0.2500000
#  333 0.6666667 0.6666667 1.0000000 0.6666667
#  444 0.3333333 0.3333333 0.6666667 1.0000000


问:
GPS stationary mode support added in the latest release of GPSD 3.16?
I read from this link.
with the following statement:
 "For most reliable service we recommend using stationary mode if your device has it. GPSD tools don’t yet directly support this, but that capability may be added in a future release.."

Anyone know if the stationary mode has been added to the latest release of GPSD 3.16 ?

Thx!

答:
It certainly does not look like it:

http://git.savannah.gnu.org/cgit/gpsd.git/log/?qt=grep&q=stationary

You can always send the appropriate config commands to the gps before starting gpsd.