问:
How to get pictures from the flickr API
My goal is to bring in photos based on a search of 5 different words; 5 photos each word. I need to bring the pictures back into my site; preferably smaller versions as I will bring many files in.

I am new to rest services in general. I saw this option:

https://www.flickr.com/services/api/flickr.photos.search.html

and I go to the API explorer link at the bottom:

https://www.flickr.com/services/api/explore/flickr.photos.search

and put in 猫 (meaning cat) for the text field and number of pictures per page at 5 and pages 1, so I would only get back 5 images. This gives me this XML link:

https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=4aa062c1cd2da6075e27b599f583665a&text=%E7%8C%AB&per_page=5&page=1&format=rest&api_sig=9f1beab3f0da8f620e197104eb81aa2a

My question would be what would I do with this request? It looks like it is giving ample information to be able to locate each image, but how would I use this XML to pull the images directly into my site?

答:
shellwe --

After making the request, you'll need to use the information returned to you and build the 'Photo Source URL' (see: https://www.flickr.com/services/api/misc.urls.html)

In essence, you'll want to loop through the response and build the photo url.

As an example, using the first line item provided in your link:

```<code>https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
</code>```

would be:

```<code>https://farm5.staticflickr.com/4218/35419029800_7a39f756be.jpg
</code>```

How you incorporate the final photo urls into your website ultimately depends on how you've got things set up.

Hope this helps some.

Title: How to get pictures from the flickr API

Body:
shellwe --

After making the request, you'll need to use the information returned to you and build the 'Photo Source URL' (see: https://www.flickr.com/services/api/misc.urls.html)

In essence, you'll want to loop through the response and build the photo url.

As an example, using the first line item provided in your link:

https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg

would be:

https://farm5.staticflickr.com/4218/35419029800_7a39f756be.jpg

How you incorporate the final photo urls into your website ultimately depends on how you've got things set up.

Hope this helps some.


来源: stackexchange

问:
JSDoc - How to document object with generic key names?
I need to document an ES6 class with JSDoc that takes in an object that has properties that has the key names as names of people so the key names can be pretty much any string, nothing predefined. So the structure of the object should be like the following:

```<code>{
    "Name of person": {
        "age": 31,
        "hobby": "Tennis"
    },
    "Name of another person": {
        "age": 29,
        "hobby": "Running"
    }
}
</code>```

So the name of each person is a key but it can be anything at all, it's not predefined. An example of what I'm trying to document:

```<code>class ExampleClass {
    /**
     * Creates an instance of ExampleClass
     * @param {Object} peopleObj            - Contains information about people.
     * @param {String} peopleObj.name       - The name of the person. <----- how should this be documented?
     * @param {Number} peopleObj.name.age   - The age of the person.
     * @param {String} peopleObj.name.hobby - The hobby of the person.
     * @memberof ExampleClass
     */
    constructor(peopleObj) {
        // Do stuff
    }
}
</code>```

I feel like if I put "peopleObj.name" it implies that the key should be "name" but not any name you like. So how do I document this with letting the user know that he can insert any name he likes there?

EDIT

