'await' operator can only be used within an async method with c# exception?

Question: I am using hellosign c# api and when I am calling function for account info using below code
var helloSign = new HelloSignClient("username", "password");
    Account account = await helloSign.Account.GetAsync();
    Console.WriteLine("Your current callback: " + account.CallbackUrl);

I am getting below error.
Error    2    The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

below is GetAsync method
public async Task<Account> GetAsync()
        {
            AccountWrapper accountWrapper = await helloSignService.MakeRequestAsync<AccountWrapper>(settings.HelloSignSettings.Endpoints.Account.Get);
            return accountWrapper.Account;
        }

this is type of account class
public class Account : AccountCondensedWithRole
    {
        [JsonProperty("callback_url")]
        public string CallbackUrl { get; internal set; }
    }

Can some one tell me how to call this or how to debug this ???
Comment: did that signature change recently - could you try a clean build?
Comment: @DanielA.White i already did rebuilt.. but not working ... so i thought of posting it ..
Comment: @DanielA.White what does signature change recently means ...???
Answer: The message is pretty clear. This line must be inside a method marked with async:
Account account = await helloSign.Account.GetAsync();

Answer: you should wrap this block in Async Method like this
public async Task<Type> MethodAsync(){
    // other code if needed ....
    var helloSign = new HelloSignClient("username", "password");
    Account account = await helloSign.Account.GetAsync();
    Console.WriteLine("Your current callback: " + account.CallbackUrl);
    return type;

}

Comment: How should I call inside main method, if I want to some return type.. How can i do that can u please explain it to me ??
Answer: You can only use await in an async method.
Here's another question to the same problem await operator


In Borderlands, what is the fastest way to get 5 seconds of hangtime in a vehicle?

Question: I'm starting fresh and seeing if I can complete bigger challenges earlier on to net large amounts of experience for a low-level character. Out of these challanges, the hang-time in vehicle challanges seem like they would be particularly easy to net.
Because of this, I'm curious: What's the earliest point in the game where one can net the 5 second hang-time achievement? If you don't know if your suggested location is the earliest location, that's fine; I have never gotten the 5 seconds of hangtime achievement and so would like to know where it can be gotten regardless of time spent reaching the location.
Comment: I got the first 2 levels of the hang-time challenges by using the ramps in Dahl Headlands whenever I was driving about. Even with a little dedication it took a while. Not sure if there are better places to get it - Hence not posting an answer ;)
Answer: Melee off Piss Wash Gully (Earliest opportunity)
If you have a partner Melee your vehicle while you're in it on the Piss Wash ramp, that also unlocks it. (Youtube Video)
Dahl Headlands
I've gotten it in the Dahl Headlands off the beginning Ramp.  You've got to be lined up perfectly.
Rust Commons East
There's a bridge near the Middle of Nowhere that (at one point) during the game is lowered for you (I believe it's on the mission to go to Janistown);  If you talk to the Claptrap, and then back up the racer, you'll get insane air if you jump the bridge while it's about 50 degrees or better.
General Knoxx's Armory
The highways in the Sunken Sea provide good opportunities. The easiest way to do it is to get in the racer and launch your self off the left end of a broken road (where the curb hits the road). The hitting of the curb makes you go higher and makes it more likely.
Comment: Thanks for the detailed answer :D  It's very much appreciated. I'll be trying these out tonight :3
Comment: A great answer!
Comment: Mêlée off Piss Wash Gully is how speed-runner Youkai did it too.
Answer: I did it by sliding the runner on its side while it was moving. This gave me the achievement even though it was a glitch. It it is very difficult to do, but you can do it as soon as you get the runner.
Comment: Hey superslayer, Welcome to Arqade! Thanks for taking the time to answer a question! I edited your answer to improve clarity; if you feel that it doesn't convey the same message, then feel free to revert the edit.
Comment: Also, have you ever repeated this glitch? If it's repeatable, do you think you could get us a screenshot?


Ceiling Fan with Recessed Lights

Question: This is for U.S. based electrical in a house built in 2001.
Currently I have a ceiling fan w/light on a 14/2 NM-B run to a single-pole light switch. When the switch is turned off, neither the fan nor light turn on. If switch is turned on, the light or fan can be activated based off pull chains on fan.
I want to add 4 recessed lights off the ceiling fan (which I will be replacing with a remote controlled fan), except I need the lights controlled by the switch, and the fan to be always on (as it will be controlled by the remote control, and not the switch).
I believe I need to pull 14/3 NM-B wire in place of the 14/2 to make this work. Please confirm. See diagram for proposed solution.

FYI: Wire B is going to a different room, Wire C is the wire I would switch out with 14/3.
Also, I left out Ground from the diagram to make it cleaner, I would obviously ground everything.
Answer: You have this right-on-the-money, save for one thing.  I'd pull a 14/4 instead of the 14/3 -- that way, if you want to have two separate switched hots at the fan location as well as a switched hot for the cans, you can do that.  Copper is cheap compared to the hassle of re-pulling wires!
Comment: 14/3 is able to switch two hots... 14/4 would just give an additional but unnecessary neutral.
Comment: I meant atop the existing switched hot for the cans :)
Comment: Oh, so 3 switch loops ?
Comment: @Kris 14/4 has `white black red blue` good for 3 switched hots.  (Or 2 switched and an unswitched.  Or 3-phase.) 14/2/2 has `black red and 2 whites`, intended for 2 complete circuits.   14/2/2 is the universal donor since you can re-mark one of the whites.
Comment: @Harper 14/2/2 is actually more common at the DIY local store.. 14/4 i've only seen through electrical warehouses.

Ceiling Fan with Recessed Lights


Multiple Angular validators work independently, but not together

Question: I've written two validation directives. Each one works fine individually, but when both are applied, numberValidator fails anytime rangeValidator fails (so, because "3" fails rangeValidator, it fails numberValidator as well, even though it passes when rangeValidator is out of the picture).
Logging verifies that the numberValidator is indeed failing (vs some error in HTML).
I would have expected the directives to function independently of one another -- I don't want the user to enter "3" and still see "Must be a number."
Using a number input is not an option.
My JS:
app.directive('rangeValidator', function () {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            var min = scope.$eval(attrs.minValue);
            var max = scope.$eval(attrs.maxValue);
            ctrl.$parsers.unshift(function (viewValue) {
                if (parseInt(viewValue) >= min && parseInt(viewValue) <= max) {
                    // it is valid
                    ctrl.$setValidity('rangeValidator', true);
                    return viewValue;
                } else {
                    // it is invalid, return undefined (no model update)
                    ctrl.$setValidity('rangeValidator', false);
                    return undefined;
                }
            });
        }
    };
});

app.directive('numberValidator', function () {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue) {
                if (!isNaN(parseInt(viewValue))) {
                    // it is valid
                    console.log('Number Validator passed!');
                    ctrl.$setValidity('numberValidator', true);
                    return viewValue;
                } else {
                    // it is invalid, return undefined (no model update)
                    ctrl.$setValidity('numberValidator', false);
                    return undefined;
                }
            });
        }
    };
});

Answer: I see you've followed the Angular docs' advice and returned undefined for invalid values within your parser function. The problem with doing that (in your case) is that it breaks the parsers pipeline: the directive that first detects an invalid value will pass undefined to the next one, which will obviously deem it invalid as well.
I can think of two solutions:
1) Let the original value flow through the parsers pipeline:
ctrl.$parsers.unshift(function (viewValue) {
    if (parseInt(viewValue) >= min && parseInt(viewValue) <= max) {
        ctrl.$setValidity('rangeValidator', true);
    } else {
        ctrl.$setValidity('rangeValidator', false);
    }
    return viewValue;
});

...

ctrl.$parsers.unshift(function (viewValue) {
    if (!isNaN(parseInt(viewValue))) {
        ctrl.$setValidity('numberValidator', true);
    } else {
        ctrl.$setValidity('numberValidator', false);
    }
    return viewValue;
});

Working demo here.
This won't prevent the model from being updated with invalid values, and you'll need to use the $valid or $invalid properties to check the field state before using its value, but you'll be able to check errors independently of each other.
2) Set different priorities to both directives
You can control the order the directives are executed by setting different priorities to each one, and by doing so you can check for invalid values in an incremental way, like this:
Invalid range
Invalid number

Working demo here.
It comes with a caveat: it may become very messy as more validations are added.
Personally I like the first approach better, even though it doesn't prevent the model from being updated with invalid values.
Comment: My aim was to avoid updating the model (checking field state was going to get tiresome quickly in this case), so I appreciate the dual approach. Thanks!


Can't post on my own business time line. Error says. The user hasn't authorized the application to perform this action

Question: I have a problem when trying to post on my own business time line on facebook.
I get an error that says:
"(OAuthException)(#200) The user hasn't authorized the application to perform this action"
I think this has to do with the scope "publish_actions" in somehow but how can I authorize this publish_actions permission exactly?
I have looked everywhere in my account under "https://developers.facebook.com"
I have put my App for review but I cant add "publish_actions" as a permission for Facebook to review because on this permission there is a message which says: "It looks like you haven't made any API requests to access content with the publish_actions permission in the last 30 days"
But how can I use this permission without having the permission??
I would be very greatful for help if I am on the right track and what I am missing out?
Thank you!
<code>    try
    {
        String appID = "12345";
        String appSecret = "123456";
        String accessToken = "123|1234_a-b";
        String clientToken = "1234567";
        String pageID = "123456789";
        Facebook.FacebookClient client = new Facebook.FacebookClient(accessToken);

        var dicParams = new Dictionary<string, object>();
        dicParams["message"] = "Hello on the time line message!";
        dicParams["caption"] = string.Empty;
        dicParams["description"] = string.Empty;
        dicParams["name"] = "Some Name";
        dicParams["req_perms"] = "publish_stream,manage_pages,status_update,publish_actions";
        dicParams["scope"] = "publish_stream,manage_pages,status_update,publish_actions";
        dicParams["access_token"] = accessToken;
        var publishResponse = client.Post("/" + pageID + "/feed", dicParams);

        MessageBox.Show("You posted on the timeline successfully!");
    }
    catch (Exception ex)
    { MessageBox.Show(ex.ToString()); }
</code>

