问:
Drag and Drop whole row in QAbstractTableModel PyQt5
I have a simple example of QAbstractTableModel. The goal is to drag and drop the whole row in a table. I have re-implemented functions needed, but have no idea how to re-implement MIME functions (I called them in the end of my class but left them untouched). Could you please help me with this example?</p>

```<code>from PyQt5 import QtCore, QtGui, QtWidgets
import sys

    class Mainwindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.table = QtWidgets.QTableView()
        self.setCentralWidget(self.table)

        headers = [None, 'Matreial', 'γ, kg/m3', 'λa', 'λb']

        data = [
            [1, 'Blocks γ=500 GOST 31359-2007', 500, 0.18, 0.22],
            [2, 'Blocks γ=600 GOST 31359-2008', 600, 0.25, 0.27],
            [3, 'Insulation', '80-125', 0.041, 0.042]
            ]

        model = Materials(data, headers)
        self.table.setModel(model)

        self.table.setSelectionBehavior(self.table.SelectRows)
        self.table.setSelectionMode(self.table.SingleSelection)
        self.table.setDragDropMode(self.table.InternalMove)
        self.table.setDropIndicatorShown(True)
        self.table.setDragEnabled(True)
        self.table.setAcceptDrops(True)

class Materials(QtCore.QAbstractTableModel):

    def __init__(self, materials = [[]], headers = [], parent = None):
        super(Materials, self).__init__()
        self.materials = materials
        self.headers = headers

    def rowCount(self, parent):
        return len(self.materials)

    def columnCount(self, parent):
        return len(self.headers)

    def data(self, index, role):

        if role == QtCore.Qt.DisplayRole:
            row = index.row()
            column = index.column()
            value = self.materials[row][column]
            return value

    def setData(self, index, value, role = QtCore.Qt.EditRole):

        if role == QtCore.Qt.EditRole:
            row = index.row()
            column = index.column()
            text = str(value)
            if type(text)==str:
                self.materials[row][column] = text
                self.dataChanged.emit(index, index)
                return True
        return False

    def headerData(self, section, orientation, role):

        if role == QtCore.Qt.DisplayRole:
            if orientation == QtCore.Qt.Horizontal:
                return self.headers[section]

    def flags(self, index):
        return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled

    def insertRows(self, position, rows, parent = QtCore.QModelIndex()):
        self.beginInsertRows(parent, position, position + rows - 1)

        for i in range(rows):

            defaultValues = ['' for i in range(self.columnCount(None))]
            self.materials.insert(position, defaultValues)

        self.endInsertRows()
        return True

    def removeRows(self, position, rows, parent = QtCore.QModelIndex()):
        self.beginRemoveRows(parent, position, position + rows - 1)

        for i in range(rows):
            value = self.materials[position]
            self.materials.remove(value)

        self.endRemoveRows()
        return True

    def supportedDropActions(self):
        return QtCore.Qt.CopyAction | QtCore.Qt.MoveAction

    def supportedDragActions(self):
        return QtCore.Qt.CopyAction | QtCore.Qt.MoveAction

    def mimeTypes(self):
        return super().mimeTypes()

    def mimeData(self, indexes):
        return super().mimeData(indexes)

    def dropMimeData(self, data, action, row, col, parent):
         return super().dropMimeData(data, action, row, col, parent)

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    application = Mainwindow()
    application.show()

    sys.exit(app.exec())
</code>```

答:
I figured it out: re-implemented mimeTypes, mimeData, dropMimeData. Also changed insertRows.
dropMimeData code looks a bit ugly - I would be glad if any suggestions how to make it better.

Anyway, I'm waiting for comments!

```<code>from PyQt5 import QtCore, QtGui, QtWidgets
import sys

class Mainwindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.table = QtWidgets.QTableView()
        self.setCentralWidget(self.table)

        headers = [None, 'Matreial', 'γ, kg/m3', 'λa', 'λb']

        data = [
            [1, 'Blocks γ=500 GOST 31359-2007', 500, 0.18, 0.22],
            [2, 'Blocks γ=600 GOST 31359-2008', 600, 0.25, 0.27],
            [3, 'Insulation', '80-125', 0.041, 0.042]
            ]

        self.model = Materials(data, headers)
        self.table.setModel(self.model)

        self.table.setSelectionBehavior(self.table.SelectRows)
        self.table.setSelectionMode(self.table.SingleSelection)
        self.table.setDragDropMode(self.table.InternalMove)
        self.table.setDropIndicatorShown(True)
        self.table.setDragEnabled(True)
        self.table.setAcceptDrops(True)

class Materials(QtCore.QAbstractTableModel):

    def __init__(self, materials = [[]], headers = [], parent = None):
        super(Materials, self).__init__()
        self.materials = materials
        self.headers = headers

    def rowCount(self, parent):
        return len(self.materials)

    def columnCount(self, parent):
        return len(self.headers)

    def data(self, index, role):

        if role == QtCore.Qt.DisplayRole:
            row = index.row()
            column = index.column()
            value = self.materials[row][column]
            return value

    def setData(self, index, value, role = QtCore.Qt.EditRole):

        if role == QtCore.Qt.EditRole:
            row = index.row()
            column = index.column()
            text = str(value)
            if type(text)==str:
                self.materials[row][column] = text
                self.dataChanged.emit(index, index)
                return True
        return False

    def headerData(self, section, orientation, role):

        if role == QtCore.Qt.DisplayRole:
            if orientation == QtCore.Qt.Horizontal:
                return self.headers[section]

    def flags(self, index):
        return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled

    def insertRows(self, value, position, rows, parent = QtCore.QModelIndex()):  ####add value
        self.beginInsertRows(parent, position, position + rows - 1)

        for i in range(rows):
            self.materials.insert(position, value)       ####change here

        self.endInsertRows()
        return True

    def removeRows(self, position, rows, parent = QtCore.QModelIndex()):
        self.beginRemoveRows(parent, position, position + rows - 1)

        for i in range(rows):
            item = self.materials[position]
            self.materials.remove(item)

        self.endRemoveRows()
        return True

    def supportedDropActions(self):
        return QtCore.Qt.CopyAction | QtCore.Qt.MoveAction

    def supportedDragActions(self):
        return QtCore.Qt.CopyAction | QtCore.Qt.MoveAction

    def mimeTypes(self):
        return ['text']

    def mimeData(self, indexes):
        mimedata = QtCore.QMimeData()
        list_1 = []
        for i in indexes:
            list_1 += [str(i.data())]

        b = bytearray(','.join(list_1).encode('utf-8'))
        mimedata.setData('text', b)

        return mimedata

    def dropMimeData(self, mimedata, action, row, col, parent):

        drop_data = mimedata.data('text').split(',')
        item_list = [b.data().decode('utf-8') for b in drop_data]

        new_list = []
        for item in item_list:
            try:
                new_list += [int(item)]
            except ValueError:
                new_list += [item]
        final_list = []
        for item in new_list:
            if type(item) == int:
                final_list += [item]
            else:
                try:
                    final_list += [float(item)]
                except ValueError:
                    final_list += [item]

        if final_list in self.materials:
             position = self.materials.index(final_list)

        self.removeRows(position, 1)
        self.insertRows(final_list, parent.row(), 1)

        return True

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    application = Mainwindow()
    application.show()

    sys.exit(app.exec())
</code>```

Body:
I have a simple example of QAbstractTableModel. The goal is to drag and drop the whole row in a table. I have re-implemented functions needed, but have no idea how to re-implement MIME functions (I called them in the end of my class but left them untouched). Could you please help me with this example?

from PyQt5 import QtCore, QtGui, QtWidgets
import sys

    class Mainwindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.table = QtWidgets.QTableView()
        self.setCentralWidget(self.table)

        headers = [None, 'Matreial', 'γ, kg/m3', 'λa', 'λb']

        data = [
            [1, 'Blocks γ=500 GOST 31359-2007', 500, 0.18, 0.22],
            [2, 'Blocks γ=600 GOST 31359-2008', 600, 0.25, 0.27],
            [3, 'Insulation', '80-125', 0.041, 0.042]
            ]

        model = Materials(data, headers)
        self.table.setModel(model)

        self.table.setSelectionBehavior(self.table.SelectRows)
        self.table.setSelectionMode(self.table.SingleSelection)
        self.table.setDragDropMode(self.table.InternalMove)
        self.table.setDropIndicatorShown(True)
        self.table.setDragEnabled(True)
        self.table.setAcceptDrops(True)

