php if statement issue with exploded array value

Question: My if ($arr[$key][0] == 'th') // is not working
I've been trying to convert my array value to string, but still my if statement is not true, please help!!!
Code:
$preparedstring = "
pb,List information,ca;
'th',Name,ca;
th,Surname,ca;
th,ID,ca;
th,Gender,ca;
th,Gender,ca;
pb,personal details,ca;
fl,Name,la;
fl,Surname,la;
fl,ID,la;
fl,Gender,la
";

$columncount = 0;
$firstindex = 0;
$lastindex = 0;
$functionvalue = "";

$outerARR = explode(";", $preparedstring);
$arr = array();

foreach ($outerARR as $arrvalue){

    $innerarr = explode(",", $arrvalue);
    $arr[] = $innerarr;

}
print_r($arr);

unset($arrvalue);
//Read the array
foreach ($arr as $key => $arrvalue1){
    $functionvalue = $arr[$key][0];

    echo $functionvalue;

    //Get column key functions
        if ($arr[$key][0] == 'th'){
            $firstindex++;
            echo "
".$a."

";
        }
        elseif ( $firstindex > 0 )
        {
                $lastindex = $key - 1;
        }

    foreach ($arrvalue1 as $arrvalue2){

           }
    $a++;
}

echo "
".$arr[0][0].".

 First Index : ".$firstindex. " Last Index : ".$lastindex. "---".$functionvalue;

Output:
Array ( [0] => Array ( [0] => pb [1] => List information [2] => ca ) [1] => Array ( [0] => 'th' [1] => Name [2] => ca ) [2] => Array ( [0] => th [1] => Surname [2] => ca ) [3] => Array ( [0] => th [1] => ID [2] => ca ) [4] => Array ( [0] => th [1] => Gender [2] => ca ) [5] => Array ( [0] => th [1] => Gender [2] => ca ) [6] => Array ( [0] => pb [1] => personal details [2] => ca ) [7] => Array ( [0] => fl [1] => Name [2] => la ) [8] => Array ( [0] => fl [1] => Surname [2] => la ) [9] => Array ( [0] => fl [1] => ID [2] => la ) [10] => Array ( [0] => fl [1] => Gender [2] => la ) )

pb 'th' th th th th pb fl fl fl fl

pb.

First Index : 0 Last Index : 0--- fl

This is the output, as you can see my if statement is false
Comment: What is $a supposed to refer to?
Answer: You need to remove all newlines from the string and then perform the operations:
$outerARR = explode(";", preg_replace('~[\r\n]+~', '', $preparedstring));


Can we build tensorflow lite on distro's other than Raspberry Pi such as Ubuntu/CentOS?

Question: The official documentation Tensorflow Lite on Raspberry Pi says it can be build on Raspberry Pi, but are there any instructions/information on how to build it on other Linux distributions such as Ubuntu/CentOS/RedHat. Is it possible to build at all?
Answer: Raspberry Pi default distribution is Rasbian, which is based on Debian. Ubuntu is also based on Debian. Therefore you can probably use most of the RPi instructions also on Debian/Ubuntu.
For other Linux distro families like CentOS/RHEL/Fedora you will need a different way to install the dependencies, but in general the process should be the same.
Answer: The official guide of building tflite on Raspbian may not be complete, but actually works.
As for other Linux distributions, your link did show how to compile on Ubuntu 16.04; you can build on PC and then copy the binary&symbolic link the library to run .tflite models on RPi.


How can we redirect to another page with object data using AngularJs

Question: I am trying to redirect my form to another page which is the /customerActivation with the customer object obtained from /getCustomerAccount route. I have searched on online sources and tried many suggestions but none work.
So I want to ask if there is a way to handle this using angular Js? This is my first handling this kind of situation
This is my form which submits or calls the function in my controller

 Please Enter your customer loyalty card number

  <form ng-submit="activateAccount()">

            <input type="text" class="form-control" id="formCard"
                   ng-model="nbcard" placeholder="Card number" required>

       <button type="submit" class="btn btn-info btn-lg btn-block btn-trans ">
         Activate my account
       </button>
  </form>

I have implemented this function in my controller
customerManageAPP = angular.module('customerMngAPP', []);

customerManageAPP.controller('CustomerController',  function($scope, $http) {

    let URL_ACT_ACCOUNT = `http://localhost:${port}/getCustomerAccount`;

    $scope.activateAccount = function() {
        $http.get(URL_ACT_ACCOUNT + `?cardNumber=${$scope.nbcard}`)
            .then(function (response) {
                $scope.customerAccount =  response.data;
                $location.path('/customerActivation/' + $scope.customerAccount.firstname + $scope.customerAccount.lastname);
            });
    };
});

and I have this in my routes file
router.get('/customerActivation', function(req, res) {
    res.setHeader('Content-Type', 'text/html');
    res.sendFile( __dirname + '/views' + '/customerActivation.html');
});

router.get('/getCustomerAccount', async (req, res) => {
    const { cardNumber } = req.query;

    const response = await Customers.find({"nb_card": cardNumber});

    res.json(response);

});

Answer: In general one uses a client-side router to parse the url:
With ngRoute:
angular.module("app",["ngRoute"])
.config(function($routeProvider) {
    $routeProvider.when({
        url: "/customerActivation/:customerId",
        templateUrl: "views/customerActivation.html",
        controller: "ActivationController"
    })
})
.controller("ActivationController", function($scope, $routeParams) {
    console.log("customerId", $routeParams.customerId);
})

For more information, see

AngularJS ngRoute $route Service API Reference - Example


Given $x,y,z >0$ and $xy^2z^3 = 108 $, what is the minimum value of $x+y+z$?

Question: Given $x,y,z >0$ and $xy^2z^3 = 108 $, what is the minimum value of $x+y+z$ ?
This is a homework problem, so if someone could just give me an outline/hint of the method used to solve this it would be much appreciated.
Thanks
Comment: This type of problem can be solved effectively with the AM-GM inequality, and I added an answer to this below. :)
Comment: https://en.wikipedia.org/wiki/Lagrange_multiplier
Comment: Note that $108 = 1 \cdot 2^2 \cdot 3^3$ so $6$ is a good possible candidate just by using the prime factorization of 108.
Comment: Similar :https://math.stackexchange.com/questions/565362/maximum-minimum-u-xy2z3?rq=1
Answer: By AM-GM Inequality,$$x+y+z = x+\frac{y}{2}+\frac{y}{2}+\frac{z}{3}+\frac{z}{3}+\frac{z}{3}\geq6\left(\frac{xy^2z^3}{2^2\cdot3^3}\right)^\frac{1}{6}=6\left(\frac{108}{2^2\cdot3^3}\right)^\frac{1}{6}=6$$
Equality holds when $x=\frac{y}{2}=\frac{z}{3}$, so plugging this into $xy^2z^3=108$ we know the equality occurs when $x=1, y=2,z=3$.
Answer: To prove the solution is $x=1,y=2,z=3$ we can write the constrained problem as
$min f(y,z)$ where $f(y,z) = \frac{108}{y^2 z^3} + y + z$.
Solving for the minimum of $f(y,z)$ we get:
$$
\frac{\partial f}{\partial y} = -2 \frac{108}{y^3 z^3} +1 = 0
$$
$$
(yz)^3 = 216
$$
$$
yz = 6
$$
$$
\frac{\partial f}{\partial z} = -3 \frac{108}{y^2 z^4} +1 = 0
$$
$$
(yz^2)^2 = 324
$$
$$
yz^2 =18
$$
Solving the pair of quadratic equations we get $y=2$ and $z=3$, and hence $x=1$. So the minimum value of the sum is $6$.
Comment: It remains to show that the point you've found is a minimum
Comment: You are correct. Since the constraint space is compact, then any local max/min is a global max/min. And since the solution $x=108,y=1,z=1$ works and is bigger than $6$ we can conclude that $6$ is a minimum.
Comment: @ Emil Kerimov: Why is the constraint space compact ? The minimization of $f(y, z)$ requires $y > 0, z >0$ which is not a closed set. Secondly, the fact that f(1, 1) > f(2, 3), how does that help to conclude that it is a minimum ?


Using Infrared sensor in my app for TV remote control

Question: I want to build a android app for IR-based TV remote control. In Android Docs, I got this : https://developer.android.com/reference/android/hardware/ConsumerIrManager.html
In this doc, there is a method transmit which takes two parameters : carrier frequency and pattern.
Are these parameters unique to different TV models?
Assuming them to be unique and if I want to control a Samsung Smart TV with this app, then how can I access corresponding data for passing as parameters in the transmit function.
Answer: Yes the carrierFrequency and pattern parameters are usually unique to the different models and brands. However, chances are the same maker may use the same pattern across different models.
For example, this pattern may work for the SAMSUNG smart TVs (power button):
carrierFrequency: 38000
pattern: 4500, 4500, 560, 1680, 560, 1680, 560, 1680, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, 1680, 560, 1680, 560, 1680, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, 1680, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, 1680, 560, 560, 560, 1680, 560, 1680, 560, 1680, 560, 1680, 560, 1680, 560, 1680, 560, 46946

(make sure your phone has the built-in IR blaster hardware)
There is no easy way to find the patterns for a specific TV. That's why there are people or companies scan and collect those patterns for share or for sale.

http://irdb.tk/find/
http://www.remotecentral.com/cgi-bin/codes/


Problems with using themes in Geany

