问:
Can I use two different TTK themes in one Tkinter (tk.Tk) root window?
This question concerns Python and Tkinter.

I'd like to use two different ttk themes simultaneously, e.g. 'clam' and 'vista' in one Tkinter window. So I wrote this:

```<code>import tkinter as tk
import tkinter.ttk as ttk

class GUI(tk.Tk):

    def __init__(self):

        super().__init__()
        Button_v1()
        Button_v2()

class Button_v1(ttk.Button):

    def __init__(self, default_text="Test"):

        super().__init__(text=default_text)

        s = ttk.Style()
        s.theme_use('clam')
        s.configure(self.winfo_class(), foreground='blue')
        self.pack()

class Button_v2(ttk.Button):

    def __init__(self, default_text="Test2"):

        super().__init__(text=default_text)

        s2 = ttk.Style()
        s2.theme_use('vista')
        s2.configure(self.winfo_class(), foreground='red')
        self.pack()

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

The code loads, however:

I expected the first Button's foreground to be blue and the second Button's foreground to be red, and for two separate themes to be used.

Instead, both buttons have a red foreground, and both apply the same theme.

Is it possible to use two separate ttk themes in one Tkinter program?

答:
No, it's not possible, because theme has a global meaning in this context. You can represent theme as a set of styles for widgets (for widget layout elements, actually), you can change style and/or create a new one, but you can't use more than one of themes at the time, because widget's layout depends heavily on it.

When you call theme_use('theme_name') tkinter rebuilds all widget's layouts and redraws your entire application, and you can easily check this, thanks to <<ThemeChanged>> virtual event.

Here's a snippet. You will see three prints, caused by each button and by root himself.

```<code>try:
    import tkinter as tk
    import tkinter.ttk as ttk
except ImportError:
    import Tkinter as tk
    import ttk

class GUI(tk.Tk):
    def __init__(self):
        super().__init__()
        self.bind('<<ThemeChanged>>', lambda event: print('theme changed in root and across all widgets!'))
        Button_v1()
        Button_v2()

class Button_v1(ttk.Button):
    def __init__(self, default_text="Test"):
        super().__init__(text=default_text)
        s = ttk.Style()
        s.theme_use('clam')
        s.configure(self.winfo_class(), foreground='blue')
        self.pack()

class Button_v2(ttk.Button):
    def __init__(self, default_text="Test2"):
        super().__init__(text=default_text)
        s2 = ttk.Style()
        s2.theme_use('vista')
        s2.configure(self.winfo_class(), foreground='red')
        self.pack()

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

If you need different foreground for each button - then create a new style for each of them and use the style parameter:

Here's an another snippet:

```<code>try:
    import tkinter as tk
    import tkinter.ttk as ttk
except ImportError:
    import Tkinter as tk
    import ttk

class GUI(tk.Tk):
    def __init__(self):
        super().__init__()

        s = ttk.Style()
        s.configure('blue.TButton', foreground='blue')
        s.configure('red.TButton', foreground='red')

        Button_v1()
        Button_v2()

class Button_v1(ttk.Button):
    def __init__(self, default_text="Test"):
        super().__init__(text=default_text, style='blue.TButton')
        self.pack()

class Button_v2(ttk.Button):
    def __init__(self, default_text="Test2"):
        super().__init__(text=default_text, style='red.TButton')
        self.pack()

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

Everything is well described here and there.

Body:
This question concerns Python and Tkinter.

I'd like to use two different ttk themes simultaneously, e.g. 'clam' and 'vista' in one Tkinter window. So I wrote this:

import tkinter as tk
import tkinter.ttk as ttk

class GUI(tk.Tk):

    def __init__(self):

        super().__init__()
        Button_v1()
        Button_v2()

class Button_v1(ttk.Button):

    def __init__(self, default_text="Test"):

        super().__init__(text=default_text)

        s = ttk.Style()
        s.theme_use('clam')
        s.configure(self.winfo_class(), foreground='blue')
        self.pack()

class Button_v2(ttk.Button):

    def __init__(self, default_text="Test2"):

        super().__init__(text=default_text)

        s2 = ttk.Style()
        s2.theme_use('vista')
        s2.configure(self.winfo_class(), foreground='red')
        self.pack()

GUI().mainloop()

The code loads, however:

I expected the first Button's foreground to be blue and the second Button's foreground to be red, and for two separate themes to be used.

Instead, both buttons have a red foreground, and both apply the same theme.

Is it possible to use two separate ttk themes in one Tkinter program?

Body:
No, it's not possible, because theme has a global meaning in this context. You can represent theme as a set of styles for widgets (for widget layout elements, actually), you can change style and/or create a new one, but you can't use more than one of themes at the time, because widget's layout depends heavily on it.

When you call theme_use('theme_name') tkinter rebuilds all widget's layouts and redraws your entire application, and you can easily check this, thanks to <<ThemeChanged>> virtual event.

Here's a snippet. You will see three prints, caused by each button and by root himself.

try:
    import tkinter as tk
    import tkinter.ttk as ttk
except ImportError:
    import Tkinter as tk
    import ttk

class GUI(tk.Tk):
    def __init__(self):
        super().__init__()
        self.bind('<<ThemeChanged>>', lambda event: print('theme changed in root and across all widgets!'))
        Button_v1()
        Button_v2()

class Button_v1(ttk.Button):
    def __init__(self, default_text="Test"):
        super().__init__(text=default_text)
        s = ttk.Style()
        s.theme_use('clam')
        s.configure(self.winfo_class(), foreground='blue')
        self.pack()

class Button_v2(ttk.Button):
    def __init__(self, default_text="Test2"):
        super().__init__(text=default_text)
        s2 = ttk.Style()
        s2.theme_use('vista')
        s2.configure(self.winfo_class(), foreground='red')
        self.pack()

GUI().mainloop()

If you need different foreground for each button - then create a new style for each of them and use the style parameter:

Here's an another snippet:

try:
    import tkinter as tk
    import tkinter.ttk as ttk
except ImportError:
    import Tkinter as tk
    import ttk

class GUI(tk.Tk):
    def __init__(self):
        super().__init__()

        s = ttk.Style()
        s.configure('blue.TButton', foreground='blue')
        s.configure('red.TButton', foreground='red')

        Button_v1()
        Button_v2()

class Button_v1(ttk.Button):
    def __init__(self, default_text="Test"):
        super().__init__(text=default_text, style='blue.TButton')
        self.pack()

class Button_v2(ttk.Button):
    def __init__(self, default_text="Test2"):
        super().__init__(text=default_text, style='red.TButton')
        self.pack()

GUI().mainloop()

Everything is well described here and there.


来源: stackexchange

问:
making a legend in Line graph with a grouping variable, ggplot2
I have data that looks like this, where line is a grouping variable representing a genetic line, tp is a time point (x axis), expr is gene expression relative to 0 tine point, and col is a color assignment for each line:

```<code>line    tp    expr           col
358 LL  0   0                yellowgreen
358 LL  30  -2.459476064     yellowgreen
358 LL  60  0.645900697      yellowgreen
358 LL  90  0.040513329      yellowgreen
380 LL  0   0                indianred4
380 LL  30  0.893111431      indianred4
380 LL  60  0.847461181      indianred4
380 LL  90  -0.867875889     indianred4
441 HL  0   0                blue
441 HL  30  1.934555631      blue
441 HL  60  3.144618461      blue
441 HL  90  1.883829994      blue
486 LL  0   0                bisque4
487 LL  30  -0.064427095     bisque4
488 LL  60  0.015498302      bisque4
489 LL  90  1.047567166      bisque4
832 HL  0   0                blueviolet
832 HL  30  -0.233381601     blueviolet
832 HL  60  -3.562884526     blueviolet
832 HL  90  -0.038818998     blueviolet
913 HL  0   0                orange
913 HL  30  0.799850689      orange
913 HL  60  0.818883617      orange
913 HL  90  -0.07758268      orange
Average 0   0                black
Average 30  0.145038832      black
Average 60  0.318246289      black
Average 90  0.331272154      black
</code>```

using the following code, I produce exactly what I want but with no legend:

```<code># Set color spectrums:
larvae_col <- as.vector(CG13288_L$col)

ggplot(data=CG13288_L, aes(x = tp, y = expr, group=line)) +
  geom_line(size=1, color=larvae_col) +
  theme_light() + theme(panel.grid=element_blank()) +
  labs(title="CG13288 (FBgn0035648) - Larvae", x="Time Point", y="LogFC Expression") +
  theme(axis.title.x = element_text(color="black", face="bold", size=35, margin=margin(20,0,0,0))) +
  theme(axis.title.y = element_text(color="black", face="bold", size=35, margin=margin(0,20,0,0))) +
  theme(plot.title=element_text(color="black", face="bold", size=40, margin=margin(0,0,20,0))) +
  theme(axis.text = element_text(size=30, color="black", face="bold")) +
  theme(panel.border = element_rect(color = "black", size=1.5)) +
  theme(axis.ticks = element_line(color = "black", size=1.5)) +
  scale_x_discrete(expand=c(0.01,0.04)) +
  scale_y_continuous(limits=c(-4,4), breaks=c(-4,-2,0,2,4), expand=c(0.02,0.01))

ggsave("CG13288_L.pdf", plot = last_plot(), device = "pdf", width = 15, height = 10, units = "in", useDingbats=FALSE)
</code>```

I have toyed around with using "color" instead of "group" on the first line but get vertical lines for each tp (time point). How can I add a legend to this?

答:
If you want a variable to automatically appear in legends, you should specify it within the aes object.
Just change your line 2 to:

```<code>geom_line(size=1, aes(colour=col)) +
</code>```

This way your legend would assign the color names to ggplot default colors. To change the default ggplot colors, you can add:

```<code>scale_colour_manual(values=unique(larvae_col))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have data that looks like this, where line is a grouping variable representing a genetic line, tp is a time point (x axis), expr is gene expression relative to 0 tine point, and col is a color assignment for each line:

line    tp    expr           col
358 LL  0   0                yellowgreen
358 LL  30  -2.459476064     yellowgreen
358 LL  60  0.645900697      yellowgreen
358 LL  90  0.040513329      yellowgreen
380 LL  0   0                indianred4
380 LL  30  0.893111431      indianred4
380 LL  60  0.847461181      indianred4
380 LL  90  -0.867875889     indianred4
441 HL  0   0                blue
441 HL  30  1.934555631      blue
441 HL  60  3.144618461      blue
441 HL  90  1.883829994      blue
486 LL  0   0                bisque4
487 LL  30  -0.064427095     bisque4
488 LL  60  0.015498302      bisque4
489 LL  90  1.047567166      bisque4
832 HL  0   0                blueviolet
832 HL  30  -0.233381601     blueviolet
832 HL  60  -3.562884526     blueviolet
832 HL  90  -0.038818998     blueviolet
913 HL  0   0                orange
913 HL  30  0.799850689      orange
913 HL  60  0.818883617      orange
913 HL  90  -0.07758268      orange
Average 0   0                black
Average 30  0.145038832      black
Average 60  0.318246289      black
Average 90  0.331272154      black

