Age Verification

Question: I got stumped doing age verification and am wondering what's the best way now. It does not have to be robust, my initial plan was using jquery.
I found this resource,
http://www.techerator.com/2010/09/how-to-perform-age-verification-with-jquery-and-cookies-mmm-cookies/
For ease of use, I have pasted the method here:
Used on pages that need verification
if ($.cookie('is_legal') == "yes") {
 //legal!
} else {
 document.location = "http://www.domain.com/[pathtofile]/verify.php?redirect=http://<?php echo $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; ?>";
}

The verification page
$('#accept-btn').click(function(){
 $.cookie('is_legal', 'yes', { expires: 1, path: '/', domain: 'domain.com' });

 <?php if ( !isset($_REQUEST['redirect']) || $_REQUEST['redirect'] == "" ) { ?>
 document.location = "http://www.domain.com";

 <?php }else{ ?>
 document.location = "<?php echo $_REQUEST['redirect']; ?>";
 <?php } ?>
});

here is the html part of it.

Are you OVER 18

YES

     NO

First issue is that the else statement is not working, as well it seems to be using the same variable for the redirect for the YES option and the NO option.
SO I am curious, just for learning sake, why this is not working properly and how to fix, and secondly what's really the better way here. Like I said seo/php or a robust way is not critical.
My desired result is that, when they access any page on the site they get a yes or no option and then, when YES they get access to the page, if they choose no, it's a redirect.
Comment: I guess you'd have to be eighteen years old to figure out how to set a cookie in the browser using JavaScript, right?
Comment: You are mixing languages in a single statement. Short answer is don't do that. Ever.
Comment: Tadman, you might find this useful, it's got pictures too http://www.wikihow.com/Be-Sarcastic
Comment: Fresheye, ok, gotcha, I found that tutorial online and it was not working right.
Comment: @Deedub the tutorial does not mix languages. No one mixes languages, because its a very bad idea. Also you have not provided enough information to debug this. Please provide the code for the `NO` option, as well as the html for the the buttons. Also please be more clear as to your desired result. What is the difference between `http://www.domain.com` and `` for example.
Comment: To understand why this is wrong you need to understand the client-server model first. PHP is interpreted **before** JavaScript. You can generate JS in PHP but it's all text, they don't understand each other, you need a format to transfer your data from and to the server, like JSON or XML. But the nature of the web is synchronous, you'd have to leave to page to send or receive info, that's when AJAX comes in, it lets you do it asynchronously, without a page refresh.
Comment: Don't forget Tadman's right-hand man ;-) "moi" And George C., God rest his comedy soul. There's a certain thing about Canadian comedy, a *"je ne sais quoi"* type of thing ;-) Wouldn't you say @tadman ? ;-)
Comment: Fresheye - thanks! I guess I am confused alittle. There was no real clear explanation of what the NO button was. I assumed that it was implemented in the ELSE part.
Comment: elclanrs - gothca - thanks!
Comment: Fred - here is a resource for you.  http://www.wikihow.com/Be-Funny
Comment: did you add jquery and jquery.cookie.js?
Comment: yeah, :) Not that far back, ha.
Comment: @Deedub [**Here**](http://www.georgecarlin.com/) <= he'll set you straight, and you can [**subscribe to this channel**](http://www.thecomedynetwork.ca/) - Enjoy the ride ;-)
Answer: How about a pure PHP version of this??
<?php

/**
 * @author - Sephedo
 * @for - Deedub @ Stackoverflow
 * @question - http://stackoverflow.com/questions/18751788/age-verification
 */

$min_age = 18; // Set the min age in years

if( isset( $_POST['submit'] ) )
{
    if( mktime(0, 0, 0, $_POST['month'], $_POST['day'], $_POST['year'] ) < mktime(0, 0, 0, date('m'), date('j'), ( date('Y') - $min_age ) ) )
    {
        var_dump("over $min_age");
    }
    else
    {
        var_dump("under $min_age");
    }
}

?>

<form method="POST" >
<fieldset>
<legend>Enter your age</legend>
Day:
<select name="day" >
<?php
    for( $x=1; $x <= 31; $x++ )
    {
        if( $x == date("j" ) ) echo "<option selected>$x</option>"; else echo "<option>$x</option>";
    }
?>
</select>
Month:
<select name="month" >
<?php
    for( $x=1; $x<=12; $x++ )
    {
        if( $x == date("m" ) ) echo "<option selected>$x</option>"; else echo "<option>$x</option>";
    }
?>
</select>
Year:
<select name="year" >
<?php
    for( $x=date("Y"); $x>=(date("Y")-100); $x-- )
    {
        echo "<option>$x</option>";
    }
?>
</select>
<input type="submit" name="submit" />
</fieldset>
</form>

Comment: sephendo, that could work too! THANK YOU!  I think it would be simpler to have a simple yes or no.
Comment: I have added another answer with just the yes and no buttons
Comment: I also added the cookie bit - be careful when testing and add setcookie('age_verification', '') at the top to reset
Answer: New Version as requested in comments
<?php
    /**
     * @author - Sephedo
     * @for - Deedub @ Stackoverflow
     * @question - http://stackoverflow.com/questions/18751788/age-verification
     */

    // ADD TO ALL PAGES WHICH NEED TO HAVE AGE VERIFICATION
    session_start();
    if(! isset( $_SESSION['age_verification'] ) or $_SESSION['age_verification'] != true ) die( header("Location: checkage.php?url=http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]") );

    // session_destroy(); // uncomment to reset for testing and debugging.

    echo 'hello over 18 person';

?>

<?php

    /**
     * @author - Sephedo
     * @for - Deedub @ Stackoverflow
     * @question - http://stackoverflow.com/questions/18751788/age-verification
     */

    // checkage.php
    session_start();

    // checkage.php
    if( isset( $_POST['yes'] ) )
    {
        $_SESSION['age_verification'] = true;

        if( isset( $_GET['url'] ) )
        {
            die( header('Location: ' . $_GET['url'] ) );
        }
        else
        {
            die( header('Location: index.php') );
        }
    }
    elseif( isset( $_POST['no'] ) )
    {
        $_SESSION['age_verification'] = false;
    }

    // The below line will check if someone has already said no so you can show them a page which tells them to they are too young.
    if( isset( $_SESSION['age_verification'] ) and $_SESSION['age_verification'] != true ) die( header('Location: tooyoung.php') );

    ?>

    <form method="POST" >
    <fieldset>
    <legend>Are you over 18?</legend>
    <input type="submit" name="yes" value="Yes" /> <input type="submit" name="no" value="No" />
    </fieldset>
    </form>

Comment: thanks Sephedo- so how does it capture the url of the specific page you are on, assuming people can visit any page on the site?
Comment: so you are redirecting back.. ill add something in.
Comment: I have changed the above answer what do you think? tried and tested code
Comment: I get the yes or not abouve the page content and it still shows the page... weird :)
Comment: I did make a tweek just after posting it just try copying it again see if that makes a difference
Comment: Sorry for the late response. I just tried it again, and it still hows the page.

Age Verification


Sing in with username and reset password with only email - B2C CUSTOM POLICY

Question: I am using Custom Policy B2C, when I register, I insert email, username and password. When I  sign in, I sign in with username. When I reset password, I reset password with only email,but just here I have to next error message
enter image description here
I believe that the email not match with username, but I want reset password only email, please any help,  What XML tag Should I to setting ? or any other setting?
MY RESETPASSWORD.XML
     <BasePolicy>
    <TenantId>XXXXXXXXXX.onmicrosoft.com</TenantId>
    <PolicyId>B2C_1A_TrustFrameworkExtensions</PolicyId>
  </BasePolicy>
  <RelyingParty>
    <DefaultUserJourney ReferenceId="PasswordChange" />
    <TechnicalProfile Id="PolicyProfile">
      <DisplayName>PolicyProfile</DisplayName>
      <Protocol Name="OpenIdConnect" />
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="email" />
        <OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub" />
        <OutputClaim ClaimTypeReferenceId="tenantId" AlwaysUseDefaultValue="true" DefaultValue="
            {Policy:TenantObjectId}" />
      </OutputClaims>
      <SubjectNamingInfo ClaimType="sub" />
    </TechnicalProfile>
  </RelyingParty>

MY TRUSTFRAMWORKEXTENTIONS.XML => REGISTER
<TechnicalProfile Id="AAD-UserWriteUsingLogonName">
                    <Metadata>
                        <Item Key="Operation">Write</Item>
                        <Item Key="RaiseErrorIfClaimsPrincipalAlreadyExists">true</Item>
                    </Metadata>
                    <InputClaims>
                        <InputClaim ClaimTypeReferenceId="signInName" PartnerClaimType="signInNames.userName" Required="true" />
                    </InputClaims>
                    <PersistedClaims>
                        <PersistedClaim ClaimTypeReferenceId="signInName" PartnerClaimType="signInNames.userName" />
                        <PersistedClaim ClaimTypeReferenceId="email" PartnerClaimType="strongAuthenticationEmailAddress" />
                        <PersistedClaim ClaimTypeReferenceId="newPassword" PartnerClaimType="password" />
                        <PersistedClaim ClaimTypeReferenceId="displayName" DefaultValue="SomeDefaultDisplayNameValue" />

                    </PersistedClaims>
                    <OutputClaims>
                        <OutputClaim ClaimTypeReferenceId="objectId" />

                        <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="localAccountAuthentication" />
                        <OutputClaim ClaimTypeReferenceId="userPrincipalName" />
                    </OutputClaims>
                    <IncludeTechnicalProfile ReferenceId="AAD-Common" />
                    <UseTechnicalProfileForSessionManagement ReferenceId="SM-AAD" />
        </TechnicalProfile>
            <TechnicalProfile Id="LocalAccountSignUpWithLogonName">
                    <DisplayName>User ID signup</DisplayName>
                    <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=188.8.131.52, Culture=neutral, PublicKeyToken=null" />
                    <Metadata>
                        <Item Key="IpAddressClaimReferenceId">IpAddress</Item>
                        <Item Key="ContentDefinitionReferenceId">api.localaccountsignup</Item>
                        <Item Key="LocalAccountType">Username</Item>
                        <Item Key="LocalAccountProfile">true</Item>
                        <Item Key="language.button_continue">Registrase</Item>

                         <Item Key="EnforceEmailVerification">false</Item>
                    </Metadata>
                    <InputClaims>
                        <InputClaim ClaimTypeReferenceId="signInName" />
                    </InputClaims>
                    <OutputClaims>
                        <OutputClaim ClaimTypeReferenceId="objectId" Required="true" />
                        <OutputClaim ClaimTypeReferenceId="signInName" Required="true" />
                        <OutputClaim ClaimTypeReferenceId="newPassword" Required="true" />
                        <OutputClaim ClaimTypeReferenceId="reenterPassword" Required="true" />
                        <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="Verified.Email" Required="true" />
                        <OutputClaim ClaimTypeReferenceId="executed-SelfAsserted-Input" DefaultValue="true" />

                        <OutputClaim ClaimTypeReferenceId="authenticationSource" />
                        <OutputClaim ClaimTypeReferenceId="userPrincipalName" />

                    </OutputClaims>
                    <ValidationTechnicalProfiles>
                        <ValidationTechnicalProfile ReferenceId="AAD-UserWriteUsingLogonName" />
                    </ValidationTechnicalProfiles>
                    <UseTechnicalProfileForSessionManagement ReferenceId="SM-AAD" />
                </TechnicalProfile>

