text:
Q: Issue RaspberryPi 3b+ and docker compose : Installing build dependencies: finished with status 'error' I'm working on a rapsberrypi 3b+, with Raspbian Buster Lite (version : February 2020)
I installed all dependencies as mentioned in this tutorial https://medium.com/@techiebouncer/install-docker-and-docker-compose-on-raspberry-pi-4-raspbian-buster-c5b78b9a0d08. Everything is up-to-date, however with I create my container there is a issue at step two of the Dockerfile when running this cmd :
RUN apt-get update \
&& apt-get install build-essential -y \
&& pip install poetry

The error message is very long:
  Installing build dependencies: finished with status 'error'
  ERROR: Command errored out with exit status 1:
   command: /usr/local/bin/python /usr/local/lib/python3.7/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-e8my0zvf/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.6.0' wheel 'cffi>=1.8,!=1.11.3; platform_python_implementation != '"'"'PyPy'"'"''
       cwd: None
  Complete output (100 lines):
  Collecting setuptools>=40.6.0
    Downloading setuptools-46.1.3-py3-none-any.whl (582 kB)
  Collecting wheel
    Downloading wheel-0.34.2-py2.py3-none-any.whl (26 kB)
  Collecting cffi!=1.11.3,>=1.8
    Downloading cffi-1.14.0.tar.gz (463 kB)
  Collecting pycparser
    Downloading pycparser-2.20-py2.py3-none-any.whl (112 kB)
  Building wheels for collected packages: cffi
    Building wheel for cffi (setup.py): started
    Building wheel for cffi (setup.py): finished with status 'error'
    ERROR: Command errored out with exit status 1:
     command: /usr/local/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-w3618jys/cffi/setup.py'"'"'; __file__='"'"'/tmp/pip-install-w3618jys/cffi/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-tib_06xh
         cwd: /tmp/pip-install-w3618jys/cffi/
    Complete output (36 lines):
    running bdist_wheel
    running build
    running build_py
    creating build
    creating build/lib.linux-armv7l-3.7
    creating build/lib.linux-armv7l-3.7/cffi
    copying cffi/cparser.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/recompiler.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/commontypes.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/vengine_cpy.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/backend_ctypes.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/cffi_opcode.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/ffiplatform.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/vengine_gen.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/verifier.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/setuptools_ext.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/pkgconfig.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/model.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/error.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/__init__.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/api.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/lock.py -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/_cffi_include.h -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/parse_c_type.h -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/_embedding.h -> build/lib.linux-armv7l-3.7/cffi
    copying cffi/_cffi_errors.h -> build/lib.linux-armv7l-3.7/cffi
    running build_ext
    building '_cffi_backend' extension
    creating build/temp.linux-armv7l-3.7
    creating build/temp.linux-armv7l-3.7/c
    gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DUSE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/include/ffi -I/usr/include/libffi -I/usr/local/include/python3.7m -c c/_cffi_backend.c -o build/temp.linux-armv7l-3.7/c/_cffi_backend.o
    c/_cffi_backend.c:15:10: fatal error: ffi.h: No such file or directory
     #include <ffi.h>
              ^~~~~~~
    compilation terminated.
    error: command 'gcc' failed with exit status 1
    ----------------------------------------
    ERROR: Failed building wheel for cffi
    Running setup.py clean for cffi
  Failed to build cffi
  Installing collected packages: setuptools, wheel, pycparser, cffi
      Running setup.py install for cffi: started
      Running setup.py install for cffi: finished with status 'error'
      ERROR: Command errored out with exit status 1:
       command: /usr/local/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-w3618jys/cffi/setup.py'"'"'; __file__='"'"'/tmp/pip-install-w3618jys/cffi/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-8j22vllc/install-record.txt --single-version-externally-managed --prefix /tmp/pip-build-env-e8my0zvf/overlay --compile --install-headers /tmp/pip-build-env-e8my0zvf/overlay/include/python3.7m/cffi
           cwd: /tmp/pip-install-w3618jys/cffi/
      Complete output (36 lines):
      running install
      running build
      running build_py
      creating build
      creating build/lib.linux-armv7l-3.7
      creating build/lib.linux-armv7l-3.7/cffi
      copying cffi/cparser.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/recompiler.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/commontypes.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/vengine_cpy.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/backend_ctypes.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/cffi_opcode.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/ffiplatform.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/vengine_gen.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/verifier.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/setuptools_ext.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/pkgconfig.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/model.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/error.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/__init__.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/api.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/lock.py -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/_cffi_include.h -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/parse_c_type.h -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/_embedding.h -> build/lib.linux-armv7l-3.7/cffi
      copying cffi/_cffi_errors.h -> build/lib.linux-armv7l-3.7/cffi
      running build_ext
      building '_cffi_backend' extension
      creating build/temp.linux-armv7l-3.7
      creating build/temp.linux-armv7l-3.7/c
      gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DUSE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/include/ffi -I/usr/include/libffi -I/usr/local/include/python3.7m -c c/_cffi_backend.c -o build/temp.linux-armv7l-3.7/c/_cffi_backend.o
      c/_cffi_backend.c:15:10: fatal error: ffi.h: No such file or directory
       #include <ffi.h>
                ^~~~~~~
      compilation terminated.
      error: command 'gcc' failed with exit status 1
      ----------------------------------------
  ERROR: Command errored out with exit status 1: /usr/local/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-w3618jys/cffi/setup.py'"'"'; __file__='"'"'/tmp/pip-install-w3618jys/cffi/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-8j22vllc/install-record.txt --single-version-externally-managed --prefix /tmp/pip-build-env-e8my0zvf/overlay --compile --install-headers /tmp/pip-build-env-e8my0zvf/overlay/include/python3.7m/cffi Check the logs for full command output.
  ----------------------------------------
ERROR: Command errored out with exit status 1: /usr/local/bin/python /usr/local/lib/python3.7/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-e8my0zvf/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.6.0' wheel 'cffi>=1.8,!=1.11.3; platform_python_implementation != '"'"'PyPy'"'"'' Check the logs for full command output.

It seems that there is an issue with libffi-dev module but it is up-to-date.
Or with gcc but I don't know what to install?

A: When you are building a docker image, every build dependency should be installed into the image, not on the host. If the package is required only for building, but not when running the image, you can uninstall it to reduce the image size:
RUN apt update \
  && apt install build-essential libffi-dev -y \
  && pip install poetry \
  && apt remove build-essential libffi-dev -y

how did you know thanks to the error message that you have to install it in the image and not in the host?

The error message
c/_cffi_backend.c:15:10: fatal error: ffi.h: No such file or directory
       #include <ffi.h>
                ^~~~~~~
      compilation terminated.
      error: command 'gcc' failed with exit status 1

indicates that the ffi.h is not available in the image when RUN pip install poetry is executed - the package that provides it on Debian and derivatives is libffi-dev.


