text:
Q: Most efficient way to collect and save large amounts of data in background in android I'm building an Android application that accepts data from a variety of different sensors (5 in total) each providing acceleration & gyro, and one sending EMG data as well. This is happening all over bluetooth v4.1 at a rate of around 50Hz.
I need to listen to all these sensors in the background and save the data.
I want to know:
1) What is the most efficient way to save the data to disk ?
For reference all the data from all sensors amounts to around 23Mb per hour. Should I save the data in a file constantly (I doubt it), every hour etc. ? and is it inexpensive to data the data in text form, or should I save it as a large float array or something ?
2) What is the most efficient way to handle this type of background task ?
There does seem to be a fair amount of discussion around this. I've read about the following classes:

*

*Service

*IntentService

*HandlerThreads

*AsyncTask

*ThreadPool

Its really not clear to me which one I should use for this type of work. If someone more enlightened than me could comment I'd be very grateful.
Thank you in advance for the help.

A: For your first item, you obviously have to make a judgement call about how much data you'll willing to risk if the app gets stopped for some reason. The longer you save up data in a buffer, the more that will be lost in a crash. I don't see any reason to not append the data to a file as you obtain it.
As for deciding on the best format for the data, some things to consider are:

*

*What will you be doing with the data? Some formats (CSV text, JSON, etc.) will be easier for your downstream processes to use than others.

*If you're trying to write out the data as you obtain it, you'll probably want to minimize the amount of pre-processing required.

*Some formats, such as the XML-based ones, are much less efficient space-wise than others. The smallest would probably be a binary format.

In addressing the second item a bit, the two Service items are useful if you want the process to keep working in the background; otherwise your app has to remain in the forefront. Since yours would be running for a long time, you'd probably want to use IntentService.
The other items are just different ways to run things on a thread separate from your main thread. The AsyncTask makes it easy to run stuff where you want progress feedback and where you want to use the eventual results to update your GUI.
Handlers can be run on other threads, but are typically just used to run stuff at different times on the main thread. This is done by posting (optionally delayed) messages to a message queue.
ThreadPool and other threading constructs are much more low level. It's a roll-your-own approach where you have more fine-tune control, but have to do much most of the house-keeping work manually.
A couple of useful pages are Processes and Threads and Android Thread Constructs (Part 4): Comparisons.


text:
Q: How to Change Django InMemoryField to PIL Image object? Here Take a look at my code:
profile_picture = self.validated_data.get('profile_picture',False)
if profile_picture:
    pic = profile_picture.read()

Now, I want to crop the image if it's not in a particular resuloution; I want to convert the pic to a PIL.Image.Image object. How do I do that?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Segmentation fault due to unused int I don't understand why my declaration of int y is preventing my program from suffering a segmentation fault. The program does as intended with the declaration there, but gives me a segmentation fault if I comment it out or delete it:
uint8_t chunk[CHUNKS];
int x = 0; int y;
char filename[6];
FILE *card = fopen(argv[1], "r");
FILE *img = fopen(filename, "w");

//reads 512 byte chunks
while (fread(chunk, sizeof(uint8_t), CHUNKS, card) >= CHUNKS)
{
    //checks first 4 bytes for jpeg signature
    if (chunk[0] == 0xff && chunk[1] == 0xd8 && chunk[2] == 0xff && (chunk[3] & 0xf0) == 0xe0)
    {
        //if second or more jpeg, close old file first
        if (x > 0)
        {
            fclose(img);
            sprintf(filename, "%03i.jpg", x);
            x++;
            img = fopen(filename, "w");
            //WCHUNKS += 512;
            fwrite(chunk, sizeof(uint8_t)*CHUNKS, 1, img);
        }

        //if first jpeg
        else
        {
            x++;
            fclose(img);
            //printf("I found %i Jpegs\n", x);
            sprintf(filename, "%03i.jpg", 0);
            img = fopen(filename, "w");
            fwrite (chunk, sizeof(uint8_t)*CHUNKS, 1, img);
            //WCHUNKS += 512;
        }
    }

    //if not a new jpeg, continue writing to current file
    else
    {
        //WCHUNKS += 512;
        fwrite (chunk, sizeof(uint8_t)*CHUNKS, 1, img);

    }
}

fclose(img);
fclose(card);
}

A: As already mentioned in the comments, the line:
sprintf(filename, "%03i.jpg", x);

Writes 8 bytes in to an array of 6 chars, thus writing past the end of the array.
But why would declaring an extra variable help?
Well technically, writing past the end of an array in C is undefined behavior, but in practice, there is always something in that extra memory, and local variables are usually arranged continuously on the stack.
By declaring an extra unused int just before your filename array, the way your compiler arranges those variables, you actually add 4 (maybe 8) more bytes to your array.
Without them, you would clobber x causing it to have a huge number which would force the sprintf write even more bytes past the end of the array, which would now clobber some memory that is not allocated for variables, and that is how you get your segmentation fault.
You can usually look at the assembly, or use a debugger to find out how your variables are arranged in memory and thus get some idea what will happen when you write past one of them.


text:
Q: Remove all except 1 dot from text string and convert into number I have a text string which reflects thousand separators as a dot but also the decimal.
I want to convert this to a number but retain the decimal.
1.056.865.39  should be 1056865.39
6.685.3 should be 6685.3

I've tried substitute and replace but I can't work out how to retain the last decimal.
Any ideas how to do this in excel?

A: Try:
=SUBSTITUTE(TEXTBEFORE(A1,".",-1),".",)+TEXTAFTER(A1,".",-1)/100

Old Excel versions:
=NUMBERVALUE(SUBSTITUTE(D13,".",",",LEN(D13)-LEN(SUBSTITUTE(D13,".",))),",",".")

A: Excel 2013:
=SUBSTITUTE(A1,".","")/10^(1+(LEFT(RIGHT(A1,3))="."))


text:
Q: Android, make an animation text scroll up on the screen like first part of Star Wars I'm trying to create an animation in my android app.
I want the animation like the credits of Star Wars the movie, where a text goes up gradually.  If there is another way to do it than I'd like to know.

A: here is  a very good example of animation for u
http://android-er.blogspot.com/2012/02/various-effect-of-interpolator-in.html

A: Try this :
Put this piece of code in an xml file in res/anim/animationfile.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator" >

<translate
    android:duration="5000" ---> set your time here
    android:fromYDelta="-100%p"
    android:toYDelta="100%p" /> </set>

Now to set the animation, do this :
Animation translatebu= AnimationUtils.loadAnimation(this, R.anim.animationfile);
tv.setText("Some text view.");
tv.startAnimation(translatebu);

This is how you do it roughly.


text:
Q: Node.js: архитектура приложения с поддержкой плагинов Хочу в своем приложении дать возможность написания плагинов сторонним разработчикам. Как это можно реализовать с учетом того что плагины могут обладать своими зависимостями. Возможно ли сделать так чтобы плагин не мог выбросить исключение, которое приведет к завершению приложения. Существуют ли вообще паттерны для реализации плагинов в node.js?
PS: Остановился на architect. Само строит граф зависимостей и в нужной последовательности инициализирует модули. Все устраивает, от исключений, конечно, никто не застрахует.


