text:
Q: d3 stratify - missing data field I am using stratify to build a d3 tree from a flat data structure. However, some fields are missing when I try to call them with d.data.fieldname
Here is my data structure:
var flatData = [

  {"name": "Data Encrypted", "parent": null, "category": "test", "score": null },
  {"name": "Malware on Target", "parent": "Data Encrypted", "category": "test", "score": null  },
  {"name": "Malware executed", "parent": "Data Encrypted", "category": "test", "score": "1"  },
  {"name": "Files modified", "parent": "Data Encrypted", "category": "test", "score": "1"  },

];

I am building the hierarchical data structure with this stratify command:
var treeData = d3.stratify()
  .id(function(d) { return d.name; })
  .parentId(function(d) { return d.parent; })
  (flatData);

The d3 tree is displayed correctly, and I can expand / collapse nodes etc, and display the ID and Name of each node using d.data.id and d.data.name respectively. If I try and use d.data.score or d.data.category to display data I get an 'undefined' error.
Any information that can help me get past this issue would be greatly appreciated.


text:
Q: Drupal не подгружется css и js Залил drupal на хост, открыл стартовую страницу друпала а там такая штука

не подгружаются css. Посмотрел в консоль, не может загрузить ни css файлы, ни js, с проблемой 500. Как решать? php 7.2, drupal 8.6.2

A: Проверь права доступа к папкам:

*

*sites

*sites/default

*sites/default/files

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using linux sort on multiple files Is there a way I can run the following command with Linux for many files at once?
$ sort -nr -k 2 file1 > file2

A: I assume you have many input files, and you want to create a sorted version of each of them.  I would do this using something like
for f in file*
do
    sort $f > $f.sort
done

Now, this has the small problem that if you run it again, if will not only sort all the files again, it will also create file1.sort.sort to go with file1.sort.  There are various ways to fix that.  We can fix the second problem by creating sorted files thate don't have names beginning with "file":
for f in file*
do
    sort $f > sorted.$f
done

But that's kind of weird, and I wouldn't want files named like that.  Alternatively, we could use a slightly more clever script that checks whether the file needs sorting, and avoids both problems:
for f in file*
do
    if expr $f : '.*\.sort' > /dev/null
    then
        : no need to sort
    elif test -e $f.sort
    then
        : already sorted
    else
        sort -nr -k 2 $f > $f.sort
    fi
done


text:
Q: \usepackage[turkish]{babel} and \includegraphics inconcistency Here is my document :
\documentclass[12pt]{book}

% must-have packages
\usepackage[turkish]{babel}
\usepackage[utf8]{inputenc} % This package will support Turkish chars
% must-have packages

\usepackage[a4paper,left=2.5cm,right=2cm]{geometry}
\usepackage{graphicx}
\usepackage{listings}

% settings
\setcounter{secnumdepth}{0}
% settings

\begin{document}

\framebox{\includegraphics[scale=0.5]{./images/image_3.png}}

\end{document}

When I try to build a pdf out of this file I received bunch of errors. here is one of them :

Missing \endcsname inserted
  ...graphics[scale=0.5]{./images/image_3.png}}

When I remove the babel package, it runs smoothly. Even when I change the language to another language, it runs as well.
What is happening here?

A: Please check the answers on this question: \newgeometry doesn't work with Turkish babel package. One answer by @karlkoeller gives an automatic way of switching the shorthand off before \includegraphics then on again after it.

A: I believed that this problem had been solved, but it seems not.
Since you can input directly Turkish specific characters as Unicode, you should not need the = shortcuts; so
\begin{document}
\shorthandoff{=}

will cure the problem. In case you really need the shortcuts with =, the unique way seems to be to say
\shorthandoff{=}

before all \includegraphics commands and \shorthandon{=} again after them.


text:
Q: Write a curl request in R I have necessary data about parameters for curl request that i need. They all are in this json:
        {
            "name": "GET /tablesbyquery",
            "protocolProfileBehavior": {
                "disableBodyPruning": true
            },
            "request": {
                "auth": {
                    "type": "bearer",
                    "bearer": [
                        {
                            "key": "token",
                            "value": "hnjP4YUFwoR0jhUy_q8jF99jK5WlQ",
                            "type": "string"
                        }
                    ]
                },
                "method": "GET",
                "header": [],
                "body": {
                    "mode": "raw",
                    "raw": "",
                    "options": {
                        "raw": {
                            "language": "json"
                        }
                    }
                },
                "url": {
                    "raw": "http://source.os-pub.com/tables/tablesbyquery?timePeriod=actual&sort=utdDate,asc&query=&isNotEmptyStatus=false&size=20&page=0&providerId=",
                    "protocol": "http",
                    "host": [
                        "source",
                        "os-pub",
                        "com"
                    ],
                    "path": [
                        "tables",
                        "tablesbyquery"
                    ],
                    "query": [
                        {
                            "key": "timePeriod",
                            "value": "actual"
                        },
                        {
                            "key": "sort",
                            "value": "utdDate,asc"
                        },
                        {
                            "key": "query",
                            "value": ""
                        },
                        {
                            "key": "isNotEmptyStatus",
                            "value": "false"
                        },
                        {
                            "key": "size",
                            "value": "20"
                        },
                        {
                            "key": "page",
                            "value": "0"
                        },
                        {
                            "key": "providerId",
                            "value": ""
                        }
                    ]
                }
            },
            "response": []
        }

How to write curl request in R to extract this data? I see that i need to use access token here, but which parameters must also be included? And where should i put this parameters in GET function from httr package?

A: The difficulty with this kind of question is that the person who answers is unable to test their code. Of course, you shouldn't share your real authorisation code, but since the URL is password protected, I don't understand why you need to give a dummy URL, which would make this easier to answer.
I'll therefore need to stick my neck out here and show you what I think should work rather than what I know to work.
Assuming the server is returning json or html, the following code should store the text response to res_text which you can then parse as required.
library(httr)

url      <- "http://source.os-pub.com/tables/tablesbyquery?"
query    <- paste0("timePeriod=actual&sort=utdDate,asc&query=",
                   "&isNotEmptyStatus=false&size=20&page=0&providerId=")
full_url <- paste0(url, query)
key      <- "hnjP4YUFwoR0jhUy_q8jF99jK5WlQ"

res      <- GET(full_url, add_headers(Authorization = paste("Bearer", key)))

res_text <- content(res, "text")


text:
Q: combine two sql update query into one query I have two update queries that I will like to combine into one query
UPDATE table_a DD
SET    DD.tomato = BH.tomato
       DD.juice = 'TRUE'
FROM   table_b BH
WHERE  BH.guava = DD.guava

In the second update query, I want to set DD.banana to true where BH.guava = DD.guava and BH.title = 'Ripe'
UPDATE table_a DD
SET     DD.banana = 'True'
FROM    table_b BH
WHERE   BH.guava = DD.guava
AND     BH.title = 'Ripe'

Any help will be appreciated...
Thanks in advance

A: You can use conditional logic:
UPDATE table_a DD
    SET DD.tomato = BH.tomato
        DD.juice = 'TRUE',
        DD.banana = (CASE WHEN BH.title = 'Ripe' THEN 'True' ELSE DD.banana END)
    FROM table_b BH
    WHERE BH.guava = DD.guava


