get location on iphone ONLY from the GPS - not the wifi network

Question: i am creating an app that uses location-
everything works swimmingly except one thing-
when i come home my iphone connects to my local wifi network and instead of getting my location using the gps in the phone it tries to get it by figuring out where my wifi network is connected to- if i turn my wifi off it keeps an accurate location point-
as soon as my phone is connected to my wifi network it starts telling me my location is several km/miles from my actual point.
i would like my app NOT to use the wifi network to try get my location-
is there a way i can-
a. tell if a location point has been derived from the GPS so i can ignore locations derived from the wifi network.
b. stop location services jumping over to wifi for location
Answer: Well I did some playing around
Found some apple documentation that says that [location verticalAccuracy] REQUIRES a device with gps.
So I stuck this code in (abridged) and based on the limited testing I have done, it appears to be doing what I want:
if (([location horizontalAccuracy] > 0) && ([location verticalAccuracy] > 0)){
     //report location here
}

Thanks all for your replies.
Answer: Other than asking the user to turn off his Wifi, there's no documented way you can force the location manager to use GPS over Wifi.  It might be possible with private API, but that would also get you rejected from the App Store.
Comment: hey dave- thanks for that reply- i was afraid of that- i couldnt find anything after scouring the net- im hoping someone has a sly way of doing it without app store rejection- may have to end up doing some sort of time/distance calculation between points to see if the new location is physically unfeasible, but that would be a pretty poor solution- cheers, dave.
Answer: You can set cLLocationAccuracy.desiredAccuracy = kCLLocationAccuracyBest and see if that does it. It should try and limit to GPS use, however that isn't 100% guarenteed.
Comment: hey jamone- thanks for that reply- yeah i have it set to best but the locations services seem to give preference to wifi over the gps- cheers, dave.
Answer: The reason it uses WIFI at home is because there's no way it can have direct sight of the GPS satellites out in space - instead of not giving you any location data, it uses the next best available source.
Answer: the inaccurate GPS coordinates are obtained by the iPhone not only via the Wi-Fi or mobile networks, but also the real-coordinates with accuracy level >100 metres.
What I use is to put the line: if (newLocation.horizontalAccuracy < 0 || newLocation.horizontalAccuracy > 50) return;

as the first line in the didUpdateToLocation, to filter out inaccurate coordinates.
The 'location age' i.e. NSTimeInterval locationAge=[locTimestamp timeIntervalSinceNow]; does NOT serve for me to get rid of cached coordinates.
Answer: A-GPS = GPS + cell tower triangulation. There is no WI-FI positioning.
Comment: It's commonly known that the iPhone/iPod touch/iPad use the skyhook service that can look up a WiFi's MAC address and then query the web service and find out the approximate location of that hot spot. This is done by mapping WiFi hotspots similar to how Google does street view. Wikipedia "Assisted GPS, generally abbreviated as A-GPS, is a system which can improve the startup performance of a GPS" It helps the GPS lock on faster by giving it a starting location and almanac data and a few other things. It does not mean the GPS uses that only for position. Its just to start faster.
Comment: hey adrian, thanks for that reply- my iphone is giving me the same location at home as my ipod, and my ipod doesnt have gps or cell reception- im presuming my iphone is grabbing the location from the same place as my ipod is getting it from- i should note: i get no phone reception in my house (tin roof lol)- cheers, dave-
Comment: The A-GPS just means the cell signal can get used to speed up the GPS lock. It doesn't effect the GPS's position accuracy. And yes there is WiFi location also used.
Comment: @jamone Can you define WI-FI. Please look first what AGPS means and don't tell me your home WiFi router can tell you your position on the iPhone. And YES... cell triangulation is used to make a better positioning.
Comment: There is no wi-fi positioning? Are you drunk?


DJANGO: Serving static with NGINX/gunicorn

Question: I can't seem to get static files loading properly with NGINX.
Strangely if I go to [MY-server-IP]:8001   which is the port assigned with gunicorn, The files load
But if I just go to [MY-server-IP] in the browser the page loads but none of the static does.
Here is my nginx settings:
server {
    server_name [MY-IP];

    access_log off;

    location ~ ^ /static/ {
        alias /django-app/static/;
    }

    location /media/ {
         alias /django-app/SENECA-DJANGO/media/;
    }

    location / {
        proxy_pass http://[MY-IP]:8001;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
    }
  }

Comment: Do you really have `/django-app/` in root?
Comment: @AlexeyTen yes I do, is that a terrible idea? django-app is a virtual environment.
Comment: Not terrible, just unusual. It's common error to put incomplete path to root/alias, so I just check.
Answer: Did you mean to use the "^~" modifier in the static location? Unless it's a typo, you appear to be using a regular expression in your /static/ location anchored to a leading space.
location ^~ /static/ {
    alias /django-app/static/;
}

Comment: Yes I did. I just added it recently to see if there would be a difference. Strangely it deactivates all access to the site via [My-IP] but [My-IP]:8001 still works. This isn't an answer though... move to comments?
Comment: @AllTheTime, I've added some detail. The location stanza is formated better in an answer block, but I'll move this to comments if you want.
Comment: It's just that it doesn't address my issue and/or solve my problem


Display numbers with ordinal suffix in PHP

Question: I want to display numbers as follows

1 as 1st,
2 as 2nd,
...,
150 as 150th.

How should I find the correct ordinal suffix (st, nd, rd or th) for each number in my code?
Comment: See my answer here. http://stackoverflow.com/questions/69262/is-there-an-easy-way-in-net-to-get-st-nd-rd-and-th-endings-for-numbers/69284#69284 That question was for .NET, but I answered with a PHP solution, so it should help you out.
Comment: @Tom, a lookup table might be better, just initialize it with the 23000 values and get the value at index n, where n is the number you want the ordinal.
Comment: Col. Shrapnel. you may brilliant but not all. any way thanks for showing interest on my question
Comment: The only way I can think of doing this is have a if statement going up for every number you could possible have, IE, if(1) then "st" elseif (2) then "nd" etc etc if (23000) then "nd".  It's a problem if you have big numbers but you could write a program to write the code for you, it could loop all the numbers printing the ifs for you to copy + paste into your code.
Comment: @John, very very clever idea, it would be very quick to access as well as each index represents the number you are looking up.
Comment: @Tom & @Gullen, lookup table is only better than doing calculation if the calculation is expensive, like to calculate logarithm or square root, but for this question, doing calculation is cheaper than initializing the lookup table.
Comment: @Lukman maybe you didnt get the memo, these answers in the comments are for finding the worst possible way of a solution to the problem.
Comment: Look at this post. The function there works https://kitson-consulting.co.uk/blog/php-code-add-st-nd-rd-or-th-number
Answer: from wikipedia:
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if (($number %100) >= 11 && ($number%100) <= 13)
   $abbreviation = $number. 'th';
else
   $abbreviation = $number. $ends[$number % 10];

Where $number is the number you want to write. Works with any natural number.
As a function:
function ordinal($number) {
    $ends = array('th','st','nd','rd','th','th','th','th','th','th');
    if ((($number % 100) >= 11) && (($number%100) <= 13))
        return $number. 'th';
    else
        return $number. $ends[$number % 10];
}
//Example Usage
echo ordinal(100);