MY TRUSTFRAMWORKEXTENTIONS.XML => FORGOT PASSWORD
nter code here

                        <OrchestrationStep Order="3" Type="InvokeSubJourney">
                            <Preconditions>
                                <Precondition Type="ClaimsExist" ExecuteActionsIf="false">
                                <Value>isForgotPassword</Value>
                                <Action>SkipThisOrchestrationStep</Action>
                                </Precondition>
                            </Preconditions>
                            <JourneyList>
                                <Candidate SubJourneyReferenceId="PasswordReset" />
                            </JourneyList>
                        </OrchestrationStep>

==========================================================================
<SubJourneys>
        <SubJourney Id="PasswordReset" Type="Call">
        <OrchestrationSteps>

            <OrchestrationStep Order="1" Type="ClaimsExchange">
            <ClaimsExchanges>
                <ClaimsExchange Id="PasswordResetUsingEmailAddressExchange" TechnicalProfileReferenceId="LocalAccountDiscoveryUsingEmailAddress" />
            </ClaimsExchanges>
            </OrchestrationStep>

            <OrchestrationStep Order="2" Type="ClaimsExchange">
            <ClaimsExchanges>
                <ClaimsExchange Id="NewCredentials" TechnicalProfileReferenceId="LocalAccountWritePasswordUsingObjectId" />
            </ClaimsExchanges>
            </OrchestrationStep>
        </OrchestrationSteps>
        </SubJourney>
     </SubJourneys>

When I register, my email not save look at this picture,
what I wrong? , I am new with custom policy
enter image description here
Answer: If you created the user with a username and didn't capture the email then you can't use the standard password reset because that is based on email.
Look at this policy - it shows how to use username or email.
But beware. Email is preferred for security because you can ask the user to verify the email. The only way to verify username is to use MFA and ask the user e.g. to enter the SMS OTP.
That's why you should always capture the email when you signup with username.
Comment: Hi @rbrayb, I think you are right, I edited my post with my register tags and add a picture
Comment: I select this comment, because that link shows me how to create a new custom flow, thanks,


Not enough space on /tmp

Question: I'm not able to run update manager as I get an error saying that there is not enough free space in the /tmp directory. I've practically cleaned out the tmp directory but the error persists.
here's df-h
/dev/loop0       13G   11G  952M  92% /
udev            2.0G  4.0K  2.0G   1% /dev
tmpfs           785M  920K  784M   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            2.0G  584K  2.0G   1% /run/shm
/dev/sda6        20G   14G  6.4G  68% /host

overflow        1.0M   16K 1008K   2% /tmp

Comment: where is your / ? Why is it on a /dev/loop ?
Comment: Here, a simple reboot solved the issue. As @josinalvo explained, `/` was full and was increased on the fly: The disk was a virtual disk.
Answer: What seems to have happened:
Your / was full, then Ubuntu created a new partition, in RAM memory, to use temporarily.
Now, this 1MB partition is not big enough for the job, either.
What we can do:
1) increase the size of this partition just to do the upgrade
2) actually delete enough files in the HD that this partition is no longer needed.

To do 1:
open a terminal and run
sudo umount /tmp
sudo mount -t tmpfs -o size=1048576,mode=1777 overflow /tmp

This should give you an 1MB partition (just like the one you had =P).
Now, to increase the size, you increase the size in that line, so that, with size=10485760, you'd get 10 MB.
Your goal is to find a number that is enough for the job, but leaves enough ram too
Comments on 1
You may want to try sudo umount -l /tmp, if you get some variation of "the file system is busy and cannot be unmounted"
Another possible solution to "the file system s busy(...)" is to do fuser -m /tmp to find pids (process numbers) that are using /tmp, then ps -elf <pids>, stop or kill processes
You may want to try sudo mount -t tmpfs -o size=1MB,mode=1777 overflow /tmp or even sudo mount -t tmpfs -o size=1G,mode=1777 overflow /tmp (for 1 megabyte or 1 gigabyte, respectively) - that is, units are available so that you dont have to type a huge number

To do 2:
Open a terminal and run sudo umount /tmp or, if that fails, sudo umount -l /tmp.
Then clean up!
Delete files in /tmp (now /tmp is the thing actually in your HD, rather than a virtual ram disk), uninstall unused packages, delete files in your home folder and so on.
Comment: This answer worked for me but I needed to kill some things before /tmp would umount. If you get a message that says /tmp is busy, then do `fuser -m /tmp` to find pids that are using /tmp, then `ps -elf `, stop or kill processes. Then umount /tmp. Also suggested on internet `sudo umount overflow`.
Comment: Actually, I failed to `umount` this tmpfs by all above ways.
I googled `umount -l /tmp` and it helped.
Comment: @gaoithe I used `sudo lsof | grep tmp` to find the pid then `kill` to kill it. In my case this was Xorg. This is the X Window System which I don't use anyways.
Comment: To do 2 even simpler: after cleanup just reboot. This avoids problems with `umount /tmp` because of a being busy.
Comment: use size with G or MB with all above, and it will work.
Comment: May i know why you have reverted back my edits?
Comment: Thank you for your improvements on my answer! (but some, I did not like and removed)
Comment: Too many processes to fool around with on a live web server, so I followed @Roland's suggestion to reboot (sudo shutdown -r now). As a side benefit  I gained back 10G on a 40G file system - although that may have been from rebuilding db tables (mysql "optimize") I did just to be sure.
Comment: The instruction under 'to do 2' worked for me. With Ubuntu 14.04 LTS. This issue came about after updating a kernel images. I have removed unused kernel images following https://superuser.com/a/1042344/491642
Answer: sudo mount -o remount,size=1048576 /tmp

changes tmpfs size without need to unmount partition and hence not disturbing running apps.
Answer: I know about this problem on my Kubuntu 16.04, and user63070 shows the best answer. Change the size at /etc/fstab like this:
tmpfs     /tmp     tmpfs     defaults,size=10G,mode=1777     0     0

Reboot, and you got 10GB for your /tmp folder.
Answer: Looks like your / partition is full.
If you have space on other partitions on your disk, you might use this space to increase the size of your / partition. There are tools available for this, for example gparted.
sudo apt-get install gparted

http://gparted.sourceforge.net
Comment: is there a 'safer' tool, apparently gparted is kinda tricky to handle especially for noobs
Comment: It is very tricky, and not the easiest way to address the problem. I would not venture using it for this
Answer: I am pretty sure @user220420 was referring to /etc/fstab instead of /etc/mtab. I had lots of free GB in my root, however, Firefox wouldn't let me download anything from the internet. A small window would pop-up before finishing any download, telling /tmp had not enough space left. Within fstab, there's this line where you can increase tmp's folder size. It was set to 100M so I changed it to 1000M. After reboot, I right-clicked on /tmp (in root) and properties showed 1GB free (to make sure changes applied properly). That was it.
Comment: Let me tell you that this worked with other distros other than Ubuntu. I could accomplish this on Sabayon as well.
Answer: If you install your Ubuntu with default LVM settings nowadays, your LV size might be to low. Run:
df -h

and check if /dev/mapper/ubuntu--vg-ubuntu--lv is full (about 100%). If so, run:
sudo lvdisplay

to get the actual size of your LV. If you have space left more than that, you can allocate it by:
sudo lvextend -l +100%FREE /dev/ubuntu-vg/ubuntu-lv

This will then use all available disk space. Extend the filesystem afterwards to use the new disk space:
sudo resize2fs /dev/mapper/ubuntu--vg-ubuntu--lv

Answer: Open up /etc/mtab in your favorite text editor with root privledges (ie "sudo vim /etc/mtab"). And increase the memory allocated to your /tmp folder. After restart Ubuntu will increase the space to /tmp, and fix this problem.
Comment: 1) You don't edit `/etc/mtab` - that file is handled by `mount`, 2) there is probably no entry fo `/tmp` in `etc/fstab` either.

Not enough space on /tmp


Proving the following inequality using Mathematical Induction

Question: I need to prove the following inequality is true for n > 2.
$n^3$ > 2$n^2$ + 3

Prove using base case n = 3:

$3^3$ > 2$(3)^2$ + 3
27 > 2(9) + 3
27 > 18 + 3
27 > 21 (true)

Assume true for n = k:

$k^3$ > 2$k^2$ + 3

Prove for n = k +1

$(k+1)^3$ > 2$(k+1)^2$ + 3
I'm not sure where to go from here. I'm thinking I may need to prove it for n = k +2 (since I'm proving the expression is true for n > 2), but I'm not sure. How would I be able to prove this using n = k + 1?
Comment: I would start by opening the parentheses in the third step.
Comment: Are you specifically asking for an induction proof? Straight proof is easier...
Answer: Note that\begin{align}(k+1)^3&=k^3+3k^2+3k+1\\&>2k^2+3+3k^2+3k+1\text{ (by the assumption)}\\&=5k^2+3k+4.\end{align}So, all that you have to prove now is that $5k^2+3k+4\geqslant2(k+1)^2+3=2k^2+4k+5$. In other words, what remains to be proved is that $k^2\geqslant k+1$, which is quite easy.
Comment: I'm not quite sure where the expression following $2k^2$ + 3 comes from in your second line of working.
Comment: You are assuming that $k^3>2k^2+3$, right?! Therefore,$$k^2+3k^2+3k+1>2k^2+3+3k^2+3k+1.$$This is only a particular case of $a>b\implies a+c>b+c$.
Answer: Now, $$(k+1)^3=k^3+3k^2+3k+1=2(k+1)^2+3+k^3+k^2-k-4>2(k+1)^2+3.$$
Answer: Hint: $(k+1)^3>2(k+1)^2+3$ is equal to $-k^3>-k^2+k+4$ now we have
$$k^3>2k^2+3>-k^2+k+4$$ if $$k^2-k+7>0$$ which is true for $k\geq 3$


Single class has a Class Redefinition Error

Question: I'm new to C++, and I'm having a problem with my class definitions in a header file.
The code for the header file (Student.h) is:
#include <string>
using namespace std;

class Student
{
  // Data Members for a Student
  string id;
  string preferences[3];
  int skill;

  // Constructor
 public:
  Student(){}

 public:
  void SetID(string str)
  { this->id = str; }
 public:
  void SetSkill(int i)
  { this->skill = i; }
 public:
  void SetPreferences(int i, string s)
  {
    this->preferences[i] = s;
  }
};

class StudentSchedule
{
 public:
  StudentSchedule(){}
};

The compiler error says that line 14 (class Student) is a redefinition of 'Student', and that line 15 ({ -- the open brace following class Student) is the previous definition of 'Student'.
The same error on the first two consecutive lines exists for the StudentSchedule class.
I have no .c, .cpp, or .h files anywhere in my compilation that define either class. I have no idea why I'm getting this error.
Answer: You need header guards on that header file.  It is presumably being included twice.
Modify the header, adding these lines to the beginning and end.
#ifndef STUDENT_H
#define STUDENT_H

// Put the entire contents of your header here...

#endif

The define doesn't need to be STUDENT_H... it just needs to be unique.
With these directives added, the compiler will ignore all contents of the header file if it has already been parsed.
Alternatively, while it is not standard C++, all major compilers will allow you to put a single
#pragma once

as the first line of the header to prevent it from being parsed multiple times.
Answer: You're probably including the .h file twice, the first time it will define Student, the second it will try to redefine it.
See the Wikipedia entry on include guards for a more extensive explanation of the problem and information on how to avoid it.
In short, there are two ways to do it
Version 1, #defined include guards
#ifndef STUDENT_HPP
#define STUDENT_HPP

...your code here...

#endif

Usually the #define is called some variation of the file name since it has to be different in every include file.
Version 2, #pragma once
#pragma once

...your code here...

This pragma is (as most pragmas) not portable to all compilers, but some of the most important ones. It also has the advantage of not needing a manually assigned name.
Which you use is up to you, but you most likely have to pick one :)
Answer: I prefer using
   #pragma once

as the first line of a header file, instead of the defines. Even if this is non-standard, it does avoid name clashes and can reduce compile time.
Comment: It's nice (certainly simpler), but that's not standard C++
Comment: yes, that is the only drawback. For me, the advantages outweigh this.
Answer: When I learnt c++ our professor said, the first two lines that you write in c++ class should always be #ifndef followed by #define. This prevents multiple definitions in header files
http://www.fredosaurus.com/notes-cpp/preprocessor/ifdef.html


UpdateResource API - External component has thrown an exception

Question: I'm trying to change a file version of one of my exe files, and for some reason I receive an error that the memory I'm trying to write into is protected and then I receive a message that the external component thrown an exception. I'm not sure what I am doing wrong here, any help would be appreciated.
   Public Sub ChangeVersion(ByVal FILE As String)
            Dim handle As IntPtr = BeginUpdateResource(FILE, False)
            Dim ver As String = "188.8.131.52"
            UpdateResource(handle, "RT_VERSION", "FILEVERSION", MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), ver, ver.Length)
            EndUpdateResource(handle, False)
   End Sub