text:
Q: predict function not evaluating for all given points with F# R-type-provider I am converting a small code snippet to F# using the R type provider. Everything works fine and evaluates, however I cannot seem to make the predict function use all the points I give it for its prediction.
The R code snippet:
Nit = c(0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,6,6,6)
AOB = c(4.26,4.15,4.68,6.08,5.87,6.92,6.87,6.25,6.84,6.34,6.56,6.52,7.39,7.38,7.74,7.76,8.14,7.22)
AOBm=tapply(AOB,Nit,mean) #means of AOB
Nitm=tapply(Nit,Nit,mean) #means of Nit
fitAOB=lm(AOBm∼ns(Nitm,df=2)) #natural spline
predict(fitAOB,data.frame(Nitm=seq(xmin,xmax,.5))

and the coresponding F# code:
let Nit = [0;0;0;1;1;1;2;2;2;3;3;3;4;4;4;6;6;6]
let AOB = [4.26;4.15;4.68;6.08;5.87;6.92;6.87;6.25;6.84;6.34;6.56;6.52;7.39;7.38;7.74;7.76;8.14;7.22]

let AOBm = R.tapply(AOB,Nit, "mean")
let Nitm = R.tapply(Nit, Nit, "mean")

let fitAOB =
    namedParams [
        "AOBm", box AOBm
        "Nitm", box Nitm
    ]
    |> R.data_frame
    |> fun d -> R.lm(formula="AOBm~splines::ns(Nitm,df=2)", data=d)

let xmin, xmax = float(List.min Nit), float(List.max Nit)

let prediction1 =
    namedParams [ "Nitm",[xmin .. 0.5 .. xmax]]
    |> R.data_frame
    |> fun data -> R.predict(fitAOB, data)

prediction1.Print()

The R code snippet gives me following for the prediction:
      1        2        3        4        5        6        7        8
4.753486 5.177103 5.590795 5.984636 6.348702 6.673067 6.947806 7.166302
       9       10       11       12       13
7.335171 7.464340 7.563733 7.643276 7.712893

And the F# code snippet gives me following for the prediction:
val it : string =
  "       0        1        2        3        4        6
4.753486 5.668817 6.470509 7.048984 7.388006 7.660199
"

What am I missing?, eg. why doesn't the predict function take all the [0.0 .. 0.5 .. 6.0] points into account when predicting?

A: Found a way to make R.predict yield the same result as the predict function used from within R.
let prediction1 =
    namedParams [
        "type",box "prediction"
        "Nitm",box [0.0 .. 0.5 .. 6.0]
    ]
    |> R.data_frame
    |> fun d -> R.predict(fitAOB, [0.0 .. 0.5 .. 6.0], d)
prediction1.Print()

which gives
val it : string =
  "       1        2        3        4        5        6        7        8
4.753486 5.177103 5.590795 5.984636 6.348702 6.673067 6.947806 7.166302
       9       10       11       12       13
7.335171 7.464340 7.563733 7.643276 7.712893
"

However, I don't quite understand why I have to repeat the [0.0 .. 0.5 .. 6.0] sequence..


text:
Q: Tetris full row only half-removed I'm trying to create a Tetris game with Processing 3.
My problem is that the highest full row gets only half deleted.
Here are a couple of screenshots to illustrate what happens before the last move:

And after the last move:

Here's the code that handles the deletion of the lines:
void remove_full_line() {
  for(int h = 900; h > 0; h-=50) {
    if (line_sum(h) == 12) { // 12 column-canvas
      for (int i = 0; i < fallen_tetros.size(); i++) {
        if (fallen_tetros.get(i)[1] == h) {
          fallen_tetros.remove(i);
        }
      }
    }
  }
  // ...
  // Code to lower the rows above
  // ...
}

fallen_tetros is an ArrayList<int[]>, and each element contains the x and y coordinates of a single square (not a full tetromino).
As you can see, I use 50x50 squares, so I check for a full line every 50 pixels, starting from the bottom (900).
What concerns me is that the row seems to be considered full since some squares get deleted. But I don't get why only half of them get deleted, and why it happens only on the highest row.

A: You should get into the habit of debugging your code to understand exactly what's going on. Consider adding println() statements to your code, like this:
for (int i = 0; i < fallen_tetros.size(); i++) {
   println("i: " + i);
   if (fallen_tetros.get(i)[1] == h) {
     println("removing: " + i);
     fallen_tetros.remove(i);
     println("tetros size: " + tetros.size());
   }
}

But basically, your problem is caused by the fact that you're removing items from an ArrayList while iterating over it. When you remove an item (say, at index 0), then every other item shifts down by one. You have a new item at index 0. Then your for loop goes to the next index (index 1) and removes that item, and again everything is shifted down by one. You have a new item at index 1, and you move on to index 2. But notice that you're basically skipping over the item that just moved into the index you just removed!
You can get around this problem by looping backwards or by using an Iterator.
Also note that it seems a little weird to mix pixel coordinates with array indexes. Just store everything in a 2D array, or an ArrayList that holds each row (instead of holding each column like your code currently works). That way you don't have to iterate over each cell individually, you can just remove the entire row all at once.


text:
Q: Jquery: submit the closest form I am trying to submit the closest form because there are somany forms in the same id and name
<form id="frmid" method="post">
// so many tags here
<button  onclick="setTimeout(function(){ updatecartshi(this)()}, 1000);">+</button>
// so many tags here
</form>

and the function is
function updatecartshi(obj)(){
   $(obj).closest("#frmCart").submit();
}

but this is not working my my form is not submitted
Thanks in advance

A: You need to set different id for each form. ID is a unique key for each element and can't same with other element id.
If you want to do like that, use class.
<form class="frmid" method="post">
Class name can be same for different element.

A: For the friends who wants to know the answer for this question
  onclick="var obj=this;setTimeout(function(){ $(obj).closest('#frmCart').submit();}, 1000);"


text:
Q: File path errors in eclipse? (Java Spring) InputStream inp = new FileInputStream("src/main/resources/ExportHour.xls");

I have a file in the src/main/resources folder of my Java Spring project.
I am attempting to create an inputstream in one of my Controllers, however I always get a file not found exception. When I change the path location to point specifically to the file on my machine, it works fine.
Any way I can make it so the file can be found within the java project?

A: It sounds like you could just change the working directory of your process - it's not where you think it is, I suspect. For example, I suggest you write
File file = new File("src/main/resources/ExportHour.xls");

and then log file.getAbsolutePath(), to see what exact file it's using.
However, you should almost certainly not be using a FileInputStream anyway. It would be better to use something like:
InputStream inp = Foo.class.getResourceAsStream("/ExportHour.xls");

... for some class Foo which has a classloader which includes the resources you need.
(Or possibly /resources/ExportHour.xls", depending on your build structure.)
That way even when you've built all of this into a jar file, you'll still be able to open the resource.

A: Try with spring ClassPathResource.
InputStream inp = new ClassPathResource("ExportHour.xls").getInputStream();

That is because the resources folder in maven is put in your jar file directly i.e. the ExportHours.xls file is put inside your jar in the root directory.


text:
Q: how to get the httparty call return something inside an array [{"Id"=>1015765, "Date"=>"/Date(1468062000000+0100)/", "EventGroupName"=>"Electric Daisy Carnival", "VenueName"=>"Milton Keynes Bowl", "Town"=>"Milton Keynes", "Country"=>"UK", "TicketCount"=>35, "Currency"=>"GBP", "MinPrice"=>79.75, "LayoutId"=>3932, "EventGroupId"=>32347, "VenueId"=>3596}]

I'm getting this response form an api im calling
How do i go about getting the id to use elsewhere in the controller???
Heres my controller
api = HTTParty.get("url here").parsed_response
id = api["Events"]

I have tried sticking  [Id] on the end of the id call but that didnt work.
Sam
Additional
Heres what i tried :)
id = api["Events"].first["Id"]
    results = HTTParty.get("partoneofurl" + id + "parttwoofurl")

 syntax error, unexpected tIDENTIFIER, expecting ')'

 syntax error, unexpected ')', expecting keyword_end

A: The result of the HTTParty call is an array that contains a hash table with the response elements. To access the these values you need first to access the hash table, that is the array's first element and then you can access the values in the hash table. You can do that in this way:
$ api.first["Key"]


text:
Q: Resizing Ubuntu root partition installed in "Install inside Win" mode I've installed Ubuntu 10.04 Desktop i386 using "Install inside Windows" option. In the installation i dedicated 3GB for the root parition. Now i have a Windows 7 and a Ubuntu.
Currently, I need more space for the Ubuntu root parition (just 50MB freespace remained!). I realized the it is a simple 3GB file in the Windows and root parition is virtually in that file.
So it should be possible to increase the size of the root parition. But i cannot find any way for this.
I do not want to reinstall the my Ubuntu or add another partition. Is there any painless way to just increase the size of root parition?

A: Try this section of the Wubi guide on the Ubuntu wiki.
The reason for adding a second disk (mounted on /home) rather than resizing the original one is that this allows you to do it while booted into Ubuntu from the original virtual disk.
Otherwise you'll need to boot from a live CD, increase the size of the file itself, and resize the file system to fill the space. I can explain further if you're interested in following this route, but using the utility mentioned on the wiki seems a lot easier.
Also, your root file system typically doesn't keep on growing, but home does, so having a separate virtual disk for home seems like a good idea.


text:
Q: How would I translate this C# code into PHP? I need a PHP version of the following C# code:
string dateSince = "2010-02-01";
string siteID = "bash.org";
string sharedSecret = "12345"; // the same combination on my luggage!

using System.Security.Cryptography;

MD5CryptoServiceProvider x = new MD5CryptoServiceProvider();
byte[] dataBytes = System.Text.Encoding.ASCII.GetBytes(string.Format("{0}{1}{2}",   dateSince,  siteID, sharedSecret));
string result = BitConverter.ToString(x.ComputeHash(dataBytes));

... this code snippet appears to be incomplete.  But here's what I think is going on:

*

*concatenating dateSince, siteID, and sharedSecret.  Stealing underpants.

*???

*converting that string into a ascii encoded byte array.

*taking the MD5 hash of that array.
This mysterious BitConverter object appears to be converting that MD5 hashed array, into a string of hexadecimal numbers.  According to the aforementioned doc, the value of result should look something like: "6D-E9-9A-B6-73-D8-10-79-BC-4F-EE-51-A4-84-15-D8"
Any help is greatly appreciated!!

Forgot to include this earlier.  Here's the PHP version of what I've written so far:
$date_since = "2010-02-01";
$site_id = "bash.org";
$shared_secret = "12345";

$initial_token = $date_since.$site_id.$shared_secret;

$ascii_version = array();
foreach($i=0; $i < strlen($initial_token); $i++) {
    $ascii_version[] = ord(substr($initial_token,$i,1));
}

$md5_version = md5(join("", $ascii_version));

$hexadecimal_bits = array();
foreach($i=0; $i < strlen($md5_version); $i++) {
   // @todo convert to hexadecimal here?
   $hexadecimal_bits[] = bin2hex(substr($md5_version,$i,1));
}

$result = join("-", $hexadecimal_bits);

A: I think this will work for you.  It looks like the MD5CryptoServiceProvider::ComputeHash method returns an array of 16 bytes, not a string of 32 characters like the normal PHP md5() function.  However, PHP's md5() has a second optional parameter that forces "raw output", which does correspond to the output of ComputeHash().
$date_since = "2010-02-01";
$site_id = "bash.org";
$shared_secret = "12345";
$initial_token = $date_since.$site_id.$shared_secret;

//get the RAW FORMAT md5 hash
//corresponds to the output of MD5CryptoServiceProvider::ComputeHash
$str = md5($initial_token, true);
$len = strlen($str);
$hex = array();
for($i = 0; $i < $len; $i++) {
    //convert the byte to a hex string representation (left padded with zeros)
    $hex[] = str_pad(dechex(ord($str[$i])), 2, '0', STR_PAD_LEFT);
}
//dump output
echo implode("-",$hex);

//outputs fe-0d-58-fd-5f-3d-83-fe-0f-6a-02-b4-94-0c-aa-7b

A: This is what I see except that what it outputs won't input the dashes. Those would have to be injected some other way.
var $dateSince = "2010-02-01";
var $siteID = "bash.org";
var $sharedSecret = "12345"; // the same combination on my luggage!

var $full_string = $dateSince . $siteID . $sharedSecret;

string result = md5($full_string);


text:
Q: is something difficult to do, or hard to do? When do I say something is difficult to do or hard to do
Or difficult to understand or hard to understand
Thus, when do I use difficult and when do I use hard?

A: Both terms are synonyms, they mean the same.
According to Cambridge dictionary
hard adjective (DIFFICULT)

difficult to understand, do, experience, or deal with

difficult adjective

not easy or simple; hard to do or to understand

EDITED: Take a look below to J.R's comment and to the linked entry of the dictionary. There are additional meanings of hard not shared by difficult.
hard adjective (SOLID)
hard adjective (SEVERE)
hard adjective (ALCOHOL) - A hard drink contains a high level of alcohol
hard adjective (WATER) - Hard water contains a high level of minerals
hard adjective (WEATHER) - Used to describe a time when there is bad weather


text:
Q: How can i remove .php extension from url i have a website that have TWO LANGUAGE. so basically it was set up in .htaccess file. i want to remove the php extension
i've tried this code and still not working
this is the original code that i have
RewriteEngine on
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
#RewriteRule en en/
#RewriteRule id id/
RewriteRule id/(.*)$ $1
RewriteRule en/(.*)$ $1

and this is the code that i've tried
RewriteEngine on
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME}\.php !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
#RewriteRule en en/
#RewriteRule id id/
RewriteRule ^(.*)$ id/(.*)$ $1.php [NC,L]
RewriteRule ^(.*)$ en/(.*)$ $1.php [NC,L]

and the output says "The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script.


text:
Q: Var++ causes RangeError in recursive function parameter in JavaScript I have a simple linear recursive function in JavaScript computing a factorial of a number.
function factorialImproved(n) {

  function factorialIter(p, c, m) {
    if (c > m) {
      return p;
    } else {
      return factorialIter(c * p, c++, m); // RangeError: Maximum call stack size exceeded // ++c or c+1 is OK
    }
  }

  return (factorialIter(1, 1, n))
}

I'm trying to figure out why I get RangeError with c++ but not with ++c or c+1.

A: (c++) evaluates as c. So you are calling factorialIter with the same c every time.
Therefore, c = 1 won't be bigger than m = n unless n < 1.
However, (++c) evaluates as c+1. Just remember this rule:

*

*(++c): first increment then c.

*(c++): first c then increment.

In my opinion, you should be using c+1. Do not use c++ or ++c unless you want to use c in that scope later.

A: You return the same value of c, because with postfix increment, it returns the actual value and then it increments the variable.
For getting a result, you could use just c + 1 as value. Or use prefix increment. But if you do not use the variable again, it is not advisable.

function factorialImproved(n) {

    function factorialIter(p, c, m) {
        if (c > m) {
            return p;
        } else {
            return factorialIter(c * p, c + 1, m); // RangeError: Maximum call stack size exceeded // ++c or c+1 is OK
        }
    }

    return (factorialIter(1, 1, n))
}

console.log(factorialImproved(5));


text:
Q: Codeginiter : chmod(): Invalid argument error I am using pdftk library for modify the pdf files. but i am getting the  chmod(): Invalid argument error.
Following is my code :
  include('fillpdf/createXFDF.php');
    $fdf_file = 'fillpdf/acord.fdf';
    $acord = array();
    $acord['******'] = 'a';
    $acord['******'] = 'a';
    $pdf_file_url  = 'http://localhost/******/fillpdf/Cancellation.pdf';
    $fdf = createXFDF( $pdf_file_url, $acord );
    // print_r($fdf); die;
           if ($fp = fopen($fdf_file, 'w')) {
                chmod($fdf, 777);
                fwrite($fp, $fdf, strlen($fdf));
                $CREATED = TRUE;
            } else {
                echo 'Unable to create file: ' . $fdf_file . '

';
                $CREATED = FALSE;
            }
            // var_dump($CREATED); die;
    fclose($fp);
    $command = '"C:\\Program Files (x86)\\PDFtk\\bin\\pdftk.exe" C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation.pdf fill_form acord.fdf output C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation_new.pdf';
    exec($command);