text:
Q: Redirect if a value matches with any cell in a specific range - google sheets .gs (updated)
function doGet() {
return HtmlService.createTemplateFromFile('Form.html').evaluate()
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

var scriptProp = PropertiesService.getScriptProperties();

function doPost (e) {
var lock = LockService.getScriptLock();
lock.tryLock(10 * 1000);

var doc = SpreadsheetApp.getActiveSpreadsheet();
var sh = doc.getSheetByName("Sheet1");
var values = sh.getRange(2, 12, sh.getLastRow()-1, 1).getValues();
// Logger.log(values);

try {

var sheet = doc.getSheetByName("OTP");
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow() + 1;
var newRow = headers.map(function(header) {
return header === 'Timestamp' ? new Date() : e.parameter[header]
});
sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

var value = newRow[1];
for (var i = 0; i < values.length; i++) {
if (values[i] == value) {
return HtmlService.createTemplateFromFile('Confirmation.html').evaluate()
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
} else {
return HtmlService.createTemplateFromFile('Error.html').evaluate()
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}}}

catch (e) {
return ContentService.createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
.setMimeType(ContentService.MimeType.JSON)
}

finally {
lock.releaseLock()
}}

The purpose of the above code is to check if the value newRow[1] matches with any cell value in the range (L2:L) in Sheet1, then redirects to Confirmation.html, otherwise, to Error.html based on the if statement in the code
Now the problem is; only if newRow[1] == first/top value in the range (L2:L), the user is redirected to Confirmation and any other value below that in the range redirects the user to error
For example:
If we have 4 values in the range L2:L like that:
L2: John
L3: Mike
L4: Jenny
L5: Tom
If a user submits John as newRow[1], redirected to Confirmation and that is correct with no problem, but
If a user submits Mike or Jenny or tom, redirected to error and this wrong because the new submitted value is still in the range and should redirect the user to Confirmation as well
Any help is appreciated. Thanks in advance

A: Use Array.flat to flatten the data first before checking for the value instead of a for-loop:
if(values.flat().includes(value)){
  return /*confirmation page*/
} else {
  return /*error page*/
}

The for loop did not work, because the logic is amiss: Your code states that:
for each value in values
  if this value(in loop) is equal to value, I'm checking
    end this function and return confirmation html
  else
    end this function and return error html

Whatever the case, the function will end after checking the first value. The correct way to do such a for loop would be:
var isValueInColL = false;
for (var i = 0; i < values.length; i++) {
  if (values[i][0] == value) {//added [0]
    isValueInColL = true;
    break;// no need to check rest of col L
  }
}
var html = isValueInColL ? 'Confirmation' : 'Error';
return HtmlService.createTemplateFromFile(html).evaluate()
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

A: Try it this way:
function doGet() {
  return HtmlService.createHtmlOutputFromFile('Form.html');
}

function doPost (e) {
  Logger.log(JSON.stringify(e))
  if(!e || !e.parameter) {
    Browser.msgBox('No Parameters');
    return;
  }
  var doc=SpreadsheetApp.getActive();
  var sheet=doc.getSheetByName('OTP');
  var headers=sheet.getRange(1,1,1,sheet.getLastColumn()).getValues()[0];
  var nextRow=sheet.getLastRow() + 1;
  var newRow=headers.map(function(header) {return (header=='Timestamp')?new Date():e.parameter[header];});
  sheet.getRange(nextRow,1,1,newRow.length).setValues([newRow]);
  var sheet1=doc.getSheetByName("Sheet1");
  var values=sheet1.getRange(2,12,sheet1.getLastRow()-1,1).getValues();
  var value=newRow[1];
  for (var i=0;i<values.length; i++) {
    if (values[i][0]==value) {
      return HtmlService.createHtmlOutputFromFile('Confirmation');
    }else {
      return HtmlService.createHtmlOutputFromFile('Error');
    }
  }
}

Try your html this way:
<!DOCTYPE html>
<html lang="en">
<head>
  <base target="_top">
  <style>body {font-family: "Lato", sans-serif}</style>
</head>
<body>
  <form action="script URL" target="_self" method="POST">
  <input type="number" placeholder="Enter OTP" required name="OTP">
  <button type="submit">Send</button>
  </form>
</body>
</html>

Some of your html tags were out of place for example the body tag doesn't belong above the

redpajama_set_name: RedPajamaStackExchange


text:
Q: pgfplots: drawing areas from a table starting "above" an axis Please let me explain the motivation behind this a bit more broadly. I'd like to draw measured benchmark values as follows:
background/nothing between the x-axis and the minimum value
a green area between the minimum value and the median
a black line at the median
a red area between the median and the maximum value
background/nothing above the maximum
I tried various attempts to reach this before using the IMHO quite inelegant way of just drawing a white area on top of the other plots (although after all the pain I think I can live with that :), the code below shows that and how an alternative solution should look like too.
One try was to use stacked plots, but of course the values are stacked and I could not find an equivalent to bar shift=0pt. I also think there is no way to disable the stacking per plot (or the other way around, i.e. disable it globally but enable it for selected plots).
The most similar solution I could find yet is Fill between two curves in pgfplots. but I could not get it to work with the pre-existing table data I have (is there really no easy way to copy selected columns into a new table!?). Is the white area approach below really the best way to do this?
\documentclass{article}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\begin{document}

\pgfplotstableread{
    size        min         max         med
    1           1           3           2
    10          2           4           3
}{\loadedtable}

\begin{tikzpicture}
\begin{axis}[
    legend entries={above median,below median, median,},
    ymin=0,
    area style,
    ]
    \addplot [fill=red!40, draw=none]   table [x=size, y=max]   {\loadedtable} \closedcycle;
    \addplot [fill=green!40, draw=none] table [x=size, y=med]   {\loadedtable} \closedcycle;
    \addplot [draw=black, line legend]  table [x=size, y=med]   {\loadedtable};
    \addplot [fill=white, draw=white]   table [x=size, y=min]   {\loadedtable} \closedcycle;

\end{axis}
\end{tikzpicture}

\end{document}

A: You can use stack plots=y if you set subtract the minimum value from the median value and the median value from the maximum value by using y expr=\thisrow{med}-\thisrow{min} and y expr=\thisrow{max}-\thisrow{med}.
Stacking of plots can be applied to selected plots by only providing stack plots=y to the desired plots, or by setting stack plots=false for the plots you don't want to stack.

\documentclass{article}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\begin{document}

\pgfplotstableread{
    size        min         max         med
    1           1           3           2
    10          2           4           3
}{\loadedtable}

\begin{tikzpicture}
\begin{axis}[
    enlarge x limits=false, axis on top,
    legend entries={below median,median, above median},
    reverse legend, legend pos=outer north east,
    ymin=0,
    ]
    \addplot [stack plots=y, fill=none, draw=none, forget plot]   table [x=size, y=min]   {\loadedtable} \closedcycle;
    \addplot [stack plots=y, fill=green!40, draw opacity=0, area legend] table [x=size, y expr=\thisrow{med}-\thisrow{min}]   {\loadedtable} \closedcycle;
    \addplot [stack plots=false, draw=black, thick]  table [x=size, y=med]   {\loadedtable};
    \addplot [stack plots=y, fill=red!40, draw opacity=0, area legend]   table [x=size, y expr=\thisrow{max}-\thisrow{med}]   {\loadedtable} \closedcycle;

   %

\end{axis}
\end{tikzpicture}

\end{document}


text:
Q: CodeIgniter, Order by number of rows in a separate joined table? I have 4 tables that link together...
Firstly the hotels table

*

*hotel_id

*town_id

*hotel_name

Then the towns table:

*

*town_id

*region_id

*town_name

Then the regions table:

*

*region_id

*country_id

*region_name

Finally the countries table

*

*country_id

*country_name

What I need to do is list the towns in order of how many hotels there are within that town.
The reason I have included the regions table and the countries table is because, when displaying that town, I need to display the country it's from. This can only be obtained via the regions table..
Therefore using the active records in CodeIgniter I have done this so far:
$this->db->join('regions','towns.town_region_id = regions.region_id');
$this->db->join('countries','regions.region_country_id = countries.country_id');
$query = $this->db->get('towns');

foreach ($query->result() as $row) {
     echo "<li>";
     echo "$row->town_name, $row->country_name";
     echo "</li>";
}

This outputs:

*

*London, United Kingdom

*Washington, United States

*New York, United States

*Moscow, Russia

*etc, etc

Each one of these cities have hotels in them. All I need now is to order them by how many hotels there are in each town..
Any help would be much appreciated! Thanks.

A: $this->db->select('t.*,c.*,COUNT(h.hotel_id) AS nhotels');
$this->db->from('towns t');
$this->db->join('hotels h','h.town_id = t.town_id');
$this->db->join('regions r','t.town_region_id = r.region_id');
$this->db->join('countries c','r.region_country_id = c.country_id');
$this->db->group_by('t.town_id');
$this->db->order_by("nhotels",'DESC');
$query = $this->db->get();

which will produce the following query:
SELECT `t`.*, `c`.*, COUNT(h.hotel_id) AS nhotels
FROM (`towns` t)
   JOIN `hotels` h
      ON `h`.`town_id` = `t`.`town_id`
   JOIN `regions` r
      ON `t`.`town_region_id` = `r`.`region_id`
   JOIN `countries` c
      ON `r`.`region_country_id` = `c`.`country_id`
GROUP BY `t`.`town_id`
ORDER BY `nhotels` DESC

A: SELECT
   hotels.town_id,
   count(hotels.hotel_id) from hotels AS hotels_count,
   towns.town_name
FROM
    hotels,
LEFT JOIN
    towns ON hotels.town_id = towns.town_id
GROUP BY hotels.town_id
ORDER BY hotels_count DESC;


text:
Q: how to tell Latex to ignore empty lines This is a problem I had for long time. I use software to generate Latex (SW). It adds lots of empty lines.  Which ends up using extra white space between a text and the displayed equation that follows.
I've always fixed this by manually removing these empty lines once I am done editing the document. But this is time consuming to do each time.
Is there some command one can add to the preamble only to tell Latex to automatically ignore empty lines, or treat them as if they had % as first character?
I will first show a MWE that shows the problem and then show what I tried after that.  Compare the output of this file
\documentclass[11pt]{article}
\usepackage{amsmath}
\usepackage[grid]{eso-pic}
\setlength\parindent{0pt}
\begin{document}
line 1

\begin{align*}
x &= y
\end{align*}

line 2
\end{document}

With this file
\documentclass[11pt]{article}
\usepackage{amsmath}
\usepackage[grid]{eso-pic}
\setlength\parindent{0pt}
\begin{document}
line 1
%
\begin{align*}
x &= y
\end{align*}
%
line 2
\end{document}

Here it is side by side

The left image is for the first file above. You can see it has extra space before the \begin{align} and after \end{align} which I do not like.
I'd like to obtain same output as the right side image (less space), but without having to manually edit the latex file each time by either adding % or to delete the blank lines.
This is what I tried. I saw this question how-to-remove-blank-lines-around-equations but this requires one to manually edit the Latex file and add commands after preamble.
I saw this how-to-disable-new-paragraph-at-empty-line and I tried the solution there which says
  Redefine \par, for example \let\par\relax

But that broke many things in my main build and I was getting many latex errors. The second solution there which says
   Redefine \endlinechar to be 32

This is what I tried.
\documentclass[11pt]{article}
\usepackage{amsmath}
\usepackage[grid]{eso-pic}
\usepackage[subtle]{savetrees}
\setlength\parindent{0pt}
\endlinechar=32
\begin{document}
line 1

\begin{align*}
x &= y
\end{align*}

line 2
\end{document}

update: I need to try the above again on my main build. I had written it wrong before. Will update soon to see if it worked.
I also tried the package \usepackage[moderate]{savetrees} and this is the result
\documentclass[11pt]{article}
\usepackage{amsmath}
\usepackage[grid]{eso-pic}
\usepackage[moderate]{savetrees}
\setlength\parindent{0pt}
\begin{document}
line 1

\begin{align*}
x &= y
\end{align*}

line 2
\end{document}

Here is side by side

So \usepackage[moderate]{savetrees} did what I want for this example. But when I tried it on large document, I found it compresses things too much in many other places and made line too close to each others. So I did not like the effect. When I tried \usepackage[subtle]{savetrees}, the space was not removed any more.
So I am not sure what to try next.
I asking if there is some other solution to try. Again, I want all empty lines to be treated as %. But by modifying the preamble only. Not the internals of the document, as the document itself is auto-generated.
Using texlive 2017. I use lualatex to compile latex file.


text:
Q: Discover the linear operation between 'x' and 'y' Discover the linear operation between 'x' and 'y'...
This is my code:
public class Program {
    public static int Puzzle(int x, int y) {
        return ( x / y ) * y;
    }
}

This is the result:
x       y       EXPECTED RESULT     YOUR RESULT     DESCRIPTION
1       1       1                   1
2       2       2                   2
919     648     1135                648             Mismatch

I can't imagine what code are suposed to be write.

A: x + (y / 3)

where x and y are integer types.  You need to think about why being integer types is so essential.

A: For solution you need to take a closer look into word "linear operator": it means, that for x and y it returns something like ax + by, where a and b are constants. So:
a * 1 +  b * 1 = 1
a * 2 + b * 2 = 2 // may be removed as it's the same as the first line multiplied by 2
a * 919 + b * 648 = 1135
You can subtract first equality from the last multiplied by 648 and get
a * (919 - 648) = 1135 - 648 => a = 487 / 271 => b = 1 - a = (271 - 487) / 271 = -216 / 271
So, the resulting operator is
f(x, y) = 487/271 * x - 216/271 * y


text:
Q: Хорошая информация по ncurses Хочу выучить ncurses. Все, что я нашел, - hello world'ы.
A: NCURSES Programming HOWTO
A: Неплохой вводный раздел есть в книге Метью, Стоунс. Основы программирования в Linux.
Далее - очень хороший HOWTO


text:
Q: WindowsError: [Error 193] %1 is not a valid Win32 application in Python I wish to import liblas module in Python 2.7 on window 64bit. If I import the module with IDLE (Python GUI) I have no problem.
If I use PyScripter "PyScripter-v2.5.3-x64-Setup.exe" I get this error message.
>>> import liblas
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python27\lib\site-packages\liblas\__init__.py", line 2, in <module>
    from core import get_version
  File "C:\Python27\lib\site-packages\liblas\core.py", line 138, in <module>
    las = ctypes.CDLL(os.path.join(local_dlls, lib_name))
  File "C:\Python27\Lib\ctypes\__init__.py", line 365, in __init__
    self._handle = _dlopen(self._name, mode)
WindowsError: [Error 193] %1 is not a valid Win32 application

I have used liblas in PyScripter many times without problem and right now I can load all standard modules (e.g.: numpy, GDAL, etc.), but tonight (I need to finish an analysis!!!) I have this inconvenience.

A: Please make sure to have Python 2.7 64b edition :) or even though you are working on 64b OS, use the x86 (AKA 32b) edition of PyScripter
Edit 1 (following comments exchange w/ Gianni)
One should verify his/her entire Python process "composed" from same entities in the sense of 32b/64b builds (e.g. if your Python interpreter is 32b one, then it must use C types coming from C dll  Python extensions which were compiled as 32b dlls).
In our example (liblas) one should go to C:\Python27\lib\site-packages\liblas , find the extension dll and see its type via dumpbin , here is some picture for demonstration :