For anyone wondering, this is how I ended up documenting this (can't add it as answer since someone closed this question).

```<code>/**
* Information about a single person.
* @typedef Person
* @type {object}
* @property {number} age   - The age of the person.
* @property {string} hobby - The hobby of the person.
*/
class ExampleClass {
    /**
     * Creates an instance of ExampleClass.
     * @param {Object.<string, Person>} peopleObj - Information about people as {@link Person}
     *                                              objects where the key is their name.
     * @memberof ExampleClass
     */
    constructor(peopleObj) {
        // Do stuff
    }
}
</code>```

答:
What you are describing is covered in the @type JSDoc documentation.

The object should be documented as follows:

```<code>/**
 * @typedef Person
 * @type {Object}
 * @property {number} age - the person's age
 * @property {string} hobby - the person's hobby
 */

/**
 * ExampleClass
 */
class ExampleClass {

    /**
     * Creates a dictionary of people
     * @param {Object.<string, Person>} peopleObj - an object with names as keys and Person objects as values.
     * @memberof ExampleClass
     */
     constructor(peopleObj) {}
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to document an ES6 class with JSDoc that takes in an object that has properties that has the key names as names of people so the key names can be pretty much any string, nothing predefined. So the structure of the object should be like the following:

{
    "Name of person": {
        "age": 31,
        "hobby": "Tennis"
    },
    "Name of another person": {
        "age": 29,
        "hobby": "Running"
    }
}

So the name of each person is a key but it can be anything at all, it's not predefined. An example of what I'm trying to document:

class ExampleClass {
    /**
     * Creates an instance of ExampleClass
     * @param {Object} peopleObj            - Contains information about people.
     * @param {String} peopleObj.name       - The name of the person. <----- how should this be documented?
     * @param {Number} peopleObj.name.age   - The age of the person.
     * @param {String} peopleObj.name.hobby - The hobby of the person.
     * @memberof ExampleClass
     */
    constructor(peopleObj) {
        // Do stuff
    }
}

I feel like if I put "peopleObj.name" it implies that the key should be "name" but not any name you like. So how do I document this with letting the user know that he can insert any name he likes there?

EDIT

For anyone wondering, this is how I ended up documenting this (can't add it as answer since someone closed this question).

/**
* Information about a single person.
* @typedef Person
* @type {object}
* @property {number} age   - The age of the person.
* @property {string} hobby - The hobby of the person.
*/
class ExampleClass {
    /**
     * Creates an instance of ExampleClass.
     * @param {Object.<string, Person>} peopleObj - Information about people as {@link Person}
     *                                              objects where the key is their name.
     * @memberof ExampleClass
     */
    constructor(peopleObj) {
        // Do stuff
    }
}

Body:
What you are describing is covered in the @type JSDoc documentation.

The object should be documented as follows:

/**
 * @typedef Person
 * @type {Object}
 * @property {number} age - the person's age
 * @property {string} hobby - the person's hobby
 */

/**
 * ExampleClass
 */
class ExampleClass {

    /**
     * Creates a dictionary of people
     * @param {Object.<string, Person>} peopleObj - an object with names as keys and Person objects as values.
     * @memberof ExampleClass
     */
     constructor(peopleObj) {}
}


问:
IndexedDB "updates" every browser restart and erases data
I wrote a Firefox WebExtension that downloads data files from a website and uses IndexedDB to store/update the data.  The .SQLite file that is created is ~2GB in size.  Whenever I restart Firefox, the extension executes the onupgradeneeded event, even though I always use version "1".  I create the database object stores and indexes in that event, so all my data ends up getting deleted.

The only time this doesn't happen is when I close Firefox while the data is being downloaded or stored.  The next time I start Firefox, it does not execute the event (as should be the case).  It then continues to update the database as it was programmed to do.

I installed the SQLite Manager extension in hopes that I could identify something causing the issue to the database, but nothing was obvious to me.

Here is part of my background script:

```<code>init().then(fetchData).then(addData).catch(dberror);

function init() {
    req = indexedDB.open("db", 1);

    req.onupgradeneeded = e => {
        var name;
        var key;

        console.log("Upgrading database...", e.oldVersion, e.newVersion);
        db = e.currentTarget.result;
        var store = db.createObjectStore("db", { keyPath: "KEY" });
        db.createObjectStore("version", { keyPath: "version" });

        for (name in indexes) {
            key = ...
            store.createIndex(name, key);
        };
    };

    return new Promise( (resolve, reject) => {
        req.onsuccess = e => {
            db = e.currentTarget.result;
            db.onerror = dberror;
            var cursor = db.transaction("MECs").objectStore("MECs").index("STATUS_DATE").openCursor(null, 'prev');
            cursor.onsuccess = e => {
                if (e.target.result) {
                    lastMod = e.target.result.key;
                    fileYear = lastMod.getFullYear();
                }
                else lastMod = new Date(startingfileYear, 0);
                resolve(lastMod);
            }
            cursor.onerror = reject;
        };
        req.onerror = e => {
            dberror(e);
            reject(e);
        }
    });
}

function fetchData(param) {
    // Get data based on the param and return it
    return fetchFile(filename);
}

function addData(data) {
    var trans = db.transaction("db", "readwrite");
    var store = trans.objectStore("db");
    var req;
    var n = 0;
    var data2 = [];
    var addPromise;

    trans.onerror = event => console.log("Error! Error! ", event.target.error);
    trans.onabort = event => console.log("Abort! Abort! ", event.target.error);

    data.forEach((row, index) => {
        //process data here
        data2 = ...
    });

    (function storeRegData(n) {
        var row = data[n];
        if (!row) return;
        req = store.put(row);
        req.onsuccess = event => {
            numUpdated++;
            storeRegData(++n);
        }
        req.onabort = event => console.log("Abort! Abort! ", event.target.error);
        req.onerror = event => console.log("Error! Error! ", event.target.error);
    })(0);   // I'm storing one row at a time because the transaction is failing when I queue too many rows.

    addPromise = fetchData(data2).then(
        response => {
            var trans2 = db.transaction("db", "readwrite");
            var store2 = trans2.objectStore("db");
            var req2;
            response.forEach(row => {
                req2 = store2.put(row);
                req2.onsuccess = event => numUpdated++;
                req2.onerror = console.log;
            });
            return new Promise((resolve, reject) => trans2.oncomplete = e => resolve(response));
        },
        console.log)
    );

    return new Promise((resolve, reject) => trans.oncomplete = e => {
        if (noMoreData)
            resolve(addPromise);
        else if (moreData)
            resolve( addPromise.then(fetchData).then(addData) );
    });
}
</code>```

And here is my manifest

```<code>{
"author": "Name",
"manifest_version": 2,
"name": "Extension",
"description": "Extension",
"version": "3.0",

"applications": {
  "gecko": {
    "strict_min_version": "50.0",
    "id": "myID",
    "update_url": "https://update.me"
  }
},

"background": {
  "scripts": [
    "js/background.js"
  ]
},

"content_scripts": [
  {
    "matches": [ "https://match.me/*" ],
    "js": [
      "script.js"
    ],
    "css": [
      "style.css"
    ]
  }
],

"icons": {
  "48": "icon.png"
},

"options_ui": {
  "page": "options.html"
},

"page_action": {
  "browser_style": true,
  "default_icon": {
    "19": "icon-19.png",
    "38": "icon-38.png"
  },
  "default_title": "Extension",
  "default_popup": "popup.html"
},

"permissions": [
  "https://web.address/*",
  "downloads",
  "notifications",
  "storage",
  "tabs",
  "webRequest",
  "webNavigation"
],

"web_accessible_resources": [
  "pictures.png"
]
}
</code>```

Why does Firefox think the database is at version 0 when I restart the browser?  I can use the stored data after I download it, so why does it overwrite it on every restart?  I could possibly do a workaround where I only create the store and indexes on extension installation or update, but that's not a solution to the actual issue.

UPDATE: I tried the following to no avail -

Close the database and re-open after storing each data file

Create a new object store for each data file

UPDATE 2:  It appears this is related to a storage issue.  Apparently, 2GB is the storage limit for non-persistent storage.  In Firefox you can by-pass this by making the storage persistent with the following command:
indexedDB.open("db", { version: 1, storage: "persistent" })

See the bugzilla report here.

Unfortunately, when run from a background page, the popup asking for confirmation is not handled, so you can never acknowledge it.  Supposedly, when Firefox 56 comes out, you'll be able to use the "unlimitedStorage" permission, which will by-pass the confirmation popup, so it should work from the background page.

Update 3:  So it looks like the limit is actually ~1.5 GB.  I just spent over a week re-coding the extension to create and use a different database for each year of data, making each database no larger than 150 MB.  And still onupgradeneeded executes when I restart the browser and wipes all my data.  If, however, I limit the total amount of data in all the databases to the above limit, it works.  Unfortunately, I'm still in the same boat.

Does no one have any ideas?

答:
As I mentioned in the updates to my question, there appears to be a limit of ~1.5GB for the "default" storage of indexedDB.  Changing the storage to "persistent" will remove that limit.  Because persistent storage currently requires user input, however, the database has to be opened from a window that can handle a UI response.

This can be done from the background script by creating a new window with browser.window.create() and opening the database from there.  There are security restrictions that prevent inline scripts from running in the new page, so I had to link to local javascript files for that (i.e. .  I think you can also change the content security policy with a manifest instruction, but I didn't do that.

Hopefully, the unlimitedStorage permission will be supported in Firefox 56, which will remove the popup, allowing a persistent database to be created/accessed directly from the background script.

Body:
I wrote a Firefox WebExtension that downloads data files from a website and uses IndexedDB to store/update the data.  The .SQLite file that is created is ~2GB in size.  Whenever I restart Firefox, the extension executes the onupgradeneeded event, even though I always use version "1".  I create the database object stores and indexes in that event, so all my data ends up getting deleted.

The only time this doesn't happen is when I close Firefox while the data is being downloaded or stored.  The next time I start Firefox, it does not execute the event (as should be the case).  It then continues to update the database as it was programmed to do.

I installed the SQLite Manager extension in hopes that I could identify something causing the issue to the database, but nothing was obvious to me.

Here is part of my background script:

init().then(fetchData).then(addData).catch(dberror);

function init() {
    req = indexedDB.open("db", 1);

    req.onupgradeneeded = e => {
        var name;
        var key;

        console.log("Upgrading database...", e.oldVersion, e.newVersion);
        db = e.currentTarget.result;
        var store = db.createObjectStore("db", { keyPath: "KEY" });
        db.createObjectStore("version", { keyPath: "version" });

        for (name in indexes) {
            key = ...
            store.createIndex(name, key);
        };
    };

    return new Promise( (resolve, reject) => {
        req.onsuccess = e => {
            db = e.currentTarget.result;
            db.onerror = dberror;
            var cursor = db.transaction("MECs").objectStore("MECs").index("STATUS_DATE").openCursor(null, 'prev');
            cursor.onsuccess = e => {
                if (e.target.result) {
                    lastMod = e.target.result.key;
                    fileYear = lastMod.getFullYear();
                }
                else lastMod = new Date(startingfileYear, 0);
                resolve(lastMod);
            }
            cursor.onerror = reject;
        };
        req.onerror = e => {
            dberror(e);
            reject(e);
        }
    });
}

function fetchData(param) {
    // Get data based on the param and return it
    return fetchFile(filename);
}

function addData(data) {
    var trans = db.transaction("db", "readwrite");
    var store = trans.objectStore("db");
    var req;
    var n = 0;
    var data2 = [];
    var addPromise;

    trans.onerror = event => console.log("Error! Error! ", event.target.error);
    trans.onabort = event => console.log("Abort! Abort! ", event.target.error);

    data.forEach((row, index) => {
        //process data here
        data2 = ...
    });

    (function storeRegData(n) {
        var row = data[n];
        if (!row) return;
        req = store.put(row);
        req.onsuccess = event => {
            numUpdated++;
            storeRegData(++n);
        }
        req.onabort = event => console.log("Abort! Abort! ", event.target.error);
        req.onerror = event => console.log("Error! Error! ", event.target.error);
    })(0);   // I'm storing one row at a time because the transaction is failing when I queue too many rows.

    addPromise = fetchData(data2).then(
        response => {
            var trans2 = db.transaction("db", "readwrite");
            var store2 = trans2.objectStore("db");
            var req2;
            response.forEach(row => {
                req2 = store2.put(row);
                req2.onsuccess = event => numUpdated++;
                req2.onerror = console.log;
            });
            return new Promise((resolve, reject) => trans2.oncomplete = e => resolve(response));
        },
        console.log)
    );

    return new Promise((resolve, reject) => trans.oncomplete = e => {
        if (noMoreData)
            resolve(addPromise);
        else if (moreData)
            resolve( addPromise.then(fetchData).then(addData) );
    });
}

And here is my manifest

{
"author": "Name",
"manifest_version": 2,
"name": "Extension",
"description": "Extension",
"version": "3.0",

"applications": {
  "gecko": {
    "strict_min_version": "50.0",
    "id": "myID",
    "update_url": "https://update.me"
  }
},

"background": {
  "scripts": [
    "js/background.js"
  ]
},

"content_scripts": [
  {
    "matches": [ "https://match.me/*" ],
    "js": [
      "script.js"
    ],
    "css": [
      "style.css"
    ]
  }
],

"icons": {
  "48": "icon.png"
},

"options_ui": {
  "page": "options.html"
},

"page_action": {
  "browser_style": true,
  "default_icon": {
    "19": "icon-19.png",
    "38": "icon-38.png"
  },
  "default_title": "Extension",
  "default_popup": "popup.html"
},

"permissions": [
  "https://web.address/*",
  "downloads",
  "notifications",
  "storage",
  "tabs",
  "webRequest",
  "webNavigation"
],

"web_accessible_resources": [
  "pictures.png"
]
}

Why does Firefox think the database is at version 0 when I restart the browser?  I can use the stored data after I download it, so why does it overwrite it on every restart?  I could possibly do a workaround where I only create the store and indexes on extension installation or update, but that's not a solution to the actual issue.

UPDATE: I tried the following to no avail -

Close the database and re-open after storing each data file

Create a new object store for each data file

UPDATE 2:  It appears this is related to a storage issue.  Apparently, 2GB is the storage limit for non-persistent storage.  In Firefox you can by-pass this by making the storage persistent with the following command:
indexedDB.open("db", { version: 1, storage: "persistent" })

See the bugzilla report here.

Unfortunately, when run from a background page, the popup asking for confirmation is not handled, so you can never acknowledge it.  Supposedly, when Firefox 56 comes out, you'll be able to use the "unlimitedStorage" permission, which will by-pass the confirmation popup, so it should work from the background page.

Update 3:  So it looks like the limit is actually ~1.5 GB.  I just spent over a week re-coding the extension to create and use a different database for each year of data, making each database no larger than 150 MB.  And still onupgradeneeded executes when I restart the browser and wipes all my data.  If, however, I limit the total amount of data in all the databases to the above limit, it works.  Unfortunately, I'm still in the same boat.

Does no one have any ideas?

Body:
As I mentioned in the updates to my question, there appears to be a limit of ~1.5GB for the "default" storage of indexedDB.  Changing the storage to "persistent" will remove that limit.  Because persistent storage currently requires user input, however, the database has to be opened from a window that can handle a UI response.

This can be done from the background script by creating a new window with browser.window.create() and opening the database from there.  There are security restrictions that prevent inline scripts from running in the new page, so I had to link to local javascript files for that (i.e. <script src="db.js"></script>.  I think you can also change the content security policy with a manifest instruction, but I didn't do that.

Hopefully, the unlimitedStorage permission will be supported in Firefox 56, which will remove the popup, allowing a persistent database to be created/accessed directly from the background script.


问:
How to get values from dynamically generated DOM input elements Java
so I have this HTML code:

```<code><form method="get" action="#" id="startForm">
    <input type="text" name="period" id="period" placeholder="The number of days"/>
    <input type="submit" name="submit" value="submit" id="startSubmit"/>