Question: I'm trying to switch to the Geany editor for my web development but need to switch to a dark theme. In searching for some default themes I came across this excellent collection.
I've now installed the themes and they appear when I go to View -> Editor -> Color and I can select one. However, selecting a theme does nothing.
I am running Geany 0.20 (the latest version on Ubuntu 11.10) and have tried installing the new version and the deprecated version of the themes but get the same from both.
Comment: Works fine for me. Try restarting geany.
Comment: Try installing the themes by just running `./install`
Comment: @Capt.Nemo Did you install the master branch or deprecated branch version?
Comment: master`````````
Comment: Geany does not work with Ubuntu dark theme. You can put all the color scheme you prefer but it will look ugly. Especially the "compiler" window is impossible to read
Answer: Happened with me too , you need to copy all the colorschemes in ~/.config/geany/colorschemes and the next step which was not mentioned anywhere is you also need to copy the files in filedefs folder in the zip to corresponding folder in ~/.config/geany/filedefs and then it will start working !!
Answer: I've got the same Geany (0.2) and Ubuntu (11.10) as yours, and the following commands worked for me:
<code>git clone https://github.com/codebrainz/geany-themes.git
cd geany-themes
./install
</code>
Make sure that you have

Geany installed. Click To Install
Restart geany after installation
Comment: I uninstalled, removed ~/.config/geany, reinstalled, opened geany, installed the themes, killed geany and reopened then selected a theme. For some reason it won't save my theme selection.
Comment: Try filing a bug, or contacting a developer.

Problems with using themes in Geany


java - Sorting a 2d array by the total of one column issue

Question: I am trying to create a method that will take a randomly filled 2D array (each row is a worker, and each column is a year they worked over the summer. Each element in the array is how much money they made that summer) and sort by the worker who made the most total money from every summer worked and sort from greatest to least from there. Here is the class:
import java.util.Scanner;

public class SummerStats
{

int[][] salaries;

SummerStats(int people, int years)
{
  int i;
  int j;
  salaries = new int[years][people];

  for (i = 0; i < salaries.length; i++) // initialize salaries[][] with random salaries
  {
     for (j = 0; j < salaries[i].length; j++)
     {
        salaries[i][j] = (int)(Math.random() * 1001);
     }
  }

}

// I have omitted a few methods here that are not relevant to this question

     // method returns sorted array by earnings of a person over all years
   public int[][] sortedEarnings()
{
  int i = 0;
  int j = 0;
  int[][] sorted = new int[salaries.length][salaries[i].length];
  int rowSum = 0;
  int row[][] = new int[2][salaries.length];
  boolean flag = true;
  int temp = 0;

  // sorted will be a copy of salaries, then be sorted by total of each row
  for (i = 0; i < salaries.length; i++)
  {
     for (j = 0; j < salaries[i].length; j++)
     {
        sorted[i][j] = salaries[i][j];
     }
  }

  // sum rows
  for (i = 0; i < sorted.length; i++)
  {
     for (j = 0; j < sorted[i].length; j++)
     {
        rowSum = rowSum + sorted[i][j];
     }
     row[1][i] = rowSum;
     rowSum = 0;
  }

  // set worker index
  i = 0;
  for (j = 0; j < row[i].length; j++)
  {
     row[i][j] = (j + 1);
  }

  // sort by total earned for each worker
  i = 1;
  while (flag)
  {
     flag = false;
     for (j = 0; j < row[i].length - 1; j++)
     {
        if (row[i][j] < row[i][j + 1]) // if total amount is less than next position then swap
        {
           temp = row[i - 1][j]; // only need to sort the indeces, not the actual sums
           row[i - 1][j] = row[i - 1][j + 1];
           row[i - 1][j + 1] = temp;
           flag = true;
        }
     }
  }

  return row;
 }

}

The idea now is, You create an identical array to the randomly generated one, then create rowSum which only finds the sum of each workers total salaries, create an index of worker numbers, then sort by the sum of salaries and swap out the worker numbers accordingly. For some reason my bubble sort just is not working, I have tried it using two for loops, as well as this while loop
idea (which currently results in an unending loop, so be careful).
If anyone could find whats wrong with this sort or offer me a better method of sorting that would be great!
Answer: Your salaries 2D array is inverted. You said:

each row is a worker, and each column is a year

but you allocate as new int[years][people] which means that years are the rows and people are the columns, and if you try to sort the outer array, you're sorting across years.
Change to new int[people][years]. Then you can sort the outer array using Arrays.sort(T[] a, Comparator<? super T> c).
Arrays.sort(salaries, new Comparator<int[]>() {
    @Override
    public int compare(int[] worker1, int[] worker2) {
        int total1 = sum(worker1);
        int total2 = sum(worker2);
        return Integer.compare(total1, total2);
    }
});

Using the following helper method:
static int sum(int[] worker) {
    int sum = 0;
    for (int salary : worker)
        sum += salary;
    return sum;
}

It's not going to be especially fast, since it has to re-sum on every compare. To improve that, you should create a Worker class, instead of relying on 2D arrays.
You can then make the Worker class cache/pre-calculate the totalSalary, and make it implement Comparable, so you won't need a Comparator.


How to unite two Observables?

Question: I have two IObservable<bool> ( canEdit1 and canEdit2 ), how can I unite them?
Here is a sample of my code:
var canEdit1 = InerrProperty1.WhenAnyValue(x => x.Property1, x => x,
                (prop1, x) => prop1 != null &&  x != null);
var canEdit2 = InerrProperty2.WhenAnyValue(x=> x.Property1, x=>x.Property2,
    (prop1,prop2) => !string.IsNullOrEmpty(prop1) && !string.IsNullOrEmpty(prop2));

Comment: What do you mean "unite" ? Can you provide few examples of what should happen with different values in different sequence?
Comment: @HereticMonkey This seems to be a ReactiveUI question. Can't use the RxJS solution.
Answer: You can use the Merge functionality. It should look something like this:
var merged = canEdit1.Merge(canEdit2);

You can later subscribe to it, or do additional operators on it.
Answer: With the system.reactive library, there are multiple ways for combining observables. Has explained here, none implements a topological ordered query resolution. In a cases like diamond dependency graph, none of them will avoid intermediate/incoherent states.

Storm.Net (Simple Topologically Ordered Reactive Model) his an attempt to provide a data model that propagates update in a topological order.

How to unite two Observables?


How to change from GDM to LightDM?

Question: I've upgraded to 12.04. My upgrade didn't go as expected; X crashed at the middle of the upgrade. I had to install many packages manually.
This left me with a GDM login screen.  How do I change from GDM to lightDM?
Answer: Let me first tell you that now Ubuntu does not use GDM as its display manager in version 12.04...It uses lightdm as its display manager...
So the screen you want is actually lightdm.
So you will have to install lightdm as follows.
Enter these commands in the terminal:
sudo apt-get install lightdm

Install lightdm

After installing lightdm enter the following commands to set lightdm as the default display manager:
sudo dpkg-reconfigure lightdm

Then you will get the following screen:

hit enter and then you will get this screen:

Navigate your option to lightdm and hit enter.
Now Restart.
you'll get your screen :)
Comment: This is also the answer for those who upgraded to 17.10 and miss seeing their wallpaper when they select their account.  Lightdm previews the wallpaper, Gdm does not.
Comment: Same goes for 18.04.
Comment: Thanks @Nirmik. It works perfectly.

How to change from GDM to LightDM?


Sawdust from treated wood on my lawn

Question: Over the weekend I built a playhouse for my kids in the back yard using pressure treated lumber.  As I was cleaning up I realized that my lawn was covered in chemical laden sawdust.  Has anyone here had experience with this?  Is it a problem and if so is there a solution?
Comment: Wait... You're worried about the chemical laden sawdust on your lawn, but what about the chemical laden lumber your children are playing in!?
Comment: I'd just make sure no one is eating the grass. After a few storms, things will quickly break down and get dispersed into the soil. Maybe use a leaf blower to disperse it (wear a dust mask) if there's too much in one location.
Comment: Not really.  http://dufferinpark.ca/cityplaygrounds/pdf/ccatreatedwood.pdf
Comment: When you say chemical laden, what are you referring to?
Comment: The chemicals used in the pressure treating process.
Comment: @BMitch Please do not use comments to answer questions, especially when you are making health and safety claims that cannot be properly vetted as an "answer." Thanks.
Comment: I've used a Dyson bagless vacuum cleaner to get sawdust off my lawn and it worked surprisingly well.
Answer: Unless you have a big enough pile to make snowballs...or sawdust balls rather.  I wouldn't worry about it.  It shouldn't hurt the grass and again unless the kids are rolling around it it, or licking it you should be just fine.
In the First Aid section of the MSDS, for skin contact it says...

For skin contact, wash immediately with soap and water. Get medical
  attention if irritation develops or persists.

The by the book answer is yes follow the MSDS to the letter. But MSDS sheets are written with lawsuits in mind and are generally overzealous in how things should be handled. This is the same reason a piece of stained oak threshold at Lowe's has a "This product has been known to cause cancer in the state of California" sticker on it. I have had ptw dust in my eyes and on my body and had no ill effects. Sure if you have a pile, pick/clean it up, if its scattered...mine is realistic advice, I would not worry about it.
Comment: Can you provide any sources for this information, or is this simply your opinion?
Comment: Yes but the same thing shows up on MSDS sheets for latex paint, I am not saying you should rub either all over your skin but a little sawdust in the yard isn't going to hurt anything.
Comment: I neither agree or disagree. I was just pointing out that the answer would be better with sources to back up your claims.
Comment: Good point, comments moved up to the answer, makes it better, thanks.
Comment: @James: I agree that the sawdust isn't a big deal but I just have to say that your argument that "I did something potentially dangerous and I'm fine" is a really bad way to approach safety issues.
Comment: I wouldn't use the same argument if this were a question say...about running electrical.  Just trying to get across this is not a big deal.
Comment: Well the question is about whether a chemical is or isn't dangerous, so I think the only way to know is to consult an appropriate authority. "I've smoked cigarettes all my life and I'm fine, therefore smoking must be safe."

Sawdust from treated wood on my lawn


ADODB::_RecordsetPtr::Open throws Exception like Query timeout Expired in c++

Question: here i am trying to query a table of sql server 2008 r2 from my c++ application. It contains 21,54,514. but it throws an exception like "Query timeout expired" . below is my code base
<code>ADODB::_ConnectionPtr           m_pDBConnection;
ADODB::_RecordsetPtr                m_pRS;

m_pDBConnection.CreateInstance("ADODB.Connection");
m_pRS.CreateInstance("ADODB.RecordSet");

m_pRS->Open(wstrSQL.c_str(), _variant_t((IDispatch *) m_pDBConnection, true),
        ADODB::adOpenStatic,
        ADODB::adLockReadOnly,
        ADODB::adCmdText);
</code>
When the above line is get executed it throws the above said exception.
i know the issue , the issue is actually with  default timeout set. it is actually 15 sec.
can anybody please tell how to reset or change timeout in ADODB::_RecordsetPtr. I searched in google a lot , we can do reset timeout for ADODB::_ConnectionPtr but not for ADODB::_RecordsetPtr. it would be vary usefull for me. Thanks in advance.
Answer: According to Coding Journey you need to set the CommandTimeout on the connection and on the command.
<code>// The recordset for the result
ADODB::_RecordsetPtr rs;
// Timeout on connection
m_pDBConnection->CommandTimeout = 60;
// Need to create command first, then configure it, then open RecordSet
ADODB::_CommandPtr cmd(__uuidof(ADODB::Command));
cmd->ActiveConnection = m_pDBConnection;
cmd->CommandText = wstrSQL.c_str();
cmd->CommandTimeout = 60;
rs->Open(cmd, vtMissing, ADODB::adOpenStatic, ADODB::adLockReadOnly, ADODB::adCmdText);
// Reset the timeout on the connection
m_pDBConnection->CommandTimeout = 15;
</code>
Comment: @user1450931 If my answer helped you please accept it and maybe even upvote it. Thanks.
Comment: Thanks @WernerHenze. I used this for vba, not c++, but I had not seen any vba questions that rolled all of the needed properties (connection, query, timeout) into one command and then executed it against a recordset. That helped me!
Comment: I like this, but can you really pass cmd as the first parameter to the Open call?  Won't compile for me.  Instead of `rs->Open` I would try `cmd->Execute(NULL, NULL, adCmdStoredProc)` which should return that `_RecordsetPtr` object
Comment: @demongolem The code compiles and works for me. Regarding Open see https://msdn.microsoft.com/en-us/library/windows/desktop/ms675544(v=vs.85).aspx.


Colobot crashes half a second after launching!

Question: I want to play colobot on my linux machine but it crashes after 1/2 second later.
Here's gdb dump:
<code>Starting program: /usr/games/colobot
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

** (zenity:4874): WARNING **: Error retrieving accessibility bus address: org.freedesktop.DBus.Error.ServiceUnknown: The name org.a11y.Bus was not provided by any .service files
3.14.0
[INFO]: Colobot starting
[INFO]: Creating CApplication
[INFO]: Error on parsing profile: No such node (Resources.Data)
[INFO]: Using datadirs: /usr/share/games/colobot
[INFO]: Error on parsing profile: No such node (Language.Lang)
[INFO]: Opening audio device...
[INFO]: Done.
[INFO]: CApplication created successfully
[New Thread 0x7fffe8bc2700 (LWP 4878)]
[New Thread 0x7ffff7fb9700 (LWP 4877)]
[New Thread 0x7fffeafa6700 (LWP 4876)]
[INFO]: Error on parsing profile: No such node (Setup.Resolution)
[INFO]: Creating CDevice
[INFO]: Auto-detecting VBO support
[INFO]: Detected ARB_vertex_buffer_object extension - using VBOs
[INFO]: CDevice created successfully
[INFO]: Error on parsing profile: No such node (Gamer.LastName)
[INFO]: Error on parsing profile: No such node (Setup.Resolution)
[INFO]: Simulation speed = 1,00

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff2349ca9 in ?? () from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
(gdb) bt
#0  0x00007ffff2349ca9 in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#1  0x00007ffff20773e0 in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#2  0x00007ffff1fc8972 in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#3  0x00007ffff1fca068 in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#4  0x00007ffff1fca719 in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#5  0x00007ffff20389ee in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#6  0x00007ffff2035a03 in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#7  0x00007ffff20c3ff6 in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#8  0x00007ffff20c41b0 in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#9  0x00007ffff20c48b2 in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#10 0x00007ffff20c4c5f in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#11 0x00007ffff20c52b8 in ?? ()
---Type <return> to continue, or q <return> to quit---
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#12 0x00007ffff1fcbe52 in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#13 0x00007ffff1fcc12c in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#14 0x00007ffff1fe4644 in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#15 0x00007ffff1fe5d3c in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#16 0x00007ffff2087c22 in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#17 0x00007ffff20882da in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#18 0x00007ffff1d4e90b in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#19 0x00007ffff1d4ee52 in ?? ()
   from /usr/lib/nvidia-340/libnvidia-glcore.so.340.76
#20 0x00000000004e82a5 in Gfx::CGLDevice::CreateTexture(ImageData*, Gfx::TextureCreateParams const&) ()
#21 0x00000000004e8d32 in Gfx::CGLDevice::CreateTexture(CImage*, Gfx::TextureCreateParams const&) ()
#22 0x000000000049ccb8 in Gfx::CEngine::UpdateGroundSpotTextures() ()
#23 0x000000000049e16a in Gfx::CEngine::Draw3DScene() ()
---Type <return> to continue, or q <return> to quit---
#24 0x000000000049e5f0 in Gfx::CEngine::Render() ()
#25 0x00000000004604bd in CApplication::Render() ()
#26 0x0000000000463804 in CApplication::Run() ()
#27 0x000000000045c0d1 in main ()
</code>
From my perspective it is OGLs/drivers fault or messed up shader programs.
Can someone help me out?
Comment: Seems like it could be an Nvidia driver bug.  Are you stuck on the 340.76 driver for your card, or could you move up to a more recent version?
Comment: Yes I am stuck. I'm using a obsolete GPU that means no more updates from Nvidia.
Comment: However the issue was fixed when reinstalling the driver on ubuntu update center.
Answer: The issue was the driver.
Try reinstalling or updating see if it works. I know it worked for me :)
Comment: +amaranth Thanks, didn't know that ;)


Pass single column of dataTable to function in vb.net

Question: I have a dataTable with 5 rows and 2 columns(Id,Name). I need to pass the 5 rows with only one column(Id) of the dataTable to a function parameter which is a dataTable.
This is what I tried
myfunction(dt.Rows.Item("Id")

Public function myfunction (dt as dataTable)
// Some code

End Function

But this is not working. Why is it so? Even if a column is excluded the dataTable still remains as a dataTable. How can I pass the "ID" column without including the "Name" column to this function as a parameter.
Answer: Functions need a DataType and a Return statement.
Your Function is expecting a DataTable and you are passing a DataRow.
dt.Rows.Item takes a Integer, not a String.
You don't Dim a Function, you call it.
Stack Overflow asks for a Minimum, Complete and Reproducible example of your problem. Your code is not that.
I gave your Function a name and something trivial to do so I could demonstrate the proper syntax. If you don't need the whole DataTable then don't pass it to the function. I am just passing the values in the ID column as a List(Of T) If your Function is not under your control and it wants a DataTable, then just pass dt.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim lst = dt.Rows.OfType(Of DataRow)().Select(Function(dr) dr.Field(Of Integer)("ID")).ToList()
    Dim MaxID = GetMaxID(lst)
End Sub

Public Function GetMaxID(lst As List(Of Integer)) As Integer
    Dim MaxI = lst.Max
    Return MaxI
End Function

Answer: There are several issues with what you provided.
First, your function call is missing a parentheses on the end.
myfunction(dt.Rows.Item("Id"))

Second, your function is expecting a datatable, but you are passing a cell (and also not specifying which row, so this wouldn't work)...
If you truly want your function to use a datatable, you need to just pass dt like:
myFunction(dt)

If you want to pass the cell value instead, you can change your function definition to take a string or whatever datatype is within that column, and pass the value like:
myFunction(dt.Rows(ROWNUMBER).Item("Id"))

Comment: I need all the rows in the dataTable with only one column "Id"
Comment: Just pass the whole datatable then in your function use the data from the desired column only, like `For Each row As DataRow In dt.Rows )> Next`. Show us what you intend to use with the datatable in your function.


Do links to inaccessible sites make my website inaccessible?

Question: My website contains links to third-party websites, mostly articles on news websites.  If these third-party websites are not accessible, and I am trying to meet WCAG 2.0/2.1 AA standards, do these links make my site inaccessible?
Any answers supported by WCAG are greatly appreciated.
Answer: Merely providing links to an inaccessible site does not make your own site inaccessible. A conformance claim only covers the site (domain or subdomain) for which the owner claims conformance; it does not require you to fix the rest of the web.
However, if linking means embedding content from other websites, that external content can cause accessibility issues. In a regular WCAG conformance claim, you cannot exclude this external content; conformance claims are for full pages. For such scenarios, you may wish to provide a Statement of Partial Conformance - Third Party Content.
Another scenario is where an online shop uses an external payment process. If the buying process begins on your own site but requires the use of an external payment services to complete the purchase, that external part must also be considered when making a conformance claim. This is covered by the section Complete processes in WCAG 2.1.
Comment: Thank you, user800.  By 'embedding content from other websites', I imagine you are referring to iFrames or similar?
Comment: @ZEST iframes would be one way of doing this. Simple using images that are hosted elsewhere (e.g. animated GIFs) would also count.
Comment: Thank you for the clarification, much appreciated!


UI for AND, OR and NOT query combinations

Question: I'm working on a project where users can choose multiple criteria and mix them with logical operators AND, OR and NOT. Currently we decided not to let users mix criteria because the UI is too complex for them. But in the future we want to give them more freedom.
Have you already encountered this problem?
How did you solve it?
Have you got an example?
In my mind, maybe one block provides the criteria and another block lets the users manage a box. The user could drag and drop multiple criteria on different boxes and then apply logical operators on them.
What do you think about this?
Comment: Perhaps do it visually using Venn diagrams
Comment: Can you please try to make the question more concrete by providing your own example (describe the problem domain) or a mockup?
Answer: Finance, accounting, risk management people use interfaces like this all the time. I want category A, B, C in time range X but without B1 and C 2.
If you're making an app for such users I don't think it's an issue at all. As always make sure you understand how users complete their task and what they are trying to accomplish (don't take the BA's word for it); think about how you can improve on it; present a variety of options to the users and test, test, test.
These people are expert users and they want to get their data as fast as possible.
Comment: Actually you have introduced another operator.   Without is  Expect.
Comment: @Blam every time someone wanted something "without" they meant **AND NOT** for each item after "without" - usually implemented using `NOT` operator - I have no idea what do you mean by `Expect` operator, could you please elaborate?
Comment: Except is take away as opposed to and not.  In the case of multi value properties like cc it can be different.
Comment: Thanks for your answer. We have to learn more about users used to do with our application to get their result. In the future, we'll offer differents UI, let users test them, and get feedback to choose the best :)
Answer: I have yet to see a GUI that could replace the expressive power of a text representation for any query.
Bugzilla has a somewhat clumsy Custom Search interface that allows you to "Show Advanced Features" to be able to put parentheses around groups of criteria like (a OR b) AND (c OR d NOT e) - almost impossible to change your mind if you make a 1 wrong click, but the search in bugzilla is a GET request, so it is possible to manipulate the text of the query in the URL.
If individual criteria are too complex (i.e. not simple keywords), you can try to experiment and separate the Boolean logic from individual criteria, e.g.:
Criteria:
1. ddd ddd ddd
2. ddd ddd ddd
3. ...

□ Match ALL Criteria
□ Match ANY Criterium
■ Create Custom Query [?](help box):
  +---------------------------------+
  |1 AND 2 AND 3                    |
  +---------------------------------+

Unless manually edited, the text box should be pre-populated by ANDs when matching ALL criteria vs. ORs if matching ANY, it should not automatically change after manually edited, any omitted criteria should be highlighted red with appropriate warning message..
You could provide buttons AND OR NOT ( ) - when pressed to insert that command into text box, also possible to drag&drop into arbitrary position, same for dragging criteria into the text box..
But as always, ask your users and test your solutions.
Comment: Thanks for your answer. That's an interesting solution. Very helpful !
Answer: Your description reminded me of the Advanced Search feature in the Thunderbird mail client.
In Thunderbird's Advanced Search window, users either pick "all of the following" (a query with only AND operators) or "any of the following" (a query with (a query with only OR operators).
The query itself is then constructed from a number of 'rules', which are of the form field, condition, value. Every condition has an inverse, which provides the NOT operator (for example, there is a 'does not contain', 'larger than' is paired with 'smaller or equal than', and so on).

There is no grouping, and making queries that contain both OR and AND operators is impossible, so this solution is less powerful than some form of text-based query. However, it's relatively easy to understand, probably useful enough for advanced users (if maybe not power users), and relatively easy to implement.

Image from here.
Comment: Thanks for your answer. Very interesting solution. I'll take a look.


Why does file: prefix not working in @ContextConfiguration with my test using spring framework?

Question: My folder structure looks like :
project
    subproject
      src
       - main
          -java
       - test
          -java
          -resources
            -spring
              context.xml

when I try to use @ContextConfiguration(locations={"file:src/test/resources/spring/context.xml"}) my ide (intellij) shows cannot resolve directory. However, if I change the code to
@ContextConfiguration(locations={"/spring/context.xml"})

or
@ContextConfiguration(locations={"classpath:/spring/context.xml"})

The error disappears.
My original setting already has the following configure in pom.xml
<testResources>
        <testResource>
            <directory>src/test/resources</directory>
        </testResource>
</testResources>

What could be the problem?
Answer: Try loading test resources like:
@TestPropertySource(properties = { "spring.config.location=classpath:spring/context.xml" })

Comment: Thanks for the suggestions. Actually in my case ```@ContextConfiguration(locations={"classpath:spring/context.xml"})``` works,  but I still wonder why ```@ContextConfiguration(locations={"file:src/test/resources/spring/context.xml"})``` doesn't work. Do you have any idea?
Comment: As far as I know, when you use `file` to load location, it checks absolute path from your root project. You may need to change location value to `file:subproject/src/test/resources/spring/context.xml` . Or may be it's just IntelliJ issue and build should work with maven command directly in cmd.
Comment: Thank you so much! You are right about the problem. When I added subproject in the path IntelliJ stop giving error.  Is is just IntelliJ being different? If I switch IDE (for example switching to eclipse), will the case be any different?
Comment: Try to run test from command prompt with command `mvn test` with and without subproject in file path. You will get idea whether it's code issue or IDE.


php/mysql - only a fragment of a long text is inserted into DB

Question: In my code, I use the variable $content.
It's a text string with a length of ~200000.
$session doesn't matter in this case.
If i try to insert the following data, ...
$c = mysql_real_escape_string($content);

mysql_query("
  INSERT INTO data (time, session, key_, value_)
  VALUES('".time()."', '".$session."', 'content', '".$c."')
");

...a new row is generated in the DB and time, session, key_ and value_ are written.
But when $content had a length of ~200000, the inserted text is only a fragment of the first ~1300 characters.
The field type is set to longtext, collation is utf8_bin.
If i choose $c = strlen(mysql_real_escape_string($content));, something about '200000' is written to value_.
There is no mysql_error in any case.
So why is only a "short" fragment of my variable inserted?
edit:
To avoid this problem, I used base64_encode(), to encode all data and the query did its job.
Comment: Can you give the describe result of the table?
Comment: As stated in the PHP manual for the [`mysql_query()`](http://php.net/manual/en/function.mysql-query.php) function: *Use of this extension is discouraged. Instead, the [MySQLi](http://www.php.net/manual/en/book.mysqli.php) or [PDO_MySQL](http://www.php.net/manual/en/ref.pdo-mysql.php) extension should be used. See also [MySQL: choosing an API](http://www.php.net/manual/en/mysqlinfo.api.choosing.php) guide and [related FAQ](http://www.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated) for more information.*
Comment: Describe result is:

    [Field] => time
    [Type] => int(15)
    [Null] => NO
    [Key] =>
    [Default] =>
    [Extra] =>

    [Field] => session
    [Type] => varchar(32)
    [Null] => NO
    [Key] =>
    [Default] =>
    [Extra] =>

    [Field] => key_
    [Type] => varchar(100)
    [Null] => NO
    [Key] =>
    [Default] =>
    [Extra] =>

    [Field] => value_
    [Type] => longtext
    [Null] => NO
    [Key] => MUL
    [Default] =>
    [Extra] =>

@eggyal: Thanks a lot, I'll try it.
Comment: Try again - this time just using html safe ascii
Comment: @eggyal:I tried MySQLi, but nothing changed.
Answer: check the type of the field in the database, what type are you using ?
Comment: The type is longtext, as the question says. But text, mediumtext and largetext don't work.
Answer: Try to set field type to TEXT .


How do I know when my water heater should be replaced?

Question: The condo I just moved into has an original 2001 gas water heater that is missing a few features one would like to see in 2015, such as inspectable anodes. The home inspector pointed this out as a potential problem but only due to the heater's age; not due to any kind of malfunction.
Is this the kind of job where one should wait until the heater starts to malfunction? Is there a recommended replacement schedule one should use? Are newer models efficient enough that it makes sense to replace it anyway?
Comment: Gas, electric, oil?
Comment: A gas heater will not have anodes.
Comment: @wayfaring the ones on sale and the one I installed before in a previous home did/do.
Comment: I would not wait for a 14-year-old water heater to fail before replacing it. It's kind of like playing Russian roulette with your condo.
Comment: If it isn't broken why would you fix it? Any efficiency gain is unlikely to pay for itself, amortized. Natural gas is relatively cheap right now. Most tank failures start as a slow seep or leak, so keep an eye on it, especially if it is located *inside* your home.
Comment: @Jimmy: Based on my current natural gas prices of $1.10/therm, (EnergyGuide says) the new model costs 54 fewer therms / year and will pay for itself in approx.  11 years (and has a 12 year warranty). About breaks even but takes a long time.
Comment: Agreed, but the longer you wait the less total cost over time... no?
Answer: Your other question implies that it's gas. Yes, there are more efficent gas units (as well as more efficient electric heat-pump units) available now. (Electric resistance units are really about the same since they started using a reasonable amount of insulation on them.)
Waiting for the one you have to fail may mean water damage and replacing it in a hurry, which can negatively impact your ability to shop around and get exactly what you want. You are certainly past the usual "lifetime" of a water heater already, though that can vary with water quality/chemistry.
In some areas significant rebates are available on heat pump water heaters, which are otherwise expensive, but which can (compare YOUR local rates for each) actually be cheaper than gas to run, especially if the "moderate A/C effect" is beneficial in your climate.
Comment: Yes, it is gas. EnergyGuide label on the old one says 268 therms/year; new ones without new ducting are around 217 therms/ year.
Answer: Most newer water heaters don't last as long as they used to. Try to find out what kind of warranty your water heater has. If it has less than a 10 year warranty, then it is only a matter of time before it fails.
The majority of new heaters will be much more efficient than what you have. Keep an eye on the energy ratings. There are some that perform better than others. Some heaters are also "smart". They are programmable and will heat water at certain times of the day such as in the morning when people are typically showering. There are also tankless water heaters which are very efficient. Since you have gas, that would be an excellent option.


HTML5 video element — alternative text

Question: Unlike the img element, the video element doesn't include an alt attribute for missing or inaccessible content. It seems to me that video is more likely to cause loading or accessibility problems than the humble image.
The note in the W3C Document Doesn't make make clear a simple alternative.
Is there a recommended procedure for providing a suitable alternative text, or, say a link to a transcript?
Comment: have you looked at adding ARIA attributes to the content, and using javascript handlers to trap any loading errors
Answer: As you pointed out, the tag <video> doesn't have an alt attribute.
I have two ideas to satisfy at least in part this need.
1) Adding a paragraph inside the <video> tag
<video>
  <source src="my-video-path.mp4" type="video/mp4">

Description of the video...

</video>

2) Adding schema data
<video itemscope itemtype="http://schema.org/VideoObject">
    <source src="my-video-path.mp4" type="video/mp4">
    <meta itemprop="name" content="Name of the video">
    <meta itemprop="description" content="Description of the video...">
    <meta itemprop="duration" content="PT1M33S">
    <meta itemprop="thumbnail" content="my-video-thumbnail-path.jpg">
</video>

Comment: Any non-`` and non-`` content inside the `` tag should *only* be a replacement for the video and *not* supplemental to it — it's only intended for browsers that don't support the video element. (kindof like ``.) The [spec](https://html.spec.whatwg.org/multipage/media.html#the-video-element) even says "this content is not intended to address accessibility concerns."

HTML5 video element — alternative text


How to upload an email attachment file in WooCommerce Orders of WordPress Admin Panel

Question: Is it possible to upload an email attachment file (e.g., PDF quote) right in the WooCommerce>Orders section?
I want WooCommerce attach the file to the default email template when I hit update button to complete and order.
I do not want to put the file(s) on server.
Answer: this code will let you add a static PDF file (or in fact, any kind of file) to the WooCommerce Order Emails.
<code>add_filter( 'woocommerce_email_attachments', 'attach_terms_conditions_pdf_to_email', 10, 3);

function attach_terms_conditions_pdf_to_email ( $attachments , $id, $object ) {
$your_pdf_path = get_template_directory() . '/terms.pdf';
$attachments[] = $your_pdf_path;
return $attachments;
}
// you need to upload your term in your upload directory
</code>
Comment: Thank you very much @Mostafa. Your suggestion does attach the file. However I am wondering is there any way to read the $your_pdf_path from an open file dialog box opens in WooCommerce Orders?


Parent view not animating child view's frame changes in SwiftUI

Question: So I'm finishing up work on a SwiftUI based iOS App. I'm in the process of refining animations and visual layout stuff. My issue is as follows:
I have a parent view (A) which contains a child view (B) in its body, both views use an @ObservedObject view model for their data. I also have an overlay view (C) applied within A's body onto B. When B changes its frame size due to reloading on a data change from its view model, the overlay does not animate through the frame size change and just jumps to the new position.
    struct A: View {
        @ObservedObject var viewModel: ViewModelForA

        var body: some View {
            VStack {
                Spacer()
                B().overlay{
                    VStack{
                        HStack{
                            Spacer()
                            C()
                        }
                        Spacer()
                    }
                }
            }
        }
    }

.animation(animation, value: value) is used within B to animate itself
I can't use .animation(animation) without a value because it's deprecated and as we know causes haphazard animations
I don't have a value to animate on, because A doesn't have access to the values in B that would have caused B to change frame size.
C is a simple button view that relies on setup and data from A

How can I get C to animate correctly according to B's changing frame size?
Answer: I just had this same issue and can't find anything online for how to do this so I came up with a solution of my own that uses an environment action (similar to how the OpenURLAction is structured).
Usage of the solution (implementation shown after)
To use it, you use this custom .childTriggeredAnimation(animation: .default) modifier on the parent view. This adds an animateParent action to the environment which can be used by child views to trigger an animation in the parent.
struct ParentView: View {
    // without the solution, the text above
    // and below the child view jump instantly
    // even though the child view size is animating
    // with the solution, they animate along with the child
    var body: some View {
        VStack {
            Text("Above")
            ChildView() // grows and shrinks in an animated way
            Text("Below")
        }
        .childTriggeredAnimation(animation: .default) // part 1
    }
}

And then in the child view you pull the animateParent action out of the environment with @Environment(\.animateParent) and then call that action when you want the animation to take place in the parent.
struct ChildView: View {
    @State private var isBig = false
    @Environment(\.animateParent)
    private var animateParent // part 2
    var body: some View {
        Button {
            // causes animation in child view
            isBig.toggle()
            // triggers animation in parent
            animateParent() // part 3
            // OR animateParent(overrideAnimation: whatever)
        } label: {
            Rectangle()
                .frame(height: isBig ? 400 : 200)
        }
        .animation(.default, value: isBig)
    }
}

Implementation
For the implementation we define a custom EnvironmentKey (the docs demonstrate this very well) to use to store the action to run that will trigger the animation in the parent.
We also make a custom ViewModifier to place on the parent view to setup the animation in the parent and to add the custom action to the environment so that the child views can access it when they need to.
import SwiftUI
struct AnimateParentAction {
    private let action: (Animation?) -> Void
    init(action: @escaping (Animation?) -> Void) {
        self.action = action
    }
    func callAsFunction() {
        action(nil)
    }
    func callAsFunction(overrideAnimation: Animation) {
        action(overrideAnimation)
    }
}
private struct AnimateParentActionKey: EnvironmentKey {
    static var defaultValue: AnimateParentAction = .init(action: { _ in })
}
extension EnvironmentValues {
    var animateParent: AnimateParentAction {
        get { self[AnimateParentActionKey.self] }
        set { self[AnimateParentActionKey.self] = newValue }
    }
}
private struct OnAnimateParentCalledModifier: ViewModifier {
    let animation: Animation
    @State private var animationToggle = false
    @State private var overrideAnimation: Animation?
    func body(content: Content) -> some View {
        content
            .environment(\.animateParent, AnimateParentAction(action: { overrideAnimation in
                self.overrideAnimation = overrideAnimation
                animationToggle.toggle()
            }))
            .animation(overrideAnimation ?? animation, value: animationToggle)
    }
}
extension View {
    func childTriggeredAnimation(animation: Animation) -> some View {
        modifier(OnAnimateParentCalledModifier(animation: animation))
    }
}

This solution worked for me, I am curious to see if anyone has come up with other better solutions but I feel like this is decently clean and reusable despite the boilerplate needed to set it up initially.


Selenium Variable not working

Question: I'm trying complete an online form with date variables. The table looks like this:
store  CourseStartDate  11/01/2015

type    name=AA7iA      ${CourseStartDate}

It runs great in Selenium, no errors. But, in the application I'm using Selenium IDE enters the actual text ${CourseStartDate}.
What do I have wrong here?
I know it's something really simple and stupid but I can't find an answer anywhere and I've spent hours looking.
Answer: The syntax for store is wrong. It should be : store value variable.
So try as :
store 11/01/2015 CourseStartDate

type name=AA7iA ${CourseStartDate}

Comment: Thank you very much, that did the trick. I knew it was a stupid mistake.

Selenium Variable not working


A system of two recurrence relations with contradicting solutions??

Question: I have this system of recurrence relations,
\begin{array}{rl} i p_{i,j} & = p_{i-1,j} \\ j p_{i,j} &= i p_{i,j-1} \end{array}
that I want to solve.
If I iterate through the first relation first, I get that
$$ p_{i,j} = \frac 1{i! j!} p_{0,0} $$
and if iterate through the second relation first I get
$$ p_{i,j} = \frac 1{i! j!} i^j p_{0,0} $$
which is contradicting. And neither of these solutions seems to satisfy both relations!!
So what is going awry?
Comment: Well, the second one tells us that $p_{0,j}=0$ and you quickly deduce that $p_{i,j}=0$ $\forall i,j$.
Comment: wow! thanks! this is really embarrassing!! I will delete the question
Answer: If you iterate through the first relation first, you get $$p_{i,j} = \frac{1}{i!}p_{0,j}$$ and then one iteration through the second relation gives you $$p_{0,j} = \frac{0}{j}p_{0,j-i} = 0$$
So in fact this iteration order gives you $p_{i,j} = 0$ $\forall j>0$.
If you iterate through the second relation first, you get, as you claimed, $$p_{i,j} =  \frac{1}{i!j!}i^j p_{0,0}$$
which isn't a contradiction, it just tells you that $p_{0,0} = 0$ as well.
One more look at the first relation confirms that $p_{i,j} = 0$ $\forall i,j$ (as lulu pointed out in the comments).
Comment: thanks. what his tricked me is this:
$$ p_{i,j} {=} \frac 1{i!} p_{1,j} {=} \frac 1{i!} \frac 1{j!} p_{1,0} {=} \frac 1{i!j!} p_{0,0} $$
the first and third equalities are using the first recurrence relation, and second equality using the second recurrence relation


How to show irreducible closed subsets of Spec are vanishing sets of primes?

Question: I would like to show if $R$ is a comm ring, and $Y \subset\operatorname{Spec}R$
is a closed irreducible subset,
then there is a prime ideal $p \subset R$ such that $Y = V(p)$,
i.e. $Y = \{ q \in \operatorname{Spec}R : q \supseteq p\}$.
I'm not quite sure where to begin, other than saying

$Y = V(I)$ for some ideal $I$ because $Y$ is closed;
and $I$ cannot be factored into a product of ideals $J,J'$ each with vanishing set different from $V(I)$, since $Y$ is irreducible and $V(JJ') = V(J) \cup V(J')$.

Would anyone know how to approach this?
Note: This question seems related, but what I would like to show is roughly a converse to what that question is trying to show.
Answer: As you noted, if $Y$ is closed, $Y=V(I)$ for some $I$, and one can assume that $I$ is a radical ideal. Suppose $V(I)$ is irreducible, and suppose $f,g\in R$ and $fg\in I$. If $X_{fg}$ denotes the usual basic open set of primes not containing $fg$, then
$$
\emptyset=X_{fg}\cap V(I)=(X_f\cap V(I))\cap (X_g\cap V(I))
$$
as $X_{fg}=X_f\cap X_g$.
Since $V(I)$ is irreducible, at least one of $X_f\cap V(I)$ or $X_g\cap V(I)$ must be empty, since two nonempty open subsets of an irreducible space cannot be disjoint. If $X_f\cap V(I)=\emptyset$, then $f$ is contained in every prime ideal containing $I$, i.e., $f$ is in the radical of $I$, i.e., $f\in I$ since $I$ is radical. Similarly, if $X_g\cap V(I)$ is empty, $g\in I$. In any case, $I$ is a prime ideal.
Comment: Thank you, this was very helpful!
Comment: +1, nice answer. For completeness, if I'm remembering correctly, $Y = V(I)$ for $I = \cap_{P \in Y} P$, and this proof shows $I$ is prime when $Y$ is irreducible. In this way, the maps $P \mapsto V(P), Y \mapsto \cap_{P \in Y} P$ define a bijective correspondence between elements of $Spec(R)$ and irreducible closed subsets of $Spec(R)$, which restricts to a bijection between irreducible components of $Spec(R)$ and minimal prime ideals.
Answer: $V(x^2)$ is closed and irreducible in $\mathbb{C}[x]$, but not prime.
You're probably looking for primary decomposition.
Comment: Here I meant $V(p)$ as in just a set of primes on which all of $I$ vanishes, not as the actual scheme $\operatorname{Spec} R/p$. I'm interested in showing every irreducible closed subset of an affine scheme has a generic point.


Is There A Way To Make Flowey Like you?

Question: So I just got Undertale, but I've known pretty much everything about it for three or more months. What I don't know is all of the endings for neutral routes. I first started with a couple of pacifist runs, but now I've grown a love for neutral. I first spared everyone but the bosses, which meant I had to kill Flowey. But since he's my favorite character, I didn't. In the end, Flowey asked me if I could prove to him that I could make it through a run without killing anyone to get a better ending. I wasn't done with neutral routes though. So naturally, I reset the game. When I saw Flowey again in his little spot where you first meet him, he said something like "Hey. Remember what I said? Don't kill anyone." Then he popped into the ground and Toriel came.
I did as he said and made it through most of the game without killing anyone. But when it came to Asgore, I decided not to spare him, just to test it out. As a result, Flowey got a bit angry. He said something similar to "You made all of these friends, just to kill ASGORE? What the hell is wrong with you?" and "Are you trolling me? You're only trolling yourself." When I reset the game, Flowey wasn't there at the beginning.
Once again, I decided to do a neutral route. But this time, I kill everyone EXCEPT the bosses. So that's what I did. After I spared Toriel, I was thinking of seeing Flowey again, have him scold at me a bit, and reset. But he didn't appear after that either. And like the previous run, I wasn't able to fight Omega because Flowey knew what would happen. So I hurried through the credits, skipped through Sans's call (which I didn't read because I skipped through so fast, but I know he said something different that time), and got to Flowey. He said "Why do you keep coming here? Oh wait, I get it. You want to be friends, don't you? You're PATHETIC." He then talks about how he could get along with someone like himself.
I reset the game again, but I haven't done anything yet. I made it to Flowey's spot, but once again, he's not there. I wonder if he's pushing me towards a genocide route, which was my original plan until now, or should I continue to go through neutrals just to see was he says. Maybe, he might give up. I'm not sure. But if there's one thing I'm sure about, it's that I am not giving up. So back to the question, can you possibly make Flowey like you, without going through a genocide route? I don't think I should go through genocide yet for two reasons. One, because then Flowey's memory will be reset when I give my soul to Chara, and two, because I don't want to see Flowey die.
Answer: You've obviously already read some spoilers, but I'm not sure exactly what you do and don't know, so I'll be using spoiler markup anyway.
First, a direct answer to your question with the bare minimum of spoilers possible:

 If you do the True Pacifist route, then Flowey will be sincerely nice to you, and wish that you were his friend. This requires you to go through the entire game without killing any monster at all (0 EXP earned, LV 1), and also requires you to befriend several monsters along the way. If you are missing another aspect of the route, Flowey would normally give you a hint about it after the credits (he has already given you the "don't kill anyone" hint, and he's not going to repeat himself). However, killing Asgore causes him to yell at you for that instead, even though it's after the point of no return and therefore not strictly relevant.

Now for the spoiler you probably don't want to read unless you already know everything about the game:

 Flowey is really the last remnants of Asriel Dreemurr. He is generally unable to feel positive emotions, and as a result, he will never truly be friends with the protagonist, or with any other character, unless he's returned to his original form. This only happens in the True Pacifist ending, and only temporarily.
Answer: How I got Flowey to like me was I did a neutral run where I killed all monsters and spared all bosses but, at the end I killed Flowey. Then I started a genocide route, and after you kill Toriel, Flowey will team up with you meaning you have befriended him and Flowey will say "Let's grind em' to dust." thus you get Flowey to like you because he says you're just like him, "hollow inside" and I transformed it into a new route called "The pure evil route" because you are like Flowey's sidekick and you are evil.
Comment: This is way different from the accepted answer. Is there a source?
Answer: If you do a 'true pacifist' run (meaning don't kill anyone), then you must have a date with papyrus and go to the true lab. When you go to Asgore, everyone shows up, and Papyrus says that a little flower told you to come here. Asriel and Dreemur fight, and then he hugs you after sparing him and says take good care of Mom and Dad (Toriel and Asgore) and that technically means his your friend. I don't know any other way

Is There A Way To Make Flowey Like you?


Really high kernel boot time

Question: My system boot time suddenly became very high. I've been dual booting Kubuntu and Win10 for quite some times. The root partition is on ssd. I recently increased my swap size using live usb and then this started to happen. Before this, my boot time was about 7-10 seconds. Here's the systemd-analyze output now. Notice the kernel time, about 36s.
Tried switching to previous kernels, still slow. Here's the inxi -Fz info. Unfortunately, I don't know exactly what to look for in the dmesg info. Only other query I found related to my issue is this one.
I don't think my issue can be resolved by decreasing different service's startup time. But here's the blame and critical-chain output anyway;
blame and critical-chain.
I'm just including blkid, grub and fstab info, it that's required.
Thanks. Kindly let me know, if any other info is required.
Comment: Try `sudo update-initramfs -u -k all`
Comment: @kenn How will this help when the problems are with fstab and NCQ disk errors?
Comment: @heynnema Editing some system files may give rise to conflicts. Rebuilding initial ramdisk will solve such issues.
Comment: @kenn ramdisk has nothing to do with incorrect mounts in /etc/fstab, or with NCQ disk errors. Fixing /etc/fstab won't "give rise to conflicts". Did you read my answer?
Comment: @heynnema there is nothing wrong running `sudo update-initramfs -u -k all`. It will check if modified system files are consistent, else it will print errors. Initial ramdisk is important for fast boot. I also don't know all the modification user did. So my suggestion is a general approach rather than your specific answer.
Answer: BIOS
ASUS X556UB v: 1.0
You have BIOS version X556UB.411. Version 412 is available here.
Note: Confirm that I have the correct web page for your model #.
Note: Have good backups before updating the BIOS.
Nvidia GM108M [GeForce 940M]
It looks like you're using the nouveau video driver. The Nvidia driver would provide better performance. The Nvidia driver can be downloaded here. (Or use Software & Updates Additional Drivers tab).
FSTAB (the real problem #1)
Note: 1.309s home-shawon-Store.mount
Change this line:
/dev/sdb1    /home/shawon/Store    ntfs    defaults,noatime,uid=1000,x-gvfs-hide    0    2

To this:
/dev/sdb1    /home/shawon/Store    ntfs    defaults,noatime,uid=1000,x-gvfs-hide    0    0

Note: For more reliable operation, change the /dev/sdxx to UUID=xxxxxxxxxxxxxxx
NCQ errors (the real problem #2)
Note: ata2.00: failed command: READ FPDMA QUEUED
Native Command Queuing (NCQ) is an extension of the Serial ATA protocol allowing hard disk drives to internally optimize the order in which received read and write commands are executed.
Edit sudo -H gedit /etc/default/grub and change the following line to include this extra parameter. Then do sudo update-grub to write the changes to disk. Reboot. Monitor hangs/etc., and watch grep -i FPDMA /var/log/syslog* or dmesg for continued error messages.
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash libata.force=noncq"

SWAP
Suggest the use of a /swapfile, instead of a swap partition.
Note: Incorrect use of the rm and dd commands can cause data loss. Suggest copy/paste.
In the terminal...
sudo swapoff -a           # turn off swap
sudo rm -i /swapfile      # remove old /swapfile

sudo dd if=/dev/zero of=/swapfile bs=1M count=4096

sudo chmod 600 /swapfile  # set proper file protections
sudo mkswap /swapfile     # init /swapfile
sudo swapon /swapfile     # turn on swap
free -h                   # confirm 16G RAM and 4G swap

Edit /etc/fstab, using sudo -H gedit /etc/fstab or sudo pico /etc/fstab.
Confirm this /swapfile line in /etc/fstab... and confirm no other "swap" lines... use SPACES in this line... confirm NO TABS...
/swapfile  none  swap  sw  0  0

Note: Comment out this line in /etc/fstab...
UUID=76408dec-2d63-402b-9624-fc562b8e9b5b    none    swap    sw    0    0

reboot                    # reboot and verify operation

Comment: Hi, @heynnema! First of all, thank you for taking your time to provide such detailed response.
Luckily I already resolved my issue through [fstab modification](https://pastebin.ubuntu.com/p/Pf3G3TnzQ3/) and switching to nvidia. Kernel time is about 4s now.
Comment: Now, upon your suggestion, I updated the bios, switched to using swapfile and modified the /etc/default/grub. while checking with `sudo dmesg -HT | grep -i --color=never ata2 | grep -i --color=never failed` found some [error](https://pastebin.ubuntu.com/p/2f7V2HJJgm/).
Comment: Unfortunately, I had to switch back to nouveau again. For the life of me I couldn't run windows 7 guest in vmware workstation pro (16.2.1) while the nvidia driver was active. But that's another can of worms and (probably) outside of this question's scope. I tried with nvidia-driver-495 and nvidia-driver-470, but no luck. Finally I settled with nvidia-driver-470, but set the PRIME Profile to Intel (Power Saving Mode). After that, I couldn't find any nouveau related message/ warning in [dmesg](https://pastebin.ubuntu.com/p/XCGr9gHsrV/). Thanks again, for your assistance.
Comment: @Harley Good on the fstab fix. The ata2 errors occurred after the change of /etc/default/grub and a reboot (required)? Nvidia 495 is beta software. 470 is the correct one to use. Nouveau wasn't creating any errors in dmesg. It was just something I noticed in your other logs that indicated you weren't using Nvidia. Check for any VMWare settings having to do with accelerated GPU. Are you using X11/xorg or Wayland?
Comment: @Harley I reviewed your latest dmesg, and although you're not getting any more NCQ errors, you are getting read/media errors. See Update #1 in my answer. After bad blocking the disk, you **may** be able to remove the NCQ patch. Report back.
Comment: # I rebooted anyway; after every trial, either nvidia-driver change or after running `sudo update-grub`. # Yes, 'Accelerate 3d Graphics' is enabled in vmware guest (win7_x64) display settings. # My session type is `x11`.
Comment: @Harley Turn off "Accelerate 3D Graphics", put Nvidia in Performance Mode, reboot and retest. Let me know how the bad blocking goes.
Comment: Sadly I can't fix this with `e2fsck` as /dev/sdb is a ntfs formatted disk. Although I can employ the `chkdsk` from Windows 10. On the other hand both linux partitions are on ssd (sda), in that case, you advised NOT to use `e2fsck` on ssd. [Here's](https://pastebin.ubuntu.com/p/P2s838KddJ/) the `blkid` output.
Comment: @Harley Do both `chkdsk /f` and `chkdsk /r` on /dev/sdb.
Answer: Your log file shows the most time-consuming process with the line:
6.458s NetworkManager-wait-online.service

Therefore it would appear your biggest performance gain would be to have systemd not wait for the network to come up.  See:

What does NetworkManager-wait-online.service do?

The answer explains the process in detail but, to summarize, you can use:
sudo systemctl disable NetworkManager-wait-online.service

Long kernel boot time
From this answer:

Long kernel load time

Try enabling Intel SpeedStep in BIOS.
Comment: That didn't help. In this case, it was not responsible for high kernel time. here's the new [systemd-analyze](https://pastebin.ubuntu.com/p/MK3gbtHHVR/) and [blame](https://pastebin.ubuntu.com/p/kwsWmDQNgb/) output after rebooting. Kernel time (about 35s) was barely deviated by this change.
Comment: @Harley After booting check `dmesg` for long times between commands. I've revised the answer with possible solution if that occurs.
Comment: @WinEunuuchs2Unix The problem is with the mount for Store in /etc/fstab, and NCQ errors.
Comment: @heynnema Thanks. I've upvoted your answer, but will leave mine here for the time-being as a general solution for others coming to this question.

Really high kernel boot time


Using M2 command on Thales Payshield 9000 HSM to decrypt a message

Question: I am provided with an HSM Encrypted message (HEX format), and I'm supposed to implement the decryption using M2 command of that message. I have:

Encrypted data: M1000030DF29D4728FE8365D1FA6ACF96E50A3CFC7F4013A6C8D6624
Keys:

ZMK clear 1: <32 HEX digit key>
ZMK clear 2: <32 HEX digit key>
ZMK clear 3: <32 HEX digit key>
IWK/ZMK encrypted: <32 HEX digit key> / Key Check Value: <6 HEX digit key>

Provided the above data, how can I implement the decryption in Python?
Answer: Combine the ZMK key by XOR 3 clear components of ZMK. And use the combined key to Import the IWK (encrypted under LMK). At last use the IWK to decrypt the message from M100.
To form the M2 message, you may refer to the sample structure below:
Comment: Any idea how can I implement that in Python?
Comment: which part you don't know how to do? combine key? communicate with hardware? form M2 message?
Comment: The thing is that I'm not using any hardware in the process. I just want to implement it programmatically.


prove equilateral triangle

Question: Recently I have encountered such a proving problem.
As shown below, given a $\triangle ABC$, $AD$ intersects $BC$ at $D$ so that $AD$ is perpendicular to $BC$, $BE$ intersects $AC$ at $E$ so that $BE$ is the angle bisector of $\angle ABC$, $CF$ intersects $AB$ at $F$ so that $CF$ is the median of $AB$, $AD$, $BE$, $CF$ intersect at a common point.

We need to prove that triangle ABC is an equilateral triangle. I have tried several approaches, but it seems useless in the end.
Any thoughts? Or is it actually not an equilateral triangle?
Answer: I naively thought such a triangle would have to be equilateral, but when I tried to demonstrate it by construction I ended up producing a counterexample pretty easily.
Start by fixing points $A$ and $B$. We also fix a third point $C^\prime$ and require that $C$ lie on the ray $\vec{BC^\prime}$. Drop a perpendicular from $A$ down to $BC^\prime$ and call the point of intersection $D$. Next construct the angle bisector of $\angle ABC^\prime$; denote the intersection of the angle bisector with the line $AD$ by $G$. Finally, construct the midpoint $F$ of $AB$, and extend a line through $F$ and $G$. The intersection of $FG$ and $BC^\prime$ determines the third vertex of the triangle, $C$.
The result is that for any angle $\angle ABC^\prime$, there is a point $C$ such that the triangle $\triangle ABC$ satisfies all of our hypotheses. And of course, if $\angle ABC^\prime$ is not necessarily $60^\circ$, then $\triangle ABC$ is not necessarily equilateral.

EDIT: The last paragraph is not entirely correct. The first sentence should read: for any $\color{red}{\text{non-obtuse}}$ angle $\angle ABC^\prime$, there is a point $C$ such that the triangle $\triangle ABC$ satisfies all of our hypotheses.
Comment: Thanks a lot! I understand it now.
Comment: @qsmy You're quite welcome. Note that I just edited my response to include a minor correction.
Comment: Yep. I see your edit.

prove equilateral triangle


How to restart a Python script in itself

Question: I'm writing a script using Flet and I need to write a script to restart the app, but I don't know how to implement it.
Here's the code:
def theme_changed(e):
        print(data["theme"])
        data["theme"] = str(theme_dd.value)
        print(data["theme"])

        def close_app(e):
            page.banner.open = False
            #Here I need the code
        def restar_late(e):
            page.banner.open = False
            page.update()

        page.banner = ft.Banner(leading=ft.Icon(ft.icons.SETTINGS,color=ft.colors.RED_100,size=40),content=
            ft.Text("Please restart the application\nto apply the changes",font_family=font),actions=[
                ft.ElevatedButton("Restart Now",style=buttonsStyle,on_click=close_app),
                ft.ElevatedButton("Restart Late",style=buttonsStyle,on_click=restar_late)
            ],open=True)
        page.update()

Comment: Long story short (but your own use case may not require it and given answer may suffice):  if you're running say a webserver that has to stay up but needs restarting, you may need a class of program  that manages other processes, starts them, keeps themup if they fail, restarts them - https://en.wikipedia.org/wiki/Init - that might be`systemd` on Linux, `Service Manager` on Windows…. Again, *you* may not need this, but mentioning just in case.
Comment: The code as posted results in 11 times `IndentationError: unexpected indent`. Can you [fix](https://stackoverflow.com/posts/76643724/edit) the indentation? But *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***[without](https://meta.stackexchange.com/a/131011)*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** "Edit:", "Update:", or similar - the question should appear as if it was written today)
Answer: import os
import sys

def restart_script():
    python = sys.executable
    os.execl(python, python, *sys.argv)

# Your script code here

# When you want to restart the script:
restart_script()

Comment: Wouldnt you have the same script, twice, after this?  A webserver might refuse to start as well, seeing another pgm (its copy) is using the configured port.  The *code* looks ok, but I'd be cautious about assuming it worked.
Comment: I have an error: C:\Program: can't open file 'D:\\[Python Script Folder]\\Files\\Python311\\python.exe': [Errno 2] No such file or directory
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: Note that Windows does not support anything like the Unix `exec()` syscall. I assume the Python run-time is emulating that behavior by spawning a new process, waiting for it to terminate, then terminating the current process.
Comment: @KirilAf, See my previous comment. You should avoid the solution in this answer on Windows. As JL Peyret pointed out in their comment it is better to simply kill the current process and use a process manager to restart it.


Creating smart login/my account buttons

Question: How can I make my php website be able to tell if a user is logged in?
I want to show a link to "my account" instead of "Login".
EX. user goes to home page and clicks "login" on top right corner, then after logging in when browsing the home page again it will display "my account" instead of "login".
This is what the login button looks like. I want to be able to replace this with "my account" if a user is logged in.
https://i.stack.imgur.com/8xCDB.png
UPDATE: This is the code im attempting to use now. its giving me errors on lines 69/72
    <form action="scripts/login.php" id="login-form">
        <fieldset>
        <?php
       if(isset($_SESSION['name_of_user']))
       {
    **LINE 69** My AccountForgot Password?
Register     }
        }
        else{
    **LINE 72**     LoginForgot Password?
Register     }
        ?>

Comment: Don't know why people are downvoting and not letting you know why. Its obvious what the question is, and (although it is "basic" php) if you don't know it then its perfectly valid to ask the question. Ignore the downvoters (especially the silent ones).
Comment: I agree; a perfectly valid question. I guess that the silent downvoters are those who do not know the answers themselves. :)
Answer: So you need to use sessions to do this.
First of all you call this right at the top of your php file:
session_start();

To start the session, then you can set $_SESSION variables. When the user logs in you can set (for example):
$_SESSION['user_name'] = "Lucas Weir";

Then on the next php script you can do:
if(isset($_SESSION['user_name'])){
    // user is logged in, hide the button here
} else {
    // user is not logged in, show the login button
}

Sessions aren't complicated at all, but its worth looking into them. This is a very basic way of using sessions, but it isn't very secure at all. To be honest, I'm surprised you've managed to create a whole user login/authentication script without using sessions yet. ;)
Edit: a bit more info.
Sessions are stored on the server. They are "similar" to cookies. A session token is stored in a cookie on the client computer. This is then used to cross reference the session information stored on your server.
As the session token (Session id) is stored on the client computer, it can send it every time another one of your scripts loads. This means that when you set a session variable using $_SESSION['name'] = "value"; the same value can be retrieved on the next script that gets called.
For a bit more information and some examples/tutorials have a look here: http://www.w3schools.com/php/php_sessions.asp
Comment: @Gary you're welcome. :) I typed up a few examples to show you some more cool stuff you can use to make things easier/look better: http://pastebin.com/xq04DfU6 Hope that helps. :)
Comment: You can't just put HTML in PHP like that. You must close the PHP tags first. Do something like this: `HTML Here (you've close the PHP tag)Some more HTML here`
Comment: Thanks a million ill try this out and look into that. :)
Comment: this is the code im using now with your recommendations but dreamweaver is giving me syntax errors on lines 69 and 72 look above
Comment: Inside PHP you have to echo the HTML
Comment: @LucasWeir you're ok. :) its difficult when you don't know how what you're doing. You'll pick it up.
Comment: @Thomas I never though to break out of PHP in the middle of an if-statement.  That's why I love this site, I was trying to help and ended up learning something new myself.