I have given all the necessary permission to folder and files. but don't know what is wrong??
Thanks in advance!!!

A: Why you need to give chmod($fdf,0777); to $fdf. It's not even the file. as per your code the $fdf = createXFDF( $pdf_file_url, $acord ); is calling function and it's not file. so just comment the chmod($fdf,0777); line and check your code is working or not??
Hope it helps!!!

A: Try like this...For chmod() function first number is always zero.
chmod(file,mode);

The mode parameter consists of four numbers:
1.The first number is always zero
2.The second number specifies permissions for the owner
3.The third number specifies permissions for the owner's user group
4.The fourth number specifies permissions for everybody else
include('fillpdf/createXFDF.php');
    $fdf_file = 'fillpdf/acord.fdf';
    $acord = array();
    $acord['******'] = 'a';
    $acord['******'] = 'a';
    $pdf_file_url  = 'http://localhost/******/fillpdf/Cancellation.pdf';
    $fdf = createXFDF( $pdf_file_url, $acord );
    // print_r($fdf); die;
           if ($fp = fopen($fdf_file, 'w')) {
                chmod($fdf,0777);
                fwrite($fp, $fdf, strlen($fdf));
                $CREATED = TRUE;
            } else {
                echo 'Unable to create file: ' . $fdf_file . '

';
                $CREATED = FALSE;
            }
            // var_dump($CREATED); die;
    fclose($fp);
    $command = '"C:\\Program Files (x86)\\PDFtk\\bin\\pdftk.exe" C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation.pdf fill_form acord.fdf output C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation_new.pdf';
    exec($command);


text:
Q: Question regarding class with static functions and namespace in PHP I am using PHP 5.2.14 at work, so there is no namespace option for me.
Is it acceptable for me to substitute classes with static functions for namespacing?
For example, we have lots of "handy" function lying around that does miscellaneous things that are all bunched into this one file, and they tend to get messy.
I would love to see them follow some sort of organizing logic.
So my solution is this...
I want to just create classes called "StringTools" or "DateTools" and every time we need to do use those function I would simply call SomethingTools::funciton_name(...). It would be simple class filled with static functions, with an empty constructor, made purely for the sake of namespacing and organizing.
It would be easy to manage and very organized, because related functions will be organized into it's own file or even folder, the class calls will be handled by autoload, so we don't even have to include anything.
Is this an acceptable approach to the problem? or is there a better way to deal with organizing functions in pre 5.3 PHP so programmers doesn't step on each others feet when naming them? unorganized stuff really really bugs me and I'm actually looking forward to the hours of extra work I'll be spending sorting this out.

A: This is not just acceptable its probably the only clean solution. The goal of an object should always be to group like functions, so as long as you are following this, it would make sense (IMO) to group these functions into classes. What you want to watch out for is that you actually grouping like functions and not just throwing functions into a class. This will just make the problem worse as it will confuse developers when it comes to finding methods when writing new code.


text:
Q: How to pass props to a React Router route I'm trying to pass data from App to Home component but I don't know how in this situation.
In my App.js, I have firebase auth which holds email when logged in.
I need to pass this to Home component but I don't know how in this situation.I know how to pass data by doing somthing like <Home user={user}> this but not right now.
In where should I put passing data in code like this?
<Route exact  path="/" component={Home} />

I attached my code in CodeSandbox
https://codesandbox.io/s/heuristic-mestorf-8qbx9?fontsize=14&hidenavigation=1&theme=dark
There are App.js  Home.js and Login.js
What i did in App.js is rendering pages and only to see pages when logged in.
Login.js is logging in with firebase auth and finally in Home component, I want to print out user's email.
Can somebody give me clues or help me please?? I will be very thankful:))

A: To pass props into a react-router route you must use a slightly different syntax
<Route
  exact
  path='/'
  render={(props) => <Home {...props} auth={authState} />}
/>

In this case, authState would be your firebase user data. It could be a boolean, or any other data you want to pass in as a prop.
Then in your Home component you will receive the prop and can use it however you want:
function Home({auth}) {
  return (

      {auth ?
Logged In
 :
Logged Out
}

  );
}


text:
Q: C++ Variable destruction Suppose I have this:
std::wstring str = std::to_wstring(100);
str = std::to_wstring(1000); // Is the previous str destroyed?

If I reassign the local variable to another variable, is the old one destroyed?

A: The old one is the new one, only the members are copied. Consider a simple implementation of assignment:
struct foo {
    int value;
    foo& operator=(const foo& other) {
       value = other.value;
       return *this;
    }
};

After assignment a = b; the object a is still the same object. If foo manages a resource, the operator= of course has to account for that and you can safely assume that all standard containers are not broken.

A:
Is the previous str destroyed?

Yes. There is no memory management happening in the code snippet you shared, it's all automatic storage.


text:
Q: Parametrized curve in $\mathbb{R}^n$
Let $\mu: [x,y]\to \mathbb{R}^n$ be a parametrized curve in
  $\mathbb{R}^n$ such that $\mu(x)=x_1$ and $\mu(y) = y_1$. Show that
  for any constant vector $v$ where $\lVert  v \rVert=1$ then: $$(y_1-x_1) \dot\ v =
 \int^y_x \mu'(t) \dot\ v \ dt \le \int^y_x \lVert\mu'(t)\rVert dt.$$ Using
  this show that $$\lVert\mu(y)-\mu(x)\rVert\le \int^y_x \lVert\mu'(t)\rVert dt.
$$

How can I prove this?
For the first part I know that I must use Cauchy-Schwarz inequality but I don't know how to apply it here. The second part is telling me the distance (or length) between $x_1$ and $y_1$ is less than the length (arc length) of $\mu$?

A: You're right. The first is Cauchy-Schwarz: Just integrate. For the second, pick the right unit vector $v$.

A: For the first part, Cauchy-Schwarz tells us that
$$\mu'(t) \cdot v \leq |\mu'(t) \cdot v| \leq ||\mu'(t)|| \cdot||v|| = ||\mu'(t)||$$
Since $||v|| =1$. Applying integrals, we get
$$ (y_1 - x_1) \cdot v = \int_{x}^{y} \mu'(t) \cdot v \leq \int_{x}^{y} ||\mu'(t)||$$
For the second part, the hint above is good. If you cannot figure it out, the solutions is below (highlight to see the math):

 Note that you can take the absolute value of both sides and preserve the inequality,  since the right-hand side is already positive. But

$$\color{white}{ ||(y_1 - x_1) \cdot v|| = ||(y_1 - x_1)|| \cdot ||v|| \cdot \cos \theta }$$

So choose a unit length $v$ for which $\cos \theta = 1$


text:
Q: check parentId of case and Messaging.InboundEmailHandler class parentid if case parentid and incoming email parentld same then store the email on its related list
 Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

    List<Case> cs = [SELECT Id, parentId FROM case WHERE parentld =: **** LIMIT 1];

what i put at where clause if parentid and incoming email has same parentid should i use Messaging.InboundEmail email or Messaging.InboundEnvelope envelope and how

A: You are doing the right thing : -
// Apex Email Service
    Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();

now based on your incoming email you need take the parent id , say if the id is in subject then you can find it in,
String strSubject = email.subject;

if the id is in body then you can find it in,
String myPlainText = email.plainTextBody;

from those strings you need to find out the ParentId then you can use it in your own query.


text:
Q: web browser client how to capture something like a document completed event AFTER THE JAVASCRIPT HAS LOADED So i want to get the visible content of a page using a web browser control, the programming language does't matter C# or VB is totally fine, i am already using something like this
Dim wb As New WebBrowser
wb.Navigate("http://some_random_website.com")

While wb.ReadyState <> WebBrowserReadyState.Complete
            Application.DoEvents()
End While
Dim content_retrieved as string = wb.Document.Body.InnerText

(i am only interested in the visible content not the html source)
Which basically makes the program do nothing until the web browser client has finished loading the page and it works just fine
But i have some pages that creates their content dynamically and the WebBrowserReadyState.Complete fires before the javascript has done loading its functions so i get the page without the dynamically created content
Any solution or reference would be very helpful.
Thank's in advance!

A: You can use the DocumentCompleted event in C#.
Usage shown here - https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documentcompleted(v=vs.110).aspx


text:
Q: why blogs are not showing as a list? i am a beginner in React.js. i am trying to show blogs as a list array but it's not showing. code as followed:
const Posts=props=>{
    return(

                {props.author.Text}

        {props.Title}

        {props.Content}

    )
}
const posts =[{
    Title: 'Just A Title',
    Content: 'This is the first post in react.',
    author:{
        Text:'Just an image',
        imageUrl:'https://placekitten.com/g/64/64'
    }
},
{
    Title: 'Just A Title',
    Content: 'This is the first post in react.',
    author:{
        Text:'Just an image',
        imageUrl:'https://placekitten.com/g/64/64'
    }}
]

const blog=props=>{
    return(
        <Posts
            Title={posts.Title}
            Content={posts.Content}
            author={posts.author}
            />
    )

}
const postList=props=>{
    const plists=props.blog.map((p,i)=>{
        return(
            <React.Fragment key={i}>
        {p.Title}
        {p.Content}
        {p.author}

        </React.Fragment>

        )
    })
return
{plists}

}
class Post extends Component {

    render(){
        return(

            <postList blog={blog}/>

        )
    }
}

problem is when i excute npm start there is no error but in localhost there is nothing. My main goal is to make the post with createPost.js. createPost.js is working showing the input boxes. that's why i put manual post for testing

A: I removed some code because I don't what it's purpose is but the following will work.

const Post = ({ post }) => {
  return (

{post.author.Text}

{post.Title}

{post.Content}

  );
};
const Posts = ({ posts }) => {
  return posts.map((post, i) => (
    <Post post={post} key={i} />
  ));
};

const Blog = ({ posts }) => {
  return <Posts posts={posts} />;
};

const App = () => (
  <Blog
    posts={[
      {
        Title: 'Just A Title',
        Content: 'This is the first post in react.',
        author: {
          Text: 'Just an image',
          imageUrl: 'https://placekitten.com/g/64/64',
        },
      },
      {
        Title: 'Just A Title',
        Content: 'This is the first post in react.',
        author: {
          Text: 'Just an image',
          imageUrl: 'https://placekitten.com/g/64/64',
        },
      },
    ]}
  />
);

//render app
ReactDOM.render(
  <App />,
  document.getElementById('root')
);


text:
Q: Ionic 2 push notification not triggered in android app Ionic 2 push notification pushObject.on('notification') not triggered in android app(No push notifications received) but pushObject.on('registration') and pushObject.on('error') are triggered. Can anyone help me?

A: I had the same issue with my xiaomi phone, They have an annoying batter manager. try the following and see.
Step 1: Go to settings --> advanced settings --> battery manager --> protected apps, then find the app you want to see notifications from, and protect it. This is "whitelisting" the app so Huawei's overeager software doesn't shut it down for no reason.
Step 2: Go to settings --> apps --> advanced --> ignore battery optimizations, then find the app and ignore it. Don't be tricked by the misleading wording, "ignoring" the app actually means to let it run, because you're telling the battery optimization function, aka Doze, to "ignore" that app.
Step 3: Go to settings --> notification panel & status bar --> notification center, then find the app, then activate "allow notifications" and also "priority display". You have to activate the priority part too to make sure you get notifications. I've tried just activating allow notifications but not priority and I still didn't get notifications from that app.
Original Source