using the following code, I produce exactly what I want but with no legend:

# Set color spectrums:
larvae_col <- as.vector(CG13288_L$col)

ggplot(data=CG13288_L, aes(x = tp, y = expr, group=line)) +
  geom_line(size=1, color=larvae_col) +
  theme_light() + theme(panel.grid=element_blank()) +
  labs(title="CG13288 (FBgn0035648) - Larvae", x="Time Point", y="LogFC Expression") +
  theme(axis.title.x = element_text(color="black", face="bold", size=35, margin=margin(20,0,0,0))) +
  theme(axis.title.y = element_text(color="black", face="bold", size=35, margin=margin(0,20,0,0))) +
  theme(plot.title=element_text(color="black", face="bold", size=40, margin=margin(0,0,20,0))) +
  theme(axis.text = element_text(size=30, color="black", face="bold")) +
  theme(panel.border = element_rect(color = "black", size=1.5)) +
  theme(axis.ticks = element_line(color = "black", size=1.5)) +
  scale_x_discrete(expand=c(0.01,0.04)) +
  scale_y_continuous(limits=c(-4,4), breaks=c(-4,-2,0,2,4), expand=c(0.02,0.01))

ggsave("CG13288_L.pdf", plot = last_plot(), device = "pdf", width = 15, height = 10, units = "in", useDingbats=FALSE)

I have toyed around with using "color" instead of "group" on the first line but get vertical lines for each tp (time point). How can I add a legend to this?

Body:
If you want a variable to automatically appear in legends, you should specify it within the aes object.
Just change your line 2 to:

geom_line(size=1, aes(colour=col)) +

This way your legend would assign the color names to ggplot default colors. To change the default ggplot colors, you can add:

scale_colour_manual(values=unique(larvae_col))


问:
JavaMail: Java.awt.datatransfer.Transferable doesn't exist
I wasn't going to open a question, but I had no solution to this problem!

I have a problem receiving messages from IMAP server.

The error says "Caused by: java.lang.ClassNotFoundException: Didn't find class "java.awt.datatransfer.Transferable" on path...." Here's my code:

```<code>enter String test(){
    String all="";
    try{
        class Runner extends AsyncTask<Object, String, String> {
            @Override
            protected String doInBackground(Object... params) {
                Looper.prepare();
                String all ="";
                try{
                    Message[] msgs = ReceiveMail("imap.gmail.com","993","USER@gmail.com","PASS"); // After passing this line, error logging says error is in this line!
                    for(Message m: msgs){
                        all+=m.getSubject()+"\n"+m.getContent().toString()+"\n\n"; // Error shows here, but popups above
                    }
                    return all;
                }catch (Exception e){
                    e.printStackTrace();
                }
                Looper.loop();
                return all;
            }
        }
        Runner r = new Runner();
        all = r.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, this).get();
    }catch (Exception e){
        e.printStackTrace();
    }
    return all;
}
private Message[] ReceiveMail(String host,String port,String user,String pass){
    try{
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");
        props.setProperty("mail.imaps.host", host);
        props.setProperty("mail.imaps.port", port);
        props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.imaps.socketFactory.fallback", "false");
        Session imapSession = Session.getInstance(props);
        Store store = imapSession.getStore("imaps");
        store.connect(host, user, pass);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        return inbox.getMessages();
    }catch (Exception e){
        e.printStackTrace();
        //log_all("ReceiveMail function: "+e.getMessage());
    }
    return null;
}
</code>```

What is the problem?

Note When I don't use AsyncTask error "Network in main thread" appears.

SOLUTION:

Download these and add them as libraries.

Remove javax.* from dependencies tab in the module settings.

That'll solve it.

答:
The JavaMail API Reference Implementation version 1.5.5 and later have built in support for Android and include support for OAuth2.
Per the documentation:

Android does not provide a Java Compatible runtime and so can't run the standard JavaMail distribution. Instead, a special version of JavaMail is available for Android. This special version of JavaMail depends on a special version of the JavaBeans Activation Framework.

You can try out this version by adding the following to your build.gradle file for your Android application:

```<code> android {
     packagingOptions {
         pickFirst 'META-INF/LICENSE.txt' // picks the JavaMail license file
     }
 }

 repositories {
     jcenter()
     maven {
         url "https://maven.java.net/content/groups/public/"
     }
 }

 dependencies {
     compile 'com.sun.mail:android-mail:1.5.6'
     compile 'com.sun.mail:android-activation:1.5.6'
 }
</code>```

Body:
I wasn't going to open a question, but I had no solution to this problem!

I have a problem receiving messages from IMAP server.

The error says "Caused by: java.lang.ClassNotFoundException: Didn't find class "java.awt.datatransfer.Transferable" on path...." Here's my code:

enter String test(){
    String all="";
    try{
        class Runner extends AsyncTask<Object, String, String> {
            @Override
            protected String doInBackground(Object... params) {
                Looper.prepare();
                String all ="";
                try{
                    Message[] msgs = ReceiveMail("imap.gmail.com","993","USER@gmail.com","PASS"); // After passing this line, error logging says error is in this line!
                    for(Message m: msgs){
                        all+=m.getSubject()+"\n"+m.getContent().toString()+"\n\n"; // Error shows here, but popups above
                    }
                    return all;
                }catch (Exception e){
                    e.printStackTrace();
                }
                Looper.loop();
                return all;
            }
        }
        Runner r = new Runner();
        all = r.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, this).get();
    }catch (Exception e){
        e.printStackTrace();
    }
    return all;
}
private Message[] ReceiveMail(String host,String port,String user,String pass){
    try{
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");
        props.setProperty("mail.imaps.host", host);
        props.setProperty("mail.imaps.port", port);
        props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.imaps.socketFactory.fallback", "false");
        Session imapSession = Session.getInstance(props);
        Store store = imapSession.getStore("imaps");
        store.connect(host, user, pass);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        return inbox.getMessages();
    }catch (Exception e){
        e.printStackTrace();
        //log_all("ReceiveMail function: "+e.getMessage());
    }
    return null;
}

What is the problem?

Note When I don't use AsyncTask error "Network in main thread" appears.

SOLUTION:

Download these and add them as libraries.

Remove javax.* from dependencies tab in the module settings.

That'll solve it.

Body:
The JavaMail API Reference Implementation version 1.5.5 and later have built in support for Android and include support for OAuth2.
Per the documentation:

Android does not provide a Java Compatible runtime and so can't run the standard JavaMail distribution. Instead, a special version of JavaMail is available for Android. This special version of JavaMail depends on a special version of the JavaBeans Activation Framework.

You can try out this version by adding the following to your build.gradle file for your Android application:

 android {
     packagingOptions {
         pickFirst 'META-INF/LICENSE.txt' // picks the JavaMail license file
     }
 }

 repositories {
     jcenter()
     maven {
         url "https://maven.java.net/content/groups/public/"
     }
 }

 dependencies {
     compile 'com.sun.mail:android-mail:1.5.6'
     compile 'com.sun.mail:android-activation:1.5.6'
 }


问:
Object Oriented questions in Javascript
I've been using javascript for a while, but have never learned the language past the basics.  I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc.

John gives this example in his book:

Function #1

```<code>function User( name, age ){
  this.name = name;
  this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
  return this.name;
};
User.prototype.getAge = function(){
  return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
</code>```

I'm still learning about the prototype property, so I tried writing something similar:

Function #2

```<code>function User (name, age ) {
  this.name = name;
  this.age = age;
  this.getName = function() {
    return this.name;
  };
  this.getAge = function() {
    return this.age;
  };
}
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
</code>```

It doesn't use the prototype property to create the getName and getAge functions, but the output is the same as John's example.

I took it one step further, and created this:

Function #3

```<code>var User = {
  name: "",
  age: 0,
  setName: function(name) {
    this.name = name;
  },
  setAge: function(age) {
    this.age = age;
  },
  getName: function() {
    return this.name;
  },
  getAge: function() {
    return this.age;
  }
};
User.setName("Bob");
User.setAge(44);
console.log("User: " + User.getName() + ", Age: " + User.getAge());
</code>```

Again - it looks different than John's example (and I had to add setter methods), but the output is the same.

Question #1 - what is the difference between the 3 functions?  What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).

Question #2 - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand?  Can the {...} shorthand have constructors?

Thanks in advance for helping me learn!

EDIT
I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:

```<code>var user = new User("Bob", 44);
</code>```

Just like in Function #1 - or is that not possible?

EDIT #2
Wow!  Thanks everyone for the awesome answers.  That really makes it a lot more clear to me.  So if I understand correctly, the difference between #1 and #2 aren't too much.  If I only ever create one "User" object - they probably aren't different at all.  But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.

I really appreciate all of the great answers - Thanks!

答:
Question #1

prototype has the benefit of monkey patching. As the first example shows, the function are added after-the-fact. You can continue this to add or replace any methods you need (though, with fair warning).

Defining objects like #2 is more along the lines of classic OOP. But, then again, monkey patching isn't allowed in all OOP languages.

Question #2

In your 3rd function, you don't even need the get and set functions -- name and age are public properties (the potential downside to {}).

```<code>var User = {
  name: "",
  age: 0
};

User.name = 'Bob';
User.age = 44;

console.log("User: " + User.name + ", Age: " + User.age);
</code>```

When you create an object using {} (an object literal), {} is the constructor (varying on browser). But, essentially, no you can't use a constructor in this format.

OwnerDisplayName: BrianH

ContentLicense: CC BY-SA 2.5

Title: Object Oriented questions in Javascript

Body:
I've been using javascript for a while, but have never learned the language past the basics.  I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc.

John gives this example in his book:

Function #1

function User( name, age ){
  this.name = name;
  this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
  return this.name;
};
User.prototype.getAge = function(){
  return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());

I'm still learning about the prototype property, so I tried writing something similar:

Function #2

function User (name, age ) {
  this.name = name;
  this.age = age;
  this.getName = function() {
    return this.name;
  };
  this.getAge = function() {
    return this.age;
  };
}
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());

It doesn't use the prototype property to create the getName and getAge functions, but the output is the same as John's example.

I took it one step further, and created this:

Function #3