class Materials(QtCore.QAbstractTableModel):

    def __init__(self, materials = [[]], headers = [], parent = None):
        super(Materials, self).__init__()
        self.materials = materials
        self.headers = headers

    def rowCount(self, parent):
        return len(self.materials)

    def columnCount(self, parent):
        return len(self.headers)

    def data(self, index, role):

        if role == QtCore.Qt.DisplayRole:
            row = index.row()
            column = index.column()
            value = self.materials[row][column]
            return value

    def setData(self, index, value, role = QtCore.Qt.EditRole):

        if role == QtCore.Qt.EditRole:
            row = index.row()
            column = index.column()
            text = str(value)
            if type(text)==str:
                self.materials[row][column] = text
                self.dataChanged.emit(index, index)
                return True
        return False

    def headerData(self, section, orientation, role):

        if role == QtCore.Qt.DisplayRole:
            if orientation == QtCore.Qt.Horizontal:
                return self.headers[section]

    def flags(self, index):
        return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled

    def insertRows(self, position, rows, parent = QtCore.QModelIndex()):
        self.beginInsertRows(parent, position, position + rows - 1)

        for i in range(rows):

            defaultValues = ['' for i in range(self.columnCount(None))]
            self.materials.insert(position, defaultValues)

        self.endInsertRows()
        return True

    def removeRows(self, position, rows, parent = QtCore.QModelIndex()):
        self.beginRemoveRows(parent, position, position + rows - 1)

        for i in range(rows):
            value = self.materials[position]
            self.materials.remove(value)

        self.endRemoveRows()
        return True

    def supportedDropActions(self):
        return QtCore.Qt.CopyAction | QtCore.Qt.MoveAction

    def supportedDragActions(self):
        return QtCore.Qt.CopyAction | QtCore.Qt.MoveAction

    def mimeTypes(self):
        return super().mimeTypes()

    def mimeData(self, indexes):
        return super().mimeData(indexes)

    def dropMimeData(self, data, action, row, col, parent):
         return super().dropMimeData(data, action, row, col, parent)

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    application = Mainwindow()
    application.show()

    sys.exit(app.exec())

Body:
I figured it out: re-implemented mimeTypes, mimeData, dropMimeData. Also changed insertRows.
dropMimeData code looks a bit ugly - I would be glad if any suggestions how to make it better.

Anyway, I'm waiting for comments!

from PyQt5 import QtCore, QtGui, QtWidgets
import sys

class Mainwindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.table = QtWidgets.QTableView()
        self.setCentralWidget(self.table)

        headers = [None, 'Matreial', 'γ, kg/m3', 'λa', 'λb']

        data = [
            [1, 'Blocks γ=500 GOST 31359-2007', 500, 0.18, 0.22],
            [2, 'Blocks γ=600 GOST 31359-2008', 600, 0.25, 0.27],
            [3, 'Insulation', '80-125', 0.041, 0.042]
            ]

        self.model = Materials(data, headers)
        self.table.setModel(self.model)

        self.table.setSelectionBehavior(self.table.SelectRows)
        self.table.setSelectionMode(self.table.SingleSelection)
        self.table.setDragDropMode(self.table.InternalMove)
        self.table.setDropIndicatorShown(True)
        self.table.setDragEnabled(True)
        self.table.setAcceptDrops(True)

class Materials(QtCore.QAbstractTableModel):

    def __init__(self, materials = [[]], headers = [], parent = None):
        super(Materials, self).__init__()
        self.materials = materials
        self.headers = headers

    def rowCount(self, parent):
        return len(self.materials)

    def columnCount(self, parent):
        return len(self.headers)

    def data(self, index, role):

        if role == QtCore.Qt.DisplayRole:
            row = index.row()
            column = index.column()
            value = self.materials[row][column]
            return value

    def setData(self, index, value, role = QtCore.Qt.EditRole):

        if role == QtCore.Qt.EditRole:
            row = index.row()
            column = index.column()
            text = str(value)
            if type(text)==str:
                self.materials[row][column] = text
                self.dataChanged.emit(index, index)
                return True
        return False

    def headerData(self, section, orientation, role):

        if role == QtCore.Qt.DisplayRole:
            if orientation == QtCore.Qt.Horizontal:
                return self.headers[section]

    def flags(self, index):
        return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled

    def insertRows(self, value, position, rows, parent = QtCore.QModelIndex()):  ####add value
        self.beginInsertRows(parent, position, position + rows - 1)

        for i in range(rows):
            self.materials.insert(position, value)       ####change here

        self.endInsertRows()
        return True

    def removeRows(self, position, rows, parent = QtCore.QModelIndex()):
        self.beginRemoveRows(parent, position, position + rows - 1)

        for i in range(rows):
            item = self.materials[position]
            self.materials.remove(item)

        self.endRemoveRows()
        return True

    def supportedDropActions(self):
        return QtCore.Qt.CopyAction | QtCore.Qt.MoveAction

    def supportedDragActions(self):
        return QtCore.Qt.CopyAction | QtCore.Qt.MoveAction

    def mimeTypes(self):
        return ['text']

    def mimeData(self, indexes):
        mimedata = QtCore.QMimeData()
        list_1 = []
        for i in indexes:
            list_1 += [str(i.data())]

        b = bytearray(','.join(list_1).encode('utf-8'))
        mimedata.setData('text', b)

        return mimedata

    def dropMimeData(self, mimedata, action, row, col, parent):

        drop_data = mimedata.data('text').split(',')
        item_list = [b.data().decode('utf-8') for b in drop_data]

        new_list = []
        for item in item_list:
            try:
                new_list += [int(item)]
            except ValueError:
                new_list += [item]
        final_list = []
        for item in new_list:
            if type(item) == int:
                final_list += [item]
            else:
                try:
                    final_list += [float(item)]
                except ValueError:
                    final_list += [item]

        if final_list in self.materials:
             position = self.materials.index(final_list)

        self.removeRows(position, 1)
        self.insertRows(final_list, parent.row(), 1)

        return True

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    application = Mainwindow()
    application.show()

    sys.exit(app.exec())


来源: stackexchange

问:
How the ftell() function works?
I have this code and I don't understand how it works:

```<code>void print(char * fileName)
{
    FILE * fp;
    int ch;
    fp = fopen(fileName, "r");
    while (ftell(fp) < 20)
    {
        ch = fgetc(fp);
        putchar(ch);
    }
    fclose(fp);
}
</code>```

How does ftell(fp) work in the loop?
Because there is nothing inside the loop that get it up.
How it is progressive?

答:
ftell() gets you the current value of the position indicator of the stream(in your case, it basically returns the character position it is currently pointing to right now).

fgetc() gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream. This function returns the character read as an unsigned char cast to an int or EOF on end of file or error

Flow of your program

What that means in very simple terms is -

fgetc() is reading one character after character from the file and advancing the pointer to the next character.

ftell() is returning you the current position in in bytes from the
beginning of the file. This means it tells the position of the character it is pointing right now(since 1 char takes 1 byte).

So, your program reads from the file until ftell() returns the
position which is less than 20.This means that it will keep looping until 20 characters have been read from your file.

Hope this clears your doubt !

ContentLicense: CC BY-SA 4.0

Title: How the ftell() function works?

Body:
I have this code and I don't understand how it works:

void print(char * fileName)
{
    FILE * fp;
    int ch;
    fp = fopen(fileName, "r");
    while (ftell(fp) < 20)
    {
        ch = fgetc(fp);
        putchar(ch);
    }
    fclose(fp);
}

How does ftell(fp) work in the loop?
Because there is nothing inside the loop that get it up.
How it is progressive?


问:
pulsectl library - Could not find module 'libpulse.so.0'
I made a python script on linux, which uses the pulsectl library and it works just fine. When I tried to run it on windows i got an error: FileNotFoundError: Could not find module 'libpulse.so.0' (or one of its dependencies). Try using the full path with constructor syntax.. I have pulsectl installed on both systems. I searched for the file on multiple sites, but I couldn't find anything. Not even a single thread about this error. Here is the traceback message: https://pastebin.pl/view/17da8815

答: Ok, I found a solution. If anybody has the same problem, go to this site, download the preview binaries, extract items, open the bin folder and then copy all the items to your C:\Windows folder. If asked for permission from UAC just click 'Allow'. And that's it.


问:
Looping over long values from JSON and writing to console in C#
I have a JSON file structured like so in a file named 'Config.json':

```<code>    {
      "name": "Michael",
      "ids": [111111, 222222, 333333, 444444, 555555]
    }
</code>```

I am deserializing it like so:

```<code>Config config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("Config.json"));
</code>```

I have a Config class like so:

```<code>class Config
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("ids")]
        public long Ids{ get; set; }
    }
</code>```

How do I iterate over the ids and write them to console? I have tried this:

```<code>    var ids = new List<long> { config.Ids};

    foreach (long id in ids)
    {
        Console.WriteLine(id.ToString());
    }
</code>```

But I get an error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Int64' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly

I cannot figure out how to deserialize and write this...I have tried experimenting with different values (uint64) but the same error occurs.

Thanks so much!

答:
Your ids property in your Json is an array (as indicated by the square brackets). To properly desierialize this Json, your model class should look like

public class Config
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("ids")]
    public IEnumerable<long> Ids { get; set; }
}
```

<p>Then, if you want to write all of the values to console</p>

<pre class="lang-cs prettyprint-override"><code>foreach (var id in config.Ids)
{
    Console.WriteLine(id);
}
</code>```

Body:
I have a JSON file structured like so in a file named 'Config.json':

    {
      "name": "Michael",
      "ids": [111111, 222222, 333333, 444444, 555555]
    }

I am deserializing it like so:

Config config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("Config.json"));

I have a Config class like so:

class Config
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("ids")]
        public long Ids{ get; set; }
    }

How do I iterate over the ids and write them to console? I have tried this:

    var ids = new List<long> { config.Ids};

    foreach (long id in ids)
    {
        Console.WriteLine(id.ToString());
    }

But I get an error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Int64' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly

I cannot figure out how to deserialize and write this...I have tried experimenting with different values (uint64) but the same error occurs.

Thanks so much!