</form>
</code>```

and this is the JavaScript code:

```<code>var btnSubmit = document.getElementById('startSubmit');
btnSubmit.addEventListener('click', function (e) {

    e.preventDefault();
    var myForm = document.createElement('form');
    var period  = document.getElementById('period').value;

    for(var i = 0; i < period ; i++){

        var input0 = document.createElement('input');

        input0.setAttribute('type', 'text');
        input0.setAttribute('placeholder', 'The count of tasks');
        input0.setAttribute('style', 'margin: 10px');
        input0.setAttribute('id', 'taskDone'+i);
        input0.setAttribute('onchange', 'myFunction()');

        document.body.appendChild(input0);
        myForm.appendChild(input0);
        document.body.appendChild(myForm);

        function myFunction(){
            var  taskDone = document.getElementById('taskDone').value;
            var  newForm = document.createElement('form');

            for(var j = 0; j < taskDone ; j++){

                var input1 = document.createElement('input');

                input1.setAttribute('type', 'text');
                input1.setAttribute('id', 'time'+i);

                document.body.appendChild(input1);
                newForm.appendChild(input1);
                document.body.appendChild(newForm);
            };
        };
    };
    console.log(myForm);
});
</code>```

so my problem is that in the function when I try to take the value from the generated DOM element it will reset the page what I want to do is to take the number that is going to be placed into the input and make as many new inputs textboxes as it's the number is typed (it takes the number from the generated dom element and creates new dom element)

答:
You need to define the function myFunction() as myFunction = function(){..}
Secondly the id attribute needs to be unique. Hence use

input0.setAttribute('id', 'taskDone'+i); to set the id and

```<code>input0.setAttribute('onchange', 'myFunction("'+i+'")');
</code>```

to call the function.

Similarly access the id as

```<code>var  taskDone = document.getElementById('taskDone'+i).value;
</code>```

Try the fiddle - https://jsfiddle.net/djbb79d8/

Body:
so I have this HTML code:

<form method="get" action="#" id="startForm">
    <input type="text" name="period" id="period" placeholder="The number of days"/>
    <input type="submit" name="submit" value="submit" id="startSubmit"/>
</form>

and this is the JavaScript code:

var btnSubmit = document.getElementById('startSubmit');
btnSubmit.addEventListener('click', function (e) {

    e.preventDefault();
    var myForm = document.createElement('form');
    var period  = document.getElementById('period').value;

    for(var i = 0; i < period ; i++){

        var input0 = document.createElement('input');

        input0.setAttribute('type', 'text');
        input0.setAttribute('placeholder', 'The count of tasks');
        input0.setAttribute('style', 'margin: 10px');
        input0.setAttribute('id', 'taskDone'+i);
        input0.setAttribute('onchange', 'myFunction()');

        document.body.appendChild(input0);
        myForm.appendChild(input0);
        document.body.appendChild(myForm);

        function myFunction(){
            var  taskDone = document.getElementById('taskDone').value;
            var  newForm = document.createElement('form');

            for(var j = 0; j < taskDone ; j++){

                var input1 = document.createElement('input');

                input1.setAttribute('type', 'text');
                input1.setAttribute('id', 'time'+i);

                document.body.appendChild(input1);
                newForm.appendChild(input1);
                document.body.appendChild(newForm);
            };
        };
    };
    console.log(myForm);
});

so my problem is that in the function when I try to take the value from the generated DOM element it will reset the page what I want to do is to take the number that is going to be placed into the input and make as many new inputs textboxes as it's the number is typed (it takes the number from the generated dom element and creates new dom element)

Body:
You need to define the function myFunction() as myFunction = function(){..}
Secondly the id attribute needs to be unique. Hence use

input0.setAttribute('id', 'taskDone'+i); to set the id and

input0.setAttribute('onchange', 'myFunction("'+i+'")');

to call the function.

Similarly access the id as

var  taskDone = document.getElementById('taskDone'+i).value;

Try the fiddle - https://jsfiddle.net/djbb79d8/


问:
min and max in multidimensional-array
hi i am trying to find min and max values of x and y how can i find this min and max functions is not working correctly</p>

```<code>$dataPoints = array(
 array('x' => 2343, 'y' => 4322),
  array('x' => 103, 'y' => 303 ),
  array('x' => 2345,'y' => 2321 ),
  array('x' => 310, 'y' => 2044 ),
  array('x' => 173, 'y' => 793 ),
  array('x' => 456, 'y' => 2675),
  array('x' => 24, 'y' => 819 ));
</code>```

ContentLicense: CC BY-SA 2.5

Title: min and max in multidimensional-array

Body:
hi i am trying to find min and max values of x and y how can i find this min and max functions is not working correctly

$dataPoints = array(
 array('x' => 2343, 'y' => 4322),
  array('x' => 103, 'y' => 303 ),
  array('x' => 2345,'y' => 2321 ),
  array('x' => 310, 'y' => 2044 ),
  array('x' => 173, 'y' => 793 ),
  array('x' => 456, 'y' => 2675),
  array('x' => 24, 'y' => 819 ));

Body:
//to find max use rsort() & for min :sort()
//Below will return you the max
$dataPoints = array(
     array('x' => 2343, 'y' => 4322),
      array('x' => 103, 'y' => 7303 ),
      array('x' => 2345,'y' => 2321 ),
      array('x' => 310, 'y' => 2044 ),
      array('x' => 173, 'y' => 793 ),
      array('x' => 456, 'y' => 2675),
      array('x' => 24, 'y' => 819 ));

      foreach ($dataPoints as $key=>$value) {
        $x[$key] = $value['x'];
        $y[$key] = $value['y'];
      }
rsort($x,SORT_DESC);
rsort($y,SORT_DESC);

echo $x[0];
echo $y[0];


问:
CSS Background-color works bottom half only
I'm trying to make a social media button using an a tag and a fontawesome icon. I want to make the entire background color to be black by using css, but when I tried it only the bottom half turned black.

Html:

```<code><div class="social-media">
    <a class="social-media-icon">
        <i class="fa fa-instagram fa-4x" aria-hidden="true"></i>
    </a>
</div>
</code>```

Css (less):

```<code>.social-media{
    .social-media-icon{
        color: red;
        background-color: black;
    }
}
</code>```

What should I do?

答:
First change your display of a tag to inline-block as it's a inline element, then using pseudo-selector :after add new styling and using z-index align that back of fontawesome icon.

.social-media-icon {
  display: inline-block;
  position: relative;
  color: red;
}

.social-media-icon:after {
  content: "";
  position: absolute;
  left: 2%;
  bottom: 8px;
  width: 95%;
  height: 25px;
  background: black;
  z-indeX: -1;
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<div class="social-media">

    <i class="fa fa-instagram fa-4x" aria-hidden="true"></i>

</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a social media button using an a tag and a fontawesome icon. I want to make the entire background color to be black by using css, but when I tried it only the bottom half turned black.

Html:

Css (less):

.social-media{
    .social-media-icon{
        color: red;
        background-color: black;
    }
}

What should I do?

Body:
First change your display of a tag to inline-block as it's a inline element, then using pseudo-selector :after add new styling and using z-index align that back of fontawesome icon.

.social-media-icon {
  display: inline-block;
  position: relative;
  color: red;
}

.social-media-icon:after {
  content: "";
  position: absolute;
  left: 2%;
  bottom: 8px;
  width: 95%;
  height: 25px;
  background: black;
  z-indeX: -1;
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<div class="social-media">
  <a class="social-media-icon">
    <i class="fa fa-instagram fa-4x" aria-hidden="true"></i>
  </a>
</div>


问:
Boolean expression with four operands
How can I write a boolean expression which will be true if and only if there is one out of four operands is true? I need the most succinct possible way to write it.</p>

答:
Here's how I'd do it:

```<code>((A XOR B) XOR (C XOR D)) AND (NOT (A AND B)) AND (NOT (C AND D))
</code>```

The first part

```<code>((A XOR B) XOR (C XOR D))
</code>```

Works for all cases except three inputs being true, hence the second part.

Title: Boolean expression with four operands

Body:
Here's how I'd do it:

((A XOR B) XOR (C XOR D)) AND (NOT (A AND B)) AND (NOT (C AND D))

The first part

((A XOR B) XOR (C XOR D))

Works for all cases except three inputs being true, hence the second part.


问:
How do I create a vector that is the sum of the last 12 months' values in a time series?
So, I have a two time-series with a monthly frequency. Monthly Brazilian federal government revenue ("receitamensal" vector) and monthly spending ("gastomensal" vector). I want to create two vectors out of those series: accumulated revenue in the last 12 months and accumulated spending in the last 12 months. So that in any given month, the value is the sum of the last 12 months.
I'm using the BETS library to get my data. Right now my code is:

```<code>library(BETS)
Receitamensal <- BETS.deflate(BETS.get(7544),
                          BETS.GET(433),
                            type='perc')
Gastomensal <- BETS.deflate(BETS.get(7546),
                        BETS.GET(433),
                          type='perc')
</code>```

So, what do I do?

答:
wow that package had a lot of dependencies to install.
Does the following work for you?

```<code>tail(Receitamensal,12)
tail(Gastomensal, 12)
</code>```

And then simply put sum() around each one.

EDIT:

If you are looking for a rolling sum as indicated in the comments, then you will find the rollsum() function from the zoo package (thank you @ulfelder) the most useful:

```<code>install.packages("zoo")
zoo::rollsum(Receitamensal, 12, fill = NA, align = "right")
</code>```

Body:
So, I have a two time-series with a monthly frequency. Monthly Brazilian federal government revenue ("receitamensal" vector) and monthly spending ("gastomensal" vector). I want to create two vectors out of those series: accumulated revenue in the last 12 months and accumulated spending in the last 12 months. So that in any given month, the value is the sum of the last 12 months.
I'm using the BETS library to get my data. Right now my code is:

library(BETS)
Receitamensal <- BETS.deflate(BETS.get(7544),
                          BETS.GET(433),
                            type='perc')
Gastomensal <- BETS.deflate(BETS.get(7546),
                        BETS.GET(433),
                          type='perc')

So, what do I do?

Body:
wow that package had a lot of dependencies to install.
Does the following work for you?

tail(Receitamensal,12)
tail(Gastomensal, 12)

And then simply put sum() around each one.

EDIT:

If you are looking for a rolling sum as indicated in the comments, then you will find the rollsum() function from the zoo package (thank you @ulfelder) the most useful:

install.packages("zoo")
zoo::rollsum(Receitamensal, 12, fill = NA, align = "right")


问:
Java program wont react till the window gets resized
I have a simple java program and when I run it, using eclipse, it displays the 3 JButtons that I have set to the layout. The buttons are set to change the alignment of the layout. So you press left to align left and right to align right and center to align center.

While the buttons do this, the alignment doesn't change in the window till you resize it.

Ive tried updating both the jdk and eclipse and didnt make a difference and I cant see a problem with the code itself.

Anyone know why this is?

import javax.swing.JFrame;

```<code>public class Main {
    public static void main(String []args){

        Layout_buttonsAndActionEvents layout = new Layout_buttonsAndActionEvents();

        layout.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        layout.setSize(300,300);
        layout.setVisible(true);

    }

}

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Layout_buttonsAndActionEvents extends JFrame {

    private static final long serialVersionUID = 1L;
    private JButton leftButton;
    private JButton rightButton;
    private JButton centerButton;

    private FlowLayout layout;
    private Container container;

    public Layout_buttonsAndActionEvents(){
        super("The Title");
        layout = new FlowLayout();
        container = new Container();
        setLayout(layout);

        leftButton = new JButton("Left");
        add(leftButton);
    //Align to the left
        leftButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent event){
                layout.setAlignment(FlowLayout.LEFT);
                layout.layoutContainer(container);
            }
        });

    centerButton = new JButton("Center");
    add(centerButton);

    //Align to the right
         centerButton.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent event){
                    layout.setAlignment(FlowLayout.CENTER);
                    layout.layoutContainer(container);
                }
            });

         rightButton = new JButton("Right");
        add(rightButton);

        //Align to the right
            rightButton.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent event){
                    layout.setAlignment(FlowLayout.RIGHT);
                    layout.layoutContainer(container);
                }
            });

    }

}
</code>```

答:
Because you are adding the buttons to the JFrame's content
pane ( via the add() method which is really a call to
getContentPane().add() under the covers ) you need to call revalidate() on
the content pane.

In the three action listeners, change:

```<code>    layout.setAlignment(FlowLayout.XXX);
    layout.layoutContainer(container);