var User = {
  name: "",
  age: 0,
  setName: function(name) {
    this.name = name;
  },
  setAge: function(age) {
    this.age = age;
  },
  getName: function() {
    return this.name;
  },
  getAge: function() {
    return this.age;
  }
};
User.setName("Bob");
User.setAge(44);
console.log("User: " + User.getName() + ", Age: " + User.getAge());

Again - it looks different than John's example (and I had to add setter methods), but the output is the same.

Question #1 - what is the difference between the 3 functions?  What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).

Question #2 - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand?  Can the {...} shorthand have constructors?

Thanks in advance for helping me learn!

EDIT
I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:

var user = new User("Bob", 44);

Just like in Function #1 - or is that not possible?

EDIT #2
Wow!  Thanks everyone for the awesome answers.  That really makes it a lot more clear to me.  So if I understand correctly, the difference between #1 and #2 aren't too much.  If I only ever create one "User" object - they probably aren't different at all.  But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.

I really appreciate all of the great answers - Thanks!

LastEditorDisplayName: BrianH

Body:
Question #1

prototype has the benefit of monkey patching. As the first example shows, the function are added after-the-fact. You can continue this to add or replace any methods you need (though, with fair warning).

Defining objects like #2 is more along the lines of classic OOP. But, then again, monkey patching isn't allowed in all OOP languages.

Question #2

In your 3rd function, you don't even need the get and set functions -- name and age are public properties (the potential downside to {}).

var User = {
  name: "",
  age: 0
};

User.name = 'Bob';
User.age = 44;

console.log("User: " + User.name + ", Age: " + User.age);

When you create an object using {} (an object literal), {} is the constructor (varying on browser). But, essentially, no you can't use a constructor in this format.

OwnerDisplayName: Jonathan Lonowski


问:
Two rows in one in SQL server
The answer is too close, Thanks
But
The problem is that if too many records to be entered

```<code>           |    id   |    name   |    age    |   Tel
------------------------------------------
      1    |    1   |   Frank   |    40     |   null
      2    |    1   |   null    |    50     |   7834xx
      3    |    1   |   Alex    |    null   |   null
      4    |    1   |   null    |    20     |   null
      5    |    2   |   James   |    null   |   4121xx
</code>```

Query return the Maximum value
Like:

```<code>           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Frank   |    50     |  7834xx
</code>```

i need Select Query like this:

```<code>           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Alex    |    20     |  7834xx
</code>```

what do I do? Plz?

答:
Here's a roundabout way to combine the last non-empty value of 3 columns:

```<code>-- Using a table variable for test data
declare @Test table (tableId int identity(1,1), id int, name varchar(100), age int, tel varchar(30));
insert into @Test (id, name, age, tel) values
(1,'Frank',40,null),
(1,null,50,'7834xx'),
(1,'Alex',null,null),
(1,null,20,null),
(2,'James',null,'4121xx');

select n.id, n.name, a.age, t.tel
from (
    select top(1) with ties id, name
    from @Test
    where name is not null
    order by row_number() over (partition by id order by tableId desc)
) n
inner join (
    select top(1) with ties id, age
    from @Test
    where age is not null
    order by row_number() over (partition by id order by tableId desc)
) a on (n.id = a.id)
inner join (
    select top(1) with ties id, tel
    from @Test
    where tel is not null
    order by row_number() over (partition by id order by tableId desc)
) t on (n.id = t.id);
</code>```

or by re-using a CTE

```<code>;with CTE AS (
    select * ,
    row_number() over (partition by id, iif(name is not null,1,0) order by tableId desc) as rn_name,
    row_number() over (partition by id, iif(age is not null,1,0) order by tableId desc) as rn_age,
    row_number() over (partition by id, iif(tel is not null,1,0) order by tableId desc) as rn_tel
    from @Test
 )
select n.id, n.name, a.age, t.tel
from CTE n
join CTE a on (a.id = n.id and a.age is not null and a.rn_age = 1)
join CTE t on (t.id = n.id and t.tel is not null and t.rn_tel = 1)
where (n.name is not null and n.rn_name = 1);
</code>```

Result :

```<code>╔════╦══════╦═════╦════════╗
║ id ║ name ║ age ║  tel   ║
╠════╬══════╬═════╬════════╣
║  1 ║ Alex ║  20 ║ 7834xx ║
╚════╩══════╩═════╩════════╝
</code>```

After looking at this answer more than a year later.

You could also use the window function first_value for this.

Without using any join.

```<code>select Id, name, age, tel
from
(
    select Id
    , row_number() over (partition by id order by tableId desc) as rn
    , first_value(name) over (partition by id order by iif(name is null,1,0), tableId desc) as name
    , first_value(age) over (partition by id order by iif(age is null,1,0), tableId desc) as age
    , first_value(tel) over (partition by id order by iif(tel is null,1,0), tableId desc) as tel
    from @Test
) q
where rn = 1
and name is not null and age is not null and tel is not null;
</code>```

Title: Two rows in one in SQL server

Body:
The answer is too close, Thanks
But
The problem is that if too many records to be entered

           |    id   |    name   |    age    |   Tel
------------------------------------------
      1    |    1   |   Frank   |    40     |   null
      2    |    1   |   null    |    50     |   7834xx
      3    |    1   |   Alex    |    null   |   null
      4    |    1   |   null    |    20     |   null
      5    |    2   |   James   |    null   |   4121xx

Query return the Maximum value
Like:

           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Frank   |    50     |  7834xx

i need Select Query like this:

           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Alex    |    20     |  7834xx

what do I do? Plz?

Body:
Here's a roundabout way to combine the last non-empty value of 3 columns:

-- Using a table variable for test data
declare @Test table (tableId int identity(1,1), id int, name varchar(100), age int, tel varchar(30));
insert into @Test (id, name, age, tel) values
(1,'Frank',40,null),
(1,null,50,'7834xx'),
(1,'Alex',null,null),
(1,null,20,null),
(2,'James',null,'4121xx');

select n.id, n.name, a.age, t.tel
from (
    select top(1) with ties id, name
    from @Test
    where name is not null
    order by row_number() over (partition by id order by tableId desc)
) n
inner join (
    select top(1) with ties id, age
    from @Test
    where age is not null
    order by row_number() over (partition by id order by tableId desc)
) a on (n.id = a.id)
inner join (
    select top(1) with ties id, tel
    from @Test
    where tel is not null
    order by row_number() over (partition by id order by tableId desc)
) t on (n.id = t.id);

or by re-using a CTE

;with CTE AS (
    select * ,
    row_number() over (partition by id, iif(name is not null,1,0) order by tableId desc) as rn_name,
    row_number() over (partition by id, iif(age is not null,1,0) order by tableId desc) as rn_age,
    row_number() over (partition by id, iif(tel is not null,1,0) order by tableId desc) as rn_tel
    from @Test
 )
select n.id, n.name, a.age, t.tel
from CTE n
join CTE a on (a.id = n.id and a.age is not null and a.rn_age = 1)
join CTE t on (t.id = n.id and t.tel is not null and t.rn_tel = 1)
where (n.name is not null and n.rn_name = 1);

Result :

╔════╦══════╦═════╦════════╗
║ id ║ name ║ age ║  tel   ║
╠════╬══════╬═════╬════════╣
║  1 ║ Alex ║  20 ║ 7834xx ║
╚════╩══════╩═════╩════════╝

After looking at this answer more than a year later.

You could also use the window function first_value for this.

Without using any join.

select Id, name, age, tel
from
(
    select Id
    , row_number() over (partition by id order by tableId desc) as rn
    , first_value(name) over (partition by id order by iif(name is null,1,0), tableId desc) as name
    , first_value(age) over (partition by id order by iif(age is null,1,0), tableId desc) as age
    , first_value(tel) over (partition by id order by iif(tel is null,1,0), tableId desc) as tel
    from @Test
) q
where rn = 1
and name is not null and age is not null and tel is not null;

ContentLicense: CC BY-SA 4.0


问:
How to fit all pixel sized images in a div?
I'm building a web application where I want to display product like in e-commerce website. The images of random dimension have to be fit in a particular box.
I have tried following code but it distorts the image if height is more than width, but looks perfectly if it is vice versa.</p>

```<code><div class="panel panel-default text-center">
                <div class="panel-heading" style="padding:2px;">
                    <a href="#" style=" text-decoration: none;"><img  src="images/abc.jpg" style="width:100%;height:220px;" /></a></a>
                </div>

                <div class="panel-body w3-card" style="padding-top:0px;background-color:#ebebeb;">
                    <a href="#" class="pull-left" style=" text-decoration: none;"><h5 style="margin-bottom:0px;" ><b>Product One</b></h5>
                    <p class="pull-left" style="margin-top:0px;color:#6e6e6e;margin-bottom:0px;"><i class="fa fa-inr"></i> 10,000/-</p></a>
                </div>

            </div>
</code>```

答:
If you don't care much about Edge / IE, you can use object-fit like in the example below:

Product One

 10,000/-

```
</div>
</div>
</p>

<p>If you <strong>do</strong> care and <strong>if</strong> you can use <code>background-image</code>, i'd advise you going the way below:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.panel-heading {
  height: 200px;
  background-size: cover;
  background-position: center center;
  background-repeat: no-repeat;
  background-image: url('http://placehold.it/1000x1000');
}</code>```

Product One

 10,000/-

```

Body:
I'm building a web application where I want to display product like in e-commerce website. The images of random dimension have to be fit in a particular box.
I have tried following code but it distorts the image if height is more than width, but looks perfectly if it is vice versa.

Product One

 10,000/-

Body:
If you don't care much about Edge / IE, you can use object-fit like in the example below:

<div class="panel panel-default text-center">
  <div class="panel-heading" style="padding:2px;height:200px;">
    <a href="#" style=" text-decoration: none;"><img src="http://placehold.it/1000x1000" style="width:100%;height:100%;object-fit:cover;" /></a>
  </div>
  <div class="panel-body w3-card" style="padding-top:0px;background-color:#ebebeb;">
    <a href="#" class="pull-left" style=" text-decoration: none;">
      <h5 style="margin-bottom:0px;"><b>Product One</b></h5>
      <p class="pull-left" style="margin-top:0px;color:#6e6e6e;margin-bottom:0px;"><i class="fa fa-inr"></i> 10,000/-</p>
    </a>
  </div>

If you do care and if you can use background-image, i'd advise you going the way below:

div.panel-heading {
  height: 200px;
  background-size: cover;
  background-position: center center;
  background-repeat: no-repeat;
  background-image: url('http://placehold.it/1000x1000');
}

<div class="panel panel-default text-center">
  <div class="panel-heading" style="padding:2px;height:200px;">
    <a href="#" style=" text-decoration: none;"></a>
  </div>
  <div class="panel-body w3-card" style="padding-top:0px;background-color:#ebebeb;">
    <a href="#" class="pull-left" style=" text-decoration: none;">
      <h5 style="margin-bottom:0px;"><b>Product One</b></h5>
      <p class="pull-left" style="margin-top:0px;color:#6e6e6e;margin-bottom:0px;"><i class="fa fa-inr"></i> 10,000/-</p>
    </a>
  </div>


问:
multi rows in 1 rows , SQL server
The problem is that if too many records to be entered

```<code>           |    id   |    name   |    age    |   Tel
------------------------------------------
      1    |    1   |   Frank   |    40     |   null
      2    |    1   |   null    |    50     |   7834xx
      3    |    1   |   Alex    |    null   |   null
      4    |    1   |   null    |    20     |   null
      5    |    2   |   James   |    null   |   4121xx