A: This error can also be caused because the DLL that Python is attempting to run has been compiled on a newer version of C++.  Make sure you are running the latest version of the Microsoft C++ Distribution.
You can see the version you are running in the Python terminal window (highlighted in bold)
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Download here
https://www.microsoft.com/en-us/download/details.aspx?id=48145

A: You are probably using 64 bits Python.
You should install the 32 bits version instead.

A: If you got this error too, plase take a look at your python.exe file.
In my case it was corrupted as you can see below:

So I copied from another venv and reinstalled the dependencies.
Then it worked :)


text:
Q: Can `merge!` change a CONST in Ruby? I have a situation where merge! seems to modify the value of a CONST.  Can this occur?  How?
I'm doing some API ingestion and mapping, like you do...
module Placement
  FEATURE_DEFAULTS = {
    "thingone" => "false",
    "thingtwo" => "false"
  }

  def extract_features!(feat)
    feat['norm_features'] ||= FEATURE_DEFAULTS
    feat['norm_features'].merge!(
      Array(feat['attributes']['feature']).reduce({}) do |h,f|
        h[f] = "true"
        h
      end
    )
  end

  def get_placement(_opts)
    data_source["things"]["thing"].map do |thing|
      product = {}
      thing.each do |key, value|
        new_key = RENAME_FIELDS[key] || key
        new_value = REPLACE_FIELDS[key] || value
        product[new_key] = new_value
      end

      binding.pry  # 1
      extract_features!(product)
      binding.pry  # 2
      product
    end
  end
end

Later, I include this in a class for the API client, and then I call the get_placement method.
Dilemma
step 1
For the first run, in pry binding 1 & 2, the value of FEATURE_DEFAULTS is as seen above.  For 2 the value of FEATURE_DEFAULTS is the same, and the value of product['norm_features'] is the same (plus the results of the meshing operation of extract_features!
step 2
The output (to the caller of get_placement), for every thing/product, is
  FEATURE_DEFAULTS = {
    "thingone" => true,
    "thingtwo" => true
  }

step 3
When I run this the second time (after starting up the service / app), the value of FEATURE_DEFAULTS, and pry binding 1 & 2, is
  FEATURE_DEFAULTS = {
    "thingone" => true,
    "thingtwo" => true
  }

What is happening here?

This seems to confirm that, after running the extract_features! method, the FEATURE_DEFAULTS CONST is changed.  If I do not use merge! in extract_features!, and use merge instead, then the CONST value does not change.

I can post more code, if needed, or most to a Gist.
Ruby MRI 2.2.2
I am doing this inside a rails app, but I don't see that it matters.

A:
I have a situation where merge! seems to modify the value of a CONST. Can this occur? How?

No, in general, methods cannot change variable bindings, regardless of whether those variables are local variables, instance variables, class variables, global variables, or constants. Variables aren't objects in Ruby, you can't call methods on them, you can't pass them as arguments to methods, ergo, you can't tell them to change themselves.
The exception to this are meta-programming methods like Binding#local_variable_set, Object#instance_variable_set, Module#class_variable_set, or Module#const_set.
What you can do, however, and what you are doing in this case, is tell the object the variable points to to change itself. The documentation for Hash#merge! is unfortunately a bit unclear in that it does not explicitly mention that Hash#merge! mutates its receiver.

This seems to confirm that, after running the extract_features! method, the FEATURE_DEFAULTS CONST is changed.  If I do not use merge! in extract_features!, and use merge instead, then the CONST value does not change.

No, it only confirms that the state of the object FEATURE_DEFAULTS points to changed, it doesn't say anything about whether the binding of FEATURE_DEFAULTS, i.e. which object it points to, changed. You can confirm that the constant still points to the same object by looking at its object_id.
Of course, constants can be re-assigned anyway, albeit triggering a warning.


text:
Q: Import Excel Slow Performance within Foreach Loop and Do Filtering The following code runs incredibly slowly when performing a FOREACH LOOP then do filtering using data from table cabang and insert to a table called part_rak.
The filtering loop through each row on excel file then loop based comma separator
Filtering Loop
if (explode(",", $rowData[0][14]) > 1) {

                foreach (explode(",", $rowData[0][14]) as $key => $value2) {
                    $data       = array(
                                "rak_part_id"   => $last,
                                "rak_cabang_id" => $this->spareparts_m->get_cabang_id_by_code("B"),
                                "rak_code"      => $value2,
                                "rak_created_at"=> date('Y-m-d H:i:s')
                    );
                    $this->db->insert("part_rak",$data);
                }

            }else{
                foreach (explode("|", $cabang) as $key => $value) {
                    $data       = array(
                                "rak_part_id"   => $last,
                                "rak_cabang_id" => $value,
                                "rak_code"      => $expRak[$key],
                                "rak_created_at"=> date('Y-m-d H:i:s')
                    );
                    $this->db->insert("part_rak",$data);

                }
            }

here it is my model method get_cabang_id_by_code
public function get_cabang_id_by_code($cabang_code)
    {
        $q = $this->db->get_where("cabang",array("cabang_code" => $cabang_code));
        return $q->result_array()[0]['cabang_id'];
    }

I'd be grateful of any suggestions which would improve the performance of my script.
below is my complete import source code
public function import($uploaded)
    {
        $inputFileName =  './public/uploads/excel/'.$uploaded['file_name'];
        try {
            $inputFileType = IOFactory::identify($inputFileName);
            $objReader = IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($inputFileName);
        } catch(Exception $e) {
            die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
        }

        $sheet          = $objPHPExcel->getSheet(0);

        $highestRow     = $sheet->getHighestRow();
        $highestColumn  = $sheet->getHighestDataColumn();
        $last_id="";
        for ($row = 3; $row <= $highestRow; $row++){                  //  Read a row of data into an array
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);

            $data = array(
                "part_no"           => $rowData[0][0],
                "part_revised_no"   => $rowData[0][1],
                "part_latest_no"    => $rowData[0][2],
                "part_desc"         => $rowData[0][3],
                "part_incoming_date"=> $rowData[0][4],
                "part_fob_japan"    => $rowData[0][5],
                "part_min_order"    => $rowData[0][6],
                "part_master_key1"  => $rowData[0][7],
                "part_total_stock"  => $rowData[0][8],
                "part_stock_j"      => $rowData[0][9],
                "part_stock_b"      => $rowData[0][10],
                "part_stock_s"      => $rowData[0][11],
                "part_stock_m"      => $rowData[0][12],
                // "part_rak"          => $rowData[0][13],
                "part_last_opname"  => $rowData[0][17],
                "part_discontinued" => $this->convDiscontinued($rowData[0][18]),
                "part_mesin_code"   => $rowData[0][19],
                "part_srp"          => $rowData[0][20],
                "part_srp_cod"      => $rowData[0][21],
                "part_supv_price"   => $rowData[0][22],
                "part_mgr_price"    => $rowData[0][23],
                "part_dtr_price"    => $rowData[0][24],
                "part_keterangan"   => $rowData[0][25],
            );
            // $data['part_rak_id']   = implode(",", $arrLast);
            $insert     = $this->db->insert("sparepart", $data);
            $last       = $this->db->insert_id();

            $cabang = $this->spareparts_m->get_cabang_id_by_code("J")."|".
                      $this->spareparts_m->get_cabang_id_by_code("B")."|".
                      $this->spareparts_m->get_cabang_id_by_code("S")."|".
                      $this->spareparts_m->get_cabang_id_by_code("M");

            $rak_code   = $rowData[0][13]."|".$rowData[0][14]."|".$rowData[0][15]."|".$rowData[0][16];
            $expRak     = explode("|", $rak_code);
            $arrLast    = [];

            if (explode(",", $rowData[0][13]) > 1) {

                foreach (explode(",", $rowData[0][13]) as $key => $value2) {
                    $data       = array(
                                "rak_part_id"   => $last,
                                "rak_cabang_id" => $this->spareparts_m->get_cabang_id_by_code("J"),
                                "rak_code"      => $value2,
                                "rak_created_at"=> date('Y-m-d H:i:s')
                    );
                    $this->db->insert("part_rak",$data);
                }

            }else{
                foreach (explode("|", $cabang) as $key => $value) {
                    $data       = array(
                                "rak_part_id"   => $last,
                                "rak_cabang_id" => $value,
                                "rak_code"      => $expRak[$key],
                                "rak_created_at"=> date('Y-m-d H:i:s')
                    );
                    $this->db->insert("part_rak",$data);
                    // $arrLast[]= $this->db->insert_id();
                }
            }

            if (explode(",", $rowData[0][14]) > 1) {

                foreach (explode(",", $rowData[0][14]) as $key => $value2) {
                    $data       = array(
                                "rak_part_id"   => $last,
                                "rak_cabang_id" => $this->spareparts_m->get_cabang_id_by_code("B"),
                                "rak_code"      => $value2,
                                "rak_created_at"=> date('Y-m-d H:i:s')
                    );
                    $this->db->insert("part_rak",$data);
                }

            }else{
                foreach (explode("|", $cabang) as $key => $value) {
                    $data       = array(
                                "rak_part_id"   => $last,
                                "rak_cabang_id" => $value,
                                "rak_code"      => $expRak[$key],
                                "rak_created_at"=> date('Y-m-d H:i:s')
                    );
                    $this->db->insert("part_rak",$data);
                    // $arrLast[]= $this->db->insert_id();
                }
            }

            if (explode(",", $rowData[0][15]) > 1) {

                foreach (explode(",", $rowData[0][15]) as $key => $value2) {
                    $data       = array(
                                "rak_part_id"   => $last,
                                "rak_cabang_id" => $this->spareparts_m->get_cabang_id_by_code("S"),
                                "rak_code"      => $value2,
                                "rak_created_at"=> date('Y-m-d H:i:s')
                    );
                    $this->db->insert("part_rak",$data);
                }

            }else{
                foreach (explode("|", $cabang) as $key => $value) {
                    $data       = array(
                                "rak_part_id"   => $last,
                                "rak_cabang_id" => $value,
                                "rak_code"      => $expRak[$key],
                                "rak_created_at"=> date('Y-m-d H:i:s')
                    );
                    $this->db->insert("part_rak",$data);
                    // $arrLast[]= $this->db->insert_id();
                }
            }

            if (explode(",", $rowData[0][16]) > 1) {

                foreach (explode(",", $rowData[0][16]) as $key => $value2) {
                    $data       = array(
                                "rak_part_id"   => $last,
                                "rak_cabang_id" => $this->spareparts_m->get_cabang_id_by_code("M"),
                                "rak_code"      => $value2,
                                "rak_created_at"=> date('Y-m-d H:i:s')
                    );
                    $this->db->insert("part_rak",$data);
                }

            }else{
                foreach (explode("|", $cabang) as $key => $value) {
                    $data       = array(
                                "rak_part_id"   => $last,
                                "rak_cabang_id" => $value,
                                "rak_code"      => $expRak[$key],
                                "rak_created_at"=> date('Y-m-d H:i:s')
                    );
                    $this->db->insert("part_rak",$data);
                    // $arrLast[]= $this->db->insert_id();
                }
            }

        }
    }