Creating smart login/my account buttons


I'm after a reference for specific CLI instances

Question: I've had a good search online but cannot find a reference for what certain commands do.
Specifically, I'm talking about when in the Terminal a minus/dash followed by a letter is used in a command.
Some of them I do know, like -h for human readable, -V for version etc.
As an example I cannot find anything that explains the -m in the following command:
python3 -m venv my_env
Also can anyone explain, does it matter where in the command the -m for example is placed? Could it be at the end or middle? And does -m always do the same or does that change depending on the command being entered?
Are they specific to Debian based distros?
If anyone has a reference they could point me too that would be great.
Comment: https://www.commandlinux.com/man-page/man1/python3.1.html
Comment: Please refer https://askubuntu.com/help/on-topic, Ubuntu and official flavors of Ubuntu (https://ubuntu.com/download/flavours) are on-topic on this site. The on-topic link provides alternate SE sites for non-Ubuntu OSes.   *Ubuntu maybe a Debian based distro, but your question isn't specifically on-topic as I read it*.
Comment: just FYI:  beyond `man` (which does require you to know the command before you can look up it's page), there are also other manual like tools.  `apropos` (eg. `apropos directory` can let you know `ls` is the command will display a directory, along with every other directory related tool), `info` & more...  (many commands will provide documentation with `--help` or `-h`  (--help for GNU commands, -h or equiv. if they're older unix commands from 70s & 80s)
Answer: You can get the manpages (the manual) with the man command.
This will give you a description of the command and details about how to use the command.
Example: man grep
Comment: How did I not know about this!? Awesome, thanks!