</code>```

My Query :

```<code> select id, max(name) as name, max(age) as age, max(tel) as tel
 from Table group by id;
</code>```

Result = return the Maximum value Like:

```<code>           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Frank   |    50     |  7834xx
</code>```

But I need Select Query like this:
Ex: (maybe):
   select id, lastRowsNotNull(name) as name, lastRowsNotNull(age) as age ,lastRowsNotNull(tel) as tel from Table group by id;

```<code>           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Alex    |    20     |  7834xx
</code>```

What do I do? pleas?

答:
```<code>drop table if exists dbo.TableC;

create table dbo.TableC (
Ident int primary key
, Id int
, name varchar(100)
, age int
, Tel varchar(100)
);

insert into dbo.TableC (Ident, Id, name, age, Tel)
values (1, 1, 'Frank', 40, null)
, (2, 1, null, 50, '7834xx')
, (3, 1, 'Alex', null, null)
, (4, 1, null, 20, null)
, (5, 2, 'James', null, '4121xx');

select
*
from (
select
    MIN(t.Ident) as Ident
    , t.id
from dbo.TableC t
group by t.Id
) t
outer apply (
    select
        top (1)
        tn.name
    from dbo.TableC tn
    where tn.name is not null
        and tn.Id = t.Id
    order by tn.Ident desc
) tname
outer apply (
    select
        top (1)
        ta.age
    from dbo.TableC ta
    where ta.age is not null
        and ta.Id = t.Id
    order by ta.Ident desc
) tage
outer apply (
    select
        top (1)
        tt.tel
    from dbo.TableC tt
    where tt.Tel is not null
        and tt.Id = t.Id
    order by tt.Ident desc
) ttel
</code>```

Title: multi rows in 1 rows , SQL server

Body:
The problem is that if too many records to be entered

           |    id   |    name   |    age    |   Tel
------------------------------------------
      1    |    1   |   Frank   |    40     |   null
      2    |    1   |   null    |    50     |   7834xx
      3    |    1   |   Alex    |    null   |   null
      4    |    1   |   null    |    20     |   null
      5    |    2   |   James   |    null   |   4121xx

My Query :

 select id, max(name) as name, max(age) as age, max(tel) as tel
 from Table group by id;

Result = return the Maximum value Like:

           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Frank   |    50     |  7834xx

But I need Select Query like this:
Ex: (maybe):
   select id, lastRowsNotNull(name) as name, lastRowsNotNull(age) as age ,lastRowsNotNull(tel) as tel from Table group by id;

           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Alex    |    20     |  7834xx

What do I do? pleas?


问:
Ajax doesn't return json if there is text in php file
I'm pretty new to Jquery Ajax and sorry if that's a simple thing.

So my problem here is that I want to retrieve a json object from my php file, but it only works when I echo only one Json object like this :

```<code><?php
header('Content-type: application/json; charset=utf-8');
$arr = array ('Lastname'=>'Doe','Firstname'=>'John','Age'=>109);
echo json_encode($arr);
</code>```

When I want to echo another json or some text returned as json in my javascript file, I don't get anything back from the ajax call.

```<code>  <?php
// This code doesn't work
    header('Content-type: application/json; charset=utf-8');
    $arr = array ('Lastname'=>'Doe','Firstname'=>'John','Age'=>109);
    echo 'hi there';
    $json = 'Hello people';
    echo json_encode($json);
    echo json_encode($arr);
</code>```

My ajax call is this :

```<code>$.ajax({
        url: 'test.php',
        type: 'GET',
        success: function (response) {
            console.log(response);
        }
    });
</code>```

So my final question is : what's wrong in my code, and what's not allowed in ajax call

答:
So, the output of this code

// This code doesn't work
header('Content-type: application/json; charset=utf-8');
$arr = array ('Lastname'=>'Doe','Firstname'=>'John','Age'=>109);
echo 'hi there';
$json = 'Hello people';
echo json_encode($json);
echo json_encode($arr);
```

<p>Will be:</p>

<pre class="lang-php prettyprint-override"><code>hi there"Hello people"{"Lastname":"Doe","Firstname":"John","Age":109}
</code>```

Which is not valid JSON

Correct way of responding with JSON is to use just one call to json_encode:

header('Content-type: application/json; charset=utf-8')
$response = [
    'message' => 'hi there',
    'people' => [
        ['Lastname'=>'Doe', 'Firstname'=>'John', 'Age'=>109],
    ],
];
echo json_encode($response);
```

Body:
I'm pretty new to Jquery Ajax and sorry if that's a simple thing.

So my problem here is that I want to retrieve a json object from my php file, but it only works when I echo only one Json object like this :

<?php
header('Content-type: application/json; charset=utf-8');
$arr = array ('Lastname'=>'Doe','Firstname'=>'John','Age'=>109);
echo json_encode($arr);

When I want to echo another json or some text returned as json in my javascript file, I don't get anything back from the ajax call.

  <?php
// This code doesn't work
    header('Content-type: application/json; charset=utf-8');
    $arr = array ('Lastname'=>'Doe','Firstname'=>'John','Age'=>109);
    echo 'hi there';
    $json = 'Hello people';
    echo json_encode($json);
    echo json_encode($arr);

My ajax call is this :

$.ajax({
        url: 'test.php',
        type: 'GET',
        success: function (response) {
            console.log(response);
        }
    });

So my final question is : what's wrong in my code, and what's not allowed in ajax call

Body:
So, the output of this code

// This code doesn't work
header('Content-type: application/json; charset=utf-8');
$arr = array ('Lastname'=>'Doe','Firstname'=>'John','Age'=>109);
echo 'hi there';
$json = 'Hello people';
echo json_encode($json);
echo json_encode($arr);

Will be:

hi there"Hello people"{"Lastname":"Doe","Firstname":"John","Age":109}

Which is not valid JSON

Correct way of responding with JSON is to use just one call to json_encode:

header('Content-type: application/json; charset=utf-8')
$response = [
    'message' => 'hi there',
    'people' => [
        ['Lastname'=>'Doe', 'Firstname'=>'John', 'Age'=>109],
    ],
];
echo json_encode($response);


问:
How to print the "instantiated" variable in Python OOP?
I am studying the book "Learn Python the Hard Way" with Python3. The author presented the concept of OOP with this example:

```<code>class Song (object):

    def __init__(self,lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print (line)

happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family","With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()
</code>```

OOP is kind of funny to me. The author suggest that we should "trash", "break" and "thrash" the code above a little bit.

I was trying to print the variable name in which the object was "instanced" (not sure if "instanced" is the correct word here, maybe the correct word is "instantiated"). In order to try that, I added the following methods on the class Songs():

```<code>class Song (object):

    def __init__(self,lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print (line)

    def name_of_var(self):
        print (Song)

    def name_of_var_2(self):
        print (object)

    def name_of_var_3(self):
        print (self)

    def name_of_var_3(self):
        print (self)
</code>```

I used the examples of objects provided by the author:

```<code>happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family","With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()
</code>```

Finally, I tried doing:

```<code>print(Song(["They rally around the family","With pockets full of shells"]))

print (happy_bday.name_of_var())

print (happy_bday.name_of_var_2())

print (happy_bday.name_of_var_3())

print (happy_bday.__init__(happy_bday))
</code>```

I wasn't able to achieve my goal. Using the methods above I got:

```<code><__main__.Song object at 0x7f4b784f3da0>
<class '__main__.Song'>
None
<class 'object'>
None
<__main__.Song object at 0x7f4b784f3d30>
None
None
pedr
</code>```

My objective was to create some method in which I would do:

```<code>print (happy_bday.__some__method())
</code>```

And the program would return:

```<code>happy_bday
</code>```

Maybe that's not even possible in Python... If I am not wrong, you can do this type of thing in Lisp/Racket (but I am not 100% sure). Is this possible in Python? How can I do that?

答:
Others have commented on why what you want to do is unnecessary (and possibly undesirable). But it isn't actually true that it's impossible. After all, globals() is a dictionary of the objects and their references in global scope, and is designed for introspection of this sort. So you could define a method for your class that returns the names of all identifiers for an instance of that class. For example:

```<code>class Song():
    def __init__(self,lyrics):
        self.lyrics = lyrics
    def sing_me_a_song(self):
        for line in self.lyrics:
            print (line)

    def names_of_var(self):
       for k in globals().keys():
            if globals()[k] == self:
                print(k)

In [32]: happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])
In [33]: happy_bday2 = happy_bday
In [34]: happy_bday.names_of_var()
happy_bday
happy_bday2
</code>```

Of course, this only works if you defined your Songs in global scope (not e.g. within some function).

Body:
I am studying the book "Learn Python the Hard Way" with Python3. The author presented the concept of OOP with this example:

class Song (object):

    def __init__(self,lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print (line)

happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family","With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()

OOP is kind of funny to me. The author suggest that we should "trash", "break" and "thrash" the code above a little bit.

I was trying to print the variable name in which the object was "instanced" (not sure if "instanced" is the correct word here, maybe the correct word is "instantiated"). In order to try that, I added the following methods on the class Songs():

class Song (object):

    def __init__(self,lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print (line)

    def name_of_var(self):
        print (Song)

    def name_of_var_2(self):
        print (object)

    def name_of_var_3(self):
        print (self)

    def name_of_var_3(self):
        print (self)

I used the examples of objects provided by the author:

happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family","With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()

Finally, I tried doing:

print(Song(["They rally around the family","With pockets full of shells"]))

print (happy_bday.name_of_var())

print (happy_bday.name_of_var_2())

print (happy_bday.name_of_var_3())

print (happy_bday.__init__(happy_bday))

I wasn't able to achieve my goal. Using the methods above I got:

<__main__.Song object at 0x7f4b784f3da0>
<class '__main__.Song'>
None
<class 'object'>
None
<__main__.Song object at 0x7f4b784f3d30>
None
None
pedr

My objective was to create some method in which I would do:

print (happy_bday.__some__method())

And the program would return:

happy_bday

Maybe that's not even possible in Python... If I am not wrong, you can do this type of thing in Lisp/Racket (but I am not 100% sure). Is this possible in Python? How can I do that?

Body:
Others have commented on why what you want to do is unnecessary (and possibly undesirable). But it isn't actually true that it's impossible. After all, globals() is a dictionary of the objects and their references in global scope, and is designed for introspection of this sort. So you could define a method for your class that returns the names of all identifiers for an instance of that class. For example:

class Song():
    def __init__(self,lyrics):
        self.lyrics = lyrics
    def sing_me_a_song(self):
        for line in self.lyrics:
            print (line)

    def names_of_var(self):
       for k in globals().keys():
            if globals()[k] == self:
                print(k)

In [32]: happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])
In [33]: happy_bday2 = happy_bday
In [34]: happy_bday.names_of_var()
happy_bday
happy_bday2