Comment: I like your solution. Additionally if you prefer not to generate **0th** modify the last line to be `$abbreviation = ($number)? $number. $ends[$number % 10] : $number;`
Comment: @GavinJackson your addition to this excellent solution really helped me out (+1). Could you please explain to me what is going on in the calculation? I want to understand. Cheers!
EDIT: Found an answer: [conditional operator](http://stackoverflow.com/questions/1080247/what-is-the-php-operator-called-and-what-does-it-do)
Comment: @HafezDivandari - are you sure? Just tested with 7.1.19 and seems to work fine
Comment: Although a bit difficult to understand at first, I do now think it best represents how the ordinal suffix system works for English.
Comment: Sorry, had to break the 111 votes to 112 :D Made it a function in Delphi along with a demo app: http://pastebin.com/wvmz1CHY
Comment: one liner version of your function for those inclined: `return $n . ($n %100 > 3 && $n %100 < 21 ? 'th' : array('th','st','nd','rd','th','th','th','th','th','th')[$n %10]) ;`
Comment: If you don't want the one-liner as suggested, you could do a return inside the if statement before declaring the `$ends` array. You can also drop the `else` if you do that.
Comment: @lacopo You're right, I was testing with http://phpfiddle.org and it returned a buggy output, sorry.
Answer: PHP has built-in functionality for this. It even handles internationalization!
$locale = 'en_US';
$nf = new NumberFormatter($locale, NumberFormatter::ORDINAL);
echo $nf->format($number);

NOTE: This requires intl php Extension and only available in PHP 5.3.0 and later.
Comment: Note this also requires PECL intl >= 1.0.0
Comment: Do you know if it is possible to get the ordinal number in word form? i.e. first, second, third, etc. instead of 1st, 2nd, 3rd...
Comment: @Jhn you have to install the extension `apt-get install php5-intl`
Comment: @jeremy When I tried to use NumberFormatter, it always throws an error that `NumberFomatter file not found`. How did you work around this?
Comment: @Aley I see. Yii has a built-in formatter that we're using right now. heh
Answer: This can be accomplished in a single line by leveraging similar functionality in PHP's built-in date/time functions.  I humbly submit:
Solution:
function ordinalSuffix( $n )
{
  return date('S',mktime(1,1,1,1,( (($n>=10)+($n>=20)+($n==0))*10 + $n%10) ));
}

Detailed Explanation:
The built-in date() function has suffix logic for handling nth-day-of-the-month calculations.  The suffix is returned when S is given in the format string:
date( 'S' , ? );

Since date() requires a timestamp (for ? above), we'll pass our integer $n as the day parameter to mktime() and use dummy values of 1 for the hour, minute, second, and month:
date( 'S' , mktime( 1 , 1 , 1 , 1 , $n ) );

This actually fails gracefully on values out of range for a day of the month (i.e. $n > 31) but we can add some simple inline logic to cap $n at 29:
date( 'S', mktime( 1, 1, 1, 1, ( (($n>=10)+($n>=20))*10 + $n%10) ));

The only positive value(May 2017) this fails on is $n == 0, but that's easily fixed by adding 10 in that special case:
date( 'S', mktime( 1, 1, 1, 1, ( (($n>=10)+($n>=20)+($n==0))*10 + $n%10) ));

Update, May 2017
As observed by @donatJ, the above fails above 100 (e.g. "111st"), since the >=20 checks are always returning true.  To reset these every century, we add a filter to the comparison:
date( 'S', mktime( 1, 1, 1, 1, ( (($n>=10)+($n%100>=20)+($n==0))*10 + $n%10) ));

Just wrap it in a function for convenience and off you go!
Comment: Will this work for numbers > 31?
Comment: @Popnoodles you tell me: https://onlinephp.io/c/f6246 [onlinephp.io Sandbox]
Answer: Here is a one-liner:
$a = <yournumber>;
echo $a.substr(date('jS', mktime(0,0,0,1,($a%10==0?9:($a%100>20?$a%10:$a%100)),2000)),-2);

Probably the shortest solution. Can of course be wrapped by a function:
function ordinal($a) {
  // return English ordinal number
  return $a.substr(date('jS', mktime(0,0,0,1,($a%10==0?9:($a%100>20?$a%10:$a%100)),2000)),-2);
}

Regards,
Paul
EDIT1: Correction of code for 11 through 13.
EDIT2: Correction of code for 111, 211, ...
EDIT3: Now it works correctly also for multiples of 10.
Comment: Yeah, sorry. When I read the question I thought, hey this should be possible by a single line of code. And I just typed it away. As you see from my edits, I'm improving. After the third edit now I think it's quite done. At least all numbers from 1 to 150 print out nicely on my screen.
Comment: I like this approach, but alas, it doesn't work :-(

30th comes out as 30st. 40th comes out as 40st. etc.
Comment: Looks good up to 500! (haven't tested it further than that). Good work! :-)
Answer: from http://www.phpro.org/examples/Ordinal-Suffix.html
<?php

/**
 *
 * @return number with ordinal suffix
 *
 * @param int $number
 *
 * @param int $ss Turn super script on/off
 *
 * @return string
 *
 */
function ordinalSuffix($number, $ss=0)
{

    /*** check for 11, 12, 13 ***/
    if ($number % 100 > 10 && $number %100 < 14)
    {
        $os = 'th';
    }
    /*** check if number is zero ***/
    elseif($number == 0)
    {
        $os = '';
    }
    else
    {
        /*** get the last digit ***/
        $last = substr($number, -1, 1);

        switch($last)
        {
            case "1":
            $os = 'st';
            break;

            case "2":
            $os = 'nd';
            break;

            case "3":
            $os = 'rd';
            break;

            default:
            $os = 'th';
        }
    }

    /*** add super script ***/
    $os = $ss==0 ? $os : ''.$os.'';

    /*** return ***/
    return $number.$os;
}
?>

Answer: Simple and Easy Answer will be:
$Day = 3;
echo date("S", mktime(0, 0, 0, 0, $Day, 0));

//OUTPUT - rd

Comment: Doesnt say anything about dates in the question tho. I upvoted anyway - it's a quick and simple solution when you know the number range is going to be <32
Comment: OP wants this to work at least up to 150. Yours starts breaking at 32st since 0/32/0000 converts to 12/32/-0001, which rolls over to 1/1/0000, meaning the day 32 turns into the day 1 and gets an "st." As @cronoklee said, it works for numbers 31 and under, but that's not what the OP was asking for.
Answer: I wrote this for PHP4.
It's been working ok & it's pretty economical.
function getOrdinalSuffix($number) {
    $number = abs($number) % 100;
    $lastChar = substr($number, -1, 1);
    switch ($lastChar) {
        case '1' : return ($number == '11') ? 'th' : 'st';
        case '2' : return ($number == '12') ? 'th' : 'nd';
        case '3' : return ($number == '13') ? 'th' : 'rd';
    }
    return 'th';
}

Comment: I know this is late, but to answer @iletras, This function starts by getting the mod 100 of the number (divide by 100, return the remainder, which effectively removes everything from the hundreds place up), and puts that in the `$number` variable. Then it grabs the last digit and puts that in `$lastChar`. Since most cases will need a 'th' at the end, he only focuses on the special cases: numbers ending in 1, 2 or 3. In each case, this function looks for the exception (11, 12 and 13) to return 'th' in those cases, or 'st', 'nd' or 'rd' for all the others. I personally like this one the best.
Comment: Vishal Kumar, could you expand/expound/explain that a bit more? Tks!
Answer: you just need to apply given function.
function addOrdinalNumberSuffix($num) {
  if (!in_array(($num % 100),array(11,12,13))){
    switch ($num % 10) {
      // Handle 1st, 2nd, 3rd
      case 1:  return $num.'st';
      case 2:  return $num.'nd';
      case 3:  return $num.'rd';
    }
  }
  return $num.'th';
}

Answer: Here is the correct solution
$numberFormatter = new NumberFormatter('en_US', NumberFormatter::ORDINAL);

echo $numberFormatter->format(11);

Answer: Generically, you can use that and call echo get_placing_string(100);
<?php
function get_placing_string($placing){
    $i=intval($placing%10);
    $place=substr($placing,-2); //For 11,12,13 places

    if($i==1 && $place!='11'){
        return $placing.'st';
    }
    else if($i==2 && $place!='12'){
        return $placing.'nd';
    }

    else if($i==3 && $place!='13'){
        return $placing.'rd';
    }
    return $placing.'th';
}
?>

Answer: I made a function that does not rely on the PHP's date(); function as it's not necessary, but also made it as compact and as short as I think is currently possible.
The code: (121 bytes total)
function ordinal($i) { // PHP 5.2 and later
  return($i.(($j=abs($i)%100)>10&&$j<14?'th':(($j%=10)>0&&$j<4?['st', 'nd', 'rd'][$j-1]:'th')));
}

More compact code below.
It works as follows:
printf("The %s hour.\n",    ordinal(0));   // The 0th hour.
printf("The %s ossicle.\n", ordinal(1));   // The 1st ossicle.
printf("The %s cat.\n",     ordinal(12));  // The 12th cat.
printf("The %s item.\n",    ordinal(-23)); // The -23rd item.

Stuff to know about this function:

It deals with negative integers the same as positive integers and keeps the sign.
It returns 11th, 12th, 13th, 811th, 812th, 813th, etc. for the -teen numbers as expected.
It does not check decimals, but will leave them in place (use floor($i), round($i), or ceil($i) at the beginning of the final return statement).
You could also add format_number($i) at the beginning of the final return statement to get a comma-separated integer (if you're displaying thousands, millions, etc.).
You could just remove the $i from the beginning of the return statement if you only want to return the ordinal suffix without what you input.

This function works commencing PHP 5.2 released November 2006 purely because of the short array syntax. If you have a version before this, then please upgrade because you're nearly a decade out of date! Failing that, just replace the in-line ['st', 'nd', 'rd'] with a temporary variable containing array('st', 'nd', 'rd');.
The same function (without returning the input), but an exploded view of my short function for better understanding:
function ordinal($i) {
  $j = abs($i); // make negatives into positives
  $j = $j%100; // modulo 100; deal only with ones and tens; 0 through 99

  if($j>10 && $j<14) // if $j is over 10, but below 14 (so we deal with 11 to 13)
    return('th'); // always return 'th' for 11th, 13th, 62912th, etc.

  $j = $j%10; // modulo 10; deal only with ones; 0 through 9

  if($j==1) // 1st, 21st, 31st, 971st
    return('st');

  if($j==2) // 2nd, 22nd, 32nd, 582nd
    return('nd'); //

  if($j==3) // 3rd, 23rd, 33rd, 253rd
    return('rd');

  return('th'); // everything else will suffixed with 'th' including 0th
}

Code Update:
Here's a modified version that is 14 whole bytes shorter (107 bytes total):
function ordinal($i) {
  return $i.(($j=abs($i)%100)>10&&$j<14?'th':@['th','st','nd','rd'][$j%10]?:'th');
}

Or for as short as possible being 25 bytes shorter (96 bytes total):
function o($i){return $i.(($j=abs($i)%100)>10&&$j<14?'th':@['th','st','nd','rd'][$j%10]?:'th');}

With this last function, simply call o(121); and it'll do exactly the same as the other functions I listed.
Code Update #2:
Ben and I worked together and cut it down by 38 bytes (83 bytes total):
function o($i){return$i.@(($j=abs($i)%100)>10&&$j<14?th:[th,st,nd,rd][$j%10]?:th);}

We don't think it can possibly get any shorter than this! Willing to be proven wrong, however. :)
Hope you all enjoy.
Comment: you don't need to use `abs()` with modulus `%`
Comment: Relying on modulo only will still leave the negative sign in place. `abs();` removes the negative sign which is what I needed.
Answer: An even shorter version for dates in the month (up to 31) instead of using mktime() and not requiring pecl intl:
function ordinal($n) {
    return (new DateTime('Jan '.$n))->format('jS');
}

or procedurally:
echo date_format(date_create('Jan '.$n), 'jS');

This works of course because the default month I picked (January) has 31 days.
Interestingly enough if you try it with February (or another month without 31 days), it restarts before the end:
...clip...
31st
1st
2nd
3rd

so you could count up to this month's days with the date specifier t in your loop: number of days in the month.
Answer: function ordinal($number){

    $last=substr($number,-1);
    if( $last>3 || $last==0 || ( $number >= 11 && $number <= 19 ) ){
      $ext='th';
    }else if( $last==3 ){
      $ext='rd';
    }else if( $last==2 ){
      $ext='nd';
    }else{
      $ext='st';
    }
    return $number.$ext;
  }

Answer: Found an answer in PHP.net
<?php
function ordinal($num)
{
    // Special case "teenth"
    if ( ($num / 10) % 10 != 1 )
    {
        // Handle 1st, 2nd, 3rd
        switch( $num % 10 )
        {
            case 1: return $num . 'st';
            case 2: return $num . 'nd';
            case 3: return $num . 'rd';
        }
    }
    // Everything else is "nth"
    return $num . 'th';
}
?>

Answer: Here's another very short version using the date functions. It works for any number (not constrained by days of the month) and takes into account that *11th *12th *13th does not follow the *1st *2nd *3rd format.
function getOrdinal($n)
{
    return $n . date_format(date_create('Jan ' . ($n % 100 < 20 ? $n % 20 : $n % 10)), 'S');
}

Answer: I realise this is an ancient post, however it's probably worth adding that as of PHP 8, the match control structure allows a more concise:
$ordinal = match(in_array(abs($position)%100, [11, 12, 13]) ? 0 : abs($position)%10) { 1 => 'st', 2 => 'nd', 3 => 'rd', default => 'th' };

If you need to append that to the position to get a place:
$place = $position.match(in_array(abs($position)%100, [11, 12, 13]) ? 0 : abs($position)%10) { 1 => 'st', 2 => 'nd', 3 => 'rd', default => 'th' };

You can obviously simplify that out if you know your position will always be positive or less than 11 or whatever.
Answer: I fond this small snippet
<?php

  function addOrdinalNumberSuffix($num) {
    if (!in_array(($num % 100),array(11,12,13))){
      switch ($num % 10) {
        // Handle 1st, 2nd, 3rd
        case 1:  return $num.'st';
        case 2:  return $num.'nd';
        case 3:  return $num.'rd';
      }
    }
    return $num.'th';
  }

?>

HERE
Comment: I am not quite sure what this answer offers in addition to ChintanThummar's answer. Well, it hints that ChintanThummar made a copyright violation, unless he wrote the code at your source...


App Crashing When Relaunching

Question: When I hard exit (double click home and minus) and then relaunch app it is freezing up.
The Console shows this:
[app directory path .....]has changed; re-reading symbols.
I think it may have to do with this code in my appdelagate.m
- (void)applicationWillTerminate:(UIApplication *)application
{
    [self saveCode];
}

- (void)saveCode
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"routine.plist"];
    [NSArray writeToFile:path atomically:YES];
}

Comment: Is that a typo, or are you calling `[NSArray writeToFile:atomically:]` like that?  If it isn't a typo, that's your problem.  Replace `NSArray` with the name of your array variable.
Comment: Hello, I am also facing the same issue.Having some "performSelector" in applicationWillResignActive method will cause the "failed to resume" crash after re-lunching app.
Answer: First: saving a plist to populate a UITableViewController is a really tedious way to save data persistently and an inconsistent one as you may have realized, I would recommend that you use Core Data instead.
Second: Run the debugger (before launching your app) and find any line of text that's shown in black (grey lines are for methods called by the os and the cocoa layer, black ones are for your own methods). The debugger can be run via Run > Debugger or Command + Shift + Y.
Comment: Well, my advise would be to check out the tutorial I pointed you to on my answer, read it, analyze it, and then decide whether you want to implement it or if you are comfortable with what you have now. The reason I (and many other people, I believe) prefer Core Data is that once you get the grasp of it, it's really easy and simple to use (even simpler than pure SQL) with the added bonus that it is in fact a SQLite database.
Comment: I haven't learned CoreData yet and don't want to waste time learning it and holding up my app.  Therefore I will learn it and implement it into the app after it releases.
Comment: And I posted in the question what the debugger came up with.
Comment: That's console output, you need debugger output. And good luck with the implementing core data after release thing
Comment: About the CoreData, are you saying it will be difficult to do after releaseing?
Comment: Unfortunately yes, a little bit, but if you have the will to do it and are not lazy enough to go through the process, then it shouldn't be a big deal
Comment: yah I get it, well I'm not sure if i should do it now or after.  My data model is relatively simple I think so I'm not sure if I will even need it at all.  I do want to have user accounts though.
Answer: The similar kind of crashing issue - on quick relaunch is being faced when I use location manager in the application. The case is : my application quits on pressing home button rather than going into the background in iPhone 4. And on iPhone 3G (where no background processing is supported) the case is same - it crashes on relaunch [atleast it seems like a crash].
If we wait even 1 second to relaunch the app, it does not crash.

App Crashing When Relaunching


What is underneath the original bath tile in my 1950s home?

Question: My home is a pier and beam 1950s home.
I recently had a water leak and it damaged the flooring in my bathroom. I pulled it up, and it turns out there are several layers of flooring, all of which have some amount of water damage.
At the bottom (or what I hope is the bottom) is the original tile floor. I started pulling up some tiles that were loose from what I think is previous water damage, and found what looks like a dirt floor.

Here is a closer view of where I've removed loose tiles

I thought it might just be a crushed layer of thinset, so I tried to break through it and it just seems to keep going! I grabbed a masonry bit and drilled down ~5" before I ran out of bit.

Any thoughts in what this is and how I would go about fixing this floor?
Answer: It is likely a mud bed/mortar bed which was what was used before thinset and cement board became the standard, basically a dry pack of sand and cement lightly wetted and screed flat.
https://www.tcnatile.com/faqs/71-thick-setthick-bed.html


How do I nail furring strips without them cracking?

Question: While remodeling my basement, I had several walls where I just put up furring strips and foam insulation rather than framing in a "real" wall.  I used 1x2 furring strips and attached them with a ramset and 1 1/2 inch nails.
Problem is, putting the nails through the furring strips would quite often cause them to crack.  I tried pre-drilling (didn't really help) and also tried using 1x3 strips in some places (helped a little, but not much).
Is there some trick to nailing up furring strips to keep them from cracking on you?
Comment: The only other suggestion I can suggest here is that you can get galvanised pressed / cold rolled steel furring strips.  Here in the UK we call it stud and track.  This can be bolted straight through into concrete with a concrete nailer and obviously will never split. Then you can screw plasterboard into it.
Answer: You may be using the wrong load.  This site recommends using a Yellow #4 load on strips 3/4" thick, or Green #3 for 1/4" - 1/2".
You could also use concrete screws.

Pre-drill holes in furring strip and wall (about every 24").
Clean holes in walls well (with shop-vac).
Using concrete screws fasten furring strip to wall (do not over tighten).
Comment: Good thought, but I was using #3 loads.  Concrete screws would probably work, but would take quite a bit longer to do.
Answer: I figured out a workaround for this.  Today, rather than using actual furring strips, I just ripped a sheet of 3/4 inch plywood into strips on the table saw.  Being plywood, it doesn't split.  Not an ideal solution, but worked out pretty well for me.
Answer: As an aside, remember that basement concrete walls are not watertight, so when the ground is wet, the interior concrete may get moisture on the inside. Furring strips directly against concrete is a good way to end up with wet wood, which means mold and rot. Same goes for where the basement floor meets the studs. Full framing an inch or so from the wall with foam insulation behind is better for keeping the finished wall dry, even though you'll lose some interior space.
Comment: That's why it's good to use pressure-treated furring strips.
Answer: Also look into using construction adhesive to attach the furring strips and then fewer masonry screws.
Comment: Yup, used adhesive as well, and only two nails per strip.  Made sure to keep them away from the ends of the board as well.
Answer: When you hammer a nail through a strip of wood, the point of the nail splits and goes between the fibers of the wood.  Instead, take each nail as you use it, put the head on a firm surface and tap the point once or twice with your hammer.  This will flatten the point so that instead of splitting the fibers of the wood it cuts the fibers of the wood as it penetrates and is thus far less likely to crack the board.
Comment: Interesting, seems like this would work in general, but would it work in my case with a ramset and cement nails?  Seems like those nails are tough enough that pounding them with a hammer a few times wouldn't dull them much.
Comment: Why ask for conjecture? I just grabbed a ramset nail, set the head against a slab and smacked the pointy end with a hammer. It dulls the tip quite nicely. Not quite as much as an 8# nail, but close enough. I'm sure SKL is correct and just like with normal woodworking, it will significantly reduce splitting.
Answer:
Is there some trick to nailing up furring strips to keep them from cracking on you?

SKL has hit the nail on the tail, dull the tip first. That technique reduces splitting of all types of lumber.
Keep your fasteners away from the ends of the boards.
Pre-drilling the holes would typically prevent splitting, but not so much with concrete nails. When the nail is being driven into the concrete, it tries to escape sideways, stressing the furring strip and frequently cracking it. The force is enough to split 2x4s if you didn't pay attention to tip #2.
Unless you've got a system in place (sill gasket) to prevent your concrete walls from wicking moisture up from the footings and the dirt against the outside of the walls (vapor barrier/membrane/drainage gravel), your plywood strips will get moist. Then they'll mold and delaminate. If you're using marine grade plywood, it'll take a bit longer.
Instead of furring strips, use 3/4 hardwood flooring. While doing some demo work in a basement, I found hardwood flooring glued (one quarter sized glob per foot) and nailed to the walls where it had been fastened 65 years prior. It was still in very good condition. Pine would have long since fallen victim to moisture and rotted away. After pre-drilling holes, I'd wager that most any hardwood will resist the forces of a concrete nail without splitting.


Making a new file in subdirectories using python

Question: I am trying to create a file in a subdirectory, both of which will not exist when the program is first run. When I do this:
newfile = open('abc.txt','w')

It will create abc.txt just fine but the following will cause an error, saying the file or directory does not exist
newfile = open('folder/abc.txt','w')

I tried using os.makedirs to create the directory first but that failed as well raising the same error. What is the best way to create both the folder and file?
Thanks
Comment: How did you use `os.makedirs`?
Answer: >>> import os
>>> os.makedirs('folder')
>>> newfile = open('folder' + os.sep + 'abc.txt', 'w')
>>> newfile.close()
>>> os.listdir('folder')
['abc.txt']

This works for me
Comment: did not know `os.sep`, will start using this.
Comment: yea. is os.sep just a seperator?

It works for me now. Thanks =)
Comment: `print(os.sep)` It varies depending on your operating system.  So it's '/' on real operating systems.
Answer: A couple of things to check:

os.makedirs takes just the path, not the file.  I assume you know this already, but you haven't shown your call to makedirs so I thought I'd mention it.
Consider passing an absolute, not a relative, path to makedirs.  Alternatively, use os.chdir first, to change to a directory in which you know you have write permission.

Hope those help!
Comment: It's `makedirs`, not `mkdirs`.  For just one directory it's `mkdir`
Comment: What do you mean by absolute path? From my understanding the path is hardcoded so if I move the entire directory of the file, everything would be in a mess?
Comment: Instead of `makedirs('folder')`, `makedirs('/path/to/folder')`.


Firebase partial deploy multiple grouped functions

Question: I'm trying to deploy multiple grouped cloud functions at once with the following command
firebase deploy --only functions:groupName.functionName,functions:groupName.anotherFunctionName

However it is simply skipping the deployment of these functions. If I deploy them individually like so
firebase deploy --only functions:groupName.functionName and firebase deploy --only functions:groupName.anotherFunctionName one after the other they are being deployed. I would like to be able to do it in a single command.
Am I missing something or is this functionality simply not built in yet?
EDIT
I also tried the following command with the same result:
firebase deploy --only functions:groupName.functionName,groupName.anotherFunctionName

EDIT
Maybe there is something different about the way our functions are declared in the functions/index.ts:
exports.authentication = require('./authentication')

and in functions/authentication.ts:

exports.createCustomToken = functions
    .region('europe-west1')
    .https
    .onCall(async (data: any, context: any) => {/*...*/})

exports.anotherFunction= functions
    .region('europe-west1')
    .https
    .onCall(async (data: any, context: any) => {/*...*/})

which would lead to the command
firebase deploy --only functions:authentication.createCustomToken,authentication.anotherFunction

Answer: The correct way of deploying multiple single cloud functions that are part of a group is like this:
firebase deploy --only functions:groupName.functionName,functions:groupName.anotherFunctionName

This can now be found in the official documentation, as Rafael Lemos pointed out in his post.
If it doesn't work for you like this, you might need to setup your node environment and the Firebase CLI Tools again. This is a breeze with the Node Version Manager NVM. Installing the latest LTS version and nvm use --lts and the following npm i -g firebase-tools should do the trick.
Answer: Its not working because you are adding the functions: part of the command before every function to be deployed.
As you can see in the documentation, to specify each function within a group you just need to declare it in the format deploy --only functions:groupA.function1,groupB.function4, so applying to your case, if you use the following command it should work:
firebase deploy --only functions:groupName.functionName,groupName.anotherFunctionName

Comment: The group contains many more functions and I only want to deploy 2 or 3 that I'm working on at a time. I'm going to see if this might be a bug with the Firebase support. Thanks for taking your time to look at my question.
Comment: Thank you for your reply @Rafael! I should have specified that I have already tried that. However it also skips the deployment of both functions if I leave out the second `functions:` part.
Comment: Well, in that case you are doing everything correctly. I would say that you should probably reach out to [Firebase Support](https://firebase.google.com/support), as this does not appear to be the expected behavior of Firebase Cli
Comment: Thanks again! I will try that in the weekend. I also updated my question with how I implemented the cloud functions themselves. Maybe you can see if the way the functions are 'grouped' is wrong, as they work fine when deploying separately.
Comment: they appear to be declared correctly, are those 2 the only functions in the group? If so you could deploy the whole group with `firebase deploy --only functions:authentication`.


Error loading DefaultTemplate.xaml in designer

Question: I can't load my projects' DefaultTemplate.xaml file in the designer. (using VS2010 premium, recently reinstalled)
When loading the DefaultTemplate.xaml from the build templates in TFS, I get an error saying that the activity cannot be loaded.
There are errors loading the namespaces. Somehow it cannot find the assemblies needed for TFS.
In the errors list I get about 50 complaints about these namespaces.
I've poked around in it, but never commited any changes. I've tried restoring the original version, but that didn't work.
I've tried replacing the template with the DefaultTemplate.xaml from another project, but I got the same error. I'm at a loss here. How can I fix my VS2010 or template so I can edit it again using the designer?
I can open other projects' DefaultTemplate.xaml files in the designer without any problems.
I suspect that it has to do with some setting in VS2010 or my project somehow not having the right references, but I can't figure out what's wrong or how to solve it.
Comment: What's the error you get? Any design time exception?
Comment: The first error I get says the following: (the others are just like it).
`Error 2 Assembly 'Microsoft.TeamFoundation.Common' was not found. Verify that you are not missing an assembly reference. Also, verify that your project and all referenced assemblies have been built. D:\files\work\Afstuderen Onno Filippo\BuildProcessTemplates\DefaultTemplate.xaml 4 14 Miscellaneous Files`
Answer: Hope this or this will address your issue.
Edit:
If above doesn't work try below, you may get more descriptive error by using this. This works for windows applications on VS2008. I've never tried this with VS2010. You can debug your devenv.exe instance by another devenv.exe. Below are the steps. Give it a go...
1) Start a second instance of visual studio
2) go the the Tools menu, "Attach to process", select the 'devenv.exe' process, and click the 'attach' button.
3) In the Debug/Exceptions menu Turn on exception catching when first thrown (in the Debug->Exceptions menu).