Answer: The Using Resources sample, linked from the UpdateResource documentation, says you have to use FindResource, LoadResource and LockResource before you can call BeginUpdateResource and UpdateResource.

Use the LoadLibrary function to load the executable file Hand.exe.
Use the FindResource and LoadResource functions to locate and load the dialog box resource.
Use the LockResource function to retrieve a pointer to the dialog box resource data.
Use the BeginUpdateResource function to open an update handle to Foot.exe.
Use the UpdateResource function to copy the dialog box resource from Hand.exe to Foot.exe.
Use the EndUpdateResource function to complete the update.

(You're also not doing any checking of return values before calling the next function. If BeginUpdateResource fails for example (because you haven't called LockResource first, for instance), it returns NULL or zero, and if it does you shouldn't be calling UpdateResource. UpdateResource returns a BOOL that indicates if it was successful or not, and if it wasn't you shouldn't be calling EndUpdateResource. ALWAYS check the return values of API calls - they exist for a reason, and ignoring them is a bad idea.)
Comment: Agreed about always checking error codes. Since he's P/Invoking these functions from VB.NET, he needs to make sure that the `SetLastError` attribute is set to `true` in the P/Invoke definition. Then he can use `Marshal.GetLastWin32Error` to retrieve the error code in the event that the function fails.


How can I make a spectator mode in Bedrock Edition via Commands?

Question: Java has a game mode titled "Spectator" where one view the world as a ghost-like form, going through walls and able to "possess" players' bodies and see what they would see on their screen, without the person being able to tell.
Can the "Spectate Player" part be obtained in Bedrock Edition?
Answer: What's Possible
I will share how to make the spectate player part via commands, because a usable, non-nuisance no-clipping through blocks is not (that I am aware) possible in Vanilla Minecraft Bedrock. This will not show how to use a system such as item-dropping to change the player you spectate, as you will have to do that part yourself.
Real Quick
I will be using the selector
@a[tag="viewed"]

and referring to them as viewed for the player being watched, and
@a[tag="spectator"]

for the spectator, which I will refer to as spectator.
Use the /tag command to apply and remove tags from entities.
Approach
You will teleport an invisible player behind the spectating player, depending on the viewed's looking position. How do we know someone's look position?
^ ^ ^

These carets each mean something. It is kinda confusing, but for this tutorial we focus on that last caret. ^ ^ ^2 refers to the block in front of where the player's head is looking, 2 blocks in front of the head. This means that if we use a negative value (i.e. ^ ^ ^-3) we get the blocks behind the player's looking location.
(Do not confuse this with tildes ~! They are separate, as tildes just return the block the player's legs are in.)
How
We will use /execute along with /tp. Make a repeating command block; grab a repeating command block by entering this command into your chat window:
/give @s repeating_command_block

Put this command into it:
execute @a[tag="viewed"] ~ ~ ~ tp @a[tag="spectator"] ^ ^ ^-4 facing ^ ^ ^1 false

What did we do? Well first, we used the execute command for the sole purpose of getting access to those carets (^ ^ ^) we use for look location. We are getting the look location of the player with tag viewed. (Remember, you can change the selector as you desire). We put -4 on the end to get the 4 blocks behind that player's look direction. You can adjust this if you want to, just use a negative number. The facing and the more carets just tell us where our spectator should be looking, which is right where the viewed is looking. The false is to prevent the hazard test (you don't need to understand this).
The reason we must use a negative value is because if the spectator is in front of the viewed, the viewed wouldn't be able to place blocks, open chests, break blocks, as they would always hit the spectator!
When the Person starts Spectating
Before that person starts spectating, you need to use these commands on them, you could do this when you first give them the spectator tag.
effect @a[tag="spectator"] invisibility 99999 255 true

Make them invisible for a while, and show no particles.
gamemode @a[tag="spectator"] a

You don't want them breaking/placing blocks, do you?
effect @a[tag="spectator"] resistance 99999 255 true

Make them immune to damage.
effect @a[tag="spectator"] effect weakness 99999 255 true

So they can't hit entities, they won't even deal any knockback or be able to break armor stands!
Also make sure they do not have a bow, armor, milk, potions etc., if you need to be sure use /clear.
You're Ready!
Once you have a system in place for who is being viewed, spectated, and the effects are given accordingly, set the repeating command block's Needs Redstone select box to Always Active.
Limitations

If the viewed looks up, the spectator will be tped underground and
although they cannot suffocate, they will be looking at dirt or whatever
block until you level your vision.
If the spectator finds a way to block someone attacking the viewed, they could act as a human shield, this is why I like to teleport them back a fair amount, that way its harder to block PVP.
Answer: As a follow up to @Penguin
If you have the world on Education Edition you can run a command to allow the user to fly.
You can do: /ability @p mayfly true
To get them out of fly mode you first must do /ability @o mayfly false. Then you must kill them because just taking away the ability will not take them out of fly.
Also if you would want to mute the user in chat to prevent them for letting other users know what is going on you can do: /ability @p mute true
To unmute them, simply do /ability @p mute false
Comment: Do remember that once a player is flying the only way to force them to stop is killing them.
Comment: Oh. I should edit that.
Comment: taking it away doesn't do anything if they do not manually stop flying. They can still fly. The only thing removing the ability does is if they stop flying then try to fly again, they will not be a able to fly again. The only way I know to work around this is /kill
Comment: Oh. Well thanks for letting me know!


How to create a Fallback answer when user doesn't provide a parameter in the right format in Dialogflow

Question: I have an intent in Dialogflow where user needs to provide a parameter in a specific format of a entity that I have created (entity has a regex format). I would like to have a fallback answer ifn user provide the paramater in the wrong format. I've tried to create a followup fallback for the intent but the fallback intent is not triggered.
What I'm doing wrongthis is the parameter user need to enter which I want to have a fallback message if it's not in the right format
Comment: Is see that you made the entity required and added a prompt to ask the user another question in case they say nothing at all, does that work?
Comment: Hi Jordi, Yes, the bot ask the user to provide the order number but I want the bot to reply with something like "The format entered is not correct..." in case he provides the order number in the wrong format.
Answer: Okay, as you mentioned in the comments, you already have a prompt set for when the user doesn't mention an order number at all. If the user inputs an ordernumber and it doesn't match the regex, Dialogflow will not detect a matching entity and because of that no entity is found in the user input. So even if just 1 character is off, it is handled in the same way as it not being mentioned at all.
Depending on the product that you use you might have a second option if you include a webhook. I'm not completely sure if Dialogflow supports this, but if your product numbers consist  of a consistent structure, for example AB0000, you could try and create a regex that looks for a entity that consist of 2 letters and 4 numbers. This will then be detected as valid even when someone mentions ZY9999.
In your webhook you can then keep a collection of regexes that are considered valid productnumbers. You then run the code ZY9999 against those regexes and if the regexes say it is valid you know the product is valid. If those product regexes say its invalid then you create a new response telling the user that they need to input something else. It will be difficult to tell what exactly is wrong with the number, but its better than repeating "Did you enter a number?" over and over again.


ERR_CONNECTION_REFUSED And Domain refused to connect

Question: I'm trying to connect WordPress instance on google cloud with the custom domain but I'm having this error
<code>This site can't be reachedquotivy.com refused to connect.
Try:

Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_REFUSED
</code>
What I found it wired is that the domain is working on Tor browser and not working on Chrome and Safari, and I tried to take an online screenshot from it and it's working & I ping the domain and seems working too! not so sure what to debug or do to fix this bug!
This is a sample URL: https://quotivy.com/rumi/when-the-world-pushes-you-to-your-knees/
How it looks like on my browsers:

Custome DNS on my google cloud
Comment: I've checked you domain and found no issues at all. GCP Firewall and GCP Cloud DNS were configured correctly. Do you still have this issue? Have you tried to check from different PC or mobile phone?
Comment: Most likely you did not wait for DNS to propagate. This can take a few hours after creating or changing the DNS resource records.
Comment: If Domain, DNS, and virtual hosts are set up correctly and it still shows this error then try checking file permissions.
Answer: If you have moved the site recently then check in your database (either domain.com/phpmyadmin or SSH if Cloud SQL) for references to the old domain and update to the new domain. This includes moving from http to https
In GCP Compute Engine VM Instance settings, make sure to allow http and allow https traffic. You may want to assign a static IP in GCP Console > VPC Network > External IP addresses
Lastly you may need to update etc/apache2/sites-enabled/000-default.conf to make sure your servername matches your WordPress domain name


Filter tags in LogCat (in Android Eclipse Plug-In)

Question: There is a TextField "Filter" below the LogCat output. However, it seems to filter only the Message-column. Id like to filter Tags also. Because there are my class names.
How can I achieve it?
Comment: I am not able to test the given answer(s) anymore, since I stopped developing Android Apps. Please suggest if I should mark an answer done, if you have tested it and matches the requirements of my question.
Answer: There's a button that looks like a green + in the upper right of the log cat window, if you mouse over it says "Create Filter" in the popup from that you can filter by log tag. It creates a new tab in log cat with the filter name you specified. Then all of the output of that tag will go to that tab and not the "Log" tab.
Comment: Can't use wildcards like "com.mynamespace.*" ;( But thanks for showing me that function ;)
Comment: I'd really like to be able to use wildcards in here too.
Answer: In Eclipse, if I would like to exclude those annoying Choreographer messages,I write this filter in the logcat filter TextField : tag:^(?!Choreographer).*$ and it excludes all messages which tag starts with the text Choreographer
If you want multiple exclusions : tag:^(?!Choreographer|dalvikvm-heap|Trace).*$
Answer: The Log tag field accepts Java regular expressions, so try this:
^TAG_A$|^TAG_B$

which matches exactly those tags. You can go crazy with complicated regular expressions, if that's your idea of fun.
Comment: Woah great, I never noticed that. Welcome to StackOverflow!
Comment: This seems to be working only in ADT, since if I use it programatically (Runtime.getRuntime().exec("logcat [] ... [] ...")), it doesn't work.
Answer: Old question, but still relevant, and didn't see this answer among the answers here.
To filter by multiple columns in logcat textfield, simply use a space between regular expressions, and the column title in lower case followed by : to assign the regex to that column instead of the default "text:"
for example:
tag:wif text:event

a space '' is used as an AND argument.
a single '|' without space is an OR.
Regarding one of the comments I've seen here - There is no realy need for a wildcard, since it is automatically applied before and after the filter text.
If you don't want wildcard, you can use regular expression syntax to restrict the string.
for example: ^starswith or fullword$
TIP: if you want to match a space character or a tab in your output, just type in: \s at the desired place.
Comment: thanks for the tip with the whitespace \s that is exactly what I was looking for
Answer: A sample from the ADB manual:

adb logcat ActivityManager:I MyApp:D *:S