send data from the UI thread to another thread which is not created in by the Main Activity "Android"

Question: I checked in several websites but i didn't find an answer to this question.
I have a UI thread that calls a service with an alarmManager at a specific frequency.
and the service by itself calls another IntentService, that starts a Server/client thread. I want to know if it is possible to make the Server/Client Threads communicate with the UI thread?
Thanks a lot for your help.
Comment: You can bind service to your activity.
Answer: The IntentService.onCreate() method is always executed on the UI thread. You can create a new Handler instance inside that method and store it in an instance or a class data member of your IntentService implementation. You can use this Handler to post(Runnable) to be executed on the UI thread, or sendMessage(Message) which will be processed on the UI thread by your handleMessage(Message) implementation. I would suggest to stick with post(Runnable) for simplicity.
Update based on your comment:
Assuming your background thread does continuous processing on its own and does not have a looper, the easiest way would be to create a queue (ArrayList<MyLocation> would work for example), and add each new location to the tail of it from the UI thread. Meanwhile the background thread picks the next location from the head and processes it as expected. This is a very simple asynchronous way of communicating between the two threads (and is essentially a simplified version of how Looper and Message work).
However, the main drawback of this approach is that your background thread is always busy thus waisting CPU resources if there are no incoming location updates. The better alternative would be to change your background thread to be a Looper thread and send Message to it. Here's an example of how to Create Looper thread and send a Message to it.
Comment: Thanks for your answer.
In my case i have a location listener in the main Activity, and when the onlocationchanged() i would like to send the new location to the thread Server/client launched by the IntentService. How can it be possible if my handler is created in the Intentservice and not in UI thread?