4) Open the designer with the debugger attached
5) The second visual studion will break on your error.
Comment: Thanks for providing the links. I had read them both before posting the question. Unfortunately they do not provide the answer for me. The first isn't really a solution. The solution of the second link refers to the first. I've also read Ewald's suggestion in that thread, but it doesn't seem to deal with the problem at hand.
Comment: @Onno : I've edit my answer. That's the only way AFAIK to find the design time errors. But I am not quite sure how it work in your case.
Comment: Thnx for the suggestion. It  turned out that the solution was the problem. The last changeset worked ok with my laptop. I reverted to the last changeset of my solution on my work pc and it was ok again.


What kind of electrical outlet is this, and how do I replace it?

Question: I have an electrical outlet which hasn't been reliable (the bottom one doesn't always have power unless you jiggle the plug), so I want to change it. I've changed a few plain outlets, but I found something new (to me!) when I went to remove it:

The wires run into the back of the box, as well as attach to the side. What is this called, and how do I remove them?
Comment: Is that green paint on the outlet? In the picture it looks surprisingly similar to the color of copper corrosion amd if this is not paint you have a bit of a mess to clean up.
Comment: @MichaelKaras I checked, I think that's just the flash on my camera. The outlet appears to be clean. Thanks for the heads up.
Answer: The holes in the back accept straight wire and are electrically connected directly to the screws on the side.  The holes are a newer connection method while the screws are more traditional.  Tightening the screws presses contacts against the wires in the holes and holds them in place.
In this case, you have a feed wire going to one and then continuing on to another place from the second.  By the electrical code (at least in Ontario), you're not allowed to do this.  You must connect the feed to the branch and to a short "stub" wire with a marette and then connect that stub wire to your outlet (either at the screw or through the hole in the back).  Some people take short-cuts, however, and connect it this way to avoid the marettes.
Aside from that, I'll note that you have a "split circuit" outlet here.  The top and bottom outlets are on different circuits, perhaps because it's a kitchen outlet and thus they must be split circuit (by the electrical code of Ontario, anyway -- your mileage may vary) or because one outlet (with the red wire) is "switched" by some wall switch.  Make sure you break off the connector tabs between the two sockets on the new outlet so you don't accidentally short the two circuits together.
EDIT: As pointed out by @MichaelKaras, some outlets don't bind the straight-in wires with the screws but have spring-loaded clips that hold the wire and are released by inserting a small screwdriver into the square opening just above the hole.
EDIT: @MPelletier makes a great comment: US multi-wire circuits like that require either a double breaker or that the two breakers be yoked together so that you can't only turn off one. You might consider fixing the breaker box wiring for safety purposes.  That's true in Canada as well.
Comment: @MPelletier - The poke in wires on that outlet are not secured via the screws. Instead they are retained by a spring clip inside that bites into the wire. To release the bite on the wire you have to insert a small flat blade screw driver into the rectangular hole right next to the wire. Press the blade in and possibly tip it to one side and the poke in wire should come free. Repeat for the other two wires.
Comment: When you install the replacement outlet, if you care about secure, reliable, long lasting connections, you should consider using only the binding screws with a properly formed and oriented hook on the wire, rather than the poke-in connections.
Comment: @MPelletier US multi-wire circuits like that require either a double breaker or that the two breakers be yoked together so that you can't only turn off one. You might consider fixing the breaker box wiring for safety purposes. The next person might not be so observant.
Comment: It's in a kitchen alright. And close enough to Ontario (Quebec), so the electrical code might be similar. I tried unscrewing it. The suckers seem stuck in. I might as well snip them. And yes, I did notice the split circuit and had to turn off two switches in the breaker box.
Comment: @MichaelKaras Only after sniping them did I notice the release slots. Big fail on me.
Comment: @BrianWhite - You should consider correcting your answer regarding how the poke in wires are retained on this outlet. Please see my earlier comment to MPelletier. The type of straight in wire retention that you describe is indeed found on some higher current, better quality and GFCI types of outlets but not in this case.
Comment: @MichaelKeras, thanks for pointing that out.  I've been working with GFCI outlets recently and didn't notice the little square openings in the photo.
Comment: It can be a real pain to get the poke-ins to release; you may have ended up snipping them anyway.
Comment: Also, those cables look quite fat - backwiring is only approved for 14 AWG nowadays, though some older devices might still say 12 or 14 AWG. So I would definitely go for the loop and setscrew connection approach.
Comment: Looks like 14/3 wire to me.
Comment: One element which I discovered which might have been revealed by the double set of wires: each plug was on a different breaker, thus independent. Not knowing this, I installed the new outlets, flipped the breaker, and realized I had caused a short circuit. A call to a local electrician and $80 taught me to remove the pin between the two screws on each side. Ouch.
Answer: This receptacle has "stab-in" connectors on it. The wire pushes in and is held in by a spring tab. To remove the wire, get a new piece of wire and strip off about 1-in. of insulation. Hold the wire with a pliers and push it into the rectangular hole below the stab in. That'll release the spring retainer.
These receptacles are known for intermittent failure because the spring retainer heats up and loses its spring tension.
As for whether this receptacle is up to code, here's what I see. It appears from the photo that the bonding tab has been removed from the brass colored screw connectors. This is usually done so either the top or bottom receptacle can be turned on or off by a switch. If the power to the top and bottom (even if one is switched) comes from the same breaker (just flip the breaker and if you lose power to both, then its on the same circuit), then both can share the same neutral (white) wire.
However, if the red and black wires are from different circuits, code requires that you hook the handles of both breakers together. That way, if one breaker overloads, it will turn off the 2nd circuit and not overload the single white wire.