text:
Q: how to run multiple scala programs on multiple cores with sbt? I have written a scala program with several input args, and then I use a bash to set up the program with different parameters, such as
sbt "runMain Experiment --profix data --binFile bin/000000.bin --bucketNum 8" &
sbt "runMain Experiment --profix data --binFile bin/000000.bin --bucketNum 16" &
sbt "runMain Experiment --profix data --binFile bin/000000.bin --bucketNum 32" &
sbt "runMain Experiment --profix data --binFile bin/000000.bin --bucketNum 64" &
sbt "runMain Experiment --profix data --binFile bin/000000.bin --bucketNum 128" &

The above five programs start to run. However, I found that they share a single CPU core. The server has 28 CPU cores, so the other 27 core is idle. How can I run multiple scala programs on multiple cores?
As shown in the figure, there are three programs, and each of them uses 1/3 of the CPU


text:
Q: Create multiple database instances via Firebase CLI I am looking into automating the deployment of a project that is made up of multiple functions that are triggers on multiple realtime database instances.
Using firebase deploy allows you to deploy both functions and database rules.
I have also created targets so i can deploy different rules for different database instances.
The only missing part of my automation is actually creating those different database instances via the Firebase CLI tool; Since deploying a trigger function to a specific database that doesn't exist will fail. Ideally i would like to make sure to create those database instances if they don't exist and then continue my deployment.
Is there a way to create different database instances via the CLI ?

A: I don't know when it was added, but this might be useful for others having the same question.
You can create a Firebase Realtime Database instance using the following CLI command:
firebase database:instances:create [instance-name]

I don't know why this isn't described in the CLI reference, but it is mentioned here: https://firebaseopensource.com/projects/firebase/firebase-tools/

A: You can Create realtime database instance by firebase CLI using the below command

firebase database:instances:create -P <alias_or_project_id> <DBinstanceName>

This Command work fine if you have paid plan.
For Free Plan it throw error:- FirebaseError: HTTP Error: 400, Precondition check failed.
Note : <DBinstanceName> should be alpha-numeric with hyphens.


text:
Q: What exactly goes in creating a subdomain I recently got myself a domain name. I wanted to add a couple of sub-domains to it.
I want to know what goes on when you create a new sub-domain. How does a router know how to resolve a sub-domain.
Some hosting providers also charge for creating them. Do they incur legitimate expenses to create and manage these or is it pure profit?

A: If your domain host charges for sub domains, find a new host, that kind of service should be free. If you are not sure where to find one, check out zonedit.com . Their domains update in almost real-time, and they give you plenty of control. They also have guides for how to add sub domains. When you make a subdomain it will point to an IP address, this can be any public IP address, including ones that you used on other sub domains.
As for the costs to a business to add a subdomain. The cost is so small it is legally immeasurable. It is adding a few lines of text to a config file in a server somewhere. Charging for this server is a rip off, instead of charging for domain hosting as a whole.

A: it would depend on who manages the dns servers. if your providers do, the presumably they would have to have separate zone files (it is better to organize things) etc. to manage your subdomains. if they delegate your domain to your own dns servers and you create your subdomains arbitrarily, then they should have no more overhead at all and have no reason to charge you more. not a legal expert so if they still charge you in that case, i am not sure if would be legal for them to do so.


text:
Q: How to set up TeX software to begin making existing Greek and Hebrew texts into custom interlinear pdfs? Starting Point
I have a W32TeX package with latex, pdftex, xetex installed on a win7 box and am interested in getting started creating interlinear Greek-Hebrew (2 line, no English) texts of Biblical passages (sourced from Hebrew OT, Septuagint, Greek NT, and Delitzsch's Hebrew NT translation in public domain).
I have bookmarked a good question on doing an interlinear text and have perused and bookmarked some of the getting-started information. For example, tex.stackexchange.com/questions/12668/where-do-i-start-latex-programming appears to cover some of the necessary faq pre-req.s for my question.
What I need to know

*

*What software package(s) is best suited for the purpose of arranging both Greek-to-Hebrew and Hebrew-to-Greek interlinear texts? (Hope this is not a purely subjective question). An answer might be that XeTeX will work fine, or that "SomeOther"TeX is especially suited to RTL, LTR alterations within a line.

*Additionally, what reading is essential to learn skills needed for preparing multi-line/language texts from existing written sources? An answer would include some direction toward specific documentation available, or include a hyperlink to a multi-line tutorial that features working examples of methods specific to multi-line text.

*Lastly, any tips on finding source texts from the public domain which may be easy for the beginner to set into multi-line texts? [To be honest, I am also trolling just for the source text files in my question on the hermeneutics SE Site] EDIT: the texts tips are in my comment below The source text basis may help to inform the rest of this question.
Purpose
I use both Hebrew and Greek texts for regular reading, and do not like to read on the computer, or print poor copies. There are some good reading tools that just treat Hebrew or Greek with English, but I want to make publisher quality prints that pair 1) OT Hebrew with LXX, and 2) NT Greek with Delitzsch's Hebrew Translation. (If someone has a files set up for this and is willing to share that would be super awesome).

A: I have used the expex package in the past for interlinear text (in my case, Portuguese and phonetic transcription; here's an example of what I achieved.)


text:
Q: Coloring around divs within a flexbox I'm trying to make a website's footer. In the image you see how it is supposed to be, and what I got. I was trying to get the location of my div called secretarias and the location of my div called direita because I wanted my blue divs to color AROUND these two, like in the image.
but jquery's location didn't work. And I'm not even sure it's a good way of doing that. I just want to color a couple of pixels more than what's colored around both these divs, and make that circular border around.
And also: I couldn't get div "rights" to be perfectly aligned on center. It's the only one that has a problem because its font size has got to be a little bit smaller than the others.

/*
var position = $("#secretarias").position();
var bottom_l = position.bottom;
var left_l = position.left;

$("#rodapecor01").css("bottom: ",bottom_l, "left: ",left_l);

var position2 = $("#direita").position();
var bottom_r = position2.bottom;
var left_r = position2.left;

$("#rodapecor02").css("bottom: ",bottom_r, "left: ",left_r);

I couldn't make my JQuery work here but you can check it on the fiddle: http://jsfiddle.net/o2gxgz9r/552/
*/
#rodape {
 position: absolute;
 bottom: 0;
 width: 100%;
 height: 27.5%;
 background: #e7e7dc;

 font-size: 3vh;
 font-family: PT_Sans-Web-Regular;
 text-align: center;

 display: flex;
 flex-direction: row;
 flex-wrap: nowrap;
 flex-flow: row nowrap;
 justify-content: space-between;
 align-items: center;
}

#organizador {
 width: 48.60015522%;
 display: flex;
 flex-direction: row;
 flex-wrap: nowrap;
 flex-flow: row nowrap;
 justify-content: space-around;
}

#centro {
 width: 90%;
 display: flex;
 flex-direction: row;
 flex-wrap: nowrap;
 flex-flow: row nowrap;
 justify-content: flex-start;
}

#secretarias {
 width: 11.95230368%;
 background: #541324;
 color: white;
 text-align: right;
}

.linha {
 width: 4%;
 text-align: center;
}
.menurodape {
 text-align: center;
}

#direita {
 width: 39.4475411%;
 display: flex;
 flex-direction: row;
 flex-wrap: nowrap;
 flex-flow: row nowrap;
 justify-content: space-between;
 background: #541324;
 color: white;
}

#mapadosite {

}

#rights {
 font-size: 1.5vh;
 text-align: center;
}

#rodapecor01 {
 /* background:#541324; */
 background: lightblue;
  position: absolute;
  bottom: 15%;
  left: 5%;
  width: 5%;
  height: 5%;
}

#rodapecor02 {
 /* background:#541324; */
 background: lightblue;
  position: absolute;
  bottom: 15%;
  right: 5%;
  width: 5%;
  height: 5%;
}

#rodapelinha {
  background:#541324;
  position: absolute;
  bottom: 27%;
  width: 100%;
  height: 2%;
}
#whatimtryingtodo{
 background: url('https://i.imgsafe.org/60c6fb0a1d.jpg');
 background-repeat: no-repeat;
 position:absolute;
 top: 20px;
 width: 100%;
 height: 500px;
}
What I'm trying to do:

What I got:

SECRETARIAS:

DESENVOLVIMENTO

|

SAÚDE

|

EDUCAÇÃO

|

SEGURANÇA

|

CULTURA

MAPA DO SITE

© 2016 UNA-SUS/UFCSPA - Todos os direitos reservados

A: If you drop your absolute positioned div's and add a border radius to your div's in question, you'll most likely get the desired result. (I also added a small padding to show how to make the colored area a little bigger)
Updated CSS rules
#secretarias {
  ...
  padding: 5px 10px;
  border-radius: 10px;
}
#direita {
  ...
  padding: 5px 10px;
  border-radius: 10px;
}

For the text in rights element to center, I gave it flex: 1, and by doing that it will fill the remaining space and the text centers inside it.
Sample

#rodape {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 27.5%;
  background: #e7e7dc;
  font-size: 3vh;
  font-family: PT_Sans-Web-Regular;
  text-align: center;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-items: center;
}
#organizador {
  width: 48.60015522%;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  flex-flow: row nowrap;
  justify-content: space-around;
}
#centro {
  width: 90%;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  flex-flow: row nowrap;
  justify-content: flex-start;
}
#secretarias {
  width: 11.95230368%;
  background: #541324;
  color: white;
  text-align: right;
  padding: 5px 10px;
  border-radius: 10px;
}
.linha {
  width: 4%;
  text-align: center;
}
.menurodape {
  text-align: center;
}
#direita {
  width: 39.4475411%;
  display: flex;
  justify-content: space-between;
  background: #541324;
  color: white;
  padding: 5px 10px;
  border-radius: 10px;
}
#mapadosite {
}
#rights {
  flex: 1;
  font-size: 1.5vh;
  text-align: center;
}
#rodapelinha {
  background: #541324;
  position: absolute;
  bottom: 27%;
  width: 100%;
  height: 2%;
}

SECRETARIAS:

DESENVOLVIMENTO

|

SAÚDE

|

EDUCAÇÃO

|

SEGURANÇA

|

CULTURA

MAPA DO SITE

© 2016 UNA-SUS/UFCSPA - Todos os direitos reservados


text:
Q: Alignment and sizing of stacked icons using fontawesome not working I am trying to use stacked icons with fontawesome.  I followed the example in Dave Gandy's excellent blog post.
http://blog.fontawesome.io/2014/05/19/stacking-text-and-icons/
Stacking works fine, but I am trying to align a stacked icon with a non-stacked icon (which is fa-5x).  I cannot seem to make the size/alignment of a stacked icon match the size/alignment of a non-stacked icon.
See this codepen: http://codepen.io/rfiol/pen/YPQNaG

  27

A: Try this
CSS
.calendar-text {
  margin-top: .3em;
}
.calendar-text {
  font-size:100%;
}
.col-md-1:nth-child(3) .calendar-text-half {
  font-size:50%;
}
.col-md-1:nth-child(3) .fa-stack {
  transform: scale(2,2);
}
.fa-stack {
  font-size:2.5em;
}
.row {
  width:100%;
  height:100px;
  display:block;
}