text:
Q: How to specify data frame as time series? I am loading in time-series data into R for analysis. I am trying to lag one of the variables in order to difference the series. Unfortunately, the values of the differences variables all equal 0, because R wasn't successful at lagging the weight variable. I know I am supposed to use the as.ts(data$date) to specify that that "date" variable is a time series but every time I do so it changes the "date" variable into numeric numbers. Not to mention I thought I specified that the "date" column in the dataset was a time/date variable when I initially loaded it. How can I specify the data.frame as a time series?
data=read.csv("filelocation",header=T,colClasses=c("Date","numeric")

  date   weight
2010-10-04 52495
2010-10-01 53000
2010-09-30 52916
2010-09-29 52785
2010-09-28 53348
2010-09-27 52885
2010-09-24 52174
2010-09-23 51461
2010-09-22 51286
2010-09-21 50968
2010-09-20 49250

data=data[order(data$date),]
diffweight1=weight-lag(weight,1)

A: Try this:
library(zoo)

z <- read.zoo("filelocation", header = TRUE, sep = ",")
diff(z)

A: when you manipulate times series it is better to use (zoo or xts) packages. Many time series operations as lags, diff become very simple.
here an example using xts package ( I prefer this one)
# I read your data
dat <- read.table (text = 'date   weight
2010-10-04 52495
2010-10-01 53000
2010-09-30 52916
2010-09-29 52785
2010-09-28 53348
2010-09-27 52885
2010-09-24 52174
2010-09-23 51461
2010-09-22 51286
2010-09-21 50968
2010-09-20 49250',header=TRUE)
# I construct my xts object
dat.xts <- xts(dat$weight,order.by=as.POSIXct(dat$date))
# new 2 columns withs lags(1) and diff

merge(dat.xts, ll = lag(dat.xts),dd =diff(dat.xts))
           dat.xts    ll   dd
2010-09-20   49250    NA   NA
2010-09-21   50968 49250 1718
2010-09-22   51286 50968  318
2010-09-23   51461 51286  175
2010-09-24   52174 51461  713
2010-09-27   52885 52174  711
2010-09-28   53348 52885  463
2010-09-29   52785 53348 -563
2010-09-30   52916 52785  131
2010-10-01   53000 52916   84
2010-10-04   52495 53000 -505

A: What I feel you need is difference between adjacent rows for weight col
You can try :
weight <- c(20,40,70,110)
diff(weight)
[1] 20 30 40

since 40 - 20 = 20, 70 - 40 = 30 and so on
similarly try difftime for time series in case you need that

A: Time-series objects are designed to track data sampled at equally spaced points in time. You have an uneven sampling interval, but ts(data) seems to do what you're looking for.


text:
Q: How to create grafana dashboard without time range? I want to remove time range selector from grafana dashboard to not query for specific selected time range. I am using influxdb and I want to load all data without selecting specific time range and query with some where clausess. Is it possible?

A: In the dahboard setting enable Hide time picker and all InfluxDB queries write in the raw mode without time conditon ($timeFilter macro).


text:
Q: File naming inside a for loop Please have a look on the following Minimal Working Example (MWE)
import numpy as np
T_val = np.linspace(100,200,15)
for i,T in enumerate(T_val):
    ut_file_name = 'kappaFunction_P_E_%2d.pdf' % i
    print out_file_name

The output for this MWE coming like:

.
  .
  kappaFunction_P_E_ 7.pdf
  kappaFunction_P_E_ 8.pdf
  kappaFunction_P_E_ 9.pdf
  kappaFunction_P_E_10.pdf
  kappaFunction_P_E_11.pdf
  kappaFunction_P_E_12.pdf
  .
  .

What I intended to get is

... kappaFunction_P_E_08.pdf, kappaFunction_P_E_09.pdf,  kappaFunction_P_E_10.pdf....

Instead of prepending 0 before the single digit number it is leaving a space. How can we get rid of this?

A: ut_file_name = 'kappaFunction_P_E_{:0>2}.pdf'.format(i)

Your should use format(). You can reference from https://pyformat.info/ or docs from https://docs.python.org/2/library/string.html.

A: Add a 0 to the format
... %02d.pdf' % i

that will print 07, 08, 09, etc.

A: You don't need to use enumerate since your are only using the index.
And for your format to work as expected, you need to use %02d to get the 0 before:
import numpy as np
T_val = np.linspace(100,200,15)
for i in range(len(T_val)):
    ut_file_name = 'kappaFunction_P_E_%02d.pdf' % i
    print out_file_name


text:
Q: How to make startx use alternate xinitrc? I don't have a desktop manager installed (and I don't want to). After logging in through the terminal I use startx to start the GUI. I have entries in ~/.xinitrc for my GUI sessions. Right now I have xmonad in there, but sometimes I want to run a GNOME session, and sometimes a KDE session. I used to edit ~/.xinitrc for that purpose, but I think there should be a more elegant way (something like using alternate configurations). However, I can't find anything in man startx or man xinit.
I plan to have several configuration files (one for each GUI session), and then tell startx to load them when I want. How can I do that?

A: According to the xinit man page that I read, xinit (and thereby startx) looks in its command line parameters for a client program to run.  If it doesn't find one, it runs ~/.xinitrc instead.  So you should be able to write
startx path/to/my_alternate_xinitrc

and it will do what you want.  You will need to provide a path, though, and not just a filename.  In my testing, startx ./my_xinitrc worked but startx my_xinitrc did not.


text:
Q: using React to show existing JS/html pages in Tabs I am new to React I am trying to create a simple code.
At the moment I have several dashboards that I wrote using HTML/JavaScript/JQuery integrating with a php server code in MVC way.
My goal is to create a dashboard center, basically this page will show a few Tabs, each tab will  load a different dashboard.
I run into multiple problems when importing my files (I added them to the src directory) when importing JS files to the react app, I get failed to compile on about everything inside those files.
the react is also shouting about me using ag-grid compoinents inside the JS files.
is there a way to do what I need to achieve ?
is there a way to load a html files from within the React app.
import React from 'react';
import './App.css';
import { render } from "react-dom";
import Tabs from './Tabs';
require('./tab-dashboard-css/tabStyles.css');

function App() {
  return (

Tabs Demo

        <Tabs>

              // I want to load an html file into a Tab like this

            After 'while, Crocodile!

            Nothing to see here, this tab is extinct!

        </Tabs>

  );
}

export default App;

this is an example of one of my html files
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Generic Dashboard</title>

    <link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-grid.css">
    <link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-theme-balham.css">

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet">
    <link href="/UI_Assets/select2/select2.min.css" rel="stylesheet"/>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">

    <link href="/dashboards/css/style.css" rel="stylesheet"/>

    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">

    <title>Campaign/AdSet/Ad</title>

Generic Dashboard – Accounts

            Client:

            <select class="SelectClientClass" id="SelectClient" onchange="handleClientSelection()">
                <option value="" selected disabled hidden>Select Client / App</option>
            </select>

A: You need to import react and react-dom depandencies and your building app into your html file.
Then you need the following code to render your App component:
ReactDom.render(React.createElement('App'), HTMLElement);

A: Hi if anyone ever have a similar question.
in the end I solved the problem with using react-iframe
then my react app just loaded my previous JS/JQUERY pages from a link to my server.
when I develop new apps from now I will do it in react no problem.
this was an easy solution for integrating my previous dashboards inside a tab component in a react app.


text:
Q: Cannot ping/ssh devices connected to a DD-WRT router I have tried to find similar questions / google it but it seems pretty hard to find a case that exactly matches mine.
I have a TP-Link wdr3500 router with DD-WRT flashed on it. The router gateway is 192.168.1.1 I have tested it with the following devices:

*

*Device A: My desktop, running Win 10 - wired 192.168.1.131

*Device B: My Intel NUC, running Ubuntu Server 16.04 - wired 192.168.1.111

*Device C: MacBook Pro - wireless 5.0 192.168.1.113

*Device D: Chromecast - wireless 5.0 192.168.1.112

*Device E: Thinkpad laptop - wireless 2.4 192.168.1.117
These are the connections I tested:

*

*From A, I can only ping C and D

*From B, I can only ping C and D (A gives me From 192.168.1.111 icmp_seq=1 Destination Host Unreachable, while E just times out)

*From C and D I can ping everything except E

*From E I can ping everything.

I would like to be able to ping everything from anything, does anyone have a clue what is wrong with my setup, and where and how can I fix it ?
Thanks a lot in advance


text:
Q: Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right I wrote this code, it passed initial test cases but it shows run time error when I submitted. I am unable to understand why?
Run time error:- Index -1 array out of bounds for length 8
class Solution {
public int[] duplicateZeros(int[] arr)
{
    int n=arr.length;
    int count=0;
    for(int i=0;i<n;i++)
    {
        if(arr[i]==0)
            count=count+1;
    }

    int loc= n-1;
    int p=n-1+count;
    if(count==0)
        return arr;
    for(int i=n-1,j=p;i>=0;i--,j--)
    {
        if(j<=n && loc>=0)
        {
            if(arr[i]==0)
            {
                arr[loc]=0;
                arr[loc-1]=0;
                loc=loc-2;
            }
            else
            {
                arr[loc]=arr[i];
                loc=loc-1;
            }
        }
    }
    return arr;

}
}

A: In the following code if loc is 0 and arr[i] is 0 and j <= n you enter the nested if and arr[loc-1] is arr[-1] that can give you the ArrayOutOfBoundException
// If j <= n and loc is 0 enter the first if
if (j <= n && loc >= 0) {
   // If arr[i] == 0 enter the second if
   if (arr[i] == 0) {
       arr[loc] = 0;
       arr[loc - 1] = 0;   // loc is 0 so arr[loc - 1] throw the Error
       loc = loc - 2;
   } ...

A: class Solution {
    public int[] duplicateZeros(int[] arr) {
        int n = arr.length;
        int count = 0;
        /* While we are not at the end of arr and the value is 0... */
        for(; (count < n) && (arr[count] == 0); count++) {
            /* Add one to count until we are done */
        }

        /* If half or more of the array is 0, then we zero things and are done */
        if (count > n/2) {
            for (int i = count; i < n; i++) {
                arr[i] = 0;
            }
            return arr;
        }

        /* We have shifting work to do :'( */
        int end = n - 1;
        int loc = n - 1 - count;
        int boundary = 2 * count;
        /* Shift from loc to end while we have not copied into a space that will be 0 */
        for(; end >= boundary; end--; loc--) {
            arr[end] = arr[loc];
        }

        /* Put a 0 into all the spots there should be a zero, ignoreing the places there is already a 0 */
        for (int i = count; i < boundary; i++) {
            arr[i] = 0;
        }
        /* Done! */
        return arr;
    }
}

I didn't test this code... but it should be very close to what you want.
I think your issue is that you overcomplicated your code and tried to wrap your steps into if{} else{} logic you didn't need to.
You also tried to do duff's loop by setting two 0's at once.
Also, you don't need to return arr - when you return to the caling function, you will have modified the original array.

A: The biggest problem is that you are trying to create the result into the same array. If there are any 0's, this won't fit.
Here is a slightly simpler solution requiring Java 8 or higher:
public static int[] duplicateZeros(int[] arr) {
    return Arrays.stream(arr)
        .flatMap(i -> i == 0 ? IntStream.of(i, i) : IntStream.of(i))
        .toArray();
}


text:
Q: Tell difference of a scaled app on Mesos I am running server apps inside Docker on Mesos, some apps are scaled to multiple instances. When I am collecting data inside the app, I want the app to be able to store some type of identifiers so later on when I read data, I know which app it is collected from. For example, I scaled an app to 3 instances on mesos, and from the data, I want to read that the data is from either app_1, app_2 or app_3. I thought of using host IP, but those scaled apps are sometimes spawned inside the same node. I cannot use something like pid because it will change when the app restarts.
Thus I tried to read if there are environment variables that can help me distinguish between them, but they are all the same across the platform except HOSTNAME, so I wonder if anyone has other ideas. Thank you very much.

A: You can use the MESOS_TASK_ID task-level environment variable for this, see the Marathon docs for more details. Also, note that a Marathon application instance corresponds to a Mesos task.


text:
Q: MatplotlabL : put 6 plots in one figure I have a data_frame, with columns: my_time, field_A, field_B, field_C, field_D, field_E and field_F
I am using the following code to plot field_A vs. my_time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib

plt.plot(my_df[['my_time']], my_df[['field_A']])
plt.show()

my_time is of datetime unit. I then did the same thing for field_B, field_C, field_D, field_E, field_F and totally got 6 figures.
Is it possible to put all 6 figures as 6 subplots (2x3) of one figure? Thanks!

A: This should be pretty simple. Set my_time to be the index and call plot:
c = ['field_A', 'field_B', ...]
my_df.set_index('my_time')[c].plot(subplots=True)
plt.show()

If you want to plot my_time against all other columns, this should do:
my_df.set_index('my_time').plot(subplots=True)


text:
Q: ksqlDB driver support? Wondering if it's reasonably possible to support ksqlDB, and if so, what the level of effort might be.
I'd be willing to look into this further, and probably implement, but it's pretty new and it has largely sql-compliant syntax, with what looks like some extra bits that might not be easy (and maybe impossible) to implement with an ORM.
I notice that there's not really any ORMs out there for ksqlDB right now, and it's not immediately obvious if that's because ksqlDB is fairly new, or if it would be basically impossible to implement with most ORMs.

A: I see no reason why it can't be supported. At the very least the core functionality of ORM's could be implemented for their basic queries being done in the background on materialized views in ksqlDB. On top of that, I can see special methods added that are specific to ksqlDBs new feature set.
It's possible that Confluent is already working on it as Kafka as a whole matures.


text:
Q: Missing Https Headers For Pusher ChatKit Api i'm trying to get ChatKit to FlutterSDK, but i'm facing a little tiny problem ,,
i'm sending request to ChatKit End Point ,, but i think i'm missing headers so i never get authed ,, (reponse Code 401)
so what i should use as header?
i was trying to connect via Dart Http Package
   static String _apiEndPoint =
     "https://us1.pusherplatform.io/services/chatkit/v2/:instance_id";
   static final String _usersEndPoint = "/users";

   var uri = Uri.parse("$_apiEndPoint$_usersEndPoint");
   var request = new http.MultipartRequest("POST", uri);
   request.fields['name'] = '$name';
   request.fields['id'] = '$username';
   request.fields['avatar_url'] = '$avatarUrl';
   request.fields['custom_data'] = '{"email": "$email"}';
   request.send().then((response) {
     print(response.statusCode);
   });

i thought that's enough to create user account by following docs here:
https://docs.pusher.com/chatkit/reference/api#create-a-user

A: You need to add a header (use request.headers['authorization'] = 'Bearer $token';) and calculate the bearer token as described here.


text:
Q: PGPool II - Failover when current master node dies I have a 2 node high-availability postgresql 9.5 cluster. I'm using streaming replication, PGPool II (3.5.4 [ekieboshi]), and a virtual (or floating) secondary IP all hosted on aws to accomplish this.
I've configured the PGPool Watchdog and it is running well but only seems to be executing a failover script on the failed node when the postgresql service instance dies.
I'd like to be able to execute a failover script on the slave node when the master becomes unreachable. Is there any hook for this in PGPool II? If not, is this not really even a good idea? Thanks in advance for your help.

A: Sounds like you might have incorrect values for your failover_command value. And Typically the failover script is run on pgpool server, not the database node.
failover_command = '/etc/pgpool-II/failover.sh %d %H %P /tmp/postgresql.trigger.failover [hostname of failover pgpool server]'

This configuration above is passing the new master candidate and an argument to my failover script which is executed on pgpool but ultimately promotes the master candidate (which is a hot standby) to a master using postgresql.

A: The hook you need is failover_command.
All the scripts defined in PgPool's configuration - failover_command, follow_master_command, failback_command, etc - are executed by the pgpool master process. You can check which one is master using pcp_watchdog_info utility.
It means that if you want to execute commands on PostgreSQL node you need to setup password-less auth from pgpool into postgres nodes and use ssh inside the script. To give an example, in my failover.sh I have this:
#!/bin/bash
node=$1
host=$2
port=$3
pgdata=$4
newmasternode=$5
newmasterhost=$6
oldmasternode=$7
oldprimarynode=$8
newmasterport=$9
newmasterpgdata=${10}

echo "$0 params: node=$node host=$host port=$port pgdata=$pgdata newmasternode=$newmasternode newmasterhost=$newmasterhost oldmasternode=$oldmasternode oldprimarynode=$oldprimarynode newmasterport=$newmasterport newmasterpgdata=$newmasterpgdata"

ssh_opts="-o BatchMode=yes -o StrictHostKeyChecking=no -o CheckHostIP=no -o ConnectTimeout=10"

echo "$0 Disabling postgresql on $host"
ssh $ssh_opts -l root $host 'systemctl mask postgresql --now'

if [ $newmasternode -ne $oldmasternode ]; then
    echo "$0 Promoting postgresql on $newmasterhost"
    ssh $ssh_opts -l root $newmasterhost 'pg_ctlcluster 10 main promote'
fi


text:
Q: Is it possible .FLV to .MP4 conversion on client side by ffmpeg-asm.js? Is it possible to do .FLV to .MP4 conversion on client side by ffmpeg-asm.js?
The main issue lot's of mobile video players didn't support flash, but .FLV still popular at the internet ;(
Have no idea how to avoid server-side conversion and storing...

A: Yes, it is possible to convert in browser to an MSE compatible format. But I would still recommend a server side conversion. Its is extreme cheap to switch containers from flv to mp4.


text:
Q: Change the behavior of a mod_watch state function I'm using the supervisord state to manage my web app instances.
When a config file changes, I want to reload the supervisor config and restart affected instances. I currently do this using the watch prerequisite in a supervisord.running state, but the default supervisord.mod_watch state function only restarts my instances without reloading the config.
The docs say supervisord.mod_watch has a reload option, which is False by default. If I could somehow set it to True my problem would be solved. Does anyone know how to do this?
Btw: I already tried to use the onchanges prerequisite and just set reload: True when using supervisord.running, but somehow that prereq never gets triggered.


text:
Q: Setup Jenkins running on Linux to execute PowerShell script How do you setup Jenkins running on Linux to execute a PowerShell script on a remote Windows Server 2008 without password prompt.
Master Jenkins on Linux / Slave on Windows. Would this work?

A: Install an SSH server on the Windows server and use a public/private key pair for authentication. On Linux, you can then run
ssh -i <private key file> user@host "command"

to issue "command" on the server.

A: EDIT
A complete edit, since I couldn't get the previous answer working.

*

*Install Powershell for Linux: Powershell on Github;

*Write a powershell script:

$username = "username"
$secpass = ConvertTo-SecureString "password" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($username,$secpass)
$remotepath = "c:\path\to\your.ps1"

Invoke-Command -ComputerName windowscomputer -Credential $mycreds -FilePath $remotepath

*

*Now use Jenkins to execute a shell:

powershell -NonInteractive -ExecutionPolicy ByPass /path/to/your/local.ps1
This is how I got it working eventually.


text:
Q: Django Ajax and Looping over Response I currently have the following template,
{% extends "123/123-base.html" %}
{% block main %}

        <form method="post" name="inputlookup" action="/lookup_ajax">
        {% csrf_token %}
            <input class="span2" id="hostinput" name="hostinput" type="text">
            <select title="Record" id="recordinput" name="recordinput" >
                <option value="A">A</option>
                <option value="MX">MX</option>
                <option value="Cname">Cname</option>
            </select>
            <button id="button" class="btn" type="submit">Lookup</button>
        </form>

{% endblock %}

However the response I receieve back from the server I want to loop over using the Django template tags, like this,
{% extends "123/123-base.html" %}
{% block main %}
        {% if error %}
            {{ error }}
        {% else %}

                HOSTNAME
                TTL
                CLASS
                TYPE
                DETAILS

            {% for answer in response %}

                {% for field in answer %}
                    {{ field }}
                {% endfor %}

            {% endfor %}

        {% endif %}
{% endblock %}

Any ideas on how this should be done ?
Thanks,

A: It looks to me like you're returning a JSON object for your AJAX call. If that's correct then django doesn't come into it for displaying the result. You'd need to change your success function to something like the following:
success: function(json){
    // Table header
    var table = $('
').addClass('table table-style table-striped');
    var thead = $('
');
    var headrow = $('
');
    var head1 = $('').text('HOSTNAME');
    var head2 = $('').text('TTL');
    var head3 = $('').text('CLASS');
    var head4 = $('').text('TYPE');
    var head5 = $('').text('DETAILS');
    $(headrow).append(head1, head2, head3, head4, head5);
    $(thead).append(headrow);
    $(table).append(thead);

    // table body
    var tbody = $('
');
    num_answers = json.length
    for (i = 0; i < num_answers; i++) {
        var row = $('
');
        var cell1 = $('').text(json[i][0]);
        var cell2 = $('').text(json[i][1]);
        var cell3 = $('').text(json[i][2]);
        var cell4 = $('').text(json[i][3]);
        var cell5 = $('').text(json[i][4]);
        $(row).append(cell1, cell2, cell3, cell4, cell5);
        $(tbody).append(row);
    }
    $(table).append(row);
    $('#mainsection').append(table);
}


text:
Q: WebView Cookies Как я могу реализовать, чтобы сохранялся Cookies сайта?
A: Было уже много раз. Вот например на SO: WebView and Cookies on Android.
Если в двух словах, то проблема в том, что при каждой загрузке браузер запускает новую сессию. Если же вы хотите, чтобы куки сохранялись и после закрытия приложения, то куки надо сохранять с помощью CookieSyncManager и CookieManager. Обо всём этом есть на SO по ссылке выше.


text:
Q: AWS layer errors out with "Runtime.ImportModuleError - Error: Cannot find module 'tslib'" I will try to be as clear as possible when I ask about this problem.
Context: I have a lambda function and a layer. The layer is a means of sending emails using the AWS SES. The lambda is merely a function that calls this layer to use the AWS SES to send emails. The layer utilizes the "aws-sdk/client-ses" package to serve its purpose.
My problem: whenever I try to invoke my lambda when its calling my layer, I get the following failure on the layer's part:
{
    "errorType": "Runtime.ImportModuleError",
    "errorMessage": "Error: Cannot find module 'tslib'\nRequire stack:\n- /opt/node_modules/@aws-sdk/client-ses/dist-cjs/index.js\n- /opt/sendTemplatedEmail.js\n- /var/task/src/lambdas/sendTAPEmailHandler.js\n- /var/runtime/index.mjs",
    "stack": [
        "Runtime.ImportModuleError: Error: Cannot find module 'tslib'",
        "Require stack:",
        "- /opt/node_modules/@aws-sdk/client-ses/dist-cjs/index.js",
        "- /opt/sendTemplatedEmail.js",
        "- /var/task/src/lambdas/sendTAPEmailHandler.js",
        "- /var/runtime/index.mjs",
        "    at _loadUserApp (file:///var/runtime/index.mjs:1000:17)",
        "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1035:21)",
        "    at async start (file:///var/runtime/index.mjs:1200:23)",
        "    at async file:///var/runtime/index.mjs:1206:1"
    ]
}

However, if I take the code in the layer and define it in the lambda and use the same "aws-sdk/client-ses" package, all works just fine with no problems.
I have already concluded that the problem is the "aws-sdk/client-ses" package itself, evident by:

*

*The package of "tslib" is a dependency of the "aws-sdk/client-ses" package.

*This error only ever appears with the aws-sdk package or its sub packages. I already tried with a different package like "date-fns" and it worked like a charm.

I have already researched on this problem but nothing I found was helpful or had any definite answers.
Here's my layer's code:
const { SESClient, SendBulkTemplatedEmailCommand } = require("@aws-sdk/client-ses");

const config = {
  credentials: {
    accessKeyId: process.env.SLS_AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.SLS_AWS_SECRET_ACCESS_KEY
  },
  region: process.env.SLS_AWS_EMAIL_REGION
};

const sesClient = new SESClient(config);

const params = ({ source, destinations, templateName }) => ({
  Source: source,
  Template: templateName,
  Destinations: destinations,
  DefaultTemplateData: JSON.stringify({
    name: "Maria",
    orderNumber: "123456"
    // TODO: Replace with any default variables you want to pass to the template
  }),
});

const command = (emailParams) => new SendBulkTemplatedEmailCommand(params(emailParams));

const sendTemplatedEmail = async (emailParams) => {
  try {
    const data = await sesClient.send(command(emailParams));
    return data
  } catch (error) {
    // TODO: Log error;
    return error;
  }
};

module.exports = sendTemplatedEmail

Here's my layer's package.json file:
{
  "name": "sendTemplatedEmail",
  "version": "1.0.0",
  "main": "sendTemplatedEmail.js",
  "license": "MIT",
  "dependencies": {
    "@aws-sdk/client-ses": "^3.272.0"
  }
}

Here's my serverless.yml file
service: service_name

frameworkVersion: "3"

provider:
  name: aws
  runtime: nodejs18.x
  profile: serverless_service_name
  stage: dev_stage_here
  region: region_value_here
  environment:
    SLS_AWS_REGION: ${env:SLS_AWS_REGION, "SLS_AWS_REGION_VALUE_HERE"}
    SLS_AWS_ACCESS_KEY_ID: ${env:SLS_AWS_ACCESS_KEY_ID, "SLS_AWS_ACCESS_KEY_ID_VALUE_HERE"}
    SLS_AWS_SECRET_ACCESS_KEY: ${env:SLS_AWS_SECRET_ACCESS_KEY, "SLS_AWS_SECRET_ACCESS_KEY_VALUE_HERE"}
    SLS_AWS_EMAIL_REGION: ${env:SLS_AWS_EMAIL_REGION, "SLS_AWS_EMAIL_REGION_VALUE_HERE"}

layers:
  SendTemplatedEmail:
    path: src/layers/sendTemplatedEmail
    name: SendTemplatedEmail
    description: Send templated email
    compatibleRuntimes:
      - nodejs18.x

package:
  patterns:
    - "!layerSourceTarball.tar.gz"
  exclude:
    - .gitignore
    - README.md
    - serverless.yml
    - src/layers/**
    - src/emailTemplates/**
    - .serverless
    - .prettierrc.json
    - .prettierignore
  excludeDevDependencies: true
  individually: true

plugins:
  - serverless-offline

functions: ${file(./sls/functions.yml):functions}

custom:
  serverless-offline:
    port: 5000
    httpPort: 5000
    websocketPort: 5001
    lambdaPort: 5002

My machine's current node version is: v16.19.0
Can you please help me figure out the problem? If there's any more additional information that I must provide please let me know and I'll update this post accordingly.
I defined a layer to send emails by utilizing the aws-sdk/client-ses package. The layer should have worked when I called it from my lambda function but it doesn't.
Things I've tried so far:

*

*Played around with the node version.

*Played around with the aws-sdk/client-ses version.

*I researched the internet for possible answers and found none that were helpful.

*Install the "tslib" library manually in the layer's folder.


text:
Q: 2 ELBs (ALBs) to 1 target group, possible? I have the following scheme:

Internet <-> elb1external <-> varnish <-> elb2internal <-> targetgroupofwebnodes

But some /static/* & /media/* are routed to targetgroupofwebnodes from elb1external directly, around varnish & second ELB, so I need both elb1 & elb2 to point to the same target group of web nodes.
The Amazon web console shows the group as grayed out, when I try to select it from the drop down on the second ELB, but I do see mentioning of that scheme being possible on the web.
As a workaround I've created targetgroupofwebnodes2 with the same servers in it, but I'm required to have only 1 & the next task is autoscaling, so there's going to be an autoscaling group instead of target group.
Must I use the CLI for that or there's a way through the web console?

A: I'm not sure if you can point two ALBs to a single TargetGroup. However since you mentioned AutoScaling you can have the ASG instances automatically registered in more than one TargetGroups, therefore your approach with two target groups will work just as well with AutoScaling.
Hope that helps.
UPDATE #1
The OP was able to find this link to AWS docs on limits titled: Limits for Your Application Load Balancers. In this docs on limits the number of target groups per ALB is mentioned in this table:

Target Group Limits

*

*Load balancers per target group: 1

*Targets per target group (instances or IP addresses): 1000

*Targets per target group (Lambda functions): 1

Based on this info, you cannot have the same target group in more than one ALB.


text:
Q: Why does my jsfiddle work but not my web site? I'm not sure what im missing here
I have the following JS fiddle:
http://jsfiddle.net/thetylercox/eeMva/3/
And the site:
http://soldbybillcox.com/treasure/demo1.html
I'm not sure what I am missing but my website does not work.

A: On the line 68 you have illegial symbols right after a closing bracket }.

Remove it and the code should work.

A: Just before your closing </script> tag, you've got an illegal character.
Try right-clicking and 'view-source' in Chrome. You'll see it. Line #68.

A:  from copying and pasting from fiddle

A: Open up your console, it says: Uncaught SyntaxError: Unexpected token ILLEGAL, demo.php:68
    ...
    var total1 = document.getElementById("total1").value = total;

}

These might be caused by a BOM if you're using different files/includes to generate the output. Otherwise, it might just be some copy/paste error. Just remove the }</script> to make sure the 'invisible' chars are gone between } and < and then type }</script> again and be done with it.

A: Seems to work just fine, except you have a random trio of symbols at the end of your <script>, so remove those and it should be just fine.


text:
Q: Error in matcaffe installation
The above error showed up when I tried to install matcaffe in ubuntu. I switched to caffe root directory, and ran the following commands:
$ cd /home/naved/Desktop/caffe-master
$ make all matcaffe
$ make mattest

My matlab version is 2011a.
After running make mattest, the error above showed up.
What should I do to solve this problem?

A: I believe that the functionality for custom unit test caffe(and specifically the package matlab.unittest.TestCase) was introduced in version R2015a of MATLAB, and that if you're on an older version it won't be available


text:
Q: How to run ASP.Net Web Site outside of visual studio 2010?? no exe file? I have created an ASP.Net web site with VB script and SQL Database, through Visual Studio 2010. I now need to be able to run my website on the browser without using the ctrl+F5 shortcut that can be used in Visual Studio. I dont want to use the IIS approach is there and alternative?
Why is there no exe file in my bin folder? Can I create one? Also whats with the dll files?

A: You seem to be fundamentally misunderstanding what a web application is.  It's not a standalone executable, that's a desktop application.  A web application, by definition, requires a web server.  Most commonly for ASP.NET applications, IIS.
Visual Studio provides a built-in web server to use for debugging.  Outside of Visual Studio, you deploy the web application to an IIS instance and can then access the application by pointing your browser to that IIS instance.
It can be on the same physical machine as the browser, there's no restriction that a "web server" needs to be a physically separate "server" machine.  But you do need a "web server" running somewhere to deploy the application to it.
To sum up:

I now need to be able to run my website on the browser

The browser doesn't "run" the application.  The browser connects to the web server, which hosts the application.

I dont want to use the IIS approach is there and alternative?

There are other web servers you can use besides IIS (such as Apache with mod_mono perhaps), though I imagine IIS is going to be the simplest and most straightforward in this case.

Why is there no exe file in my bin folder?

Because you created a web application, not a desktop application.

Can I create one?

No.  At least not in the way you think.

Also whats with the dll files?

Those are where compiled code is kept.  A web server would use them to invoke functionality in your application.  Indeed, a desktop application would also use them to invoke that same functionality.

A:
I dont want to use the IIS approach is there and alternative?

Yes, you can use Owin and Katan. It creates an executable file.
By and large, you run the exe file on server. Then client browser accesses the application.
Note: If you are new to ASP.net, it is not what you want.


text:
Q: Proving that $S=\bigcup_{j=0}^{2^k-1} S_{n-1+k}$ is a spanning set for the $2$-D Baker map A set $S \subset X$ is a $(n,\epsilon)$-spanning set if $\forall x \in X$, $\exists y \in S $ such that $d_n(x,y)<\epsilon$. This is where we define $d_n(x,y)$ by $d_n(x,y)=\max_{0\leq k < n}d(f^k(x),f^k(y)$ for some topological dynamical system $f:X \rightarrow X$.
Let $X=[0,1]^2$ and let us take $f=F$ to be the two dimensional baker map defined by:
$F(x,y =
\left\{
 \begin{array}{ll}
  (2x,\frac{y}{2})  & \mbox{if } 0 \leq  x < \frac{1}{2} \\
  (2x-1,\frac{y+1}{2}) & \mbox{if } \frac{1}{2} \leq x < 1
 \end{array}
\right.$
Let $\epsilon = 1/2^k$. Let $S_{n}(y)=\{(\frac{i}{2^{n}},y) : 0 \leq i \leq 2^n-1 \}$. Then consider the set of points
$S = \bigcup_{j=0}^{2^k-1} S_{n-1+k}(\frac{j}{2^k})$
and show that it is an $(n,\epsilon)$-spanning set for the baker map $F$.
If we let $x \in X$ I then get that $x$ lies in some square $\displaystyle [\frac{i}{2^{n-1+k}},\frac{i+1}{2^{n-1+k}}] \times [\frac{j}{2^k},\frac{j+1}{2^k}]$ for some $i,j \in S$. However I cannot see a way such that $d_n(F(x),F(y) < \epsilon=\frac{1}{2^k}$ for some $y \in S$.
Applying $F$ to the $x$ coordinate I get that $F^{n-1}(x,y)=(2^{n-1}x,\frac{1}{2^{n-1}}y)$, which seems to get back to where we started and doesnt provide much help to solving the question.
I am now stuck on where to go now.

A: First try to understand what $F$ does to each one of those squares: $\left[\frac{i}{2^{n}},\frac{i+1}{2^n}\right]\times\left[\frac{j}{2^n},\frac{j+1}{2^n}\right]$ (visualize $F$ on the entire square as in the notes to understand its action - squeezing in one direction but stretching in the other).
Now what happens if you iterate $F$ (up to $n$ times)? How does this turn out for the $n$-step Bowen metric then? Which points are already "covered" by a single square in the first $n$ steps?
Finally think about how many (which) of those squares (better rectangles) you would need to $(n,\varepsilon)$-span the entire phase space $[0,1]^2$. This is where you want to change the initial shape from being a square $\left[\frac{i}{2^{n}},\frac{i+1}{2^n}\right]\times\left[\frac{j}{2^n},\frac{j+1}{2^n}\right]$ to a rectangle $\left[\frac{i}{2^{n-1+k}},\frac{i+1}{2^{n-1+k}}\right]\times\left[\frac{j}{2^k},\frac{j+1}{2^k}\right]$. Picking a single point from each one of those rectangles is gives you the $(n,\varepsilon$-spanning set $S$.


text:
Q: Cassandra ExecutionResult on importlib._bootstrap failed I am trying to execute multi-process to pull the data from Cassandra. But, I'm facing the issue.I want to pull it for single key or multiple keys using the multi-process provided my Cassandra
My cassandra_db class
from cassandra.cluster import Cluster
import cassandra
import pandas as pd
import numpy as np
from datetime import datetime
import sys
import os
from threading import Event
import itertools
from multiprocessing import Pool
from cassandra.concurrent import execute_concurrent_with_args
from cassandra.query import tuple_factory
ip_address = '127.0.0.1'

class cassandra_db(object):

    concurrency = 2 # chosen to match the default in execute_concurrent_with_args

    def __init__(self,process_count=None):
        self.pool = Pool(processes=process_count, initializer=self._setup)

    @classmethod
    def _setup(cls):
        cls.session = Cluster([ip_address]).connect(keyspace='test')
        cls.session.row_factory = pandas_factory
        cls.prepared = cls.session.prepare('SELECT * FROM tr_test WHERE key=?')

    def close_pool(self):
        self.pool.close()
        self.pool.join()

    def get_results(self, params):
        try:
             xrange
        except NameError:
              xrange = range
        params = list(params)
        print("-----> ",params)
        print("-----+>",self.concurrency)
        self.pool.map(_multiprocess_get, (params[n:n + self.concurrency] for n in xrange(0, len(params), self.concurrency)))

    @classmethod
    def _results_from_concurrent(cls, params):
        return execute_concurrent_with_args(cls.session, cls.prepared, params)

def _multiprocess_get(params):
    return cassandra_db._results_from_concurrent(params)

My calling class
    import os
import pandas as pd
import sys
relative_path='/home/anji'
sys.path.append(os.path.join(relative_path ,'commons','Database Operations'))
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
from cassandra_db import cassandra_db
from cassandra.policies import ConstantReconnectionPolicy
processes =2
con_db = cassandra_db(processes)
keys=[(1,),(2,)]
df = con_db.get_results(keys)
print("Result",df.head())

Error:
multiprocessing.pool.MaybeEncodingError: Error sending result: '[[ExecutionResult(success=True, result_or_exc=<cassandra.cluster.ResultSet object at 0x7fa93658bbe0>), ExecutionResult(success=True, result_or_exc=<cassandra.cluster.ResultSet object at 0x7fa936a2e0f0>)]]'. Reason: 'PicklingError("Can't pickle <class 'importlib._bootstrap.ExecutionResult'>: attribute lookup ExecutionResult on importlib._bootstrap failed",)'

My trying to execute for 2 keys but facing the issue. Can any help me to solve this issue


text:
Q: How do I call a function whose declaration is unknown at compiletime this is bascially the problem.
void call_function(void* func, const char* funcdecl, void* arguments) {

  // how do I do this?

  // some pseudo code
  for(i = 0; i < numargs; ++i) {
    if(funcdecl.args[i].type == TYPE_DOUBLE) {
      push funcdecl.args[i].doubleValue
    }
    ...
  }
  call func
  reslut.type = funcdecl.result_type;
  if(funcdecl.result_type == TYPE) {
    result.value = read_doulbe_from_stack();
  }
}

// nothing from here on is known before call_function.

double foobar(int a, int b, int c) {
  return a * 0.1 + b * 0.3 + c * 0.2;
}

typedef struct MyArgumentsStruct {
  int a;
  int b;
  int c;
} MyArgumentsStruct;

int main() {
  MyArgumentsStruct arguments;
  call_function( (void*)(foobar), "double foobar(int a, int b, int c);", &arguments);
}

so basically I cant cast the void* to a function type, because I don't know it.
I have looked up what gcc does when compiling to asm. And when I understand it correctly, it generates a lot of push instructions to push all function arguments on the stack, and then it uses call to go to a function. The function then knows how to get the arguments from the stack and pushes the result back.
So my question is, how do I push arguments from manually to the stack?
How would I read the return value from the stack?

A: If you are only looking to solve the problem, then pick a library like libffi (see the question linked by @SteveSummit).
If you want to learn how it is done, you will need to have a grasp on assembly. Start by simplifying the problem by picking a single architecture, single calling convention, no arguments, leave the parsing of the C function declaration for later, etc. As soon as you manage to make the simplest function call successfully, you can proceed to study the rest of details -- there are many!


text:
Q: Difference between text and varchar (character varying) What's the difference between the text data type and the character varying (varchar) data types?
According to the documentation

If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.

and

In addition, PostgreSQL provides the text type, which stores strings of any length. Although the type text is not in the SQL standard, several other SQL database management systems have it as well.

So what's the difference?

A: Somewhat OT: If you're using Rails, the standard formatting of webpages may be different. For data entry forms text boxes are scrollable, but character varying (Rails string) boxes are one-line. Show views are as long as needed.

A: A good explanation from http://www.sqlines.com/postgresql/datatypes/text:

The only difference between TEXT and VARCHAR(n) is that you can limit
  the maximum length of a VARCHAR column, for example, VARCHAR(255) does
  not allow inserting a string more than 255 characters long.
Both TEXT and VARCHAR have the upper limit at 1 Gb, and there is no
  performance difference among them (according to the PostgreSQL
  documentation).

A: On PostgreSQL manual

There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead.

I usually use text
References: http://www.postgresql.org/docs/current/static/datatype-character.html

A: The difference is between tradition and modern.
Traditionally you were required to specify the width of each table column. If you specify too much width, expensive storage space is wasted, but if you specify too little width, some data will not fit. Then you would resize the column, and had to change a lot of connected software, fix introduced bugs, which is all very cumbersome.
Modern systems allow for unlimited string storage with dynamic storage allocation, so the incidental large string would be stored just fine without much waste of storage of small data items.
While a lot of programming languages have adopted a data type of 'string' with unlimited size, like C#, javascript, java, etc, a database like Oracle did not.
Now that PostgreSQL supports 'text', a lot of programmers are still used to VARCHAR(N), and reason like: yes, text is the same as VARCHAR, except that with VARCHAR you MAY add a limit N, so VARCHAR is more flexible.
You might as well reason, why should we bother using VARCHAR without N, now that we can simplify our life with TEXT?
In my recent years with Oracle, I have used CHAR(N) or VARCHAR(N) on very few occasions. Because Oracle does (did?) not have an unlimited string type, I used for most string columns VARCHAR(2000), where 2000 was at some time the maximum for VARCHAR, and in all practical purposes not much different from 'infinite'.
Now that I am working with PostgreSQL, I see TEXT as real progress. No more emphasis on the VAR feature of the CHAR type. No more emphasis on let's use VARCHAR without N. Besides, typing TEXT saves 3 keystrokes compared to VARCHAR.
Younger colleagues would now grow up without even knowing that in the old days there were no unlimited strings. Just like that in most projects they don't have to know about assembly programming.

A: In my opinion, varchar(n) has it's own advantages. Yes, they all use the same underlying type and all that. But, it should be pointed out that indexes in PostgreSQL has its size limit of 2712 bytes per row.
TL;DR:
If you use text type without a constraint and have indexes on these columns, it is very possible that you hit this limit for some of your columns and get error when you try to insert data but with using varchar(n), you can prevent it.
Some more details: The problem here is that PostgreSQL doesn't give any exceptions when creating indexes for text type or varchar(n) where n is greater than 2712. However, it will give error when a record with compressed size of greater than 2712 is tried to be inserted. It means that you can insert 100.000 character of string which is composed by repetitive characters easily because it will be compressed far below 2712 but you may not be able to insert some string with 4000 characters because the compressed size is greater than 2712 bytes. Using varchar(n) where n is not too much greater than 2712, you're safe from these errors.

A: text and varchar have different implicit type conversions. The biggest impact that I've noticed is handling of trailing spaces. For example ...
select ' '::char = ' '::varchar, ' '::char = ' '::text, ' '::varchar = ' '::text

returns true, false, true and not true, true, true as you might expect.

A: As "Character Types" in the documentation points out, varchar(n), char(n), and text are all stored the same way. The only difference is extra cycles are needed to check the length, if one is given, and the extra space and time required if padding is needed for char(n).
However, when you only need to store a single character, there is a slight performance advantage to using the special type "char" (keep the double-quotes — they're part of the type name). You get faster access to the field, and there is no overhead to store the length.
I just made a table of 1,000,000 random "char" chosen from the lower-case alphabet. A query to get a frequency distribution (select count(*), field ... group by field) takes about 650 milliseconds, vs about 760 on the same data using a text field.

A: There is no difference, under the hood it's all varlena (variable length array).
Check this article from Depesz: http://www.depesz.com/index.php/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/
A couple of highlights:

To sum it all up:

*

*char(n) – takes too much space when dealing with values shorter than n (pads them to n), and can lead to subtle errors because of adding trailing
  spaces, plus it is problematic to change the limit

*varchar(n) – it's problematic to change the limit in live environment (requires exclusive lock while altering table)

*varchar – just like text

*text – for me a winner – over (n) data types because it lacks their problems, and over varchar – because it has distinct name

The article does detailed testing to show that the performance of inserts and selects for all 4 data types are similar. It also takes a detailed look at alternate ways on constraining the length when needed. Function based constraints or domains provide the advantage of instant increase of the length constraint, and on the basis that decreasing a string length constraint is rare, depesz concludes that one of them is usually the best choice for a length limit.

A: (this answer is a Wiki, you can edit - please correct and improve!)
UPDATING BENCHMARKS FOR 2016 (pg9.5+)
And using "pure SQL" benchmarks (without any external script)

*

*use any string_generator with UTF8

*main benchmarks:
2.1. INSERT
2.2. SELECT comparing and counting

CREATE FUNCTION string_generator(int DEFAULT 20,int DEFAULT 10) RETURNS text AS $f$
  SELECT array_to_string( array_agg(
    substring(md5(random()::text),1,$1)||chr( 9824 + (random()*10)::int )
  ), ' ' ) as s
  FROM generate_series(1, $2) i(x);
$f$ LANGUAGE SQL IMMUTABLE;

Prepare specific test (examples)
DROP TABLE IF EXISTS test;
-- CREATE TABLE test ( f varchar(500));
-- CREATE TABLE test ( f text);
CREATE TABLE test ( f text  CHECK(char_length(f)<=500) );

Perform a basic test:
INSERT INTO test
   SELECT string_generator(20+(random()*(i%11))::int)
   FROM generate_series(1, 99000) t(i);

And other tests,
CREATE INDEX q on test (f);

SELECT count(*) FROM (
  SELECT substring(f,1,1) || f FROM test WHERE f<'a0' ORDER BY 1 LIMIT 80000
) t;

... And use EXPLAIN ANALYZE.
UPDATED AGAIN 2018 (pg10)
little edit to add 2018's results and reinforce recommendations.

Results in 2016 and 2018
My results, after average, in many machines and many tests: all the same (statistically less than standard deviation).
Recommendation

*

*Use text datatype, avoid old varchar(x) because sometimes it is not a standard, e.g. in  CREATE FUNCTION clauses   varchar(x)≠varchar(y).

*express limits (with same varchar performance!) by with CHECK clause in the CREATE TABLE e.g. CHECK(char_length(x)<=10). With a negligible loss of performance in INSERT/UPDATE you can also to control ranges and string structure  e.g. CHECK(char_length(x)>5 AND char_length(x)<=20 AND x LIKE 'Hello%')

A: I wasted way too much time because of using varchar instead of text for PostgreSQL arrays.
PostgreSQL Array operators do not work with string columns. Refer these links for more details: (https://github.com/rails/rails/issues/13127) and (http://adamsanderson.github.io/railsconf_2013/?full#10).

A: If you only use TEXT type you can run into issues when using AWS Database Migration Service:

Large objects (LOBs) are used but target LOB columns are not nullable

Due to their unknown and sometimes large size, large objects (LOBs) require more processing
and resources than standard objects. To help with tuning migrations of systems that contain
LOBs, AWS DMS offers the following options

If you are only sticking to PostgreSQL for everything probably you're fine. But if you are going to interact with your db via ODBC or external tools like DMS you should consider using not using TEXT for everything.

A: character varying(n), varchar(n) - (Both the same). value will be truncated to n characters without raising an error.

character(n), char(n) - (Both the same). fixed-length and will pad with blanks till the end of the length.

text - Unlimited length.

Example:
Table test:
   a character(7)
   b varchar(7)

insert "ok    " to a
insert "ok    " to b

We get the results:
a        | (a)char_length | b     | (b)char_length
----------+----------------+-------+----------------
"ok     "| 7              | "ok"  | 2


text:
Q: Choosing redis maxmemory size and BGSAVE memory usage I am trying to find out what a safe setting for 'maxmemory' would be in the following situation:

*

*write-heavy application

*8GB RAM

*let's assume other processes take up about 1GB

*this means that the redis process' memory usage may never exceed 7GB

*memory usage doubles on every BGSAVE event, because:

In the redis docs the following is said about the memory usage increasing on BGSAVE events:

If you are using Redis in a very write-heavy application, while saving an RDB file on disk or rewriting the AOF log Redis may use up to 2 times the memory normally used.

*

*the maxmemory limit is roughly compared to 'used_memory' from redis-cli INFO (as is explained here) and does not take other memory used by redis into account

Am I correct that this means that the maxmemory setting should, in this situation, be set no higher than (8GB - 1GB) / 2 = 3.5GB?
If so, I will create a pull request for the redis docs to reflect this more clearly.

A: I would recommend in this case a limit of 3GB. Yes, the docs are pretty much correct and running a bgsave will double for a short term the memory requirements. However, I prefer to reserve 2GB of memory for the system, or at a maximum for a persisting master 40% of maximum memory.
You indicate you have a very write heavy application. In this case I would highly recommend a second server do the save operations. I've found during high writes and a bgsave the response time to the client(s) can get high. It isn't Redis per se causing it, but the response of the server itself. This is especially true for virtual machines. Under this setup you would use the second server to slave from the primary and save to disk while the first remains responsive.


text:
Q: help with wp_localize_script I am a little confused on this function.
I have it working for one javascript variable. I tried to get it working for two others and it found that it repeats the code in the header 3 times. I tried using an array for the handle but that just broke the code
 <?php wp_localize_script( $handle, $name, $data ); ?>

 function localize_my_script() {
$image_url = get_template_directory_uri() . '/images/supersized/';
$src = get_template_directory_uri() . '/images/preload.gif';
$swfLocation = get_template_directory_uri() . '/js/audiojs.swf';

$localizations = array( 'image_path' => $image_url, 'src' => $src, 'swfLocation' => $swfLocation );

wp_localize_script( 'shutter', 'scriptvars', $localizations );
//wp_localize_script( 'preloader', 'script', $localizations );
//wp_localize_script( 'audio', 'scriptv', $localizations );
 }
 add_action( 'wp_enqueue_scripts', 'localize_my_script' );

with the two lines commented out above, the script only prints one line of code in the header for all three variables. But if I uncomment the 2, then it prints them three times. It includes all three variables in that one line of code. So how to I get the handles in there so it doesn't make 2 more lines of code?

A: That's how the wp_localize_script function works. It prints all the variables before your script is included to make sure that the variables are available to the script. If you want to print the localized variables only one time, but make sure that they are accessible for all three scripts - you can do that by setting dependencies when enqueueing/registering your scripts. So, register the 'audio' and 'preloader' scripts with dependency set to 'shutter' (WordPress will then make sure that 'shutter' is included before 'preloader' and 'audio'), and then localize only the 'shutter' script.


text:
Q: Update specific value of one file by values in another text file I have a text files in ascii format and wanted to replace a specific value by value saved in another text file.
consider a file of name text_1. . . . 50.asc 5 columns, 4 rows
sample data in a file
 0.40007 0.544 0.6795 0.1545 -3.4028
 0.61488 0.8471 0.7444 0.3537 0.0709
 0.65128 0.6651 0.7948 0.9200 0.893
 0.70952 0.5990 0.5061 0.610 0.893

And I wanted to replace (5th column, 1st row) of each file by value same in Replacing_values.txt.
It have data
1
2
3
4
.
.
.
50

Expected result (continued to all files)
 0.40007 0.544 0.6795 0.1545  1
 0.61488 0.8471 0.7444 0.3537 0.0709
 0.65128 0.6651 0.7948 0.9200 0.893
 0.70952 0.5990 0.5061 0.610 0.893

I have tried this
for i in `seq 50`; do x=`awk 'FNR==(1) {print $5}' *.asc`; y=`cat Replacing_values.txt`; echo $x==$y ;done

A: With flexible GNU awk features:
gawk -i inplace -v repl="Replacing_values.txt" 'FNR==1{ getline $5 < repl }1' *.asc

*

*-i inplace - allows to modify the input file(s) in-place

*-v repl="Replacing_values.txt" - a variable keeping the filename with replace values

*FNR==1 - consider only the 1st line of each input file

*getline $5 < repl - read next record from repl file and assign it to the 5th column $5


text:
Q: devextreme dxTreeView clearSelection I am using devextreme dxTreeView , I want a clear selection function to uncheck current selection.
self.SubViewModel = {
    treeViewOptions: {
        items: Stores,
        dataStructure: "plain",
        showCheckBoxesMode: true,
        searchValue: self.PackSearch,
        parentIdExpr: "Key",
        keyExpr: "ID",
        displayExpr: "Name",
        selectionMode: "single",
        expandAllEnabled: true,
        expandeExpr: "expanded",
        expandNodesRecursive: true,
    }
};

A: This is a jquery solution https://www.devexpress.com/Support/Center/Question/Details/T221422/dxtreeview-clearselection
function clearSelection() {
    treeView.beginUpdate();
    $.each(treeView.option('items'), function() {
        treeView.unselectItem(this);
    });
    treeView.endUpdate();
}

A: w.r.to ko and DevExtreme you need to add an observable to manage such things
    "id": "1_1",
    "text": "Super Mart of the West",
    "expanded": true,
    "selected": variable which is observable,

You can add "selected": ko.observable() and reset the value to false on your click event by iterating self.SubViewModel.treeViewOptions.items recursively.
Tip: mentioning "selected" key in your items object you may not be able to achieve any custom selections other than any others are provided.

A: The Official Way

*

*You can use getSelectedNodeKeys methods for getting to all key which is selected

*Then use unselectItem methods for unselect all selected node keys

Find the documentation here for getSelectedNodeKeys And unselectItem
And the other way with jQuery if the data structure is plain (in your case it is): alternatively you just clear selected (which is written selectedExpr) from dataSource or items
const element = $(".treeElement");
const items = element.option("items");
element.option("items",items.map(o => {
     o.selected = false
}));


text:
Q: Error when trying to check typeof undefined json object When Im trying to check if the [action] is defined I keep getting javascript errors.
    if((typeof array_from_php.api_description[mobile_type][action]) != 'undefined') {
        console.log('defined');
        api = array_from_php.api_description[mobile_type][action];
    } else {
        console.log('undefined');
        mobile_type = 0;
        api = array_from_php.api_description[mobile_type][action];
    }

Error:
Uncaught TypeError: Cannot read property 'register_mobile' of undefined

A: you need to check each property like
if(array_from_php && array_from_php.api_description && array_from_php.api_description[mobile_type] && (typeof array_from_php.api_description[mobile_type][action]) != 'undefined') {
    console.log('defined');
    api = array_from_php.api_description[mobile_type][action];
} else {
    console.log('undefined');
    mobile_type = 0;
    api = array_from_php.api_description[mobile_type][action];
}