</code>```

to:

```<code>    layout.setAlignment(FlowLayout.XXX);
    getContentPane().revalidate();
</code>```

Also, you can remove all references to the variable named 'container' as it does nothing in your example.

Body:
I have a simple java program and when I run it, using eclipse, it displays the 3 JButtons that I have set to the layout. The buttons are set to change the alignment of the layout. So you press left to align left and right to align right and center to align center.

While the buttons do this, the alignment doesn't change in the window till you resize it.

Ive tried updating both the jdk and eclipse and didnt make a difference and I cant see a problem with the code itself.

Anyone know why this is?

import javax.swing.JFrame;

public class Main {
    public static void main(String []args){

        Layout_buttonsAndActionEvents layout = new Layout_buttonsAndActionEvents();

        layout.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        layout.setSize(300,300);
        layout.setVisible(true);

    }

}

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Layout_buttonsAndActionEvents extends JFrame {

    private static final long serialVersionUID = 1L;
    private JButton leftButton;
    private JButton rightButton;
    private JButton centerButton;

    private FlowLayout layout;
    private Container container;

    public Layout_buttonsAndActionEvents(){
        super("The Title");
        layout = new FlowLayout();
        container = new Container();
        setLayout(layout);

        leftButton = new JButton("Left");
        add(leftButton);
    //Align to the left
        leftButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent event){
                layout.setAlignment(FlowLayout.LEFT);
                layout.layoutContainer(container);
            }
        });

    centerButton = new JButton("Center");
    add(centerButton);

    //Align to the right
         centerButton.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent event){
                    layout.setAlignment(FlowLayout.CENTER);
                    layout.layoutContainer(container);
                }
            });

         rightButton = new JButton("Right");
        add(rightButton);

        //Align to the right
            rightButton.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent event){
                    layout.setAlignment(FlowLayout.RIGHT);
                    layout.layoutContainer(container);
                }
            });

    }

}

Body:
Because you are adding the buttons to the JFrame's content
pane ( via the add() method which is really a call to
getContentPane().add() under the covers ) you need to call revalidate() on
the content pane.

In the three action listeners, change:

    layout.setAlignment(FlowLayout.XXX);
    layout.layoutContainer(container);

to:

    layout.setAlignment(FlowLayout.XXX);
    getContentPane().revalidate();

Also, you can remove all references to the variable named 'container' as it does nothing in your example.


问:
Tomcat Access Logs in Spring Boot for different operating systems
Recently I've started to work with Spring Boot and have a following question:

We have different environments (like stage, development, production) and all of them can be run on windows or linux.
So I've created application-stage.properties, application-prod.properties, application-devl.properties to specify stuff like db connections and so on because its OS agnostic (the same for windows and linux).

Now I would like to enable access logs for embedded Tomcat server.
So following various guides I used the following in my application.properties file:

```<code>server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.enabled=true
</code>```

I was forced to specify a relative path because we use both linux and windows, however I would like the access log to be created in different places depending on the OS .
For example, we store logs in windows under c:\<product>\logs and in linux we use /var/log/<product>/...

For usual logs we use logbacks and it allows stuff like this, but since access log is not actually logback driven and instead uses Valves, my question is: how we can achieve the same level of flexibility here?

I don't think I should provide additional profile for this and use it like:

```<code>--spring.profiles.active=windows / linux
</code>```

Because I believe spring boot has some solution up on its sleeves for this :)
Thanks a lot in advance

答:
Here is the solution I've come up with. Maybe it will help someone.

There are 2 steps.

Step 1
I've created application-windows.properties and application-linux.properties files in src/main/resources. These files hold the OS dependent configuration.

For example in Linux I specify something like this:

```<code>server.tomcat.accesslog.directory=/var/log/access_logs
</code>```

For windows it can be (for example):

```<code>server.tomcat.accesslog.directory=C:\\Temp\\access_logs
</code>```

Step 2

The spring boot application (the file with a main method) usually looks like this:

```<code>// maybe some additional annotations
@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String[] args) throws Exception {
       SpringApplication.run(..., args);
    }
}
</code>```

The documentation of spring boot in paragraph 25.2 states that profiles can be added programmatically
So I've slightly changed the main class to allow this programmatic addition:

```<code>// maybe some additional annotations
@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String[] args) throws Exception {
       SpringApplication myApp = new SpringApplication(...);
       myApp.setAdditionalProfiles(getOSName());
       myApp.run(args);
    }

    private static String getOSName() {
     String os = System.getProperty("os.name");
     if (os.toLowerCase().contains("win")) {
         return "windows";
     }
     else {
          return "linux";
     }
    }
}
</code>```

That's it, now there is no need to specify the profiles in --spring.profiles.active property (I usually use this to specify the environment, like staging, production, etc.
The point it that spring will load the relevant property file automatically now.

Thanks to all the people who have suggested their solutions!

Body:
Recently I've started to work with Spring Boot and have a following question:

We have different environments (like stage, development, production) and all of them can be run on windows or linux.
So I've created application-stage.properties, application-prod.properties, application-devl.properties to specify stuff like db connections and so on because its OS agnostic (the same for windows and linux).

Now I would like to enable access logs for embedded Tomcat server.
So following various guides I used the following in my application.properties file:

server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.enabled=true

I was forced to specify a relative path because we use both linux and windows, however I would like the access log to be created in different places depending on the OS .
For example, we store logs in windows under c:\<product>\logs and in linux we use /var/log/<product>/...

For usual logs we use logbacks and it allows stuff like this, but since access log is not actually logback driven and instead uses Valves, my question is: how we can achieve the same level of flexibility here?

I don't think I should provide additional profile for this and use it like:

--spring.profiles.active=windows / linux

Because I believe spring boot has some solution up on its sleeves for this :)
Thanks a lot in advance

Body:
Here is the solution I've come up with. Maybe it will help someone.

There are 2 steps.

Step 1
I've created application-windows.properties and application-linux.properties files in src/main/resources. These files hold the OS dependent configuration.

For example in Linux I specify something like this:

server.tomcat.accesslog.directory=/var/log/access_logs

For windows it can be (for example):

server.tomcat.accesslog.directory=C:\\Temp\\access_logs

Step 2

The spring boot application (the file with a main method) usually looks like this:

// maybe some additional annotations
@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String[] args) throws Exception {
       SpringApplication.run(..., args);
    }
}

The documentation of spring boot in paragraph 25.2 states that profiles can be added programmatically
So I've slightly changed the main class to allow this programmatic addition:

// maybe some additional annotations
@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String[] args) throws Exception {
       SpringApplication myApp = new SpringApplication(...);
       myApp.setAdditionalProfiles(getOSName());
       myApp.run(args);
    }

    private static String getOSName() {
     String os = System.getProperty("os.name");
     if (os.toLowerCase().contains("win")) {
         return "windows";
     }
     else {
          return "linux";
     }
    }
}

That's it, now there is no need to specify the profiles in --spring.profiles.active property (I usually use this to specify the environment, like staging, production, etc.
The point it that spring will load the relevant property file automatically now.

Thanks to all the people who have suggested their solutions!


问:
Automate @usage documentation in Rcpp functions
How can I automate the documentation of the @usage section for Rcpp functions? In an ordinary R function within a package documented using roxygen2, the Usage section is added automatically. This is convenient for automatically documenting default arguments.

```<code>#' @title Hello world
#' @return Prints 'Hello world'
#' @export
#' @useDynLib RcppSandBox

hello <- function(x = 1) {
  print("Hello, world!")
}
</code>```

Hello world

Usage

hello(x = 1)

Value

Prints 'Hello world'

Yet when I write an analogous script with Rcpp, the documentation is produced but no @usage section is written.

```<code>//' Hello, Rcpp!
//' @name rcpp_hello
//' @param CharVec Print x or not.
//' @export

#include <Rcpp.h>
using namespace Rcpp;

// This is a simple function using Rcpp that creates an R list
// containing a character vector and a numeric vector.
//
// Learn more about how to use Rcpp at:
//
//   http://www.rcpp.org/
//   http://adv-r.had.co.nz/Rcpp.html
//
// and browse examples of code using Rcpp at:
//
//   http://gallery.rcpp.org/
//

// [[Rcpp::export]]
List rcpp_hello(bool CharVec = true) {
  CharacterVector x = CharacterVector::create("foo", "bar");
  NumericVector y   = NumericVector::create(0.0, 1.0);
  List z            = List::create(x, y);
  if (CharVec) {
  } else {
    List z = List::create(y);
  }
  return z;
}
</code>```

Hello, Rcpp!

Description

Hello, Rcpp!

Arguments

CharVec  Print x or not.

I looked at the source code and documentation for dplyr::between, but there doesn't seem to be any special @usage section, yet the @usage section is present in the documentation.

I also looked at http://r-pkgs.had.co.nz/man.html and http://dirk.eddelbuettel.com/code/rcpp/Rcpp-attributes.pdf and Ctrl-F'd for usage, but found nothing relevant.

I know I can add //' @usage rcpp_hello(CharVec = TRUE) in this particular case but the advantage of letting roxygen2 automate the process is that I can change the default arguments.

DESCRIPTION file:

```<code>Package: RcppSandBox
Type: Package
Title: What the Package Does (Title Case)
Version: 0.1.0
Author: Who wrote it
Maintainer: The package maintainer <yourself@somewhere.net>
Description: More about what it does (maybe more than one line)
    Use four spaces when indenting paragraphs within the Description.
License: What license is it under?
Encoding: UTF-8
LazyData: true
Imports: Rcpp (>= 0.12.10)
LinkingTo: Rcpp
RoxygenNote: 6.0.1
</code>```

Session info:

```<code>> sessionInfo()
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=English_Australia.1252  LC_CTYPE=English_Australia.1252    LC_MONETARY=English_Australia.1252
[4] LC_NUMERIC=C                       LC_TIME=English_Australia.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RcppSandBox_0.1.0    dplyr_0.5.0          RevoUtilsMath_10.0.0