Of course, this only works if you defined your Songs in global scope (not e.g. within some function).


问:
better understanding type promotion of variadic parameters in c
When a variable argument function is called in c the integer parameters are promoted to int and floating point parameters are promoted to double

Since the prototype doesn’t specify types for optional arguments, in a call to a variadic function the default argument promotions are performed on the optional argument values. This means the objects of type char or short int (whether signed or not) are promoted to either int or unsigned int, as appropriate; and that objects of type float are promoted to type double. So, if the caller passes a char as an optional argument, it is promoted to an int, and the function can access it with va_arg (ap, int).

int type should be 4 byte on 32 bit machines and 8 byte on 64 bit machines, is that right?

So I wonder what append when I pass a long long int to a variable argument function like printf with %lld format.

And, again, I wonder what append when I pass a long double variable to printf with %Lf format (no matter if on 32 or 64 bit machines).

[Edited]

on a 32 bit machine, I tried this:

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

int main(void)
{
    printf("sizeof(int) %d\n", sizeof(int));
    printf("sizeof(long int) %d\n", sizeof(long int));
    printf("sizeof(long long int) %d\n", sizeof(long long int));
    printf("%lld\n", 1LL<<33);

    printf("sizeof(float) %d\n", sizeof(float));
    printf("sizeof(double) %d\n", sizeof(double));
    printf("sizeof(long double) %d\n", sizeof(long double));
    return 0;
}
</code>```

The result is:

```<code>sizeof(int) 4
sizeof(long int) 4
sizeof(long long int) 8
8589934592
sizeof(float) 4
sizeof(double) 8
sizeof(long double) 12
</code>```

this makes me think that not all parameters are promoted to int, otherwise I would get printed 0 instead of 8589934592.

Maybe only arguments smaller than int are promoted to int. And something similar could be for floating point types.

[Edited]

on a 64 bit machine I run this:

```<code>int main(void)
{
    printf("sizeof(int) %lu\n", sizeof(int));
    printf("sizeof(long) %lu\n", sizeof(long));
    printf("sizeof(long long) %lu\n", sizeof(long long));
    return 0;
}
</code>```

and get

```<code>sizeof(int) 4
sizeof(long) 8
sizeof(long long) 8
</code>```

if I understand well the standard, only char and short are promoted to int. I wonder what happen in smaller architecture, such like 16 bit or 8 bit MCU. I think that int size is dependent by architecture, but I wonder if sizeof(int) can be 1 on 8 bit architecture. In this case promotion of short to int could be impossible unless loosing some bits

答:
"int type should be 4 byte on 32 bit machines and 8 byte on 64 bit machines, is that right?" No. According to the Standard, ints must be at least 16 bits in width (§5.2.4.2.1), but there is no further stipulation.

When you pass a long long int to printf() it is not subject to the integer promotions (§6.3.1.1 2):

The following may be used in an expression wherever an int or unsigned
  int may be used:

An object or expression with an integer type (other than int or unsigned int) whose integer conversion rank is less than or equal to
  the rank of int and unsigned int.

A bit-field of type _Bool, int, signed int, or unsigned int.

If an int can represent all values of the original type (as restricted
  by the width, for a bit-field), the value is converted to an int;
  otherwise, it is converted to an unsigned int. These are called the
  integer promotions.58) All other types are unchanged by the integer
  promotions.

If you pass a long double to printf() no conversion is made (§6.5.2.2 6):

If the expression that denotes the called function has a type that
  does not include a prototype, the integer promotions are performed on
  each argument, and arguments that have type float are promoted to
  double. These are called the default argument promotions.

The conversion specifiers corresponding to the arguments in the printf() statement have no bearing on these promotions and conversions, except insofar as there will be undefined behavior if the specifiers and the types of their corresponding arguments do not match.

So, the integer promotions are performed, and floats are converted to doubles, but "No other conversions are performed implicitly" (§6.5.2.2 8).

Addressing your edit to the question: "this makes me think that not all parameters are promoted to int." Correct. Only integer types with integer conversion rank "less than or equal to the rank of int and unsigned int" are subject to integer promotion. It is simpler for floating point types; floats are promoted to double. That is all.

It may be worth pointing out that, according to §6.2.5 10, there are three real floating point types, float, double, and long double. The values which may be held by a float are a subset of the values which may be held by a double, which are in turn a subset of the values which may be held by a long double. Hence, there is no possibility of promotion for long double types.

Further, according to §6.3.1.1 1:

The rank of long long int shall be greater than the rank of long int,
  which shall be greater than the rank of int, which shall be greater
  than the rank of short int, which shall be greater than the rank of
  signed char.

So there is no possibility of a long long int or long int ever being promoted to int or unsigned int.

As for your final concern that promotion of a short to an int may, in some implementation, be impossible without losing some bits, note that §6.2.5 8 guarantees that an int must be able to contain a short, since the conversion rank of an int must be greater than that of a short:

For any two integer types with the same signedness and different
  integer conversion rank (see 6.3.1.1), the range of values of the type
  with smaller integer conversion rank is a subrange of the values of
  the other type.

Body:
When a variable argument function is called in c the integer parameters are promoted to int and floating point parameters are promoted to double

Since the prototype doesn’t specify types for optional arguments, in a call to a variadic function the default argument promotions are performed on the optional argument values. This means the objects of type char or short int (whether signed or not) are promoted to either int or unsigned int, as appropriate; and that objects of type float are promoted to type double. So, if the caller passes a char as an optional argument, it is promoted to an int, and the function can access it with va_arg (ap, int).

int type should be 4 byte on 32 bit machines and 8 byte on 64 bit machines, is that right?

So I wonder what append when I pass a long long int to a variable argument function like printf with %lld format.

And, again, I wonder what append when I pass a long double variable to printf with %Lf format (no matter if on 32 or 64 bit machines).

[Edited]

on a 32 bit machine, I tried this:

#include <stdio.h>

int main(void)
{
    printf("sizeof(int) %d\n", sizeof(int));
    printf("sizeof(long int) %d\n", sizeof(long int));
    printf("sizeof(long long int) %d\n", sizeof(long long int));
    printf("%lld\n", 1LL<<33);

    printf("sizeof(float) %d\n", sizeof(float));
    printf("sizeof(double) %d\n", sizeof(double));
    printf("sizeof(long double) %d\n", sizeof(long double));
    return 0;
}

The result is:

sizeof(int) 4
sizeof(long int) 4
sizeof(long long int) 8
8589934592
sizeof(float) 4
sizeof(double) 8
sizeof(long double) 12

this makes me think that not all parameters are promoted to int, otherwise I would get printed 0 instead of 8589934592.

Maybe only arguments smaller than int are promoted to int. And something similar could be for floating point types.

[Edited]

on a 64 bit machine I run this:

int main(void)
{
    printf("sizeof(int) %lu\n", sizeof(int));
    printf("sizeof(long) %lu\n", sizeof(long));
    printf("sizeof(long long) %lu\n", sizeof(long long));
    return 0;
}

and get

sizeof(int) 4
sizeof(long) 8
sizeof(long long) 8

if I understand well the standard, only char and short are promoted to int. I wonder what happen in smaller architecture, such like 16 bit or 8 bit MCU. I think that int size is dependent by architecture, but I wonder if sizeof(int) can be 1 on 8 bit architecture. In this case promotion of short to int could be impossible unless loosing some bits


问:
Program not responding to linux signals sent from terminal without continuous printing on terminal
I have a C program that goes like:

```<code>while(1){
    if(flag1){
         ...
    }
    if(flag2){
         ...
    }
}
</code>```

Now these flags will be raised in handlers for SIGINT AND SIGTSTP signals. The terminal just shows     ^C and ^Z when Ctrl+C or Ctrl+Z is entered, but the conditional code blocks are not executed.

However the exact same program, but if I give a printf like below:

```<code>while(1){
    printf("  ");
    if(flag1){
         ...
    }
    if(flag2){
         ...
    }
}
</code>```

The program responds to the Ctrl+Z or Ctrl+C signals, and the respective conditional code blocks are executed.
Could someone explain this behavior? I am not sure why keeping the terminal busy with something being printed continuously, makes my program respond to the signals, while not otherwise.

答:
The conditional code blocks could be optimized out, because compiler doesn't know these variables can change out of the loop. Define flags as volatile, i.e.

```<code>volatile int flag1;
...
</code>```

This way compiler knows not to make any assumptions about the values of these variables.

Body:
I have a C program that goes like:

while(1){
    if(flag1){
         ...
    }
    if(flag2){
         ...
    }
}

Now these flags will be raised in handlers for SIGINT AND SIGTSTP signals. The terminal just shows     ^C and ^Z when Ctrl+C or Ctrl+Z is entered, but the conditional code blocks are not executed.

However the exact same program, but if I give a printf like below:

while(1){
    printf("  ");
    if(flag1){
         ...
    }
    if(flag2){
         ...
    }
}

The program responds to the Ctrl+Z or Ctrl+C signals, and the respective conditional code blocks are executed.
Could someone explain this behavior? I am not sure why keeping the terminal busy with something being printed continuously, makes my program respond to the signals, while not otherwise.

Body:
The conditional code blocks could be optimized out, because compiler doesn't know these variables can change out of the loop. Define flags as volatile, i.e.

volatile int flag1;
...

This way compiler knows not to make any assumptions about the values of these variables.


问:
Execute Multiple SQL Server Queries for 2 Linked Servers
I have 2 Linked Servers "NewDump" and "OldDump" (Dumps from different dates). I have queries to compare tables from these dumps (like FTM$, FSF$ etc). Each query compares a table between these linked server. Is there a way i can run all these ".SQL" queries (FTM.SQL and FSF.SQL) using a batch file together for automation

eg queries: FTM.SQL

```<code>FROM (
SELECT  *
FROM NewDump...FTM$) t1