codepen http://codepen.io/anon/pen/jEwBNd


text:
Q: How do I animate moving a list item to the top? I have a list and would like to move the item to the top when it's clicked on. Simultaneously, all other items should move down to make space.
That's what I have so far:

item-1

item-2

item-3

item-4

//
  $('li').on('click', function () {
    $(this).css({ position : 'absolute', top : $(this).position().top });
    var height = $(this).parent().children().first().height();
    var list = $(this).parent();
    $(this).animate({top: '0px'}, { duration: 500, queue: false });

    list.children().each(function( index, element) {
    var $liElement = $(element);
    if($liElement != $(this))
    {
        $liElement.animate({top: height + 'px'}, { duration: 500, queue: false });
    }
  });
});

Here is the link: http://jsfiddle.net/5qgnjvdp/
I see the item moving on top but all others don't move at all. What is wrong here?
Should I use prepend() to insert the list item on top when the animation is finished?

A: While not really an "animation", I was working on something some time ago along similar lines. What I ended up using was a slideUp, then a slideDown to give a sense of animation without actual animation connected to the move.

$('li').click(function() {
        $(this).slideToggle(500, function() {
        $(this).prependTo('#list').slideToggle(500); });
    });
li { list-style: none; background: #ddd;padding: 5px 10px; border: 1px solid #aaa; margin: 10px; text-transform: uppercase; font-weight: bold;color:#fff; }
#list { margin:20px; padding:0; }

item-1

item-2

item-3

item-4

$('li').click(function() {
        $(this).slideToggle(500, function() {
        $(this).prependTo('#list').slideToggle(500); });
    });

fiddle update
Again, I realize this isn't really an animation beyond the slide toggles, but it conveys a sense of interactivity similar to an animation.

A: There are a couple of problems with your script.

*

*When comparing $liElement != $(this) you are in the scope of the each function where this refers to the current list child, which is the same as element. Store the clicked li in a variable outside of the looping function and compare with that. Also no need to compare the $(...) objects. element != clickedLi would suffice.

*When you animate the other li elements they don't have position: absolute (or relative) so you won't see their movement.

*If you assign the other li elements an absolute position you move all of them to the same position, the second row in the list. You could use position relative to move them down. You should just make sure to exclude the elements that come after the original position of the clicked li.

After the animation is complete you should insert the list item as the first child of the list and then remove the absolute/relative positioning, including the top style to make sure it works a second time (and to ensure that the visible representation is in line with the elements' structure.


text:
Q: Auth with google sheets API V4 / REST / Go I have read example https://developers.google.com/sheets/reference/rest/v4/spreadsheets.values/update from Google
Everything is great until I coming to authentication.
I would like to send this Put request to update a spreadsheet from my application from Golang:
key := "my key"
// I think I do not need key, because it have to be OAuth...
spreadsheetId := "myspreadsheetID"
link := fmt.Sprintf("https://sheets.googleapis.com/v4/spreadsheets/%s/values/A1?valueInputOption=RAW&fields=updatedCells&key=%s",
spreadsheetId, key)

request := gorequest.New()
resp, body, errs := request.Put(link).
    Send(`{"values": [ ["hello","my", "friends" ] ]}`).
    End()

if errs != nil {
    fmt.Println(errs)
}

if resp.StatusCode != 200 {
    fmt.Println(resp.Status)

}

fmt.Println(body)

The response is
401 Unauthorized
{
 "error": {
 "code": 401,
 "message": "The request does not have valid authentication credentials.",
 "status": "UNAUTHENTICATED"
 }
}

I tried to grasp the Auth Guide but honestly I am not sure I figured out how can auth the request...
Any help would be appreciated very much.

A: Key is used for accessing Public data, Oauth2 requires that you authenticate and grant the application permission to access private data.
Worked in V3: If you want to use a key you can set the google sheet you are trying to access public and it will work.
Otherwise you are going to have to implement Oauth2. I cant help with go but a quick search on google turned up a bunch of Oauth2 tutorials for it.
Update:
I just did a quick check in the documentation. Method: spreadsheets.values.update
Authorization

Requires one of the following OAuth scopes:

* https://www.googleapis.com/auth/drive
* https://www.googleapis.com/auth/spreadsheets

which leads me to think that they removed the public trick from the v4 of the api.  Looks like you are going to have to implement oauth2 or service accounts


text:
Q: POSIX/Bash pad variable with trailing newlines I have a variable with some lines in it and I would like to pad it with a number of newlines defined in another variable. However it seems that the subshell may be stripping the trailing newlines. I cannot just use '\n' with echo -e as the lines may already contain escaped chars which need to be printed as is.
I have found I can print an arbitrary number of newlines using this.
n=5
yes '' | sed -n "1,${n}p;${n}q"

But if I run this in a subshell to store it in the variable, the subshell appears to strip the trailing newlines.
I can approximate the functionality but it's clumsy and due to the way I am using it I would much rather be able to just call echo "$var" or even use $var itself for things like string concatenation. This approximation runs into the same issue with subshells as soon as the last (filler) line of the variable is removed.
This is my approximation
n=5
var="test"
#I could also just set n=6
cmd="1,$((n+1))p;$((n+1))q"
var="$var$(yes '' | sed -n $cmd; echo .)"

#Now I can use it with
echo "$var" |  head -n -1

Essentially I need a good way of appending a number of newlines to a variable which can then be printed with echo.
I would like to keep this POSIX compliant if at all possible but at this stage a bash solution would also be acceptable. I am also using this as part of a tool for which I have set a challenge of minimizing line and character count while maintaining readability. But I can work that out once I have a workable solution

A: Command substitutions with either $( ) or backticks will trim trailing newlines. So don't use them; use the shell's built-in string manipulation:
n=5
var="test"
while [ "$n" -gt 0 ]; do
    var="$var
"
    n=$((n-1))
done

Note that there must be nothing after the var="$var (before the newline), and nothing before the " on the next line (no indentation!).

A: A sequence of n newlines:
printf -v spaces "%*s" $n ""
newlines=${spaces// /$'\n'}


text:
Q: How to update a particular column of each row of a table? Hi I would like to update my last column with values from a text file which I will receive in later stages.
Currently i am able to update all rows of the last column at a time using jquery. But i want to read from a file (output.txt) and update each row of the table for that column.
$(document).ready(function() {
    $('.ms-listviewtable').find('td').eq(3).text('changedValue');
});

        Value1
        Value2
        Value3
        Value4

A: If I correctly understand what you want to do, then try this jQuery:
var file = 'http://foo.com/foo.txt';

$.get(file, function(data){
    var lines = data.responseText.split("\n");

    for (var i = 0, l = lines.length; i < l; i++) {
        $('.ms-listviewtable tr').eq(i).find('td.ms-lastCell').text(lines[i]);
    }
});

I have not tested the AJAX but it should point you in the correct direction, you can use AJAX to return the response text from the .txt file, split it on a character (in your case, a line break), then loop through the table rows, replacing the text in the last cell of each row with the corresponding line.
Here is a fiddle, demonstrating the code to loop through the lines.


text:
Q: Export CSV From Postgres VIA Command Line Hello Stack Overflowers!
I'm currently exporting a Postgres table as a .csv using a C# application I developed. I'm able to export them no problem with the following command...
set PGPASSWORD=password
psql -U USERNAME Database_Name
\copy (SELECT * FROM table1) TO C:\xyz\exportfile.csv CSV DELIMITER ',' HEADER;

The problem I am running into is the .csv is meant to be used with Tableau, however, when importing to excel I run into the same issue. It turns text fields into integers in both Tableau and Excel. This causes issues specifically on joining serial numbers on the Tableau side.
I know I can change these fields in Tableau/Excel manually but I am trying to find a way to make sure the end-user wouldn't need to do this. I'd like for them to just drag and drop the updated .csv postgresql data extracts and be able to start Tableau no problem. They don't seem real tech-savvy. I know you can connect Tableau directly to Postgres but in this particular case, I am not allowed to due to limitations beyond my control.
I'm using PostgreSQL 12 and Tableau v2019.4.0
EDIT: As request providing example data! Both of the fields are TEXT inside of PostgreSQL but the export doesn't specify.
Excel Formatting
ASSETNUM,ITEMNUM
1834,8.11234E+12
1835,8.11234E+12

Notepad Formatting
ASSETNUM,ITEMNUM
1834,8112345673294
1835,8112345673295

Note: If you select the specific cell in Excel it shows the full number.

A: CSV files don't have any type information, so programs like Excel/Tableau are free to interpret the data how they like.
However, @JorgeCampos's link provides useful information. For example
"=""123""","=""123"""

gets interpreted differently than
123,123

when you load it into Excel.
If you want to add quotes to your data, the easiest way is to use PostgreSQL's string functions, e.g.
SELECT '"=""' || my_column || '"""' FROM my_database


text:
Q: android application runs in AVD but stoppes in real device I have created a very simple android app using visual studio (xamarin for visual studio) and have changed nothing I mean the codes are as the same as default when you create an android app.
[Activity(Label = "App2", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    int count = 1;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        // Get our button from the layout resource,
        // and attach an event to it
        Button button = FindViewById<Button>(Resource.Id.MyButton);

        button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
    }
}

When I run it, android virtual device starts and application runs normally without error but when I copy .apk file from the bin folder of my solution to my real phone it installs fine but when I want to run it it gives the "unfortunately App1 has stopped error.
I copy the "App2.App2-Signed.apk" to my phone.
and also the "Export Android Package" option in build menu of visual studio is disabled.
what is the reason?
I used to create android apps with eclipse and never got this error.
note that I don't change anything in application, The application structure and codes and etc are all the default generated by xamarin's own template.

A: Have you tried to plug your android device into your computer? You make have to enable your phone to work with your android app.
Here is a link with more information about connecting a real android phone to an android application: http://developer.android.com/training/basics/firstapp/running-app.html

A: You cannot just pick the APK from your bin folder and make it run on your phone. You have to follow the complete process of signing and publishing the app to get the Adhoc build.
You can start here:
Preparing an Application for Release


text:
Q: How to receive file with type csv from API response I have the export button which hit API and send response in .csv type. When i hit the API, the response said status: 200 but i getting HttpErrorResponse in the console, and got this error
SyntaxError: Unexpected token T in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad

I have tried to ask my friend that I have to change my Header, but i don't understand how to do it properly. Should i set the header within Token Interceptor as same as when i set the token of the headers (if ya, how can I do that?)? Or how can i solve my problem?
This is the function that the button triggered:
onExport = () => {
    this._service.getDataExport(1, 1, this.filter).subscribe(
      res => {
        console.log(res);
        // const filename = `MediaPreparation.csv`;
        // const blob = new Blob([res.data], { type: 'text/csv' });
        // saveAs(blob, filename);
      },
      err => console.log(err)
    );
  }

This this is the service that I hit:
getDataExport = (page = 1, perPage = 1, filter = null): Observable<any> => {
   const _url = `${this.base_url}/api/v1/media-preparation/export`;

   return this.http.post(_url, {
     page : page.toString(),
     perPage: perPage.toString(),
     filter : filter
   });
}

and this is the Token Inteceptor:
import { AuthService } from './auth.service';
import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';

@Injectable()
export class TokenInterceptorService implements HttpInterceptor {

  constructor(private injector: Injector) { }

  intercept(req, next) {
    const authService = this.injector.get(AuthService);
    const tokenizedReq = req.clone({
      setHeaders: {
        Authorization: `Bearer ${authService.getToken()}`
      }
    });

    return next.handle(tokenizedReq);
  }
}

Thanks for helping, and I am sorry for the bad explanation, I stil beginner in Angular.

A: The reason is easy, HttpClient is trying to parse your response as JSON, since it's the most common scenario and the default action.
To prevent HttpClient to parse your response, you have to put responseType: 'text' in your httpOptions:
private httpOptions = {
  headers: new HttpHeaders({}),
  responseType: 'text'
};

Then use this object as last parameter of your http method (I suppose get):
this.http.get(url, httpOptions)
  .subscribe(res => {
    // res is just a string, you have to split it on new lines and commas
    // or you can use a third part library
  });

Note:
Some servers may need to add some not-standard Accept header, for example:
headers: new HttpHeader({
  Accept: 'text/csv'
});

Or
headers: new HttpHeader({
  Accept: 'application/csv'
});

Or (standard but not semantic):
headers: new HttpHeader({
  Accept: 'plain/text'
});


text:
Q: Segmentation Fault cuando redirijo entrada, pero funciona cuando es por consola Tengo el siguiente código:
#include <stdio.h>

#define WLEN      32    /* word length */
#define LOGWLEN   50016 /* log word length -- round(LOG2(WLEN) */
#define SMAX      50016 /* maximum string length -- multiple of WLEN */
#define BITMAX    128   /* maximum bit string length -- round(SMAX/WLEN) */
#define ALPHASIZE 26    /* alphabet size */

typedef unsigned int WORD;
typedef short unsigned int INDEX;   /* i: alpha[i] == char */

int nwords;             /* no. of words for bits */
WORD bit1[BITMAX];
WORD bit2[BITMAX];
WORD a_strings[ALPHASIZE][BITMAX];
WORD *pb1, *pb2, *t1;

WORD bitmask[LOGWLEN] =
        {0x55555555, 0x33333333, 0x0f0f0f0f, 0x00ff00ff, 0x0000ffff};

void bitops(last, cur, index)
WORD *last, *cur;
INDEX index;
{
    register WORD x, y;
    register int j;
    register WORD *a_s;
    register WORD top_borrow, bottombit;

    a_s = &a_strings[index][0];
    bottombit = 1;
    for (j = 0; j < nwords; j++) {
        y = *(last++);
        x =  y | *(a_s++);
        top_borrow = (y >> (WLEN - 1)) & 0x1;
        y = ((y << 1) | bottombit);
        if (x < y)
            top_borrow = 1;
        *(cur++) = x & ((x - y) ^ x);
        bottombit = top_borrow;
    }
    return;
}

void alphastrings(s, len)
INDEX *s;
int len;
{
    register INDEX *p;
    register int i, j;

    for (i = 0; i < ALPHASIZE; i++)
        for (j = 0; j < nwords; j++)
            a_strings[i][j] = 0;
    p =  s;
    j = len;
    for (i = 0; i < j; i++)
        a_strings[*(p++)][i/WLEN] |=  1 << (i % WLEN);

    return;
}

int bitcount(wp)
WORD *wp;
{
    register WORD w, count;
    register int j, rshift, i;

    count = 0;
    for (i = 0; i < nwords; i++) {
        w = *(wp++);
        rshift = 1;
        for (j = 0; j < LOGWLEN; j++) {
            w = (w & bitmask[j]) + ((w & ~bitmask[j]) >> rshift);
            rshift <<= 1;
        }
        count += w;
    }
    return (count);
}

int bitlcs(a, lena, b, lenb)
INDEX *a;
int lena;
INDEX *b;
int lenb;
{
    register int i;
    register INDEX *pbstring;
    register int j, k;

    nwords = (lena + WLEN - 1) / WLEN;

    alphastrings(a, lena);

    pb1 = &bit1[0];
    for (i = 0; i < nwords; i++)
        *pb1++ = 0;     /*** bit1[i] = 0; ***/
    pb1 = &bit1[0]; pb2 = &bit2[0];
    pbstring = b;

    for (i = 1; i <= lenb; i++) {
        bitops(pb1, pb2, *(pbstring++));
        t1 = pb1; pb1 = pb2; pb2 = t1;
    }
    return (bitcount(pb1));
}

int leer(INDEX * s) {
    int c, index, i = 0;
    while((c = getchar()) != EOF && c != '\n') {
        s[i++] = (int) c - 97;
    }
    return i;
}

int main(int argc, char const *argv[])
{
    INDEX stringa[SMAX];// = {1, 1, 1};
    INDEX stringb[SMAX];// = {1, 2, 1};
    int lenA, lenB;
    lenA = leer(stringa);
    lenB = leer(stringb);
    printf("%d\n", bitlcs(stringa, lenA, stringb, lenB));
    return 0;
}

Estoy testeándolo con 50000 letras "a" y 50000 letras "e" como entrada, para eso armé un archivo con dichas letras. El problema se dá en que cuando compilo con:
gcc -O2 miPrograma.c -o miPrograma.exe

Y lo ejecuto con ./miPrograma.exe < strings.txt
Arroja Segmentation Fault, aunque si lo ejecuto simplemente ./miPrograma.exe y copio y pego ambos strings funciona correctamente.
Probé, además, que al debuguearlo con
gcc -O2 miPrograma.exe -g
gdb ./a.out
run < strings.txt

También funciona perfectamente, por lo que no puedo ver donde se encuentra el problema. No se qué hacer, si alguien pudiera darme una mano se lo agradecería.
UPDATE
He notado que cuando el número de caracteres decrementa no hay problema con las redirecciones, por lo que claramente es un problema a la hora de almacenar los 50000 de cada letra.

A: Ahí solucioné el problema.
En cuanto al SIGSEGV estaba en presencia de un Heisenbug tal como se explica en esta pregunta. Desactivando la randomización de memoria en el debugger se solucionó:
(gdb) set disable-randomization off

En cuanto al algoritmo, tenia un problema de seteo de la macro BITMAX (cuyo valor se establece a partir del redondeo de la división SMAX/WLEN) la cual había quedado con el valor 128 y me había olvidado de cambiarlo al correspondiente (1563) al actualizar los valores de SMAX y WLEN.


text:
Q: String encoding of Arabic characters in UTF-8 An Arabic name shall be sent via SOAP. The name is encoded like this:
<value>Ù…ØÙ…Ø¯ Ø¹Ø¨Ø¯Ø§Ù„Ù„Ù‡ Ù‡Ù„Ø§Ù„</value>

However when converting the above to UTF-8 with some online converters the result looks like this:
محمد عبدالله هلال
What am I missing here so that the correct Arabic characters are displayed?
Thanks,
Robert

A: The encoded data you showed does encode the nonsensical data you showed (or similar, because it actually encodes some unprintable characters as well).
So your input is already wrong.
You might be able to salvage it, but the correct solution would be to make sure that the input is correct in the first place.

A: This has been the problem Sending UTF-8 data from Android. Your code would work fine except that you will have to encode your String to Base64 . At Server you just decode Base64 String back. It worked for me. I can share if you need the code.


text:
Q: Convert the matches of a regex into a multidimensional array The code below correctly matches:

*

*letter 'c' followed by digit

*letter 'c' followed by digit dash digit

*digit may be followed by an other digit enclosed in square parentheses []
and creates an array as expected as this:
Array
(
    [0] => Array
    (
        [start] => 4
        [end]=> 8
    )
    [1] => Array
    (
        [start] => 2
        [end]=>
    )
    [2] => Array
    (
        [start] => 3
        [end] => 5
    )
    [3] => Array
    (
        [start] => 6[2]
        [end] =>
    )
    [4] => Array
    (
        [start] => 8[4]
        [end] => 10
    )
    [5] => Array
    (
        [start] => 14
        [end] => 21[5]
    )
)

CODE:
 $str = "a2c4-8|a6c2,c3-5,c6[2],c8[4]-10,c14-21[5]";

 $re = "~c(?<start>\d+(?:\[\d+])?)(?:-(?<end>(?&start)?))?~";

 $myarray = explode("|",$str);

foreach ($myarray as $my) {
    preg_match_all($re, $my, $matches);

    $res = array_map(function($ms, $me) {
        return array("start" => $ms, "end" => $me);
    }, $matches["start"], $matches["end"]);
}

echo "<pre>";
    print_r($res);
echo "</pre>";

Now I would like to add an other key with the value of the digit after the a.
So for example, given the above $str
$str = "a2c4-8|a6c2,c3-5,c6[2],c8[4]-10,c14-21[5]".

the a values are: 2 and 6 and the expected result array would be the following. Note that 6 is repeated for every c matched.
Array
(
    [0] => Array
    (
        [a] => 2
        [start] => 4
        [end]=> 8
    )
    [1] => Array
    (
        [a] => 6
        [start] => 2
        [end]=>
    )
    [2] => Array
    (
        [a] => 6
        [start] => 3
        [end] => 5
    )
    [3] => Array
    (
        [a] => 6
        [start] => 6[2]
        [end] =>
    )
    [4] => Array
    (
        [a] => 6
        [start] => 8[4]
        [end] => 10
    )
    [5] => Array
    (
        [a] => 6
        [start] => 14
        [end] => 21[5]
    )
)

A: You can do that:
$str = "a2c4-8|a6c2,c3-5,c6[2],c8[4]-10,c14-21[5]";

$re = '~(?:a(?<a>\d+))?c(?<start>\d+(?:\[\d+])?)(?:-(?<end>\g<start>))?~';

if (preg_match_all($re, $str, $matches, PREG_SET_ORDER) ) {
    $a = ''; // current value for "a" -----,
    $result = array_map(function ($i) use (&$a) {
        if (!empty($i['a'])) $a = $i['a'];
        else $i['a'] = $a;

        if (!isset($i['end'])) $i['end'] = '';

        foreach ($i as $k=>$v) {
            if (is_numeric($k)) unset($i[$k]);
        }

        return $i;

    }, $matches);
}

print_r($result);

But if you already know exactly how is the string format and if you don't need to validate it, there are probably smarter (and faster) ways to obtain the same result.
For example, using explode and formatted strings with sscanf:
$str = "a2c4-8|a6c2,c3-5,c6[2],c8[4]-10,c14-21[5]";

$parts = explode('|', $str);
$result = [];

$keys = ['a', 'start', 'end'];

foreach($parts as $part) {
    foreach(explode(',', $part) as $k=>$v) {
        if ($k)
            list($start, $end) = sscanf($v, 'c%[^-]-%[^,]');
        else
            list($a, $start, $end) = sscanf($v, 'a%dc%[^-]-%[^,]');

        $result[] = array_combine($keys, [$a, $start, $end]);
    }
}

print_r($result);


text:
Q: locale filter function running multiple times I'm running the following code:
 add_filter('locale', 'set_my_locale');
 function set_my_locale( $lang ) {
   $lang = "de";
   echo 'test';
   return $lang;
 }

This is returning the correct 'de' language, but it is echoing out the 'test' 5 times.
Why is it echoing the 'test' 5 times?
The reason that I have the echo 'test'; in there is because I want to do some other checks in this function but it seems to run 5 times for some reason.

A: This is the expected behaviour. The locale filter is filtering the result of the get_locale() function. All this means is that get_locale() is being called at least 5 times.


text:
Q: Upload csv and insert or update the results failing Can anyone see what I am doing wrong here? Basically what is supposed to happen is you upload the csv, it then pulls the rows out and checks with the database if that row exists, if it does it updates it, if it doesn't it inserts it. If the row is blank it ignores it.
What is actually happening is when I upload a csv I just get 'updated' for each of the 4 test lines whether it is in the database or not.
Also if anyone can suggest a better way of doing this, or trimming down the code please let me know, as I know by coding isn't the greatest by any stretch of the imagination.
if(isset($_GET['uploadfile'])) {
    $file = fopen($_FILES['csvfile']['tmp_name'], 'r+');
    while(! feof($file))
    {
        $line = fgetcsv($file, 0, ',');

        list($productcode, $v9cm, $v1litre, $v2litre, $v3litre, $v5litre, $v7litre) = $line;
        $rowcheck = "SELECT * FROM `stock` WHERE `productcode` = '$productcode'";

if (@mysql_num_rows(mysql_query($rowcheck))!=1) {

    if ($productcode == NULL OR $productcode == ''){}
    else {
        $datecreated = date('Y-m-d');
// Insert Posted Data
mysqli_query($db,"INSERT INTO stock (`datecreated`, `productcode`, `9cm`, `1litre`, `2litre`, `3litre`, `5litre`, `7litre`) VALUES ('$datecreated', '$productcode', '$v9cm', '$v1litre', '$v2litre', '$v3litre', '$v5litre', '$v7litre')") or die ('Unable to execute query. '. mysqli_error());
    echo $productcode.' - Added<br/ >';

    }
}
else{
    if ($productcode == NULL OR $productcode == ''){}
    else {
$stmt = $db->prepare("UPDATE stock SET 9cm = '$v9cm',1litre = '$v1litre',2litre = '$v2litre',3litre = '$v3litre',5litre = '$v5litre',7litre = '$v7litre' WHERE productcode = '$productcode'");

if ($stmt === FALSE) { echo "an error has occured"; }

$stmt->execute();
$stmt->close();
echo $productcode.' - Updated<br/ >';
    }
}
}
fclose($file);

}
}

A: There seemed to be a brace missing which I think would indeed have made it try to update whatever - indented statements to help make it a bit clearer and added mysqli instead of mysql where it appeared to be wrong - assuming everything should be mysqli. Hope that may help.
You will need to add clean-up/sanitizing/escape code but I assume you know that
if(isset($_GET['uploadfile'])){
    $file = fopen($_FILES['csvfile']['tmp_name'], 'r+');
        while(! feof($file)){
        $line = fgetcsv($file, 0, ',');

        list($productcode, $v9cm, $v1litre, $v2litre, $v3litre, $v5litre, $v7litre) = $line;

        $rowcheck = "SELECT * FROM `stock` WHERE `productcode` = '$productcode'";

             if (@mysqli_num_rows(mysqli_query($rowcheck))!=1){

                 if ($productcode == NULL OR $productcode == ''){
                 echo "Product code missing and rowcheck is not 1<br/ >";  // for testing
                 }else{
                 $datecreated = date('Y-m-d');
                 // Insert Posted Data
                 mysqli_query($db,"INSERT INTO stock (`datecreated`, `productcode`, `9cm`, `1litre`, `2litre`, `3litre`, `5litre`, `7litre`) VALUES ('$datecreated', '$productcode', '$v9cm', '$v1litre', '$v2litre', '$v3litre', '$v5litre', '$v7litre')") or die ('Unable to execute query. '. mysqli_error());
                 echo $productcode.' - Added<br/ >';
                 }

             }elseif($productcode == NULL OR $productcode == ''){
             echo "Product code missing<br/ >"; // for testing
             }else{
             $stmt = $db->prepare("UPDATE stock SET 9cm = '$v9cm',1litre = '$v1litre',2litre = '$v2litre',3litre = '$v3litre',5litre = '$v5litre',7litre = '$v7litre' WHERE productcode = '$productcode'");

                  if ($stmt === FALSE){
                  echo "an error has occured<br/ >";
                  }else{
                  $stmt->execute();
                  $stmt->close();
                  echo $productcode.' - Updated<br/ >';
                  }
             }
       }
 }

You might also like to look at the security implications of using uploaded files directly by their temp name http://www.acunetix.com/websitesecurity/php-security-4/ among many others.

A: This is what worked in the end :
    if(isset($_GET['uploadfile'])){
        $file = fopen($_FILES['csvfile']['tmp_name'], 'r+');
            while(! feof($file)){
            $line = fgetcsv($file, 0, ',');

            list($productcode, $v9cm, $v1litre, $v2litre, $v3litre, $v5litre, $v7litre) = $line;

            $query = mysqli_query($db, "SELECT * FROM stock WHERE productcode='".$productcode."'");

    if(mysqli_num_rows($query) > 0){

         $stmt = $db->prepare("UPDATE stock SET 9cm = '$v9cm',1litre = '$v1litre',2litre = '$v2litre',3litre = '$v3litre',5litre = '$v5litre',7litre = '$v7litre'
           WHERE productcode = '$productcode'");

        if ($stmt === FALSE) { echo "an error has occured"; }

        $stmt->execute();
        $stmt->close();
        echo $productcode.' - Updated<br/ >';

    }else{
        // do something
        if (!mysqli_query($db,$query))
        {

              $datecreated = date('Y-m-d');
        // Insert Posted Data
       mysqli_query($db,"INSERT INTO stock (`image`,`genusid`,`datecreated`, `productcode`, `9cm`, `1litre`, `2litre`, `3litre`, `5litre`, `7litre`) VALUES ('None.gif','5','$datecreated', '$productcode', '$v9cm', '$v1litre', '$v2litre', '$v3litre', '$v5litre', '$v7litre')") or die ('Unable to execute query. '. mysqli_error());
            echo $productcode.' - Added<br/ >';
        }
    }

                    }}}

A: It may be easier to use mysql's ON DUPLICATE KEY UPDATE clause (http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html).
See hjpotter92's answer here: On Duplicate Key Update same as insert. Your query would need to be modified to something like this:
INSERT INTO table (id,a,b,c,d,e,f,g)
    VALUES (1,2,3,4,5,6,7,8)
    ON DUPLICATE KEY
        UPDATE a=a, b=b, c=c, d=d, e=e, f=f, g=g;

This should allow you to remove most of the conditional logic and also cut down on the number of queries you run.


text:
Q: What is infinity to the zeroth power? I am not happy with the answers posted to similar questions.
For example, in:
What is infinity to the power zero
the accepted answer is 1, which is definitely wrong.
I think the answer is any non-zero, non-one, non-infinite number.  Is this correct?
Looking for the solution to:   $(1/0)^0$

A: It is an indeterminate form and as such cannot be assigned any value.
It is better expressed as $\lim_\limits{{x\to \infty}\\,\\{y\to 0}}x^y$.
As commented by Did, it is true that $x^y$ has no limit when $x\to \infty$ and $y\to 0$.
And $\infty^0$ has no definite meaning in mathematics. It is basically some kind of a meaningless statement where the notation of infinity has been wrongly used since infinity is not a number, it is a concept. To speak of infinity, I must add the following:

In standard real analysis, the symbol $\infty$ is simply used to
  denote an unbounded limit. Whenever the symbol is used, in series and
  integrals, for example, it has a precise definition with
  epsilon/delta. Similarly, in set theory, it also has a precise
  definition; we say a set $S$ is infinite if there is no bijection from
  $S$ to a bounded subset of $\mathbb{N}$.


text:
Q: how can I quickly add WMC functions to my Logitech Harmony One remote? I have a Logitech Harmony One that I'd like to use to control Windows Media Center. I have a WMC remote and a receiver that I'm currently using. So I could program all those buttons via the learning feature, but ugh.
Is there a quick way to load the WMC remote functionality into the Logitech remote and then use the Logitech remote to control WMC?

A: Oops, found it shortly after I posted this:
Add a new device:
Device type: Computer -> Media Center PC
Manufacturer: Microsoft
Model: Windows Media Center SE

Works good so far.


text:
Q: Characterizations of regular holonomic D-modules I'm looking for references for the various characterizations of regular holonomic D-modules, in particular proofs of their equivalence. For instance, some characterizations I've seen (in the analytic category) are:

*

*$\chi(M_x,\mathcal O_x) =\chi(M_x,\mathcal {\hat O}_x)$ for all $x$ source for notation (Though they give a source for this, I was unable to find it there)

*$R\operatorname{Hom}_D(M_x, \mathcal O_x) \cong R\operatorname{Hom}_D(M_x,\hat {\mathcal O}_x)$ via the natural map for all $x$

*A characterization having to do with V-filtrations near smooth points of subvarieties

*The D-module inverse image along any morphism from a smooth curve is  regular in the sense of Fuchs


text:
Q: Issue registering a user with ory kratos I'm struggling getting my flutter application to register a user with Kratos. I have a shell script using the API where I am able to get a successful registration:
#!/bin/sh

init_response=$(http http://127.0.0.1:4433/self-service/registration/api)

flow_uri=$(echo $init_response | jq -r '.ui.action')

echo $flow_uri

http POST $flow_uri "method"="password" "traits.email"="test@gmail.com" "traits.name.first"="Rodger" "traits.name.last"="Wilco" "password"="kense#$%@@ntme5765" "traits.mobile"="1234567890"

I receive the following on the registration:
HTTP/1.1 200 OK
Cache-Control: private, no-cache, no-store, must-revalidate
Content-Length: 1922
Content-Type: application/json; charset=utf-8
Date: Fri, 29 Oct 2021 06:23:57 GMT
Vary: Origin
Vary: Cookie

{
    "identity": {
        "created_at": "2021-10-29T06:23:57.388886Z",
        "id": "19699c9b-14b7-4263-a15f-45803d000eea",
        "recovery_addresses": [
            {
                "created_at": "2021-10-29T06:23:57.410531Z",
                "id": "f4b6dbc7-0e98-4e10-bc90-d4c35fa982dd",
                "updated_at": "2021-10-29T06:23:57.410531Z",
                "value": "test@gmail.com",
                "via": "email"
            }
        ],
        "schema_id": "default",
        "schema_url": "http://127.0.0.1:4433/schemas/default",
        "state": "active",
        "state_changed_at": "2021-10-29T06:23:57.388568437Z",
        "traits": {
            "email": "test@gmail.com",
            "mobile": "1234567890",
            "name": {
                "first": "Rodger",
                "last": "Wilco"
            }
        },
        "updated_at": "2021-10-29T06:23:57.388886Z",
        "verifiable_addresses": [
            {
                "created_at": "2021-10-29T06:23:57.395915Z",
                "id": "fb13d7a7-aba7-41bd-aba2-75a9459e2d38",
                "status": "sent",
                "updated_at": "2021-10-29T06:23:57.395915Z",
                "value": "test@gmail.com",
                "verified": false,
                "verified_at": null,
                "via": "email"
            }
        ]
    },
    "session": {
        "active": true,
        "authenticated_at": "2021-10-29T06:23:57.467702368Z",
        "expires_at": "2021-10-30T06:23:57.428123866Z",
        "id": "45ec9e67-8022-4586-89eb-cb9d30c60888",
        "identity": {
            "created_at": "2021-10-29T06:23:57.388886Z",
            "id": "19699c9b-14b7-4263-a15f-45803d000eea",
            "recovery_addresses": [
                {
                    "created_at": "2021-10-29T06:23:57.410531Z",
                    "id": "f4b6dbc7-0e98-4e10-bc90-d4c35fa982dd",
                    "updated_at": "2021-10-29T06:23:57.410531Z",
                    "value": "test@gmail.com",
                    "via": "email"
                }
            ],
            "schema_id": "default",
            "schema_url": "http://127.0.0.1:4433/schemas/default",
            "state": "active",
            "state_changed_at": "2021-10-29T06:23:57.388568437Z",
            "traits": {
                "email": "test@gmail.com",
                "mobile": "1234567890",
                "name": {
                    "first": "Rodger",
                    "last": "Wilco"
                }
            },
            "updated_at": "2021-10-29T06:23:57.388886Z",
            "verifiable_addresses": [
                {
                    "created_at": "2021-10-29T06:23:57.395915Z",
                    "id": "fb13d7a7-aba7-41bd-aba2-75a9459e2d38",
                    "status": "sent",
                    "updated_at": "2021-10-29T06:23:57.395915Z",
                    "value": "test@gmail.com",
                    "verified": false,
                    "verified_at": null,
                    "via": "email"
                }
            ]
        },
        "issued_at": "2021-10-29T06:23:57.428141826Z"
    },
    "session_token": "89aLaF0Gue7jc5TmshY5rQv52wDwJbhU"
}

I am able to make the first call to self-service/registration/api fine and receive the flow id. However on the self-service/registration/flows?id=XXX I see the following in the in the kratos logs:
kratos_1               | time=2021-10-29T07:13:01Z level=error msg=An error occurred while handling a request audience=application error=map[debug: details:map[docs:https://www.ory.sh/kratos/docs/debug/csrf hint:The anti-CSRF cookie was found but the CSRF token was not included in the HTTP request body (csrf_token) nor in the HTTP Header (X-CSRF-Token). reject_reason:The HTTP Cookie Header was set and a CSRF token was sent but they do not match. We recommend deleting all cookies for this domain and retrying the flow.] message:the request was rejected to protect you from Cross-Site-Request-Forgery reason:The request was rejected to protect you from Cross-Site-Request-Forgery (CSRF) which could cause account takeover, leaking personal information, and other serious security issues. status:Forbidden status_code:403] http_request=map[headers:map[accept:application/json accept-encoding:gzip content-length:133 content-type:application/json; charset=utf-8 forwarded:proto=http;host="backend.trusteeman.co.za:9080";for="10.0.2.2:39498" user-agent:Dart/2.14 (dart:io) x-forwarded-for:10.0.2.2 x-forwarded-host:backend.trusteeman.co.za:9080 x-forwarded-port:9080 x-forwarded-proto:http] host:kratos:4433 method:POST path:/self-service/registration/flows/id=29806d2f-a793-4815-bb2e-dd89255ac524 query:<nil> remote:172.18.0.8:48238 scheme:http] http_response=map[status_code:403] service_name=Ory Kratos service_version=v0.7.6-alpha.1
kratos_1               | time=2021-10-29T07:13:01Z level=info msg=started handling request http_request=map[headers:map[accept:application/json accept-encoding:gzip content-length:133 content-type:application/json; charset=utf-8 forwarded:proto=http;host="backend.trusteeman.co.za:9080";for="10.0.2.2:39498" user-agent:Dart/2.14 (dart:io) x-forwarded-for:10.0.2.2 x-forwarded-host:backend.trusteeman.co.za:9080 x-forwarded-port:9080 x-forwarded-proto:http] host:kratos:4433 method:POST path:/self-service/registration/flows/id=29806d2f-a793-4815-bb2e-dd89255ac524 query:<nil> remote:172.18.0.8:48238 scheme:http]
kratos_1               | time=2021-10-29T07:13:01Z level=info msg=completed handling request http_request=map[headers:map[accept:application/json accept-encoding:gzip content-length:133 content-type:application/json; charset=utf-8 forwarded:proto=http;host="backend.trusteeman.co.za:9080";for="10.0.2.2:39498" user-agent:Dart/2.14 (dart:io) x-forwarded-for:10.0.2.2 x-forwarded-host:backend.trusteeman.co.za:9080 x-forwarded-port:9080 x-forwarded-proto:http] host:kratos:4433 method:POST path:/self-service/registration/flows/id=29806d2f-a793-4815-bb2e-dd89255ac524 query:<nil> remote:172.18.0.8:48238 scheme:http] http_response=map[headers:map[content-type:application/json set-cookie:csrf_token_806060ca5bf70dff3caa0e5c860002aade9d470a5a4dce73bcfa7ba10778f481=0FE+eI5iwMUr8DfsR9yeimE7wcp9uk4MggzN8NS9cFk=; Path=/; Max-Age=31536000; HttpOnly; SameSite=Lax vary:Origin] size:706 status:403 text_status:Forbidden took:184.317µs]

Now in the init there a entry for csrf_token but the value is empty.
I'm not sure what I am missing. Any help greatly appreciated
Edit 1: Running kratos 0.7.6. There is spring cloud api gateway that is forwarding the request to kratos from the flutter app.
Edit 2: So the script was connecting directly to kratos. I've changed it to use the API gateway and seeing the same issue now.

A: I was using the wrong URL. Was using:
/self-service/registration/flows?id=XXX
This is the correct one:
/self-service/registration?flow=XXX


text:
Q: Elegantly Parsing Rigid Data in Perl I'm working with a large dataset that basically boils down to something like this:
my $input = q(
<foo>111</foo>
<foo>222</foo>
<foo>333</foo>
<foo></foo>
<foo>555</foo>
); # new-lines are either CR+LF, LF, or CR

Based on the example above, let's assume that the following constraints are in effect:

*

*There will always be 5 lines of data.

*Data in each line is enclosed in a single tag such as <foo>...</foo>.

*Data will contain no nested tags.

*All lines use the same tag (e.g foo) to enclose their data.

Ultimately, taking the above as the data source, I'd like to end up with something akin to this:
my %values = (
  one   => '111',
  two   => '222',
  three => '333',
  four  => '',
  five  => '555'
);

This is my attempt:
my @vals = $input =~ m!<foo>(.*?)</foo>!ig;

if (scalar @vals != 5) {
  # panic
}

my %values = (
  one   => shift @vals,
  two   => shift @vals,
  three => shift @vals,
  four  => shift @vals,
  five  => shift @vals
);

This works as I want, however it looks ugly and is not very flexible. Unfortunately, this is the best I can do for now since I'm new to Perl.
So, given the above constraints, what's a more elegant way to do this?

A: Merging two arrays into a hash:
my @keys = qw/one two three/;
my @values = qw/alpha beta gamma/;

my %hash;
@hash{@keys} = @values;

A: First, take another look at:
my %values = (
  one   => '111',
  two   => '222',
  three => '333',
  four  => '',
  five  => '555'
);

This data structure associates an integer with a piece of data. But there is already a built in data structure that serves the same purpose: Arrays.
So, use arrays. Instead of writing $values{ one }, you would write $values[ 0 ], and the mapping between integers and data values would be transparent.
If the keys are something other than integers, you can do:
use strict; use warnings;

my @keys = qw(a b c d e);

my $input = q(
<foo>111</foo>
<foo>222</foo>
<foo>333</foo>
<foo></foo>
<foo>555</foo>
); # new-lines are either CR+LF, LF, or CR

my %values;

# hash slice
@values{ @keys } = $input =~ m{ <foo> (.*?) </foo>}gix;

use YAML;
print Dump \%values;

Output:
---
a: 111
b: 222
c: 333
d: ''
e: 555

A: Oh, something like this give or take?
use Number::Spell;
$input =~ s|<(?:/)?foo>||g;
my @lines = grep { $_ } split "\n", $input; # grep for blank lines
my $i = 0;
my %hash = map { spell_number($i++) => $_ } @lines;

Hmm, I can make this better.
use Number::Spell;
my $i = 0;
my %hash = map { s|<(?:/)?foo>||g; $_ ? spell_number($i++) => $_ : () }
           split "\n", $input;

ed. whoops, had an @lines instead of $input inna second snippet. use caution; I have only typed out this code; I have not written a unit test.


text:
Q: Generic vs. specific element styles - for maintainability Consider the following three scenarios...
Scenario A
@import "reset.css";
/* ... */
p {margin:1em 0;}
/* ... */
p#copyright {margin:0; padding:10px;}

In Scenario A, a generic rule is applied to all
 elements that gives it top and bottom margins, so that the paragraphs are properly spaced when used in the HTML. But, by doing so, this causes cases where a
 element now needs its generic margins removed for decorative purposes, e.g. the Copyright at the foot of the document must have no margins.
Scenario B
@import "reset.css";
/* ... */
div.content_body p,
div.sidebar_body p {margin:1em 0;}
/* ... */
p#copyright {padding:10px;}

In Scenario B, it is assumed that
 elements don't need top and bottom margins unless explicitly defined.  Here the Content and Sidebar elements will need well-spaced paragraphs
Scenario C
@import "reset.css";
/* ... */
p.spaced {margin:1em 0;}
/* ... */
p#copyright {padding:10px;}

In Scenario C, only
 elements with a class spaced will have top and bottom margins applied.
Questions:
Which is the better scenario to use, and more importantly why?
What impact does each scenario have on:

*

*browser CSS performance

*CSS weight and maintainability

*the proliferation of UI defects

If you had to add a new widget that needed flowing paragraphs, which scenario would be better for you?
Thanks!

A: Generic first because it's better to allow all first and then block fews later. :)

A: I try to follow the principle that unadorned selectors (like "p" by itself) should provide reasonable defaults, and then use more specific selectors to override those defaults. I think this is best represented by Scenarios A and B.
If the markup is simple, and there exists a good, global default, then my stylesheets look like Scenario A.
If the markup is less simple, or global defaults are hard to define, then my stylesheets look more like Scenario B.
I try to avoid Scenario C if possible. I want it to be super easy for me (or someone else) to add new content 6 months later. I find that:

*

*The fewer specialized classes there are, the easier it is to "fall into the pit of success" because the simplest thing you write (
Whatever
) will just work.

*The more specialized classes there are, the greater the chance that you'll need to practice copy/paste programming to maintain consistent markup usage.

*CSS works better when classes are semantic and describe what a piece of content is than when they are presentational and describe how content should be displayed. Scenario C is an example of presentational styling, which is only marginally better than inline styles.

A: It totally depends on the design of your site.
If most paragraphs on the site should have margins, but a couple don't, then the approach in A would require the least code, and would thus probably result in lower CSS weight and more maintainability.
But if only paragraphs within your content and sidebar areas require margins (or there aren't many outside them that do), then the approach in B is a better idea.
As for the approach in C, my main worry with that would be how the HTML for the site is generated. If it's generated by a back-end system, that system will have to know which paragraphs should be spaced, and which shouldn't. That's extra complexity for the system, or its users, to deal with.
For the specific example of paragraphs, I've often ended up with something like B. It's easy to assume that paragraphs should have some nice, decent styling that would make, say an article nice to read. But if you look at most modern websites, most of what's on the page isn't content like that: it's menus and sidebars and special little things. Now, that may not be great, design-wise, but if you're implementing a design like that, B is the way to do that with less code, and less code generally means lower weight, easier maintainability, and fewer defects.

A: Personally I prefer scenario A. I find if you do things this way you can make the most of the cascade. The question you have to ask yourself though is "what is the sensible default?" Meaning is it more likely that a p will need spacing, or more likely that it wont. That should help you determine what your blanket defaults should be. Generally speaking the answer to this question is going to put you in line with scenario A.

A: D None of the above
@import ""; // don't need this
p { } // don't need this
ul#footer li { padding: 10px }

*

*Browsers manufacturers know an awful lot about their technology in particular and about typography and layout in general.  A 'reset' is a great way of disposing of all that aggregated experience. Browser default behaviour is a good thing and should only be overwritten in exceptional circumstances.  Different browsers do look a bit different.  This is not a bad thing.  See: http://dowebsitesneedtolookexactlythesameineverybrowser.com/

*A copyright citation is not a paragraph of text.  It is probably one among several items in a list of supporting information about the page in question.  If not, it is a list of one.