The *:S is vital as this would suppress other tags different than the ones specified by us.
Unfortunately, one can't use wildcards in the names, i.e.:

adb logcat ActivityManager:I MyApp*:D *:S

wouldn't work.
Answer: When filtering, you must use no whitespace after 'tag:' and all is case sensitive. For example:
tag:MIRKO

and not
TAG: mirko

Answer: Run logcat in a shell and pipe it through grep.
There's probably even a way to do execute this from an eclipse window that would capture the output.
Comment: adb logcat | grep someNameOfInterest    you can also use the -i flag to make it case insensitive.  Oh, and you have to _have_ grep, ie, be on linux or unix or cygwin or msys or have a grep executable for your OS.
Comment: Could you provide the commands how to pipe it in the shell? Sorry, I grew up with OS using GUI and have no clue on those things...
Answer: this should be the same across all platforms, but I'm specifically doing this on Mac Snow leopard, helios....
with the latest eclipse and android plugin, go to window -> show view -> android -> logcat
then in the upper right corner of the view there are filter buttons : "V" "D" "I" "W" "E" then a + edit and -
click on the + and type in your tag, or pid
enjoy filtered logCat
Answer: In LogCat's search textbox, you will see the hint text "Search for messages, Accepts Java regexes, Prefix with pid:, app:, tag: or text: to limit scope."
So just type in tag:YOUR_TAG_NAME


Do I have enough amperage in my service?

Question: I'm renovating a small house and want to install an electric tankless water heater to save space. A local store offers one that requires 2 50-amp breakers; the house has 200-amp service. The house also has:

an oven (40 amp breaker)
maybe a stackable washer/dryer unit (30 amp)
heat pump (2 ton - not yet installed, I'm guessing needs 25 amp breaker)

Will the 200-amp service be enough to handle all this?
Comment: What about freezer or refrig, washer, dryer, toaster, toaster oven, other kitchen appliances?
Comment: How many square feet is this house, and how many breakers do you have to turn off to turn all the kitchen counter receptacles off? Also, what is the actual kW rating on the tankless heater you want, and who's your electric utility?  Finally, can you post a photo of your breaker panel please? (Door open, but cover still on)
Comment: There will be a dishwasher, refrigerator, microwave. The homeowner will add their own things to the house for sure. The heater is a Marey ECO180, drawing 18kW. We are on Dominion Power in VA.
Comment: @GregH can you post photos of the breaker panel then, please?
Comment: With the heat pump, how is emergency heat going to be handled? (When the weather is too cold for the heat pump to function).  Typical midwestern house that is two 70A circuits of electric strip heaters.
Answer: You're getting very close to the limit. You're up to 170 Amps without the kitchen appliances and recreational devices. The tankless water heater is a large load, takes about 4 times the load of a regular tank heater.
Comment: what about doing the laundry and baking a cake on a hot day or on a very cold day?
Comment: Seems like 195 to me.  100+40+30+25?
Comment: @Joe That's a 240 volt  circuit  Two single 50 Amp breakers or 1 double pole 50 Amp. 50 amps either way.  His oven is a double 40 for 240 Volts, he could use two single 40's.  The current alternates between the two breakers so each one has to handle the max.
Comment: @jsotola   The burners aren't being used and all these items will be cycling on and off.. save me a piece of the cake.
Comment: Ah, gotcha - thanks for explaining !
Comment: @Joe  New information from OP. 18kw heater will need 75 amps  so instructions call for 2- 50 Amp  double pole breakers.
Comment: If conventional heat pump (not a mini-split), you will also need to account for EM heat in the indoor air handler (30-40 amps at 240?).    But on other topic:  Very unlikely everything would be on full at the same time. EX: even if all burners and the over were on at the same time, it wouldn't draw a full 40 amps.
Answer: The decision to ask for a "load calclation" in order to get a permit is a local authorities prerogative.
A load calc includes various loads like heating, laundries, kitchen, bathrooms, square footage and others and it is hard to guess if a 200A service would be adequate.


How can I allow a snap application to execute a custom script

Question: I have a Nextcloud server that was installed via snap (Github page). It has run quite well so far, but now I would like to start using Nextcloud's workflow feature to run a script when a new mkv file is created (Very simple script that executes ffmpeg and just converts the file from an mkv container to mp4).
However this is where my knowledge of snap ends. The snap has no access to the script I've created, and also doesn't have permissions to execute ffmpeg. Is there a way to give snap the access it needs to run ffmpeg and my script?
Comment: AFAIK, the developer is responsible for doing this by building the snap with the classical packaging. Normal packaging mode completely sandboxes the program, so it can't execute anything on the machine.
Comment: [Rant] My experience is that snap incapacitates you.[/Rant] Try to install it without snap.
Comment: Read the errors in syslog: Is this a permission-denied error due to the *location*, or due to the *activity*, or something else?
Comment: A snap package (that is not `classic`) is separate from the rest of the applications of your system. Therefore, the `ffmpeg` executable is not accessible from within the snap.

Just like GIMP plugins, you can run plugins from within the GIMP snap, but the plugins need to be statically linked because they cannot access any of the libraries of the system.
Comment: @kanehekili Ugh.  This really ticks me off.  Why does Ubuntu *insist* on having so many packages as snaps when I wind up being unable to do the things I need to do, *and* then am asked to jump through a bunch of hoops to get my work done.  This is *not* user friendly, and even as an "expert" I find this tiresome and almost too difficult.
Answer: Based on everyone's comments. It sounds like in order to give snap permission to execute ffmpeg and my script, I would either need to A) redo my implementation as a "writable snap" per the nextcloud-snap documentation, or B) stop using snap altogether (I'm not tied to snap, but I'm also not interested in redoing my nextcloud installation at this time). So I can't use my script through nextcloud's workflow feature as-implemented. However, I did find a workaround for my scenario. My script just needs access to run ffmpeg on my stored nextcloud data, and the snap does allow me to designate an external data directory where my nextcloud data can be stored. So I did the following

I copied my data to an external directory, pointed snap to use that data directory per These instructions

Set up an incron job to execute my script when a new file is uploaded via nextcloud. My incrontab entry looks like this /mnt/nextcloud/data/directory/ IN_ATTRIB ~/bin/my_script.sh $@$#

As the final step in my script, I instruct nextcloud to scan for new files in my destination directory by running /snap/bin/nextcloud.occ files:scan --path="username/videos/converted (note: path is relative to the nextcloud username)
Comment: **Without snap** you could've installed it [this](https://markus-blog.de/index.php/2021/07/08/how-to-install-nextcloud-hub-22-on-ubuntu-20-04-with-postgresql-13-php8-0-fpm-apache2-and-http-2/) way.


How to write a SQL query that will Count two types of values in the Same Column of one Table?

Question: I have a table name 'demo' with fields id(PK), user and item with below data:
id  user item
==  ==== =====
1   anuj    A
2   anuj    A
3   anuj    A
4   anuj    B
5   anuj    B
6   anuj    B
7   patil   A
8   patil   A
9   patil   A
10  rahul   B
11  rahul   B
12  tanmay  A
13  tanmay  A

Now I want to write a query which will give me result like this:
User   Count of A    Count of B
====   ==========    ===========
anuj   3             3
patil  3             0
rahul  0             2
tanmay 2             0

Basically is this possible?  I have tried but not successful.
Answer: Use Conditional Aggregate
Case statement inside the count aggregate will produce either 1 or NULL. Since the NULL values are eliminated by aggregate functions the count will consider the value to count only when condition is satisfied
select User,
      Count(case when item = 'A' then 1 end) as `Count of A`,
      Count(case when item = 'B' then 1 end) as `Count of B`
From yourtable
Group by User

Comment: Thanks for such a quick help..  But above query is giving Syntax error.
Comment: @Raj - There was a extra comma. Updated check now
Comment: Great!! Worked like a charm!  Thanks a lot... :)
Comment: Just wanted to know will this work in **sqlite** also?
Answer: select
user,
sum(if(item="A",1,0)) as "count of A",
sum(if(item="B",1,0)) as "count of B"
from
demo
group by user;


How to fix the "SDK directory does not exist"?