FULL OUTER JOIN (
SELECT *
FROM OldDump...FTM$) t2

ON t1.id = t2.id
WHERE

t1.id IS NULL OR
t2.id IS NULL
</code>```

eg FSF.SQL Query

```<code>FROM (
SELECT  *
FROM NewDump...FSF$) t1

FULL OUTER JOIN (
SELECT *
FROM OldDump...FSF$) t2

ON t1.id = t2.id
WHERE

t1.id IS NULL OR
t2.id IS NULL
</code>```

The Queries FSF.SQL and FTM.SQL are stored in C:\Users\user\Documents\SQL Server Management Studio\Queries

答:
This query worked for me to run multiple .SQL files. </p>

```<code>SET NOCOUNT ON
GO
PRINT 'Start...'
:On Error exit

   :r C:\Queries\FTM.sql
   :r C:\Queries\FSF.sql

PRINT 'Finish...'
GO
</code>```

Body:
I have 2 Linked Servers "NewDump" and "OldDump" (Dumps from different dates). I have queries to compare tables from these dumps (like FTM$, FSF$ etc). Each query compares a table between these linked server. Is there a way i can run all these ".SQL" queries (FTM.SQL and FSF.SQL) using a batch file together for automation

eg queries: FTM.SQL

FROM (
SELECT  *
FROM NewDump...FTM$) t1

FULL OUTER JOIN (
SELECT *
FROM OldDump...FTM$) t2

ON t1.id = t2.id
WHERE

t1.id IS NULL OR
t2.id IS NULL

eg FSF.SQL Query

FROM (
SELECT  *
FROM NewDump...FSF$) t1

FULL OUTER JOIN (
SELECT *
FROM OldDump...FSF$) t2

ON t1.id = t2.id
WHERE

t1.id IS NULL OR
t2.id IS NULL

The Queries FSF.SQL and FTM.SQL are stored in C:\Users\user\Documents\SQL Server Management Studio\Queries

Body:
This query worked for me to run multiple .SQL files.

SET NOCOUNT ON
GO
PRINT 'Start...'
:On Error exit

   :r C:\Queries\FTM.sql
   :r C:\Queries\FSF.sql

PRINT 'Finish...'
GO


问:
Support native recursion
I read an article about recursion in Haskell that says:

But the lambda calculus does not appear on the surface to have any
  means of recursion, because of the anonymity of expressions. How do
  you call something without a name? Being able to write recursive
  functions, though, is essential to Turing completeness. We use a
  combinator – known as the Y combinator or fixed-point combinator – to
  write recursive functions in the lambda calculus. Haskell has native
  recursion ability based on the same principle as the Y combinator.

What does native recursion mean?

Consider following code snippet:

```<code>applyTimes :: (Eq a, Num a) => a -> (b -> b) -> b -> b
applyTimes 0 f b = b
applyTimes n f b = f (applyTimes (n-1) f b)
</code>```

The above code does not conform Y combinator principle, because applyTimes is called in function body itself and it does not defined before.

Please proof my answer, if I wrong.

答:
The above code does not conform to the Y combinator principle, because applyTimes is called in function body itself and it does not defined before.

What about something like this?

```<code>fix :: (a -> a) -> a
fix f = f (fix f)

applyTimes :: (Eq a, Num a) => a -> (b -> b) -> b -> b
applyTimes n f b = fix go n where

  go rec n = if n == 0 then b
             else f (rec (n - 1))
</code>```

Title: Support native recursion

Body:
I read an article about recursion in Haskell that says:

But the lambda calculus does not appear on the surface to have any
  means of recursion, because of the anonymity of expressions. How do
  you call something without a name? Being able to write recursive
  functions, though, is essential to Turing completeness. We use a
  combinator – known as the Y combinator or fixed-point combinator – to
  write recursive functions in the lambda calculus. Haskell has native
  recursion ability based on the same principle as the Y combinator.

What does native recursion mean?

Consider following code snippet:

applyTimes :: (Eq a, Num a) => a -> (b -> b) -> b -> b
applyTimes 0 f b = b
applyTimes n f b = f (applyTimes (n-1) f b)

The above code does not conform Y combinator principle, because applyTimes is called in function body itself and it does not defined before.

Please proof my answer, if I wrong.

Body:
The above code does not conform to the Y combinator principle, because applyTimes is called in function body itself and it does not defined before.

What about something like this?

fix :: (a -> a) -> a
fix f = f (fix f)

applyTimes :: (Eq a, Num a) => a -> (b -> b) -> b -> b
applyTimes n f b = fix go n where

  go rec n = if n == 0 then b
             else f (rec (n - 1))


问:
Shiny deployment error
When I am trying to deploy my shiny app at shinyapps.io I get below error :

```<code>> deployApp()
Preparing to deploy application...DONE
Uploading bundle for application: 187055...DONE
Deploying bundle: 857060 for application: 187055 ...
Waiting for task: 416072120
  building: Processing bundle: 857060
  building: Parsing manifest
  building: Building image: 849457
  building: Installing system dependencies
################################ Begin Task Log ################################
[2017-06-07T17:28:40.200495546+0000] Execute script: packages/build/nloptr.sh
+ set -e
+ VERSION=2.4.2
+ cd /tmp
+ curl -O http://ab-initio.mit.edu/nlopt/nlopt-2.4.2.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0################################# End Task Log #################################
Error: Unhandled Exception: Child Task 416072122 failed: Error building image: Build exited with non-zero status: 56
</code>```

Has anyone come across this error. Appreciate if someone help me on how to resolve this. I am using R version 3.4.0

Thanks,

答:
It looks like your app require NLopt, but shinyapps.io failed to install the package. The package installation seemed to be some shell script which may not work in the shinyapps.io server(because of permission etc).

Basically the deployment process scan your file and environment, then try to duplicate the dependency packages in the server. If you used CRAN version the server will also install CRAN version, which should not need build from source or running some shell script. If you used github version server will also try to use github version or build from source, which could have more dependency requirement.

Another possibility is the R package is just the interface and you need to install the actual library, which failed to be installed in server.

R packages will often rely on operating system packages to be
  installed on the server. If your application happens to use an R
  package that requires a system library that is not installed by
  default, please let us know by filing an issue, or a pull request, at
  shinyapps-package-dependencies

Title: Shiny deployment error

Body:
When I am trying to deploy my shiny app at shinyapps.io I get below error :

> deployApp()
Preparing to deploy application...DONE
Uploading bundle for application: 187055...DONE
Deploying bundle: 857060 for application: 187055 ...
Waiting for task: 416072120
  building: Processing bundle: 857060
  building: Parsing manifest
  building: Building image: 849457
  building: Installing system dependencies
################################ Begin Task Log ################################
[2017-06-07T17:28:40.200495546+0000] Execute script: packages/build/nloptr.sh
+ set -e
+ VERSION=2.4.2
+ cd /tmp
+ curl -O http://ab-initio.mit.edu/nlopt/nlopt-2.4.2.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0################################# End Task Log #################################
Error: Unhandled Exception: Child Task 416072122 failed: Error building image: Build exited with non-zero status: 56

Has anyone come across this error. Appreciate if someone help me on how to resolve this. I am using R version 3.4.0

Thanks,


问:
How to erase specific data in file python
I cant seem to write each line in a file so Its like a one long string like :
"a,1;b,2;c,3". I want to write a method that deletes "b,2" for example. Also, I cant write it with lines and that why im a bit confused and stuck... Thnks for all the helpers.</p>

```<code>class Data:

def __init__(self):

    print "are you ready?? :)"

def add_data(self, user_name, password):

    add = open("user_data.txt", "a")
    add.write(user_name + "," + password + ";")
    add.close()

def show_file(self):

    file = open("user_data.txt", "r")
    print file.read()
    file.close()

def erase_all(self):

    file = open("user_data.txt", "w")
    file.write("")
    file.close()

def return_names(self):

    file = open("user_data.txt", "r")
    users_data = file.read()
    users_data = users_data.split(";")
    names = []

    for data in users_data:

        data = data.split(",")
        names.append(data[0])

    file.close()
    return names

def is_signed(self, user_name):

    names = self.return_names()

    for name in names:

        if user_name == name:

            return True

    return False

def is_password(self, user_name, password):

    file = open("user_data.txt", "r")
    users_data = file.read()
    users_data = users_data.split(";")

    for data in users_data:

        data = data.split(",")

        if data[0] == user_name:

            if data[1] == password:

                return True

    file.close()

    return False

def erase_user(self, user_name):

    pass
</code>```

答:
As mentioned in the comments, you'll want to include newlines each time you write a line to the file.
Just a suggestion, to make file handling easier you may want to consider using with open() each time you access the file.

So altogether, for example for the first class methods:

```<code>def add_data(self, user_name, password):
        with open('user_data.txt', 'a') as add:
            add.write(user_name + ',' + password + ';')
            add.write('\n') # <-- this is the important new line to include

    def show_file(self):
        with open('user_data.txt') as show:
            print show.readlines()
</code>```

... and similar for other methods.

As for the method that deletes a user entry from the file:

```<code># taken from https://stackoverflow.com/a/4710090/1248974
def erase_user(self, un, pw):
    with open('user_data.txt', 'r') as f:
        lines = f.readlines()

    with open('user_data.txt', 'w') as f:
        for line in lines:
            user_name, password = line.split(',')[0], line.split(',')[1].strip('\n').strip(';')
            if un != user_name and pw != password:
                f.write(','.join([user_name, password]))
                f.write(';\n')