text:
Q: Write a Stata eclass program that only returns a vector of p-values Edit: After one day I cross-posted this Statalist.
I want to write my own eclass program to work with eststo and esttab from SSC's esttab.
I want to write a wrapper for ranksum so that I can get the p-values and add them to a table alongside the p-values from t-tests. From the ereturn help file it seems like I need to return a b matrix to comply with eclass, but I can't figure out how.
I commented the bad calls below. Making the table with means and t-tests is no problem (i.e., first 3 columns). But my Wilcoxon3 command gives an error. I have tried with and without returning b, but I can't figure out the error, which is invalid syntax.
I am OK with any solution that puts the ranksum p-values into an e() container.
capture program drop Wilcoxon3
program define Wilcoxon3, eclass
    version 13

    syntax varlist [if] [in], by(varname)
    marksample touse

    local names
    foreach v of varlist `varlist' {
        ranksum `v' if `touse', by(`by')
        matrix b = nullmat(b), 1
        matrix p = nullmat(p), 2*normprob(-abs(r(z)))
        local names `names' "`v'"

    }
    matrix colnames p = `names'

    // store results
    ereturn post b
    ereturn matrix p

end

sysuse auto, clear
eststo clear

/* store means and t-tests */
estpost summarize price weight if !foreign
eststo

estpost summarize price weight if foreign
eststo

estpost ttest price weight, by(foreign)
eststo

/* /1* try to store rank-sum test *1/ */
/* Wilcoxon3 price weight, by(foreign) */
/* eststo */

/* table of means and t-tests */
esttab, cells("mean(pattern(1 0 0) fmt(3) label(!Foreign)) mean(pattern(0 1 0) fmt(3) label(Foreign)) p(star pattern(0 0 1) fmt(3) label(p))")

/* /1* try table of means, t-tests, and rank-sum tests *1/ */
/* esttab, cells("mean(pattern(1 0 0 0) fmt(3) label(!Foreign)) mean(pattern(0 1 0 0) fmt(3) label(Foreign)) p(star pattern(0 0 1 0) fmt(3) label(p)) p(star pattern(0 0 0 1) fmt(3) label(p))") */

A: I received an answer on Statalist here.
This was a case of RTFM. The ereturn post syntax doesn't require rename and equal sign, but ereturn matrix does. This is clear if you focus on the syntax example provided at the top of the ereturn help page. The = is optional, but a new name is not.
The correct code is ereturn matrix p = p.


text:
Q: OSM building and jQuery mobile I have a problem with input "range" and OSM Buildings for leaflet maps. I used basic example from official example which works fine but if I add jquery mobile to  section it breaks the range input. It's strange... I was using jquery mobile input to change the leaflet map opacity and it's working. Here is my basic example:

 var map = new L.Map('map');
map.setView([52.52111, 13.40988], 16, false);

new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: 'osm.org',
  maxZoom: 18,
  maxNativeZoom: 20
}).addTo(map);

var osmb = new OSMBuildings(map).load();

//************************************************************

var now,
  date, time,
  timeRange, dateRange,
  timeRangeLabel, dateRangeLabel;

function changeDate() {
  var Y = now.getFullYear(),
    M = now.getMonth(),
    D = now.getDate(),
    h = now.getHours(),
    m = 0;

  timeRangeLabel.innerText = pad(h) + ':' + pad(m);
  dateRangeLabel.innerText = Y + '-' + pad(M+1) + '-' + pad(D);

  osmb.date(new Date(Y, M, D, h, m));
}

function onTimeChange() {
  now.setHours(this.value);
  now.setMinutes(0);
  changeDate();
}

function onDateChange() {
  now.setMonth(0);
  now.setDate(this.value);
  changeDate();
}

function pad(v) {
  return (v < 10 ? '0' : '') + v;
}

timeRange = document.getElementById('time');
dateRange = document.getElementById('date');
timeRangeLabel = document.querySelector('*[for=time]');
dateRangeLabel = document.querySelector('*[for=date]');

now = new Date;
changeDate();

// init with day of year
var Jan1 = new Date(now.getFullYear(), 0, 1);
dateRange.value = Math.ceil((now-Jan1)/86400000);

timeRange.value = now.getHours();

timeRange.addEventListener('change', onTimeChange);
dateRange.addEventListener('change', onDateChange );
timeRange.addEventListener('input', onTimeChange);
dateRange.addEventListener('input', onDateChange);
body {
  font-family: sans-serif;
  padding: 5px;
  margin: 0;
}

#map {
  width: 300px;
  height: 300px;
  float: left;
  margin: 0 15px 0 0;
}

label {
  height: 20px;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Shadows</title>

  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

    <link rel='stylesheet prefetch' href='http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css'>

<input  id="date" type="range" min="1" max="365" step="1">

<input id="time" type="range" min="0" max="23" step="1">

A: For jQuery Mobile rangesliders you may use:
$(document).on("pagecreate", "#page-1", function() {
  $("#date").on("change", onDateChange);
  $("#time").on("change", onTimeChange);
});

Codepen: http://codepen.io/anon/pen/gLJRXb


text:
Q: Create a Javascript function to simulate clicking on a href on a page Thanks in advance to anyone that can help me on this issue.  I have a basic index.php page running a XML rotating banner. In the banner you can have html links to other pages. That all works fine. I also have a jquery Contact Form that gets hidden on load in the index.php page. To activate the form I use the following href link on the index.php page, ContactForm  and works and display form perfectly.
However my issue is that I cannot get the link to from the xml rotating banner to load the contact form. If I simply put the link ContactForm into it nothing happens. The Contact form does not appears.  I think it maybe because the link is inside the images.xml file and the #contactForm cannot get activated from within that file.  I think the form needs to be activated from the index.php file.  So what I thought I would do is create a link to a javacript script function and calls the jquery function to show the contact form.
However, I am either going about this the wrong way or I am missing something in my LoadContactForm function.  It only triggers the alerts.  I have tried so many different code snippets and I still cannot seem to get it to work. Here is the lastest version of my function that I created that is still not working. Any help and sample code would be greatly appreciated!

A: Luke... You about nailed it with:
    $("a[href="#contactForm"]").click();
I just used the following and it does work:
    $("a[href=#contactForm]").click();
Cheers!
~Ken

A: You are calling getElementById and you dont have any id. Also your script is not jQuery.
$(document).ready(function(){
  $("a[href="#contactForm"]").click(function(){
     alert("Form clicked");
  });

  function LoadContractForm(){
    $("a[href="#contactForm"]").click();
  }
});

I do not understand you question fully. How is the form hidden? Via css? What triggers the survey form? Why don't you give your survey form an id that you can refer to with $("#idname").toggle();


text:
Q: Trying to get the JSONObject inside a JSONObject I got this json I created:
{
   "error":false,
   "0":{
      "tvInfo":{
         "id":"0",
         "nome":"A Guerra dos Tronos",
         "id_tipo":"1",
         "pontuacao":"8.1",
         "nVotos":"780",
         "data_criado":"2011-04-17",
         "data_acabado":"0000-00-00",
         "id_estado":"4",
         "id_canaldono":"3",
         "idade_aconselhavel":"16",
         "tags":"war;based on novel;kingdom;dragon;king;intrigue;fantasy;world;\r\n\r\n",
         "nTemporadas":"6",
         "data_inserido":"2016-05-26 22:40:09",
         "data_ultima_atualizacao":"2016-05-26 22:40:09"
      },
      "categorias":[
         "Sci-Fi",
         "Action & Adventure",
         "Drama"
      ],
      "descricoes":[
         {
            "texto":"bababababa",
            "id_idioma":"1"
         },
         {
            "texto":"bababababa",
            "id_idioma":"2"
         }
      ],
      "criadores":[
         [
            "David Benioff",
            "46",
            "1970",
            "USA",
            "New York",
            "babababa",
            "",
            ""
         ],
         [
            "D. B. Weiss",
            "0",
            "1971-04-23",
            "",
            "",
            "",
            "",
            ""
         ]
      ],
      "fotos":[
         {
            "tipofoto":"0",
            "url":"\/uploads\/series\/gameofthrones1.png"
         },
         {
            "tipofoto":"0",
            "url":"\/uploads\/series\/gameofthrones1Background.png"
         }
      ],
      "trailers":[

      ]
   },
...

I want to get everything that starts on 0 the"id?" 0 so I did this:
JSONObject tv1 = jObj.getJSONObject("0");

And it works, but then I'm trying to get the "fotos" so I did like this:
JSONObject tv1Fotos = tv1.getJSONObject("fotos");

And it dosent work. It gets Method threw JSONException

A: Because you are calling getJSONObject() and fotos is an array
use getJSONArray() instead


text:
Q: Convergence or divergence of the series $1+\frac{1}{2}-\frac{1}{3}+\frac{1}{4}+\frac{1}{5}-\frac{1}{6}+...$ I'm taking undergrad real analysis. I'm trying to come up with a general formula for the series
\begin{equation}
1+\frac{1}{2}-\frac{1}{3}+\frac{1}{4}+\frac{1}{5}-\frac{1}{6}+...
\end{equation} and cannot understand how to get the negative term to only show up with powers of $3$. Or is there another way to test the series. any help would be appreciated.

A: The partial sums of this series can be bounded below by partial sums of the series $$1+\frac14+\frac17+\frac1{10}+\cdots$$ which in turn can be bounded below by the partial sums of the series $$\frac13+\frac16+\frac19+\frac1{12}+\cdots=\frac13\left(1+\frac12+\frac13+\frac14+\cdots\right).$$
The latter series is a constant multiple of the harmonic series, hence it diverges.

A: $$ \begin{align}
&\quad\, \sum_{n=0}^{\infty}\left[+\frac{1}{3n+1}+\frac{1}{3n+2}\color{red}{-}\frac{1}{3n+3}\right] \\[2mm]
&= \sum_{n=0}^{\infty}\left[\frac{1}{3n+1}+\frac{1}{3n+2}\color{red}{-}\frac{2}{3n+3}+\frac{1}{3n+3}\right] \\[2mm]
&= \sum_{n=0}^{\infty}\left[\frac{1}{3n+1}+\frac{1}{3n+2}\color{red}{-}\frac{2}{3n+3}\right]+\sum_{n=0}^{\infty}\left[\frac{1}{3n+3}\right] \\[2mm]
&= \log{3}+\frac{1}{3}\sum_{n=1}^{\infty}\frac{1}{n} \color{red}{\,\,\rightarrow\,\,\infty} \\[2mm]
\end{align} $$


text:
Q: unable to upload csv file in php I was trying to upload a csv file in php. I also want it to be able to accept any type of file.
This is the code I'm using, however, it always enters the, "Could not copy file!" condition.
HTML code

<title>File Uploading Form</title>

File Upload:

Select a file to upload:

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />

<input type="submit" value="Upload File" />
</form>

PHP code
<?php
if( $_FILES['file']['name'] != "" )
{
   copy( $_FILES['file']['name'], "/var/www/html/uploads" ) or
           die( "Could not copy file!");
}
else
{
    die("No file specified!");
}
?>

<title>Uploading Complete</title>

Uploaded File Info:

Sent file: <?php echo $_FILES['file']['name'];  ?>

File size: <?php echo $_FILES['file']['size'];  ?> bytes

File type: <?php echo $_FILES['file']['type'];  ?>

I have checked that the uploads folder and the html as well as php files are of permission 777, so they should be able to upload these files
EDIT
I have removed a lot of code from the php file and tried to make it upload(copy) a hardcoded file path from the filesystem.
What I observe is that, if I just run php upload.php from the command line, it works and "uploads" the file from the Downloads onto the Desktop. However,the same upload.php, if run from the browser and via index.html, on one of my servers, it just says, "Could not copy file!". On another server, it downloads the upload.php file. Basically, the same script works from the command line. Doesn't work from the browser.
(I don't see any error message etc on the browser console)
index.html

<title>File Uploading Form</title>

File Upload:

Select a file to upload:

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />

<input type="submit" value="Upload File" />
</form>

upload.php
<?php
$a = 2;
$b = 1;

if( $a > $b )
{
 copy( "/home/PepperBoy/Downloads/myfile.csv", "/home/PepperBoy/Desktop/myfile.csv" ) or die( "Could not copy file!");
}
else
{
    die("No file specified!");
}
?>

<title>Uploading Complete</title>

Uploaded File Info:

Sent file: <?php echo $_FILES['file']['name'];  ?>

File size: <?php echo $_FILES['file']['size'];  ?> bytes

File type: <?php echo $_FILES['file']['type'];  ?>

A: The name value in the $_FILES array doesn't contain the path to the file. Use tmp_name instead. You also need to give the copied file a name not just the destination directory. Also move the file rather than copy it or you will end up cluttering up the tmp directory
move_uploaded_file( $_FILES['file']['tmp_name'], "/var/www/html/uploads/". $_FILES['file']['name'] )
or die( "Could not copy file!");

A: Replace this with your same line of code.
copy( $_FILES['file']['tmp_name'], "/var/www/html/uploads" ) or die( "Could not copy file!");


text:
Q: Getting an error when running apt update: ModuleNotFoundError: No module named 'apt_pkg' When I run apt update on a Ubuntu 18.04.6 LTS, which is a server my company use for hosting Netbox, I get the following issue:
$ sudo apt update
Hit:1 http://azure.archive.ubuntu.com/ubuntu bionic InRelease
Hit:2 http://azure.archive.ubuntu.com/ubuntu bionic-updates InRelease
Hit:3 http://azure.archive.ubuntu.com/ubuntu bionic-backports InRelease
Hit:4 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu bionic InRelease
Hit:5 https://packages.microsoft.com/ubuntu/18.04/prod bionic InRelease
Hit:6 http://security.ubuntu.com/ubuntu bionic-security InRelease
Traceback (most recent call last):
  File "/usr/lib/cnf-update-db", line 8, in <module>
    from CommandNotFound.db.creator import DbCreator
  File "/usr/lib/python3/dist-packages/CommandNotFound/db/creator.py", line 11, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'
Reading package lists... Done
E: Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/test -w /var/lib/command-not-found/ -a -e /usr/lib/cnf-update-db; then /usr/lib/cnf-update-db > /dev/null; fi'

I get a similar issue when I run neofetch:
$ neofetch
Traceback (most recent call last):
  File "/usr/lib/command-not-found", line 28, in <module>
    from CommandNotFound import CommandNotFound
  File "/usr/lib/python3/dist-packages/CommandNotFound/CommandNotFound.py", line 19, in <module>
    from CommandNotFound.db.db import SqliteDatabase
  File "/usr/lib/python3/dist-packages/CommandNotFound/db/db.py", line 5, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

A colleague of mine told me to run these and try again, but I got the same issue:
sudo apt-get remove command-not-found
sudo apt-get clean
sudo apt-get update
sudo apt-get install command-not-found

Then I went to check how many python version are installed on this server, and I count 4:
$ ls -ls /usr/bin/python*
   0 lrwxrwxrwx 1 root root       9 Apr 16  2018 /usr/bin/python -> python2.7
   0 lrwxrwxrwx 1 root root       9 Apr 16  2018 /usr/bin/python2 -> python2.7
3544 -rwxr-xr-x 1 root root 3628904 Nov 28 18:51 /usr/bin/python2.7
   0 lrwxrwxrwx 1 root root      25 Jan 10 08:10 /usr/bin/python3 -> /etc/alternatives/python3
   0 lrwxrwxrwx 1 root root      16 Oct 25  2018 /usr/bin/python3-config -> python3.6-config
   4 -rwxr-xr-x 1 root root    1018 Oct 28  2017 /usr/bin/python3-jsondiff
   4 -rwxr-xr-x 1 root root    3661 Oct 28  2017 /usr/bin/python3-jsonpatch
   4 -rwxr-xr-x 1 root root    1342 May  1  2016 /usr/bin/python3-jsonpointer
   4 -rwxr-xr-x 1 root root     398 Nov 15  2017 /usr/bin/python3-jsonschema
5356 -rwxr-xr-x 1 root root 5481816 Dec  7 01:11 /usr/bin/python3.10
4424 -rwxr-xr-x 2 root root 4526456 Nov 25 14:10 /usr/bin/python3.6
   0 lrwxrwxrwx 1 root root      33 Nov 25 14:10 /usr/bin/python3.6-config -> x86_64-linux-gnu-python3.6-config
4424 -rwxr-xr-x 2 root root 4526456 Nov 25 14:10 /usr/bin/python3.6m
   0 lrwxrwxrwx 1 root root      34 Nov 25 14:10 /usr/bin/python3.6m-config -> x86_64-linux-gnu-python3.6m-config
   0 lrwxrwxrwx 1 root root      10 Oct 25  2018 /usr/bin/python3m -> python3.6m
   0 lrwxrwxrwx 1 root root      17 Oct 25  2018 /usr/bin/python3m-config -> python3.6m-config

Running python3 --version it returns Python 3.10.9
Does anyone have a clue how can I resolve this issue without having to migrate the hosted app? That would be a nightmare :(
EDIT:
I moved to /usr/lib/python3/dist-packages looked for apt_pkg via ls -la | grep "apt_pkg.cpython" and found the file apt_pkg.cpython-36m-x86_64-linux-gnu.so, I renamed the file to apt_pkg.so and now I could run apt update with a new error message:
$ sudo apt update && sudo apt upgrade
[sudo] password for admin-federico-dostuni:
Hit:1 http://azure.archive.ubuntu.com/ubuntu bionic InRelease
Get:2 http://azure.archive.ubuntu.com/ubuntu bionic-updates InRelease [88.7 kB]
Get:3 http://azure.archive.ubuntu.com/ubuntu bionic-backports InRelease [83.3 kB]
Hit:4 http://security.ubuntu.com/ubuntu bionic-security InRelease
Hit:5 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu bionic InRelease
Hit:6 https://packages.microsoft.com/ubuntu/18.04/prod bionic InRelease
Fetched 172 kB in 1s (176 kB/s)
Reading package lists... Done
Building dependency tree
Reading state information... Done
All packages are up to date.
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] y

Setting up update-notifier-common (3.192.1.15) ...
Traceback (most recent call last):
  File "/usr/lib/update-notifier/package-data-downloader", line 24, in <module>
    import debian.deb822
  File "/usr/lib/python3/dist-packages/debian/deb822.py", line 78, in <module>
    class TagSectionWrapper(collections.Mapping):
AttributeError: module 'collections' has no attribute 'Mapping'
dpkg: error processing package update-notifier-common (--configure):
 installed update-notifier-common package post-installation script subprocess returned error exit status 1
Errors were encountered while processing:
 update-notifier-common
E: Sub-process /usr/bin/dpkg returned an error code (1)

A: because of the file /usr/lib/update-notifier/package-data-downloader, its first line contains this:
#!/usr/bin/python3

from ahead info, your python is Python 3.10.9,
and apt_pkg is apt_pkg.cpython-36m-x86_64-linux-gnu.so, which means it only match the python3.6, you may should do:
sudo rm /usr/bin/python3
sudo ln -f /usr/bin/python3.6 /usr/bin/python3
make sure the python3 --version is python3.6.x
run update command for a test,
sudo apt update


text:
Q: Hide specific element based on value from name attribute I have HTML like this:

   <input name="studentName" value="George">
   <input name="studentName" value="Kim">
   <input name="studentName" value="David">
   <input name="studentName" value="Kanto">

How can I hide other input element except "David" using jQuery?

A: You can use :not(), Attribute Equals Selector [name="value"], .hide()

$("div input:not([value=David])").hide()

   <input name="studentName" value="George">
   <input name="studentName" value="Kim">
   <input name="studentName" value="David">
   <input name="studentName" value="Kanto">


text:
Q: System properties overrides local propreties under Windows @Configuration
@EnableTransactionManagement
@PropertySource(value = "classpath:/properties.properties")
public class DataBaseConfig {

@Resource
private Environment env;

@Bean
public DataSource dataSource() {

    String username = env.getProperty(ConfigurationProperties.DATABASE_USERNAME);
    env.getProperty("username : " + username);

    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    //some code
    return dataSource;
}

}

I have a problem. When I load my properties with Environment it replaces them with system ones if they have the same name. For example, when I'm trying to load the property "username" from my property file it gets replaced with the system property "username". I know that the environment contains not only my properties, but also other properties from other sources, including system properties, but I don't know how I can influence their order. What is the weirdest thing here is that this code works fine under Linux and loads the properties I need. But under Windows it loads system properties. I have never dealt with such situations, so I would be grateful for any help.

A: You don't need to use Bean of type Environment. If you have defined @PropertySource as you done, you could make use of @Value("..."). In that case:
@Value("${username}")

Please try it.


text:
Q: Postgresql is not starting I'm running PostgreSQL 9.2 in a Windows Server.
Everything was fine up to five days ago. Then the service shut down and now when I try to start the cluster (both using the Windows Service and pg_ctl start), I receive the following error messages:

FATAL:  database files are incompatible with server
DETAIL:  The database cluster appears to use a different floating-point number format than the server executable.
HINT:  It looks like you need to initdb.

Just for testing I tried to create a new cluster the simplest way possible:
initdb -D c:\Senior\GestaoDeLoja\PostgresqlIntegrador\data2
and received the same error messages.


text:
Q: How can I add touch to a watch face (EFL)
I am trying to add touch events to my watch face that I am developing with the EFL libraries. But the touch layer is either not working or, when it is, it is fully covering my watch face, although it should be transparent.
My code that creates the watch window is:
Evas_Object *win = NULL;
int ret = EINA_FALSE;

/*
 * Get watch window object
 */
ret = watch_app_get_elm_win(&win);
if (ret != APP_ERROR_NONE) {
    dlog_print(DLOG_ERROR, LOG_TAG, "failed to get watch window. err = %d", ret);
    return NULL;
}
evas_object_resize(win, width, height);

/* <Variant A or B here> */

evas_object_show(win);

Then I try to create a transparent gesture layer and touch callbacks (like described on https://docs.tizen.org/application/native/guides/ui/efl/touch-gesture). I have tried two variants.
Variant A - I use the same window that I created for the watch (win). No errors, but it doesn't work, no touch events:
/* Variant A */
/* Gesture layer transparent object */
Evas_Object *r;
/* Gesture layer object */
Evas_Object *g;

win = elm_win_util_standard_add("gesture_layer", "Gesture Layer");
elm_win_autodel_set(win, EINA_TRUE);

/* Gesture layer transparent object */
r = evas_object_rectangle_add(evas_object_evas_get(win));
evas_object_move(r, 0, 0);
evas_object_color_set(r, 0, 0, 255, 128);
elm_win_resize_object_add(win, r);

/* Gesture layer object */
g = elm_gesture_layer_add(win);
elm_gesture_layer_attach(g, r);
evas_object_show(r);

/* Set callbacks */
elm_gesture_layer_cb_set(g, ELM_GESTURE_N_TAPS, ELM_GESTURE_STATE_START, n_finger_tap_start, NULL);

Variant B - I use a separate object winTouch for the touch layer. It works, but the layer appears fully opaque and the watch face cannot be seen:
/* Variant B */
Evas_Object *winTouch;

/* Gesture layer transparent object */
Evas_Object *r;
/* Gesture layer object */
Evas_Object *g;

winTouch = elm_win_util_standard_add("gesture_layer", "Gesture Layer");
elm_win_autodel_set(winTouch, EINA_TRUE);

/* Gesture layer transparent object */
r = evas_object_rectangle_add(evas_object_evas_get(winTouch));
evas_object_move(r, 0, 0);
evas_object_color_set(r, 0, 0, 255, 0);
elm_win_resize_object_add(winTouch, r);

/* Gesture layer object */
g = elm_gesture_layer_add(winTouch);
elm_gesture_layer_attach(g, r);
evas_object_show(r);
evas_object_show(winTouch); // <--- Without this line, Variant B behaves like Variant A

/* Set callbacks */
elm_gesture_layer_cb_set(g, ELM_GESTURE_N_TAPS, ELM_GESTURE_STATE_START, n_finger_tap_start, NULL);
// and other callbacks

What am I doing wrong?
My project is based on the SDK sample "Chronograph Watch". There are actually 4 different Evas_Object's:

*

*evas_object_resize(win, width, height);

*evas_object_resize(bg, width, height);

*evas_object_resize(chronograph_layout, DIAM_SCREEN, DIAM_SCREEN);

*evas_object_resize(parts, size_w, size_h);

Where should I add the gesture layer? When I add it on 1, Variant A does nothing, Variant B works but covers the watch face. If I do it on one of the others, both Variants work but cover the watch face. I don't understand why, since I am specifying a transparent color.
EDIT: One new thought: could it be that the touch gesture layer does only work on apps, not on watch faces?

A: You don't need to create a new window for gesture layer.
you got a window from API. then did you create a new window using elm_win_add API?
My below sample code works well. window was transprent.
Plz see you code carefully and if you don't find the wrong things.
why don't you share your full code. i will look around.
static Evas_Event_Flags
n_finger_tap_start(void *data , void *event_info)
{
    printf("tap start\n");
   return EVAS_EVENT_FLAG_ON_HOLD;
}

void
test_gesture_layer(void *data EINA_UNUSED, Evas_Object *obj EINA_UNUSED,
      void *event_info EINA_UNUSED)
{
   Evas_Coord w, h;
   Evas_Object *win;

   w = 480;
   h = 800;

   win = elm_win_add(NULL, "gesture-layer", ELM_WIN_BASIC);
   elm_win_title_set(win, "Gesture Layer");
   elm_win_autodel_set(win, EINA_TRUE);
   evas_object_resize(win, w, h);

   Evas_Object *r, *g;

   r = evas_object_rectangle_add(evas_object_evas_get(win));
   evas_object_move(r, 0, 0);
   evas_object_color_set(r, 0, 0, 0, 0);
   elm_win_resize_object_add(win, r);

   g = elm_gesture_layer_add(win);
   elm_gesture_layer_attach(g, r);
   evas_object_show(r);

   elm_gesture_layer_cb_set(g, ELM_GESTURE_N_TAPS,
       ELM_GESTURE_STATE_START, n_finger_tap_start, NULL);

   evas_object_show(win);
}

*

*anyway i recommend you add a touch event callback on window.
refer https://docs.tizen.org/iot/api/5.0/tizen-iot-headed/Example_Evas_Images_2.html
this page find EVAS_CALLBACK_MOUSE_DOWN, EVAS_CALLBACK_MOUSE_UP.

A: The widget tree of chronographwatch App is
Win -> Bg -> Layout -> Images
This sample app's top view is Layout(main.edc), So you should attach gesture layer on that.
Evas_Object *gesture;
gesture = elm_gesture_layer_add(chronograph_layout);
elm_gesture_layer_attach(gesture, chronograph_layout);

elm_gesture_layer_cb_set(gesture, ELM_GESTURE_N_TAPS,
  ELM_GESTURE_STATE_START, n_finger_tap_start, NULL);
elm_gesture_layer_cb_set(gesture, ELM_GESTURE_N_TAPS,
  ELM_GESTURE_STATE_END, n_finger_tap_end, NULL);

I can get an event properly.

*

*If you want to use system defined gestures such as flick, zoom, rotate, long tap
you need to use gesture layer.
but if you just want to get touch event on the object. just use EVAS_CALLBACK_MOUSE_XXX.

Hope you got a solution.


text:
Q: select2 height wrong? I have a select2 listbox looking like this:

The first value is empty and it works alright but the box doesn't seem high enough.
I make the following call to create it:
$elem.select2({minimumResultsForSearch: 10, placeholder: undefined, width: 'resolve'});

This is the HTML before the select2 is called:
<select class="select required" id="user_transaction_company_user_id" name="user_transaction[company_user_id]"><option value=""></option>
<option value="17">enza rinaldi</option>
<option value="14">stijn verrept</option></select>

I see that there is an empty value first, that's no problem but it should dispplay it correctly, not half the height.

A: you should define a placeholder option, it will remove the empty option and display the placeholder when no value is selected.

A: If you do not want to set a default value (by default the first option of your selectbox), you need an empty value in your options. If you then set a placeholder when initialising select2, select2 will automatically replace this empty option with the placeholder text (this placeholder can be blank). Once the user selects an option, there is no way to choose the empty option anymore (unless you specify allowClear: true).
In code (assuming an empty option is set as follows):
<option value=""></option>

After choosing an option, user cannot choose the empty option anymore:
$elem.select2({ placeholder: "" });

After choosing an option, user is able to deselect/choose the empty option:
$elem.select2({ placeholder: "", allowClear: true });

A: If you really want an empty option that can be selected after another option has been selected you can fill the option with &nbsp to make it full height.


text:
Q: 'Fatal: cherry-pick failed' with Git I was working on a branch X. I made a commit and pushed it.
Then I wanted to cherry-pick it to branch Y. But due to some unmerged files present, I got the following message:
error: 'cherry-pick' is not possible because you have unmerged files.
hint: Fix them up in the work tree,
hint: and then use 'git add/rm <file>' as
hint: appropriate to mark resolution and make a commit,
hint: or use 'git commit -a'.
fatal: cherry-pick failed

Now, I just want to delete my branch Y, then re-create the branch Y and then want to manually edit the file where I was trying to cherry-pick.
Currently, I'm unable to delete the branch as it is my working branch.
I cannot checkout any other branch. I'm getting the following error on trying to change the branch.
mod/assign/locallib.php: needs merge
error: you need to resolve your current index first

I just need to delete the branch Y, without losing anything on branch X.
EDIT #1
I edited the file mod/assign/locallib.php
On doing git status, I get:
# On branch MDL-38267_24
# Unmerged paths:
#   (use "git add/rm <file>..." as appropriate to mark resolution)
#
#   both modified:      mod/assign/locallib.php
#

What file should I add in git add .. ?

A: Since you have already edited the conflict file, you just need
git add mod/assign/locallib.php

then
git cherry-pick --continue

A: You attempted to do a merge (via either git merge or git pull) and have files that have conflicts that are not resolved.  If you do git status, you will likely see file(s) listed as being 'changed by both'.  You need to take care of this before you do anything else.
Do git mergetool and it will bring up the files one at a time.  Fix the file so that the conflicts are resolved and then you should be able to proceed.


text:
Q: Classic ASP Split DateTIME to String I have a DateTime value pulled from a field in an MSSQL database  I want to split this and remove all delimiters so that I have just a string of the date.
So: 2012-11-06 14:36:20.810
Becomes: 20121106143620810

Ideally, I don't want the milliseconds either......
So: 2012-11-06 14:36:20.810
Becomes: 20121106143620

I am using Classic ASP for this application.
Any ideas?

A: Quick and dirty:
dateFromDB = "2012-11-06 14:36:20.810"
formatedDate = Replace(dateFromDB, "-","")
formatedDate = Replace(formatedDate, ":","")
formatedDate = Replace(formatedDate, " ","")
formatedDate = Left(formatedDate, Len(formatedDate)-4)

Of course you can optimize it in various ways, but this will get the job done

A: *

*Keep this value in string and remove all special characters.

*If you don't want milliseconds then remove the last 3 characters also.


text:
Q: Mongo Write Client connection What does the MongoDB_ActiveClientsWriting_ metric in mongostat refer to?
If I am performing multiple writes from an application on the same connection  - does it get audited as a single Active Client?
In that case - does a connection indicate a thread - a single funnel of write?
Or does Mongo have inherent worker threads to fork off parallel writes on a connection.
If so,what is the metric/configuration that flags the active threads writing at a time.
We are using Mongo 4.x.x

A: It is stats from the locker - how many active connections keep write lock at the time of reporting.
https://docs.mongodb.com/manual/reference/command/serverStatus/#serverstatus.globalLock.activeClients reads:

globalLock.activeClients.total
The total number of internal client connections to the database including system threads as well as queued readers and writers. This metric will be higher than the total of activeClients.readers and activeClients.writers due to the inclusion of system threads.
globalLock.activeClients.readers
The number of the active client connections performing read operations.
globalLock.activeClients.writers
The number of active client connections performing write operations.

The metric itself is calculated in https://github.com/mongodb/mongo/blob/3a508dcd9755cc5012288068ce88afb9117ac8b8/src/mongo/db/stats/lock_server_status_section.cpp#L55


text:
Q: Sql server query to select data implementing for-each logic I'm writing sql queries to populate data in my report.  I have data in a table like this...
    Name           Gender           MainCategory            SubCategory

    Mark             M              Category 1              Sub Category 1
    Peter            M              Category 1              Sub Category 2
    Gemma            F              Category 1              Sub Category 1
    Paul             M              Category 3              Sub Category 2
    Mike             M              Category 3              Sub Category 4
    Elle             F              Category 3              Sub Category 4
...
...So on

How can I implement foreach logic.. would like to see results like..
   Description                                              Total

   Total Category 1 Employees of Sub Category 1               2
   Total Category 1 Employees of Sub Category 2               1
   Total Category 3 Employees of Sub Category 2               1
   Total Category 3 Employees of Sub Category 4               2

A: Hope following query will help you.
SELECT 'Total ' + MainCategory + ' Employees of ' + SubCategory As [Description],
       COUNT(*) As Total
FROM MyTable
Group BY MainCategory, SubCategory


text:
Q: Invalid capability and invalid name with custom keyboard I've designed a custom keyboard for the use of my own application only. That's why in fact, I didn't use UIInputViewController but only UIViewController (and set a delegate to the custom text field which is actually a subclassed UIScrollView). When I call becomeFirstResponder() on my text field, it takes incredibly long (not only the first time but each time I call this function) until the keyboard actually appears (around 2 seconds). Furthermore I get the following error messages:
_BSMachError: (os/kern) invalid capability (20)
_BSMachError: (os/kern) invalid name (15)

I don't know where these error logs are coming from, the only thing I can tell is that if I don't set my custom view controller's view as the inputView of my text field but a built-in UIView subclass like UISlider I get neither any delay nor any error message.
I would really appreciate any hint or solution to this problem, thanks in advance.
BTW: I'm using Xcode 7.0 official release and iOS 9.0.2 with Swift 2.0 - the delay occurs on the simulator as well as on the device in both debug and release mode, debug executable switched on or off

A: In my case the problem was finally resolved by removing some constraints (that were actually valid and did what they were supposed to), however I don't think that's a general solution to this awkward error message.


text:
Q: Simple Restful service with POST request results in HTTP 405 error: Method not allowed I have just started working in REST. Below is my complete source code. I have tried JSON type , even plain text(TEXT/PLAIN) type. Still getting

HTTP 405 method not allowed.

JerseyClient:
package com.post;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

    public static void main(String[] args) {
        try{
        // TODO Auto-generated method stub
  Client client = Client.create();
  WebResource r = client.resource("http://localhost:8080/PostExample/rest/priya/metallica/post");
  String input = "{\"singer\":\"Metallica\",\"title\":\"Fade To Black\"}";
  ClientResponse resp = r.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, input);
  if (resp.getStatus() != 201) {
        throw new RuntimeException("Failed : HTTP error code : "
             + resp.getStatus());
    }

    System.out.println("Output from Server .... \n");
    String output = resp.getEntity(String.class);
    System.out.println(output);

} catch (Exception e) {

    e.printStackTrace();

}
}

    }

Resource:
package com.post;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/priya/metallica")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.TEXT_PLAIN)
    public Response createTrackInJSON(Track track) {

        String result = "Track saved : " + track;
        return Response.status(201).entity(result).build();

    }
}

POJO class:
package com.post;

public class Track {

    private String singer;
    private String title;

    public String getSinger(){
        return singer;
    }
    public void setSinger(String singer){
        this.singer=singer;
    }
    public String getTitle(){
        return title;

    }
    public void setTitle(String title){
        this.title =title;
    }

}

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>PostExample</display-name>
 <servlet>
 <servlet-name>jersey-serlvet</servlet-name>
 <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
 <init-param>
 <param-name>com.sun.jersey.config.property.packages</param-name>
 <param-value>com.post</param-value>
 </init-param>

 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>jersey-serlvet</servlet-name>
 <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>
</web-app>

I have tried with XMl format too by using corresponding annotation in pojo/resource/client but same HTTP 405 error occurring.

A: Try out these steps to solve the above.

*

*Change the consumes from text plain to JSON (@Consumes(MediaType.ApplicationJson))

*In the rest client use below code to create a JSON POST Request use this code
ClientResponse response = webResource.type("application/json")
       .post(ClientResponse.class, input);

*Try calling service from external rest client like postman and see it how
goes.

*Most important thing please implement interface serialiazable on bean named "Track"


text:
Q: Abrir, editar e salvar um arquivo binário no Python3 É possível abrir um arquivo binário e ler seus bits no Python3, editar e salvar um novo binário. Se for possível, como?

A: Para abrir um arquivo em modo binário basta usar o modo b na funcão open:
open("arquivo", "r+b") # Abre arquivo em modo binário para edição

A partir daí, todas as funções normais de leitura, escrita e navegação de arquivos estão valendo:
with open("arquivo", "r+b") as arquivo:
    byte = arquivo.read(1)
    # altera byte
    arquivo.write(byte)

Lembrando que, como o arquivo foi aberto em modo binário, todas as funções vão aceitar e retornar objetos byte.

A: Sim, é possível. Considere um arquivo binário chamado teste.bin de exemplo com o seguinte conteúdo (bytes em hexadecimal):
 A0 B0 C0 D0 E0 F0

O seguinte código lê esses bytes e altera o conteúdo do byte na posição 2 (que inicialmente tem o valor C0) para FF:
with open('teste.bin', 'r+b') as file:
    byte = file.read(1)
    while byte != b'':
        print(byte)
        byte = file.read(1)

    file.seek(2, 0)
    file.write(b'\xFF')

Resultado da execução:
b'\xa0'
b'\xb0'
b'\xc0'
b'\xd0'
b'\xe0'
b'\xf0'

Bytes no arquivo após a execução:
A0 B0 FF D0 E0 F0

P.S.: Esse exemplo "edita" o mesmo arquivo. Se você desejar criar um
  segundo arquivo com as alterações, basta abri-lo com um outro nome de
  variável. Por exemplo, ao invés e usar o with open, você pode fazer
  assim:
srcFile = open('teste.bin', 'rb')
tgtFile = open('teste2.bin', 'wb')
. . .
srcFile.read ...
tgtFile.write ...
. . .
srcFile.close()
tgtFile.close()

Note que no exemplo inicial eu usei 'r+b' para abrir o arquivo. O
  r e o + indicam que o arquivo vai ser aberto para leitura e para
  atualização, e o b indica que ele deve ser aberto como binário ao
  invés de texto. Nesse segundo exemplo, eu já abro cada arquivo em um
  modo distinto: o arquivo de origem (srcFile) eu abro apenas como
  leitura (e por isso uso 'rb') e o de destino (tgtFile) eu abro
  apenas como gravação (e por isso uso 'wb'). O uso do w na abertura
  do arquivo de destino faz com que ele seja sempre truncado (se quiser
  manter o conteúdo existente você deve abrir com o r+).


text:
Q: What does it mean by "The continuous date / time input field 'u_busq_idig' is ignored. Insufficient type specified for field 'sex'"? i´m creating a model and at the moment of using de C5.0 Operator is appears me error and the following message: "The continuous date / time input field 'u_busq_idig' is ignored.
Insufficient type specified for field 'sex'"
Here i leave the image.
Thank you in advance!

A: @Cristobal Daponte, C5.0 does not use any field with type Time, Date and Timestamp to build model, if any field with these type are used as input field, it will automatically skip them and report the warning message you saw.
For the error, you might need to add a Type node before the modeling node, and initialize all input fields by click the Read Values button in the node editor like below:
Read Values in Type


text:
Q: Laravel 5 how to set Cache-Control HTTP header globally? My Laravel application is returning Cache-Control: no-cache, private HTTP header by default for each site. How can I change this behaviour?
P.S.: It is not a PHP.ini problem, because changing session.cache_limiter to empty/public does not change anything.

A: For people that seek a way to write less code, here is another way you can add headers to a response without extra steps.
In the example above, I created a middleware to prevent routes from being cached in the end user browser.
<?php

class DisableRouteCache
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)->withHeaders([
            "Pragma" => "no-cache",
            "Expires" => "Fri, 01 Jan 1990 00:00:00 GMT",
            "Cache-Control" => "no-cache, must-revalidate, no-store, max-age=0, private",
        ]);
    }
}

Source: Attaching Headers To Responses

A: Laravel 5.6+
There's no longer any need to add your own custom middleware.
The SetCacheHeaders middleware comes out of the box with Laravel, aliased as cache.headers
The nice thing about this Middleware is that it only applies to GET and HEAD requests - it will not cache POST or PUT requests since you almost never want to do that.
You can apply this globally easily by updating your RouteServiceProvider:
protected function mapWebRoutes()
{
    Route::middleware('web')
        ->middleware('cache.headers:private;max_age=3600') // added this line
        ->namespace($this->namespace)
        ->group(base_path('routes/web.php'));
}

protected function mapApiRoutes()
{
    Route::prefix('api')
        ->middleware('api')
        ->middleware('cache.headers:private;max_age=3600') // added this line
        ->namespace($this->namespace)
        ->group(base_path('routes/api.php'));
}

I don't recommend that though. Instead, as with any middleware, you can easily apply to specific endpoints, groups, or within the controller itself, e.g.:
Route::middleware('cache.headers:private;max_age=3600')->group(function() {
    Route::get('cache-for-an-hour', 'MyController@cachedMethod');
    Route::get('another-route', 'MyController@alsoCached');
    Route::get('third-route', 'MyController@alsoAlsoCached');
});

Note that the options are separated by semicolon not comma, and hyphens are replaced by underscores. Also, Symfony only supports a limited number of options:
'etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public', 'immutable'
In other words you can't simply copy and paste a standard Cache-Control header value, you will need to update the formatting:
CacheControl format:       private, no-cache, max-age=3600
  ->
Laravel/Symfony format:    private;max_age=3600

A: Laravel 5.5 <
You can have a global middleware for that. something like:
<?php

namespace App\Http\Middleware;

use Closure;

class CacheControl
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->header('Cache-Control', 'no-cache, must-revalidate');
        // Or whatever you want it to be:
        // $response->header('Cache-Control', 'max-age=100');

        return $response;
    }
}

then just register this as a global middleware in the Kernel file:
protected $middleware = [
    ....
    \App\Http\Middleware\CacheControl::class
];


text:
Q: Find out how many NATs exist between my home machine and the Internet Are there any tools/utilities that can help me find out how many NATs exist between my home machine and the public Internet?
Any references to protocols that would help me figure this out would also be useful.

A: I thought traceroute (linux) provides the list of routers that are encountered while a packet travels from a source to destination. But it doesn't necessarily mean that each router has an integrated NAT component.
Please correct me if I am wrong.

A: Start > Run > type cmd to open a Command Prompt. Enter the following command:
tracert www.google.com

A: Some SOHO routers will show your connections and the associated ports.  You won't be able to get the information from routers in the Internet.  On Windows you can view your connections by typing the following in a Command Prompt:
netstat


text:
Q: How do I have weblogic reload cached JSPs on restart Our method of deploying a new version of an app for weblogic (11g) is to copy over top of the existing ear file and then stop and restart the weblogic server. We do a start/stop of weblogic rather than a redeployment, because of the known permgen issue (where eventually we will run out of perm gen and have to bounce the weblogic server).
However, this method of deploying has a drawback-- new JSP versions are not seen by weblogic. In order to fix this we have had to wipe out the contents of the tmp directory that maintain a cache of the compiled JSPs prior to restarting the server. Is there a setting that would tell weblogic to wipe the cache/reload/recompile JSPs when it starts back up?

A: Changing the JSP refresh timer
A standard solution is to tell Weblogic to check JSP freshness more frequently by either setting the value in your web.xml or in your weblogic.xml.
In production mode, Weblogic won't check for new JSP versions (default value: -1) while it does each second in development mode (default value: 1).
The choice between modifying web.xml or weblogic.xml is up to you, regarding the application servers you target, being WebLogic only or not.
If you prefer to modify web.xml, then set a value for the context parameter weblogic.jsp.pageCheckSeconds as follows:
<context-param>
  <param-name>weblogic.jsp.pageCheckSeconds</param-name>
  <param-value>0</param-value>
</context-param>

If you prefer to modify weblogic.xml, then set a value for parameter page-check-seconds in the jsp-descriptor section. Here is the relevant excerpt from the documentation:

Sets the interval, in seconds, at which WebLogic Server checks to see if JSP files have changed and need recompiling. Dependencies are also checked and recursively reloaded if changed.
  The value -1 means never check the pages. This is the default value in a production environment.
  The value 0 means always check the pages.
  The value 1 means check the pages every second. This is the default value in a development environment.
  In a production environment where changes to a JSP are rare, consider changing the value of  pageCheckSeconds to 60 or greater, according to your tuning requirements.

Source: http://docs.oracle.com/cd/E21764_01/web.1111/e13712/weblogic_xml.htm#i1038490
Forcing redeployment
Restarting Weblogic server does not force it to redeploy a Web Application (especially in production mode).
Solution
Trigger explicitly the "redeploy" life-cycle operation using command line like this:
java -cp weblogic.jar weblogic.Deployer -redeploy [-remote -adminurl t3://hostname:hostport] -username login -password password -name webapp.name [-upload -source webapp.war]

*

*Note that -redeploy is WAYS much safer than -update, esp. with Weblogic <= 10.x

*Keep first block between [ ], only if the server is not local. Remove the [ ] in that case.

*Keep second block between [ ], if you want to combine the WAR file uploading in the same step, which is way simpler. Remove the [ ] in that case.

A: To avoid this you should first update your Module and then restart the server..this should fix your problem.
Although process mentioned by is always give 100% correctness. But you can try above mentioned steps.


text:
Q: How to create a link_to with a button to an action inside a form_for? I have a resource called users. Inside the edit action, I have a form_for to edit user's information. I want to place a button inside the form to redirect to another action. So I am doing this:
<%= form_for @user, html: {class: 'form-horizontal'} do |f| %>

      <%= f.label :name, "Name", class: "col-sm-4 control-label"%>

        <%= f.text_field :name, required: "required", class: "form-control" %>

      <%= f.label :email, "Email", class: "col-sm-4 control-label"%>

        <%= f.email_field :email, required: "required", class: "form-control" %>

      <%= link_to root_path do %>
        <button class="btn btn-default" name="button">Go to Root</button>
      <% end %>

    <%= f.submit "Save", class: "btn btn-default" %>

<% end %>

The problem is that, when I click the "Go to Root" button, It process the form in the update action like if I have pressed the submit button. But If I change

      <%= link_to root_path do %>
        <button class="btn btn-default" name="button">Go to Root</button>
      <% end %>

for

      <%= link_to root_path do %>
        Go to Root
      <% end %>

It goes to te root_path. Why is it happening and Why I can't use a  to create a link to another action inside this form?

A: By default a form button will have type submit. You need to specify that is of type button.
Try the following:
<button type="button" class="btn btn-default" name="button">Go to Root</button>


text:
Q: Does type projection have an opposite, or is it still projection (or just mapping)? This is based on my assumption that taking an object of type:
public class Fruit : IBasicFruit, IFruitDetails
{
    // IBasicFruit implementation
    public string name { get; set; }
    public string color { get; set; }

    // IFruitDetails implementation
    public string scientific_name { get; set; }
    public bool often_mistaken_for_vegetable { get; set; }
    public float average_grams { get; set; }
    public int century_domesticated { get; set; }
}

... and from it creating an object of type:
public class BasicFruit : IBasicFruit
{
    public string name { get; set; }
    public string color { get; set; }
}

... is known as "projection", or "type projection" (that projection applies not only to anonymous types).
Now, let's say I send a serialized BasicFruit from a server to my client application, where some highly sophisticated farm logic is performed on those two strings, and then it gets sent back to the server, where the ORM is not aware of the BasicFruit type, only of the Fruit entity type. If I create a new Fruit object based on my BasicFruit object (ignoring the properties that do not exist in BasicFruit), so my ORM can persist it, is that the opposite of projection, because I am going from subset to superset, or is it still considered projection, or is this just mapping?
Could projection be considered a form of mapping?

A: In relational algebra projection is an operation that takes a relation and a subset of that relation's columns and returns a new relation.  The new relation is the same as the input relation, except it only has the specified columns.
projection : Relation -> Column list -> Relation

There may be fewer rows in the output relation than the input relation because multiple rows project to the same row if their values for the specified columns are the same.
Now consider the inverted operation:
inverse_projection : Relation -> Column list -> Relation

Here we have an input relation whose column names are a subset of the columns in the output relation.  Now we need the Column list to be columns of the output relation, which is now a superset of the columns in the input relation.  This is a bit peculiar because we have to create rows for the output relation where some of the column values are left unspecified.  Purely from a relational algebra perspective, this doesn't make much sense.  After all, where does the data come from for these unspecified columns?  Also, unlike the projection operation the input and output relations always have the same number of rows.
In SQL we're allowed to insert data by specifying only some of the table's columns.  The unspecified columns take on their default values.
INSERT INTO fruit (name, color) VALUES
('apple', 'red'),
('apple', 'green'),
('orange', 'orange');

Going back to relational algebra this is like more like taking the cross product of the relation...
NAME, COLOR
apple, red
apple, green
orange, orange

with the relation...
SCIENTIFIC_NAME, OFTEN_MISTAKEN_FOR_A_VEGETABLE, AVERAGE_GRAMS, CENTURY_DOMESTICATED
"", false, null, null

than doing a so-called inverted projection.  Again, they're similar conceptually, but you're really taking a cross product with the default values.


text:
Q: Trying to find a short story with a cowboy and psychologist who knows he's delusional I can't remember where I read this short story, but the plot is that a cowboy perches on the edge of a cliff looking for Black Bart or some such other villain to ride up.
From behind the cowboy comes a psychologist who explains kindly to the cowboy that he's experiencing a delusion which has thrown him back into the old West, and that none of this is real - no gun, no cliff, no Black Bart.  To prove it, the psychologist walks out in front of him, and promptly falls off the cliff to his death.  The cowboy shakes his head and picks up his rifle because he sees Black Bart riding up in the distance.
Any clues?  No idea as to title or author but it might have been in an anthology of Hugo or Nebula winners.

A: It's called "Texas Week" by Albert Hernhuter. You may have read it in 50 Short Science Fiction Tales edited by Isaac Asimov.


text:
Q: Volume mount on SCC as requirement for running Falco Is it possible to run falco with removing several volume value on scc ? for example just putting hostpath only as value on falco SCC because on the environment (OCP & k8s) only permitted to access hostpath only..
as i see, the value on SCC falco yaml is:
Volume:
 - configMap
 - emptyDir
 - secret
 - hostpath

thanks


text:
Q: Unity3D + Leap Motion: Gesture replay and recognition from web He there,
I'm currently working on a serious game for a school project. In short, this game is supposed to help people with differtent types of hand arthritis (and related diseases). The general idea is that the game will help the patiënt with moving their hands and fingers to keep them as healthy as possible.
The fact is, that every patiënt is different, so each patiënt has different "exercises" they have to perform. We have thought about this problem and we think the best way to handle this, is to record exercises for each patiënt.
We came up with the following idea. We created a web portal for doctors and physiotherapists. In here, they are able to "create" patiënt files. Each patiënt file has different information about that particular patiënt. Next to that, the doctor is able te record different exercises using the leap motion. I have used the jestPlay project to achieve this. So far, the doctor/therapist is able to record an exercise for a particular patiënt and store this exercise as a .json file on the server.
In addition to this, another part of the time is building a game in the Unity3D engine (C#). In this game, the player uses spells to clear the game. These spells are supposed to be the particular exercises the doctor recorded in the web application. When the patiënt logs in on the game, the .json file of the exercises will be send to the Unity3D engine. So far, so good.
Once the .json file is in Unity, I use a json parser to put it into an object(array). The data should be translated to a movement in leap motion (a replay so to speak). Once the particular patiënt does the movement/exercise the doctor initially recorded, then the spell is should complete.
Now, I have the following issues and I don't really know where to start to tackle this. I really hope there is someone that has dealed with something like this before and is able/willing to help me out with it.
-How do I translate the data from the webapplication (see http://www.yorickkeijzer.nl/cotf/application/exercise.json2 for an example) to a leap motion replay / exercise / movement in Unity?
-How do I make Unity recognize the diffent movements/exercises (so compare the .json data from the web application with the real time leap motion data in unity)?
I hope, I have explained it clear enough. If you have any questions, please don't hesitate to ask them.
Thanks a lot!

A: Reposting this response from: https://community.leapmotion.com/t/unity3d-gesture-replay-and-recognition-from-web/209/2
documents sending information between the javascript/web Leap client and the unity web engine.
In summary: you can use the Javascript Leap client to detect frame data and send it (or a subset of that data) to the web player using Unity's browser API. Leap web player does not directly have access to the frame data stream because of browser sandboxing, which is why we have to give it an indirect feed of frame data.
I would not recommend sending every piece of information in the frame to the web player; if you know what information you want -- finger tips, palm location, gestures -- send that information to Unity in a custom message JSON block.
If you are sending in JSON keep in mind you'll be sending strings of JSON; to pick apart that data you would use the JSONObject code found in the wiki and referenced in that article.
There are Gists of the basic files used by me in my implementation.
Dave Edelhart
Senior Web Developer
Leap Motion
Other links:
Leap JavaScript API documentation: js.leapmotion.com


text:
Q: Power Automate Filter List items by person login name We need to filter the list items by person login name (fully qualified i.e, i:0#.f|membership|xyz@abc.com),
How we can achieve this using Power automate GetList Items method or through REST API,
Any help would be appreciated.

A: Follow below steps:

*

*Get User Id from SharePoint using user login name:

REST API endpoint: /_api/web/siteusers('<login-name>')?$select=Id

Flow expression used: uriComponent(variables('loginName'))

Complete Uri: _api/web/siteusers('@{uriComponent(variables('loginName'))}')?$select=Id

*Filter SharePoint list items using user ID:

References:

*

*SharePoint REST API: Get User Id by User Name

*get items - filter person field

*Microsoft Docs - uricomponent() function

*Parsing JSON in Microsoft Flow


text:
Q: How TrueCaller works on Windows Phone? TrueCaller is an app that shows live incoming caller information right on the built in incoming call UI.
How did they did that?

A: Based on the apps description of what it does, TrueCaller has access to privileged API. Normal apps cannot intercept or monitor phone calls the way TrueCaller's overview describes.


text:
Q: Get user geolocated country name in Woocommerce 3 I would like to add "We ship to {country name}" in WooCommerce header based on user geoip country name?
I would like to write html content in the header of my WooCommerce store, such as We ship to "Your Country name".
Any help will be really appreciated?
I have WooCommerce geolocation enabled already.

A: You can make a custom function based on WC_Geolocation Class this way:
function get_user_geo_country(){
    $geo      = new WC_Geolocation(); // Get WC_Geolocation instance object
    $user_ip  = $geo->get_ip_address(); // Get user IP
    $user_geo = $geo->geolocate_ip( $user_ip ); // Get geolocated user data.
    $country  = $user_geo['country']; // Get the country code
    return WC()->countries->countries[ $country ]; // return the country name

}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

USAGE
You will add the following code in your child theme's header.php file:
1) in between html code:
<?php printf( '
' . __('We ship to %s', 'woocommerce') . '
', get_user_geo_country() ); ?>

2) or in between php code:
printf( '
' . __('We ship to %s', 'woocommerce') . '
', get_user_geo_country() );

Converting this to Shortcode:
function get_user_geo_country(){
    $geo      = new WC_Geolocation(); // Get WC_Geolocation instance object
    $user_ip  = $geo->get_ip_address(); // Get user IP
    $user_geo = $geo->geolocate_ip( $user_ip ); // Get geolocated user data.
    $country  = $user_geo['country']; // Get the country code
    return sprintf( '
' . __('We ship to %s', 'woocommerce') . '
', WC()->countries->countries[ $country ] );
}
add_shortcode('geoip_country', 'get_user_geo_country');

Code goes in function.php file of your active child theme (or active theme). Tested and works.
Normal shortcode usage (in the backend text editor):
[geoip_country]

or in php code:
echo do_shortcode( "[geoip_country]" );


text:
Q: SoapUI + Groovy + Get 3 test data from 3 different environment respectively In SoapUI, We have 3 different environment and 3 different test data property files.
So my problems are:

*

*How to set 3 different end points in SoapUI?

*How to get test data as per the environment using Groovy?

A: I try to answer your questions

1.- How to set 3 different end points in SoapUI.

Set your test steps URL with a property like:
http://${#Project#endpoint}

And add the endpoint property in your test data file.

2.- How to get test data as per the environment using Groovy.

If you have a typical property file with key=value you can use the code shown below:
// read property file
def properties = new java.util.Properties();
properties.load( new java.io.FileInputStream( "/tmp/sample.properties" ));

proj = testRunner.testCase.testSuite.project;

def names = [];
names =  properties.propertyNames();
while( names.hasMoreElements() )
{
  def name = names.nextElement();
  log.info name + " " + properties.getProperty(name);
  proj.setPropertyValue(name, properties.getProperty(name)) ;
}

With this you save all properties in the project level, if you prefer to save in testCase or testSuite use testRunner.testCase or testRunner.testCase.testSuite instead of testRunner.testCase.testSuite.project.
Hope this helps,


text:
Q: Facebook open graph redirect when clicking on shared box from website Good morning, I'm Gabriele from Italy, nice to meet you all.
I have a problem with Facebook open graph. We have a 2 pages wordpress website: in the first one there is a mail chimp form to fill to join a sort of competition. When you subscribe to the form you are redirected to page 2 with congratulations etc..
In this second page there is a sharing element so you can share that you have joined the competition. I need that the box you visualize when you share page 2 on fb do not send you to that page but to the first one. So in the second page  I set this open graph tags but it always redirect to page 2:
<meta property="og:type" content="website">
<meta property="og:url" content="the first page I want to share, not the second">
<meta property="og:title" content="bla bla">
<meta property="og:image" content="image url">
<meta property="og:description" content="bla bla">
<meta property="og:locale" content="it_IT">

Can someone please help?
Thanks a lot!

A: Pointing the og:url from the second page to the first one should work, as long as:

*

*The Facebook crawler can read this second page and see this og:url. If this results page access is restricted (i.e. to the logged in user that caused it) it would not work

*The first page has a correct og:url pointing to itself.
You can use the Sharing debugger to verify if the crawler is being able to see your changes, and also to force it to refresh any cache it may have from a previous version: https://developers.facebook.com/tools/debug/


text:
Q: Doubled requests on nodejs http server Scenario
I am running a very simple server on nodejs:
var http = require("http");
var ConnectionsNumber = 0;

function onRequest(request, response)
{
    console.log((new Date).toUTCString() + " - Request received");
    console.log(request.headers);
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Listening\n");
    response.end();
    ConnectionsNumber++;
    console.log('Requests so far: ' + ConnectionsNumber);
}

http.createServer(onRequest).listen(8888);
console.log((new Date).toUTCString() + " - Server started");

But when I start the server and make requests (via Chrome) the server receives two requests at once. Here is the log:
Wed, 03 Oct 2012 16:03:27 GMT - Server started
Wed, 03 Oct 2012 16:03:34 GMT - Request received
{ host: 'localhost:8888',
  connection: 'keep-alive',
  'cache-control': 'max-age=0',
  'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  'accept-encoding': 'gzip,deflate,sdch',
  'accept-language': 'it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4',
  'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3' }
Requests so far: 1
Wed, 03 Oct 2012 16:03:34 GMT - Request received
{ host: 'localhost:8888',
  connection: 'keep-alive',
  accept: '*/*',
  'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4',
  'accept-encoding': 'gzip,deflate,sdch',
  'accept-language': 'it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4',
  'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3' }
Requests so far: 2

Question
What is happening?
Edit
Here is the winner:
var http = require("http");
var ConnectionsNumber = 0;

function onRequest(request, response)
{
    console.log((new Date).toUTCString() + " - Request received");
    console.log(request.url);

    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Listening\n");
    response.end();

    ConnectionsNumber++;
    console.log('Requests so far: ' + ConnectionsNumber);
}

http.createServer(onRequest).listen(8888);
console.log((new Date).toUTCString() + " - Server started");

And the corresponding log:
Wed, 03 Oct 2012 20:00:04 GMT - Server started
Wed, 03 Oct 2012 20:00:14 GMT - Request received
/
Requests so far: 1
Wed, 03 Oct 2012 20:00:14 GMT - Request received
/favicon.ico
Requests so far: 2

That's all folks.

A: Chrome requests a favicon by default. That is probably why you are seeing a second request.


text:
Q: Where is the "generate constructor" option in Eclipse Oxygen? I'm using Eclipse for PHP and can't find the "generate constructor using fields" option.
It's not in the "Source" menu nor in the right click "Source" context menu. Tried highlighting the class but it didn't work.

A: PDT haven't such feature. Please open enhancement request: https://bugs.eclipse.org/bugs/enter_bug.cgi?product=PDT


text:
Q: Error while rendering the page with the help of Angular 5 I'm doing a project with the help of Angular 5. I am calling an API in it.
I am getting following error:
Error: StaticInjectorError(AppModule)[Router -> ApplicationRef]:
  StaticInjectorError(Platform: core)[Router -> ApplicationRef]:
    NullInjectorError: No provider for ApplicationRef!
    at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:951)
    at resolveToken (core.js:1195)
    at tryResolveToken (core.js:1140)
    at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1035)
    at resolveToken (core.js:1195)
    at tryResolveToken (core.js:1140)
    at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1035)
    at resolveNgModuleDep (core.js:8071)
    at _callFactory (core.js:8143)
    at _createProviderInstance$1 (core.js:8091)

My Package.json is:
{
  "name": "demo-app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.0.3",
    "@angular/common": "^6.0.3",
    "@angular/compiler": "^6.0.3",
    "@angular/core": "^6.0.3",
    "@angular/forms": "^6.0.3",
    "@angular/http": "^6.0.3",
    "@angular/platform-browser": "^6.0.3",
    "@angular/platform-browser-dynamic": "^6.0.3",
    "@angular/router": "^6.0.3",
    "core-js": "^2.5.4",
    "rxjs": "^6.0.0",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular/compiler-cli": "^6.0.3",
    "@angular-devkit/build-angular": "~0.6.8",
    "typescript": "~2.7.2",
    "@angular/cli": "~6.0.8",
    "@angular/language-service": "^6.0.3",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.2.1",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.0",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.3.0",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1"
  }
}

I have app.module.ts as follows, in which I am giving a route "fetch" and calling the corresponding controller.
import { NgModule } from '@angular/core';
import { FetchApiComponent } from './fetch-api/fetch-api.component';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
{ path: 'fetch', component: FetchApiComponent },

];

@NgModule({
  declarations: [

    FetchApiComponent
  ],
  imports: [

    RouterModule.forRoot(routes)
  ],
exports: [
RouterModule
],
  providers: [],
  bootstrap: []
})
export class AppModule { }

The main.ts is following
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

It is showing that the error is thrown by main.ts file because of the following code.
platformBrowserDynamic().bootstrapModule(AppModule)
      .catch(err => console.log(err));

Screenshot of the error:

A: To achieve expected result without eror, import BrowserModule
import { NgModule } from '@angular/core';
import { FetchApiComponent } from './fetch-api/fetch-api.component';
import { Routes, RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';

const routes: Routes = [
{ path: 'fetch', component: FetchApiComponent },

];

@NgModule({
  declarations: [

    FetchApiComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
exports: [
RouterModule
],
  providers: [],
  bootstrap: []
})
export class AppModule { }

code sample for reference - https://stackblitz.com/edit/angular-2xbbzj?file=src/app/app.module.ts
Note: Remove BrowserModule from imports to see the same error


text:
Q: How To Display information in PDF format in Android I want to display some copy right agreement in pdf format in EditText or TextView. How to do that in Android ? Are there any APIs or any sample codes ? I will be waiting for valuable reply.
Thanks,

A: Android does not natively support pdfs (and EditText/TextViews certainly don't!) You could check to see if Adobe Reader for Android is installed, or you can (and this is what I recommend) convert whatever agreement you're trying to show to plaintext and display it in a TextView. If you need more formatting control, you could try converting your agreement to HTML and showing it in a WebView.


text:
Q: Substract data in R So I have a data which is
data = read.csv("CarPrice_Assignment.csv")

Then i described numdata if the data set is a num variable
numdata = select_if(data, is.numeric)

I want to describe other data that is in data but not it numdata as categorical data. How to substract data-numdata?
I've tried using
catdata = setdiff(data,numdata)

But it doesn't work for columns. Is there any way to do this?


text:
Q: CSS element different height on element's side Is it possible to get my desired output using css or jQuery without rotating the element?
I wanted this output

A: Without completely understanding your objective I'm assuming you're trying to create shapes without using the rotation properly. This method shows you how to create shapes with CSS3 :) Hope that helps!
https://www.cssportal.com/css3-shapes/
For example this creates a parallelogram:
#parallelogram {
   width: 130px;
   height: 75px;
   background: blue;
   /* Skew */
   -webkit-transform: skew(20deg);
   -moz-transform: skew(20deg);
   -o-transform: skew(20deg);
   transform: skew(20deg);
}


text:
Q: getRootPane() default button - Is this a bug? I have made an SSCCE. Please note that it must be Windows Look&Feel.
import java.awt.*;
import javax.swing.*;

public class DefaultButtonBug {
private static final String LAF_WINDOWS = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";

public static void main(String[] args) {

    try {
        UIManager.setLookAndFeel(LAF_WINDOWS);
    } catch (Exception ex) {
        System.out.println("Setting the L&F failed so I cannot reproduce the bug.");
        System.exit(1);
    }

    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            JPanel content = new JPanel();
            JButton defaultButton = new JButton("Default");

            content.add(defaultButton);

            JFrame frame = new JFrame();

            frame.getRootPane().setDefaultButton(defaultButton);
            frame.setContentPane(content);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        }
    });
}
}

*

*Launch this

*The button should be focused. If not, click it.

*Click on any other window, to make sure this current window loses the focus

*The button keeps animating in blue tints, even when this window has no focus anymore!

The button 'pulsing' animation is something not present in the standard Java L&F.
Remark that when this button is no longer the default button (remove the appropriate line in the code), the button will be gray after the window loses focus and there is no animation whatsoever.
My question to you is: is this considered a bug? Because this makes the EDT keep doing stuff instead of being idle when the window is hidden behind another window too (I did some profiling). Indeed, that's the stuff that bothers me the most of all: hiding the window does not make the EDT go idle.

A:
getRootPane() default button - Is this a bug?

*

*not as described in a comment by @Guillaume Polet

*but I'd be inclined to use KeyBindings, because any JComponents with FocusInWindow and added ActionListener can consume() ENTER key pressed, for all JButtons JComponents

*focus is managable by getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT/*.WHEN_FOCUSED*/)

*notice (Win OS) JButton has implemented TAB as an accelerator in KeyBindings, too.
from code
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class DefaultButtonBug {

    private static final String LAF_WINDOWS = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(LAF_WINDOWS);
        } catch (Exception ex) {
            System.out.println("Setting the L&F failed so I cannot reproduce the bug.");
            System.exit(1);
        }
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JPanel content = new JPanel();
                JButton focusedButton1 = new JButton("Focused");
                focusedButton1.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("Focused pressed");
                    }
                });
                content.add(focusedButton1);
                final JButton defaultButton2 = new JButton("Default");
                defaultButton2.setIcon(UIManager.getIcon("OptionPane.informationIcon"));
                defaultButton2.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("Default pressed");
                    }
                });
                defaultButton2.getModel().addChangeListener(new ChangeListener() {
                    @Override
                    public void stateChanged(ChangeEvent e) {
                        ButtonModel model = (ButtonModel) e.getSource();
                        if (model.isRollover()) {
                            defaultButton2.setIcon(UIManager.getIcon("OptionPane.errorIcon"));
                        } else {
                            defaultButton2.setIcon(UIManager.getIcon("OptionPane.informationIcon"));
                        }
                    }
                });
                content.add(defaultButton2);
                JFrame frame = new JFrame();
                frame.getRootPane().setDefaultButton(defaultButton2);
                frame.getRootPane().getInputMap(
                        JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT/*.WHEN_FOCUSED*/)
                        .put(KeyStroke.getKeyStroke("ENTER"), "clickButton");
                frame.getRootPane().getActionMap().put("clickButton", new AbstractAction() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        defaultButton2.doClick();
                    }
                });
                frame.getRootPane().setDefaultButton(defaultButton2);
                frame.setContentPane(content);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

learning item of day

*

*on Win7/8 (Java6/7) are allowed mouse event on un_focused Java Window (for all standard L&F), can be listener from ChangeListener added to ButtonModel

*doesn't work on WinXP
focused

un_fosused firing the same events a

EDIT
in Win7 compiled in JDK7_011 flashing JButtons (focused in Java window) with blue Color

*

*flashing with blue color on second period

and


text:
Q: Hibernate: cannot drop foreign key Having this two classes:
Address.java:
@Embeddable
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Address {
    private String street;
    private String city;
    private String state;
    private String pincode;
}

User.java:
@Entity
@Data
public class User {
    @Id
    private int id;
    private String name;
    @ElementCollection
    private Set<Address> addresses = new HashSet<>();
}

DemoApplication.java:
@Bean
CommandLineRunner dataLoader2(UserRepository userRepo){
  return  new CommandLineRunner() {
    @Override
    public void run(String... args) throws Exception {
      User u = new User();
      u.setName("Some random name");
      Address a1 = Address.builder()
          .street("First Street")
          .city("first city")
          .state("first state")
          .pincode("100001")
          .build();
      Address a2 = Address.builder()
          .street("Second Street")
          .city("Second city")
          .state("second state")
          .pincode("200002")
          .build();
      u.setAddresses(new HashSet<>(Arrays.asList(a1, a2)));
      userRepo.save(u);
    }
  };
}

When run, if fails with this error:

GenerationTarget encountered exception accepting command : Error
executing DDL "alter table user_addresses drop foreign key
FKfm6x520mag23hvgr1oshaut8b" via JDBC Statement

Yet, the final tables are created:
describe user_addresses:
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| user_id | int          | NO   | MUL | NULL    |       |
| city    | varchar(255) | YES  |     | NULL    |       |
| pincode | varchar(255) | YES  |     | NULL    |       |
| state   | varchar(255) | YES  |     | NULL    |       |
| street  | varchar(255) | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+

describe user:
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int          | NO   | PRI | NULL    |       |
| name  | varchar(255) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+

Why cannot the jdbc drop the foreign key user_id in table user_addresses? How to make the jdbc to do so?

A: "USER" is a reserved word in MySQL and that might be the root cause of the issue. Change the name of the User entity or add @Table annotation to it and define a different name.
Reference documentation:

*

*https://dev.mysql.com/doc/refman/5.7/en/keywords.html

*https://dev.mysql.com/doc/refman/8.0/en/keywords.html


text:
Q: Picking a numerical methods for solving stiff ODE systems with fixed time step. I am currently studying analytical and numerical methods and can't wrap my head around which methods to choose from.
The methods that I have learned so far are:

*

*Forward Euler

*Backward Euler

*Modified Euler

*Trapezoidal method

*Runk Katta schemes

If we were given an ODE system, which methods would I choose to obtain the most accurate solution with a fixed $∆t$?


text:
Q: Interpreting Bias Corrected bootstrapping confidence intervals in logistic regression I have a question about interpreting and using the bias corrected confidence intervals for logistic regression as produced by SPSS. I understand the rationale for using bootstrapping, but want confirmation that the BCa confidence intervals produced by the bootstrapping cannot be used as is but need to be exponentiated in order to obtain the actual confidence intervals. The screen shot below indicates this issue. The original CI is 2.263 - 3.378. In the table below that the estimates from the bootstrapping are provide. The variable remains significant, which means the CI cannot contain the neutral value of 1. The BCa CI indicated is 0.813 - 1.226, which at face value suggests the variable is not significant. However, when I exponentiate the BCa CI I arrive at 2.254-3.407, which excludes the value of 1 and is also similar to the original CI estimates. Am I thus correct in finding the exponent of the BCA supplied values for the bootstrapping CI? Many thanks.

A: You have to be careful to distinguish coefficients in their original scales from coefficients in transformed scales.
Logistic and survival regression models usually do their work in a coefficient scale in which the null hypothesis for a coefficient is a value of 0. That's the scale in which the results for "B," "Bias," and "Std.Error" are reported in your printouts. The BCa CI of 0.813 - 1.226 are well outside the null value of 0 on that scale.
Many find it easier to think about the results in terms of odds ratios (logistic) or hazard ratios (survival). For that you exponentiate the coefficient in its original scale. Thus the null hypothesis of 0 for a coefficient in the original scale becomes a null hypothesis of exp(0) = 1 in the odds-ratio or hazard-ratio scale.
What's confusing in this SPSS output is that the non-bootstrapped results show CI already in the exponentiated scale where the null hypothesis is that the exponentiated coefficient value is 1, while the bootstrapped results report the CI in the original scale, where the null hypothesis is that the original-scale coefficient equals 0.


text:
Q: firestore not updating results I am working with firestore in NodeJS, and wrote the function below, this function receives the results array as a parameter, which contains the firestore doc id that needs to be updated.
So, for each document, i am calling the set method to add the fileName field to this document. But for some reason, the result only updated when i have a single id in this results array.
Can someone help me?
async function update(results, fileName) {

        results.forEach(data => {

          let id = firestore.collection('My_collection').doc(data.DOC_ID)

          id.set(
            { filename: fileName}, {merge:true}
          )
        })
    }

A: You can try by adding a promise to your code.
async function update(results, fileName) {

        results.forEach(data => {

          let id = firestore.collection('My_collection').doc(data.DOC_ID)

          await id.set({ filename: fileName}, {merge:true})
        })
    }

Like shown in the documentation[1]
[1]https://firebase.google.com/docs/firestore/quickstart#add_data


text:
Q: Is this the decorator pattern? I'm using the built-in system class for sending emails in .NET. It's in System.Mail namespace or something like that.
I need to add an interface to this class so I can swap it out for testing or another implementation.
To do this, I just define a class that wraps this built-in class?
Is this an example of the decorator pattern? I'm just a bit confused because the description of the decorator pattern usually states that it is used to add functionality, and I won't be adding any.

A: Well, that sounds just like encapsulation (the wrapper class) and abstraction (the interface).
However, once you have the interface, you could then use the decorator pattern.
Strictly, in decorator usage each layer has the same interface; the decoration is essentially a daisy-chain of different concrete classes that (when implementing the interface) either pass the method to the next link in the chain, or do something bespoke.
(update: I'm not saying you should do it this way - this is just an example of how the decorator pattern might work, in the context of the original e-mail question)
For example, you might have an interface IEmail, a basic implementation BasicEmail (that uses the built-in .NET code), a LoggingEmail that accepts an IEmail, and just passes things along (but logs things as you go), and a ForwardingEmail that accepts an IEmail and changes the To etc (perhaps for dev/test/live purposes).
Then you could have:
`ForwardingEmail` => `LoggingEmail` => `BasicEmail` => (regular .NET classes)

(where the first three are only known as IEmail)
This allows you to extend functionality without changing the API. Very common in factory / IoC setups, and even more so with AOP.

A: No, this is not the decorator pattern, it is the proxy pattern, note: I think Microsoft expects you to make your test class inherit from the SmtpClient class, and implement the Send, AsynchSend etc yourself (in a way that they just write to a text file or whatever -- if you're wanting to plug in a test version).  However if you're wanting to do it the correct way, not the microsoft way, do it the way Marc said.  You will find more and more examples in .NET of interfaces not being there when they should have been.


text:
Q: Why is `api_key` required for GitHub Releases Uploading with Travis? I'm using Travis Enterprise and GitHub Enterprise and I have Travis configured to auto upload assets to my repo based on the instructions here.
My .travis.yml has a section like this and is current working fine:
deploy:
  provider: releases
  file: app.war
  skip_cleanup: true
  on:
    tags: true
  api_key:
    secure: *********

My question is very simply why do I need the api_key section at all since my GHE repo already has a Deploy Key configured with Read/Write access. The Deploy Key gives Travis access to that repo and enables it to retrieve the code and perform the build in the first place. Shouldn't that Deploy Key be sufficient for Travis to also upload assets to Releases section of the repo?

A: TLDR Deploy Keys interact with Git data; OAuth tokens allow API access to interact with GitHub.
A deploy key will grant Travis SSH Git access - read and write - and is scoped to a single repository. This enables SSH interaction with repositories.
The release upload process requires that Travis have an OAuth token to interact with GitHub on your behalf. The GitHub Releases API requires this token as a specific user.