Java find specific class in groovy script

Question: I have a java jar file contain interface named IOperator like this :
public interface IOperator {
    String execute(Map<String, String> parameters);
    boolean isSuccess();
}

now in groovy script (in single file):
public class ClassA {
}

public class ClassB {
}

public class classC implements IOperator {

    @Override
    String execute(Map<String, String> parameters) {
        ClassA classA = new ClassA();
        ClassB classB = new ClassB();
        return null
    }

    @Override
    boolean isSuccess() {
        return false
    }
}

Is there any way scan this groovy script to find that specific class implemented IOperator and invoke execute method ?
Note: I want do it in Java code.
Comment: In the past I've used [`Reflections.getSubTypesOf()`](https://www.javadoc.io/doc/org.reflections/reflections/0.9.10/org/reflections/Reflections.html#getSubTypesOf-java.lang.Class-) to do this.
Comment: you could use service loader https://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html
Comment: I need more details , for example when i used `scriptEngine.eval()` only load first class of script .
Comment: scriptEngine.eval() ? how it's related to your question ?
Answer: Finally i found answer :
public class OperatorManager {
    public static void run(File scriptFile) {
        try {
            GroovyScriptEngineImpl engine = (GroovyScriptEngineImpl) new GroovyScriptEngineFactory().getScriptEngine();
            GroovyClassLoader classLoader = new GroovyClassLoader();

            classLoader.parseClass(new GroovyCodeSource(scriptFile));
            engine.setClassLoader(classLoader);

            Class<?>[] loadedClasses = engine.getClassLoader().getLoadedClasses();

            Class<?> operatorImplClass = Arrays.stream(loadedClasses)
                    .filter(IOperator.class::isAssignableFrom)
                    .findFirst().orElse(null);

            if (operatorImplClass != null) {
                String result = invokeMethod(operatorImplClass);
                System.out.println(result);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String invokeMethod(Class<?> item) {
        try {
            Object instance = item.getConstructor().newInstance();
            Method execute = item.getDeclaredMethod("execute", Map.class);
            return (String) execute.invoke(instance, new Object[]{null});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}


How to make Cairo dock(with opengl) excute only on Gnome-Classic?

Question: I want to make Cairo dock(with opengl) execute in the start-up only on Gnome-Classic but not on other DEs like cinnamon, unity or gnome.How to do that?
Answer:
First create a script which will run cairo-dock based on $DESKTOP-SESSION environment variable. We are going to create the script in ~/.config/autostart directory and naming it cairo.sh

Press Ctrl+H to let nautilus show hidden file. Then Go to your home directory → .config →  autostart directory.
Right Click on the empty space in nautilus. Select Create new document → Empty Document. Name this file cairo.sh.
Double click on the newly created file to open it in gedit text editor (or any other editors of your choice) and paste these lines in it.
if [ "$DESKTOP_SESSION" = "gnome-classic" ]; then
    cairo-dock
fi

Then close the file. Right Click on it, Select Properties.
On the Properties windows, in Permissions tab, Check Allow executing file as a program.

Then create another file in the same directory, i.e ~/.config/autostart with name cairo. (Don't first name it with .desktop extensions for avoiding later hussle opening it)
In that file, copy these lines and paste there, changing the appropriate information like inputting the name of the user in place of "name of user". It is an .desktop file which will be called on startup
[Desktop Entry]
Type=Application
Exec=/home/<name of user>/.config/autostart/cairo.sh
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name[en]=Cairo

Save the file and exit gedit.
Then rename the file adding extension .desktop. To rename, Select the file and Press F2.
After renaming it, Again make the file executable. To do so, Select the file → Select Properties. And in the new window, in Permissions tab, select the checkbox saying Allow the file to run as a program.
Logout and Login to gnome-classic session. Cairo-dock will be started automatically.

If you want to run Cairo on another desktop environment as well, such as ubuntu, you just need to repeat this process, making another set of commands just for that desktop session.  First you would make another cairo.sh, naming it slightly different, such as cairo2.sh.  Then you would open it with nautilus and copy the following lines:
        if [ "$DESKTOP_SESSION" = "ubuntu" ]; then
            cairo-dock
        fi

Then you would save the file and make it executable as before.
Next, you would once again create a .desktop command, also naming it slightly different, such as cairo2.  When copying the command lines, copy the following:
    [Desktop Entry]
    Type=Application
    Exec=/home/<name of user>/.config/autostart/cairo2.sh
    Hidden=false
    NoDisplay=false
    X-GNOME-Autostart-enabled=true
    Name[en]=Cairo

Don't forget to input the user name in place of "name of user" and to make sure the name of the file on the Exec= line is the same as your .sh command for ubuntu, in this case cairo2.sh.
After this just follow the steps as before and when you log in to the appropriate desktop environment, cairo dock should open atuomatically.
Answer: Have a look at the files in /usr/share/xsessions/.
There you'll find ubuntu.desktop, ubuntu-2d.desktop (if you're not on 12.10 already) and gnome-fallback.desktop (maybe also gnome-classic.desktop. I have gnome-shell installed maybe that's where this is from).
Open one of those and you'll see they all have an Exec=gnome-session --session=... line. For gnome-fallback open /usr/share/gnome-session/sessions/gnome-fallback.session.
Now you can

change in /usr/share/gnome-session/sessions/gnome-fallback.session the line
RequiredComponents=gnome-panel;gnome-settings-daemon;
to
RequiredComponents=gnome-panel;gnome-settings-daemon;cairo-dock; (check the executable name!)
change in /usr/share/xsessions/gnome-fallback.desktop the Exec= line, for example
Exec=/home/<yourname>/<yourexecbashscript>
or also copy your current autostart folder .config/autostart/ to a new place
Exec=gnome-session --session=gnome-fallback -a <Newplaceofautostartfolder>
create a all new session. copy and rename both gnome-fallback.session and gnome-fallback.session to their new to their respective places under a new name and adjust your new session like in 1.

The first two of those work but have the disadvantage that they may or may not be overwritten on update (you will have to check, I'm not sure).
In 2. Also if you copy your autostart folder only one of those will be updated depending on which session you are logged into.
So I recommend doing it as shown in 3. Have fun.


Django Admin foreign key drop down from single SQL query

Question: Is there a simple way to get Django to populate the drop downs for a foreign key using a single SQL query?
Consider the following models;
class Site(models.Model):
    code = models.CharField(max_length=5)
    name = models.CharField(max_length=45)

    def __unicode__(self):
        return u'%s - %s' % (self.code, self.name)

class Location(models.Model):
    site = models.ForeignKey(Site)
    name = models.CharField(max_length=45, verbose_name='Location Name')

    def __unicode__(self):
        return u'%s - %s' % (self.site, self.name)

Other models then include models.ForeignKey(Location) and for selecting them these render in the admin.ModelAdmin form as drop down lists.
Using the django-debug-toolbar I can see that I get the following query executed for every Location item with its site_id value when populating the drop downs;
SELECT
  `myApp_site`.`id`,
  `myApp_site`.`code`,
  `myApp_site`.`name`
FROM `myApp_site`
WHERE `myApp_site`.`id` = 1

I can see that this is because I'm using self.site in def __unicode__(self) as I want to see the site with each location.
I tried using list_select_related = True in the admin.ModelAdmin but this is just for the related data on an instance and not for the possible values in the form.
Normally the whole foreign key drop down could be populated from a single query like;
SELECT
  `myApp_location`.`id`,
  `myApp_location`.`name`,
  `myApp_site`.`code`,
  `myApp_site`.`name`
FROM `myApp_site`
INNER JOIN `myApp_site` ON (`myApp_location`.`site_id` = `myApp_site`.`id`)

Can I force the Location model to use select_related() and eliminate the queries?
Is there a better way to include site with the location or reduce the number of queries Django is executing?
Is there a Django anti-pattern I've fallen into? I have several foreign key fields like this and I'm concerned about the number of queries increasing as the database fills up.
Answer: Try the method formfield_for_foreignkey on the AdminClass, there you can overwrite the queryset of the ForeignKey. See example below
def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == 'location':
        kwargs["queryset"] = Location.objects.select_related('site').all()
    return super(ModelWithLocationAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

Comment: Excellent that's just reduced my query count from 193 to 125 and that was for just one db_field! Will also look at using `formfield_for_manytomany` and `formfield_for_choice_field`.


VBA Code: Skipping column entries if already filled

Question: I have 3 Sheets: Sheet1, Sheet2, ...
Sheet1 has all the data, it has a Column R3 to R17 which is what I want.
Sheet2 has three columns, Static Column --- This will have a formula(=+Sheet1!R3 etc till R17) Col1 ---(same as Static Column) Will show the value of R3-R17 (but later only values will remain in this column not the formula) Col2 --- This will be next column where I want values.
On Sheet2, I want is that whenever I press the shortcut for Macro..
It should, copy the formula from that Static Column, paste it in Col1, so Col1 can get entries from Sheet1, R3-R17 column.....
then when I press the shortcut button again,
It should now copy the formula from the static column, see if Col1 is filled, if filled, put it on Col2 so Col2 now can get entries from Sheet1 (R3-R17) and keep only the REAL values in Col1.
Then when I press the shortcut button again,
It should now copy the formula from the static column, see if Col1,Col2 is filled, if filled, put it on Col3 so Col3 can get entries from Sheet1 (R3-R17) and keep only the REAL values in Col2.
I am almost half done, but cant make the macro switch to the next column ..
Sub PlayerSheet()
    Dim LC As Long, r As Range
    Set r = Application.InputBox("click in the column to copy", Type:=8)
    LC = r.Column
    Columns(LC + 1).Insert
    Columns(LC).Copy
    Cells(1, LC + 1).PasteSpecial Paste:=xlPasteFormulas
    Columns(LC).Copy
    Cells(1, LC).PasteSpecial Paste:=xlPasteValues
  End Sub

Comment: Add your tried code (as you half done) and tell us about your problem on that ;).
Answer: I dont want to answer this question... but this is my first time with this site, i dont see the option of putting additional information without editing my original question...
But here is the code :
    Sub PlayerSheet()
    Dim LC As Long, r As Range
    Set r = Application.InputBox("click in the column to copy", Type:=8)
     LC = r.Column
     Columns(LC + 1).Insert
     Columns(LC).Copy
       Cells(1, LC + 1).PasteSpecial Paste:=xlPasteFormulas
      Columns(LC).Copy
      Cells(1, LC).PasteSpecial Paste:=xlPasteValues
      End Sub

Now, it does not do what i intend it to do ... but my work is half done.
What it does is, it asks me to select the cell i want to copy.. and then copy the whole column and put it in the next column with the formulas and then, paste back only the "values" in the column where it copied it from.
What i want is that it should be fully automatic, it should not ask me to select the cell which i want to copy. It should automatically select the last column, copy it, paste it in next with formulas and then paste only the values in the column where it copied it from.
Comment: you have an `edit` grayed text below your questions tags, just click it and add your code in your question ;).
Comment: I have done that. But marked it as in my answer, can you see the whole thread and let me know how can i make the code better.
Comment: You can now `delete` this answer ;).


Dataframe - reshape dataframe from wide to long

Question: I have a dataframe like:

id
item_1
item_2
item_3
price_1
price_2
price_3
note

user1
apple
orange
water
2.00
1.50
0.80
nothing

user2
banana
milk
apple
0.50
3.50
2.00
1 bag

and I want to make it into something like:

id
item
price
note
number

user1
apple
2.00
nothing
1

user1
orange
1.50
nothing
2

user1
water
0.80
nothing
3

user2
banana
0.50
1 bag
1

user2
milk
3.50
1 bag
2

user2
apple
2.00
1 bag
3

Is it possible to do it without having to manually input those "item_"s and "price_" (since there will be quite a few of them)?
Comment: Look at pd.wide_to_long and with stubs of ['item_', 'price_'].
Answer: Use wide_to_long with specified parameters:
df = pd.wide_to_long(df,
                     stubnames=['item','price'],
                     i=['id','note'],
                     j='number', sep='_').reset_index()
print (df)
      id     note  number    item  price
0  user1  nothing       1   apple    2.0
1  user1  nothing       2  orange    1.5
2  user1  nothing       3   water    0.8
3  user2    1 bag       1  banana    0.5
4  user2    1 bag       2    milk    3.5
5  user2    1 bag       3   apple    2.0

Or convert all not _ columns first, split all columns with _ and reshape by DataFrame.stack:
df1 = df.set_index(['id','note'])
df1.columns = df1.columns.str.split('_', expand=True)
df1 = df1.rename_axis((None, 'number'), axis=1).stack().reset_index()
print (df1)
      id     note number    item  price
0  user1  nothing      1   apple    2.0
1  user1  nothing      2  orange    1.5
2  user1  nothing      3   water    0.8
3  user2    1 bag      1  banana    0.5
4  user2    1 bag      2    milk    3.5
5  user2    1 bag      3   apple    2.0

Comment: thanks so much @jezrael! the second method works perfectly! but for some reason, wide_to_long gives me an empty df...


Changes of sign of the rows of a matrix

Question: I have a matrix with three columns (say), for example:
M0 <- rbind(
  c(1, 2, 3),
  c(4, 5, 6)
)

I want to generate all changes of sign of every row of the matrix. Here the desired output is:
      [,1] [,2] [,3]
 [1,]   -1   -2   -3
 [2,]    1   -2   -3
 [3,]   -1    2   -3
 [4,]    1    2   -3
 [5,]   -1   -2    3
 [6,]    1   -2    3
 [7,]   -1    2    3
 [8,]    1    2    3
 [9,]   -4   -5   -6
[10,]    4   -5   -6
[11,]   -4    5   -6
[12,]    4    5   -6
[13,]   -4   -5    6
[14,]    4   -5    6
[15,]   -4    5    6
[16,]    4    5    6

Here is my solution:
signs <- as.matrix(expand.grid(c(-1,1),c(-1,1),c(-1,1)))

M1 <- vapply(1:nrow(M0),
             function(i) t(signs %*% diag(M0[i,])),
             array(0, dim = c(3,8)))

t(array(M1, dim = c(3, 8*dim(M1)[3])))
#       [,1] [,2] [,3]
#  [1,]   -1   -2   -3
#  [2,]    1   -2   -3
#  [3,]   -1    2   -3
#  [4,]    1    2   -3
#  [5,]   -1   -2    3
#  [6,]    1   -2    3
#  [7,]   -1    2    3
#  [8,]    1    2    3
#  [9,]   -4   -5   -6
# [10,]    4   -5   -6
# [11,]   -4    5   -6
# [12,]    4    5   -6
# [13,]   -4   -5    6
# [14,]    4   -5    6
# [15,]   -4    5    6
# [16,]    4    5    6

Do you have a more elegant solution ?
Moreover, there's one caveat with this solution: if there are some zeros in a row of the source matrix, then this solution generates some duplicates (because -0 = 0). I remove them with mgcv::uniqueCombs. Do you have a solution which doesn't generate some duplicates in the case when there are some zeros, without resorting to a "unique" function ?

EDIT: Benchmark of solutions
Let's compare the performance of three given solutions.
# @Aurèle
changesOfSign1 <- function(M){
  signs <- as.matrix(expand.grid(rep(list(c(1, -1)), ncol(M))))
  out <- matrix(c(apply(M, 1, `*`, c(t(signs)))), ncol = ncol(M), byrow = TRUE)
  out[!duplicated(out),]
}

# @989
changesOfSign2 <- function(M){
  signs <- as.matrix(expand.grid(rep(list(c(1, -1)), ncol(M))))
  # signs for each row in the resultant matrix
  m1 <- signs[rep(1:nrow(signs), times = nrow(M)), ]
  # values for each row in the resultant matrix
  m2 <- M[rep(1:nrow(M), each = nrow(signs)), ]
  #
  res <- m1*m2
  res[!duplicated(res), ]
}

# @DS_UNI
changesOfSign3 <- function(M){
  as.matrix(do.call(rbind, apply(M, 1, function(row){
    expand.grid(lapply(row, function(x) if(x==0) 0 else c(-x,x)))
  })))
}

# benchmark ####
library(microbenchmark)

benchmark <- function(nrows, ncols){
  M0 <- matrix(rpois(nrows*ncols, 3), nrow = nrows, ncol = ncols)
  microbenchmark(
    changesOfSign1 = changesOfSign1(M0),
    changesOfSign2 = changesOfSign2(M0),
    changesOfSign3 = changesOfSign3(M0),
    times = 1000
  )
}

benchmark(nrows = 20, ncols = 3)
# Unit: microseconds
#           expr      min        lq      mean   median       uq       max neval cld
# changesOfSign1  493.990  542.4075  639.2895  577.884  642.589  7912.316  1000  a
# changesOfSign2  475.248  522.7730  618.2550  554.232  608.005  7346.927  1000  a
# changesOfSign3 3506.123 3757.8030 4380.9164 3928.491 4464.204 22603.045  1000   b

benchmark(nrows = 20, ncols = 10)
# Unit: milliseconds
#           expr      min       lq     mean   median       uq      max neval cld
# changesOfSign1 30.09545 35.95840 46.39465 41.37086 49.56855 344.2176  1000  b
# changesOfSign2 41.20642 47.99532 58.59760 52.83705 60.85200 349.4958  1000   c
# changesOfSign3 13.56397 15.21439 21.34205 18.21113 22.34445 319.3990  1000 a

@Aurèle and @989 win when there are 3 columns. @DS_UNI wins when there are 10 columns.
We can improve @DS_UNI's solution with data.table:
# @DS_UNI with data.table
library(data.table)
changesOfSign4 <- function(M){
  as.matrix(rbindlist(apply(M, 1, function(row){
    do.call(function(...) CJ(..., sorted = FALSE),
            lapply(row, function(x) if(x==0) 0 else c(-x,x)))
  })))
}

Comment: There are 64 combinations for the signs of the 6 elements (beside the case of an element with value 0).
Comment: @jogo I want the changes of sign for each row, separately. So there are 8 combinations for each row.
Answer: matrix(c(apply(M0, 1, `*`, c(t(signs)))), ncol = ncol(M0), byrow = TRUE)

No claims about elegance :)
Answer: How about this:
M0 <- rbind(
  c(1, 2, 3),
  c(4, 5, 6)
)

signs <- expand.grid(rep(list(c(1, -1)), ncol(M0)))

do.call(rbind, apply(M0, FUN = `*`, signs, MARGIN = 1))

EDIT:
Ok I gave up on elegance, and I do prefer the one-liner solution by @Aurèle, however I'm editing the answer to get at least the desired output, and on the plus side it works with zero :P
my_fun <- function(row){
  expand.grid(
    lapply(row,
           function(x) {
             if(x != -x)
               return(c(x, -x))
             else
               return(x)}))}

do.call(rbind, apply(M0, FUN = my_fun, MARGIN = 1))

Comment: Ah you beat me. I've just posted a solution which is the same as your edit. Note that you don't need to do `as.list(row)`.
Comment: That does not generate the desired output (the order is not preserved).
Comment: Oops! sorry about that
Comment: I think I will delete my answer and accept yours, since you beat me.
Comment: you're right! I'll change the `as.list` thing.  And the reason why the long function instead of `unique` is because I took the sentence : `without resorting to a "unique" function` as a challenge :D
Answer: I would suspect this to be fast (no loop):
signs <- as.matrix(expand.grid(c(-1,1),c(-1,1),c(-1,1)))

# signs for each row in the resultant matrix
m1 <- signs[ rep( 1:nrow(signs), times = nrow(M0) ), ]

# values for each row in the resultant matrix
m2 <- M0[ rep( 1:nrow(M0), each = nrow(signs) ), ]

res <- m1*m2

      # Var1 Var2 Var3
 # [1,]   -1   -2   -3
 # [2,]    1   -2   -3
 # [3,]   -1    2   -3
 # [4,]    1    2   -3
 # [5,]   -1   -2    3
 # [6,]    1   -2    3
 # [7,]   -1    2    3
 # [8,]    1    2    3
 # [9,]   -4   -5   -6
# [10,]    4   -5   -6
# [11,]   -4    5   -6
# [12,]    4    5   -6
# [13,]   -4   -5    6
# [14,]    4   -5    6
# [15,]   -4    5    6
# [16,]    4    5    6

To deal with duplicated rows caused by zeros:
res[ !duplicated(res), ]

Comment: Thanks. See the benchmarks in my edited question if you are interested.
Answer: High, is this elegant enough :)
x <- 1:3

signs <- as.matrix(expand.grid(x = c(-1,1), y = c(-1, 1), z = c(-1, 1)))

    t(x * t(signs))
      x  y  z
[1,] -1 -2 -3
[2,]  1 -2 -3
[3,] -1  2 -3
[4,]  1  2 -3
[5,] -1 -2  3
[6,]  1 -2  3
[7,] -1  2  3
[8,]  1  2  3

Comment: Please, add the packages you are using. Still better, offer a solution without external packages if they are not needed (as in your case).
Comment: Ok, but how would apply this to each row and `rbind` the results ? (see the desired output in my post)

Changes of sign of the rows of a matrix


How to Access each element of a Structure with Pointer in C++

Question: I am having problems with accessing individual structure elemnsts. How to output each structure element using pointer?
#include <iostream>

using namespace std;

struct student{
int rollno;
float marks;
char name[45];
};

int main(){
student s1[2]={{1,50.23,"abc"},{2,65.54,"def"}};

for(int j=0;j<2;j++){
    cout<<"Output Rollno, Marks and Name Using Pointer"
}
return 0;
}

Answer: Just assign the address to a pointer, and print it.
student *ptr=s1; // or &s1[0], instead.
cout<<ptr->rollno;

Comment: thanks... one general question, How to print Code in stackoverflow Comment??
Comment: wrap it in "`" (the key in the left of the numbers, above the letters)
Answer: You don't have a pointer.
To output the fields, you do what you'd do in any other situation, e.g.:
cout << "marks = " << s1[j] << "\n";

Comment: Can u show the Syntax, treating s[] as pointer. eg: 'cout<<*(s1+j)'
Answer: your loop should be something like:
for(int j=0;j<2;j++){
    cout<<"Rollno:" << s1[j].rollno << " Marks:" << s1[j].marks << " Name:" << s1[j].name << endl;
}

or, using pointer (i.e. array + offset):
for(int j=0;j<2;j++){
    cout<<"Rollno:" << (s1+j)->rollno << " Marks:" << (s1+j)->marks << " Name:" << (s1+j)->name << endl;
}

Answer: If you wanted to be real raw:
void* ptr = &s1[0];

for(int j=0;j<2;j++){
    cout<< (int)*ptr << "," << (float)*(ptr+sizeof(int)) << "," << (char*)*(ptr+sizeof(int)+sizeof(float)) << endl;
}

Answer: char* p = (char* )s1;

for(int j=0;j<2;j++){
    int* a = (int*) p;
    cout << *a  << " ";
    a++;
    float* b = (float*) a;
    cout << *b  << " ";
    b++;
    char* c = (char*) b;
    cout << c << " ";
    c = c + 45 + strlen(c);
    cout<<endl;
    p = c;
}


Using LINQ to create a List where T : someClass

Question: This is related to a prior question of mine C# Generic List conversion to Class implementing List<T>
I have the following code:
public abstract class DataField
{
    public string Name { get; set; }
}

public class DataField<T> : DataField
{
    public T Value { get; set; }
}

public static List<DataField> ConvertXML(XMLDocument data) {
     result = (from d in XDocument.Parse(data.OuterXML).Root.Decendendants()
                      select new DataField<string>
                      {
                          Name = d.Name.ToString(),
                          Value = d.Value
                      }).Cast<DataField>().ToList();
    return result;
}

This works however I would like to be able to modify the select portion of the LINQ query to be something like this:
select new DataField<[type defined in attribute of XML Element]>
{
  Name = d.Name.ToString(),
  Value = d.Value
}

Is this just a poor approach? is it possible?  Any suggestions?
Comment: I feel like you're never going to know what subclass of DataField you have anyways, so why not just use `class DataField{string name; object value;}` ?
Comment: Sure, but then you'll have to parse your data each time before you use it. If you pre-parse the data into the objects, and then store them in  the data field, you can just cast them when you're ready to use them. This is what ADO.NET does with DataReader (although DataReader delays execution of the parsing until the column values are needed). For instance, `if(myField.Value is DateTime { /* do that date thing */ }` or `if(myField.Name == "importantDateThing") { var date = (DateTime)myField.Value; /* do importanty date thing */ }`
Comment: I dont really want to reference all values as object. If I was to take a similar approach, it would seem easier to just use class DataField{string name; string type; string value}.
Comment: @xixonia....yes I understand that.  But Casting like that feels wrong to me.  I know the type and have the ability to construct a list of different types.
Comment: Here's the thing though, you're STILL going to be casting. You're either checking the type of the DataField and casting, or you're checking the type of the object and casting.
Comment: Basically my motivation is to place XML in a List where T can be a number of different structures.   I know that simply using List works.  I started out that way but it seems to me that it should be possible to define for each item in the list what T is and then use it without casting.
Comment: So DataField is an abstract class with some useful abstract methods that *will* be implemented differently in subclasses?
Comment: @xixonia....yes but I was trying to keep it simple in the example.
Comment: What kind of operations are you going to do with the resulting `DataField`s?
Comment: @svick ... Primarily Data Mapping between two similar objects in the same structure.
Answer: Here is a working solution: (You must specify fully qualified type names for your Type attribute otherwise you have to configure a mapping somehow...)
I used the dynamic keyword, you can use reflection to set the value instead if you do not have C# 4...
public static void Test()
{
    string xmlData = "<root><Name1 Type=\"System.String\">Value1</Name1><Name2 Type=\"System.Int32\">324</Name2></root>";

    List<DataField> dataFieldList = DataField.ConvertXML(xmlData);

    Debug.Assert(dataFieldList.Count == 2);
    Debug.Assert(dataFieldList[0].GetType() == typeof(DataField<string>));
    Debug.Assert(dataFieldList[1].GetType() == typeof(DataField<int>));
}

public abstract class DataField
{
    public string Name { get; set; }

    ///
    /// Instanciate a generic DataField<T> given an XElement
    ///
    public static DataField CreateDataField(XElement element)
    {
        //Determine the type of element we deal with
        string elementTypeName = element.Attribute("Type").Value;
        Type elementType = Type.GetType(elementTypeName);

        //Instanciate a new Generic element of type: DataField<T>
        dynamic dataField = Activator.CreateInstance(typeof(DataField<>).MakeGenericType(elementType));
        dataField.Name = element.Name.ToString();

        //Convert the inner value to the target element type
        dynamic value = Convert.ChangeType(element.Value, elementType);

        //Set the value into DataField
        dataField.Value = value;

        return dataField;
    }

    ///
    /// Take all the descendant of the root node and creates a DataField for each
    ///
    public static List<DataField> ConvertXML(string xmlData)
    {
        var result = (from d in XDocument.Parse(xmlData).Root.DescendantNodes().OfType<XElement>()
                      select CreateDataField(d)).ToList();

        return result;
    }
}

public class DataField<T> : DataField
{
    public T Value { get; set; }
}

Answer: You cannot do this easily in C#. The generic type argument has to be specified at compile time. You can use reflection to do otherwise.
int X = 1;
Type listype = typeof(List<>);
Type constructed = listype.MakeGenericType(  X.GetType()  );
object runtimeList = Activator.CreateInstance(constructed);

Here we have just created a List<int>. You can do it with your type.
Answer: Different instances of a generic class are actually different classes.
I.e. DataField<string> and DataField<int> are not the same class at all(!)
This means, that you can not define the generic parameter during run-time, as it has to be determined during compile-time.
Comment: That's not completely right. You can create generic type at runtime using reflection. What you say is more like how C++ templates behave.
Comment: In addition, DataField and DataField can still inherit from the same parent class, and therefore they can implement abstract methods to be called via a parent class reference. That was stated really badly, but you get the idea.
Answer: I would say this is a poor approach. In reality, even after you parse your XML file, you're not going to know what types of "DataFields" you have. You might as well just parse them as objects.
However, if you know that you're only ever going to have x number of types, you can do like so:
var Dictionary<string, Func<string, string, DataField>> myFactoryMaps =
{
    {"Type1", (name, value) => { return new DataField<Type1>(name, Type1.Parse(value); } },
    {"Type2", (name, value) => { return new DataField<Type2>(name, Type2.Parse(value); }  },
};

Comment: Never underestimate the power of abstraction. :)
Answer: Termit's answer is certainly excellent. Here is a little variant.
     public abstract class DataField
        {
                public string Name { get; set; }
        }

        public class DataField<T> : DataField
        {
                public T Value { get; set; }
                public Type GenericType { get { return this.Value.GetType(); } }
        }

        static Func<XElement , DataField> dfSelector = new Func<XElement , DataField>( e =>
        {
                string strType = e.Attribute( "type" ).Value;
                //if you dont have an attribute type, you could call an extension method to figure out the type (with regex patterns)
                //that would only work for struct
                Type type = Type.GetType( strType );
                dynamic df = Activator.CreateInstance( typeof( DataField<>).MakeGenericType( type ) );

                df.Name = e.Attribute( "name" ).Value;
                dynamic value = Convert.ChangeType( e.Value , type );
                df.Value = value;
                return df;
        } );

        public static List<DataField> ConvertXML( string xmlstring )
        {
                var result = XDocument.Parse( xmlstring )
                                        .Root.Descendants("object")
                                        .Select( dfSelector )
                                        .ToList();
                return result;
        }

        static void Main( string[] args )
        {
                string xml = "<root><object name=\"im1\" type=\"System.String\">HelloWorld!</object><object name=\"im2\" type=\"System.Int32\">324</object></root>";

                List<DataField> dfs = ConvertXML( xml );
        }

Answer: you can create generic type by reflection
    var instance = Activator.CreateInstance( typeof(DataField)
                         .MakeGenericType(Type.GetType(typeNameFromAttribute) );
    // and here set properties also by reflection

Answer: @Termit and @Burnzy put forward good solutions involving factory methods.
The problem with that is that you're loading up your parsing routine with a bunch of extra logic (more testing, more errors) for dubious returns.
Another way to do it would be to use a simplified string-based DataField with typed read methods - the top answer for this question.
An implementation of a typed-value method that would be nice but only works for value types (which does not include strings but does include DateTimes):
public T? TypedValue<T>()
    where T : struct
{
    try { return (T?) Convert.ChangeType(this.Value, typeof(T)); }
    catch { return null; }
}

I'm assuming that you're wanting to use the type information to do things like dynamically assigning user-controls to the field, validation rules, correct SQL types for persistence etc.
I've done a lot of this sort of thing with approaches that seem a bit like yours.
At the end of the day you should seperate your metadata from your code - @Burnzy's answer chooses the code based on the metadata (a "type" attribute of the DataField element) and is a very simple example of this.
If you're dealing with XML, XSDs are a very useful and extensible form of metadata.
As far as what you store each field's data in - use strings because:

they are nullable
they can store partial values
they can store invalid values (makes telling the user to sort their act out more transparent)
they can store lists
special cases won't invade unrelated code because there aren't any
learn regular expressions, validate, be happy
you can convert them to stronger types really easily

I found it very rewarding to develop little frameworks like this - it is a learning experience and you'll come out understanding a lot more about UX and the reality of modelling from it.
There are four groups of test cases that I would advise you to tackle first:

Dates, Times, Timestamps (what I call DateTime), Periods (Timespan)

in particular, make sure you test having a different server locality from the client's.

lists - multi-select foreign keys etc
null values
invalid input - this generally involves retaining the original value

Using strings simplifies all this greatly because it allows you to clearly demarcate responsibilities within your framework.  Think about doing fields containing lists in your generic model - it gets hairy rather quickly and it is easy to end up with a special case for lists in pretty much every method.  With strings, the buck stops there.
Finally, if you want a solid implementation of this sort of stuff without having to do anything much, consider DataSets - old school I know - they do all sorts of wonderful things you wouldn't expect but you do have to RTFM.
The main downfall of that idea would be that it isn't compatible with WPF data binding - though my experience has been that reality isn't compatible with WPF data binding.
I hope I interpreted your intentions correctly - good luck either way  :)
Answer: Unfortunately, there no inheritance relation between C<T> and C<string> for instance.
However, you can inherit from a common non-generic class and in addition to this implement a generic interface.
Here I use explicit interface implementation in order to be able to declare a Value property typed as object, as well as a more specifically typed Value property.
The Values are read-only and can only be assigned through a typed constructor parameter. My construction is not perfect, but type safe and doesn't use reflection.
public interface IValue<T>
{
    T Value { get; }
}

public abstract class DataField
{
    public DataField(string name, object value)
    {
        Name = name;
        Value = value;
    }
    public string Name { get; private set; }
    public object Value { get; private set; }
}

public class StringDataField : DataField, IValue<string>
{
    public StringDataField(string name, string value)
        : base(name, value)
    {
    }

    string IValue<string>.Value
    {
        get { return (string)Value; }
    }
}

public class IntDataField : DataField, IValue<int>
{
    public IntDataField(string name, int value)
        : base(name, value)
    {
    }

    int IValue<int>.Value
    {
        get { return (int)Value; }
    }
}

The list can then be declared with the abstract base class DataField as generic parameter:
var list = new List<DataField>();
switch (fieldType) {
    case "string":
        list.Add(new StringDataField("Item", "Apple"));
        break;
    case "int":
        list.Add(new IntDataField("Count", 12));
        break;
}

Access the strongly typed field through the interface:
public void ProcessDataField(DataField field)
{
    var stringField = field as IValue<string>;
    if (stringField != null) {
        string s = stringField.Value;
    }
}

Answer: While the other questions mostly proposed an elegant solution to convert your XML elements to a generic class instance, I'm going to deal with the consequences of taking the approach to model the DataField class as a generic like DataField<[type defined in attribute of XML Element]>.
After selecting your DataField instance into the list you want to use these fields. Her polymorphism comes into play! You want to iterate your DataFields an treat them in a uniform way. Solutions that use generics often end up in a weird switch/if orgy since there is no easy way to associate behavior based on the generic type in c#.
You might have seen code like this (I'm trying to calculate the sum of all numeric DataField instances)
var list = new List<DataField>()
{
    new DataField<int>() {Name = "int", Value = 2},
    new DataField<string>() {Name = "string", Value = "stringValue"},
    new DataField<float>() {Name = "string", Value = 2f},
};

var sum = 0.0;

foreach (var dataField in list)
{
    if (dataField.GetType().IsGenericType)
    {
        if (dataField.GetType().GetGenericArguments()[0] == typeof(int))
        {
            sum += ((DataField<int>) dataField).Value;
        }
        else if (dataField.GetType().GetGenericArguments()[0] == typeof(float))
        {
            sum += ((DataField<float>)dataField).Value;
        }
        // ..
    }
}

This code is a complete mess!
Let's go try the polymorphic implementation with your generic type DataField and add some method Sum to it that accepts the old some and returns the (possibly modified) new sum:
public class DataField<T> : DataField
{
    public T Value { get; set; }
    public override double Sum(double sum)
    {
       if (typeof(T) == typeof(int))
       {
           return sum + (int)Value; // Cannot really cast here!
       }
       else if (typeof(T) == typeof(float))
       {
           return sum + (float)Value; // Cannot really cast here!
       }
       // ...

       return sum;
    }
}

You can imagine that your iteration code gets a lot clearer now but you still have this weird switch/if statement in you code. And here comes the point: Generics do not help you here it's the wrong tool at the wrong place. Generics are designed in C# for giving you compile time type safety to avoid potential unsafe cast operations. They additionally add to code readability but that's not the case here :)
Let's take a look at the polymorphic solution:
public abstract class DataField
{
    public string Name { get; set; }
    public object Value { get; set; }
    public abstract double Sum(double sum);
}

public class IntDataField : DataField
{
    public override double Sum(double sum)
    {
        return (int)Value + sum;
    }
}

public class FloatDataField : DataField
{
    public override double Sum(double sum)
    {
        return (float)Value + sum;
    }
}

I guess you will not need too much fantasy to imagine how much adds to your code's readability/quality.
The last point is how to create instances of these classes. Simply by using some convention TypeName + "DataField" and Activator:
Activator.CreateInstance("assemblyName", typeName);

Short Version:
Generics is not the appropriate approach for your problem because it does not add value to the handling of DataField instances. With the polymorphic approach you can work easily with the instances of DataField!
Answer: It's not impossible as you can do this with reflection. But this isn't what generics were designed for and isn't how it should be done. If you're going to use reflection to make the generic type, you may as well not use a generic type at all and just use the following class:
public class DataField
{
    public string Name { get; set; }
    public object Value { get; set; }
}

Answer: You'll need to insert the logic for determining the data type from your XML and add all the types you need to use but this should work:
            result = (from d in XDocument.Parse(data.OuterXML).Root.Descendants()
                      let isString = true //Replace true with your logic to determine if it is a string.
                      let isInt = false   //Replace false with your logic to determine if it is an integer.
                      let stringValue = isString ? (DataField)new DataField<string>
                      {
                          Name = d.Name.ToString(),
                          Value = d.Value
                      } : null
                      let intValue = isInt ? (DataField)new DataField<int>
                      {
                          Name = d.Name.ToString(),
                          Value = Int32.Parse(d.Value)
                      } : null
                      select stringValue ?? intValue).ToList();


C# Enabling/Disabling buttons using an array, Win forms/MVP

Question: i have an array of buttons [42] in a c# winforms desktop application :
private Button[] _tabButton = new Button[]{button00,button01,/*...,*/button41};

Than, when i called the "Initiate" methode i just do :
for(int i=0;i<_tabButton.Length;i++)
      {
       _tabButton[i].enabled = false;
      }

that was pretty simple and logic.
Now, am newbie in MVP/MVC, but I did a little work in the code...
i create an Interface and implement it ,to get :
public bool Button_0 { get => button00.Enabled; set => button00.Enabled = value; }
   //...
   public bool Button_41 { get => button41.Enabled; set => button41.Enabled = value; }

also :
 private bool[] _arrayButton_bool;// = new bool[42];//an array of Button_0,Button_1...

So,my problem is : How to enable/disable the 42 Buttons, using boolean variables "Button_0 ... Button_41" inside the boolean array ".
If i say :
 `_arrayButton_bool = {Button_0,Button_1,...,Button_41};
 //... inside intiate methode :
  for(int i=0;i<_arrayButton_bool.Length;i++)
      {
       _arrayButton_bool[i].enabled = false;
      }`

that will affect "_arrayButton_bool[0]", not the variable:"Button_0", i know my question is ambiguous, am not so good in english,but please i did my best to have a little help. thanks.
Comment: Your approach is fundamentally wrong, you should first explain why you (think you need) to do this.
Comment: have you tried LINQ/Lambda expressions ?
Comment: you need to put them in list and then modify it using LINQ/Lambda expressions.
Comment: Sikander Hayyat, i'll try with Linq/Lambda expression later, for now i am trying with Michał Turczyn answer and it's what am looking for, thank you.
Comment: yes , there is a better approach , also i guess i don't explain what i need in good way, thank you  @aybe.
Answer: You define setters like :
public bool Button_0
{
    get => button00.Enabled;
    set => button00.Enabled = value;
}

so Burron_0 = true; would enable the  button00 button. But the problem is, this is setter, so under the hood it is method, which you cannot simply put in an array. Trying to create array of those properties would only invoke each getter and provide bool value.
So it is impossible what you are asking. Cleanest way I can think of is to define method:
private void SetButtonsEnabledProperty(bool enabled)
{
    Button_0 = enabled;
    // through to
    Button_41 = enabled;
}


Conversion of table to Excel from JavaScript

Question: I need to export my EditorGridPanel grid data to excel without sending any data to server-side, cross browser and cross platform solution that will work in ie6 and ie7.  Any pure JavaScript solution is good as well!
So far i have found only data URI solution which is great but ie supports it only from 8-th version. Also there is a possibility to export through ActiveX component but it is not what i want since it makes my app depended to Windows and MSOffice.
Can you recommend me any solution ?
Answer: You could export to csv and then import that file into Excel , Open Office or Numbers?
Answer: Well after a wile of thinking i understood that this question is stupid because due to sandbox policy of js there is no possibility to export it directly from js.
As i said earlier i found some partial ways to do that:
ActiveX export  and  Data URI scheme
Answer: Here is a solution with a server-side call, but no server-side code writting.
http://code.google.com/p/gwt-table-to-excel/
Comment: nice tool, but i needed exactly xls :)
Answer: The class below do that without server side.
<code>public class TableToExcel {
    public static final <T> void save(final CellTable<T> table, String filename) {
        final AnchorElement a = Document.get().createAnchorElement();
        a.setHref("data:application/vnd.ms-excel;base64," + base64(table.getElement().getString()));
        a.setPropertyString("download", (filename.endsWith(".xls") || filename.endsWith(".xlsx")) ? filename : filename + ".xls");

        Document.get().getBody().appendChild(a);
        Scheduler.get().scheduleEntry(new ScheduledCommand() {
            @Override
            public void execute() {
                click(a);
                a.removeFromParent();
            }
        });
    }

    private static native void click(Element elem) /*-{
        elem.click();
    }-*/;

    public static native String base64(String data) /*-{
        return btoa(data);
    }-*/;
}
</code>


java.lang.IllegalStateException: ViewTreeLifecycleOwner not found from androidx.constraintlayout.widget.ConstraintLayout

Question: When I try to insert Compose in overlay(draw over other apps) with XML I get this exception:
java.lang.IllegalStateException: ViewTreeLifecycleOwner not found from androidx.constraintlayout.widget.ConstraintLayout{d596746 V.E...... ......ID 0,0-0,0}

But without overlay(in activity) it works normal. Does anyone know how to resolve? I already updated AppCompat library to 1.3.0
My XML code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black">
    <androidx.compose.ui.platform.ComposeView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/compose_view"/>
</androidx.constraintlayout.widget.ConstraintLayout>

My Overlay code:
mParams = WindowManager.LayoutParams(
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
    PixelFormat.TRANSLUCENT
)
layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
mView = layoutInflater.inflate(R.layout.power_overlay, null)
mParams!!.gravity = Gravity.CENTER
mWindowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
mWindowManager.addView(mView, mParams)

Comment: See https://stackoverflow.com/q/65755763/115145 and https://stackoverflow.com/a/66447195/115145 for an example of using Compose outside of a activity or fragment (in that case, an IME).
Comment: Update androidx.appcompat:appcompat to latest version 1.3.0
Comment: I think you mean ConstraintLayout in the first line, instead of Compose; consider removing the Android-jetpack-compose tag, please
Comment: @MuthuramanSundararaj already did this.
Comment: java.lang.IllegalStateException: means your trying to do something when its not ready, thats why it works when you remove it, you need to find out the appropriate moment to do this. can you try in onResume ?
Comment: Does this answer your question? [ViewTreeLifecycleOwner not found from DecorView@2da7146\[MyActivity\]](https://stackoverflow.com/questions/66382502/viewtreelifecycleowner-not-found-from-decorview2da7146myactivity)
Answer: For me it was because I had not included the appcompat library and my activity inherited from Activity instead of AppCompatActivity. The problem resolved by adding the library:
implementation("androidx.appcompat:appcompat:1.3.1")

and inheriting from AppCompatActivity:
class MyActivity: AppCompatActivity() {
  ...
}

Answer: For me, upgrade androidx.appcompat:appcompat from 1.0.0 to 1.4.1, the problem solved.
The fragment:
class Xxx : Fragment() {

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    val view = inflater.inflate(R.layout.fragment_xxx, container, false)

    view.findViewById<ComposeView>(R.id.compose_view).apply {
        setViewCompositionStrategy(
            ViewCompositionStrategy.DisposeOnLifecycleDestroyed(viewLifecycleOwner)
        )
        setContent {
            // compose
        }
    }
    return view
}

The xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

    <androidx.compose.ui.platform.ComposeView
        android:id="@+id/compose_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

Answer: I was working with drawing overlay from foregound service and for me problem was  here:
contentView = ComposeView(this).apply {
    setViewTreeSavedStateRegistryOwner(this@ForegroundService)
    setViewTreeLifecycleOwner(this@ForegroundService) // <-- missing line.
    setContent {
        OverlayComposeUi()
    }
}

Answer:
Ensure that your constraint layout is updated to latest version in app level build.gradle file.

dependencies { ...
 implementation 'androidx.constraintlayout:constraintlayout:1.3.x'

To be sure, search & Replace ALL your xml tag names

<androidx.constraintlayout.ConstraintLayout>

 //with ->

<androidx.constraintlayout.widget.ConstraintLayout>

in every place CTRL + SHIFT + R
_

And inside gradle.properties add these:

 android.enableJetifier=true
 android.useAndroidX=true

Clear out/Invalidate Caches and Restart Android Studio.

File → Invalidate Caches / Restart → Invalidate and Restart
Answer: I wrote this code and it works.
class AndroidComposeDialog<T>(
    private val activity: T,
    private val content: @Composable () -> Unit
) : Dialog(activity) where T : Context, T : androidx.lifecycle.LifecycleOwner, T : ViewModelStoreOwner, T : SavedStateRegistryOwner, T : OnBackPressedDispatcherOwner {

    private fun initViewTreeOwners() {
        val window = window ?: return
        ViewTreeLifecycleOwner.set(window.decorView, activity)
        ViewTreeViewModelStoreOwner.set(window.decorView, activity)
        window.decorView.setViewTreeSavedStateRegistryOwner(activity)
        window.decorView.setViewTreeOnBackPressedDispatcherOwner(activity)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //here i init view tree owner that will be used by compose view
        initViewTreeOwners()
        //here i hide background of dialog
        window?.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
        val view = ComposeView(context).apply {
            setContent(content)
        }
        setContentView(view)
    }
}

// A function that returns an android dialog based on entered content
@Composable
fun androidDialog(content: @Composable () -> Unit): AndroidComposeDialog<*>? {
    val context = LocalContext.current
    val activity = context as? AppCompatActivity
    val componentActivity = context as? ComponentActivity
    val dialog = remember(activity, content.hashCode()) {
        if (activity != null)
            AndroidComposeDialog(activity = activity, content = content)
        else if (componentActivity != null)
            AndroidComposeDialog(activity = componentActivity, content = content)
        else null
    }
    return dialog
}

and now it's ready to use
@Composable
fun ShowDialog() {
    val dialog = androidDialog {
        Box(
            modifier = Modifier
                .size(100.dp)
                .clip(RoundedCornerShape(25.dp))
                .background(Color.Blue)
        )
    }
    Box(modifier = Modifier.fillMaxSize()) {
        Button(onClick = {
            dialog?.show()
        }, modifier = Modifier.align(Alignment.Center)) {
            Text(text = "show dialog")
        }
    }
}