</code>```

test:

```<code>d = Data()
d.erase_all()
d.add_data('a','1')
d.add_data('b','2')
d.add_data('c','3')
d.show_file()
d.erase_user('b','2')
print 'erasing a user...'
d.show_file()
</code>```

output:

```<code>are you ready?? :)
['a,1;\n', 'b,2;\n', 'c,3;\n']
erasing a user...
['a,1;\n', 'c,3;\n']
</code>```

confirm line entry was removed from textfile:

```<code>a,1;
c,3;
</code>```

Hope this helps.

Body:
I cant seem to write each line in a file so Its like a one long string like :
"a,1;b,2;c,3". I want to write a method that deletes "b,2" for example. Also, I cant write it with lines and that why im a bit confused and stuck... Thnks for all the helpers.

class Data:

def __init__(self):

    print "are you ready?? :)"

def add_data(self, user_name, password):

    add = open("user_data.txt", "a")
    add.write(user_name + "," + password + ";")
    add.close()

def show_file(self):

    file = open("user_data.txt", "r")
    print file.read()
    file.close()

def erase_all(self):

    file = open("user_data.txt", "w")
    file.write("")
    file.close()

def return_names(self):

    file = open("user_data.txt", "r")
    users_data = file.read()
    users_data = users_data.split(";")
    names = []

    for data in users_data:

        data = data.split(",")
        names.append(data[0])

    file.close()
    return names

def is_signed(self, user_name):

    names = self.return_names()

    for name in names:

        if user_name == name:

            return True

    return False

def is_password(self, user_name, password):

    file = open("user_data.txt", "r")
    users_data = file.read()
    users_data = users_data.split(";")

    for data in users_data:

        data = data.split(",")

        if data[0] == user_name:

            if data[1] == password:

                return True

    file.close()

    return False

def erase_user(self, user_name):

    pass

Body:
As mentioned in the comments, you'll want to include newlines each time you write a line to the file.
Just a suggestion, to make file handling easier you may want to consider using with open() each time you access the file.

So altogether, for example for the first class methods:

def add_data(self, user_name, password):
        with open('user_data.txt', 'a') as add:
            add.write(user_name + ',' + password + ';')
            add.write('\n') # <-- this is the important new line to include

    def show_file(self):
        with open('user_data.txt') as show:
            print show.readlines()

... and similar for other methods.

As for the method that deletes a user entry from the file:

# taken from https://stackoverflow.com/a/4710090/1248974
def erase_user(self, un, pw):
    with open('user_data.txt', 'r') as f:
        lines = f.readlines()

    with open('user_data.txt', 'w') as f:
        for line in lines:
            user_name, password = line.split(',')[0], line.split(',')[1].strip('\n').strip(';')
            if un != user_name and pw != password:
                f.write(','.join([user_name, password]))
                f.write(';\n')

test:

d = Data()
d.erase_all()
d.add_data('a','1')
d.add_data('b','2')
d.add_data('c','3')
d.show_file()
d.erase_user('b','2')
print 'erasing a user...'
d.show_file()

output:

are you ready?? :)
['a,1;\n', 'b,2;\n', 'c,3;\n']
erasing a user...
['a,1;\n', 'c,3;\n']

confirm line entry was removed from textfile:

a,1;
c,3;

Hope this helps.


问:
How to apply TFIDF to find important words in csv file using pycharm
I have a file that includes some data,

An example of the data I have

```<code>+------------+---------------------------------+-------------------------+
|  SOC Code  |              Title              |  Occupational Category  |
+------------+---------------------------------+-------------------------+
| 11-1011.03 | Chief Sustainability Officers   | New & Emerging          |
| 11-1021.00 | General and Operations Managers | Enhanced Skills         |
+------------+---------------------------------+-------------------------+
</code>```

I need to find the most frequent words in the file
Any ideas on how can this be applied? pieces of codes would be appreciated as an example

答: You could count the words using the NLTK FreqDist method and return the most frequent ones.

Body:
I have a file that includes some data,

An example of the data I have

+------------+---------------------------------+-------------------------+
|  SOC Code  |              Title              |  Occupational Category  |
+------------+---------------------------------+-------------------------+
| 11-1011.03 | Chief Sustainability Officers   | New & Emerging          |
| 11-1021.00 | General and Operations Managers | Enhanced Skills         |
+------------+---------------------------------+-------------------------+

I need to find the most frequent words in the file
Any ideas on how can this be applied? pieces of codes would be appreciated as an example


问:
How to compile a TypeScript project to a single JS file so it is usable in browser
I have to write a Javascript SDK for a little project I am working on. To do that, I had thought of creating a TypeScript project and compiling it to a single Javascript file, so the users of my SDK could just inject that file in their web pages.

However, I just came to know that if I use import, and try to compile to a single file, then it only supports SystemJS.

So, how to compile a TypeScript project to a single JS file so it is usable in browser?

By usable in browser, I mean that if I create a class App in TypeScript, then I could do this in dev console:

```<code>var x = new App();
</code>```

I have been at this for more than a hour now, and everything I have found seems to suggest that this is not possible.

Edit: This doesn't really answer my question. Like I said in the example, I need the functionality that if there is a class called App in my TypeScript project, it should be visible to the browser with the same name, so I could do var x = new App() in my dev console. (Or a user can do this in his JS file that he injects after injecting my SDK file). That answer is just telling how to create an outfile in SystemJS.

答:
For this you can use webpack, it is a Node.JS utility that attempts to bundle Node.JS-like modules. Webpack doesn't automatically export modules to the global object, but generates (or attempts to generate) a function that replace the Node.JS's default require, which is used to execute the entry module and others, thus you can modify this function for exporting each module (or properties of each module) in the global object.

(In TypeScript, use the CommonJS module. Second, install and use the ts-loader plugin among with webpack, so you'll directly compile TypeScript from webpack.)

Maybe that applies to Webpack 2. For example, you modify the __webpack_require__ function. It is not inside the global object and thus you must interfere in the webpack's generated source code, at function __webpack_require__:

```<code>function __webpack_require__(moduleId) {
    // [...] (After the `if (installedModules...) ...`)
    /*
     * You don't have access to the module name, so export each
     * property to the browser's global object.
     */
    var exports = module.exports;
    for (var key in exports)
        window[key] = exports[key];
}
</code>```

Body:
I have to write a Javascript SDK for a little project I am working on. To do that, I had thought of creating a TypeScript project and compiling it to a single Javascript file, so the users of my SDK could just inject that file in their web pages.

However, I just came to know that if I use import, and try to compile to a single file, then it only supports SystemJS.

So, how to compile a TypeScript project to a single JS file so it is usable in browser?

By usable in browser, I mean that if I create a class App in TypeScript, then I could do this in dev console:

var x = new App();

I have been at this for more than a hour now, and everything I have found seems to suggest that this is not possible.

Edit: This doesn't really answer my question. Like I said in the example, I need the functionality that if there is a class called App in my TypeScript project, it should be visible to the browser with the same name, so I could do var x = new App() in my dev console. (Or a user can do this in his JS file that he injects after injecting my SDK file). That answer is just telling how to create an outfile in SystemJS.

Body:
For this you can use webpack, it is a Node.JS utility that attempts to bundle Node.JS-like modules. Webpack doesn't automatically export modules to the global object, but generates (or attempts to generate) a function that replace the Node.JS's default require, which is used to execute the entry module and others, thus you can modify this function for exporting each module (or properties of each module) in the global object.

(In TypeScript, use the CommonJS module. Second, install and use the ts-loader plugin among with webpack, so you'll directly compile TypeScript from webpack.)

Maybe that applies to Webpack 2. For example, you modify the __webpack_require__ function. It is not inside the global object and thus you must interfere in the webpack's generated source code, at function __webpack_require__:

function __webpack_require__(moduleId) {
    // [...] (After the `if (installedModules...) ...`)
    /*
     * You don't have access to the module name, so export each
     * property to the browser's global object.
     */
    var exports = module.exports;
    for (var key in exports)
        window[key] = exports[key];
}


问:
NServiceBus: "ArgumentNullException" being thrown by NServiceBus
I am trying to call Bus.Publish to publish a message, but I can't tell what's wrong, because the exception from NSB is just that there is a null argument.

Here is the stack trace:

```<code>System.ArgumentNullException: Value cannot be null.
Parameter name: key
   at System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at NServiceBus.Serializers.XML.MessageSerializer.WriteObject(String name, Type type, Object value, StringBuilder builder)
   at NServiceBus.Serializers.XML.MessageSerializer.Serialize(IMessage[] messages, Stream stream)
   at NServiceBus.Unicast.Transport.Msmq.MsmqTransport.Send(TransportMessage m, String destination)
   at NServiceBus.Unicast.UnicastBus.SendMessage(IEnumerable`1 destinations, String correlationId, MessageIntentEnum messageIntent, IMessage[] messages)
   at NServiceBus.Unicast.UnicastBus.Publish[T](T[] messages)
</code>```

Can anyone help?

答: Found the answer.  Apparently it is illegal in NServiceBus to use a message type which is not declared in a namespace.  Don't ask me why, but the legacy code containing the type I wanted to publish didn't declare the type in a namespace so I had to make a new type to get it to work.</p>

Body:
I am trying to call Bus.Publish to publish a message, but I can't tell what's wrong, because the exception from NSB is just that there is a null argument.

Here is the stack trace:

System.ArgumentNullException: Value cannot be null.
Parameter name: key
   at System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at NServiceBus.Serializers.XML.MessageSerializer.WriteObject(String name, Type type, Object value, StringBuilder builder)
   at NServiceBus.Serializers.XML.MessageSerializer.Serialize(IMessage[] messages, Stream stream)
   at NServiceBus.Unicast.Transport.Msmq.MsmqTransport.Send(TransportMessage m, String destination)
   at NServiceBus.Unicast.UnicastBus.SendMessage(IEnumerable`1 destinations, String correlationId, MessageIntentEnum messageIntent, IMessage[] messages)
   at NServiceBus.Unicast.UnicastBus.Publish[T](T[] messages)

Can anyone help?


问:
postgres count with like condition
I am new to Postgres and trying to figure out how can i improve performance of count query with 'Like' in where clause.

```<code>    select    count(*)
    from master_data
    where name ilike '%<userInput>%';
</code>```

I am even fine with estimated value.I googled few links and found out we can quickly get a count of entire table by using below query.

```<code> SELECT reltuples AS approximate_row_count FROM pg_class WHERE relname = '<TableName>';
</code>```

However for count with  like condition i am still not able to figure out.
Please suggest.Below are the links which i referred already.

https://wiki.postgresql.org/wiki/Count_estimate

https://www.citusdata.com/blog/2016/10/12/count-performance/#dup_counts_estimated_filtered

Postgres Version - 9.5.4

答: You might be interested in a trigram index.  This can specifically handle like with wildcards.  You can start with the documentation.

Title: postgres count with like condition

Body:
I am new to Postgres and trying to figure out how can i improve performance of count query with 'Like' in where clause.

    select    count(*)
    from master_data
    where name ilike '%<userInput>%';

I am even fine with estimated value.I googled few links and found out we can quickly get a count of entire table by using below query.

 SELECT reltuples AS approximate_row_count FROM pg_class WHERE relname = '<TableName>';

However for count with  like condition i am still not able to figure out.
Please suggest.Below are the links which i referred already.

https://wiki.postgresql.org/wiki/Count_estimate

https://www.citusdata.com/blog/2016/10/12/count-performance/#dup_counts_estimated_filtered

Postgres Version - 9.5.4


问:
how can write a cell into csv file
I have a cell that contains 4 columns(string-double-double-double).
I want save this cell in a csv file and I wrote this code:

```<code>fid = fopen('1.csv', 'w') ;
fprintf(fid, '%s\n', mycell{:,1}) ;
fclose(fid) ;
dlmwrite('1.csv', mycell(:,2:end), '-append') ;
</code>```

but this code write the first column. then write other columns down of first column. but I want 4 columns Place side by side as described above.

this picture is a sample of my data:

答:
You can simply write:</p>

```<code>xlswrite('1.csv',mycell);
</code>```

Title: how can write a cell into csv file

Body:
I have a cell that contains 4 columns(string-double-double-double).
I want save this cell in a csv file and I wrote this code:

fid = fopen('1.csv', 'w') ;
fprintf(fid, '%s\n', mycell{:,1}) ;
fclose(fid) ;
dlmwrite('1.csv', mycell(:,2:end), '-append') ;

but this code write the first column. then write other columns down of first column. but I want 4 columns Place side by side as described above.

this picture is a sample of my data:

Body:
You can simply write:

xlswrite('1.csv',mycell);


问:
I am having trouble in reading date and time from an excel sheet using python
```<code>import xlwt
import xlrd, xlutils

wb = xlwt.Workbook()
outsheet = wb.add_sheet('Page 1')

files = [r'c:\file1', r'C:c:\file2',]

outrow = 0

for f in files:

insheet = xlrd.open_workbook(f,formatting_info=True).sheets()[0]
for row in range(insheet.nrows):
    for col in range(insheet.ncols):
        outsheet.write(outrow, col,insheet.cell_value(row, col))
    outrow += 1
wb.save(r'C:\combined.xls')
</code>```

i get output as

42753.61492

42753.61492

42753.61492

42753.61492

42753.61492

where i was looking something as this

                        2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-20 09:10:06 a

答:
Can you give try to this:</p>

```<code>from datetime import datetime
import xlwt
import xlrd, xlutils

wb = xlwt.Workbook()
outsheet = wb.add_sheet('Page 1')

files = [r'c:\file1', r'C:c:\file2',]

outrow = 0

for f in files:

insheet = xlrd.open_workbook(f,formatting_info=True).sheets()[0]
for row in range(insheet.nrows):
    for col in range(insheet.ncols):
        outsheet.write(outrow, col,datetime.fromtimestamp(float(insheet.cell_value(row, col))))
    outrow += 1
wb.save(r'C:\combined.xls')
</code>```

Body:
import xlwt
import xlrd, xlutils

wb = xlwt.Workbook()
outsheet = wb.add_sheet('Page 1')

files = [r'c:\file1', r'C:c:\file2',]

outrow = 0

for f in files:

insheet = xlrd.open_workbook(f,formatting_info=True).sheets()[0]
for row in range(insheet.nrows):
    for col in range(insheet.ncols):
        outsheet.write(outrow, col,insheet.cell_value(row, col))
    outrow += 1
wb.save(r'C:\combined.xls')

i get output as

42753.61492

42753.61492

42753.61492

42753.61492

42753.61492

where i was looking something as this

                        2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-20 09:10:06 a

Body:
Can you give try to this:

from datetime import datetime
import xlwt
import xlrd, xlutils

wb = xlwt.Workbook()
outsheet = wb.add_sheet('Page 1')

files = [r'c:\file1', r'C:c:\file2',]

outrow = 0

for f in files:

insheet = xlrd.open_workbook(f,formatting_info=True).sheets()[0]
for row in range(insheet.nrows):
    for col in range(insheet.ncols):
        outsheet.write(outrow, col,datetime.fromtimestamp(float(insheet.cell_value(row, col))))
    outrow += 1
wb.save(r'C:\combined.xls')


问:
Trying to make changes on two different child forms from main form using Custom Events
I have an application with three forms.

I want to be able to update the listview control when a new object is being created in a separate form when all three of them are displayed.

MainForm - Contains a List collection instantiated inside, two buttons where CarForm and ListViewCarForm are instantiated.

```<code>public static List<Cars> listOfCars = new List<Cars>();

public List<Cars> CarList
{
   get { return listOfCars; }
   set { listOfCars = value; }
}

private void displayListViewToolStripMenuItem_Click(object sender, EventArgs e)
{
   ListViewCarForm lvcf = new ListViewCarForm();
   lvcf.Show();
}

private void newCarFormButton_Click(object sender, EventArgs e)
{
   CarForm cf = new CarForm();
   cf.Show();

   //Adds new item created to listOfItems
   cf.ObjectCreatedToList += ObjectCreatedToListCollectionHandler;
}
</code>```

CarForm - Contains controls for the user to enter values, those values are stored inside a class member variable that is created as an object and is then added inside the List Collection in the MainForm

```<code>public EventHandler ObjectCreatedToList;

//Class Property that assigns values to member variables
public Cars Info
{
   get
   {
       //Instantiates new Cars class, assigns member variables to control values and returns new Cars object
   }
   set
   {
       //set control values to Cars member variables
   }
}

private void addCarToolStripButton_Click(object sender, EventArgs e)
{
   if(ObjectCreatedToList != null)
   {
       ObjectCreatedToList(this, new EventArgs());
   }
   //Some Validation here to prevent control values to reset

   //If all control values are entered, this will clear the controls
   Info = new Cars();
}
</code>```

ListViewForm - Contains a ListView where when items are being added into the List Collection in CarForm, it should also be added to the listview control

The problem I am having is when all three forms are opened, the listview control inside the ListViewForm should be updated as new objects are being created by the CarForm and added inside the List Collection inside the MainForm.

Since the two forms are being instantiated inside a different button in the MainForm, I can't seem to figure out how to add the items inside the listview control without it not hitting the method or giving me an error.

*This is my first time working with Windows Application Forms

答:
To keep this simple, one solution is to pass the variable you need to the child form. Example: assuming the main form contains a ListBox of items and a button to open a Controlsform, then, when the user clicks the “Open Control Form” button… the ControlsForm is open, it has a text box and a button. When the user types something into the text box and then clicks the “Add to Parent List” button, the text in the text box should be added to the parent form’s ListBox items. You can pass the ListBox or List<Car> or anything you need to the child form. Hope this makes sense.

The MainForm has a ListBox and a button. The ListBox on the form is named Form1ListBoxControl. When the user clicks the “Open Control Form” button, the variable Form1ListBoxControl is passed to the newly created ControlsForm then the ControlsForm is shown…As above

Main form “Open Control Form” button click event…

```<code>private void btnOpenControlsForm_Click(object sender, EventArgs e) {
  ControlsForm controlsForm = new ControlsForm(Form1ListBoxControl);
  controlsForm.Show();
}
</code>```

ControlsForm...

To use the passed Form1ListBoxControl variable in the ControlsForm we need to make a global ListBox variable so the other methods in the form can use the parents ListBox…

```<code>ListBox parentListBox;
</code>```

In addition, we need to create a new "Constructor” for the ControlsForm to accept a ListBox parameter and use this parameter as the global variable defined above.…

```<code>public ControlsForm(ListBox passedParentListBox) {
  InitializeComponent();
  parentListBox = passedParentListBox;
}
</code>```

Finally the button event in the ControlsForm to add new items to the parents ListBox…

```<code>private void btnAddToParentList_Click(object sender, EventArgs e) {
  parentListBox.Items.Add(textBox1.Text);
}
</code>```

Body:
I have an application with three forms.

I want to be able to update the listview control when a new object is being created in a separate form when all three of them are displayed.

MainForm - Contains a List collection instantiated inside, two buttons where CarForm and ListViewCarForm are instantiated.

public static List<Cars> listOfCars = new List<Cars>();

public List<Cars> CarList
{
   get { return listOfCars; }
   set { listOfCars = value; }
}

private void displayListViewToolStripMenuItem_Click(object sender, EventArgs e)
{
   ListViewCarForm lvcf = new ListViewCarForm();
   lvcf.Show();
}

private void newCarFormButton_Click(object sender, EventArgs e)
{
   CarForm cf = new CarForm();
   cf.Show();

   //Adds new item created to listOfItems
   cf.ObjectCreatedToList += ObjectCreatedToListCollectionHandler;
}

CarForm - Contains controls for the user to enter values, those values are stored inside a class member variable that is created as an object and is then added inside the List Collection in the MainForm

public EventHandler ObjectCreatedToList;

//Class Property that assigns values to member variables
public Cars Info
{
   get
   {
       //Instantiates new Cars class, assigns member variables to control values and returns new Cars object
   }
   set
   {
       //set control values to Cars member variables
   }
}

private void addCarToolStripButton_Click(object sender, EventArgs e)
{
   if(ObjectCreatedToList != null)
   {
       ObjectCreatedToList(this, new EventArgs());
   }
   //Some Validation here to prevent control values to reset

   //If all control values are entered, this will clear the controls
   Info = new Cars();
}

ListViewForm - Contains a ListView where when items are being added into the List Collection in CarForm, it should also be added to the listview control

The problem I am having is when all three forms are opened, the listview control inside the ListViewForm should be updated as new objects are being created by the CarForm and added inside the List Collection inside the MainForm.

Since the two forms are being instantiated inside a different button in the MainForm, I can't seem to figure out how to add the items inside the listview control without it not hitting the method or giving me an error.

*This is my first time working with Windows Application Forms

Body:
To keep this simple, one solution is to pass the variable you need to the child form. Example: assuming the main form contains a ListBox of items and a button to open a Controlsform, then, when the user clicks the “Open Control Form” button… the ControlsForm is open, it has a text box and a button. When the user types something into the text box and then clicks the “Add to Parent List” button, the text in the text box should be added to the parent form’s ListBox items. You can pass the ListBox or List<Car> or anything you need to the child form. Hope this makes sense.

The MainForm has a ListBox and a button. The ListBox on the form is named Form1ListBoxControl. When the user clicks the “Open Control Form” button, the variable Form1ListBoxControl is passed to the newly created ControlsForm then the ControlsForm is shown…As above

Main form “Open Control Form” button click event…

private void btnOpenControlsForm_Click(object sender, EventArgs e) {
  ControlsForm controlsForm = new ControlsForm(Form1ListBoxControl);
  controlsForm.Show();
}

ControlsForm...

To use the passed Form1ListBoxControl variable in the ControlsForm we need to make a global ListBox variable so the other methods in the form can use the parents ListBox…

ListBox parentListBox;

In addition, we need to create a new "Constructor” for the ControlsForm to accept a ListBox parameter and use this parameter as the global variable defined above.…

public ControlsForm(ListBox passedParentListBox) {
  InitializeComponent();
  parentListBox = passedParentListBox;
}

Finally the button event in the ControlsForm to add new items to the parents ListBox…

private void btnAddToParentList_Click(object sender, EventArgs e) {
  parentListBox.Items.Add(textBox1.Text);
}