PostgreSQL run query as a string in place of sql file

Question: I have a need to run a query for maintenance reasons as below using psql
psql -U postgres -d test 'update sometbl set col1 = true;'

I could put the query in a sql file and run it using -f option but I really need this to run from within a bash script and don't want to have to use an additional sql file for this simple query.
Comment: `psql ... -c 'update ...'`
Answer: You can execute a command via the psql command line interface with the parameter -c.
So in your example, this would be:
psql -U postgres -d test -c 'update sometbl set col1 = true;'

Refer to the documenation of psql here: https://www.postgresql.org/docs/9.2/app-psql.html


Edit (split) string in PowerShell?

Question: How can I split the string "FOLDER03631140M/1/7010-win10-A01-GR1XM.CAB" cleanly at the second "/" or discard the front part of the string? Theoretically, this is halfway clear to me, but desperately easy to do... Unfortunately, I still lack the routine...
Result should be that only "7010-win10-A01-GR1XM.CAB" remains from the string.
I am happy about your support
Greetings
Nils
Comment: `("FOLDER03631140M/1/7010-win10-A01-GR1XM.CAB" -split '/')[-1]` --> `7010-win10-A01-GR1XM.CAB`
Comment: Does this answer your question? [Substring to Get Text after Second Period in Powershell](https://stackoverflow.com/questions/27513886/substring-to-get-text-after-second-period-in-powershell)
Comment: Does this answer your question? [Split a Path and take out only the last part (filename) Powershell](https://stackoverflow.com/questions/54305545/split-a-path-and-take-out-only-the-last-part-filename-powershell): `Split-Path -Leaf FOLDER03631140M/1/7010-win10-A01-GR1XM.CAB`
Answer: Try this:
<code>$string = "The string"
$string.split("/")[2]
</code>
Here .split returns an array and we have now 3 elements. Now we can get that part in the 2nd element.

Edit (split) string in PowerShell?


Tiling optimization gcc vs clang

Question: I was looking for L1 cache optimization using the tiling method.
This is the optimization technique I'm using:
// Original loop
void original_loop() {
  for (int i = 0; i < N; i++) {
    sum += array[i];
  }
}

// Loop tiling
void tiled_loop() {
  for (int i = 0; i < N; i += 16) {
    for (int j = 0; j < 16; j++) {
      sum += array[i + j];
    }
  }
}

Then interestingly enough, I found that the tiled loop in clang was actually slower than the original loop (or about the same speed).
This is my benchmarking code:
#include <chrono>
#include <iostream>

const int N = 10000;
const int blockSize = 16;
int array[N];
int sum;

// Original loop
void original_loop() {
  for (int i = 0; i < N; i++) {
    sum += array[i];
  }
}

// Loop tiling
void tiled_loop() {
  for (int i = 0; i < N; i += blockSize) {
    for (int j = 0; j < blockSize; j++) {
      sum += array[i + j];
    }
  }
}

int main() {
  // Initialize array
  for (int i = 0; i < N; i++) {
    array[i] = i;
  }

  // Benchmark original loop
  auto start = std::chrono::high_resolution_clock::now();
  for (int i = 0; i < 100000; i++) {
    sum = 0;
    original_loop();
  }
  auto end = std::chrono::high_resolution_clock::now();
  std::chrono::duration<double> elapsed = end - start;
  std::cout << "Original loop: " << elapsed.count() << " seconds" << std::endl;

  // Benchmark tiled loop
  start = std::chrono::high_resolution_clock::now();
  for (int i = 0; i < 100000; i++) {
    sum = 0;
    tiled_loop();
  }
  end = std::chrono::high_resolution_clock::now();
  elapsed = end - start;
  std::cout << "Tiled loop: " << elapsed.count() << " seconds" << std::endl;

  return 0;
}

Some results using gcc 12.2 and -O3 and clang 15.0.0 and -O3:
For N = 1000000 and blockSize = 16
**GCC**
Original loop: 11.1892 seconds
Tiled loop: 9.67448 seconds
**Clang**
Original loop: 8.52184 seconds
Tiled loop: 8.67858 seconds

Smaller numbers:
For N = 10000 and blockSize = 16
**GCC**
Original loop: 0.094786 seconds
Tiled loop: 0.0436597 seconds
**Clang**
Original loop: 0.0416874 seconds
Tiled loop: 0.0610718 seconds

I've tried this a lot of times. Clang is either doing the same or worse than the original loop. Occasionally it does better than the original one but even then the difference is not as significant as gcc. Any idea?
Here is the assembly (I couldn't find the link to the assembly code to post here. Maybe someone can replace this code with the godbolt link):
GCC:
original_loop():
        mov     ecx, DWORD PTR sum[rip]
        mov     eax, OFFSET FLAT:array
        mov     edx, OFFSET FLAT:array+40000
        pxor    xmm0, xmm0
.L2:
        paddd   xmm0, XMMWORD PTR [rax]
        add     rax, 16
        cmp     rdx, rax
        jne     .L2
        movdqa  xmm1, xmm0
        psrldq  xmm1, 8
        paddd   xmm0, xmm1
        movdqa  xmm1, xmm0
        psrldq  xmm1, 4
        paddd   xmm0, xmm1
        movd    eax, xmm0
        add     eax, ecx
        mov     DWORD PTR sum[rip], eax
        ret
tiled_loop():
        pxor    xmm1, xmm1
        mov     eax, OFFSET FLAT:array
        mov     edx, OFFSET FLAT:array+40000
        movd    xmm3, DWORD PTR sum[rip]
        movdqa  xmm2, xmm1
        movdqa  xmm0, xmm1
.L6:
        paddd   xmm3, XMMWORD PTR [rax]
        paddd   xmm0, XMMWORD PTR [rax+16]
        add     rax, 64
        paddd   xmm2, XMMWORD PTR [rax-32]
        paddd   xmm1, XMMWORD PTR [rax-16]
        cmp     rdx, rax
        jne     .L6
        paddd   xmm0, xmm3
        paddd   xmm0, xmm2
        paddd   xmm0, xmm1
        movdqa  xmm1, xmm0
        psrldq  xmm1, 8
        paddd   xmm0, xmm1
        movdqa  xmm1, xmm0
        psrldq  xmm1, 4
        paddd   xmm0, xmm1
        movd    DWORD PTR sum[rip], xmm0
        ret
sum:
        .zero   4
array:
        .zero   40000

Clang:
original_loop():                     # @original_loop()
        pxor    xmm0, xmm0
        mov     eax, 12
        movd    xmm1, dword ptr [rip + sum]     # xmm1 = mem[0],zero,zero,zero
        lea     rcx, [rip + array]
.LBB0_1:                                # =>This Inner Loop Header: Depth=1
        paddd   xmm1, xmmword ptr [rcx + 4*rax - 48]
        paddd   xmm0, xmmword ptr [rcx + 4*rax - 32]
        paddd   xmm1, xmmword ptr [rcx + 4*rax - 16]
        paddd   xmm0, xmmword ptr [rcx + 4*rax]
        add     rax, 16
        cmp     rax, 10012
        jne     .LBB0_1
        paddd   xmm0, xmm1
        pshufd  xmm1, xmm0, 238                 # xmm1 = xmm0[2,3,2,3]
        paddd   xmm1, xmm0
        pshufd  xmm0, xmm1, 85                  # xmm0 = xmm1[1,1,1,1]
        paddd   xmm0, xmm1
        movd    dword ptr [rip + sum], xmm0
        ret
tiled_loop():                        # @tiled_loop()
        mov     edx, dword ptr [rip + sum]
        xor     eax, eax
        lea     rcx, [rip + array]
.LBB1_1:                                # =>This Inner Loop Header: Depth=1
        movdqa  xmm0, xmmword ptr [rcx + 4*rax]
        movdqa  xmm1, xmmword ptr [rcx + 4*rax + 16]
        paddd   xmm1, xmmword ptr [rcx + 4*rax + 48]
        paddd   xmm0, xmmword ptr [rcx + 4*rax + 32]
        paddd   xmm0, xmm1
        pshufd  xmm1, xmm0, 238                 # xmm1 = xmm0[2,3,2,3]
        paddd   xmm1, xmm0
        pshufd  xmm0, xmm1, 85                  # xmm0 = xmm1[1,1,1,1]
        paddd   xmm0, xmm1
        movd    esi, xmm0
        add     esi, edx
        cmp     rax, 9983
        ja      .LBB1_3
        movdqa  xmm0, xmmword ptr [rcx + 4*rax + 64]
        movdqa  xmm1, xmmword ptr [rcx + 4*rax + 80]
        paddd   xmm1, xmmword ptr [rcx + 4*rax + 112]
        paddd   xmm0, xmmword ptr [rcx + 4*rax + 96]
        paddd   xmm0, xmm1
        pshufd  xmm1, xmm0, 238                 # xmm1 = xmm0[2,3,2,3]
        paddd   xmm1, xmm0
        pshufd  xmm0, xmm1, 85                  # xmm0 = xmm1[1,1,1,1]
        paddd   xmm0, xmm1
        movd    edx, xmm0
        add     edx, esi
        add     rax, 32
        jmp     .LBB1_1
.LBB1_3:
        mov     dword ptr [rip + sum], esi
        ret
array:
        .zero   40000

sum:
        .long   0

Edit
With -march=native flag
Original loop: 0.0292406 seconds
Tiled loop: 0.173324 seconds

clang performs 10x worse
Comment: Both of them are divisible by 16 @user17732522
Comment: Sorry, that was stupid.
Comment: Clang tends to generate a (very) bad code when there is an inner loop that should be vectorized like in your code. I experienced that several times so I [filled this bug](https://github.com/llvm/llvm-project/issues/53507) which is still opened. I do not really understand the answer so far : It looks like it is normal for LLVM developers... Fill free to add your example in this post if you think it is similar. You could also fill a new bug and link this one. Adding more example and having more complaining users should certainly result in more engagement.
Comment: By the way: Clang is based on LLVM internally and LLVM is responsible for such doing the SIMD optimizations passes (and more generally all backend stuff).
Answer: GCC and Clang often optimize things differently.  You're not using -march which you probably need if you want optimal results.  With -O3 -march=skylake, Clang unrolls the loop automatically, and GCC will generate similar code if you add #pragma GCC unroll 16 in original_loop(): https://godbolt.org/z/WWr1nToaG
With tiling, GCC's code is OK but Clang's is extremely bloated: https://godbolt.org/z/GYqYTc7cc - I'm not surprised the Clang code runs slower.
If you're going to use tricks like this to try to make a compiler generate better code, you have to accept that it is compiler specific.  Tweaks that help on one setup may hurt on another, and it won't be easy to predict.  Usually if you write simple code like your original_loop(), at least a given compiler will tend to improve (or stay the same) when newer versions come out.
Comment: I understand that GCC can be faster than Clang for a specific problem (or vice versa). But I don't understand how tiling can be slower than the original loop (using the same compiler).
Comment: And interestingly enough `-march=tigerlake` made it slower for me.
`clang++ -O3  -Wall -march=tigerlake`
`Original loop: 0.0289829 seconds
Tiled loop: 0.233685 seconds`
I'm using 11th gen intel coretm i7-11800h processor
Comment: *"I don't understand how tiling can be slower than the original loop"* - if you really want to understand it, use a profiler like Intel VTune.  But the overall lesson is simple: you can't always beat the compiler with clever tricks.  Tiling in this case has made the optimizer less able to do its job.  That's OK, we want the optimizer to do a good job with normal code.

Tiling optimization gcc vs clang


Can I apply polymeric sand only on a x inches wide stretch where the patio joins the wall?

Question: I am in the process of regrading my patio. I had a wet wall problem because the patio was sloped toward the house. I want to make sure that no water gets near the wall again, even with the correct slope applied.
For this I would like to apply polymeric sand on a strip of let's say 3 foot where the patio joins the wall.
Is this a good idea?
Comment: What type of wall is the patio adjoining?
Comment: The foundation is concrete walls up to the grade level. Above that it seems to be cinder blocks up the the main floor level. This is a bungalow with above the grade basement windows.
Answer: So you want to put 3 foot strip in width of polymeric sand over existing pavers? You will be OK with how that would look? I am just not sure how well such a strip will stay together over the long haul.
I sure wouldn't do it, I would bite the bullet and pull up the pavers then regrade the base away from the house and put the pavers back.
Comment: I have already done that but not I want to make sure there is no way my wall gets water again, not even the minimal infiltration when the water gets through the joints between the pavers. Yes probably the polymeric sand is not a good idea if it is not applied for the entire patio...
Comment: If you have already graded away from your house, then not much should get in. But some still could. I think the best way to really keep it out would be a moisture barrier over your outside wall extending down a foot or so from the top of your pavers.
Comment: Yes I think that this is the solution. Any idea what I could use for that?
Answer: Polymeric sand is to lock paver joints. It's not waterproof any more than concrete (less so, even).
So if the intent is to use it as a waterproofer along your wall, it won't do much.


Makita product lines comparison

Question: I have been looking at different Makita tools and I can see what seems to be two different product lines but I fail to find any information online that would suggest what is the actual differences between the models. For example there are XMT and DTM models of multitools and all I can see is that both have variable speed control dial (6, 000 to 20, 000 OPM) and that's it. The price ranges differ quite a lot while the DTMs are significantly cheaper. Can anyone shed some light and point to any actual differences between those model lines?
Comment: Unfortunately, "shopping" questions are off-topic here. Please [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Comment: After using my first Makita drill , I replaced all my power tools with Makita brand tools ( except the radial arm).
Answer: The Makita XMT series of tools is marketed toward tradespeople and professionals while the DMT is for the mass market.  Little outward differences but generally there are significant differences in durability and reliability.  You'll find DMT at big box stores and the like.  Usually you'll only find XMT at professional supply outlets.
If you are just going to be using it for typical homeowner duties, the DMT is your best value.  If you expect to use the tool to make a living, then consider XMT.
Comment: Excellent! Thank you very much for the info! I am just curious how such a significant fact is so hard to find using the official Makita sources.

Makita product lines comparison