Body:
Your ids property in your Json is an array (as indicated by the square brackets). To properly desierialize this Json, your model class should look like

public class Config
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("ids")]
    public IEnumerable<long> Ids { get; set; }
}

Then, if you want to write all of the values to console

foreach (var id in config.Ids)
{
    Console.WriteLine(id);
}


问:
LoadStop event fires multiple times
I am trying to post an HTML page using cordova-inapp-browser plugin. The problem which i am facing is the loadstop event is getting fired multiple times.

I have tried to use the code in buttonclick(onClicked()) event but then the post method is not at all working. I tried on loadstart as well which is also not giving me the desired output.

```<code>var app = {
// Application Constructor
    initialize: function() {
    document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    document.getElementById('btnClick').addEventListener('click',app.onClicked,false);
},

onDeviceReady: function() {
     this.receivedEvent('deviceready');
},

// Update DOM on a Received Event
receivedEvent: function(id) {
    var parentElement = document.getElementById(id);

    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');

    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');

    console.log('Received Event: ' + id);

},

onClicked: function(){
    var url = "https://httpbin.org/";

    console.log("Clicked Button");
    var target = "_blank";
    var options = "location=no,hidden=yes";
    ref = cordova.InAppBrowser.open('about:blank',target, options);
    ref.addEventListener('loadstop',app.onBrowserLoadStop);
},
onBrowserLoadStop: function(params){

    console.log("Start - Load Stop");

    var options = {
        uid:'ANYUID',
        pwd:'ANYPASSWORD'
    };

    var script = 'var form = document.createElement("form");';
    script += 'var url="https://httpbin.org/post";';
    script += 'form.method="post";';
    script += 'form.setAttribute("action",url);';
    for(var data in options){
        script += 'var hiddenField = document.createElement("input");';
        script += 'hiddenField.setAttribute("type","hidden");';
        script += 'hiddenField.setAttribute("name","'+data+'");';
        script += 'hiddenField.setAttribute("value","'+ options[data] + '");';
        script += 'form.appendChild(hiddenField);';
    }
    script += 'document.body.appendChild(form);';
    script += 'form.submit();';
    console.log("Scirpt: " + script);
    ref.executeScript({
        code:script
    },
    function(values){
        console.log(JSON.stringify("Script: "+ values));
     }
    );
    ref.show();
},
};
</code>```

app.initialize();

I want to post this http website only once. If you check the console the loadstop event keeps firing.

答:
add

```<code>if (theWebView.isLoading) return;
</code>```

to

```<code>(void)webViewDidFinishLoad:(UIWebView*)theWebView
</code>```

in

CDVUIInAppBrowser.m

After inserting the code above, it will fire only one 'loadstop' event when the whole page is loaded with all external dependencies.

Title: LoadStop event fires multiple times

Body:
I am trying to post an HTML page using cordova-inapp-browser plugin. The problem which i am facing is the loadstop event is getting fired multiple times.

I have tried to use the code in buttonclick(onClicked()) event but then the post method is not at all working. I tried on loadstart as well which is also not giving me the desired output.

var app = {
// Application Constructor
    initialize: function() {
    document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    document.getElementById('btnClick').addEventListener('click',app.onClicked,false);
},

onDeviceReady: function() {
     this.receivedEvent('deviceready');
},

// Update DOM on a Received Event
receivedEvent: function(id) {
    var parentElement = document.getElementById(id);

    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');

    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');

    console.log('Received Event: ' + id);

},

onClicked: function(){
    var url = "https://httpbin.org/";

    console.log("Clicked Button");
    var target = "_blank";
    var options = "location=no,hidden=yes";
    ref = cordova.InAppBrowser.open('about:blank',target, options);
    ref.addEventListener('loadstop',app.onBrowserLoadStop);
},
onBrowserLoadStop: function(params){

    console.log("Start - Load Stop");

    var options = {
        uid:'ANYUID',
        pwd:'ANYPASSWORD'
    };

    var script = 'var form = document.createElement("form");';
    script += 'var url="https://httpbin.org/post";';
    script += 'form.method="post";';
    script += 'form.setAttribute("action",url);';
    for(var data in options){
        script += 'var hiddenField = document.createElement("input");';
        script += 'hiddenField.setAttribute("type","hidden");';
        script += 'hiddenField.setAttribute("name","'+data+'");';
        script += 'hiddenField.setAttribute("value","'+ options[data] + '");';
        script += 'form.appendChild(hiddenField);';
    }
    script += 'document.body.appendChild(form);';
    script += 'form.submit();';
    console.log("Scirpt: " + script);
    ref.executeScript({
        code:script
    },
    function(values){
        console.log(JSON.stringify("Script: "+ values));
     }
    );
    ref.show();
},
};

app.initialize();

I want to post this http website only once. If you check the console the loadstop event keeps firing.

Body:
add

if (theWebView.isLoading) return;

to

(void)webViewDidFinishLoad:(UIWebView*)theWebView

in

CDVUIInAppBrowser.m

After inserting the code above, it will fire only one 'loadstop' event when the whole page is loaded with all external dependencies.


问:
string regex vs array product catalog mongodb performance
I am trying to implement a product catalog in mongodb but I am not sure should I use string to store product category which is regex friendly or should I prefer an array

eg:

```<code>{
  productId: 34523,
  name: "smartWatch",
  category: '/23425/6456/76556'
}
</code>```

or

```<code>{
  productId: 34523,
  name: "smartWatch",
  category: [23425, 6456, 76556]
}
</code>```

答: MongoDB supports various query operators on arrays such as $elemMatch and $all. Trying to achieve the same functionality with regular expression searches would be much more awkward.</p>

Body:
I am trying to implement a product catalog in mongodb but I am not sure should I use string to store product category which is regex friendly or should I prefer an array

eg:

{
  productId: 34523,
  name: "smartWatch",
  category: '/23425/6456/76556'
}

or

{
  productId: 34523,
  name: "smartWatch",
  category: [23425, 6456, 76556]
}


问:
Bad input warning in python
The question for the code is attached below .

Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:

X-DSPAM-Confidence:    0.8475

Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.

You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.

```<code>fname = input("Enter file name: ")
fh = open(fname,'r')
count=0
val=0
for line in fh:
    if line.find("X-DSPAM-Confidence:")==-1:
        continue
    else:
        count+=1
        pos=line.find(':')
        val+=float(line[pos+1:]
res=float(val/count)
print('Average spam confidence: ',res)
fh.close()
</code>```

I am getting an error stating "bad input on line 13".
can anyone help me out as to why this is happening? Thank you in advance

答:
The code below works (with the text example you have provided)</p>

```<code>import requests

total = 0
cnt = 0
r = requests.get('https://www.py4e.com/code3/mbox-short.txt')
if r.status_code == 200:
    lines = r.text.split('\n')
    length = len('X-DSPAM-Confidence:')
    for line in lines:
        idx = line.find('X-DSPAM-Confidence:')
        if idx != -1:
            cnt += 1
            val = float(line[length + 1:])
            total += val
res = float(total / cnt)
print('Average spam confidence: ', res)
</code>```

Title: Bad input warning in python

Body:
The question for the code is attached below .

Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:

X-DSPAM-Confidence:    0.8475

Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.

You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.