Question: So I'm trying to get my react native software to run and it's popping up with an error saying The SDK directory 'C:\Program Files\Android\Android studio; ' does not exist. How can I fix this?
Comment: Install Android studio. To do react native setup with Android studio you can refer: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment
Comment: Possible duplicate of [React Native android build failed. SDK location not found](https://stackoverflow.com/questions/32634352/react-native-android-build-failed-sdk-location-not-found)
Answer: Lookup 2 places:

Possible duplicate of your question
React Native start Guide

If you installed all necessary things listed in guide just do:
react-native init YOURPROJECTNAME
and after build add local.properties file in android folder of your app.
It should contain line: sdk.dir = C:\\Users\\USERNAME\\AppData\\Local\\Android\\sdk


Textbox is empty after filling with javascript

Question: I create textbox by this code:

    <asp:TextBox TextMode="MultiLine" runat="server" ID="selectText" ReadOnly="true" Width="560px" Height="50px"></asp:TextBox>

I fill it by this code:
elSelText.value = elSelText.value.substr(0, position) + chosenoption2.value + " ";

And then i try to send value in textbox to server, but it's empty!
protected void btnUseSelectClick(object sender, EventArgs e)
    {
        sourceDetails.SelectCommand += " and " + selectText.Text;
        Session["FilterSelectCommand"] = sourceDetails.SelectCommand;
        tableResults.DataBind();
    }

On the advice I added AutoPostBack="true":

    <asp:TextBox TextMode="MultiLine" runat="server" AutoPostBack="true" ID="selectText" ReadOnly="true" Width="560px" Height="50px"></asp:TextBox>

but it didn't help
Comment: Just a guess, but does removing `ReadOnly="true"` make a difference?
Comment: @Doc I think that's what `protected void btnUseSelectClick() { }` is for
Comment: The value of the textbox is empty because the server doesn't know it has changed.  The server needs to be notified somehow.  Typically this is done with either a full or partial postback.
Comment: @DStanley I don't think it would. The value wouldn't be submitted if it were `disabled`, but `readonly` shouldn't make a difference. I could be wrong though
Comment: @DStanley, you advice helped me but what if it important to stay textbox readonly?
Answer: Although it's news to me, it seems that the ReadOnly property doesn't keep track of changes from the client. If you want the "readonly" functionality but still get the value on the server, put the following in your Page_Load method:
selectText.Attributes.Add("readonly", "readonly");

And remove the ReadOnly (and AutoPostBack) property in the <asp:TextBox> tag.
( From: http://aspadvice.com/blogs/joteke/archive/2006/04/12/16409.aspx and http://forums.asp.net/t/1467081.aspx - it was a fairly quick find with Google)
Answer: Maybe a problems of ViewState. Try add the check of Page.IsPostBack in the page load event like this:
If(!Page.IsPostBack)
{
    // Data binding for the first call
}

Answer: I believe this is due to ReadOnly: ASP.Net registers which controls are readonly when sending you the page.
The value of these controls is discarded when posting back, and it is regotten (from ViewState I believe).
A workaround for this would be not setting readonly="true" on the aspx page, but setting it with $(document).ready(your_function_here();) (if you're using jQuery) or with the body onLoad event.


Stuck at Ubuntu login screen

Question: When I try to log in to my account the screen turns black for a second then goes back to the login screen. Apparently this is a fairly common problem but nothing I've tried from past questions on this site has worked so far.
What I've tried:
Using gdm instead of lightdm
sudo apt-get upgrade and sudo apt-get update
Restoring .bashrc to its default version
chown username:username .Xauthority
Reinstalling ubuntu-desktop
Creating a new login account (it just does the same thing)
Things that may or may not be helpful:
When I Cntl+Alt+F2 and do the textual login, I get a bunch of errors:
<code>Command 'lesspipe' is available in the following places
* /bin/lesspipe
* usr/bin/lesspipe
The command could not be located because 'usr/bin:/bin' is not included in the
PATH environment variable.
lesspipe: command not found
Command 'dircolors' is available in '/usr/bin/dircolors'
The command could not be located because '/usr/bin' is not included in the PATH
environment variable.
dircolors: command not found
Command 'uname' is available in '/bin/uname/'
The command could not be located because '/bin' is not included in the PATH
environment variable.
uname: command not found
-bash: [: =: unary operator expected
Command 'sed' is available in '/bin/sed'
The command could not be located because '/bin' is not included in the PATH
environment variable.
sed: command not found
Command 'ls' is available in '/bin/ls'
The command could not be located because '/bin' is not included in the PATH
environment variable.
ls: command not found
</code>
I cannot use most of the commands like ls and sudo until I export /bin and /usr/bin to the path.
When I do "ls -ltr" in /var/log, the last log files modified are:
syslog
wtmp
auth.log
lastlog
Xorg.0.log
lightdm (directory)
Xorg.0.log.old
I couldn't find any obvious error messages in any of them.
Can anyone help me to diagnose the problem?
Edit: Here is auth.log:
<code>    Jun 21 13:36:25 melissa-ThinkPad-T430 sshd[551]: Server listening on 0.0.0.0 port 22.
Jun 21 13:36:25 melissa-ThinkPad-T430 sshd[551]: Server listening on :: port 22.
Jun 21 13:36:35 melissa-ThinkPad-T430 lightdm: pam_unix(lightdm:session): session opened for user lightdm by (uid=0)
Jun 21 13:36:35 melissa-ThinkPad-T430 lightdm: pam_ck_connector(lightdm:session): nox11 mode, ignoring PAM_TTY :0
Jun 21 13:36:42 melissa-ThinkPad-T430 lightdm: pam_succeed_if(lightdm:auth): requirement "user ingroup nopasswdlogin" not met by user "melissa"
Jun 21 13:36:43 melissa-ThinkPad-T430 dbus[827]: [system] Rejected send message, 2 matched rules; type="method_call", sender=":1.32" (uid=104 pid=1715 comm="/usr/lib/indicator-datetime/indicator-datetime-ser") interface="org.freedesktop.DBus.Properties" member="GetAll" error name="(unset)" requested_reply="0" destination=":1.16" (uid=0 pid=1233 comm="/usr/sbin/console-kit-daemon --no-daemon ")
Jun 21 13:36:47 melissa-ThinkPad-T430 dbus[827]: [system] Rejected send message, 2 matched rules; type="method_call", sender=":1.40" (uid=104 pid=1831 comm="/usr/lib/indicator-datetime/indicator-datetime-ser") interface="org.freedesktop.DBus.Properties" member="GetAll" error name="(unset)" requested_reply="0" destination=":1.16" (uid=0 pid=1233 comm="/usr/sbin/console-kit-daemon --no-daemon ")
Jun 21 13:36:50 melissa-ThinkPad-T430 lightdm: pam_unix(lightdm:session): session closed for user lightdm
Jun 21 13:36:50 melissa-ThinkPad-T430 lightdm: pam_unix(lightdm:session): session opened for user melissa by (uid=0)
Jun 21 13:36:50 melissa-ThinkPad-T430 lightdm: pam_ck_connector(lightdm:session): nox11 mode, ignoring PAM_TTY :0
Jun 21 13:36:50 melissa-ThinkPad-T430 lightdm: pam_unix(lightdm:session): session closed for user melissa
Jun 21 13:36:51 melissa-ThinkPad-T430 lightdm: pam_unix(lightdm:session): session opened for user lightdm by (uid=0)
Jun 21 13:36:51 melissa-ThinkPad-T430 lightdm: pam_ck_connector(lightdm:session): nox11 mode, ignoring PAM_TTY :0
Jun 21 13:36:51 melissa-ThinkPad-T430 lightdm: pam_succeed_if(lightdm:auth): requirement "user ingroup nopasswdlogin" not met by user "melissa"
Jun 21 13:36:51 melissa-ThinkPad-T430 dbus[827]: [system] Rejected send message, 2 matched rules; type="method_call", sender=":1.47" (uid=104 pid=2010 comm="/usr/lib/indicator-datetime/indicator-datetime-ser") interface="org.freedesktop.DBus.Properties" member="GetAll" error name="(unset)" requested_reply="0" destination=":1.16" (uid=0 pid=1233 comm="/usr/sbin/console-kit-daemon --no-daemon ")
Jun 21 13:37:01 melissa-ThinkPad-T430 login[1034]: pam_unix(login:session): session opened for user melissa by LOGIN(uid=0)
Jun 21 13:38:30 melissa-ThinkPad-T430 sudo:  melissa : TTY=tty2 ; PWD=/home/melissa ; USER=root ; COMMAND=/usr/bin/apt-get install pastebinit
Jun 21 13:38:30 melissa-ThinkPad-T430 sudo: pam_unix(sudo:session): session opened for user root by melissa(uid=1000)
Jun 21 13:38:32 melissa-ThinkPad-T430 sudo: pam_unix(sudo:session): session closed for user root
Jun 21 13:38:51 melissa-ThinkPad-T430 sudo:  melissa : TTY=tty2 ; PWD=/home/melissa ; USER=root ; COMMAND=/usr/bin/apt-get -f install pastebinit
Jun 21 13:38:51 melissa-ThinkPad-T430 sudo: pam_unix(sudo:session): session opened for user root by melissa(uid=1000)
Jun 21 13:38:52 melissa-ThinkPad-T430 sudo: pam_unix(sudo:session): session closed for user root
</code>
Here is lightdm.log:
<code>[+0.00s] DEBUG: Logging to /var/log/lightdm/lightdm.log
[+0.00s] DEBUG: Starting Light Display Manager 1.2.3, UID=0 PID=1085
[+0.00s] DEBUG: Loading configuration from /etc/lightdm/lightdm.conf
[+0.00s] DEBUG: Using D-Bus name org.freedesktop.DisplayManager
[+0.00s] DEBUG: Registered seat module xlocal
[+0.00s] DEBUG: Registered seat module xremote
[+0.00s] DEBUG: Adding default seat
[+0.00s] DEBUG: Starting seat
[+0.00s] DEBUG: Starting new display for greeter
[+0.00s] DEBUG: Starting local X display
[+0.00s] DEBUG: X server :0 will replace Plymouth
[+0.02s] DEBUG: Using VT 7
[+0.02s] DEBUG: Activating VT 7
[+0.02s] DEBUG: Logging to /var/log/lightdm/x-0.log
[+0.03s] DEBUG: Writing X server authority to /var/run/lightdm/root/:0
[+0.03s] DEBUG: Launching X Server
[+0.03s] DEBUG: Launching process 1094: /usr/bin/X :0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch -background none
[+0.03s] DEBUG: Waiting for ready signal from X server :0
[+0.03s] DEBUG: Acquired bus name org.freedesktop.DisplayManager
[+0.03s] DEBUG: Registering seat with bus path /org/freedesktop/DisplayManager/Seat0
[+3.55s] DEBUG: Got signal 10 from process 1094
[+3.55s] DEBUG: Got signal from X server :0
[+3.55s] DEBUG: Stopping Plymouth, X server is ready
[+3.57s] DEBUG: Connecting to XServer :0
[+3.58s] DEBUG: Starting greeter
[+3.58s] DEBUG: Started session 1182 with service 'lightdm', username 'lightdm'
[+5.24s] DEBUG: Session 1182 authentication complete with return value 0: Success
[+5.24s] DEBUG: Greeter authorized
[+5.24s] DEBUG: Logging to /var/log/lightdm/x-0-greeter.log
[+5.30s] DEBUG: Session 1182 running command /usr/lib/lightdm/lightdm-greeter-session /usr/sbin/unity-greeter
[+8.79s] DEBUG: Greeter connected version=1.2.3
[+8.79s] DEBUG: Greeter connected, display is ready
[+8.79s] DEBUG: New display ready, switching to it
[+8.79s] DEBUG: Activating VT 7
[+13.26s] DEBUG: Greeter start authentication for melissa
[+13.26s] DEBUG: Started session 1708 with service 'lightdm', username 'melissa'
[+13.28s] DEBUG: Session 1708 got 1 message(s) from PAM
[+13.28s] DEBUG: Prompt greeter with 1 message(s)
[+20.58s] DEBUG: Continue authentication
[+20.59s] DEBUG: Session 1708 authentication complete with return value 0: Success
[+20.59s] DEBUG: Authenticate result for user melissa: Success
[+20.59s] DEBUG: User melissa authorized
[+20.59s] DEBUG: Greeter requests session ubuntu-2d
[+20.59s] DEBUG: Using session ubuntu-2d
[+20.59s] DEBUG: Stopping greeter
[+20.59s] DEBUG: Session 1182: Sending SIGTERM
[+20.70s] DEBUG: Greeter closed communication channel
[+20.70s] DEBUG: Session 1182 exited with return value 0
[+20.70s] DEBUG: Greeter quit
[+20.71s] DEBUG: Dropping privileges to uid 1000
[+20.71s] DEBUG: Restoring privileges
[+20.71s] DEBUG: Dropping privileges to uid 1000
[+20.71s] DEBUG: Writing /home/melissa/.dmrc
[+20.75s] DEBUG: Restoring privileges
[+20.82s] DEBUG: Starting session ubuntu-2d as user melissa
[+20.82s] DEBUG: Session 1708 running command /usr/sbin/lightdm-session gnome-session --session=ubuntu-2d
[+20.85s] DEBUG: Registering session with bus path /org/freedesktop/DisplayManager/Session0
[+21.07s] DEBUG: Session 1708 exited with return value 0
[+21.07s] DEBUG: User session quit
[+21.07s] DEBUG: Stopping display
[+21.07s] DEBUG: Sending signal 15 to process 1094
[+21.22s] DEBUG: Process 1094 exited with return value 0
[+21.22s] DEBUG: X server stopped
[+21.22s] DEBUG: Removing X server authority /var/run/lightdm/root/:0
[+21.22s] DEBUG: Releasing VT 7
[+21.22s] DEBUG: Display server stopped
[+21.22s] DEBUG: Display stopped
[+21.22s] DEBUG: Active display stopped, switching to greeter
[+21.22s] DEBUG: Switching to greeter
[+21.22s] DEBUG: Starting new display for greeter
[+21.22s] DEBUG: Starting local X display
[+21.22s] DEBUG: Using VT 7
[+21.22s] DEBUG: Logging to /var/log/lightdm/x-0.log
[+21.22s] DEBUG: Writing X server authority to /var/run/lightdm/root/:0
[+21.22s] DEBUG: Launching X Server
[+21.22s] DEBUG: Launching process 1919: /usr/bin/X :0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch
[+21.22s] DEBUG: Waiting for ready signal from X server :0
[+21.29s] DEBUG: Got signal 10 from process 1919
[+21.29s] DEBUG: Got signal from X server :0
[+21.29s] DEBUG: Connecting to XServer :0
[+21.29s] DEBUG: Starting greeter
[+21.29s] DEBUG: Started session 1924 with service 'lightdm', username 'lightdm'
[+21.30s] DEBUG: Session 1924 authentication complete with return value 0: Success
[+21.30s] DEBUG: Greeter authorized
[+21.30s] DEBUG: Logging to /var/log/lightdm/x-0-greeter.log
[+21.30s] DEBUG: Session 1924 running command /usr/lib/lightdm/lightdm-greeter-session /usr/sbin/unity-greeter
[+21.39s] DEBUG: Greeter connected version=1.2.3
[+21.39s] DEBUG: Greeter connected, display is ready
[+21.39s] DEBUG: New display ready, switching to it
[+21.39s] DEBUG: Activating VT 7
[+21.39s] DEBUG: Stopping greeter display being switched from
[+21.63s] DEBUG: Greeter start authentication for melissa
[+21.63s] DEBUG: Started session 1998 with service 'lightdm', username 'melissa'
[+21.63s] DEBUG: Session 1998 got 1 message(s) from PAM
[+21.63s] DEBUG: Prompt greeter with 1 message(s)
</code>
Comment: Send us auth log and lightdm log
Comment: I edited the post with auth.log and lightdm.log.
Comment: Try to use different desktop envrinoment. Instead of GNOME 2D, use Unity, or something like this.
Comment: What happens when you try to log in using the Guest account?
Answer: Please press Ctrl+Alt+F3 buttons and login with your username and password.
In the login prompt give: startx
You will be getting a Graphical user interface now.
Then disable automatic login for your account. Then create new user account,if you need. Keep automatic login disabled.
This may be the temporary solution. But this way you can make your os usable.

Stuck at Ubuntu login screen


What makes a question off topic?

Question: What should determine if a question is marked off topic on this site and what should happen to these questions?
Comment: Please read the Tour: https://cogsci.stackexchange.com/tour . There, everything you need to know is briefly described. Funny thing, this question is also off-topic, kinda meta haha. It will probably be migrated to meta.cogsci.stackexchange,com
Answer: As a new user, you have unfortunately seen some of your posts been scrutinized, put on hold, or even deleted altogether.
At the time of this writing you haven't received any badges yet on the main site, and for a struggling new user like you it's definitely time to earn the informed badge. All you have to do is go through a quick tour.
It's going to be especially helpful, in the light of your specific question here, to digest what questions are on topic here in the help center. However, given that your answers were not received well either, please do visit the help section on answering.
We really welcome new users, but a scientific stack like this does require users to fit in the community's conventions such as, but not limited to:
Questions

Be specific;
Research before asking;
Ask valid questions, avoid requests for other users' opinions;
Allow potential answers to be concise and not ask for wiki-type information;
Ask questions interesting for the community at large.

Answers

Write science, not personal opinions or anecdotal stories;
Cite credible references or sources;
Elaborate on the key points and avoid one-liners.

What makes a question off topic?


Convert "YYYYWW" into month (SSRS)

Question: I am creating a report and would like to retrieve data based on a date field (string) in the format YYYYWW. I want to filter the data so I retrieve the current month, previous month, the month before that and older values - using 4 different datasets.
For example:
201547 = November 2015
How do I create a calculated member which converts a string into the month name and year? I would like to use this value to filter out the data from the cube. Is there any other way of doing this?
:]1
Comment: Be aware that "week" does not map directly to "month" in a consistent way. How are you going to handle weeks that are split over two months e.g. Monday is the 30th June, Tuesday is 1st July - what month are you going to convert that week to? You'll need to establish some business rules for this. You'll also need to know when "week 1" starts - the week numbering may be linked to *financial year*, not calendar year.
Comment: Thank you so much for the fast response!! I'll let you guys know how it turned out tomorrow.
Answer: Using a combination of the resources found out on the internet you can find the information you require.
First you need to find the first day of the first week of the year.  This has already been determined by this answer as
DateAdd("d",
    (-1) * (CInt(New DateTime(Year(Now), 1, 1).DayOfWeek) +
    IIf(CInt(New DateTime(Year(Now), 1, 1).DayOfWeek) < DayOfWeek.Monday,
        7,
        0)
    ) + 1,
    New DateTime(Year(Now), 1, 1))

This needs to be adapted for any year - not just the current one by finding the year from the string as follows
CInt(Left(Parameters!myDate.Value,4))

Now, as noted in this resource you can use a DateAdd to add the number of weeks of the year you have entered to the first date of the year
=(DateAdd(DateInterval.WeekOfYear,
    CInt(Right(Parameters!myDate.Value,2))-1,
    <<FIRST_DAY_OF_YEAR>>)

You then want to get the month name of the month of this date, using Month and MonthName.  Smashing it all together would result in the following
=MonthName(Month(DateAdd(DateInterval.WeekOfYear,
    CInt(Right(Parameters!myDate.Value,2))-1,
    DateAdd("d",
        (-1) * (CInt(New DateTime(CInt(Left(Parameters!myDate.Value,4)), 1, 1).DayOfWeek) +
        IIf(CInt(New DateTime(CInt(Left(Parameters!myDate.Value,4)), 1, 1).DayOfWeek) < DayOfWeek.Monday,
            7,
            0)
        ) + 1,
        New DateTime(CInt(Left(Parameters!myDate.Value,4)), 1, 1))
    )))

This will get a Textual value of the month for the interval
Create a new placeholder in the same textbox and then repeat the above for finding the year
=Year(DateAdd(DateInterval.WeekOfYear, ...

(Remember to remove the last brace otherwise you'll get a End of Statement expected error.)
This shoud give what you require, so
201501 = December 2014
201547 = November 2015
201553 = December 2015
201622 = May 2016

Let me know if this helps, or if you have further questions
Comment: This solution also works great! I would definitely use this as an alternative to the MDX option above.
Answer: Try adding a calculated field and set it to this expression:
=MonthName(Month(DateAdd("ww",CInt(MID("201547",5,LEN("201547")))
,DateSerial(CInt(LEFT("201547",4)),1,1)))) & " " & LEFT("201547",4)

Then use that field to filter your report.
Replace the string for the field returning "201547"
=MonthName(Month(DateAdd("ww",
CInt(MID(Fields!YearWeek.Value,5,LEN(Fields!YearWeek.Value)))
,DateSerial(CInt(LEFT(Fields!YearWeek.Value,4)),1,1))))
& " " & LEFT(Fields!YearWeek.Value,4)

UPDATE: MDX script for querying a calulated member with the required format:
I've tested with the following MDX:
WITH MEMBER [Measures].[month&year] AS
  'FORMAT(DateAdd("ww",STRTOVALUE(MID("201547",5,LEN("201547"))) ,CDATE(DateSerial(LEFT("201547",4),1,1))),"MMMM") + " " + LEFT("201547",4)'
SELECT { [month&year] } ON COLUMNS
FROM [Your Cube]

To use it in your query replace "201547" for [Dimension].[Attribute].MemberValue that corresponds to your cube structure:
WITH  MEMBER [Measures].[month&year] as
'FORMAT(DateAdd("ww",STRTOVALUE(MID([Dimension].[Attribute].MemberValue,5,LEN([Dimension].[Attribute].MemberValue)))
,CDATE(DateSerial(LEFT([Dimension].[Attribute].MemberValue,4),1,1))),"MMMM") + " " + LEFT([Dimension].[Attribute].MemberValue,4)'
SELECT
   { [Dimension].[Attribute].[Attribute] }
   {[month&year]} ON COLUMNS
FROM [Your Cube]

Once you have this field in your dataset you can easily filter the values using a parameter.
Let me know if this can help you.
Answer: Part 1: Establishing which day falls into which week
ISO-8601 declares the international standards for converting dates into week numbers, and vice-versa.
ISO standard weeks start on a Monday. A year can have either 52 or 53 weeks.
There are 4 ways of establishing when Week 1 starts:
- It is the first week with a majority (4 or more) of its days in January.
- Its first day is the Monday nearest to 1 January.
- It has 4 January in it. Hence the earliest possible dates are 29 December through 4 January, the latest 4 through 10 January.
- It has the year's first working day in it - i.e. excluding Saturdays, Sundays and the 1st of January.
Part 2: Excel calculations
This answer assumes that the dates are being stored as 6-character strings.
First determine the year and what day of the week it starts on.
1) Strip the first four characters from the string.`
    =left(<cell containing the year+week string>, 4)
2) Prepend "1/1/" to it.
    ="1/1/"&left(<cell containing the year+week string>, 4)
3) Convert this string to an Excel date
    =datevalue(<the last result>)
4) Determine the Weekday of the 1st day of that year.
    =weekday(<the last result>)
5) Calculate the Excel date of the first Monday.
    =if((<the last result>-4)<0,<the result of step 3>+8-<the last result>, <the result of step 3>+1-<the last result>)
6) Work out how many weeks on from that we are:
    =right(<original 6 char year/week string>,2)
7) Convert 6) to a number
    =value(<last result>)
8) Add that to the Monday of Week 1
    =<result of step 5>+<result of step 7>*7
9) Convert this to a month number
    =month(<last result>)
10) Convert this to a month name
    =choose(<last result>,"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
11) Add the year back on
    =<lastresult>&" "&<result of 1>

This gives the month number which contains the Monday of the current numbered week.
If  cell A1 contains '201547
then cell B1 should contain:
=CHOOSE(MONTH(IF((WEEKDAY(DATEVALUE("1/1/"&LEFT(A1,4)))-4)<0,DATEVALUE("1/1/"&LEFT(A1,4))+1-WEEKDAY(DATEVALUE("1/1/"&LEFT(A1,4))),DATEVALUE("1/1/"&LEFT(A1,4))+8-WEEKDAY(DATEVALUE("1/1/"&LEFT(A1,4))))+7*(VALUE(RIGHT(A1,2)))),"January","February","March","April","May","June","July","August","September","October","November","December")&" "&LEFT(A1,4)
If A1 contains 201547 then B1 returns "November 2015".
Further considerations:
You may want to make it more sophisicated, so that a month ending in a Monday does not have the week commencing with its final Monday counted as part of the month.  More generally, that week only counts as part of a month is 3 or more of the days are in the month.  Or 3 or more of its working days are part of the month.
As it is, I would  sort with the calculated month and year as primary key and the YYYYMM code as secondary key.
Comment: Is this for determining the result in Excel?  The OP states that they are using Reporting Services...

Convert "YYYYWW" into month (SSRS)


"lang.link.toolbar is null or not an object" when using CKeditor with IE7

Question: I get this error only in IE7.

lang.link.toolbar is null or not an object

I thought I may have accidentally deleted something when setting up the language, so I went to ckeditor/lang/en.js and there was indeed a CKEDITOR.lang.en.link.toolbar being set.
I set up the actual CKEditor using the jQuery adapter like so...
$( '#input-product-description' ).ckeditor(
  function() { /* callback code */ },
  {
  startupFocus: true,
  language: 'en',
  defaultLanguage: 'en',
  removePlugins : 'smiley, about, sourcearea, flash, newpage, pagebreak, popup, preview, stylescombo, table, tabletools, elementspath, save, templates, print, find, font, forms, horizontalrule, justify, format, colorbutton, div, blockquote, indent, clipboard, image, showblocks, wsc' ,
  toolbar :
      [
        ['Undo','Redo'],
        ['Bold','Italic'],
        ['NumberedList','BulletedList']
      ],
   resize_enabled: false

 });

Does anyone know why this error may occur?
Comment: Possibly related: http://dev.ckeditor.com/ticket/7705
Comment: Just a throwaway shot-in-the-dark suggestion, but I remember running into some problems with IE7 with ready vs. load. Maybe ensure the binding occurs after a window.load event.
Answer: if you want to change the ckEditor language plz try to add this as the following:
or you can see the following examble from the Multi-language interface tab on CKEditor language demo
var editor = CKEDITOR.instances.editorName; // GETTING AN INSTANCE OF THE EDITOR
var editorData = editor ? editor.getData() : initialHtml; // GET THE OLD DATA IF YOU WANT TO REUSE IT
if (editor) {
editor.destroy(); // DESTROY THE OLD EDITOR
}
editor = CKEDITOR.appendTo('demoInside', { language: 'en' }); // add new one to your target
editor.setData(editorData); // set your new data

Answer: How about you make your call once the editor is ready.
InstanceReady event


How to display/ hide some portion of the form on radio button selection in android?

Question: I have a requirement where the form has to ask "do you  have valid license:" and in radio choice 1)yes 2)no . on selection of yes  the fields to fill licenseno. , licensee_name and take license photo should  appear and  on selection of no these thing should  be hidden and it should continue with filling of the rest of the form fields .
Answer: Try to write the child View Like licenseno and name and photo inside one layout and give one id to that layout the programmatically you can hide visibility of that block.
Like :
LinearLayout ly=(LinearLayout)findViewById(R.id.LayoutID);

    ly.setVisibility(View.INVISIBLE);
            OR
    ly.setVisibility(View.GONE);

According to Your Radio Button Click Event you can achieve this
Answer: For your concern try like this
Get Radio button like this :
RadioButton rbone = (RadioButton) findViewById(R.id.rone);
RadioButton rbtwo = (RadioButton) findViewById(R.id.rtwo);

Get Radio Group like this
radioGroup = (RadioGroup) dialog.findViewById(R.id.rg);

And then fallow like this
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                            @Override
                            public void onCheckedChanged(RadioGroup group, int checkedId) {
                                // TODO Auto-generated method stub
            if (rbone.isChecked() == true) {
                    view1.setVisibility(View.VISIBLE);
                    view2.setVisibility(View.GONE);
                    }else{
                    view2.setVisibility(View.VISIBLE);
                    view1.setVisibility(View.GONE);
                    }

                            }
                        });

Comment: when i tried your code i got error in setOnCheckedChangeListener which says "The method setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener) in the type RadioGroup is not applicable for the arguments (new OnCheckedChangeListener(){})"
Comment: hey it worked for me only thing is that i need to change the import.
Comment: hey it worked for me only thing is that i need to change the import. now i have some fields in a tablelayout where one option is to take photo the moment i take photo the page refreshes and the tablelayout again hides. after taking the photo the page should not refresh.
Comment: Simply OnClick of button (which initiates picture taking part).. set   "table_layout.setVisibility(View.GONE)" and "new_layout.setVisibility(View.VISIBLE);" . Please accept answer if it works for you :)
Answer: You can set view.VISIBLE and view.INVISIBLE for controls to visible and invisible
Comment: ya shivani  may be it will help.
Answer: Try this.. If your radio buttons belongs to the same group
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if(checkedId == R.id.radioYes){
                view.setVisibility(View.VISIBLE);
            }else if(checkedId == R.id.radioNo){
                // Depends of your requirement
                view.setVisibility(View.INVISIBLE);
                     // or
                view.setVisibility(View.GONE);
            }
        }
    });


iCACLS with variable for username in VBS

Question: Hoping someone can help as I can't quite figure this one out :(
I have the following vbs to set permissions to a list of sub folders within a specified directory (C:\test) and based on a specified user account (Test1);
<code>    Dim intRunError, objShell, objFSO

Set objShell = CreateObject("Wscript.Shell")
set objFSO = CreateObject("Scripting.FileSystemObject")

 For Each objFolder In objFSO.GetFolder("c:\Test").SubFolders
        If objFSO.FolderExists(objFolder) Then
            intRunError = objShell.Run("%COMSPEC% /c Echo Y| icacls " _
            & objFolder & " /grant:r Test1:(OI)(CI)F /T", 2, True)

            If intRunError <> 0 Then
                Wscript.Echo "Error assigning permissions for user " _
                & objFolder.Name & " to the folder " & objFolder
        End If
    End If

 Next
</code>
This all works fine. However, what i really want is to use a variable for the account that will get the permissions set. In my case, the name of the folder will always be the correct username. So I had hoped to use a variable such as:
<code>& objFolder & " /grant:r objFolder.Name:(OI)(CI)F /T", 2, True)
</code>
However, clearly that doesn't work as its being written as a literal string. I've tried a few formatting variations but can't seem to get it to do what i need.
Would anyone be able to help?
Thanks in advance!
Adam
Answer: Just figured it out, should have been:
<code>& objFolder & " /grant:r " & objFolder.Name & ":(OI)(CI)F /T", 2, True)
</code>
Adam


Props change affecting previous components visited

Question: In Registration process i have 3 screens
 1.Enter mobile Number
 2.Enter Otp
 3.Enter user data
   Here the problem is,When i hit finish button at final stage ,it dispatches the action and props will update,It also update the second component and getting error message
Enter Otp(2nd componet)
 componentWillReceiveProps(nextProps) {
    console.log(nextProps.commonState.res.data.kada)
   }

Finish(3 rd component)
this.props.register(Data)

Answer: Console you nextProps and check if you are getting null in data?
componentWillReceiveProps(nextProps) {
    console.log(nextProps)
   }


User Expectations - Changing the country, currency and language to reflect their locale

Question: Scenario:
You're a customer from Germany, and you've landed on the UK, mobile, version of a website. You've discovered that within the main menu, you can change three things - country, currency and language. Please see the screenshot below.

You've selected the country you want, the currency you want and the language you want. Once you hit "Update", what would you expect to happen? My thinking is that if the user is in the menu, then the user should remain in the menu after pressing update.
However, a colleague has suggested that the user should return to the homepage as there may be deals that are related to their locale that they could miss.
Thoughts?
Comment: Where it's a separate 'page', _I_ would expect to be returned to the page from which I came to this selector. If it's a set of pulldowns on a product page (as on e.g., DriveThruRPG), I would expect to stay on the same page, and have any data displayed updated to reflect the new choices (e.g., prices in euro, text in German, etc.)
Answer: A language especially is part of how the user interacts not just on the web, but in the real world that they live in. Any language that is selected by the user should come into force straight away, whether or not you choose to clear that overlay selection items straight away or not, some immediate change to the site I should have thought should be actioned immediately.
Answer: Surely, the menu should open as an overlay.
That way it could be opened from any page and return the user back to the original page without any problems. This would also allow for deep links into any page of the site.
Answer: I would agree with you if this was something that the user might want to "try on for size" before leaving the menu. For example, the color theme of the UI. In that case, I appreciate staying in the menu instead of being jolted back to the main UI with my changes applied in case I want to revert back to what it was.
However, in this case, there will likely not be a lot of guessing about the settings I want in this menu (because I know my locale), I want to get rid of it as fast as possible to get back to the interesting part of the app.
Even better, can you detect this kind of mismatch (perhaps based on IP address vs. localized version of the side) and have a pop-up banner at the top that says

Would you like to go to the German version of this site? [Click here].
Answer: Have you tried to see where the users goes aften they have hit save? Do they go back? Do they change language again? What is the user supposed to do in that page after he changed the locale settings? I guess when the user hit save you could show him something that the change has been made successfully (animation, confirmation popup..) and you might try maybe to automatically forward the user in the home page automatically after 2 seconds of showing the feedback. In either case check what your user are trying to do with the product, where do they go after hitting save? (Are you logging thise events to discover their behaviors?).
Personally in most cases I have seen usually the user goes back to the home page to check how the system looks like with the new locale settings, so I guess it would be better to forward him in the home page (but this is just my personal overview). Let me know how it goes for you :)
Comment: If you can please rewrite as an answer as opposed to asking so many questions.


iOS XMPP searching users by username

Question: First time I am working on XMPP Framework in iOS. Can any one help in searching the users using their username.
I have tried the way described in the below link. But no luck.
iOS XMPP framework get all registered users
Thanks in advance.
Answer: I got it finally. I did myself.
NSString *userBare1  = [[[[self appDelegate] xmppStream] myJID] bare];

NSXMLElement *query = [NSXMLElement elementWithName:@"query"];
[query addAttributeWithName:@"xmlns" stringValue:@"jabber:iq:search"];

NSXMLElement *x = [NSXMLElement elementWithName:@"x" xmlns:@"jabber:x:data"];
[x addAttributeWithName:@"type" stringValue:@"submit"];

NSXMLElement *formType = [NSXMLElement elementWithName:@"field"];
[formType addAttributeWithName:@"type" stringValue:@"hidden"];
[formType addAttributeWithName:@"var" stringValue:@"FORM_TYPE"];
[formType addChild:[NSXMLElement elementWithName:@"value" stringValue:@"jabber:iq:search" ]];

NSXMLElement *userName = [NSXMLElement elementWithName:@"field"];
[userName addAttributeWithName:@"var" stringValue:@"Username"];
[userName addChild:[NSXMLElement elementWithName:@"value" stringValue:@"1" ]];

NSXMLElement *name = [NSXMLElement elementWithName:@"field"];
[name addAttributeWithName:@"var" stringValue:@"Name"];
[name addChild:[NSXMLElement elementWithName:@"value" stringValue:@"1"]];

NSXMLElement *email = [NSXMLElement elementWithName:@"field"];
[email addAttributeWithName:@"var" stringValue:@"Email"];
[email addChild:[NSXMLElement elementWithName:@"value" stringValue:@"1"]];

NSXMLElement *search = [NSXMLElement elementWithName:@"field"];
[search addAttributeWithName:@"var" stringValue:@"search"];
[search addChild:[NSXMLElement elementWithName:@"value" stringValue:searchField]];

[x addChild:formType];
[x addChild:userName];
//[x addChild:name];
//[x addChild:email];
[x addChild:search];
[query addChild:x];

NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
[iq addAttributeWithName:@"type" stringValue:@"set"];
[iq addAttributeWithName:@"id" stringValue:@"searchByUserName"];
[iq addAttributeWithName:@"to" stringValue:[NSString stringWithFormat:@"search.%@",[self appDelegate].hostName ]];
[iq addAttributeWithName:@"from" stringValue:userBare1];
[iq addChild:query];
[[[self appDelegate] xmppStream] sendElement:iq];

Comment: I have created an application in iOS and connected & fetched users from xmpp and able to get offline messages too.Now i need to fetch conversations of a particular user using XEP-0313, How to implement XEP-0313
Answer: the right answer.
the following code
[iq addAttributeWithName:@"to" stringValue:[NSString stringWithFormat:@"search.%@",[self appDelegate].hostName ]];

means
XMPPJID *myJID = [[[self appdelegate] xmppStream] myJID];
[iq addAttributeWithName:@"to" stringValue:[NSString stringWithFormat:@"search.%@",myJID.domain]];

Comment: Got it, - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
Comment: Which delegate will handle this ?

iOS XMPP searching users by username


How to convert row into columns

Question: I have two table i got the maximum and minimum record on each id. I have following query and output
SELECT s.Id, tabl2.X, tabl2.Y
FROM (SELECT MAX(tabl2.Id) AS tbl2Id, tabl1.Id
   FROM tabl2 INNER JOIN
   tabl1 ON tabl2.Id = tabl1 .Id
   WHERE (CONVERT(date, tabl2.date) = CONVERT(date, GETDATE() - 1))  and tabl1.Id=1
   GROUP BY tabl1.Id

   UNION

   SELECT MIN(tabl2.Id) AS tbl2Id,  tabl1.Id
   FROM tabl2 INNER JOIN
   tabl1 ON tabl2.Id= tabl1.Id
   WHERE (CONVERT(date, tabl2.date) = CONVERT(date, GETDATE() - 1)) AND and  tabl1.Id=1
   GROUP BY  tabl1.Id) AS s INNER JOIN
tabl2 ON s.Id= tabl2.Id

Id          X          Y
1     73.1102528   33.545264
1     74.1240448   32.2604704

but i want output like this
Id             X           Y           X1           Y2
1          73.1102528   33.545264    74.1240448   32.2604704

Comment: Please check 'PIVOT' keyword in SQL
Comment: you could use a `Join` instead of an `Union` if the two tables has the same ID.
Comment: @Baalthasarr  what do you mean same ids.two table have one to many relation .table 2 contain the table1 id
Comment: In your example both SELECT statements return the same ID value (1), but like i saw right now, that is coincidence and can not be used as a join parameter
Comment: @Baalthasarr join parameters not work in my case,
Comment: @JayeshGoyani can you explain or explain with code.thanks
Answer: I think you can simplify your query, the min/max can come into a single statement as they are grouped on the same id. As follows:
select s.id, tabl2.x, tabl2.y
from (
    select max(tabl2.id) as tbl2id_max, min(tabl2.id) as tbl2id_min, tabl1.id
    from tabl2
    inner join tabl1 on tabl2.id = tabl1 .id
    where (convert(date, tabl2.date) = convert(date, getdate() - 1))
    and tabl1.id = 1
    group by tabl1.id
) as s inner join tabl2 on s.id= tabl2.id

Its not however clear from your example where X1 and Y1 should come from.. Pivot would be used to turn rows into columns, but I don't see where these rows come from in your example.
In addition you are selecting X/Y from tabl2 in your example directly. This implies you don't need a pivot as you can already select them directly from your table.
Provide some more info and I will update this response.

How to convert row into columns


Regex for everything except the last two characters?

Question: Can someone help me with the regex for every character except the last two?
For example:
us-central1-1 should return us-central1
europe-west4-a should return europe-west4
Please advise. Thanks.
Comment: `/^(.*).{2}$/` should work
Comment: Is the pattern *always* characters dash characters dash one character?
Comment: (\w+-\w+)- should do the job.
Comment: Please include how far you've got (show your current pattern) and would be nice if you added some context to the question :)
Answer: ^(.*)..$

This should work where:

^ start of string
$ end of string
.. last 2 chars
(.*) the matching group that you want

note: . (dot) matches any charachers except line terminators


Execute a shell script with input parameter

Question: The shell script below asks the user for hour and minute. When you enter these two inputs it schedules for imaging. When I try to run this script as root like:
bash -x /run/opt/corp/cmtg/2.0.0/sesm/admin/scripts/configure_gwcautoimaging 13 56. I get the following error: typset:'13': not a valid identifier and typset:'56': not a valid identifier.
My question is how can I execute this script with its parameter in one line. I also tried ./run/opt/corp/cmtg/2.0.0/sesm/admin/scripts/configure_gwcautoimaging << "16 16" and sh /run/opt/corp/cmtg/2.0.0/sesm/admin/scripts/configure_gwcautoimaging 16 50 but they didn't work I got same error.
#!/bin/bash
    DEBUG="";
    #DEBUG="set -x";
    eval $DEBUG;
    typeset inputHour=2;
    typeset inputMinute=0;
    typeset crontabsFile="/etc/crontab";
    typeset tmp_crontabsFile="/tmp/crontab.tmp";
    typeset imagingsh=$BIN_DIR/autoimaging.sh;
    function validateNumber
    {
      eval $DEBUG;
      typeset -i vInput=$1;
      if [[ $? != 0 ]]
      then
        return 1;
      fi
      typeset -i vBase=$2;
      if [[ $? != 0 ]]
      then
        return 1;
      fi

      if (( vInput < 0 || vInput >= vBase ))
      then
        return 1;
      fi
      return 0;
    }
    function updatecrontabs
    {
      eval $DEBUG;
      typeset hour=$1;
      typeset minute=$2;

      #remove any entries that already have the autoimaging.sh
      /bin/grep -v "${imagingsh}" $crontabsFile > ${tmp_crontabsFile};

      cat <<- EOF >> $tmp_crontabsFile
    $inputMinute $inputHour * * * $imagingsh
    EOF
      crontab ${tmp_crontabsFile}
      if [[ $? != 0 ]]
      then
        return 1;
      fi
      cp ${tmp_crontabsFile} ${crontabsFile};
    }
    # If this script is invoked with two parameters, parse the two parameters as Hour and Minute
    # Otherwise, get input from user.
    if [[ $# != 2 ]]
    then
      echo " Configure Auto Imaging ";
      while ( true )
      do
        echo -n "Please input the hour when the Auto Imaging is to be executed: ";
        read inputHour
        if [[ -n $inputHour ]]
        then
          validateNumber $inputHour 24;
          if [[ $? == 0 ]]
          then
            break;
          else
            echo "You must input the number between 0 and 24";
        echo " ";
          fi
        else
          echo "You must input the number between 0 and 24";
          echo " ";
         fi
      done
      while ( true )
      do
        echo -n "Please input the minute when the Auto Imaging is to be executed: ";
        read inputMinute
        if [[ -n $inputMinute ]]
        then
          validateNumber $inputMinute 60;
          if [[ $? == 0 ]]
          then
            break;
          else
            echo "You must input the number between 0 and 60";
        echo " ";
          fi
        else
          echo "You must input the number between 0 and 60";
          echo " ";
        fi
      done
    else
      inputHour=$1;
      inputMinute=$2;
      typeset vResult=validateNumber $inputHour 24;
      if [[ $vResult != 0 ]]
      then
        echo "The number for hour must be between 0 and 24";
        exit 1;
      fi
      vResult= validateNumber $inputMinute 60;
      if [[ $vResult != 0 ]]
      then
        echo "The number for minute must be between 0 and 60";
        exit 1;
      fi
    fi
    # Begin update the entry: auto imaging in crontabs
    updatecrontabs $inputHour $inputMinute;
    if [[ $? == 0 ]]
    then
      echo "update crontabs successfully! The auto imaging will be executed at: " $inputHour ":" $inputMinute;
      echo " ";
    else
      echo "Errors happen during update crontabs";
      echo " "
      exit 1;
    fi
    rm ${tmp_crontabsFile} > /dev/null;
    exit 0;

Comment: learn to use shell debug/trace features, i.e. `set -vx; PS4='${LINENO} #>'` To turn off, use `set +vx;unset PS4`. Good luck.
Answer: This seems suspicious:
typeset vResult=validateNumber $inputHour 24;

It doesn't call the function, you need to use $(validateNumber $inputHour 24) or backticks.
Similarly, the following line is probably wrong:
vResult= validateNumber $inputMinute 60;

It clears $vResult and calls validateNumber with $inputMinute and 60 as parameters.
I am able to get the same error if I call typeset with a number as the first argument, but I don't see such usage in your code. Are you sure you pasted the version that caused the problem?
a=12 ; typeset -i $a=b
bash: typeset: `12=b': not a valid identifier

Comment: Yes I am sure, When I execute it without parameters like: bash -x /run/opt/corp/cmtg/2.0.0/sesm/admin/scripts/configure_gwcautoimaging, it asks me Please input the hour when the GWC Auto Imaging is to be executed: and after I entered for hour it asks for minute that I want to enter.
Comment: @OscarSayin: Please, reduce the script as per [Short, Self Contained, Correct Example](http://sscce.org/). I'm not going to run code that touches crontab files.
Answer: I have edited my code parts as below and it is working now:
validateNumber $inputHour 24;
      if [[ $? != 0 ]]

and
validateNumber $inputMinute 60;
      if [[ $? != 0 ]]


Prolog looking for the inorder location of an element in tree(without using lists)

Question: I am trying to go through a binary tree in an inorder traveling method
my target is to find the occurance of a specific key in the tree
for example,
i have the following tree:
t(t(t(nil,"d",t(nil,"g",nil)),"b",t(nil,"e",nil)),"a",t(t(nil,"f",t(nil,"h",nil)),"c",nil))

when i will use my inorder_finder i will get the following:
for "c" i will get 8
for  "d" i will get 1
for "w" i will get -1
I have come up to the following code:
inorder_finder(nil,_,_,0).

inorder_place(t(_,X,_),X,Count,Place) :-
    Place is Count+1.

inorder_place(t(L,_,R),Wanted,Count,Place) :-
        inorder_place(L,Wanted,Count+1,Place),
        Place<1,
        inorder_place(R,Wanted,Count+1,Place),
        Place<1,
        Count = Count+1.

and i call the following predicate:
inorder_finder inorder_place(t(t(t(nil,"d",t(nil,"g",nil)),"b",t(nil,"e",nil)),"a",t(t(nil,"f",t(nil,"h",nil)),"c",nil)),"c",1,Place)

but it doesnt work at the moment. (just always returns false)
any ideas?
update: I have updated the code according to the comments i got - it still returns false and doesnt work as i would like it to
Comment: You have not addressed all of the issues already mentioned. Please read them again carefully.
Comment: _"c" i will get 8_ why?? your tree does not have `"c"` at all?
Comment: This is a little confusing. Do place positions start at 1 or 0? Your invalid place is set to -1, but your code continues searching if place is < 1, implying that 0 is considered an invalid place indicator. And what do you mean *it doesn't work at the moment?* In what way does it not work? Finally, if you call the predicate as you show `inorder_finder ( ...` you'll get an error since, In Prolog, you cannot have a space between functor and left parenthesis.
Comment: Place = Count + 1 should be Place **is** Count + 1
Comment: A couple of things wrong on inspection... If the correct first indicator is 1 as you say, then I'd suggest `inorder_finder (nil,_,_,0).` instead of `inorder_finder (nil,_,_,Place) :-
    Place = -1.`. The reason being  your predicate depends upon the increment of count, so with -1 your base case it would result in an invalid 0 count at some point due to increment. Also, note that `Count is Count + 1` will ALWAYS fail since `Count` can never have the same value as `Count + 1`. `inorder_finder(t(L,_,R),Wanted,Count,Place)` will always fail since it has no complete success path.
Comment: HI - first thanks I have updated the tree(it didnt copy the second line i wrote with c) and updated the predicate to be without the space, I need its first indicator to be 1, any suggestion what am i doing wrong?
Comment: Thanks for all of your help - I have updated the code according to the comments - it still returns false and doesnt work as i would like it to
Answer: Most obvious errors have been mentioned in comments, what still remain are:

Place<1 : I don't get why?? Place may has value greater than 1.
inorder_place: never defined...
inorder_place(t(_,X,_),X,Count,Place):-Place is Count+1.: even if you find the letter you need first recursively enumerate the left branch of tree and then Place of wanted letter (see answer below)
I think the problem could be solved in two parts, one in-order-enumerate all nodes then simply traverse until you find the right node. Though I didn't followed this version (even it is more clear) since with a simple-mixed solution it is more efficient since you may not need to enumerate all nodes. For this attempt that you're trying to do I think you need two counters - first one the counter when calling inorder_find(..) e.g when entering, second counter will return where the counting stopped in order to continue from there in the right branch of tree.
inorder_finder inorder_place(...):still not valid syntax for calling the predicate- it should return error not false...

My implementation:
inorder_finder(nil,_,Count,Count,-1).

inorder_finder(t(L,X,_),X,Count,Count2,Place):-
                inorder_finder(L,X,Count,Count3,_),
                Place is Count3+1,Count2 is Place.

inorder_finder(t(L,X,R),Wanted,Count,Count2,Place):-
                dif(X,Wanted),
                inorder_finder(L,Wanted,Count,Count3,Place1),
                Count4 is Count3+1,
                inorder_finder(R,Wanted,Count4,Count2,Place2),
                Place is max(Place1,Place2).

Examples:
?- inorder_finder(t(t(t(nil,"d",t(nil,"g",nil)),"b",t(nil,"e",nil)),"a",t(t(nil,"f",t(nil,"h",nil)),"c",nil)),"c",0,_,P).
P = 8 ;
false.

?- inorder_finder(t(t(t(nil,"d",t(nil,"g",nil)),"b",t(nil,"e",nil)),"a",t(t(nil,"f",t(nil,"h",nil)),"c",nil)),"W",0,_,P).
P = -1.

?- inorder_finder(t(t(t(nil,"d",t(nil,"g",nil)),"b",t(nil,"e",nil)),"a",t(t(nil,"f",t(nil,"h",nil)),"c",nil)),"d",0,_,P).
P = 1 ;
false.