loaded via a namespace (and not attached):
[1] compiler_3.4.0   magrittr_1.5     R6_2.2.2         assertthat_0.2.0 RevoUtils_10.0.4 DBI_0.6-1        tools_3.4.0
[8] tibble_1.3.0     Rcpp_0.12.10
</code>```

答:
You haven't needed to use @usage since Roxygen2 2.0 and 3.0.0 for R or Rcpp. The issue you are running into is your roxygen tags are not directly above the Rcpp attributes tag...

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

//' Hello, Rcpp!
//' @param CharVec Print x or not.
//' @export
// [[Rcpp::export]]
Rcpp::List rcpp_hello(bool CharVec = true) {
  Rcpp::CharacterVector x = Rcpp::CharacterVector::create("foo", "bar");
  Rcpp::NumericVector y   = Rcpp::NumericVector::create(0.0, 1.0);
  Rcpp::List z            = Rcpp::List::create(x, y);
  if (CharVec) {
  } else {
    Rcpp::List z = Rcpp::List::create(y);
  }
  return z;
}
</code>```

Try the above. This also means you do not need the @name tag either...

Body:
How can I automate the documentation of the @usage section for Rcpp functions? In an ordinary R function within a package documented using roxygen2, the Usage section is added automatically. This is convenient for automatically documenting default arguments.

#' @title Hello world
#' @return Prints 'Hello world'
#' @export
#' @useDynLib RcppSandBox

hello <- function(x = 1) {
  print("Hello, world!")
}

Hello world

Usage

hello(x = 1)

Value

Prints 'Hello world'

Yet when I write an analogous script with Rcpp, the documentation is produced but no @usage section is written.

//' Hello, Rcpp!
//' @name rcpp_hello
//' @param CharVec Print x or not.
//' @export

#include <Rcpp.h>
using namespace Rcpp;

// This is a simple function using Rcpp that creates an R list
// containing a character vector and a numeric vector.
//
// Learn more about how to use Rcpp at:
//
//   http://www.rcpp.org/
//   http://adv-r.had.co.nz/Rcpp.html
//
// and browse examples of code using Rcpp at:
//
//   http://gallery.rcpp.org/
//

// [[Rcpp::export]]
List rcpp_hello(bool CharVec = true) {
  CharacterVector x = CharacterVector::create("foo", "bar");
  NumericVector y   = NumericVector::create(0.0, 1.0);
  List z            = List::create(x, y);
  if (CharVec) {
  } else {
    List z = List::create(y);
  }
  return z;
}

Hello, Rcpp!

Description

Hello, Rcpp!

Arguments

CharVec  Print x or not.

I looked at the source code and documentation for dplyr::between, but there doesn't seem to be any special @usage section, yet the @usage section is present in the documentation.

I also looked at http://r-pkgs.had.co.nz/man.html and http://dirk.eddelbuettel.com/code/rcpp/Rcpp-attributes.pdf and Ctrl-F'd for usage, but found nothing relevant.

I know I can add //' @usage rcpp_hello(CharVec = TRUE) in this particular case but the advantage of letting roxygen2 automate the process is that I can change the default arguments.

DESCRIPTION file:

Package: RcppSandBox
Type: Package
Title: What the Package Does (Title Case)
Version: 0.1.0
Author: Who wrote it
Maintainer: The package maintainer <yourself@somewhere.net>
Description: More about what it does (maybe more than one line)
    Use four spaces when indenting paragraphs within the Description.
License: What license is it under?
Encoding: UTF-8
LazyData: true
Imports: Rcpp (>= 0.12.10)
LinkingTo: Rcpp
RoxygenNote: 6.0.1

Session info:

> sessionInfo()
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=English_Australia.1252  LC_CTYPE=English_Australia.1252    LC_MONETARY=English_Australia.1252
[4] LC_NUMERIC=C                       LC_TIME=English_Australia.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RcppSandBox_0.1.0    dplyr_0.5.0          RevoUtilsMath_10.0.0

loaded via a namespace (and not attached):
[1] compiler_3.4.0   magrittr_1.5     R6_2.2.2         assertthat_0.2.0 RevoUtils_10.0.4 DBI_0.6-1        tools_3.4.0
[8] tibble_1.3.0     Rcpp_0.12.10

Body:
You haven't needed to use @usage since Roxygen2 2.0 and 3.0.0 for R or Rcpp. The issue you are running into is your roxygen tags are not directly above the Rcpp attributes tag...

#include <Rcpp.h>

//' Hello, Rcpp!
//' @param CharVec Print x or not.
//' @export
// [[Rcpp::export]]
Rcpp::List rcpp_hello(bool CharVec = true) {
  Rcpp::CharacterVector x = Rcpp::CharacterVector::create("foo", "bar");
  Rcpp::NumericVector y   = Rcpp::NumericVector::create(0.0, 1.0);
  Rcpp::List z            = Rcpp::List::create(x, y);
  if (CharVec) {
  } else {
    Rcpp::List z = Rcpp::List::create(y);
  }
  return z;
}

Try the above. This also means you do not need the @name tag either...


问:
android: NeighboringCellInfo always empty !? why?
i'm trying to get info about the neighboring cells my phone can "see" atm. so far so good. i do this like this:

```<code>telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//...
ArrayList<NeighboringCellInfo> neighboringCellList = (ArrayList<NeighboringCellInfo>) telManager.getNeighboringCellInfo();
</code>```

unfortunately, this list turns out to be empty all the time. even in different places. i live in berlin, so i don't think it's because there is actually just the one cell available!

update:
my permissions look like this:

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_UPDATES" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
</code>```

答:
getNeighboringCellInfo() is deprecated in android . You should use getAllCellInfo() and save output of that in a List and using a loop on each element of List decide which is neighbor using element.isRegistered() .
NeighboringCells have isRegistered() == false .

Body:
i'm trying to get info about the neighboring cells my phone can "see" atm. so far so good. i do this like this:

telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//...
ArrayList<NeighboringCellInfo> neighboringCellList = (ArrayList<NeighboringCellInfo>) telManager.getNeighboringCellInfo();

unfortunately, this list turns out to be empty all the time. even in different places. i live in berlin, so i don't think it's because there is actually just the one cell available!

update:
my permissions look like this:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_UPDATES" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />


问:
Why this while loop does not work?
Thanks everyone! I changed my code, and it still gives the error:

list index out of range.

Why?

```<code>M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)
</code>```

`

Title: Why this while loop does not work?

Body:
Thanks everyone! I changed my code, and it still gives the error:

list index out of range.

Why?

M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)

`

Body:
You can debug by printing to observe what is happening in the code:

Before Popping:
======================================
B and C:  [2, 4, 6]
B:  [1, 3, 5]
C:  [2, 4, 6]
======================================
Enters B[0] <= C[0] since 1 <= 2
B[0] = "1" is popped out

New value for B and C:
B:  [3, 5]
C:  [2, 4, 6]

======================================
Enters C[0] <= B[0] since 2 <= 3
C[0] = "2" is popped out

New value for B and C:
B:  [3, 5]
C:  [4, 6]

After Popping:
*****************************************
B and C:  [4, 6]
B:  [3, 5]
C:  [4, 6]
*****************************************
Before Popping:
======================================
B and C:  [4, 6]
B:  [3, 5]
C:  [4, 6]
======================================
Enters B[0] <= C[0] since 3 <= 4
B[0] = "3" is popped out

New value for B and C:
B:  [5]
C:  [4, 6]

======================================
Enters C[0] <= B[0] since 4 <= 5
C[0] = "4" is popped out

New value for B and C:
B:  [5]
C:  [6]

After Popping:
*****************************************
B and C:  [6]
B:  [5]
C:  [6]
*****************************************
Before Popping:
======================================
B and C:  [6]
B:  [5]
C:  [6]
======================================
Enters B[0] <= C[0] since 5 <= 6
B[0] = "5" is popped out

New value for B and C:
B:  []
C:  [6]

======================================

Finally, it gets IndexError: list index out of range since, B is [].


问:
Loop over every name and check to see if name begins with 'A'
Loop over every name and check to see if name begins with 'A'
If it does add a message to output array saying No gift for {person's name}
Otherwise, add a message to output array saying {Person's name} loved their gift!

var person;
var gift;
function christmasTree(people){
   var output = [];
for (var i =0; i<person.length; i++){
    if (person.startsWith ("Aimee")){
      output.push(No gift for Aimee.);
    }
    if (person.startsWith ("Ariana"){
       output.push(No gift for Ariana.);
    }
    else {
    output.push(person[i] loved their gift);
    }
    return output;
}
person = ['Aimee', 'Ariana', 'Billy', 'Joel', 'Zaire', 'Lily']
gift = christmasTree [person, 'gift'];
console.log(gift);
//Output should look like:
// This should be output:
  //   [
  //     "Billy loved their gift!",
  //     "Joel loved their gift!",
 //     "No gift for Aimee",
 //     "No gift for Ariana",
 //     "Zaire loved their gift!",
 //     "Lily loved their gift!",
 //  ]
 ```

*Having trouble getting the required output. Please advise on what how I can fix this.

答:
There are quite some errors in the code that you have posted, for instance, the array object should be accessed as follows:
person[i].startsWith("A") instead of person.startsWith("A")

please take a look at the following snippet:

function christmasTree(people){
    var output = [];
    for (var i =0; i<person.length; i++){
        if (person[i].toLowerCase().startsWith("a")) {
            output.push('No gift for' + person[i]);
        }
        else {
            output.push(person[i] + ' loved their gift');
        }
    }
return output;
}
person = ['Aimee', 'Ariana', 'Billy', 'Joel', 'Zaire', 'Lily'];
gift = christmasTree(person);
console.log(gift);```

Body:
Loop over every name and check to see if name begins with 'A'
If it does add a message to output array saying No gift for {person's name}
Otherwise, add a message to output array saying {Person's name} loved their gift!

var person;
var gift;
function christmasTree(people){
   var output = [];
for (var i =0; i<person.length; i++){
    if (person.startsWith ("Aimee")){
      output.push(No gift for Aimee.);
    }
    if (person.startsWith ("Ariana"){
       output.push(No gift for Ariana.);
    }
    else {
    output.push(person[i] loved their gift);
    }
    return output;
}
person = ['Aimee', 'Ariana', 'Billy', 'Joel', 'Zaire', 'Lily']
gift = christmasTree [person, 'gift'];
console.log(gift);
//Output should look like:
// This should be output:
  //   [
  //     "Billy loved their gift!",
  //     "Joel loved their gift!",
 //     "No gift for Aimee",
 //     "No gift for Ariana",
 //     "Zaire loved their gift!",
 //     "Lily loved their gift!",
 //  ]

*Having trouble getting the required output. Please advise on what how I can fix this.


问:
solve block form objective-c to swift 3
I have a trouble problem on block, on objective-c it works well, but I couldn't translate to swift 3,

in objective-c case

```<code>typedef void (^PanCellToDeleteBlock)(NSIndexPath *cellIndexPath);