fname = input("Enter file name: ")
fh = open(fname,'r')
count=0
val=0
for line in fh:
    if line.find("X-DSPAM-Confidence:")==-1:
        continue
    else:
        count+=1
        pos=line.find(':')
        val+=float(line[pos+1:]
res=float(val/count)
print('Average spam confidence: ',res)
fh.close()

I am getting an error stating "bad input on line 13".
can anyone help me out as to why this is happening? Thank you in advance

Body:
The code below works (with the text example you have provided)

import requests

total = 0
cnt = 0
r = requests.get('https://www.py4e.com/code3/mbox-short.txt')
if r.status_code == 200:
    lines = r.text.split('\n')
    length = len('X-DSPAM-Confidence:')
    for line in lines:
        idx = line.find('X-DSPAM-Confidence:')
        if idx != -1:
            cnt += 1
            val = float(line[length + 1:])
            total += val
res = float(total / cnt)
print('Average spam confidence: ', res)


问:
Pearson correlation and p-value in columns from a data frame
For example, if we calculate Pearson correlation and P-value of first two variables of data set mtcars, results are something like this:

```<code>Correlation value:

      mpg  disp
mpg   1.00 -0.85
disp -0.85  1.00

P-value:

      mpg    disp
mpg  0.0000 0.0000
disp 0.0000 0.0000
</code>```

Instead of this, Is there any way to have results like this:

```<code>          Corr.   p-value
mp  mp    1.00    0.0000
mp  dip  -0.85    0.0000
</code>```

I have more than 200 variable and want to generate results like this and then write those results on CSV using write.csv command. Thank you!

答:
If we wanted pairwise, cor.test, use combn

```<code>out <- combn(mtcars, 2, FUN = function(x)
    cor.test(x[[1]], x[[2]], conf.level = 0.95), simplify = FALSE)
names(out) <- combn(names(mtcars), 2, FUN = paste, collapse='_')
</code>```

The output of corr.test is a list

```<code>str(out[[1]])
#List of 9
# $ statistic  : Named num -8.92
#  ..- attr(*, "names")= chr "t"
# $ parameter  : Named int 30
#  ..- attr(*, "names")= chr "df"
# $ p.value    : num 6.11e-10
# $ estimate   : Named num -0.852
#  ..- attr(*, "names")= chr "cor"
# $ null.value : Named num 0
#  ..- attr(*, "names")= chr "correlation"
# $ alternative: chr "two.sided"
# $ method     : chr "Pearson's product-moment correlation"
# $ data.name  : chr "x[[1]] and x[[2]]"
# $ conf.int   : num [1:2] -0.926 -0.716
#  ..- attr(*, "conf.level")= num 0.95
</code>```

It can be directly extracted with list extraction methods i.e. $ or [[

```<code>mydata <– do.call(rbind, Map(cbind, corgroups = names(out),
 unname(lapply(out, function(x)
        data.frame(cor.value = x$estimate, cor.pvalue = x$p.value)))))
</code>```

Body:
For example, if we calculate Pearson correlation and P-value of first two variables of data set mtcars, results are something like this:

Correlation value:

      mpg  disp
mpg   1.00 -0.85
disp -0.85  1.00

P-value:

      mpg    disp
mpg  0.0000 0.0000
disp 0.0000 0.0000

Instead of this, Is there any way to have results like this:

          Corr.   p-value
mp  mp    1.00    0.0000
mp  dip  -0.85    0.0000

I have more than 200 variable and want to generate results like this and then write those results on CSV using write.csv command. Thank you!

Body:
If we wanted pairwise, cor.test, use combn

out <- combn(mtcars, 2, FUN = function(x)
    cor.test(x[[1]], x[[2]], conf.level = 0.95), simplify = FALSE)
names(out) <- combn(names(mtcars), 2, FUN = paste, collapse='_')

The output of corr.test is a list

str(out[[1]])
#List of 9
# $ statistic  : Named num -8.92
#  ..- attr(*, "names")= chr "t"
# $ parameter  : Named int 30
#  ..- attr(*, "names")= chr "df"
# $ p.value    : num 6.11e-10
# $ estimate   : Named num -0.852
#  ..- attr(*, "names")= chr "cor"
# $ null.value : Named num 0
#  ..- attr(*, "names")= chr "correlation"
# $ alternative: chr "two.sided"
# $ method     : chr "Pearson's product-moment correlation"
# $ data.name  : chr "x[[1]] and x[[2]]"
# $ conf.int   : num [1:2] -0.926 -0.716
#  ..- attr(*, "conf.level")= num 0.95

It can be directly extracted with list extraction methods i.e. $ or [[

mydata <– do.call(rbind, Map(cbind, corgroups = names(out),
 unname(lapply(out, function(x)
        data.frame(cor.value = x$estimate, cor.pvalue = x$p.value)))))


问:
Android app does not connect to Firebase
I'm developing android app using Firebase GMS service.

I tried to follow their tutorials, i made project as they said, downloaded the json files.

But when I tried to connect my app to Firebase. They show me the error

Could not parse the Android Application Module`s Gradle config. Resolve gardle build issuse and/or resync.

However I think my grade scripts are perfect ( I'll write them bottom of the page)

This is my grade build console

```<code>Executing tasks: [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]

Configuration on demand is an incubating feature.
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for debug as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for debug as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for debug as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for debug as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for release as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for release as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for release as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for release as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAnimatedVectorDrawable2400Library UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72400Library UP-TO-DATE
:app:prepareComAndroidSupportMediarouterV72400Library UP-TO-DATE
:app:prepareComAndroidSupportPaletteV72400Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42400Library UP-TO-DATE
:app:prepareComAndroidSupportSupportVectorDrawable2400Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServices980Library
:app:prepareComGoogleAndroidGmsPlayServicesAds980Library
:app:prepareComGoogleAndroidGmsPlayServicesAdsLite980Library
:app:prepareComGoogleAndroidGmsPlayServicesAnalytics980Library
:app:prepareComGoogleAndroidGmsPlayServicesAnalyticsImpl980Library
:app:prepareComGoogleAndroidGmsPlayServicesAppindexing980Library
:app:prepareComGoogleAndroidGmsPlayServicesAppinvite980Library
:app:prepareComGoogleAndroidGmsPlayServicesAuth980Library
:app:prepareComGoogleAndroidGmsPlayServicesAuthBase980Library
:app:prepareComGoogleAndroidGmsPlayServicesAwareness980Library
:app:prepareComGoogleAndroidGmsPlayServicesBase980Library
:app:prepareComGoogleAndroidGmsPlayServicesBasement980Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesCast980Library
:app:prepareComGoogleAndroidGmsPlayServicesCastFramework980Library
:app:prepareComGoogleAndroidGmsPlayServicesClearcut980Library
:app:prepareComGoogleAndroidGmsPlayServicesDrive980Library
:app:prepareComGoogleAndroidGmsPlayServicesFitness980Library
:app:prepareComGoogleAndroidGmsPlayServicesGames980Library
:app:prepareComGoogleAndroidGmsPlayServicesGass980Library
:app:prepareComGoogleAndroidGmsPlayServicesGcm980Library
:app:prepareComGoogleAndroidGmsPlayServicesIdentity980Library
:app:prepareComGoogleAndroidGmsPlayServicesIid980Library
:app:prepareComGoogleAndroidGmsPlayServicesInstantapps980Library
:app:prepareComGoogleAndroidGmsPlayServicesLocation980Library
:app:prepareComGoogleAndroidGmsPlayServicesMaps980Library
:app:prepareComGoogleAndroidGmsPlayServicesNearby980Library
:app:prepareComGoogleAndroidGmsPlayServicesPanorama980Library
:app:prepareComGoogleAndroidGmsPlayServicesPlaces980Library
:app:prepareComGoogleAndroidGmsPlayServicesPlus980Library
:app:prepareComGoogleAndroidGmsPlayServicesSafetynet980Library
:app:prepareComGoogleAndroidGmsPlayServicesTagmanager980Library
:app:prepareComGoogleAndroidGmsPlayServicesTagmanagerApi980Library
:app:prepareComGoogleAndroidGmsPlayServicesTasks980Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesVision980Library
:app:prepareComGoogleAndroidGmsPlayServicesWallet980Library
:app:prepareComGoogleAndroidGmsPlayServicesWearable980Library
:app:prepareComGoogleFirebaseFirebaseAnalytics980Library UP-TO-DATE
:app:prepareComGoogleFirebaseFirebaseAnalyticsImpl980Library UP-TO-DATE
:app:prepareComGoogleFirebaseFirebaseAuth980Library
:app:prepareComGoogleFirebaseFirebaseAuthCommon980Library
:app:prepareComGoogleFirebaseFirebaseAuthModule980Library
:app:prepareComGoogleFirebaseFirebaseCommon980Library UP-TO-DATE
:app:prepareComGoogleFirebaseFirebaseConfig980Library
:app:prepareComGoogleFirebaseFirebaseCore980Library UP-TO-DATE
:app:prepareComGoogleFirebaseFirebaseCrash980Library
:app:prepareComGoogleFirebaseFirebaseDatabase980Library
:app:prepareComGoogleFirebaseFirebaseDatabaseConnection980Library
:app:prepareComGoogleFirebaseFirebaseIid980Library UP-TO-DATE
:app:prepareComGoogleFirebaseFirebaseMessaging980Library UP-TO-DATE
:app:prepareComGoogleFirebaseFirebaseStorage980Library
:app:prepareComGoogleFirebaseFirebaseStorageCommon980Library
:app:prepareComTsengvnTypekit100Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:processDebugGoogleServices
Parsing json file: C:\Users\AJH322\AndroidStudioProjects\hanyang\app\src\debug\google-services.json
:app:generateDebugResources
:app:mergeDebugResources
:app:processDebugManifest
:app:processDebugResources
:app:generateDebugSources
:app:mockableAndroidJar UP-TO-DATE
:app:preDebugUnitTestBuild UP-TO-DATE
:app:prepareDebugUnitTestDependencies
:app:preDebugAndroidTestBuild UP-TO-DATE
:app:prepareDebugAndroidTestDependencies
:app:compileDebugAndroidTestAidl UP-TO-DATE
:app:processDebugAndroidTestManifest
:app:compileDebugAndroidTestRenderscript UP-TO-DATE
:app:generateDebugAndroidTestBuildConfig UP-TO-DATE
:app:generateDebugAndroidTestResValues UP-TO-DATE
:app:generateDebugAndroidTestResources UP-TO-DATE
:app:mergeDebugAndroidTestResources
:app:processDebugAndroidTestResources
:app:generateDebugAndroidTestSources

BUILD SUCCESSFUL

Total time: 3 mins 14.678 secs
</code>```

and this is my gradle script (module)

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "24.0.0"
    defaultConfig {
        applicationId "com.example.ajh322.hanyang"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.android.gms:play-services:9.8.0'
    compile 'com.tsengvn:Typekit:1.0.0'
    compile 'com.squareup.okhttp3:okhttp:3.4.2'
    compile 'com.github.nkzawa:socket.io-client:0.3.0'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

project gradle
apply plugin: 'com.android.application'

```<code>android {
    compileSdkVersion 23
    buildToolsVersion "24.0.0"
    defaultConfig {
        applicationId "com.example.ajh322.hanyang"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.android.gms:play-services:9.8.0'
    compile 'com.tsengvn:Typekit:1.0.0'
    compile 'com.squareup.okhttp3:okhttp:3.4.2'
    compile 'com.github.nkzawa:socket.io-client:0.3.0'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

does anybody know how can I connect to Firebase with my app?

please save my life... thanks

+ i updated my sdk tools as people said

still not works.

答:
I recently update to Android studio 4.0 and got into this error. I was still using the obsolete way to add the databinding . Changing it to the updated way to use the data binding resolved my issue. Below is the code : </p>

```<code>buildFeatures{
        dataBinding = true
        // for view binding :
        // viewBinding = true
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm developing android app using Firebase GMS service.

I tried to follow their tutorials, i made project as they said, downloaded the json files.

But when I tried to connect my app to Firebase. They show me the error

Could not parse the Android Application Module`s Gradle config. Resolve gardle build issuse and/or resync.

However I think my grade scripts are perfect ( I'll write them bottom of the page)

This is my grade build console

Executing tasks: [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]

Configuration on demand is an incubating feature.
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for debug as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for debug as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for debug as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for debug as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for release as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for release as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for release as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
WARNING: WARNING: Dependency org.json:json:20090211 is ignored for release as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAnimatedVectorDrawable2400Library UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72400Library UP-TO-DATE
:app:prepareComAndroidSupportMediarouterV72400Library UP-TO-DATE
:app:prepareComAndroidSupportPaletteV72400Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42400Library UP-TO-DATE
:app:prepareComAndroidSupportSupportVectorDrawable2400Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServices980Library
:app:prepareComGoogleAndroidGmsPlayServicesAds980Library
:app:prepareComGoogleAndroidGmsPlayServicesAdsLite980Library
:app:prepareComGoogleAndroidGmsPlayServicesAnalytics980Library
:app:prepareComGoogleAndroidGmsPlayServicesAnalyticsImpl980Library
:app:prepareComGoogleAndroidGmsPlayServicesAppindexing980Library
:app:prepareComGoogleAndroidGmsPlayServicesAppinvite980Library
:app:prepareComGoogleAndroidGmsPlayServicesAuth980Library
:app:prepareComGoogleAndroidGmsPlayServicesAuthBase980Library
:app:prepareComGoogleAndroidGmsPlayServicesAwareness980Library
:app:prepareComGoogleAndroidGmsPlayServicesBase980Library
:app:prepareComGoogleAndroidGmsPlayServicesBasement980Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesCast980Library
:app:prepareComGoogleAndroidGmsPlayServicesCastFramework980Library
:app:prepareComGoogleAndroidGmsPlayServicesClearcut980Library
:app:prepareComGoogleAndroidGmsPlayServicesDrive980Library
:app:prepareComGoogleAndroidGmsPlayServicesFitness980Library
:app:prepareComGoogleAndroidGmsPlayServicesGames980Library
:app:prepareComGoogleAndroidGmsPlayServicesGass980Library
:app:prepareComGoogleAndroidGmsPlayServicesGcm980Library
:app:prepareComGoogleAndroidGmsPlayServicesIdentity980Library
:app:prepareComGoogleAndroidGmsPlayServicesIid980Library
:app:prepareComGoogleAndroidGmsPlayServicesInstantapps980Library
:app:prepareComGoogleAndroidGmsPlayServicesLocation980Library
:app:prepareComGoogleAndroidGmsPlayServicesMaps980Library
:app:prepareComGoogleAndroidGmsPlayServicesNearby980Library
:app:prepareComGoogleAndroidGmsPlayServicesPanorama980Library
:app:prepareComGoogleAndroidGmsPlayServicesPlaces980Library
:app:prepareComGoogleAndroidGmsPlayServicesPlus980Library
:app:prepareComGoogleAndroidGmsPlayServicesSafetynet980Library
:app:prepareComGoogleAndroidGmsPlayServicesTagmanager980Library
:app:prepareComGoogleAndroidGmsPlayServicesTagmanagerApi980Library
:app:prepareComGoogleAndroidGmsPlayServicesTasks980Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesVision980Library
:app:prepareComGoogleAndroidGmsPlayServicesWallet980Library
:app:prepareComGoogleAndroidGmsPlayServicesWearable980Library
:app:prepareComGoogleFirebaseFirebaseAnalytics980Library UP-TO-DATE
:app:prepareComGoogleFirebaseFirebaseAnalyticsImpl980Library UP-TO-DATE
:app:prepareComGoogleFirebaseFirebaseAuth980Library
:app:prepareComGoogleFirebaseFirebaseAuthCommon980Library
:app:prepareComGoogleFirebaseFirebaseAuthModule980Library
:app:prepareComGoogleFirebaseFirebaseCommon980Library UP-TO-DATE
:app:prepareComGoogleFirebaseFirebaseConfig980Library
:app:prepareComGoogleFirebaseFirebaseCore980Library UP-TO-DATE
:app:prepareComGoogleFirebaseFirebaseCrash980Library
:app:prepareComGoogleFirebaseFirebaseDatabase980Library
:app:prepareComGoogleFirebaseFirebaseDatabaseConnection980Library
:app:prepareComGoogleFirebaseFirebaseIid980Library UP-TO-DATE
:app:prepareComGoogleFirebaseFirebaseMessaging980Library UP-TO-DATE
:app:prepareComGoogleFirebaseFirebaseStorage980Library
:app:prepareComGoogleFirebaseFirebaseStorageCommon980Library
:app:prepareComTsengvnTypekit100Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:processDebugGoogleServices
Parsing json file: C:\Users\AJH322\AndroidStudioProjects\hanyang\app\src\debug\google-services.json
:app:generateDebugResources
:app:mergeDebugResources
:app:processDebugManifest
:app:processDebugResources
:app:generateDebugSources
:app:mockableAndroidJar UP-TO-DATE
:app:preDebugUnitTestBuild UP-TO-DATE
:app:prepareDebugUnitTestDependencies
:app:preDebugAndroidTestBuild UP-TO-DATE
:app:prepareDebugAndroidTestDependencies
:app:compileDebugAndroidTestAidl UP-TO-DATE
:app:processDebugAndroidTestManifest
:app:compileDebugAndroidTestRenderscript UP-TO-DATE
:app:generateDebugAndroidTestBuildConfig UP-TO-DATE
:app:generateDebugAndroidTestResValues UP-TO-DATE
:app:generateDebugAndroidTestResources UP-TO-DATE
:app:mergeDebugAndroidTestResources
:app:processDebugAndroidTestResources
:app:generateDebugAndroidTestSources

BUILD SUCCESSFUL

Total time: 3 mins 14.678 secs

and this is my gradle script (module)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "24.0.0"
    defaultConfig {
        applicationId "com.example.ajh322.hanyang"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.android.gms:play-services:9.8.0'
    compile 'com.tsengvn:Typekit:1.0.0'
    compile 'com.squareup.okhttp3:okhttp:3.4.2'
    compile 'com.github.nkzawa:socket.io-client:0.3.0'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

project gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "24.0.0"
    defaultConfig {
        applicationId "com.example.ajh322.hanyang"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.android.gms:play-services:9.8.0'
    compile 'com.tsengvn:Typekit:1.0.0'
    compile 'com.squareup.okhttp3:okhttp:3.4.2'
    compile 'com.github.nkzawa:socket.io-client:0.3.0'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

does anybody know how can I connect to Firebase with my app?

please save my life... thanks

+ i updated my sdk tools as people said

still not works.

Body:
I recently update to Android studio 4.0 and got into this error. I was still using the obsolete way to add the databinding . Changing it to the updated way to use the data binding resolved my issue. Below is the code :

buildFeatures{
        dataBinding = true
        // for view binding :
        // viewBinding = true
    }


问:
Removal of 30-40 millions record without affecting performance
I have a SQL Server database running in Full recovery.  I need to remove data (around 30-40 million records) but I cannot take the database offline as it's in constant use.  I also cannot switch it to Simple recovery mode incase anything happens and we lose live data.  When I try to remove the data in small chunks (around 2 million rows), the transaction log becomes extremely large and causes the process to become extremely slow.  Due to back-up jobs running at night, I only have a small timeframe.

Does anyone have any thoughts on how I can do this?  I thought about copying the table into another database (in Simple recovery mode) and then remove the data.  Is this a good idea?

There are 3 tables in question.  Campaign, Events and Targets.  Its the Events table that has the millions of records in and this is what takes the time to delete.  The all have the necessary relations via Id columns.

答:
You have to use small chunks otherwise your transaction log will increases

Every one one of 30-40 million deletes will be logged. If you create a new table and copy "to keep" rows you'll still have 50+ million logged rows. The fact of simple vs full recovery doesn't matter: each delete/insert is logged

If the log increases in simple recovery then I suspect you are doing it in a transaction. So the 30-40 million deletes are still logged, even in simple recovery because it would all have to be rolled back perhaps.

For 40 x 1 million deletes without a transaction in simpler recovery you can use CHECKPOINT to assist in log tidy up

See Bulk DELETE on SQL Server 2008 (Is there anything like Bulk Copy (bcp) for delete data?) for more

But something like:

```<code>SELECT 'Starting' --sets @@ROWCOUNT
WHILE @@ROWCOUNT <> 0
BEGIN
    CHECKPOINT
    --Edit: must be last to set @@ROWCOUNT
    DELETE TOP (1000000) MyTable WHERE ...
END
</code>```

Process:

full backup

change recovery to simple

delete

change recovery to full (or what it was before)

full backup

You don't have many other options if you insist on deleting 30+ million rows in one go in a short windows...

Body:
You have to use small chunks otherwise your transaction log will increases

Every one one of 30-40 million deletes will be logged. If you create a new table and copy "to keep" rows you'll still have 50+ million logged rows. The fact of simple vs full recovery doesn't matter: each delete/insert is logged

If the log increases in simple recovery then I suspect you are doing it in a transaction. So the 30-40 million deletes are still logged, even in simple recovery because it would all have to be rolled back perhaps.

For 40 x 1 million deletes without a transaction in simpler recovery you can use CHECKPOINT to assist in log tidy up

See Bulk DELETE on SQL Server 2008 (Is there anything like Bulk Copy (bcp) for delete data?) for more

But something like:

SELECT 'Starting' --sets @@ROWCOUNT
WHILE @@ROWCOUNT <> 0
BEGIN
    CHECKPOINT
    --Edit: must be last to set @@ROWCOUNT
    DELETE TOP (1000000) MyTable WHERE ...
END

Process:

full backup

change recovery to simple

delete

change recovery to full (or what it was before)

full backup

You don't have many other options if you insist on deleting 30+ million rows in one go in a short windows...


问:
How can I fix a Discord python bot whose commands are not working
My bot was working fine yesterday. I made some changes in the code and when I run it, the bot would go online without any errors but no commands would work. I tried to use an old code that worked, but even that code doesn't work. I also regenerated the token and tried, but that did not work. Please help.

Here's my code:

```<code>import random
import discord
from discord.ext import commands

client = commands.Bot(command_prefix='.')
client.remove_command('help')

TOKEN = ''

# Bot status
@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.online, activity=discord.Game('.help for commands!'))
    print("Bot is ready")

# Member join
@client.event
async def on_member_join(member):
    print(f'{member} has joined the server.')
    e = discord.Embed()
    e.set_image(url='https://i.imgur.com/zYexoRK.png')
    channel = discord.utils.get(member.guild.channels, name="welcome")
    await channel.send(f"Welcome {member.mention}! :partying_face:", embed=e)

# Member leave
@client.event
async def on_member_remove(member):
    print(f'{member} has left the server.')

# Ping command
@client.command()
async def ping(ctx):
    await ctx.send(f"Ping is {round(client.latency * 1000)}ms")

# 8ball command
@client.command(aliases=['8ball', 'test'])
async def eball(ctx, *, question):
    responses = ['Absolutely.',
                 'Definitely not.',
                 'It is certain.',
                 'Not at all.',
                 'My sources say no',
                 'Not sure',
                 'Cannot predict now',
                 'Very doubtful',
                 "Don't count on it",
                 'Outlook not so good',
                 'Most likely',
                 'Without a doubt',
                 'As I see it, yes',
                 'You kidding me?',
                 "I don't answer stupid questions.",
                 'Ask again later.',
                 "Yes, but actually no.",
                 "Yes and no.",
                 "I'm no one to decide.",
                 ]
    await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')

# Clear command
@client.command()
async def clear(ctx, amount=5):
    await ctx.channel.purge(limit=amount)

# Help command
@client.command(pass_context=True)
async def help(ctx):
    channel = ctx.message.channel
    embed = discord.Embed(
        title='Commands',
        description='Commands',
        colour=discord.Colour.magenta()

    )

    embed.set_footer(text='@Takahashi | @deviantart.com/seerlight')
    embed.set_image(url='https://i.imgur.com/AVYIGjO.jpg')
    embed.set_thumbnail(url='https://i.pinimg.com/originals/ac/33/cb/ac33cba8c9df761dfcaa31e0e998af47.gif')
    embed.set_author(name='Takahashi', icon_url='https://i.imgur.com/j4SkgMo.png')

    embed.add_field(name='.help', value='Gives this message', inline=False)
    embed.add_field(name='.ping', value='Returns latency', inline=False)
    embed.add_field(name='.8ball', value='Returns answer to your dumb questions', inline=False)
    embed.add_field(name='.clear', value='Clear previous 5 lines', inline=False)
    embed.add_field(name='.flip', value='Randomly gives heads or tails', inline=False)
    embed.add_field(name='.about', value='Information about Takahashi and its developers', inline=False)
    await ctx.send(channel, embed=embed)

# Head and Tails
@client.command(pass_context=True)
async def flip(ctx):
    flip = ['https://i.imgur.com/OqFNJO7.png',
            'https://i.imgur.com/DarGk5i.png', ]
    channel = ctx.message.channel
    embed = discord.Embed(
        title='Heads and tails',
        description='Randomly gives heads and tails',
        colour=discord.Colour.blurple()

    )

    embed.set_image(url=f'{random.choice(flip)}')
    embed.set_thumbnail(url='https://media.tenor.com/images/1dc6f800ad56428f0ac93ae57662a006/tenor.gif')
    embed.set_author(name='Takahashi', icon_url='https://i.imgur.com/j4SkgMo.png')

    await ctx.send(channel, embed=embed)

client.run(TOKEN)
</code>```

答:
when you applyed some changes, coud it be possible that you accidentaly regenerated the bottoken or that you accidentaly removed a caracter, like DASFRE8894759 becomes DASFRE884759 . the difference is hard to spot. Go to your discord developer portal and click regenerate bot token or view bottoken and copy paste the token just to be sure.

i hope i coud help

Body:
My bot was working fine yesterday. I made some changes in the code and when I run it, the bot would go online without any errors but no commands would work. I tried to use an old code that worked, but even that code doesn't work. I also regenerated the token and tried, but that did not work. Please help.

Here's my code:

import random
import discord
from discord.ext import commands

client = commands.Bot(command_prefix='.')
client.remove_command('help')

TOKEN = ''

# Bot status
@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.online, activity=discord.Game('.help for commands!'))
    print("Bot is ready")

# Member join
@client.event
async def on_member_join(member):
    print(f'{member} has joined the server.')
    e = discord.Embed()
    e.set_image(url='https://i.imgur.com/zYexoRK.png')
    channel = discord.utils.get(member.guild.channels, name="welcome")
    await channel.send(f"Welcome {member.mention}! :partying_face:", embed=e)

# Member leave
@client.event
async def on_member_remove(member):
    print(f'{member} has left the server.')

# Ping command
@client.command()
async def ping(ctx):
    await ctx.send(f"Ping is {round(client.latency * 1000)}ms")

# 8ball command
@client.command(aliases=['8ball', 'test'])
async def eball(ctx, *, question):
    responses = ['Absolutely.',
                 'Definitely not.',
                 'It is certain.',
                 'Not at all.',
                 'My sources say no',
                 'Not sure',
                 'Cannot predict now',
                 'Very doubtful',
                 "Don't count on it",
                 'Outlook not so good',
                 'Most likely',
                 'Without a doubt',
                 'As I see it, yes',
                 'You kidding me?',
                 "I don't answer stupid questions.",
                 'Ask again later.',
                 "Yes, but actually no.",
                 "Yes and no.",
                 "I'm no one to decide.",
                 ]
    await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')

# Clear command
@client.command()
async def clear(ctx, amount=5):
    await ctx.channel.purge(limit=amount)

# Help command
@client.command(pass_context=True)
async def help(ctx):
    channel = ctx.message.channel
    embed = discord.Embed(
        title='Commands',
        description='Commands',
        colour=discord.Colour.magenta()

    )

    embed.set_footer(text='@Takahashi | @deviantart.com/seerlight')
    embed.set_image(url='https://i.imgur.com/AVYIGjO.jpg')
    embed.set_thumbnail(url='https://i.pinimg.com/originals/ac/33/cb/ac33cba8c9df761dfcaa31e0e998af47.gif')
    embed.set_author(name='Takahashi', icon_url='https://i.imgur.com/j4SkgMo.png')

    embed.add_field(name='.help', value='Gives this message', inline=False)
    embed.add_field(name='.ping', value='Returns latency', inline=False)
    embed.add_field(name='.8ball', value='Returns answer to your dumb questions', inline=False)
    embed.add_field(name='.clear', value='Clear previous 5 lines', inline=False)
    embed.add_field(name='.flip', value='Randomly gives heads or tails', inline=False)
    embed.add_field(name='.about', value='Information about Takahashi and its developers', inline=False)
    await ctx.send(channel, embed=embed)

# Head and Tails
@client.command(pass_context=True)
async def flip(ctx):
    flip = ['https://i.imgur.com/OqFNJO7.png',
            'https://i.imgur.com/DarGk5i.png', ]
    channel = ctx.message.channel
    embed = discord.Embed(
        title='Heads and tails',
        description='Randomly gives heads and tails',
        colour=discord.Colour.blurple()

    )

    embed.set_image(url=f'{random.choice(flip)}')
    embed.set_thumbnail(url='https://media.tenor.com/images/1dc6f800ad56428f0ac93ae57662a006/tenor.gif')
    embed.set_author(name='Takahashi', icon_url='https://i.imgur.com/j4SkgMo.png')

    await ctx.send(channel, embed=embed)

client.run(TOKEN)


问:
api = twitter.Api() AttributeError: 'module' object has no attribute 'Api
I have been trying to write a simple mention grabber to get started with the twitter Api. Howsoever I've been experienceing some difficulties when initializing the Api.
Running python2 on archlinux I installed twitter via easy_install, built it from source and installed it via pip. None of this seems to be working.

```<code>zergling :: ~/dev/kritter » python2
Python 2.7.2 (default, Jan 31 2012, 13:26:35)
[GCC 4.6.2 20120120 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import twitter
>>> api = twitter.Api()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Api'
</code>```

Howsoever the pydoc for twitter is there. I have no clue what I'm doing wrong. I hope you can help

UPDATE:
I tried using twitter.api() instead of twitter.Api() and got the following error:
    Traceback (most recent call last):
    File "main.py", line 8, in
    api = twitter.api()
    TypeError: 'module' object is not callable

Additional Informations:

```<code>>>> print dir(twitter)
['NoAuth', 'OAuth', 'Twitter', 'TwitterError', 'TwitterHTTPError', 'TwitterResponse',  'TwitterStream', 'UserPassAuth', '__all__', '__builtins__', '__doc__', '__file__',  '__name__', '__package__', '__path__', 'api', 'auth', 'oauth', 'read_token_file', 'stream', 'twitter_globals', 'write_token_file']
>>> print twitter.__path__
['/usr/lib/python2.7/site-packages/twitter-1.7.2-py2.7.egg/twitter']
</code>```

答:
Use module python-twitter instead of twitter

```<code>$ pip install python-twitter
</code>```

Reference : https://python-twitter.readthedocs.io/en/latest/installation.html

For Modules Documentation : https://python-twitter.readthedocs.io/en/latest/twitter.html#modules-documentation

Body:
I have been trying to write a simple mention grabber to get started with the twitter Api. Howsoever I've been experienceing some difficulties when initializing the Api.
Running python2 on archlinux I installed twitter via easy_install, built it from source and installed it via pip. None of this seems to be working.

zergling :: ~/dev/kritter » python2
Python 2.7.2 (default, Jan 31 2012, 13:26:35)
[GCC 4.6.2 20120120 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import twitter
>>> api = twitter.Api()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Api'

Howsoever the pydoc for twitter is there. I have no clue what I'm doing wrong. I hope you can help

UPDATE:
I tried using twitter.api() instead of twitter.Api() and got the following error:
    Traceback (most recent call last):
    File "main.py", line 8, in
    api = twitter.api()
    TypeError: 'module' object is not callable

Additional Informations:

>>> print dir(twitter)
['NoAuth', 'OAuth', 'Twitter', 'TwitterError', 'TwitterHTTPError', 'TwitterResponse',  'TwitterStream', 'UserPassAuth', '__all__', '__builtins__', '__doc__', '__file__',  '__name__', '__package__', '__path__', 'api', 'auth', 'oauth', 'read_token_file', 'stream', 'twitter_globals', 'write_token_file']
>>> print twitter.__path__
['/usr/lib/python2.7/site-packages/twitter-1.7.2-py2.7.egg/twitter']

Body:
Use module python-twitter instead of twitter

$ pip install python-twitter

Reference : https://python-twitter.readthedocs.io/en/latest/installation.html

For Modules Documentation : https://python-twitter.readthedocs.io/en/latest/twitter.html#modules-documentation


问:
"python manage.py makemigrations" Traceback errors after creating models.py in Django
All of these errors only started happening when i did the models.py, to the best of my knowledge i didn't write any of my code wrong. Previous "makemigrations" worked.

It seems like a lot of the Traceback errors have nothing to do with the models.py though.

(hopefully these are easy to read, sorry)

The traceback error:

Traceback (most recent call last):

File "manage.py", line 21, in  main()

File "manage.py", line 17, in main execute_from_command_line(sys.argv)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django
  /core/management/init.py", line 401, in execute_from_command_line
  utility.execute()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/core/management/init.py",
  line 377, in execute django.setup()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/init.py",
  line 24, in setup apps.populate(settings.INSTALLED_APPS)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/registry.py",
  line 114, in populate app_config.import_models()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/config.py",
  line 211, in import_models self.models_module =
  import_module(models_module_name)

File "/usr/lib/python3.6/importlib/init.py", line 126, in
  import_module return _bootstrap._gcd_import(name[level:], package,
  level)

File "", line 994, in _gcd_import

File "", line 971, in _find_and_load

File "", line 955, in
  _find_and_load_unlocked

File "", line 665, in _load_unlocked

File "", line 678, in
  exec_module

File "", line 219, in
  _call_with_frames_removed

File "/home/alatimer/Environments/djangoproject/blog/models.py", line
  6, in  class Post(models.Model):

File "/home/alatimer/Environments/djangoproject/blog/models.py", line
  9, in Post date_posted = models.DateTimeField(defualt=timezone.now)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/db/models/fields/init.py", line 1107, in init super().init(verbose_name, name, **kwargs)

TypeError: init() got an unexpected keyword argument 'defualt'

models.py:

```<code>from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(defualt=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
</code>```

答:
try</p>

```<code>class Post(models.Model):
    title = models.CharField(max_length=100, blank=True, null=True)
    content = models.TextField(blank=True, null=True)
    date_posted = models.DateTimeField(defualt=timezone.now, blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
</code>```

Body:
All of these errors only started happening when i did the models.py, to the best of my knowledge i didn't write any of my code wrong. Previous "makemigrations" worked.

It seems like a lot of the Traceback errors have nothing to do with the models.py though.

(hopefully these are easy to read, sorry)

The traceback error:

Traceback (most recent call last):

File "manage.py", line 21, in  main()

File "manage.py", line 17, in main execute_from_command_line(sys.argv)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django
  /core/management/init.py", line 401, in execute_from_command_line
  utility.execute()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/core/management/init.py",
  line 377, in execute django.setup()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/init.py",
  line 24, in setup apps.populate(settings.INSTALLED_APPS)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/registry.py",
  line 114, in populate app_config.import_models()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/config.py",
  line 211, in import_models self.models_module =
  import_module(models_module_name)

File "/usr/lib/python3.6/importlib/init.py", line 126, in
  import_module return _bootstrap._gcd_import(name[level:], package,
  level)

File "", line 994, in _gcd_import

File "", line 971, in _find_and_load

File "", line 955, in
  _find_and_load_unlocked

File "", line 665, in _load_unlocked

File "", line 678, in
  exec_module

File "", line 219, in
  _call_with_frames_removed

File "/home/alatimer/Environments/djangoproject/blog/models.py", line
  6, in  class Post(models.Model):

File "/home/alatimer/Environments/djangoproject/blog/models.py", line
  9, in Post date_posted = models.DateTimeField(defualt=timezone.now)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/db/models/fields/init.py", line 1107, in init super().init(verbose_name, name, **kwargs)

TypeError: init() got an unexpected keyword argument 'defualt'

models.py:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(defualt=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

Body:
try

class Post(models.Model):
    title = models.CharField(max_length=100, blank=True, null=True)
    content = models.TextField(blank=True, null=True)
    date_posted = models.DateTimeField(defualt=timezone.now, blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)


问:
Angular does not see variables values when using timer
I need to call the backend function in angular's component according to the timer.
I tried 2 options:

Option N1:

```<code>_api: Service;

constructor(api: Service){
 this._api = api;
    if (this.timeout != null) {
      clearTimeout(this.timeout);
    }

    this.timeout = setTimeout(() => {
        this.update();
    }, 20000);
}

update()
{
this._api.GetData()….
}
</code>```

The Result of this implementation does not run timer every N seconds, it calls update() function only once. But with this approach I can access the methods/properties of the this.api

OPTION N2:

```<code>_api: Service;

constructor(api: Service){
 this._api = api;
 setInterval(this.update, 2000);
}

update()
{
this._api.GetData()….
}
</code>```

And the result is: for some reason it can't see the methods/properties of this._api.
I checked whether I can see them if I don't use setInterval and it seems that the problem is caused by setInterval.

Please advise how to arrange timer work of some method in Angular?

答:
You are correct in using setInterval to run the chunk every n seconds, but you need to use arrow function notation to refer to the class member variables using this keyword. Try the following

constructor(api: Service) {
  this._api = api;
  setInterval(() => { this.update() }, 2000);    // <-- use arrow function here
}

update() {
  this._api.GetData()….
}
```

<p>But what is the purpose of using an additional variable to refer to the injected service? You could directly refer to it.</p>

<pre class="lang-js prettyprint-override"><code>constructor(api: Service) {
  setInterval(() => { this.update() }, 2000);
}

update() {
  this.api.GetData()….
}
</code>```

Furthermore, I presume you are making some HTTP request in the GetData() function. In that case, it would be better to cancel any impending requests before triggering a new one in the interval.

```<code>dataSubscription: any;

constructor(api: Service) {
  setInterval(() => { this.update() }, 2000);
}

update() {
  if (this.dataSubscription) {
    this.dataSubscription.unsubscribe();    // <-- unsubscribing cancels any impending requests
  }
  this.dataSubscription = this.api.GetData()….
}

</code>```

Body:
I need to call the backend function in angular's component according to the timer.
I tried 2 options:

Option N1:

_api: Service;

constructor(api: Service){
 this._api = api;
    if (this.timeout != null) {
      clearTimeout(this.timeout);
    }

    this.timeout = setTimeout(() => {
        this.update();
    }, 20000);
}

update()
{
this._api.GetData()….
}

The Result of this implementation does not run timer every N seconds, it calls update() function only once. But with this approach I can access the methods/properties of the this.api

OPTION N2:

_api: Service;

constructor(api: Service){
 this._api = api;
 setInterval(this.update, 2000);
}

update()
{
this._api.GetData()….
}

And the result is: for some reason it can't see the methods/properties of this._api.
I checked whether I can see them if I don't use setInterval and it seems that the problem is caused by setInterval.

Please advise how to arrange timer work of some method in Angular?

Body:
You are correct in using setInterval to run the chunk every n seconds, but you need to use arrow function notation to refer to the class member variables using this keyword. Try the following

constructor(api: Service) {
  this._api = api;
  setInterval(() => { this.update() }, 2000);    // <-- use arrow function here
}

update() {
  this._api.GetData()….
}

But what is the purpose of using an additional variable to refer to the injected service? You could directly refer to it.

constructor(api: Service) {
  setInterval(() => { this.update() }, 2000);
}

update() {
  this.api.GetData()….
}

Furthermore, I presume you are making some HTTP request in the GetData() function. In that case, it would be better to cancel any impending requests before triggering a new one in the interval.

dataSubscription: any;

constructor(api: Service) {
  setInterval(() => { this.update() }, 2000);
}

update() {
  if (this.dataSubscription) {
    this.dataSubscription.unsubscribe();    // <-- unsubscribing cancels any impending requests
  }
  this.dataSubscription = this.api.GetData()….
}


问:
Set namespace on all files in folder and sub folders
I have a folder in my PhpStorm project with sub folders. The PHP classes in these folders do not have namespacing and there about 750 class files.

Is there a way in PhpStorm to set the namespace on all classes in a folder and sub folder?  I really do not want to go through each file manually.

答: Find and replace on each folder for the win.</p>


问:
Does returned struct of localtime() need to be freed?
```<code>struct tm *localtime(const time_t *timep);
</code>```

I checked man localtime but there's no words on whether it's my duty to clean it after using.

And in fact I have many similar doubts on functions returning a pointer, how do you determine it should be freed or not ?

答:
You're right to be concerned about functions that return pointers to static data - they are frequently not thread-safe, and it's good practice to avoid them, even if your code is not yet used in a multithreaded environment.

It's better to use the _r form of these functions, i.e. localtime_r()

Body:
struct tm *localtime(const time_t *timep);

I checked man localtime but there's no words on whether it's my duty to clean it after using.

And in fact I have many similar doubts on functions returning a pointer, how do you determine it should be freed or not ?


问:
Getting No loop matching the specified signature and casting error
I'm a beginner to python and machine learning . I get below error when i try to fit data into statsmodels.formula.api OLS.fit()

Traceback (most recent call last):

File "", line 47, in
      regressor_OLS = sm.OLS(y , X_opt).fit()

File
  "E:\Anaconda\lib\site-packages\statsmodels\regression\linear_model.py",
  line 190, in fit
      self.pinv_wexog, singular_values = pinv_extended(self.wexog)

File "E:\Anaconda\lib\site-packages\statsmodels\tools\tools.py",
  line 342, in pinv_extended
      u, s, vt = np.linalg.svd(X, 0)

File "E:\Anaconda\lib\site-packages\numpy\linalg\linalg.py", line
  1404, in svd
      u, s, vt = gufunc(a, signature=signature, extobj=extobj)

TypeError: No loop matching the specified signature and casting was
  found for ufunc svd_n_s

code

```<code>#Importing Libraries
import numpy as np # linear algebra
import pandas as pd # data processing
import matplotlib.pyplot as plt #Visualization

#Importing the dataset
dataset = pd.read_csv('Video_Games_Sales_as_at_22_Dec_2016.csv')
#dataset.head(10)

#Encoding categorical data using panda get_dummies function . Easier and straight forward than OneHotEncoder in sklearn
#dataset = pd.get_dummies(data = dataset , columns=['Platform' , 'Genre' , 'Rating' ] , drop_first = True ) #drop_first use to fix dummy varible trap

dataset=dataset.replace('tbd',np.nan)

#Separating Independent & Dependant Varibles
#X = pd.concat([dataset.iloc[:,[11,13]], dataset.iloc[:,13: ]] , axis=1).values  #Getting important  variables
X = dataset.iloc[:,[10,12]].values
y = dataset.iloc[:,9].values #Dependant Varible (Global sales)

#Taking care of missing data
from sklearn.preprocessing import Imputer
imputer =  Imputer(missing_values = 'NaN' , strategy = 'mean' , axis = 0)
imputer = imputer.fit(X[:,0:2])
X[:,0:2] = imputer.transform(X[:,0:2])

#Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2 , random_state = 0)

#Fitting Mutiple Linear Regression to the Training Set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train,y_train)

#Predicting the Test set Result
y_pred = regressor.predict(X_test)

#Building the optimal model using Backward Elimination (p=0.050)
import statsmodels.formula.api as sm
X = np.append(arr = np.ones((16719,1)).astype(float) , values = X , axis = 1)

X_opt = X[:, [0,1,2]]
regressor_OLS = sm.OLS(y , X_opt).fit()
regressor_OLS.summary()
</code>```

Dataset

dataset link

Couldn't find anything helpful to solve this issue on stack-overflow or google .

答:
Downgrading from NumPy 1.18.4 to 1.15.2 worked for me:
pip install --upgrade numpy==1.15.2

Body:
I'm a beginner to python and machine learning . I get below error when i try to fit data into statsmodels.formula.api OLS.fit()

Traceback (most recent call last):

File "", line 47, in
      regressor_OLS = sm.OLS(y , X_opt).fit()

File
  "E:\Anaconda\lib\site-packages\statsmodels\regression\linear_model.py",
  line 190, in fit
      self.pinv_wexog, singular_values = pinv_extended(self.wexog)

File "E:\Anaconda\lib\site-packages\statsmodels\tools\tools.py",
  line 342, in pinv_extended
      u, s, vt = np.linalg.svd(X, 0)

File "E:\Anaconda\lib\site-packages\numpy\linalg\linalg.py", line
  1404, in svd
      u, s, vt = gufunc(a, signature=signature, extobj=extobj)

TypeError: No loop matching the specified signature and casting was
  found for ufunc svd_n_s

code

#Importing Libraries
import numpy as np # linear algebra
import pandas as pd # data processing
import matplotlib.pyplot as plt #Visualization

#Importing the dataset
dataset = pd.read_csv('Video_Games_Sales_as_at_22_Dec_2016.csv')
#dataset.head(10)

#Encoding categorical data using panda get_dummies function . Easier and straight forward than OneHotEncoder in sklearn
#dataset = pd.get_dummies(data = dataset , columns=['Platform' , 'Genre' , 'Rating' ] , drop_first = True ) #drop_first use to fix dummy varible trap

dataset=dataset.replace('tbd',np.nan)

#Separating Independent & Dependant Varibles
#X = pd.concat([dataset.iloc[:,[11,13]], dataset.iloc[:,13: ]] , axis=1).values  #Getting important  variables
X = dataset.iloc[:,[10,12]].values
y = dataset.iloc[:,9].values #Dependant Varible (Global sales)

#Taking care of missing data
from sklearn.preprocessing import Imputer
imputer =  Imputer(missing_values = 'NaN' , strategy = 'mean' , axis = 0)
imputer = imputer.fit(X[:,0:2])
X[:,0:2] = imputer.transform(X[:,0:2])

#Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2 , random_state = 0)

#Fitting Mutiple Linear Regression to the Training Set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train,y_train)

#Predicting the Test set Result
y_pred = regressor.predict(X_test)

#Building the optimal model using Backward Elimination (p=0.050)
import statsmodels.formula.api as sm
X = np.append(arr = np.ones((16719,1)).astype(float) , values = X , axis = 1)

X_opt = X[:, [0,1,2]]
regressor_OLS = sm.OLS(y , X_opt).fit()
regressor_OLS.summary()

Dataset

dataset link

Couldn't find anything helpful to solve this issue on stack-overflow or google .


问:
How to disable splitting of chunks into different file with vuejs in webpack?
I have laravel-vue stack for my project. While building with mix it splits codes into two main files

```<code>vendor.js
app.js
</code>```

Apart from that there are around 60 files which gets created as chunks like

```<code>0.js
1.js
2.js
...

61.js
</code>```

How to tell webpack to bind these chunks into single file. Does the webpack breaks into chunks for each new component in cue?

答:
You can modify how many chunks you want in your webpack configuration file (example is from a vue.config.js file) like this:

```<code>module.exports = {
  configureWebpack: {
    optimization: {
      splitChunks: {
        minSize: 10000,
        maxSize: 250000,
      }
    }
  },
};
</code>```

I don't know your filesize, but if you increase maxSize as needed, you can have a single file.

Body:
I have laravel-vue stack for my project. While building with mix it splits codes into two main files

vendor.js
app.js

Apart from that there are around 60 files which gets created as chunks like

0.js
1.js
2.js
...

61.js

How to tell webpack to bind these chunks into single file. Does the webpack breaks into chunks for each new component in cue?

Body:
You can modify how many chunks you want in your webpack configuration file (example is from a vue.config.js file) like this:

module.exports = {
  configureWebpack: {
    optimization: {
      splitChunks: {
        minSize: 10000,
        maxSize: 250000,
      }
    }
  },
};

I don't know your filesize, but if you increase maxSize as needed, you can have a single file.