Attempt 2:
I was looking at the facebook documentation and found an URL which seems relevant to post a message on the business page timeline:
POST graph.facebook.com/{user-id}/feed?message={message}&access_token={access-token}
I have tried to put it down in code like below but again, I receive the same error message:
(OAuthException)(#200) The user hasn't authorized the application to perform this action
Question is what I do wrong. Do I need to get any other access token with "publish_action" permission?. If that is the case I can't figure out how to get such token?
<code>            String appID = "12345";
            String appSecret = "123456";
            String accessToken = "123|1234_a-b";
            String clientToken = "1234567";
            String pageID = "123456789";
            String message = "Hello World";

            String requestUrl = "https://graph.facebook.com/" + pageID + "/feed?message=" + message + "&access_token=" + accessToken;

            RestSharp.RestClient rc = new RestSharp.RestClient();
            RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("x-li-format", "json");

            request.RequestFormat = RestSharp.DataFormat.Json;

            RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
            RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;

            //"(OAuthException)(#200) The user hasn't authorized the application to perform this action"
            MessageBox.Show(restResponse.Content.ToString());
</code>
Comment: Why are you asking for publish_stream when there is no permission named that? And you are using an app access token and not a user or page access token
Comment: you need to stop using old code from some old blogpost (i assume) and start reading the official docs: https://developers.facebook.com/docs - and don´t just use random (and deprecated) permissions without knowing why.
Comment: Thanks for answers. Yes the code is from some post. I have red the developers.facebook.com/docs documentation for several days but I can't find a complete example of how to do it, so I ended up here in order to understand how to be able to post on the timeline.
Comment: I have tried to come up with an attempt 2 above using an URL from the facebook documentation but with the same error message? All info is avaliable in Attempt 2.
Answer: I have found a solution which works. This code do post a "Message" to the timeline.
Question This code works for my business page. I also like to post on my personal page for friends. So tried to change the pageID to the the ID which is my personal page: (pageID = "987654321") but still it posts on my business page.
I wonder if I need to get a page token specifically for the personal page as well?
If that is the case, I wonder how this token can be achieved?
<code>            /*********************************************************************************************************************************************************************/
            //STEPS!!! to get a non-expiring page access token:

            //1. access the following URL and note the returned access token within the browser's address bar:
            //https://www.facebook.com/dialog/oauth?client_id=APP_ID&redirect_uri=REDIRECT_URI&scope=manage_pages,publish_actions&response_type=token

            //2. access the following URL and within the returned data find the desired page's name and note the access token:
            //https://graph.facebook.com/me/accounts?access_token=ACCESS_TOKEN_RETURNED_FROM_STEP_1

            //3. access the following URL and note the returned access token:
            //https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=fb_exchange_token&fb_exchange_token=PAGES_ACCESS_TOKEN_FROM_STEP_2
            //use the Access Token Debugger to ensure your access token's profile ID matches the desired page's ID and it never expires

            String newaccesstoken = "aaaaaaaaaaaabbbbbbbbbbbbbbccccccccccccccddddddddddddddddddd";
            /*********************************************************************************************************************************************************************/

            String appID = "12345";
            String appSecret = "123456";
            String accessToken = "123|1234_a-b";
            String clientToken = "1234567";
            String pageID = "123456789"; //Business page
            //String pageID = "987654321"; //Personal page
            String redirectURI = "http://example.com";
            String message = "Hello Facebook";
            String imageURL = "http://example.com/images/example-image.png";
            String link = "http://example.co";
            String caption = "example";

            //Post a message to the time line
            String requestUrl = "https://graph.facebook.com/" + pageID + "/feed?message=" + message + "&url=" + imageURL +
                                                                                "&access_token=" + newaccesstoken;

            RestSharp.RestClient rc = new RestSharp.RestClient();
            RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("x-li-format", "json");

            request.RequestFormat = RestSharp.DataFormat.Json;

            RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
            RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;

            MessageBox.Show(restResponse.Content.ToString() + "," + responseStatus.ToString());
</code>


Parse with beautiful soup, get nodes at different levels

Question: I am trying to get the deli title, and then under the deli title get the two menu items Made to Order Deli Core and Turkey Chipotle Petite Wrap? I'm using beautiful soup 4 to do this and its not working. And the same is true for the entree times?

    <title></title>

            LUNCH

             Deli

                    <input class="chk" id="S1L0000010000047598_35356" onclick=
                    "rptlist(this);" onmouseout="wschk(0);" onmouseover=
                    "wschk(1);" type="checkbox"> Made to Order Deli Core

                    <input class="chk" id="S1L0000020000047933_06835" onclick=
                    "rptlist(this);" onmouseout="wschk(0);" onmouseover=
                    "wschk(1);" type="checkbox"> Turkey Chipotle Petite Wrap

             Entrée

<input class="chk" id=
                "S1L0000030000044794_08943" onclick="rptlist(this);"
                onmouseout="wschk(0);" onmouseover="wschk(1);" type="checkbox">
                Steamed
                Corn

                    <input class="chk" id="S1L0000040000033087_22244" onclick=
                    "rptlist(this);" onmouseout="wschk(0);" onmouseover=
                    "wschk(1);" type="checkbox"> Cuban Mojo Roasted Pork Loin

or if I could get it into a XML format like this:
<counter name="Deli">
    <dish>
        <name>Made to Order Deli Core</name>
    </dish>
    <dish>
        <name>Turkey Chipotle Petite Wrap</name>
    </dish>
</counter>

Thank you very much in advance, I really appreciate you taking the time to help me.
Answer: Actually i used both beautiful soup and element tree(for xml parsing)
fetch all elements in
# -*- coding: UTF-8 -*-

from bs4 import *
import xml.etree.ElementTree as ET

html='''

    <title></title>

            LUNCH

             Deli

                    <input class="chk" id="S1L0000010000047598_35356" onclick=
                    "rptlist(this);" onmouseout="wschk(0);" onmouseover=
                    "wschk(1);" type="checkbox"> Made to Order Deli Core

                    <input class="chk" id="S1L0000020000047933_06835" onclick=
                    "rptlist(this);" onmouseout="wschk(0);" onmouseover=
                    "wschk(1);" type="checkbox"> Turkey Chipotle Petite Wrap

             Entrée

<input class="chk" id=
                "S1L0000030000044794_08943" onclick="rptlist(this);"
                onmouseout="wschk(0);" onmouseover="wschk(1);" type="checkbox">
                Steamed
                Corn

                    <input class="chk" id="S1L0000040000033087_22244" onclick=
                    "rptlist(this);" onmouseout="wschk(0);" onmouseover=
                    "wschk(1);" type="checkbox"> Cuban Mojo Roasted Pork Loin

 '''

soup = BeautifulSoup(html)

counter = ET.Element('counter')
counter.set("name", "#Deli")

for i in soup.findAll('span'):
    dish = ET.SubElement(counter, 'dish')
    name = ET.SubElement(dish, 'name')
    name.text= i.text.replace('\n',' ')

print ET.dump(counter)

Answer: You could this something like this :
# -*- coding: utf-8 -*-

soup = BeautifulSoup(html)
title = soup.find('td', class_='station').text.strip()

spans = soup.find_all('span', class_='ul')

# create the root of the XML file
root = ET.Element("counter")
root.set("name", title)

for item in spans:
    # retrieve the text inside the
    text = list(list(item.parents)[2].previous_siblings)[1].text.strip()
    if text == u'Entrée':
        break

    dish = ET.SubElement(root, 'dish')
    name = ET.SubElement(dish, 'name')
    name.text = item.text.rstrip()

tree = ET.ElementTree(root)
tree.write("filename.xml")

And this is the content of desired xml file :
<counter name="Deli">
    <dish>
        <name>Made to Order Deli Core</name>
    </dish>
    <dish>
        <name>Turkey Chipotle Petite Wrap</name>
    </dish>
</counter>

Is very important include the following line # -*- coding: utf-8 -*- line above in the beginning of your file to avoid problems  with the accent , see SyntaxError: Non-ASCII character '\xa3' in file when function returns '£' for more details.
Comment: Thats awesome, but what if i didn't know there was only 2 items. Is there a way to get all the items listed before the Entrèe section? Thanks
Comment: @user3349689 this line limit to only two `spans = soup.find_all('span', class_='ul')[:2]`, if you want all try this `spans = soup.find_all('span', class_='ul')`
Comment: right but see my problem is that I want it to only get the items under the Deli section and stop getting them before this line ' Entrée', if I leave it as find all it also get the Steamed Corn item which isn't under the deli section, and there can be different number of items under the deli section. Thanks for the help
Comment: @user3349689 See updated answer, with the above code if encounter the text Entrée stops the creation of the xml and get all between Deli and Entrée
Comment: Ya thats great, but what if I didn't know the number of deli items is there a way to do that, because this only works if I know the number of items?
Comment: @user3349689 The stop condition it's when encounter the `Entrée` word the deli items no influence over the loop.
Comment: that doesn't seem to be working because if I remove the [:2] on line 6, it gets every span (item) and doesn't stop at the word entree.
Comment: @user3349689 , please see the updated answer and sorry the [:2] it's a mistake from the last code


Is there a macro I can put on a command button, to move the current sheet to a different closed workbook?

Question: I have 2 workbooks for the department. "Workorders" & "Completed Workorders"
"Workorders" is a shared book that other departments put in Task request. The guys in the department, fill them out when they have completed the task. Each Sheet is renamed with the task number ID, so the sheet is never the same name.
The "Workorders" book needs to be the main book. So is there a way for them to have a command button "Complete", that would move the active sheet they have filled out in "Workorders" into the "Completed Workorders" book. Either keep it open in the background, so they never see it, or if it can open, move the sheet, and close back.
thank you for your help, and i do hope it is possible.
Comment: I think this post may help you. [See this link](http://stackoverflow.com/questions/6863940/how-to-copy-sheets-to-another-workbook-using-vba)
Answer: Insert a button on the workbook and assign this code to the button, make sure to change the filename path to yours:
<code>Private Sub CommandButton1_Click()
    On Error Resume Next
    Dim sheetIndex As Integer
    sheetIndex = 1
    Application.ScreenUpdating = False
    Workbooks.Open Filename:="C:\YourPath\Completed Workorders.xlsm"
    Windows("Workorders.xlsm").Activate
    ActiveSheet.Select
    ActiveSheet.Copy Before:=Workbooks("Completed Workorders.xlsm").Sheets(sheetIndex)
    sheetIndex = sheetIndex + 1

    ActiveWorkbook.Save
    Windows("Completed Workorders.xlsm").Close
    Application.DisplayAlerts = False
    ActiveSheet.Delete
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub
</code>
Comment: Thank you, so much for helping me with this. I did not explain very well that each sheet that has to moved is a different number (example - Pr1807 or MA17005). Can you use this with out having to put the exact name of the sheet? thank you again
Comment: check my edited post.
Comment: It works, so I am not sure what i have done. After it ask to save "Completed Workorders" which I say yes too. I get an error.    Run-Time Error '9':  Subscript out of range. when i hit debug the following line is highlighted -currentSheet.Copy Before:=Workbooks("Completed Workorders.xlsx").Sheets(sheetIndex)
Comment: umm, it shouldn't ask to save completed workorders because it already saves it before closing it. try putting this at the begining of the code Application.DisplayAlerts = False
Comment: check if your workbook is named "Completed Workorders.xlsx"
Comment: It is named "Completed Workorders.xlsm". I changed the .xlsx to the .xlsm. Is this what i did wrong?
Comment: yes, if you change the extension, you must change it in the code as well - I've modified my answer to match your file extension.
Comment: It is working except it is moving all the sheets in "Workorders" to "Completed workorders" not just the one sheet that i am working on.
Comment: ok, take a look at edited post answer, it will only take the current sheet that has the button on and copy over.
Comment: It works, perfect!!! thank you so much for being so patient with me and helping, it is truly appreciated. your my knight in shining amour!!
Comment: Please mark this post as the answer if it help you. thanks.
Comment: Hello, I hate to ask you another question, but is there any way we can move the page completely, with out coping it?
Comment: you mean, after copy, delete the worksheet that you are working on in "Workorders.xlsm" ?
Comment: Yes, after it is moved to "Completed Workorders.xlsm" it has to be removed from "Workorders.xlsm". I was going to see if it could be added to this code. - thank you
Comment: Try updated answer.
Comment: Works like a dream, thank you for the addition. It is greatly appreciated.


How to loop through groups with now.js

Question: is there a way to loop through a user's groups with now.js?
When a user disconnects, I want to run some functions on the groups that they were a part of.
something like answer 1 here (1), but for some reason, that code doesn't work.
Code:
<code>nowjs.on('disconnect', function() {
    var that = this;
    this.getGroups(function(groups){
         for (i=0;i<groups.length;i++){
             nowjs.getGroup(groups[i]).removeUser(that.user.clientId);
             console.log('user removed');
         }
    })
})
</code>
Comment: Can you add your code and specifics on "doesn't work"?
Comment: It appears that support for the now.js module has ended, despite how useful it is: https://groups.google.com/forum/?fromgroups#!topic/nowjs/FZXWZr22vn8
Comment: ya...I figured that out :( That stinks! Thanks for the heads up
Answer: I forgot that I had already created an array called serverRoomsList. That held, oddly enough, a list of all the chat rooms I had already created. I just looped through that to get all of the group names.
However, I would still like to know if Now itself keeps track of groups in an array, or if I have to do it.

How to loop through groups with now.js


Is it possible to post a note to Facebook with images

Question: Is it possible to post a note to Facebook with images?
Comment: Why the unaccept of my answer?
Comment: Hi, DMCS, actually, it is possible to include a photo link in the "message" param when post note to facebook. It is html format string. Though "message" only can cantain certain tag like li,br ... , it can contain img tag also. I have done the task by post a html message, which contains external url link to photos. However thank you all the same.
Comment: Facebook is always changing their API.  So maybe now they've overcome the deficiency that I wrote about on March 1st, 2012.  It's been many months.  Please add your own answer to the correct response and mark your answer as accepted.
Answer: No you cannot post a note with images.  There is no image connection on the note graph object. http://developers.facebook.com/docs/reference/api/note/
As you can see here: http://developers.facebook.com/docs/reference/api/user/ in the notes section.

Create
You can create a note on behalf of the user by issuing an HTTP POST
request to PROFILE_ID/notes with the publish_stream permissions and
the following parameters.
Parameter     Description     Type    Required
subject The subject of the Note string yes
message Note content string yes
If the create is successful, you get the following return.
Name  Description     Type
id The new note ID string
Answer: You can put the image tag in your description HTML. You can add as many images as you want and position them how you want. You need to do it with HTML. CSS will not work in description.


(Spoiler) Can the "The Crane Returns on the Wind" interlude quest be played "out-of-order"?

Question: Base on Mihoyo official post, the new interlude quest "The Crane Returns on the Wind" unlock criteria is

Complete the Archon Quest "Chapter I: Act III - A New Star Approaches"

This means that the quest can be played before visiting Inazuma and playing thru the Archeon quest there.
The new quest involves

 the rebuild of the Jade Camber that has previously been sacrificed to defeat the Lord of the Vortrex during the Liyue Archeon quest arc.

For this reason, it would logically seem that the quest is incompatible with

 The world quests "Fishing for Jade" and "Return of the Jade Chamber" which have the npc Baiwen talk about the future plans to rebuild the Jade Chamber

Given the above, can this end up causing a sequence break in the story? More specifically, what would happen if

 a player does not complete Return of the Jade Chamber before playing "The Crane Returns on the Wind"  and thus getting the Jade Chamber back? Is "Return of the Jade Chamber" still available, resulting in the NPC talking about rebuilding the Chamber in  while it is already there or does it get removed and thus is forever-missable if not played in-time?
Answer: The possible inconsistencies introduced by "The Crane Returns on the Wind" were indeed noticed by the developers and so completing the quest earlier produces some changes in the game.
Specifically,

 the quest "Fishing for Jade" gets altered to mention that "while the Jade Chamber has been rebuilt, pieces of the old one are still floating in the water. "Return of the Jade Chamber?" has the dialogue changed so that the items you are sent to retrieve will be used for internal decoration instead that for the reconstruction.
 The altered versions of the two quests can be seen on Youtube here:
Genshin Impact - Fishing For Jade, But After Rebuilding the Jade Chamber
Genshin Impact - Return of the Jade Chamber?, But After Rebuilding the Jade Chamber


Fading an object in add mode with correct color math

Question: I have a scene rendered entirely with objects with additive blend mode.  I have a value that is oscillating from 0, to 1.  When it is 1 the object is supposed to be invisible, 0 should be entirely visible.
However I have noticed that something seems off about it, specifically it stays dark for too long.  It is not my oscillating function, I suspect it having something to do with light using a logarithmic scale.
How would I convert my linear 0->1 value into a properly scaled value between 0->1
Fragment:
precision highp float;

uniform sampler2D s_texture;

varying vec2 v_texcoord;
varying float alpha;

void main()
{
    vec4 col = texture2D(s_texture, v_texcoord);
    gl_FragColor = vec4( col.rgba  - alpha);

    if (col.a < 0.001)
    {
        discard; //11.7->12.2
    }
    //gl_FragColor = vec4(0.4);

}

Vertex:
precision highp float;

attribute vec2 pos;
attribute vec2 tc;

uniform mat4 matrix;
uniform float time;
uniform float maxLeafs;
uniform vec2 position;
uniform float instance;
uniform vec2 anchorPoint;

varying vec2 v_texcoord;
varying float alpha;

vec4 finalTranslate(vec3 pos)
{
    return vec4(pos + vec3(position, 0.0), 1.0);
}
vec3 rotate(vec3 pos, float angle)
{
    float s = sin(-angle);
    float c = cos(-angle);
    return vec3(c * pos.x - s * pos.y, s * pos.x + c * pos.y, 0.0);
}
vec3 translate(vec2 pos)
{
    return vec3(pos - anchorPoint, 0.0);
}
vec3 scale(vec3 pos, float amm)
{
    return pos * amm;
}
void main()
{

    float v = log((time * 0.9) + 0.1);
    alpha = 0.0;

    float leafCoverage = (3.14149 * 2.0);
    float goal = ((instance) / (maxLeafs + 1.0)) * leafCoverage;
    float timeFactor = smoothstep(0.0, 1.0, time);
    float calculation1 = goal * timeFactor;
    float calculation2 = clamp(timeFactor * leafCoverage, 0.0, goal);

    float scaleFactor = clamp(smoothstep(0.0, 1.0, time * 1.2), 0.0, 1.0);

    gl_Position = matrix * finalTranslate(rotate( scale(translate(pos) ,scaleFactor) ,  calculation1));
    v_texcoord = tc;
}

Right now I am just taking the oscillating float time and passing it in directly, but eventually I will put it on a function so it fades in, temporarily is extra bright, then goes to the source texture.
Edit: I solved my problem, to my surprise the GLSL log function is in base e rather then 10.
Comment: If you solved your own problem, you can also post an answer for anyone who sees the same problem in future. This is [actively encouraged](http://computergraphics.stackexchange.com/help/self-answer).
Comment: Are you using $sine/cosine$ as the oscillating function ?
Comment: Yes technically. However as you can see by the value v I am going to map it differently.
Answer: Turns this was not an issue with the scale of the values passed in, just that the log function in glsl is base e.  The solution was merely to do log(stuff)/log(10) and that got the result of a base 10 log.


Paypal integration into existing shopping cart

Question: I have developed my own shopping cart and now I want to integrate Paypal to allow the payment process to happen once the customer has clicked on the 'buy now' button.
How is it possible so that the item details are reciprocated in Paypal on the left hand side? I need to pass the item details over to Paypal based on what the customer has added to their cart.
After researching, I noticed that you can have buy now buttons on individual items and do it that way - but I have my own cart which allows for multiple items. So how can I pass these over to Paypal dynamically?
My attempt is below but when testing - the 'buy now' button does nothing when clicked on.
<?php
$checkout = "<form action='https://www.paypal.com/cgi-bin/webscr' method='post'>";
$checkout .= "<input type='hidden' name='cmd' value='_cart'><input type='hidden' name='upload' value='1'>";
$checkout .= "<input type='hidden' name='business' firstname.lastname@example.com'>";

$count = 1;
$checkout .= "<input type='hidden' name='item_name_" + $count + "' value='" + $product['common_name']+ "'>";
$checkout .= "<input type='hidden' name='item_number_" + $count + "' value='" + $count + "'>";
$checkout .= "<input type='hidden' name='quantity_" + $count + "' value='" + $item['quantity'] + "'>";
$checkout .= "<input type='hidden' name='amount_" + $count + "' value='" + $product['price'] + "'>";
$count = $count + 1;
?>

<input type='hidden' name='currency_code' value='GBP'>
<input type='hidden' name='lc' value='GB'>
<input type='hidden' name='return' value='http://www.derrysnurseries.co.uk/checkout?confirm=Confirm&confirmTerms=on'>
<input type='hidden' name='cancel_return' value='http://www.derrysnurseries.co.uk/checkout'>
<input type='hidden' name='notify_url' value='http://www.derrysnurseries.co.uk/checkout?confirm=Confirm&confirmTerms=on'>

Click <input class='securePaymentButton' type='submit' value='here'> to continue to secure payment site

<?php $checkout .= "</form>"; ?>

Answer: You're not echoing the string that has the open form tag, or you're outputting it ($checkout) AFTER this code sample,  so after the submit tag stuff. (the non php section is output right away; you can view source on your output to see what i mean).
As a result, your submit button is not part of the form and won't perform the action you specified.


What is a good approach to building and distributing a React Native iOS component that extends iOS functionality?

Question: The process I've taken thus far (for a UIView-based component) is:

react-native init project_name
Write my custom component as part of the project_name xcodeproj
Implement RCTViewManager.h
Implement the corresponding Component_Name.js file

I can follow the steps to get this working locally, however, the React Native docs for components and modules makes no mention of how the npm package should be setup -- or if npm is the tool for the job instead of cocoapods. Furthermore, how much of the generated project from react-native init project_name is to be distributed with the component is not mentioned.
Does anyone know of any guiding principles or best practices (ha!) for this process?
Answer: You'll probably want to follow this discussion on github, in which contributors are talking about a packaging solution for React Native.
https://github.com/facebook/react-native/issues/235
They mention a combination of CocoaPods and npm, but nothing's really been decided yet. Now would be the time to speak up!
Brett Vatne also has a blog article on how to do this at the moment:
http://brentvatne.ca/packaging-react-native-component/


assert each item in list contains XYZ

Question: I am trying to assert that every item in a list contains the word 'hospital'
the following code gives me a list of every hospital as a string:
List <WebElement> Hospital = driver.findElements(By.xpath("//tbody/tr/td/label"));
        for (WebElement webElement : Hospital){
        String servicenames = webElement.getText();

        System.out.println(servicenames);

What do I now need to do to assert that each item in the list contains my string?
Comment: Use lowercase / camelCase names for local variables. Besides, it's not a list of `String`s, so how can you tell if it contains the word "hospital"?
Answer: List <WebElement> Hospital = driver.findElements(By.xpath("//tbody/tr/td/label"));
        for (WebElement webElement : Hospital){
        String servicenames = webElement.getText().toLowerCase();

        System.out.println(servicenames);

        try{
        assertTrue(servicenames.contains("hospital"));

        }catch(Error e){
        verificationErrors.append(e.toString());
        }

For reference, this is what I've ended out using, sorry, didn't get the enabling assert thing - I've read somewhere that assert should be enabled as part of JUnit automatically anyway, (because it's used so regularly in testing I guess)
Anyway, this seems to be working for now...

assert each item in list contains XYZ


Prove or disprove that $f(x) = \sin x/x$ is uniformly continuous over the interval $(0,1)$?

Question: I am thinking of $\lim_{x \to 0} \ {f(x)} = 1$ but I am confused as $x=0$ is not in the domain and also I want to write an $\epsilon$-$\delta$ proof. So any help is much appreciated!
Thanks!
Answer: Ittay Weiss described the right way to solve this problem. If you really want an $\varepsilon$-$\delta$ solution, you can do the following.
Given $\varepsilon > 0$, let $\delta = \varepsilon$. Now for $x,y\in (0,1)$ with $|x-y| \leq \delta$, we have
$$|f(x) - f(y)| = |(x-y) f'(\xi)| = |x-y| \cdot |f'(\xi)| \leq \delta |f'(\xi)|,$$
where $\xi \in (0,1)$. Note that
$$f'(x) = \frac{x\cos x - \sin x}{x^2}.$$
 This function takes negative values on $(0,1)$ since $\tan x > x$ (for $x\in (0,1)$). Also
$$\frac{x\cos x - \sin x}{x^2} \geq \frac{x\cos x - x}{x^2} = \frac{\cos x - 1}{x} \geq -1.$$
That is, $f'(\xi) \in [-1,0)$.
Therefore, $|f(x) - f(y)| \leq \delta = \varepsilon$.
Comment: @AmanMittal: Yes,it does. The proof goes through with small modifications. It's no longer true that $f'(\xi) \in (-1,0)$; but it is true that $f'(\xi) \in (-1,1)$.
Comment: this is nice! appreciate it!
Comment: Nice solution! Far less messy than I had anticipated.
Comment: Does this proof hold good if the interval is entire $R$
Answer: Here is a non $\epsilon-\delta $ proof: Extend $f$ to a function $g:[0,1]\to \mathbb R$ by setting $g(x)=f(x)$ for all $x\in (0,1)$ and $g(0)=1$, $g(1)=\sin (1)$. Now, $g$ is continuous on its domain which is a closed interval and thus is uniformly continuous. It is very easy to show that the restriction of a uniformly continuous function is itself uniformly continuous and thus $f$ is uniformly continuous.
Giving a direct $\epsilon -\delta $ proof will be quite technically messy. Is there any particular reason you wish to obtain such a proof.
Comment: Because that is how I usually do these proofs and for instance, I don't understand your proof completely because I don't know why the restriction of a uniformly continuous function is uniformly continuous. Also can you explain why g is continuous on the domain?
Comment: g is continuous at every 00 for all 0<x<=1
Comment: oh of course and thank you so much!
Comment: @UH1 how can this proof be extended over the entire $R$  ?


Disk unknown usage

Question: I use df -h find 17G used. However I use ncdu / to find which directory holding disk usage, show me only 5.5G used. What's wrong with this?
df -h screenshot:

ncdu / screenshot:

[Edit 2016.09.05]
It is resolved. I should use 'sudo ncdu /', then I found the usage is match for df -h usage.
Answer: This should work
In a terminal type:
 sudo du -BM -s /*

This will give a summary of disk usage in each directory and file in the root directory, in megabytes.
You need sudo because you want to read all the files.
There is also a man page for du.
Comment: It is resolved. Inspired by your command . I should use 'sudo ncdu /', then i found the usage is match to `df -h` usage. Thank you.

Disk unknown usage


Regular Expression to match dot separated list allowing one or more word

Question: I need an regex that allows an input string with one or more words, but the list must be separated with only a dot. For example:
test = OK
test.test = OK
test.test.1 = OK

test@test = NO
test_test = NO
test-test1 = NO
test. = NO

My regex works, but accepts also other symbols, such as -
^[a-z0-9*.\-_\.:]+$

Comment: Why not just remove the other symbols from your regex? i.e. `^[a-z0-9.]+$`. If you want to ensure that it doesn't begin or end with a dot, use `^[a-z0-9]+(?:\.[a-z0-9]+)*$`
Comment: Why `test` is ok and `testtest1` is not?
Comment: @John please post your answer and I will accept it
Answer: If you want to ensure that it doesn't begin or end with a dot, use ^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$
Explanation:

^ - Match beginning of input
[a-zA-Z0-9]+ - Match alphanumeric sequence
(?: - Beginning of a non-capturing group

\. - Match a single .
[a-zA-Z0-9]+ - Match a alphanumeric sequence

) - Close the group
* - Repeat previous group any number of times
$ - Match end of input

You can also replace [a-zA-Z0-9] with [^\W_], as this will match any character that's not non-word and also not underscore. Basically \w minus the _ character.
Answer: Try ^[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$

[A-Za-z0-9]+ match a word (letters or numbers)
(\.[A-Za-z0-9]+)* - match any following words separated by a dot

Demo


How to send a json file with HttpClient in C#?

Question: I'm trying send a JSON file with postman and it's working. But when I'm trying to send the same contents via HttpClient it's not working.
System.IO.File.WriteAllText(dirName + "\\importproduct.json", jsonitems);
var fileByteArray = File.ReadAllBytes(dirName + "\\importproduct.json");

using (var _client = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        content.Add(new StreamContent(new MemoryStream(fileByteArray)), "file");
        var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
        _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);

        var response = _client.PostAsJsonAsync(url, content).Result;
        var result = response.Content.ReadAsStringAsync().Result;
    }
}

PostMan:

Answer: Instead of using PostAsJsonAsync(); method you should use PostAsync(); So your code should be looking something like that
using (var _client = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        content.Add(new StreamContent(new MemoryStream(fileByteArray)), "file");
        var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
        _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);

        var response = _client.PostAsync(url, content).Result;
        var result = response.Content.ReadAsStringAsync().Result;
    }
}

Comment: @efecetir I'd recommend comparing the two requests using something like Telerik's Fiddler to see what the differences are.
Comment: Welcome to SO, maina :)
Comment: That is working but the main issue is application on server response me "File not found" they can't see the file but i can send it from postman by "file" key.
Comment: I am not sure 100% but I am expecting HttpClient.SendJsonAsync() to set http content type to "application/json"  while Postman content type will be "multipart/form-data".
Answer: PostAsJsonAsync method is a generic method, it expects as the second parameter the object that will be serialized and sent in the POST body.
var obj = JsonConvert.DeserializeObject<SomeModelClass>(jsonString);
var response = await _client.PostAsJsonAsync(url, obj).Result;

Answer: This is based on efecetir's post above. It works for me. BTW, I also upvoted his post.
My issue was I needed to set the content type at the content-based level.
var fileByteArray = File.ReadAllBytes(filePath);

HttpContent bytesContent = new ByteArrayContent(fileByteArray);
using (var httpClient = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
    var RequestUri = new Uri($"http://whatever.com/");
    //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);

    formData.Headers.Add("super-secret-key", "blah");
    bytesContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");

    //httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //("multipart/form-data")); // Not needed
    formData.Add(bytesContent, "file", "blah.json");
    var response = httpClient.PostAsync(RequestUri, formData).Result;
    return await HandleResponse(response);
}

Answer: Thanks for your comments.
I fixed it and convert my codes as below. Now it's working and much more clean.
HttpContent bytesContent = new ByteArrayContent(fileByteArray);
        using (var client = new HttpClient())
        using (var formData = new MultipartFormDataContent())
        {
            var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);

            formData.Add(bytesContent, "file", "importproduct.json");
            var response = client.PostAsync(url, formData).Result;
            var result = response.Content.ReadAsStringAsync().Result;

        }

Comment: You can express your gratitude by upvoting and accepting the best answer and not by copy-pasting the work of others! -1 from me.
Comment: i tried the link that i shared https://stackoverflow.com/a/19664927/3363877 and it worked for my case.
Answer: Here's code I'm using to post form information and a file
using (var httpClient = new HttpClient())
{

    var surveyBytes = ConvertToByteArray(surveyResponse);

    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var byteArrayContent =   new ByteArrayContent(surveyBytes);

    byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/csv");
       var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
    var response = await httpClient.PostAsync(url , new MultipartFormDataContent
    {
        {byteArrayContent, "\"file\"", dirName + "\\importproduct.json"}
    });

    return response;
}

This is for .net 4.5.


How to be notified when Notification starts the current Activity in Android

Question: If I setup a notification to start an activity, then if the user is using this exact activity when taping the notification nothing happens, is there anyway the code can be notified when this happen?
My activity launch mode is normal and no flags nor any special configuration exists.
Edit:
The notification does work and when the user is viewing activity other than the one associated with the notification, the activity is opened as expected, my question is that when the user is viewing the same activity that should open on notification tap, then when he pulls down the notification drawer and tap the notification nothing happens.
Comment: Maybe this will help: http://stackoverflow.com/q/12043671/6272369
Comment: No this talks about a different issue
Comment: `when taping the notification nothing happens, is there anyway the code can be notified when this happen? `. Very strange question. So your code does not work.  And now you want to be notificated that it does not work? Notifying the code or the user?
Answer: I have come to a solution to this:
I set the launchMode of my activity to singleTop this way when the notification is clicked onNewIntent is called, my activity is guaranteed not to stay in stack so singleTop has no side effect


PHP MySQL PDO: get last inserted ROW not ID

Question: I have currently a script to insert new data automatically when using the form to add a new element.
I use
 public string PDO::lastInsertId ([ string $name = NULL ] )

Logic of course. Now I am only wondering if this might cause any problems in case a table has no ID field and no auto increment field.
Aside the fact if this means there is a bad database structure used.
I want to make sure that this routine works in any situation. Good database or a bad database structure. It should not matter.
What I mean is that I would like to get back the row with data so I can search for it.
E.G.
1
Insert new data into the database
$query = $pdo->prepare("INSERT INTO `tablename` SET `data_name`='John', `data_familyname`='Doe', 'data_age`=45, `data_wife`='Sarah Doe'");
$query->execute();

2
Fetch the last inserted row entirely
///$LastID = $pdo->lastInsertId();
$query = $pdo->prepare("SELECT `data_name`,`data_familyname`,`data_age`,`data_wife` FROM `tablename` WHERE LAST IDFIELD = ".$pdo->lastInsertId());
$query->execute();
$row = $query->fetch();

Row contains
array(
        'data_name'         =>      'John',
        'data_familyname'   =>      'Doe',
        'data_age'          =>      '45',
        'data_wife'         =>      'Sarah Doe'
    );

3
Then update the last inserted row with exactly the same data as just inserted
$query = $pdo->prepare("UPDATE `tablename` SET `data_name`='Chris' WHERE `data_name`=? AND `data_familyname`=? AND 'data_age`=? AND `data_wife`=?");
$query->execute(array_values($row));

The last query is basically:
UPDATE `tablename` SET `data_name`='Chris'
WHERE `data_name`='John' AND `data_familyname`='Doe' AND 'data_age`='45' AND `data_wife`='Sarah Doe'

Of course there is the possibility that duplicate data exists. And you want to modify only the last row. That is where I meant aside from the fact if the database has any good structure.
But to prevent duplicate data one could add:
Row contains
array(
        'data_id'           =>      20,
        'data_name'         =>      'John',
        'data_familyname'   =>      'Doe',
        'data_age'          =>      '45',
        'data_wife'         =>      'Sarah Doe'
    );

The point is
Step 2
Does not work since I just made it up a couple of minutes a go. However I would like to know if there are any similar functions or routines that do the same as I just mentioned.
Hope that it is clear what I want.
My solution eventually is:
$sth = $pdo_connection->prepare("INSERT INTO `pdo_test` SET
                            `pdo_name`              =       'John Doe',
                            `pdo_description`       =       'John Doe who served in Vietnam and every other war game as a default name',
                            `pdo_text`              =       'Some text BLABLA'
                        ");
$sth ->execute();

$stmt               = $pdo_connection->query("SELECT LAST_INSERT_ID()");
$result             = $stmt->fetch(PDO::FETCH_ASSOC);
$lastID             = $result['LAST_INSERT_ID()'];

$stmt               = $pdo_connection->prepare("SHOW COLUMNS FROM `pdo_test` WHERE EXTRA LIKE '%AUTO_INCREMENT%'");
$stmt->execute();
$row                = $stmt->fetch(PDO::FETCH_ASSOC);
$AutoIncrementField = $row['Field'];

$stmt               = $pdo_connection->prepare('SELECT * FROM `pdo_test` WHERE `'.$AutoIncrementField.'` = ?');
$stmt->execute(array($lastID));
$result             = $stmt->fetch(PDO::FETCH_ASSOC);

echo print_r($result);

Result:
Array
(
    [pdo_id]            =>      64
    [pdo_name]          =>      John Doe
    [pdo_counter]       =>      0
    [pdo_description]   =>      John Doe who served in Vietnam and every other war game as a default name
    [pdo_text]          =>      Some text BLABLA
)

But an AutoIncrement field seems to be essential.
Second solution but still with an AutoIncrement field.
(as proposed by: Edwin Lambregts)
Note that this solution is not failsafe!!! Because the query selects the last inserted row... But by ALL instances! Hence if another user just inserted a new row... You will get to see his input and not yours. This can occur if the update happens in between.
$sth = $pdo_connection->prepare("INSERT INTO `pdo_test` SET
                            `pdo_name`              =       'John Doe',
                            `pdo_description`       =       'John Doe who served in Vietnam and every other war game as a default name',
                            `pdo_text`              =       'Some text BLABLA'
                        ");
$sth ->execute();

$stmt               = $pdo_connection->prepare("SHOW COLUMNS FROM `pdo_test` WHERE EXTRA LIKE '%AUTO_INCREMENT%'");
$stmt->execute();
$row                = $stmt->fetch(PDO::FETCH_ASSOC);
$AutoIncrementField = $row['Field'];

$stmt               = $pdo_connection->prepare('SELECT * FROM `pdo_test` ORDER BY `'.$AutoIncrementField.'` DESC LIMIT 0,1');
$stmt->execute();
$result             = $stmt->fetch(PDO::FETCH_ASSOC);

The outcome is:
Array
(
    [pdo_id]            =>      67
    [pdo_name]          =>      John Doe
    [pdo_counter]       =>      0
    [pdo_description]   =>      John Doe who served in Vietnam and every other war game as a default name
    [pdo_text]          =>      Some text BLABLA
)

Comment: Then you have to ensure that you're inserting a unique key of the table, so you can select that afterward. There's no built-in way to tell rows apart other than their unique keys.
Comment: `lastInsertId` only works when there's an `auto_increment` field.
Comment: Do a `SELECT` for a row whose contents are all the values you just inserted.
Comment: The point is that I want to make sure that this function works at a table that has an auto_increment field and where it has not.

So simply selecting by the last inserted values is not where I am after. Since I want to prevent modifying duplicate data when available.

If for example the field `data_id` would be present I want the query to return an array with this row included.
Answer: I'm not sure what your question is but, in order to not mess the things up in your table you have to implement this things:

Have a PK (primary key) on the table. It provides you a way to uniquely identify each row. It should be either a field or a combination of fields that uniquely identify each row. In theory, he best candidate for a PK is an intrinsic property of the entity stored in the table that identifies the entity. For example, for a Country table a good candidate for the PK is the full country name. In the real world, the AUTO_INCREMENT fields were invented because:

some tables just don't have a column or a set of columns that can be used as PK; for example, a table used to store log entries generated by the program - all the entries must be stored even if some of them are identical; an artificial PK is created for them using an AUTO_INCREMENT field;
when the type of the best candidate column for PK is string (country name in the example above) or when the candidate for PK is a set of two or more columns, using that as PK will have negative performance impact on the table; an artificial PK (created as an AUTO_INCREMENT integer field) produces a smaller index that improves the speed of the queries that use it.

On INSERT you can either generate a value for the PK and put it into the query or rely on the database to generate one for you (if the PK is an AUTO_INCREMENT field).

If you generate a value for the PK you need to be sure it does not already exist in the table. You can either check if it doesn't exist before INSERT or you can try to INSERT and check if it succeeded. Even if you check before, the INSERT can still fail because another instance of the script can run on the same time, generate and INSERT the same value for PK. In this situation you need to generate another value and try to INSERT again and this workflow repeats until it succeeds. It doesn't look like a good strategy for me.
You can let the database generate an unique value for your PK (by providing NULL for the PK in the INSERT query or not providing it at all) then ask it about the value it generated. MySQL provides the LAST_INSERT_ID() function for this purpose. An excerpt from the documentation:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

The database takes care of everything: the value is unique, it doesn't interfere with other instances of the script (or even other code) that tries to insert in the same table on the same time; the INSERT succeeds, the PK is unique, I get back the value that identifies my row and not someone else's row.

Having an additional column that is not an intrinsic property of the entities stored in the table is a small price to pay for the benefits it produces.
This is just a guideline and an artificial AUTO_INCREMENT column should be added only when it helps. In the example above with the countries table, an AUTO_INCREMENTED column for PK is not needed:

the table contains only several hundred rows; there are no insertions or deletions in it (in fact there are, but only once in a while; it's possible that your application is retired before a change in the Country table is needed);
there is a good candidate for the PK: is the ISO-3166 country code; there are even two flavors of it: 2-letter and 3-letter - pick your favorite; it is a CHAR[2] (or CHAR[3]) and because the table is so small having it as PK doesn't affect the performance in any way.
Answer: Getting the last inserted record/row certainly is possible without the usage of id's.
MySQL syntax:
SELECT column_name FROM table_name
ORDER BY column_name DESC
LIMIT 1
It will simply show  the last inserted record.
Source: http://www.w3schools.com/sql/sql_func_last.asp
Comment: **That's not true!** Always remember the code runs concurrently with other instances of itself. Between the `INSERT` and the `SELECT` you suggest, other instances of the same script could run several `INSERT`s and the `SELECT` will return a row created by another instance of the script (maybe even a record that belongs to a different user).
Comment: What in the case when we're using custom `uuid` which is alphanumeric, random value with no auto_increment?


Can someone give an example of an app that is extremely well suited to Flux/Redux?

Question: If the example could help me understand the answers to the following questions I would be very happy:
Should you use a Flux/Redux store for data that is unlikely to change throughout the apps lifecycle? And if most of the data in your app is like this should you even bother to use a flux/redux store?
I ask the question in the title because the vast majority of apps seem to be of a similar kind to mine (be it more complex) as described below. I somehow see Redux as a framework designed for apps with internal data that gets mutated (hence the large abundance of counter examples in Redux tutorials).
In my case, the first screen of my app will prompt the user to select a hotel from a list. Once selected a menu structure specific to the selected hotel will appear (which is amazingly easy with react), created from an api response to the server. Once a hotel is chosen it is unlikely that it will be changed, but possible, in which case a totally new set of menus will be loaded. The rest of the app will simply be pushing data to the server by means of form submission. And receipt confirmation for the user from the server.
Answer: Suppose you have a component tree that looks like this. Component A is the root. There's a button in Component G.
Component A --> Component B --> Component C --> Component D --> Component E --> Component F --> Component G
Now, let's say you have another component, Component K, which is nested as follows:
Component A --> Component H --> Component I --> Component J --> Component K
Component K is a simple view that takes in a prop and renders a span tag with the value of that prop. Component G contains a button that, when clicked, changes the value of the prop that Component K renders.
Now, the React-without-Flux way to do this would be to have Component A own the state and pass it down as a prop to Component K. Component A also would have a method that modifies that state and passes a reference to that function as a prop all the way down to Component G.
That doesn't sound so bad if you do it just once, but what if you have dozens of state variables? What if your components become even more nested? Your controller-views become very difficult to manage, and you will be passing dozens of props to intermediate components that won't even use those props (only pass them down to their children).
Flux allows you to reduce the complexity of your controller-views. Your controller functions can be placed in separate modules, which can be imported into the components that need to use them. Components that need to access state can subscribe to the store that contains that state.
As far as I'm concerned, this is the primary reason to use a Flux pattern.
Comment: Yes, thank you, that does make sense. So as soon as your application is passing functions down component trees that cause state changes on components in totally different branches of the component tree you will start to have a mess on your hands unless you have a central place for state to be handled.


Suggestions on creating Factories for big domain objects

Question: We have a big object graph with lot of properties and behavior in it. We are currently revisiting our domain and we are going to go the DDD approach. But we are in need of a suggestion from you experts on how to go about creating Factories for our big domain model.
Problem
We cater to multiple geographies like US, Canada, Spain, Chile, Brazil, UK etc. As it is evident each one of then have differences in addresses, names ((last name, surname 1, surname 2 etc)), phone numbers, national IDs etc. At a high level the domain model looks like this

a Transaction can have multiple
Subject's
a Subject has Name,
Address, TelephoneNumber, NationalID
a Subject can be a ConsumerSubject
    or a BusinessSubject
a ConsumerSubject has a PersonName
    while a BusinessSubject has a
    BusinessName
a Address can be a
    USAddress, UKAddress,
    CanadianAddress, ChileAddress etc
    and the same way there can be
    geography specific subclasses for
    most of the domain objects (where
    applicable)

For every new request we need to create this entire set of objects properly populated in a valid state. We can use the Abstract Factory pattern to have Geography specific factories like USTransactionFactory, CanadianTransactionFactory etc.
Required Suggestion here
How to pass-in the parameters to create these objects. Taking Address as an example

Should we have a createXXXAddress(...) method for
each geography that takes in city,
state etc as input arguments? This
means that we need to have
createUSAddress(...),
createCanadianAddress(...),
createChileanAddress(...) etc
OR should we just have one createAddress(Address addr) method
that just takes Address object and
let the client create the
appropriate geography specific
Address object? E.g
SpainAddress spain=new SpainAddress();
spain.setMuniciplaityName(...);
OR should we have a separate AbstractFactory for each of the significant domain objects? For e.g USAddressFactory, UKAddressFactory etc

Required Suggestion here
Is there a necessity to create DTO's for this? I am thinking just pass the domain to presentation layer but maintain immutability by enforcing read-only view of the domain. For e.g each domain object will implement two interfaces: ReadOnlyAddress, MutableAddress. This was inspired by how joda-time.
Any other suggestions and criticisms are welcome.
Answer:

Should we have a createXXXAddress(...) method for each geography that takes in city, state etc as input arguments? This means that we need to have createUSAddress(...), createCanadianAddress(...), createChileanAddress(...) etc
OR should we just have one createAddress(Address addr) method that just takes Address object and let the client create the appropriate geography specific Address object?
OR should we have a separate AbstractFactory for each of the significant domain objects? For e.g USAddressFactory, UKAddressFactory etc

I would definitely not recommend option 1: it would result in binding client code to specific geographies, probably requiring lots of switch/if-else statements scattered all over the place, and code changes in each of those whenever geographies are added/removed - the exact problem polymorphism was meant to resolve.
I am not quite clear about the exact difference between your options 2 and 3, but my first approach would be to use some sort of a GeographyFactory to produce part(s) or the whole of the object graph you describe here. Thus clients would call a single createAddress method but the methodf itself would be polymorphic.
Whether the factory would be dependency injected directly to the client or used (partly) transparently in the background similar to a locale in C++ depends on the circumstances - both approach may be fine.

Is there a necessity to create DTO's for this? I am thinking just pass the domain to presentation layer but maintain immutability by enforcing read-only view of the domain.

With regards to addresses, I would try to get away by immutable objects only - if an address changes, you can just create a new object and throw away the old one. Note that addresses are rarely first-class entities, but rather surrogate value objects (i.e. have no identity of their own). But of course, a lot depends on the details of your object-relational mapping solution and the DB schema.
Comment: the diff between 2 and 3 is that, in case of 2 the Client is creating the geography specific Address like UKAddress by calling "new" while in 3, the client is using the UKAddressFactory to create the address.
Comment: regarding "Thus clients would call a single createAddress method but the methodf itself would be polymorphic" this is where the actual problem is. the address properties are not common (no of properties and name of the properties) across geographies. so 1 createAddress(...) is not enough and hence can't be polymorphic. do let me know if i am missing something
Comment: @Pangea, ah, I see. Have you considered using a property list (name-value pairs) to create an Adress, instead of distinct named parameters? Could you give example(s) of how much the address properties differ between geographies?
Comment: Ok here are the details SPAIN (addressType; addressLine; municipalityCode; municipalityName; postalCode; provinceCode; provinceName;) USA (addressType; addressLine1; addressLine2; cityName; stateAbbreviation; zipCode;). As you can see the commonality is "addressType". We can share few properties but SPAIN has more properies in their address than USA
Comment: @Pangea, isn't a Spanish municipality basically a city/town/settlement? And a Spanish province analogous to a US state? If so, you could try generalizing to cover the "least common superset" of all address properties. You would have some properties empty in some geographies, but that is still a small price to pay for the resulting simplicity in dealing with addresses.
Comment: I just provided a subset of the props for Spain. Spain address is much more than this, additions include (URBANISATION, STREET_TYPE STREET_NAME, HOUSE_NUMBER, FLOOR, APARTMENT, LOCALITY) etc
Comment: @Pangea, one additional trick to handle this could be mapping several properties in one geography to a single property in another. E.g. the Spanish STREET_TYPE STREET_NAME, HOUSE_NUMBER, FLOOR, APARTMENT together would give the US addressLine1 when concatenated. So you could have "overlapping views" of the address, with different getters/setters affecting (part of) the same property.


duplicate values in hash

Question: Item1 : Box1
Item2 : Box1
Item3 : Box2
Item4 : Box2
I have an output in the form of a hash(listed above)
I want to process it so that output looks like to be
Box1 = {Item1, Item2}
Box2 = {Item3, Item4}
Comment: Do you have a question?
Comment: I am sorry if it was not clear. I am looking for the code for that change in perl
Comment: It's still not clear. You haven't shown a hash, just some plain text. Are you trying to print a hash, read text into a hash, read text into a hash and print it in a different format, or something totally different?
Answer: this is the most I could make based on your requirements:
use strict;
use warnings;

use Data::Dumper;

my %items = (
    Item1 => 'Box1',
    Item2 => 'Box1',

    Item3 => 'Box2',
    Item4 => 'Box2',
);

my %boxes = ();

foreach my $item_name ( keys %items ){
    push @{ $boxes{ $items{$item_name} } }, $item_name;
}

print "Boxes: ".Dumper( \%boxes );

and prints:
Boxes: $VAR1 = {
          'Box1' => [
                      'Item1',
                      'Item2'
                    ],
          'Box2' => [
                      'Item4',
                      'Item3'
                    ]
        };

Comment: cool, I'm glad I could help
Comment: this is what exactly i was looking for...thankyou
Comment: and sorry for the incomplete question :(

duplicate values in hash


Swapping boot and ROM chips on N64 cartridges

Question: Is this as simple as it seems? Find a matching game that uses same boot chip and swap it over to a seemingly dead board? Or do the opposite and move the game ROM chip over to a board with a working boot chip?
Is there a way to test the pins of the current installed chip to verify if it is bad or not?
I believe that the boot chip I have is CIC-NUS-6102. It's for killer instinct gold. I've gotten three bad ones in a row now and i'm going to fix at least one of them. Can't have a flaky game in the collection :)
I figured someone here may have done this before.
Comment: @fbueckert Questions about gaming hardware are on-topic here.
Comment: It's hard to hell what you're asking here; this sounds more like a hardware question than gaming.
Comment: Unless you have a good chip you have nothing to compare it too.  I check to see if there are any shorts, the Ohm and Farads are all correct.
Comment: Are there infosheets about these chips out in the public domain? Since they are manufactured directly for Nintendo by Sharp I figured that this would be protected knowledge. In my googling's i've not found a datasheet yet. That would tell me what each pin does, where it routes inside the chip, and what the ohm values should be so I can check it.
Answer: Sorry it's an old post, but I'm sure other folks are curious.
The main symptom of CIC failure is the console resets during play or stays on a black screen at boot. Even if this is true, usually it's a smaller problem  of cleaning all of the PCB contacts. (Too many products and techniques to go into and doesn't address the OP's other questions.)
A Logic Analyzer is the best tool to determine if the CIC is working. N64 Game PCB Image The linked image shows a nice clean trace coming from pin 43 (next to the 44) that goes to the far side of the CIC chip. It's hard to say exactly which CIC pin but there aren't many CIC pins actually used. Pretty much any kind of a digital signal on this pin would suggest it's working. Probably good to compare the same signal on a known working game, for example if there is a group of 64 Hi/Lo changes on the good cart and only 32 Hi/Lo changes on the bad cart it could still be a CIC issue.
For reference the CIC is actually a Sharp SM5 4-bit Microcontroller that was customized for Nintendo.
All of the CIC 6102 chips should be interchangeable. There are some CIC 6102A that should work but I wouldn't promise it.
Also since this was first posted, an Ultra CIC has been created that can be used to replace a CIC, this may affect the collecting aspects of a cartridge, but could be a good solution for a player.
Comment: Amazing answer!  Thank you for this information! :D
Answer: The problem you are going to run into is one of electronics. Rather how they are built. Those chips are set on the board so that pins protrude on the other side, and then soldered in place. If you are reasonably competent at soldering, and you have the right tools. (A solder sucker and a soldering iron btw) then it should just be a matter of trial and error. But if you don't it is going to be a nightmare, not to mention not electronically safe.
Check around with electricians and electrical repair places. You might be able to find someone that can help you out.
Edit: Downvote all you want. this is the answer. "Sure you can swap around boot chips for boot chips and ROM chips for ROM chips... HOWEVER, you will not be able to successfully do that. Expert electricians have difficulty accomplishing this task. The boards are designed and built specifically to make doing what you want to, difficult if not impossible." even if you managed to get all of that worked out. even the slightest arcing or even static shock... and you have now destroyed the chip and or board...
Comment: Their problem isn't the physical swap. They're asking if the components can be swapped and still have it operate correctly after.
Comment: Your edit added the important answering-the-question part that was missing before (the "yes it can be done in theory" part). Thank you.
Comment: No, their problem is exactly the physical swap. Physically swaping a ram chip to a board that has a working boot chip. or Physically swapping a boot chip to a board that has a working ram chip.

both of those are covered by my answer. the problem is not "will they work" because yes. that is how electronics and circutry work. you have two working chips on a working board then it will work. the issue is physically changing out the chips and the pins. ...for all the reasons i gave. pffff
Comment: ROM* chip, whatever...
Comment: Soldering isn't too hard. Just because something needs soldering, doesn't mean you can't do it.
Comment: It is really _not_ that hard to swap out a ROM chip...


Navigation in long consecutive list groups within a dropdown

Question: I have a filter bar that allows users to filter and one of the critteria that users can filter by is "Questions". These can be any of the following (and even more):

Age?
Country?
Traveler type?
How would you rate your trip?
Would you recommend us?
etc.

The way our current fitlers (this one and all the rest) are built is something like this:

The problem is that some questions - such as "Country" - have a lot of possible answers and thus occupy a huge part of the list. We cannot control how many answers a question will have and so we are facing a scenario where users have to scroll a lot in order to get to the next question in the list:

I am unsure of what solutions could be found to improve the usability for this. Any ideas or suggestions?
Edit: One solution I was thinking would be that for long lists I limit the items to a certain number (E.g. 10) and add an extra item at the last position that reads "Show all" which then expands the list to reveal all items.
Comment: Which is the criteria for separate filter 1 from filter 2? Is it only for desktop? the option of each filter are show only when clicking on the name of the filter?
Comment: Example of filters would be: Survey type, Questions, Timeframe. In this case the filter that causes the problem would be the "Questions" filter. The design is only for desktop and the list of options is only shown in a dropdown when clicking the filter name.
Comment: Use a treeview type control where they can collapse or expand everything under.
Answer: This is a ripe opportunity for a type-ahead control. In cases where you have a large number of possible choices like this, it is more likely that the user already knows the answer. It would improve the usability tremendously if you let them input the answer and move on, instead of searching a very long list, which wastes their time. For web, I would suggest something like Chosen (http://harvesthq.github.io/chosen/) or Select2 (http://ivaynberg.github.io/select2/)
It looks as if you may be forcing the user into a question and answer workflow, where it may not be needed. If this is a true filtering scenario, the user should be able to freely add and remove filter criteria without being forced into a conversation with the UI. Think of it more as a customer who knows what they want - "I would like a ham and cheese sandwich with chips and a soda" vs "I'm not really sure what I want... can you tell me about your options?"
Comment: We already have type-ahead behaviour implemented in filters because the list will be updated on-the-fly as the user types something into the search box at the top. I am however concerned that this would not be "enough" and that I should make sure the list is also friendlier if used without the type-ahead.
Comment: That's fair, but presenting the user with all of the options isn't sustainable or usable, as you've already pointed out. It seems like you may need to test with them in order to better understand their use case, but I would still point out that asking a user to answer questions in series in this case does not seem like the appropriate way to move forward.
Answer: So as stated in the edit, I was thinking of limiting list groups to a number of max number of items - let's say 10. To reveal all items the user would have to click a "Show all..." button:

This seemed like a decent approach but then the problem is dealing with selected items that are hidden by default. E.g. if item#15 is selected, but the list displays max 10 items by default. How do I show that there are extra items selected? One way of doing this would be to show them as extra selected items in the group:

I've used the vertical dots to suggest there are other items hidden between the selected ones, but I think this wouldn't be as much of aid as it would cause more confusion so I can drop them.
Even so, I'm still not very confident in this solution.
Answer: Take a look at what websites with a lot of options (such as eBay) have done with their filtering criteria. The advantage in this is they've done a lot of user testing already to arrive at their current filtering methodology.
All those scrolling dropdowns where you can select random items (I'm assuming with [ctrl+click]) has a high probability for user error and frustration.


C: convert a mathematical expression string into an int with the result

Question: I have an issue with a program: the task is to write down a function that, given a string with only numbers and + or - symbols; return the result of the expression in the int value.
I mean, given the input char="2+1+3" the result should be int=6.
I thought about using strtok to divide it into tokens and then convert them into numbers;
Do anyone have some kind of suggestion?
I'm a first year student so i'm not quite used to complicate things, and moreover I can use only standard library.
Thanks to all.
int string_expression(char s1[]){
  int i;
  char*pch;
  char* frase_dup=strdup(s1);
  int count=0;
  char**dupl;
  long int pcf;
  pch=strtok(frase_dup,"+");
  pcf=strtol(const char *pch, char **dubl, int 10);

  for(i=0; i<strlen(s1); i++) {
    if(s[i]=="-")  count=count+pcf[i+1]*-1;
    if(s[i]!=NULL) count=count+pcf[i];
  }
  return count;
}

Of course this code is all wrong, but as i said, i'm a newbie :(
Comment: my suggestion: write some code :P
Comment: You are trying to write a calculator. Start by googling stuff like "how to write a calculator in C".
Comment: **Warning** -- If the next assignment is to process `*` and `/`, merely doing `strtok`'s is not going to help much, given that you have an order of operations to consider.
Comment: There's a worked example in Kernighan and Ritchie that covers this.
Comment: Ah, nice that @Bathsheba mentions it: Buy that book. If you are sometimes on Linux or a Unix, also buy Kernighan and Pike's [The Unix Programming Environment](https://en.wikipedia.org/wiki/The_Unix_Programming_Environment), which is similarily good. If you don't have money, copy it in a copy shop or look for online PDFs. Yes, it's not nice, but you can always buy it later (I have). If you do anything more in-depth with your box, consider buying [Stevens' Advanced Programming in the Unix Environment](https://en.wikipedia.org/wiki/Advanced_Programming_in_the_Unix_Environment) as well.
Comment: sum of do strtol each number.
Comment: That function leaks memory every time it's called due to the `strdup` call.  You're responsible for calling `free()` to deallocate the memory.
Comment: @Paul will the OP live to see an effect from that? ;-) But you are right.
Comment: @PeterA.Schneider It is poorly written if it leaks memory.   Imagine if that function were called in a loop, processing expressions from a file, and there are millions of expressions.  No need to introduce bad habits to a newbie.
Comment: See: https://github.com/codeplea/tinyexpr
Answer: Since there is only addition and subtraction (white-space is not included)
It is may be just summed to convert from a string by using strtol each of the numerical value as a sequence of numbers.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int string_expression(char s1[]){
//only numbers and + or - symbols
    char *endp = s1;
    int sum = 0;
    while(*s1){
        sum += strtol(s1, &endp, 10);
        s1 = endp;
    }
    return sum;
}

int main(void){
    printf("result = %d\n", string_expression("2-1+3"));
    return 0;
}

Comment: Thanks a lot, I didn't knew the correct application of strtol, now i get it.
Just a couple of questions: The while calls a pointer to s1, why? And also, why you assign s1=endp?
Thanks again :)
Comment: @Shankher `s1` is the beginning of the string to be parsed.
`endp` is the failed position in the analysis.
`s1 = endp;`  is a need to be updated for the next analysis.
Comment: Ah okay okay, so updating s1 means that the loop can continue.
Answer: User strtol to parse the next number. Then check the next operation. Rinse and repeat. Here is how you could do that in pseudocode:

operation ← '+', accumulator ← 0, ptr ← beginning of text
summand ← strtol (ptr, &ptr, 10)
if operation ≡ '+' then accumulator ← accumulator + summand
else if operation ≡ '-' then accumulator ← accumulator − summand
else expression is malformed.
operation ← *ptr, ptr ← ptr + 1
if operation ≡ '\0' then return accumulator.
goto step 2
Answer: You'll later need to code some parser (and perhaps before a lexical tokenizer or lexer). This is a very classical exercise.
You could hand-code some recursive descent parser or use some parser generator tool (a.k.a compiler-compiler, somehow incorrectly because a compiler is a lot more than parsing).
The GNU bison tool has your exercise as an example in its documentation.
You might want (at least for fun) to explicitly construct an abstract syntax tree in memory before evaluating it.
So you could "steal" some code found on the Web quite easily, but you will learn a lot more by doing it yourself. Learning programming takes a lot of time (ten years perhaps).


Can't boot into Ubuntu in Windows 10 / Ubuntu dual boot

Question: I installed Ubuntu on a Dell XPS 13 laptop that had Windows 10 preinstalled on it. I installed it from a USB flash drive on a partition.
When I boot my computer I can only boot into Windows 10 and Ubuntu is nowhere to be seen.
If I boot into my USB then I can see that Ubuntu is installed, but I can't get to it from the BIOS boot menu.
Comment: it doesn't :( i'm not seeing UBUNTU in the boot menu
Comment: This might [help](https://help.ubuntu.com/community/WindowsDualBoot) you out with your problem.
Answer: Immediately after the motherboard / computer vendor logo splash screen appears when the computer is booting, with BIOS, quickly press and hold the Shift key, which will bring up a GNU GRUB menu screen. With UEFI press (perhaps several times) the Esc key to get to the GNU GRUB menu screen. Select Ubuntu from the GRUB menu and press Enter.
From Ubuntu open the terminal and type:
sudo update-grub && sudo reboot

If this doesn't work try booting to an
Ubuntu live session from the USB flash drive that you used to install Ubuntu, and repairing the GRUB bootloader with Boot Repair. From an Ubuntu live session open the terminal and type:
sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo apt update
sudo apt install -y boot-repair
sudo boot-repair

Open the Boot Repair application and select Advanced Options -> Main Options tab -> check Reinstall GRUB and Unhide boot menu as shown in the below screenshot. Click the Apply button. Then reboot the computer with sudo reboot

If the OSs were installed in different modes, dual booting Windows and Ubuntu with grub can't work. If your Windows is installed in BIOS mode, it is recommended to install your Ubuntu in BIOS mode, but if it's installed in UEFI mode, then do the same with Ubuntu. To check if your Windows is installed in UEFI, press the keyboard combination Windows + r then enter the command msinfo32 in the Run window. In the new window that opens up look for the entry after where it says BIOS Mode.

          BIOS vs. UEFI
If you have installed Ubuntu in legacy mode on the same drive with GPT partitioning, you can use Boot Repair's Advanced options to uninstall grub-pc and install grub-efi-amd64. That converts the Ubuntu installation from BIOS boot to UEFI boot, the same firmware as most recently manufactured laptops with Windows pre-installed have.
Converting Ubuntu into UEFI mode

Start Boot-Repair, and select Advanced options -> GRUB location tab.
If you do not see a Separate /boot/efi partition option, this means that your PC does not have any UEFI partition.
If you see a Separate /boot/efi partition option, put a checkmark in the checkbox to the left of it, then click the Apply button in the lower right corner.

Set up your BIOS so that it boots the hard drive in UEFI mode. The way to adjust this setting depends on the specific model of the computer, but generally this setting is located in the boot priority settings under the Boot tab of the BIOS/UEFI setup utility.

Converting Ubuntu into BIOS mode
Note: Use this procedure only to convert an UEFI mode Ubuntu installation to boot in BIOS/CSM/legacy mode. Such a conversion may be necessary if some hardware doesn't work correctly under UEFI mode. (Graphics cards are a common source of problems.) Converting to boot in BIOS/CSM/legacy mode while Windows boots in UEFI mode can make the boot process more awkward -- you'll need to use the computer's built-in boot manager to switch between OSs, and some computer's have such poor boot managers that this may be impossible.

If Ubuntu is installed on a GPT disk (you can check it via the sudo parted -l command), use GParted partition editor to create a BIOS-Boot partition (1MB, unformatted filesystem, bios_grub flag) at the start of its disk.
Start Boot-Repair, and select Advanced options -> GRUB location tab.
Uncheck the Separate /boot/efi partition option

Click the Apply button in the lower right corner.
Set up your BIOS so that it boots the HDD in Legacy mode. Generally this setting is located in the Boot tab → Boot order section of the BIOS.

Converting Windows into GPT mode
MBR2GPT.exe is a command line tool which is located in the System32 folder in Windows 10. With it you can effectively and non-destructively convert a Windows 10 OS disk from MBR (for Legacy BIOS) to GPT partition style (for UEFI) without modifying/deleting any data on the disk or making a clean installation of Windows 10.

Links:

UEFI - Community Help Wiki, Converting Ubuntu into UEFI or Legacy mode
Convert from EFI to BIOS boot mode
Comment: @Line The splash screen is the black screen with the motherboard / computer manufacturer's logo on it that appears when booting the computer.
Comment: what is BIOS/UEFI splash screen?
Answer: Disable the hibernation mode and Fast Boot in Windows.
Open command prompt as administrator and execute :
powercfg /h off

Open the legacy version of the Windows Control Panel (not the modern version).
Select Energy Settings, enable show hidden settings and uncheck Fast Boot.
After having done this - shutdown the computer completely - do NOT reboot.
Boot into the BIOS and select Ubuntu as the default operating system to boot.
Update :
In case there is no Ubuntu entry to be found in the BIOS / UEFI settings,
re-install the GRUB boot loader to your Ubuntu installation  in EFI mode.
Boot from the Ubuntu installation media - open a terminal and execute:
sudo mount /dev/sdXXX /mnt
sudo mount /dev/sdXX /mnt/boot/efi
for i in /dev /dev/pts /proc /sys /run; do sudo mount -B $i /mnt$i; done
sudo chroot /mnt
grub-install /dev/sdX
update-grub

Note:
sdX = disk | sdXX = efi partition | sdXXX = system partition
To identify the partition numbers use GParted - it is included in the Ubuntu installation media.
Boot into BIOS and select Ubuntu in UEFI settings to be the default operating system to boot.
Comment: Thanks! I can't see Energy Settings in the control panel?
Comment: Ok, I restarted and still the boot menu doesn't show UBUNTU
Comment: @Haim : It is there ... something with energy ... search through the old version of control panel ... maybe fast boot is already disabled after you executed the command. :)
Comment: @Haim : Did you switch the default operating system to Ubuntu in BIOS / UEFI settings ? :)
Comment: where would I do that? BTW thanks for trying to help me out
Comment: @Haim : You're welcome ! You have to look into the DELL XPS 13  manual ... but if DELL did not change it, this would be the F2 key  - so start the computer and immediately press F2 to access the BIOS settings. :)
Comment: Thank you so much for all your help, I ended up figuring it out.
When I was loading the USB I was loading it and installing UBUNTU from the legacy boot. I tried it again while loading from the UEFI boot and it all works!
Comment: "Open the legacy version of the Windows Control Panel" - how to do that?
Answer: Shutdown. Then press F12 on boot and use arrows to choose ubuntu (note lowercase).
Also, you should try shutting down, press F2 to open BIOS/UEFI settings and disable Secure Boot and make ubuntu top priority. Then GRUB can boot Windows.
If that doesn't work check the fast boot settings in BIOS and the power settings in Windows.

Search for and open Power Options in the Windows Start menu.
Click Choose what the power buttons do on the left side of the window.
Click Change settings that are currently unavailable.
Under Shutdown settings disable Turn on fast startup by unchecking it.
Comment: The problem us that UBUNTU doesn't show in the list of boot options
Comment: I had the same problem, because UEFI was pulling up the Windows 10 bootloader not GRUB.
Comment: This is the only worked answer for me.
Answer: I had the exact same problem. What fixed it for me was this:
I have 2 different hard drives installed. It took me forever to figure this out but was solved it was changing the boot priority from the first to the second drive. Probably the boot manager for ubuntu was installed on the other drive so it couldn't find it and booted straight into windows.
Answer: I had a similar issue, and it turned out that the problem was that there wasn't a working driver for my GPU preinstalled on the OS. My solution was to enter Recovery mode. At the GRUB menu press the down arrow key until you select the 2nd entry from the top (the entry with the recovery mode in its description) and then press Enter twice.
Now you should see this Recovery Menu:

Select the network option from the Recovery menu and press Enter.
Select the root option from the Recovery menu, and then use the command line to run ubuntu-drivers autoinstall && reboot to automatically install the proprietary graphics driver.
Comment: how did you take a screenshot of the recovery menu?
Comment: @HaadeeBinHafees The screenshot is of an Ubuntu guest OS that's running in a virtual machine.
Answer: What worked for me is selecting OS boot manager in the BIOS boot Options menu and pressing Enter.
Boot Options menu in BIOS:

A popup should appear asking whether you want Windows or Ubuntu boot manager. Use F5/F6 to move Ubuntu to the top.
After clicking enter after selecting OS boot manager:

Then exit BIOS by saving settings. It should boot into GRUB after that. Unfortunately none of these other answers worked for me.
Answer: For all cases when grub has been successfully installed in the ESP (EFI System Partition) but the installer didn't (or couldn't) change the boot order, users have to do it manually by opening UEFI settings -> Boot tab (the actual menu name could vary) and select Ubuntu as the first boot option in the boot sequence. That should enable the computer to boot to the GRUB menu which in turn allows selecting Ubuntu or Windows.


Letting users register to website, PHP

Question: I have my website and it's form is like this:

Information
More information
Yet more information

I want to allow users to register a username and a password so that they can log in and leave comments on the items 1, 2, 3 etc. Each item of information is stored in a mysql table, so to generate the page, each item 1, 2, 3 etc is a row/record from the table.
I am looking for a guide/resources on how to accomplish user registration and commenting on my items.
Answer: You will find a good tutorial that takes you through the steps to create a login for your website with PHP here.
After you get the login to work you can modify it to suit your particular circumstances.
Most likely you will have to create a table with userid and itemid to store which user has access to which item.
Answer: User registration is fairly straight forward.  Create a form that asks for information about the user that you desire, probably protect it with some sort of captcha (I'd recommend recaptcha).  A lot of registration includes some sort of email verification, but I find that annoying.
As to commenting, I'd create the idea of a permission. Anyone not logged in has the "guest" permission, which doesn't allow commenting, and logged in users have the "user" permission and therefore can comment on content.
Answer: net.tutsplus has been doing a series of videos on how you can use the CodeIgniter PHP framework to accomplish many different things on a website such as a login screen. I think after you watch this video you have a better understanding of what you will need to implement your security requirements and also see an example of the MVC pattern that is very common nowadays.
Good luck and hope this helps you.

Letting users register to website, PHP