@interface MyCollectionViewCell : UICollectionViewCell<UIGestureRecognizerDelegate>

@property (copy , nonatomic) PanCellToDeleteBlock panCellToDeleteBlock;
</code>```

in swift 3 case

```<code>public typealias PanCellToDeleteBlock = (_ cell:NSIndexPath) -> Void

class MyCollectionViewCell: UICollectionViewCell,UIGestureRecognizerDelegate {

let panCellToDeleteBlock:PanCellToDeleteBlock? = nil
</code>```

it looks no swift.....

here is when I use it in same class

in objective-c case

```<code>if (_panCellToDeleteBlock) {
    _panCellToDeleteBlock(_cellIndexPath);
}
</code>```

in swift case, everything looks wrong

```<code>if (self.panCellToDeleteBlock != nil) {
    self.panCellToDeleteBlock(self.cellIndexPath)
}
</code>```

here is must crazy part, this is in viweController
OC case

```<code>cell.panCellToDeleteBlock = ^(NSIndexPath *cellIndexPath){
    [weakSelf.dataArray removeObjectAtIndex:cellIndexPath.row];
    [weakSelf.collectionView reloadData];
};
</code>```

swift part I already can't do anything ....

答:
Have you tried this</p>

```<code>public typealias PanCellToDeleteBlock = (_ indexPath:NSIndexPath) -> Void

cell.panCellToDeleteBlock: PanCellToDeleteBlock = { [weak self] indexPath in
    self?.dataArray.remove(at: indexPath.row)
    self?.collectionView.reloadData()
}
</code>```

Title: solve block form objective-c to swift 3

Body:
I have a trouble problem on block, on objective-c it works well, but I couldn't translate to swift 3,

in objective-c case

typedef void (^PanCellToDeleteBlock)(NSIndexPath *cellIndexPath);

@interface MyCollectionViewCell : UICollectionViewCell<UIGestureRecognizerDelegate>

@property (copy , nonatomic) PanCellToDeleteBlock panCellToDeleteBlock;

in swift 3 case

public typealias PanCellToDeleteBlock = (_ cell:NSIndexPath) -> Void

class MyCollectionViewCell: UICollectionViewCell,UIGestureRecognizerDelegate {

let panCellToDeleteBlock:PanCellToDeleteBlock? = nil

it looks no swift.....

here is when I use it in same class

in objective-c case

if (_panCellToDeleteBlock) {
    _panCellToDeleteBlock(_cellIndexPath);
}

in swift case, everything looks wrong

if (self.panCellToDeleteBlock != nil) {
    self.panCellToDeleteBlock(self.cellIndexPath)
}

here is must crazy part, this is in viweController
OC case

cell.panCellToDeleteBlock = ^(NSIndexPath *cellIndexPath){
    [weakSelf.dataArray removeObjectAtIndex:cellIndexPath.row];
    [weakSelf.collectionView reloadData];
};

swift part I already can't do anything ....

Body:
Have you tried this

public typealias PanCellToDeleteBlock = (_ indexPath:NSIndexPath) -> Void

cell.panCellToDeleteBlock: PanCellToDeleteBlock = { [weak self] indexPath in
    self?.dataArray.remove(at: indexPath.row)
    self?.collectionView.reloadData()
}


问:
android: Fragment for RecycleView
I read about ListView and RecycleView. I understood that RecycleView is a more advanced and flexible version of ListView. So like ListFragment for listView, Is there any inbuilt fragment for RecyleView? If i need a RecycleView inside a fragment then what is the proper way to implement it?

答:
Is there any inbuilt fragment for RecyleView?

No. there isn't one.

Unlike ListFragment for listview, there isn't any default implementation provided for RecyclerView. And RecyclerView is available through the support-v7 library and it's not bundled with the Android source.

For difference between RecyclerView and ListView check this:

Recyclerview vs ListView

Here are some good resources you will like to read:

Creating Lists and Cards

Using the RecyclerView

And an example:

RecyclerViewFragment

Title: android: Fragment for RecycleView


问:
How to disable caching correctly in Sqlalchemy orm session?
I have I thread in a daemon, that loops and performs the following query:

```<code>    try:
        newsletter = self.session.query(models.Newsletter).\
               filter(models.Newsletter.status == 'PROCESSING').\
               limit(1).one()
    except sa.orm.exc.NoResultFound:
        self.logger.debug('No PROCESSING newsletters found. Sleeping...')
        self.sleep()
        return
    # (...) more code to do with found newsletter
</code>```

Where the sleep method just stops the execution of this thread for the configured time and the return statement returns to the main loop. However I found, that if I change any newsletter's status to 'PROCESSING' while the daemon is running, nothing happens, ie. the query still raises NoResultFound. If I restart the daemon however, it will find the newsletter. So I see, that the results of this query must be cached. What can I do to invalidate the cache? session.expire_all() doesn't work. I could also create new Session() object every iteration, but don't know if it's a good approach regarding system resources.

答:
Hmm I already found the answer, you apparently need to explicitly do session.commit() to get it to update, or you need to set autocommit=True on the session, through for example the sessionmaker.

```<code>sessionmaker(bind=self.engine, autocommit=True)
</code>```

However I haven't tested the session.commit() way

So this isn't a caching issue it seems to be just the way transactions work

Body:
I have I thread in a daemon, that loops and performs the following query:

    try:
        newsletter = self.session.query(models.Newsletter).\
               filter(models.Newsletter.status == 'PROCESSING').\
               limit(1).one()
    except sa.orm.exc.NoResultFound:
        self.logger.debug('No PROCESSING newsletters found. Sleeping...')
        self.sleep()
        return
    # (...) more code to do with found newsletter

Where the sleep method just stops the execution of this thread for the configured time and the return statement returns to the main loop. However I found, that if I change any newsletter's status to 'PROCESSING' while the daemon is running, nothing happens, ie. the query still raises NoResultFound. If I restart the daemon however, it will find the newsletter. So I see, that the results of this query must be cached. What can I do to invalidate the cache? session.expire_all() doesn't work. I could also create new Session() object every iteration, but don't know if it's a good approach regarding system resources.

Body:
Hmm I already found the answer, you apparently need to explicitly do session.commit() to get it to update, or you need to set autocommit=True on the session, through for example the sessionmaker.

sessionmaker(bind=self.engine, autocommit=True)

However I haven't tested the session.commit() way

So this isn't a caching issue it seems to be just the way transactions work


答:
The Swift 3 equivalents are

```<code>public typealias PanCellToDeleteBlock = (IndexPath) -> Void

class MyCollectionViewCell: UICollectionViewCell,UIGestureRecognizerDelegate {

var panCellToDeleteBlock : PanCellToDeleteBlock?
</code>```

```<code>self.panCellToDeleteBlock?(self.cellIndexPath)
</code>```

```<code>cell.panCellToDeleteBlock = { [weak self] indexPath in
    self?.dataArray.remove(at: indexPath.row)
    self?.collectionView.reloadData()
}
</code>```

Title: solve block form objective-c to swift 3

Body:
The Swift 3 equivalents are

public typealias PanCellToDeleteBlock = (IndexPath) -> Void

class MyCollectionViewCell: UICollectionViewCell,UIGestureRecognizerDelegate {

var panCellToDeleteBlock : PanCellToDeleteBlock?

self.panCellToDeleteBlock?(self.cellIndexPath)

cell.panCellToDeleteBlock = { [weak self] indexPath in
    self?.dataArray.remove(at: indexPath.row)
    self?.collectionView.reloadData()
}


问:
Objcopy --writable-text not making elf binary text section writable?
I was trying to make the .text section of an elf binary writable using objcopy --writable-text executable_name. The command executes normally without any errors.

On checking the section permission through readelf I can see that the text section is still has only read and execute permissions.

On going through the objcopy man pages for this particular option is is mentioned that the option is not meaningful for all the binary formats. (Is this the reason I am not able to do so ?).

Can anyone point out what I am missing here.

Thanks

(Ubuntu x86_64 bit machine, GNU objcopy (GNU Binutils for Ubuntu) 2.22.90.20120924)

答:
First complete this:
objcopy --writable-text --set-section-flags .text=CONTENTS,ALLOC,LOAD,CODE

Then objdump -x or readelf -a to view the loading section table which are typically after the program header.  Please see the man page for ELF.  For 32-bit executables for example:

Open the binary with hexedit and look at the value at file offset 0x1C (often 0x34), then traverse through the 0x20 byte structures (a size listed at file offset 0x2a) until you find the one which you identified in the previous dump as containing the .text section.  The second to last long value will be 00000005 (05 00 00 00) and needs to have write added which will become thereby 00000007 (07 00 00 00).  Now it will work as expected without any limitations such as shared library issues with -Wl,--omagic.  A bit technical, but takes a few seconds to do.

Regardless, this one bit flag has caused countless problems and no explanation has clarified this small point which allows it to work flawlessly.

A code solution can be easily compiled with GCC to do the change which is likely easier and a better solution if doing it routinely:

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

int main(int argc, char** argv)
{
    if (argc <= 1) return -1;
    FILE* fp = fopen(argv[1], "r+");
    Elf64_Ehdr teh;
    fread(&teh, sizeof(teh), 1, fp);
    fseek(fp, 0, SEEK_SET);
    if (teh.e_ident[EI_CLASS] == ELFCLASS64) {
        Elf64_Ehdr eh;
        fread(&eh, sizeof(eh), 1, fp);
        Elf64_Phdr* ph = malloc(eh.e_phnum * eh.e_phentsize);
        Elf64_Shdr* sh = malloc(eh.e_shnum * eh.e_shentsize);
        fseek(fp, eh.e_phoff, SEEK_SET);
        fread(ph, eh.e_phentsize, eh.e_phnum, fp);
        fseek(fp, eh.e_shoff, SEEK_SET);
        fread(sh, eh.e_shentsize, eh.e_shnum, fp);
        for (int i = 0; i < eh.e_phnum; i++) {
            if (ph[i].p_vaddr <= eh.e_entry && ph[i].p_vaddr + ph[i].p_memsz > eh.e_entry) {
            fseek(fp, eh.e_phoff + i * eh.e_phentsize + (unsigned int)&((Elf64_Phdr*)0)->p_flags, SEEK_SET);
            ph[i].p_flags |= PF_W;
            fwrite(&ph[i].p_flags, sizeof(ph[i].p_flags), 1, fp);
            }
        }
        for (int i = 0; i < eh.e_shnum; i++) {
            if (sh[i].sh_addr <= eh.e_entry && sh[i].sh_addr + sh[i].sh_size > eh.e_entry) {
            fseek(fp, eh.e_shoff + i * eh.e_shentsize + (unsigned int)&((Elf64_Shdr*)0)->sh_flags, SEEK_SET);
            sh[i].sh_flags |= SHF_WRITE;
            fwrite(&sh[i].sh_flags, sizeof(sh[i].sh_flags), 1, fp);
            }
        }
        free(ph);
        free(sh);
    } else {
        Elf32_Ehdr eh;
        fread(&eh, sizeof(eh), 1, fp);
        Elf32_Phdr* ph = malloc(eh.e_phnum * eh.e_phentsize);
        Elf32_Shdr* sh = malloc(eh.e_shnum * eh.e_shentsize);
        fseek(fp, eh.e_phoff, SEEK_SET);
        fread(ph, eh.e_phentsize, eh.e_phnum, fp);
        fseek(fp, eh.e_shoff, SEEK_SET);
        fread(sh, eh.e_shentsize, eh.e_shnum, fp);
        for (int i = 0; i < eh.e_phnum; i++) {
            if (ph[i].p_vaddr <= eh.e_entry && ph[i].p_vaddr + ph[i].p_memsz > eh.e_entry) {
            fseek(fp, eh.e_phoff + i * eh.e_phentsize + (unsigned int)&((Elf32_Phdr*)0)->p_flags, SEEK_SET);
            ph[i].p_flags |= PF_W;
            fwrite(&ph[i].p_flags, sizeof(ph[i].p_flags), 1, fp);
            }
        }
        for (int i = 0; i < eh.e_shnum; i++) {
            if (sh[i].sh_addr <= eh.e_entry && sh[i].sh_addr + sh[i].sh_size > eh.e_entry) {
            fseek(fp, eh.e_shoff + i * eh.e_shentsize + (unsigned int)&((Elf32_Shdr*)0)->sh_flags, SEEK_SET);
            sh[i].sh_flags |= SHF_WRITE;
            fwrite(&sh[i].sh_flags, sizeof(sh[i].sh_flags), 1, fp);
            }
        }
        free(ph);
        free(sh);
    }
    fflush(fp);
    fclose(fp);
    return 0;
}
</code>```

Body:
First complete this:
objcopy --writable-text --set-section-flags .text=CONTENTS,ALLOC,LOAD,CODE

Then objdump -x or readelf -a to view the loading section table which are typically after the program header.  Please see the man page for ELF.  For 32-bit executables for example:

Open the binary with hexedit and look at the value at file offset 0x1C (often 0x34), then traverse through the 0x20 byte structures (a size listed at file offset 0x2a) until you find the one which you identified in the previous dump as containing the .text section.  The second to last long value will be 00000005 (05 00 00 00) and needs to have write added which will become thereby 00000007 (07 00 00 00).  Now it will work as expected without any limitations such as shared library issues with -Wl,--omagic.  A bit technical, but takes a few seconds to do.

Regardless, this one bit flag has caused countless problems and no explanation has clarified this small point which allows it to work flawlessly.

A code solution can be easily compiled with GCC to do the change which is likely easier and a better solution if doing it routinely:

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

int main(int argc, char** argv)
{
    if (argc <= 1) return -1;
    FILE* fp = fopen(argv[1], "r+");
    Elf64_Ehdr teh;
    fread(&teh, sizeof(teh), 1, fp);
    fseek(fp, 0, SEEK_SET);
    if (teh.e_ident[EI_CLASS] == ELFCLASS64) {
        Elf64_Ehdr eh;
        fread(&eh, sizeof(eh), 1, fp);
        Elf64_Phdr* ph = malloc(eh.e_phnum * eh.e_phentsize);
        Elf64_Shdr* sh = malloc(eh.e_shnum * eh.e_shentsize);
        fseek(fp, eh.e_phoff, SEEK_SET);
        fread(ph, eh.e_phentsize, eh.e_phnum, fp);
        fseek(fp, eh.e_shoff, SEEK_SET);
        fread(sh, eh.e_shentsize, eh.e_shnum, fp);
        for (int i = 0; i < eh.e_phnum; i++) {
            if (ph[i].p_vaddr <= eh.e_entry && ph[i].p_vaddr + ph[i].p_memsz > eh.e_entry) {
            fseek(fp, eh.e_phoff + i * eh.e_phentsize + (unsigned int)&((Elf64_Phdr*)0)->p_flags, SEEK_SET);
            ph[i].p_flags |= PF_W;
            fwrite(&ph[i].p_flags, sizeof(ph[i].p_flags), 1, fp);
            }
        }
        for (int i = 0; i < eh.e_shnum; i++) {
            if (sh[i].sh_addr <= eh.e_entry && sh[i].sh_addr + sh[i].sh_size > eh.e_entry) {
            fseek(fp, eh.e_shoff + i * eh.e_shentsize + (unsigned int)&((Elf64_Shdr*)0)->sh_flags, SEEK_SET);
            sh[i].sh_flags |= SHF_WRITE;
            fwrite(&sh[i].sh_flags, sizeof(sh[i].sh_flags), 1, fp);
            }
        }
        free(ph);
        free(sh);
    } else {
        Elf32_Ehdr eh;
        fread(&eh, sizeof(eh), 1, fp);
        Elf32_Phdr* ph = malloc(eh.e_phnum * eh.e_phentsize);
        Elf32_Shdr* sh = malloc(eh.e_shnum * eh.e_shentsize);
        fseek(fp, eh.e_phoff, SEEK_SET);
        fread(ph, eh.e_phentsize, eh.e_phnum, fp);
        fseek(fp, eh.e_shoff, SEEK_SET);
        fread(sh, eh.e_shentsize, eh.e_shnum, fp);
        for (int i = 0; i < eh.e_phnum; i++) {
            if (ph[i].p_vaddr <= eh.e_entry && ph[i].p_vaddr + ph[i].p_memsz > eh.e_entry) {
            fseek(fp, eh.e_phoff + i * eh.e_phentsize + (unsigned int)&((Elf32_Phdr*)0)->p_flags, SEEK_SET);
            ph[i].p_flags |= PF_W;
            fwrite(&ph[i].p_flags, sizeof(ph[i].p_flags), 1, fp);
            }
        }
        for (int i = 0; i < eh.e_shnum; i++) {
            if (sh[i].sh_addr <= eh.e_entry && sh[i].sh_addr + sh[i].sh_size > eh.e_entry) {
            fseek(fp, eh.e_shoff + i * eh.e_shentsize + (unsigned int)&((Elf32_Shdr*)0)->sh_flags, SEEK_SET);
            sh[i].sh_flags |= SHF_WRITE;
            fwrite(&sh[i].sh_flags, sizeof(sh[i].sh_flags), 1, fp);
            }
        }
        free(ph);
        free(sh);
    }
    fflush(fp);
    fclose(fp);
    return 0;
}


问:
How to use docker with mongo to achieve replication and with opening authentication
I want to use docker run a vm mongodb, at the same time, the mongo configure file use my own defined configure file to archive replication and open authentication.

Scanning some files but don't resolve the problem.

Any ideas?

答:
The docker mongo image has a docker-entrypoint.sh it calls in the Dockerfile

Check if you can:

create your own image which would create the right user and restart mongo with authentication on: see "umputun/mongo-auth" and its init.sh script

or mount a createUser.js script in docker-entrypoint-initdb.d.

See "how to make a mongo docker container with auth"


问:
Ajax does not work in codeigniter 3
I want to make registration in CodeIgniter. Everything is fine, however, I want to add Ajax to show error and success messages. However, it does not work. Here is my view:

```<code><div class="modal-body">

                  <div id="messages"></div>
                  <?php $attributes = array('class' => 'rex-forms', 'name' => 'registrationform', 'id' => 'registrationform'); ?>
                  <?= form_open_multipart('user/register', $attributes); ?>
                      <div class="form-group">
                        <span class="text-danger"><?php echo form_error('username'); ?></span>
                        <input name="username" type="text" class="form-control" placeholder="Имя пользователя">
                      </div>
                      <div class="form-group">
                        <span class="text-danger"><?php echo form_error('mail'); ?></span>
                        <input name="mail" type="email" class="form-control" placeholder="Электронный адрес">
                      </div>
                      <div class="form-group">
                        <span class="text-danger"><?php echo form_error('password2'); ?></span>
                        <input name="password" type="password" class="form-control" placeholder="Пароль">
                      </div>
                      <div class="form-group">
                        <input name="password2" type="password" class="form-control" placeholder="Повторный ввод пароля">
                      </div>
                  </div>
                  <div class="modal-footer">
                    <button type="submit" name="submitforreg" class="rex-bottom-medium rex-btn-icon">
                        <span class="rex-btn-text">регистрация</span>
                        <span class="rex-btn-text-icon"><i class="fa fa-arrow-circle-o-right"></i></span>
                    </button>
                  </div>
                  </form>
                </div>
</code>```

Here is my controller:

```<code><?php
class User extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url', 'security'));
        $this->load->library(array('session', 'form_validation', 'email'));
        $this->load->database();
        $this->load->model('User_model');
    }

    function index()
    {
        $this->register();
    }

    function register()
    {
        //set validation rules
        $this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_dash|min_length[3]|max_length[30]|is_unique[instructors.instructors_slug]xss_clean');
        $this->form_validation->set_rules('mail', 'Email', 'trim|required|valid_email|is_unique[instructors.mail]');
        $this->form_validation->set_rules('password', 'password', 'trim|required|md5|min_length[3]');
        $this->form_validation->set_rules('password2', 'Confirm Password', 'trim|required|md5|matches[password]');

        $to_email= $this->input->post('mail');

        $data['courses'] = $this->popular_courses_model->get_popular_courses();
        $data['news'] = $this->news_model->get_news();

        //validate form input
        if ($this->form_validation->run() == FALSE)
        {
            // fails
            $this->load->view('templates/header');
            $this->load->view('pages/index', $data);
            $this->load->view('templates/footer');
        }
        else
        {
            //insert the user registration details into database
            $data = array(
                'instructors_slug' => $this->input->post('username'),
                'mail' => $to_email,
                'password' => $this->input->post('password')
            );

            // insert form data into database
            if ($this->user_model->insertUser($data)) {

                if ($this->user_model->sendEmail($to_email)) {
                    // successfully sent mail
                    $this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are Successfully Registered! Please confirm the mail sent to your Email-ID!!!</div>');
                    redirect('user/register');
                }
                else
                {
                    // error
                    $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">'.$to_email.'  gondermir '.$this->email->print_debugger().'</div>');
                    redirect('user/register');
                }
            }
            else
            {
                // error
                $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">daxil elemir</div>');
                    redirect('user/register');
            }
        }
    }

    public function login(){
            $data['title'] = 'Sign In';
            $this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_dash|min_length[3]|max_length[30]');
        $this->form_validation->set_rules('password', 'password', 'trim|required|md5|min_length[3]');

            if($this->form_validation->run() === FALSE){
                $this->load->view('login/login', $data);
            } else {

                // Get username
                $username = $this->input->post('username');
                // Get and encrypt the password
                $password = $this->input->post('password');
                // Login user
                $user_id = $this->user_model->login($username, $password);
                if($user_id){
                    // Create session

                    $user_data = array(
                        'instructor_id' => $instructor_id,
                        'id' => $id,
                        'instructors_slug' => $username,
                        'name' => $name,
                        'logged_in' => true
                        );

                    $this->session->set_userdata($user_data);

                    redirect('');
                } else {
                    $this->session->set_flashdata('login_failed', 'Неверныый логин или пароль');
                    redirect('');
                }
            }
        }

        public function logout() {
            $this->session->unset_userdata('logged_in');
            $this->session->unset_userdata('instructor_id');
            $this->session->unset_userdata('id');
            $this->session->unset_userdata('instructors_slug');
            $this->session->unset_userdata('name');

            redirect('');
        }

    function verify($hash=NULL)
    {
        if ($this->user_model->verifyEmailID($hash))
        {
            $this->session->set_flashdata('verify_msg','<div class="alert alert-success text-center">Your Email Address is successfully verified! Please login to access your account!</div>');
            redirect('');
        }
        else
        {
            $this->session->set_flashdata('verify_msg','<div class="alert alert-danger text-center">Sorry! There is error verifying your Email Address!</div>');
            redirect('');
        }
    }

}
?>
</code>```

and here is my register.js file:

```<code>$(document).ready(function() {
    $("#registrationform").unbind('submit').bind('submit', function() {
        var form = $(this);

        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            dataType: 'json',
            success:function(response) {
                if(response.success == true) {
                    $("#messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
                      '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
                      response.messages+
                    '</div>');

                    $("#registerForm")[0].reset();
                    $(".text-danger").remove();
                    $(".form-group").removeClass('has-error').removeClass('has-success');

                }
                else {
                    $.each(response.messages, function(index, value) {
                        var element = $("#"+index);

                        $(element)
                        .closest('.form-group')
                        .removeClass('has-error')
                        .removeClass('has-success')
                        .addClass(value.length > 0 ? 'has-error' : 'has-success')
                        .find('.text-danger').remove();

                        $(element).after(value);

                    });
                }
            } // /success
        });  // /ajax

        return false;
    });
});
</code>```

答:
You problem is the dynamic binding issue.

Maybe you are calling the ready function before the JQuery Javascript is included?

Here is your error.

Uncaught ReferenceError: $ is not defined at register.js:

```<code>// Remove This.
//$(document).ready(function() {
//$("#registrationform").unbind('submit').bind('submit', function() {
//   var form = $(this);

// Add This.
$('#your_model_id').on('click', '.submit_button_class', function(e) {

var str = $( "#registrationform" ).serialize();
</code>```

And Please You should put the references to the jquery scripts first.
like this.

```<code><script language="JavaScript" type="text/javascript" src="your_script.js"></script>
</code>```

Title: Ajax does not work in codeigniter 3

Body:
I want to make registration in CodeIgniter. Everything is fine, however, I want to add Ajax to show error and success messages. However, it does not work. Here is my view:

                  <?php $attributes = array('class' => 'rex-forms', 'name' => 'registrationform', 'id' => 'registrationform'); ?>
                  <?= form_open_multipart('user/register', $attributes); ?>

                        <?php echo form_error('username'); ?>
                        <input name="username" type="text" class="form-control" placeholder="Имя пользователя">

                        <?php echo form_error('mail'); ?>
                        <input name="mail" type="email" class="form-control" placeholder="Электронный адрес">

                        <?php echo form_error('password2'); ?>
                        <input name="password" type="password" class="form-control" placeholder="Пароль">

                        <input name="password2" type="password" class="form-control" placeholder="Повторный ввод пароля">

                    <button type="submit" name="submitforreg" class="rex-bottom-medium rex-btn-icon">
                        регистрация

                    </button>

                  </form>

Here is my controller:

<?php
class User extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url', 'security'));
        $this->load->library(array('session', 'form_validation', 'email'));
        $this->load->database();
        $this->load->model('User_model');
    }

    function index()
    {
        $this->register();
    }

    function register()
    {
        //set validation rules
        $this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_dash|min_length[3]|max_length[30]|is_unique[instructors.instructors_slug]xss_clean');
        $this->form_validation->set_rules('mail', 'Email', 'trim|required|valid_email|is_unique[instructors.mail]');
        $this->form_validation->set_rules('password', 'password', 'trim|required|md5|min_length[3]');
        $this->form_validation->set_rules('password2', 'Confirm Password', 'trim|required|md5|matches[password]');

        $to_email= $this->input->post('mail');

        $data['courses'] = $this->popular_courses_model->get_popular_courses();
        $data['news'] = $this->news_model->get_news();

        //validate form input
        if ($this->form_validation->run() == FALSE)
        {
            // fails
            $this->load->view('templates/header');
            $this->load->view('pages/index', $data);
            $this->load->view('templates/footer');
        }
        else
        {
            //insert the user registration details into database
            $data = array(
                'instructors_slug' => $this->input->post('username'),
                'mail' => $to_email,
                'password' => $this->input->post('password')
            );

            // insert form data into database
            if ($this->user_model->insertUser($data)) {

                if ($this->user_model->sendEmail($to_email)) {
                    // successfully sent mail
                    $this->session->set_flashdata('msg','
You are Successfully Registered! Please confirm the mail sent to your Email-ID!!!
');
                    redirect('user/register');
                }
                else
                {
                    // error
                    $this->session->set_flashdata('msg','
'.$to_email.'  gondermir '.$this->email->print_debugger().'
');
                    redirect('user/register');
                }
            }
            else
            {
                // error
                $this->session->set_flashdata('msg','
daxil elemir
');
                    redirect('user/register');
            }
        }
    }

    public function login(){
            $data['title'] = 'Sign In';
            $this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_dash|min_length[3]|max_length[30]');
        $this->form_validation->set_rules('password', 'password', 'trim|required|md5|min_length[3]');

            if($this->form_validation->run() === FALSE){
                $this->load->view('login/login', $data);
            } else {

                // Get username
                $username = $this->input->post('username');
                // Get and encrypt the password
                $password = $this->input->post('password');
                // Login user
                $user_id = $this->user_model->login($username, $password);
                if($user_id){
                    // Create session

                    $user_data = array(
                        'instructor_id' => $instructor_id,
                        'id' => $id,
                        'instructors_slug' => $username,
                        'name' => $name,
                        'logged_in' => true
                        );

                    $this->session->set_userdata($user_data);

                    redirect('');
                } else {
                    $this->session->set_flashdata('login_failed', 'Неверныый логин или пароль');
                    redirect('');
                }
            }
        }

        public function logout() {
            $this->session->unset_userdata('logged_in');
            $this->session->unset_userdata('instructor_id');
            $this->session->unset_userdata('id');
            $this->session->unset_userdata('instructors_slug');
            $this->session->unset_userdata('name');

            redirect('');
        }

    function verify($hash=NULL)
    {
        if ($this->user_model->verifyEmailID($hash))
        {
            $this->session->set_flashdata('verify_msg','
Your Email Address is successfully verified! Please login to access your account!
');
            redirect('');
        }
        else
        {
            $this->session->set_flashdata('verify_msg','
Sorry! There is error verifying your Email Address!
');
            redirect('');
        }
    }

}
?>

and here is my register.js file:

$(document).ready(function() {
    $("#registrationform").unbind('submit').bind('submit', function() {
        var form = $(this);

        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            dataType: 'json',
            success:function(response) {
                if(response.success == true) {
                    $("#messages").html('
'+
                      '<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>'+
                      response.messages+
                    '
');

                    $("#registerForm")[0].reset();
                    $(".text-danger").remove();
                    $(".form-group").removeClass('has-error').removeClass('has-success');

                }
                else {
                    $.each(response.messages, function(index, value) {
                        var element = $("#"+index);

                        $(element)
                        .closest('.form-group')
                        .removeClass('has-error')
                        .removeClass('has-success')
                        .addClass(value.length > 0 ? 'has-error' : 'has-success')
                        .find('.text-danger').remove();

                        $(element).after(value);

                    });
                }
            } // /success
        });  // /ajax

        return false;
    });
});

Body:
You problem is the dynamic binding issue.

Maybe you are calling the ready function before the JQuery Javascript is included?

Here is your error.

Uncaught ReferenceError: $ is not defined at register.js:

// Remove This.
//$(document).ready(function() {
//$("#registrationform").unbind('submit').bind('submit', function() {
//   var form = $(this);

// Add This.
$('#your_model_id').on('click', '.submit_button_class', function(e) {

var str = $( "#registrationform" ).serialize();

And Please You should put the references to the jquery scripts first.
like this.

<script language="JavaScript" type="text/javascript" src="your_script.js"></script>