text:
Q: Does DC-powered polarizing film exist? Does anyone know if there is a component or a solution for creating a switchable polarizing film using DC-power? (i.e. a film/glass/substrate/etc that can be switched between a polarizing and a non-polarizing state).
Since this functionality is included in every LCD-screen, I think it has to be possible. The closest solution I can find is smart glass, but they require AC according to my understanding

A: While you can polarize an LCD screen with a DC voltage, if you do not switch polarity of the drive rapidly, you will plate the surface.  This kills the LCD.  So a polarizing film would normally have to be driven with an AC signal, typically a square wave.
This could be as easy as using DC to power a fixed oscillator.  For a normal LCD.
You might want to look at a Boogie Board.  This is a physically changeable LCD with a click reset of crystal.  It is essentially a single LCD pixel.  That company makes an LCD bi-stable display.  It is similar to e-ink, but with LCD technology.  We visited the factor for these in Shenzhen late last year.  They can change pixels then let the hold.  While I don't know if this is DC driven, it is the closes thing to what you are looking for that I have seen.

A: What makes you think that LCDs use DC? DC is bad for liquid crystals- it causes electrolytic action. It's not that it doesn't work, it does, but it will eventually destroy the screen. LCD screens generally have drivers and such on board which generate the complex AC waveforms required for a multiplexed LCD display. A single on/off would only require a panel and some source of AC. For an example of this, see self-darkening welding goggles.
If you want something that works on DC (one polarity for light, swap polarity for dark), you can consider electrochromic  technology.  For example,
http://sageglass.com/technology/faqs/


text:
Q: How many subgroups of order $p^2$ are in $\mathbb{Zp \times Zp \times Zp}$ I have two ideas to develop this problem, the first to use the Euler function, since Zp is cyclic. And the other is to use the canonical projection.
I appreciate your ideas

A: Hint: Your group is a three-dimensional vector space over the $p$-element field. A subgroup of a vector space over such a field is always a vector subspace.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Copy folders and store them in text file to exclude once copied folders on next run I try to write a script that can monitor a folder H:\Start and copy a new subfolder with its files in H:\Start to new location H:\Target. The script should store the copied folder and files in a text file.
Each time the script starts new and monitors H:\Start, it should check the text file and copy only those subfolders which are not yet included in the text file because copied already before.
I was searching the world wide web for examples, but could not really find a starting point. Any help would be nice.
I have so far not working good :)
@echo off
setlocal EnableDelayedExpansion
pushd %1
for /D %%d in ("H:\Start\*.*") do set n=!n!;%%d
if defined n echo %n:~1% > C:\Desktop\list.txt
popd
endlocal
for /f %%i in (C:\Desktop\list.txt) do not (
    xcopy /d /s H:\Start H:\Target > C:\Desktop\list.txt >nul 2>&1
)

A: I suggest using:
%SystemRoot%\System32\xcopy.exe H:\Start H:\Target /C /H /I /K /M /Q /R /S /Y >nul

For information about all those parameters of xcopy open a command prompt window and run there xcopy /? to get help of this command displayed which explains all those parameters.
The important one is /M which selects for copying process just files with archive attribute set and which removes the archive attribute on each file in H:\Start after copying the file. This avoids that a once copied file is copied once more as long as not modified in H:\Start since last copy.
If you want to log all copied files into a text file, I suggest using:
%SystemRoot%\System32\xcopy.exe H:\Start H:\Target /C /F /H /I /K /M /R /S /Y >>C:\Desktop\list.txt

The names of the copied files are with this command line appended to text file C:\Desktop\list.txt

The following commented batch code works with directory lists as asked for.
@echo off
rem Define source and destination directory as well as
rem the names of the used list files each with full path.
setlocal EnableExtensions
set "Source=H:\Start"
set "Destination=H:\Target"
set "MainDirList=C:\Desktop\list.txt"
set "CurrentList=%Temp%\CurrentList.tmp"
set "ExcludeList=%Temp%\ExcludeList.tmp"
set "FinalDoList=%Temp%\FinalDoList.tmp"

rem Write the names of all subdirectories found in source
rem directory into a list file in directory for temporary files.
dir /AD /B "%Source%">"%CurrentList%"

rem Check if list file is not empty because of no subdirectories.
call :CheckEmpty "%CurrentList%"
if %FileIsEmpty% == 1 (
    echo No directories in %Source%
    goto EndBatch
)

rem Start copying the directories if there is no main list file
rem from a previous execution of this batch file or the main list
rem file was deleted intentionally to force copying all again.
if not exist "%MainDirList%" goto CopyDirectories

rem Start copying also if main list file is an empty file.
call :CheckEmpty "%MainDirList%"
if %FileIsEmpty% == 1 del "%MainDirList%" & goto CopyDirectories

rem Search in main list for lines matching completely lines in current
rem list with ignoring case and write the found lines into an exclude
rem list file as those directories were copied already before.
%SystemRoot%\System32\findstr.exe /I /L /X /G:"%CurrentList%" "%MainDirList%" >"%ExcludeList%"

rem Copy all directories if no line in current list is found in main list.
if errorlevel 1 goto CopyDirectories

rem Get all lines from current list not listed also in exclude list.
%SystemRoot%\System32\findstr.exe /B /I /L /V /G:"%ExcludeList%" "%CurrentList%" >"%FinalDoList%"

rem Replace the current list with the reduced final list.
move /Y "%FinalDoList%" "%CurrentList%"

rem Check if remaining current list is not empty because
rem all subdirectories copied already before.
call :CheckEmpty "%CurrentList%"
if %FileIsEmpty% == 1 (
    echo Copied already before all directories in %Source%
    goto EndBatch
)

:CopyDirectories
rem Copy each directory in remaining current list file.
for /F "usebackq delims=" %%D in ("%CurrentList%") do (
    echo Coping %Source%\%%D
    %SystemRoot%\System32\xcopy.exe "%Source%\%%D" "%Destination%\%%D" /C /H /I /K /Q /R /S /Y >nul
)

rem Append the list of copied directories to main list file.
type "%CurrentList%">>"%MainDirList%"
goto EndBatch

:CheckEmpty
rem This little subroutine just checks if size of a list file is 0.
if %~z1 == 0 ( set "FileIsEmpty=1" ) else ( set "FileIsEmpty=0" )
goto:EOF

:EndBatch
rem Delete all not further needed listed files and environment variables.
del "%ExcludeList%" 2>nul
del "%CurrentList%"
endlocal

This batch file should work for the FTP folder mounted as drive on Windows. It does not depend on attributes or timestamps. It uses explicitly only the names of the directories in H:\Start. It also does not check which directories exist already in H:\Target. Therefore it is possible to delete a directory in H:\Target if not interested in and the deleted directory will be nevertheless not copied once again from H:\Start as long as the deleted directory is not also removed from main list file.
For details on parameters used on findstr run in a command prompt window findstr /? and read the entire help output into the window.
Thanks for this question as this was really an interesting batch coding task.

A: You don't need to store anything, you can use
xcopy /d /s h:\start h:\target

/D:mm-dd-yyyy
           Copy files changed on or after the specified date.
           If no date is given, copy only files whose
           source date/time is newer than the destination time.

but if you need a list of the files you can just use a redirection :
xcopy /d /s h:\start h:\target > logfile.txt


text:
Q: Нужна помощь с двойной версией алгоритма поиска чисел в массиве от 2-х до k Дано целое число k > 2. Напечатать все числа из диапазона [2, 3, ..., k], не являющиеся простыми. Показать несколько примеров программы.
Речь идёт о выборке из заданного диапазона нужных нам элементов, а затем - о создании нового массива. Соответственно, мы можем воспользоваться как минимум двумя возможными вариантами логики решения поставленной задачи:
а) Выбираем нужный нам вариант чисел. Пройдя по массиву, проанализируем каждый из его элементов. Выберем только те варианты чисел, что не будут простыми.
б) Отсеиваем из поля данных элементы, которые нас не интересуют. Определим простые числа и уберём их, всё, что останется - и есть искомый результат.
Удобнее будет работать с простыми числами. Формулирую основной принцип-описание для корректного распознавания простого числа:
const Numbers = new Array (2,k);
while (k > 1);
for (var i = 2; i < k; i++);
(k % i == 0);
console.log"Составное число";}}

Пробовала составить варианты а и б полностью. Ни в какую.
Помогите, пожалуйста, решить.
Ещё черновой вариант:
const count = [2, k]; // задаю параметры массива
{count.array: id} // ввожу переменную
const names = ID.map (el => el.id); //назначила формат и имя массива, который хочу получить на выходе
for ID (i = 2; i <= k; i++)
{if (i/2 == 0) {el.id = false}, // проверяю на простые числа
console log(names.indexOf(el));} //возвращаю
console.log(ID.filter(el => el.id > k)); //вывожу результат

A: Оставлю этот вариант здесь:

/** @typedef {number[]} NumType */
// Создадим нужные переменные
/** @type {NumType} */
let beginArr = [];
/** @type {NumType} */
const simple = [];
/** @type {NumType} */
const combo = [];
// Создадим массив до k элементов
const k = 100;
for (let i = 2; i <= k; i++) {
  beginArr.push(i)
}

/** @type {NumType} */
const arrSecond = [ ...beginArr ]; // Для второго варианта

function simpleNumber(nums) {
  const start = nums.splice(0, 1)[0];
  nums = nums.filter(item => {
    if(item % start === 0) {
      combo.push(item);
      return false;
    }
    return true;
  });
  simple.push(start);
  if (nums.length) simpleNumber(nums)
}
// Первый вариант
simpleNumber(beginArr);

console.log('Простые', simple);
console.log('Составные', combo);
// Второй вариант
console.log('Составные 2', arrSecond.filter(it => !simple.includes(it)));

A: Вот так можно получить все делители числа списком (Python). Если длина списка = 1, то число простое. Тогда его не выводим. В противном случае - выводим.
def multiply(number):
    n = 2
    list_multipliers = []
    while number != 1:
        if number % n == 0:
            list_multipliers.append(n)
            number = number / n
        else:
            n += 1
    return list_multipliers

На вход ожидается int, на выходе отдаётся list.
Решение способом А (нужна функция multiply()):
start = int(input())
end = ''
for k in range(2, start):
    if len(multiply(k)) != 1:
        end = end + str(k)
print(end)


text:
Q: Connectedness of Euclidean plane excluding the origin Let $X= \mathbb{R}^2 \setminus \{(0,0)\}$. It is obvious that $X$ is path-connected and thus it is connected.
The definition of connectedness of a set $A$ is stated as follows: there is no pair of open sets $U_1$ and $U_2$ such that

*

*$A \subset U_1 \cup U_2$;

*$A \cap U_1 \neq \emptyset$, $A \cap U_2 \neq \emptyset$; and

*$U_1 \cap U_2 = \emptyset$.

Then, my question is can we prove the connectedness of $X = \mathbb{R}^2 \setminus \{(0,0)\}$ directly by the definition given above?

A: This definition of connectedness is more immediately suited for proving disconnectedness rather than connectedness. Basically, this definition really defines what it means to be disconnected, and then says that something is connected if it is not disconnected. This is very different than path connectedness, where the claim is that for any two points there is a connecting entity, namely a path, between the two points. Such a definition is more immediately suited to proving connectedness. If topological connectedness could be defined, equivalently, in a manner more like path connectedness, by exhibiting a connecting entity, then it would be useful for proving connectedness.
For metric spaces there is such a reformulation of connectedness. A scale on a metric space $X$ is a choice of a positive real number $R_x$ for each point $x\in X$. Given a scale, a walk is a sequence of finitely many points such that for any two adjacent points in the sequence $x,y$, either $d(x,y)\le R_x$ or $d(y,x)\le R_y$. It then holds that $X$ is connected in the topological sense if, and only if, for any two points and any scale on $X$ there exists a walk between these two points.
To obtain a similar characterisation for arbitrary topological spaces use the fact that every topological space is metrisable, provided the metric is allowed to take values in structures more general than the non-negative real numbers (and dropping the requirement that the metric is symmetric). This formalism was developed by Flagg, allowing the metric to take values in a value quantale (Quantales and continuity spaces). This approach was shown to be categorically equivalent to standard topology (A note on the metrizability of spaces). The adaptation of the notion of connectedness from classical metric spaces to Flagg's formalism was done in Metric characterisation of connectedness for topological spaces, where classical connectedness and uniform connectedness are shown to be two instances in a whole hierarchy of notions of connectedness (to which path connectedness does not belong). Among other things, some classical results about connectedness are proved using the new formalism.

A: Assume that there are two such open sets $U_1$, $U_2\subset\dot{\mathbb R}^2$. Then there is a point ${\bf a}\in U_1$ and a point ${\bf b}\in U_2$, and after a small relocation of ${\bf b}$ (if necessary) we may assume that the segment
$$\sigma:\>[0,1]\to{\mathbb R}^2, \qquad t\mapsto(1-t){\bf a}+ t{\bf b}$$
does not hit the origin. Put
$$\tau:=\sup\bigl\{t\in[0,1]\,\bigm|\,\sigma(t)\in U_1\bigr\}\ .$$
Then $0<\tau<1$, since $U_1$ is a neighborhood of ${\bf a}$ and $U_2$ is a neighborhood of ${\bf b}$. I claim that the point ${\bf c}:=\sigma(\tau)$ cannot belong to either one of $U_1$ and $U_2$.
Proof. If ${\bf c}\in U_1$ then $\sigma(\tau+\delta)\in U_1$ for some $\delta>0$, contradicting the definition of $\tau$, and if ${\bf c}\in U_2$ then $\sigma(\tau-h)\in U_2$ for all sufficiently small $h>0$, which contradicts the definition of $\tau$ as well.$\qquad\square$
It follows that there cannot be two such open sets $U_1$ and $U_2$.

A: First a proof of the connectedness of $\Bbb R^2$:
You know that $U$ must be open and closed so assume there is a $x\in U$ and since $U$ is open there is also an open ball around $x$ in $U$. Since $U$ is also closed the boundary circle is also contained in $U$. But any point on the circle has again an open neighborhood in $U$ and by compactness of the circle we know that a bigger open ball around $x$ is contained in $U$.
Now there is no bound for the balls around $x$ hence $U= \Bbb R^2$.
So how can we adopt this to the case of $\Bbb R^2$ with the origin removed? You could use this two show that two points $x,y$ which have closer distance than one oft their length lie in the same component. But by choosing such points carefully you can show that there can be just one component.


text:
Q: Gmail API for sending mails in Node.js Disclaimer:

*

*I have followed Google's own Node.js quickstart guide and successfully connect and use the  gmail.users.labels.list() functionality.

*I have checked for questions/answers here, like this one (that is not using the Node.js API I am asking about), or this one (similar to this one) which apparently is the same problem I have but the solution does not work.

My problem:
When using Google's Node.js API I get a error trying to send a email. The error is:
{
    "code": 403,
    "errors": [{
        "domain": "global",
        "reason": "insufficientPermissions",
        "message": "Insufficient Permission"
    }]
}

My setup:
fs.readFile(secretlocation, function processClientSecrets(err, content) {
    if (err) {
        console.log('Error loading client secret file: ' + err);
        return;
    }
    authorize(JSON.parse(content), sendMessage);
});

function sendMessage(auth) {
    var raw = makeBody('myrealmail@gmail.com', 'myrealmail@gmail.com', 'subject', 'message test');
    gmail.users.messages.send({
        auth: auth,
        userId: 'me',
        message: {
            raw: raw
        }
    }, function(err, response) {
        res.send(err || response)
    });
}

The function processClientSecrets is from the Google guide i mentioned above. It reads my .json file that has my access_token and refresh_token. The makeBody function is a to make a encoded body message.
In the config variabels I have also:
var SCOPES = [
    'https://mail.google.com/',
    'https://www.googleapis.com/auth/gmail.modify',
    'https://www.googleapis.com/auth/gmail.compose',
    'https://www.googleapis.com/auth/gmail.send'
];

Why it should work:

*

*the authorization process works for the gmail.users.labels.list() method.

*the message body I'm testing works if I test it at Google's test page.

My question:
Is my setup wrong? Have there been changes in the API? What am I missing?

A: So for anyone looking at this trying to get a test email sent from their API but cant get this work heres what you gotta do:
Step 1:
Replace the
var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];

with this:
var SCOPES = [
    'https://mail.google.com/',
    'https://www.googleapis.com/auth/gmail.modify',
    'https://www.googleapis.com/auth/gmail.compose',
    'https://www.googleapis.com/auth/gmail.send'
];

Step 2:
At the end of googles sample code add this:
function makeBody(to, from, subject, message) {
    var str = ["Content-Type: text/plain; charset=\"UTF-8\"\n",
        "MIME-Version: 1.0\n",
        "Content-Transfer-Encoding: 7bit\n",
        "to: ", to, "\n",
        "from: ", from, "\n",
        "subject: ", subject, "\n\n",
        message
    ].join('');

    var encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
        return encodedMail;
}

function sendMessage(auth) {
    var raw = makeBody('Receiverofyouremail@mail.com', 'whereyouaresendingstufffrom@gmail.com', 'This is your subject', 'I got this working finally!!!');
    const gmail = google.gmail({version: 'v1', auth});
    gmail.users.messages.send({
        auth: auth,
        userId: 'me',
        resource: {
            raw: raw
        }

    }, function(err, response) {
        return(err || response)
    });
}

fs.readFile('credentials.json', function processClientSecrets(err, content) {
    if (err) {
        console.log('Error loading client secret file: ' + err);
        return;
    }
    // Authorize a client with the loaded credentials, then call the
    // Gmail API.
    authorize(JSON.parse(content), sendMessage);
});

Step 3(Optional)
Delete this line:
authorize(JSON.parse(content), listLabels);

And these:
/**
 * Lists the labels in the user's account.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
 function listLabels(auth) {
   const gmail = google.gmail({version: 'v1', auth});
   gmail.users.labels.list({
     userId: 'me',
   }, (err, res) => {
     if (err) return console.log('The API returned an error: ' + err);
     const labels = res.data.labels;
     if (labels.length) {
       console.log('Labels:');
       labels.forEach((label) => {
         console.log(`- ${label.name}`);
       });
     } else {
       console.log('No labels found.');
     }
   });
 }

(So you don't get the random labels in your console)

A: Ok, so I found the problem(s).
Problem #1
While following the Node.js quickstart guide the example in that tutorial has
var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];

And when I got the .json that looks like:
{
    "access_token": "xxx_a_long_secret_string_i_hided_xxx",
    "token_type": "Bearer",
    "refresh_token": "xxx_a_token_i_hided_xxx",
    "expiry_date": 1451721044161
}

those tokens where produced taking into account only the auth/gmail.readonly scope in the tutorial code.
So I deleted the first .json, added the scopes from my final scope array (i posted in the question) and ran the tutorial setup again, receiving a new token.
Problem #2
In the object passed to the API I was sending:
{
    auth: auth,
    userId: 'me',
    message: {
        raw: raw
    }
}

but that is wrong, message key should be called resource.

Final setup:
This is what I added to the tutorial's code:
function makeBody(to, from, subject, message) {
    var str = ["Content-Type: text/plain; charset=\"UTF-8\"\n",
        "MIME-Version: 1.0\n",
        "Content-Transfer-Encoding: 7bit\n",
        "to: ", to, "\n",
        "from: ", from, "\n",
        "subject: ", subject, "\n\n",
        message
    ].join('');

    var encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
        return encodedMail;
}

function sendMessage(auth) {
    var raw = makeBody('myrealemail@gmail.com', 'myrealemail@gmail.com', 'test subject', 'test message');
    gmail.users.messages.send({
        auth: auth,
        userId: 'me',
        resource: {
            raw: raw
        }
    }, function(err, response) {
        res.send(err || response)
    });
}

And call everything with:
fs.readFile(secretlocation, function processClientSecrets(err, content) {
    if (err) {
        console.log('Error loading client secret file: ' + err);
        return;
    }
    // Authorize a client with the loaded credentials, then call the
    // Gmail API.
    authorize(JSON.parse(content), sendMessage);
});


text:
Q: Meteor app suddenly no longer runs on iOS My Meteor-based app no longer works as designed on iOS, without me having changed anything relevant. The app still works when run from a local server (http://localhost:3000) as well as when hosted at meteor.com. But, in an iOS simulator and when deployed to an iOS device through xCode, the app fails to run properly.
The app opens with a form that needs to be filled in by the user. When submitting the form, on iOS, the entered values briefly are stored in session variables, but almost immediately the session variables are emptied and the form is displayed again. (What should happen is for an external JSON file to be loaded, based on the form values, after which the contents of that JSON file is manipulated and displayed.)
I just now upgraded to the latest version of Meteor, and xCode did an upgrade itself in the background.
The app is supposed to load a Google font file (from fonts.googleapis.com), but though this works fine when the app is served from either the localhost or meteor, the font does not appear to be loaded when the app runs on iOS.
I'm sorry I don't have actual example code (the whole app?) or a running version of the app that I can show you. As the app is not yet publicly available, I'm a bit reluctant to publish it here. :(
Is there a way to meaningfully debug a Meteor app running on iOS? Is there something obvious I'm missing in the deployment?

A: Turns out there's an issue with meteor 1.0.4 and building a project using Cordova (https://github.com/meteor/meteor/issues/3814).
I downgraded to meteor 1.0.3 through:
meteor update --release 1.0.3

Then, I deleted the Cordova folder in .meteor/local/ with
rm -R cordova-build

Then, I patched 1.0.3 to 1.0.3.2 with
meteor update --patch

This solved the problem.


text:
Q: phpexcel - comments misplaced in xlsx 2010 workbook When I modify a comment in an excel workbook (2010, 2013) created by PHPEXCEL, the comment is presented at the very top of the sheet. The same appears with the phpexcel example's script 05featuredemo.inc.
I'd like the comment to stay closed to the related cell. To do this, before modifying the comment, I must first change the alignment of the cell. Doing this it works. Another solution is to copy the sheet to a new workbook.

A: In the source code ...writer/Excel2007/Comments.php the following line (line 253) is desactivated :
//$objWriter->writeElement('x:Anchor', $column . ', 15, ' . ($row - 2) . ', 10, ' . ($column + 4) . ', 15, ' . ($row + 5) . ', 18');
The solution to my problem is to reactivate this line of code.
Now the comments are staying closed to their cells when i modify them and no more displayed at the top of the sheet.
But there is a new problem : the sizing of the comment that i do in my phpexcel program doesn't work. The solution is to modify the Comments.php source code like this :
$objWriter->writeElement('x:Anchor', $column . ', 15, ' . ($row - 2) . ', 10, ' . ($column + $pComment->getWidth()) . ', 15, ' . ($row + $pComment->getHeight()) . ', 18');
The Width and Height are respectively a number of cols and a number of rows. So in my program, The Width and Height are no more like "100pt" but a number of cols and a number of rows :
                    $objPHPExcel->getActiveSheet()->getComment($col)->setWidth('15');                   $objPHPExcel->getActiveSheet()->getComment($col)->setHeight('20');
Doing this it works. I just have to modify my code to determine the size of the comments in number of cols and rows.
Question : could this problem be resolved in next version of phpexcel ?


text:
Q: electron js how to call a function rendered in index I'm going crazy to be able to call a function that I have rendered in an index and then execute that function with globalShortcut, I was researching and found that IPC could perform, but all the examples are to use functions from the main and not from the index. any idea that can guide me

A: I assume you have nodeIntegration set to true and contextIsolation set to false, as advised by the Electron documentation. To trigger a function in your renderer process from the main thread you can use ipcMain and ipcRenderer (these modules are part of Electron).
First, you need to expose an API for the renderer using contextBridge. This can be done with a preload.js file that has access to all modules like the main thread.
Example:
main.js
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');

function createMainWindow(){
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            enableRemoteModule: false,
            preload: path.join(__dirname, 'preload.js'),
        },
    });
}

app.on('ready', () => {
    createMainWindow();
});

preload.js
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('api', {
    send: (channel, data) => {
        // Whitelist channels
        let validChannels = ['toMain'];
        if (validChannels.includes(channel)) {
            ipcRenderer.send(channel, data);
        }
    },
    receive: (channel, func) => {
        let validChannels = ['fromMain'];
        if (validChannels.includes(channel)) {
            // Deliberately strip event as it includes `sender`
            ipcRenderer.on(channel, (event, ...args) => func(...args));
        }
    },
});

Then, in your renderer process you can use window.api.send(channel, parameters); to send messages to the main thread and window.api.receive(channel, parameters); to listen for incoming ones. Similarly, you would use ipcMain.on(channel, (event, parameters) => { }); in the main process to handle messages from the renderer. However, to directly send messages to it, you have to use webContents, like so: mainWindow.webContents.send(channel, parameters);.
In your case, to execute a function in the renderer, you would call mainWindow.webContents.send('fromMain', 'trigger-function'); in the main process; and listen for this event in your renderer like so:
window.api.receive('fromMain', (parameters) => {
    if (parameters === 'trigger-function'){
        // Call your renderer function here
    }
});


text:
Q: Menu is not showing after upgrading 1.9.2.4 to 1.9.4.5 I upgraded Magento 1.9.2.4 to  1.9.4.5. After upgrading, top menu is not showing

Another issue is some images are missing. I copied all Media files properly. Now its showing magento placeholder
Now media path is
/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/images/catalog/product/placeholder/image.jpg
Before it was
media/catalog/product/cache/1/thumbnail/175x175/9df78eab33525d08d6e5fb8d27136e95/2/_/2_hpbm_3292a_plan_ff.jpg
Deleted cache and tried Reindex option in Index managament. But no luck.


text:
Q: C++ - Copy Assignment Operator is Implicitly Deleted I'm trying to use copy assignment in the following case.
There're two template classes, list map and xpair.
template <typename Key, typename Value, class Less=xless<Key>>
class listmap {
public:
   using key_type = Key;
   using mapped_type = Value;
   using value_type = xpair<const key_type, mapped_type>;     //value_type
...
}

template <typename First, typename Second>
struct xpair {
   First first{};
   Second second{};
   xpair(){}
   xpair (const First& first, const Second& second):
           first(first), second(second) {}
};

In the main.cpp, I tried to write,
using commend = string;
using str_str_map = listmap<string,string>;
using str_str_pair = str_str_map::value_type;    //value_type, to be replaced
using commend_pair = xpair<commend, str_str_pair>;

int main(...) {
   commend_pair cmd_pair;
   str_str_pair newPair ("Key", "value");
   cmd_pair.second = newPair;

   ...
}

It gives me an error saying
  object of type 'xpair<const std::__1::basic_string<char>,
  std::__1::basic_string<char> >' cannot be assigned because its copy
  assignment operator is implicitly deleted

If I replace
using str_str_pair = str_str_map::value_type;

to
using str_str_pair = xpair<string, string>;

Everything works fine. Why is that? Shouldn't value_type = xpair<string, string>?

A: You have
using value_type = xpair<const key_type, mapped_type>;

Since you are using a const key_type you are no longer able to assign to it since key_type is const.
using str_str_pair = xpair<string, string>;

Works as neither string is const

A: I don't see where newPair is declared, but the error message seems like enough.
Why this fails: If either element in the pair is const, the assignment operator for that element is itself deleted.  You couldn't assign to a const string but that's exactly what you're asking it to do when you assign to pair<const string, T>.  To simplify the example
std::pair<const int, int> p(0, 0);
p.first = 1; // no, can't assign to p.first
p = std::pair<const int, int>(1, 2); // no, requires assigning to p.first

Why maps have const key types: map containers organize their elements based of the keys. If you changed a key, the map wouldn't be able to find it anymore.  Consider:
std::map<string, int> m = { ... };
auto it = m.find(k);
it->first = "a different value";

Since a std::map for example, is internally organized as a red-black tree, changing the key safely would require a reorganization of the node. However in this example you're operating directly on the pair in the node. Changing the key would require removing the pair from m, then putting it back in with a changed key.


text:
Q: PHP export MySQL to csv for app inventor When I try to export MySQL table to csv (use php) and make it a list in app inventor, but the list doesn't show.
My Block :

My php file :
if ($result = mysqli_query($dbc, "SHOW COLOMNS FROM Absent")){

$numberOfRows = mysqli_num_rows($result);
}
if($numberOfRows > 0) {
$values = mysqli_query($dbc, "SELECT full_name FROM Absent");
while($rowr = mysqli_fetch_row($values)){
for($j=0; $j<$numberOfRows; $j++) {
$csv_output .=$rowr [$j]. " ,";
}
$csv_output .= "\n";
}
}
print $csv_output;
exit;

A: Try to export to csv using mysql native method, for example:
SELECT id, name, email INTO OUTFILE '/tmp/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM users WHERE 1

A: i don't know much about app-inventor, but as for the sql queries:

*

*the first table is "CUSTOMER", your second is: "Absent", is it a typo?
(your'e iterating your "Absent" row with the number of columns you're getting from "CUSTOMER", was that your intention?)

*your "$rowr" var has only 1 column ("full_name"), so you could easily:
drop the "for loop", to:
$csv_output .=$rowr [0];
P.S.
an alternative way of coding that in php would be:
$result = mysqli_query($dbc, "SELECT column1, column2, column3 FROM Absent");

while ($row = mysqli_fetch_assoc($result))
{
   $comma = "";
   foreach(  $row as $key=>$value )
   {
       $csv_output .= $comma . $value;
       $comma = ", ";
   }
   $csv_output .= "\n";
}

print $csv_output;
exit;


text:
Q: CSS Hover: Bold changing element size with padding Alright, of course I understand why this is happening, I'm just hoping there's some creative solution.  Let's say I have this element:
.element {
    padding:0 1px;
}
.element:hover {
    font-weight:bold;
}

It's crucial that the padding be in place for visual consistency, but is there some magical way I'm not aware of to lock the element's width down before engaging in the hover behavior?
No JavaScript allowed, unfortunately.
JsFiddle:
http://jsfiddle.net/M9V3Q/
More Info
The client is extremely specific about what they want on certain parts of the site, and the nav is one of them, much to my frustration. They insist on hover being black text on a dark shade of red used in their logo, and they want the buttons to be centered. Since different browsers render text differently, the only way to create a consistent look is to use padding to create the width. Unfortunately, with normal font weight the black is very difficult to read.

A: You can use this approach:
#hoverEle {
    width: 100px;
}

#hoverEle {
    display:inline-block;
    border:1px solid black;
    padding:3px;
    text-align: center;
}
#hoverEle:hover {
    font-weight:bold;
}

Fiddle: http://jsfiddle.net/M9V3Q/4/
Cons is fixed width.
By the way, I think it is bad idea to focus buttons like this. More beautifull for user will be simple color change (e.g. #ccc) and, probably, transition effect. I think it is much more better.
Try this fiddle: http://jsfiddle.net/M9V3Q/9/
I think it is much more beautifull even in this variant :)

A: Try something like:
.element {
    padding: 0 1px;
    border: 2px solid transparent;
}
.element:hover {
    font-weight: bold;
    border: none;
}

A fiddle: http://jsfiddle.net/F4knz/

A: Could always try CSS3 box-sizing. It cuts into the elements width etc for padding, border..., and so prevents the element from expanding outside its set width.
Need to prefix -moz- or -webkit- for Firefox and safari.


text:
Q: hebrew characters from txt file does not display on word after compile to JAR file using spire.doc.jar I write in java code with spire.doc.jar that use BufferedReader to take some words from txt file and display it on word document at the end,
this is how it read the txt file:
BufferedReader abc = new BufferedReader(new FileReader("carNumbers.txt"));

everything works well but when I export my all code into jar file and run it in CMD
the word document come out with wired characters, instead of hebrew:

*

*הריני לאשר בזאת

i get:
�׳™׳×׳•׳¨ ׳•׳©׳�׳™׳˜
hebrew words that gets added to the word file with finalText.appendText like that:
finalText.appendText(",בכבוד רב" );

gets added to the word doc just fine
what i need to do to fix that please?

A: I fix that by changing this:
BufferedReader abc = new BufferedReader(new FileReader("carNumbers.txt"));

to this
BufferedReader abc = new BufferedReader(new InputStreamReader
    (new FileInputStream("carNumbers.txt"),"UTF-8"));


text:
Q: "Key vault reference error" in azure web app configuration setting I have a private certificate that was generated by azure for a web app for linux containers.  I want to pass this value to my .net core app via the web app configuration settings in the the azure portal.  This is part of a pipeline CI-CD process and the ability to specify Identity Server key values in app configuration helps to keep those values out of the source code.
PROBLEM
I keep getting the following error by the setting

❌Key vault Reference

also shown here:

I am trying to use the secret value in the format suggested by the microsoft docs here
I have tried the following formats:
@Microsoft.KeyVault(https://myvault.vault.azure.net/secrets/myCertName/versionGUID)

@Microsoft.KeyVault(VaultName=myvault;SecretName=myCertName;SecretVersion=versionGUID)

ALSO, I have added the web app to the access policies of the azure key vault
EDIT 1:
There was a format error and I had the wrong secret name so the following format worked:
@Microsoft.KeyVault(https://myvault.vault.azure.net/secrets/myCertName/versionGUID)

However I ran into a new error:

Key Vault reference was not able to be resolved because site Managed
Identity not enabled  MSINotEnabled

SO I went to the identity tab of the web app and turned on managed identity for the app.
I am now stuck with the following error:

Key Vault reference was not able to be resolved because site was
denied access to Key Vault reference's vault.

I found multiple sites that said if you just deleted the setting, saved, and then add the setting back it should resolve.  This DID NOT work for me.
I also tried granting "Full access" to the web app in the azure key vault access policies.

A: Your app should be able to reach the Key Vault to resolve a reference successfully. If everything else, e.g., access policies and syntax, appears to be in order and yet your references don't resolve, try checking if your Key Vault has any network restriction.
If you see the warning related to the 'network access control' on your Vault's Access policies settings page, you need to allow your app's IP through the Key Vault firewall.

Add your app's IP (available under Custom domains) to your Key Vault's firewall (under Networking).

Reference: https://medium.com/geekculture/troubleshooting-azure-key-vault-references-in-azure-function-apps-b228c1216f63

A: Firstly, the reference format @Microsoft.KeyVault(https://myvault.vault.azure.net/secrets/myCertName/versionGUID) is wrong, it should be @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/myCertName/versionGUID).
Secondly, I don't think you granted the permission for the MSI of your web app correctly.
From the description in your original post:

ALSO, I have added the web app to the access policies of the azure key vault

Then in your EDIT 1:

SO I went to the identity tab of the web app and turned on managed identity for the app.

Obviously the order is wrong, if you didn't enable the MSI of the app before, how you add it to the access policy? I suppose you may added the wrong one.
So in your case, make sure you have added the MSI of the web app to the access policy correctly.
1.Navigate to the web app -> Identity -> copy the Object ID(also make sure you are using system-assigned MSI, the user-assigned MSI is not supported in keyvault reference feature)

2.Then in the Access policies of the keyvault -> Add Access Policy -> seacrh for the Object ID in step 1 and add it with the Get Secret permission like below -> select and save.

3.Navigate to the app and check it, it works fine.

A: If it is a User-Managed Identity, we need to do a patch to make this working
userAssignedIdentityResourceId=$(az identity show -g MyResourceGroupName -n MyUserAssignedIdentityName --query id -o tsv)
appResourceId=$(az webapp show -g MyResourceGroupName -n MyAppName --query id -o tsv)
az rest --method PATCH --uri "${appResourceId}?api-version=2021-01-01" --body "{'properties':{'keyVaultReferenceIdentity':'${userAssignedIdentityResourceId}'}}"

Link for the doc

A: I am facing the same issue while creating resources through terraform.
I have added a key vault access policy for azure function app as well and the issue is gone.
The below part is only for those who are doing terraform.
My config looked like this,
resource "azurerm_key_vault_access_policy" "resource_group_manager" {
    key_vault_id = module.key_vault_info.key_vault_id
    tenant_id = data.azurerm_client_config.current.tenant_id
    object_id = data.azuread_group.manager.id
    key_permissions = [ "Get", "List", "Create", "Update", "Delete", ]
    secret_permissions = [ "Get", "List", "Set", "Delete", ]
}

I have added a key vault access policy only for the azure resource group
but not for azure function.
To resolve that,
I have added a key vault access policy for azure function app as well
like below,
resource "azurerm_key_vault_access_policy" "resource_group_manager" {
    key_vault_id = module.key_vault_info.key_vault_id
    tenant_id = data.azurerm_client_config.current.tenant_id
    object_id = data.azuread_group.manager.id
    key_permissions = [ "Get", "List", "Create", "Update", "Delete", ]
    secret_permissions = [ "Get", "List", "Set", "Delete", ]
}

resource "azurerm_key_vault_access_policy" "this" {
    key_vault_id = module.key_vault_info.key_vault_id
    tenant_id = data.azurerm_client_config.current.tenant_id
    object_id = azurerm_function_app.this.identity.0.principal_id
    key_permissions = [ "Get", "List", "Create", "Update", "Delete", ]
    secret_permissions = [ "Get", "List", "Set", "Delete", ]
}


text:
Q: Prevent duplicated form submission MVC 4 I know this has been asked several times may be, but most (if not all) solutions I've seen were involving a javascript solution or disabling form/submit button, which I'm not preferring.
I have couple of huge forms that may take some time to complete submission which may let the user to re-submit many times during the first submission, which eventually will cause for many records in the database.
Proposed solution:
A proposed solution is to have a generic method that have an array including all submitted forms IDs, each time a user submit a form, it's ID will be added to that array if it's not already existed, after the submit complete the ID will be popped out the array. A drawback can be counted on this solution in case a user opened two or more pages of the same form and submit them synchronously, but that can be worried about later.
My question is how feasible is my proposed solution and how good it can be? and how can I implement that generic method?
I understand that Apache Struts 2  framework has some solution to prevent such thing (Token Interceptor), how to do that in MVC 4?:

A: Just add a GUID field to the ViewModel the view is bound to (You are using ViewModels right?) and every time the empty form is asked for, generate a new GUID (solves the issue of downloading two or more copies by same user) for it and have it included in the view as a hidden field (string representation of it). Then you can implement the array solution you are talking about in a session variable or even a database based solution in which all processed GUIDs are saved in a table that gets cleared every so often, a text file that contains the list of GUIDs, etc. kind of hard to pick a complete solution based on just what you provide. But the above should provide you with all the requirements you have outlined.


text:
Q: Docker publish not working correctly for golang application I am trying to run a golang web server application (which tries to run a go blog powered by same tools which power golang blog) via docker. It runs fine without docker but fails to give any response if I use docker. I have no clue why this is happening as for a much simpler go web application, the same docker based approach works great. See below for output of various commands I used. Any help would be greatly appreciated.
docker pull maddyonline/gotutorial
docker run -d --publish 8080:8080 --name gotut maddyonline/gotutorial

81bc36e385286326a6d9f74322515a7b9748e493275c3426bcc6848a4589a7e7

docker ps

CONTAINER ID        IMAGE                    COMMAND
  CREATED             STATUS              PORTS                    NAMES
  81bc36e38528        maddyonline/gotutorial   "go-wrapper run"    20
  seconds ago      Up 20 seconds       0.0.0.0:8080->8080/tcp   gotut

curl localhost:8080

curl: (52) Empty reply from server

docker exec gotut curl localhost:8080

<!DOCTYPE html>
<html>
<head>

And rest of the file

The docker file I am using is very simple.
FROM golang:onbuild
EXPOSE 8080

I experimented with the same docker file with a much simpler golang application on the same server. And it works.
docker pull maddyonline/gowebapp
docker run -d --publish 8080:8080 --name gowebapp maddyonline/gowebapp
curl localhost:8080/icecream

Hi there, I think I love icecream!

A: I found two issues with your current code.
The first is that the string localhost in your main.go needs to be 0.0.0.0. The problem is that you've told your webserver to only serve requests sent to localhost. Because of the network mangling that Docker does, none of the traffic showing up to your webserver look to the webserver as though they were sent to localhost. By telling your webserver to listen on 0.0.0.0 you're effectively telling it that it doesn't care where the traffic was originally sent and it will accept it all.
var (
    httpFlag   = flag.String("http", "0.0.0.0:8080", "HTTP listen address") // <--- Here it the change. It's roughly line 25 of [main.go](https://github.com/maddyonline/gotutorial/blob/master/main.go#L25)
    originFlag = flag.String("origin", "", "web socket origin for Go Playground (e.g. localhost)")
    baseFlag   = flag.String("base", "", "base path for articles and resources")
)

The second issue has to due with your import paths colliding with the predetermined directory structure of the onbuild Dockerfile from which you were extending. I saw that you were trying to hardcode the import path, which is not a good idea, but I think it was your only option due to the weirdness of the go-wrapper that was being forced onto you by the onbuild Dockerfile. Ultimately you should just have the docker build process stick a static Go binary in that container. That will simplify the process of actually starting up the server in the container.
I didn't mess with your paths in your Go code, I figured you could work that out, but I did grab the upstream onbuild Dockerfile and customize it to what you need. BTW, if you look at the documentation for the onbuild Dockerfile it actually says that it's a bad idea to use that Dockerfile. ;) So, I took their advice and here is my port:
FROM golang:1.4.2

RUN mkdir -p /go/src/github.com/maddyonline/gotutorial
WORKDIR      /go/src/github.com/maddyonline/gotutorial

ADD . /go/src/github.com/maddyonline/gotutorial
RUN go-wrapper download
RUN go-wrapper install

EXPOSE 8080
CMD ["go-wrapper", "run"]

Your other sample server app didn't have the same issues because the import paths weren't specified in the same way they are in this project. Basically, it didn't care where it was living because its dependencies were not being hardcoded to a file path. It is using the normal Go packaging conventions.
Sorry, it probably seems like a lot of change, but I hope it at least helps you move forward on your project. Let me know if anything doesn't make sense.


text:
Q: javax.net.ssl.SSLException: SSLEngine closed already SSLEngine closed already in webclient (Springboot) I am using webclient in springboot application to call a external restful webservice.
getting this exception intermittently.
javax.net.ssl.SSLException: SSLEngine closed already SSLEngine closed already

I see below warning in logs before getting this exception.
javax.net.ssl.SSLException:
   at io.netty.handler.ssl.SslHandler.wrap (SslHandler.java854)
   at io.netty.handler.ssl.SslHandler.wrapAndFlush (SslHandler.java811)
   at io.netty.handler.ssl.SslHandler.flush (SslHandler.java792)
   at io.netty.channel.AbstractChannelHandlerContext.invokeFlush0 (AbstractChannelHandlerContext.java750)
   at io.netty.channel.AbstractChannelHandlerContext.invokeFlush (AbstractChannelHandlerContext.java742)
   at io.netty.channel.AbstractChannelHandlerContext.flush (AbstractChannelHandlerContext.java728)
   at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.flush (CombinedChannelDuplexHandler.java531)
   at io.netty.channel.ChannelOutboundHandlerAdapter.flush (ChannelOutboundHandlerAdapter.java125)
   at io.netty.channel.CombinedChannelDuplexHandler.flush (CombinedChannelDuplexHandler.java356)
   at io.netty.channel.AbstractChannelHandlerContext.invokeFlush0 (AbstractChannelHandlerContext.java750)
   at io.netty.channel.AbstractChannelHandlerContext.invokeWriteAndFlush (AbstractChannelHandlerContext.java765)
   at io.netty.channel.AbstractChannelHandlerContext.write (AbstractChannelHandlerContext.java790)
   at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush (AbstractChannelHandlerContext.java758)
   at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush (AbstractChannelHandlerContext.java808)
   at io.netty.channel.DefaultChannelPipeline.writeAndFlush (DefaultChannelPipeline.java1025)
   at io.netty.channel.AbstractChannel.writeAndFlush (AbstractChannel.java294)
   at reactor.netty.http.HttpOperations.lambda$send$0 (HttpOperations.java123)
   at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext (MonoFlatMap.java118)
   at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext (FluxMapFuseable.java121)
   at reactor.core.publisher.FluxContextStart$ContextStartSubscriber.onNext (FluxContextStart.java96)
   at reactor.core.publisher.Operators$ScalarSubscription.request (Operators.java2344)
   at reactor.core.publisher.FluxContextStart$ContextStartSubscriber.request (FluxContextStart.java125)
   at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.request (FluxMapFuseable.java162)
   at reactor.core.publisher.MonoFlatMap$FlatMapMain.onSubscribe (MonoFlatMap.java103)
   at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onSubscribe (FluxMapFuseable.java90)
   at reactor.core.publisher.FluxContextStart$ContextStartSubscriber.onSubscribe (FluxContextStart.java90)
   at reactor.core.publisher.MonoJust.subscribe (MonoJust.java54)
   at reactor.core.publisher.Mono.subscribe (Mono.java4213)
   at reactor.core.publisher.FluxConcatIterable$ConcatIterableSubscriber.onComplete (FluxConcatIterable.java146)
   at reactor.core.publisher.FluxConcatIterable.subscribe (FluxConcatIterable.java60)
   at reactor.core.publisher.MonoFromFluxOperator.subscribe (MonoFromFluxOperator.java81)
   at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext (MonoFlatMap.java150)
   at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onNext (FluxSwitchIfEmpty.java67)
   at reactor.core.publisher.Operators$MonoSubscriber.complete (Operators.java1782)
   at reactor.core.publisher.MonoSingle$SingleSubscriber.onComplete (MonoSingle.java171)
   at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onComplete (FluxMapFuseable.java144)
   at reactor.core.publisher.FluxJust$WeakScalarSubscription.request (FluxJust.java101)
   at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.request (FluxMapFuseable.java162)
   at reactor.core.publisher.MonoSingle$SingleSubscriber.request (MonoSingle.java94)
   at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.set (Operators.java2152)
   at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onSubscribe (Operators.java2026)
   at reactor.core.publisher.MonoSingle$SingleSubscriber.onSubscribe (MonoSingle.java114)
   at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onSubscribe (FluxMapFuseable.java90)
   at reactor.core.publisher.FluxJust.subscribe (FluxJust.java70)
   at reactor.core.publisher.InternalMonoOperator.subscribe (InternalMonoOperator.java64)
   at reactor.core.publisher.MonoDefer.subscribe (MonoDefer.java52)
   at reactor.netty.http.client.HttpClientConnect$HttpIOHandlerObserver.onStateChange (HttpClientConnect.java442)
   at reactor.netty.ReactorNetty$CompositeConnectionObserver.onStateChange (ReactorNetty.java518)
   at reactor.netty.resources.PooledConnectionProvider$DisposableAcquire.run (PooledConnectionProvider.java633)
   at io.netty.util.concurrent.AbstractEventExecutor.safeExecute (AbstractEventExecutor.java164)
   at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks (SingleThreadEventExecutor.java472)
   at io.netty.channel.nio.NioEventLoop.run (NioEventLoop.java500)
   at io.netty.util.concurrent.SingleThreadEventExecutor$4.run (SingleThreadEventExecutor.java989)
   at io.netty.util.internal.ThreadExecutorMap$2.run (ThreadExecutorMap.java74)
   at io.netty.util.concurrent.FastThreadLocalRunnable.run (FastThreadLocalRunnable.java30)
   at java.lang.Thread.run (Thread.java748)

here is full stack trace :
reactor.core.Exceptions$ReactiveException:
       at reactor.core.Exceptions.propagate (Exceptions.java393)
       at reactor.core.publisher.BlockingSingleSubscriber.blockingGet (BlockingSingleSubscriber.java97)
       at reactor.core.publisher.Mono.block (Mono.java1680)
       at .service.CustomWebClient.callTarget (CustomWebClient.java48)
       at .service.MessageServiceImpl.sendMessageToTargetGetAcknowledgement (MessageServiceImpl.java101)
       at .service.MessageServiceImpl.transferMessagesFromSourceToTarget (MessageServiceImpl.java53)
       at .controller.MessageController.processMessageFromSourceThread3 (MessageController.java71)
       at .controller.MessageController$$FastClassBySpringCGLIB$$c25da1d1.invoke (<generated>)
       at org.springframework.cglib.proxy.MethodProxy.invoke (MethodProxy.java218)
       at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint (CglibAopProxy.java771)
       at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (ReflectiveMethodInvocation.java163)
       at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed (CglibAopProxy.java749)
       at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction (TransactionAspectSupport.java367)
       at org.springframework.transaction.interceptor.TransactionInterceptor.invoke (TransactionInterceptor.java118)
       at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (ReflectiveMethodInvocation.java186)
       at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed (CglibAopProxy.java749)
       at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept (CglibAopProxy.java691)
       at .controller.MessageController$$EnhancerBySpringCGLIB$$7a54eddc.processMessageFromSourceThread3 (<generated>)
       at sun.reflect.GeneratedMethodAccessor63.invoke
       at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java43)
       at java.lang.reflect.Method.invoke (Method.java498)
       at org.springframework.scheduling.support.ScheduledMethodRunnable.run (ScheduledMethodRunnable.java84)
       at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run (DelegatingErrorHandlingRunnable.java54)
       at java.util.concurrent.Executors$RunnableAdapter.call (Executors.java511)
       at java.util.concurrent.FutureTask.runAndReset (FutureTask.java308)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301 (ScheduledThreadPoolExecutor.java180)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run (ScheduledThreadPoolExecutor.java294)
       at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java1149)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java624)
       at java.lang.Thread.run (Thread.java748)
    Inner exception javax.net.ssl.SSLException handled at reactor.core.Exceptions.propagate:
       at io.netty.handler.ssl.SslHandler.wrap (SslHandler.java854)

here is MessageServiceImpl.java
package service;
import org.hibernate.exception.SQLGrammarException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;

@Service
public class MessageServiceImpl implements MessageService {

  private static final Logger LOGGER = LoggerFactory.getLogger(MessageServiceImpl.class);

  @Autowired
  private MessageRepository repository;

  @Value("${TARGET_ENDPOINT}")
  private String baseEndPoint;

  @Autowired
  private CustomWebClient webClient;

  public Message transferMessagesFromSourceToTarget()
       {

    Message message = new Message();
    try {

      message = getMessageFromSource();
      //some code....

      sendAcknowledgementToSource(message);
      //some code....

    } catch (HttpServerErrorException | HttpClientErrorException e) {
      //somecode

    } catch (InvalidDataAccessResourceUsageException | SQLGrammarException  e) {
      //somecode
    }

    return message;

  }

  private Message getMessageFromSource() {
    return repository.getSourceMessageFromStroredProcedureCall();
  }

  private Message sendMessageToTargetGetAcknowledgement(Message message) {

    ResponseEntity<String> response = null;

    response = webClient.callTarget(baseEndPoint+ message.getHostURL(),message);

    message.setHttpStatus(response.getStatusCodeValue());

    return message;
  }

}

here is CustomWebClient component class
package service;

import XYZ.model.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/
@Component
public class CustomWebClient {

  private final WebClient webClient;

  /**
   * Constructor to autowire WebClient instance
   * @param webClient webclient instance
   */
  @Autowired
  public CustomWebClient(WebClient webClient){
    this.webClient = webClient;
  }

  public ResponseEntity<String> callTarget(String baseEndPoint, Message message) {
    String response = webClient.post().uri(baseEndPoint)
        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
        .body(BodyInserters.fromValue(message.getMessage()))
        .retrieve()
        .onStatus(HttpStatus::is5xxServerError, serverError ->
            Mono.error(new HttpServerErrorException(serverError.statusCode())))
        .onStatus(HttpStatus::is4xxClientError, clientError ->
            Mono.error(new HttpClientErrorException(clientError.statusCode())))
        .bodyToMono(String.class).block();
    return new ResponseEntity<>(response, HttpStatus.OK);
  }
}

In below configuration I am adding trust store in SSLContext.
package xyz.conf;

import static java.nio.charset.StandardCharsets.US_ASCII;

import xyz.constants.Constants;
import xyz.service.ResourceReader;
import io.netty.channel.ChannelOption;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.timeout.ReadTimeoutHandler;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.security.auth.x500.X500Principal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

/**
 * Webclient configuration
 */
@Configuration
public class WebClientConfig {

  private String user;

  private String pass;

  private ResourceReader resourceReader;

  /**
   * Constructor to autowire ResourceReader
   * @param resourceReader ResourceReader object
   */
  @Autowired
  public WebClientConfig(ResourceReader resourceReader) {
    this.resourceReader = resourceReader;
  }

  @Value("${USER}")
  public void setuser(String user) {
    this.user = user;
  }

  @Value("${PASSWD}")
  public void setpass(String pass) {
    this.pass = pass;
  }

  private static final Logger LOGGER = LoggerFactory.getLogger(WebClientConfig.class);

  @Bean
  WebClient getWebClient () throws IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException {
    LOGGER.info("WebClient configuration started.");
    TrustManagerFactory trustManagerFactory =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore trustStore = getTrustStore(resourceReader.readTrustStoreConfig());

    trustManagerFactory.init(trustStore);
    SSLContext context = SSLContext.getInstance("TLSv1.2");
    context.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());

    SslContext sslContext = SslContextBuilder
        .forClient()
        .trustManager(trustManagerFactory)
        .build();

    HttpClient httpClient = HttpClient.create().secure( t -> t.sslContext(sslContext) );
    httpClient = httpClient.tcpConfiguration(tcpClient -> tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000));
    httpClient = httpClient.responseTimeout(Duration.ofMillis(30000));

    LOGGER.info("WebClient configured successfully..");
    ReactorClientHttpConnector reactorClientHttpConnector = new ReactorClientHttpConnector(httpClient);
    return WebClient.builder().clientConnector(reactorClientHttpConnector)
        .defaultHeaders(header -> header.setBasicAuth(user, pass))
        .build();

  }

  private KeyStore getTrustStore(String certificateChainPem)
      throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {

    KeyStore keyStore = null;
    keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);

    List<X509Certificate> certificates = readCertificateChain(certificateChainPem);
    for (X509Certificate certificate : certificates) {
      X500Principal principal = certificate.getSubjectX500Principal();
      keyStore.setCertificateEntry(principal.getName("RFC2253"), certificate);
    }

    return keyStore;
  }

  private List<X509Certificate> readCertificateChain(String certificateChainPem)
      throws CertificateException {
    List<X509Certificate> certificates = new ArrayList<>();

    Matcher matcher = Constants.CERT_PATTERN.matcher(certificateChainPem);
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

    int start = 0;
    while (matcher.find(start)) {
      byte[] buffer = base64Decode(matcher.group(1));
      certificates.add((X509Certificate) certificateFactory
          .generateCertificate(new ByteArrayInputStream(buffer)));
      start = matcher.end();
    }

    return certificates;
  }

  private byte[] base64Decode(String base64) {
    return java.util.Base64.getMimeDecoder().decode(base64.getBytes(US_ASCII));
  }

}

Below is application property file
logging.level.org.springframework=INFO

TARGET_ENDPOINT=XYZ
USER=XYZ
PASSWD=XYZ

#maxidle timeout for netty pool
reactor.netty.pool.maxIdleTime=3000

I have already tried to fix this via solution given in below link but it did not work.
https://github.com/reactor/reactor-netty/issues/782
Here are version details :-
Springboot version : 2.3.3.RELEASE

A: I saw the same issue with spring boot 2.4.12 and reactor-netty-http-1.0.12. Rebooting the server solved the issue.
My take is that SSLEngine closed already could be due to not 1 specific issue, but on a per use-case basis. The easiest & simplest, but of course not the best solution, is to reboot the server. Alternatively, you can upgrade to the latest reactor-netty-http jar(provided it is compatible with your framework, it should) and hope that the issue has been resolved ;-). The best, would be to raise a GitHub issue to the reactor-netty team and send them the stack-trace.


text:
Q: how to remove an item from a std::list My code:
using namespace std;

class A{public:
  int a;
  A(int itemA) {a=itemA;}
};
class B:A{public:
  int b;
  B(int itemA, int itemB) {a=itemA; b=itemB;}
};

class C{
  list<A> a;
  list<B> b;
  void transferAB(const A& pA, int itemb){
    a.remove(pA);
    b.push_back(B(pA.a, itemb));
  }

How do I make this thing work?

A: list doesn't know how to compare your objects. You need to specify an equality operator (operator==) for your classes.
You can avoid this by store pointers to your objects, and the list will compare pointers when you call remove. Since pointers are simply numbers, there is no problem with comparison.

A: a.remove(pA);

You need overload operator == for A as Aesthete suggest, or use remove_if, thats receive predicate and pass predicate to it. http://cplusplus.com/reference/stl/list/remove_if/


text:
Q: includeStats in neo4j.rb I'm using neo4j.rb, and when I run
MATCH (a {name:'apple'}) SET a.flag = true

I'd like to get the response data, which would be along the lines of:
{
  "results": [
    {
      "columns": [],
      "data": [],
      "stats": {
        "contains_updates": true,
        "nodes_created": 0,
        "nodes_deleted": 0,
        "properties_set": 1,
        "relationships_created": 0,
        "relationship_deleted": 0,
        "labels_added": 0,
        "labels_removed": 0,
        "indexes_added": 0,
        "indexes_removed": 0,
        "constraints_added": 0,
        "constraints_removed": 0
      }
    }
  ],
  "errors": []
}

Instead, I get nothing--the object is blank, I suppose because I'm not asking for nodes to be returned, but want metadata on the query results.
There's a proposed solution here using py2neo (py2neo return number of nodes and relationships created), with includeStats: true, and I've also tried appending it to the address I'm using to run queries as ?includeStats=true, which I saw somewhere else and resulted in a server not available error (response code 302 / RuntimeError) for me. Is there any solution for this using neo4j.rb ?

A: Unfortunately we don't keep the metadata when returning results in the neo4j-core gem.  It might be something that's easy to add.  Perhaps you could create an issue:
https://github.com/neo4jrb/neo4j-core/issues
Pull requests are welcome, of course!


text:
Q: how to login with facebook with custom login button using facebook sdk As per developers.facebook.com, I made a demo for Facebook login, but they automatically give their login button with signin written on it. How to use our custom button as login button?

A: You can set it with code below. Put that Facebook FBlogin Button in place of your button and set your own image using following code. You just set frame and use your own image of FBloginButton but you can not set custom IBAction of this following fbLogin Button:
if (!FBSession.activeSession.isOpen) {

    loginview =
            [[FBLoginView alloc] initWithPublishPermissions:@[@"email"] defaultAudience:FBSessionDefaultAudienceEveryone];

}

loginview.frame =FB_login.frame;//CGRectMake(90,149, 280, 55); // here set fbLoginview frame to your login Button Frame
        for (id obj in loginview.subviews)
        {
            if ([obj isKindOfClass:[UIButton class]])
            {
                UIButton * loginButton =  obj;

                UIImage *loginImage = [UIImage imageNamed:@"btn_fb_login.png"];// here set your own image
                [loginButton setBackgroundImage:loginImage forState:UIControlStateNormal];
                [loginButton setBackgroundImage:nil forState:UIControlStateSelected];
                [loginButton setBackgroundImage:nil forState:UIControlStateHighlighted];
                [loginButton sizeToFit];
            }
            if ([obj isKindOfClass:[UILabel class]])
            {
                UILabel * loginLabel =  obj;
                loginLabel.text =@""; //@"Log in to facebook";
                loginLabel.textAlignment = NSTextAlignmentCenter;
                loginLabel.frame =CGRectMake(123,149, 280, 55);// CGRectMake(0, 0, 271, 37);
            }
        }

        loginview.delegate = self;

        [self.view addSubview:loginview];


text:
Q: UIView segue UINavigationBar flicker I'm segueing from one view to another using performSegue(withIdentifier: "showActivities", sender: nil)
The segue works fine but the black navigation bar flickers before it gets totally black. I'm doing the same between to other views and everything works fine.
The image shows what I mean.
Can anybody help me?

A: This heppend because nav bar have bugged animation, u need to set view under navbar to dark color.


text:
Q: Firebase not working properly when added to Wordpress website I want to add JS code with chat functionality using Firebase database for messages and Firebase Auth for logging in and signing up to a Wordpress website to use it for customer support, yet whenever I open the website that uses that JS returns a warning and an error. Could somebody try and help me?

Here's how my index.js code looks:

// initialization of the database
const firebaseConfig = {
  apiKey: "XXXXXXXXXXXXXXX",
  authDomain: "xxxxxxxxxxxx",
  databaseURL: "xxxxxxx",
  projectId: "xxxxxxx",
  storageBucket: "xxxxxxxx",
  messagingSenderId: "xxxxxxx",
  appId: "xxxxxxxxxxxxxxxxxxxxxxx"
};
firebase.initializeApp(firebaseConfig);
const db = firebase.database();
const currentUser = document.getElementById("currentUser");

// variables to be used for users
var username = "", receiver;
var path, listener;
var select = document.getElementById("odbiorcy");

// selecting a user from the list of users
select.addEventListener("change", function handleChange(event) {
  if (listener)
      path.off("child_added", listener)

  receiver = select.options[select.selectedIndex].text;
  document.getElementById("messages").innerHTML = "";

// fetching messages
  fetchChat = db.ref("messages/" + username + "/").child(receiver);
  listener = fetchChat.on("child_added", function (snapshot) {
      const messages = snapshot.val();
      var msg;
      if(messages.usr == receiver){
        msg = "
" + urlify(messages.msg) + messages.file + "
";
        document.getElementById("messages").innerHTML += msg;
      }else{
        msg = "
" + urlify(messages.msg) + messages.file + "
";
        document.getElementById("messages").innerHTML += msg;
      }

      var messBox = document.getElementById("wiadomosci");

// checking whether the receiver is typing
      let areTheyTyping = db.ref("status/" + receiver + "/" + username);
      areTheyTyping.on("value", function (snapshot) {
      const typing = snapshot.val();

      if(typing == null)
        return;

      const status = typing.tpg;

      if (status == "yes"){
          document.getElementById("typing").style.display = "flex";
          messBox.scrollTop = messBox.scrollHeight;
      }
      else
      {
          document.getElementById("typing").style.display = "none";
          messBox.scrollTop = messBox.scrollHeight;
      }
      });

// showing the receiver's online status
      let receiversStatus = db.ref("status/" + receiver + "/connections");
      receiversStatus.on("value", function (snapshot) {
        const status = snapshot.val();

        if(status != null)
          document.getElementById("status").innerHTML = "online";
        else
          document.getElementById("status").innerHTML = "offline";
      })
  });

  path = fetchChat;
});

// logging and disconnecting
var connectionsRef = db.ref("status/" + username + "/connections");
var lastOnlineRef = db.ref("status/" + username + "/lastOnline");
var connectedRef = db.ref(".info/connected");
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION);
firebase.auth().onAuthStateChanged(function (user) {
  if (user)
  {
      currentUser.style.display = "block";
      currentUser.innerHTML += firebase.auth().currentUser.email;
      document.getElementById("wyloguj").style.display = "block";
      username = firebase.auth().currentUser.displayName;

// updating the user's online status
      connectionsRef = db.ref("status/" + username + "/connections");
      connectedRef = db.ref(".info/connected");
      connectedRef.on("value", function (snapshot) {
          if (!snapshot.val()) {
              const connection = connectionsRef.push();
              connection.onDisconnect().remove();
              connection.set(true);
          }
      });
  }
  else
  {
      document.getElementById("chat-txt").setAttribute("disabled", "disabled");
      document.getElementById("zaloguj").style.display = "block";
      document.getElementById("zarejestruj").style.display = "block";
      document.getElementById("odbiorcy").style.display = "none";
  }
});

// fetching users to the list
const fetchUsers = db.ref("users/");
fetchUsers.on("child_added", function (snapshot) {
  const users = snapshot.val();
  var opt = document.createElement("option");
  opt.value = users.userId;
  opt.innerHTML = users.username;
  select.appendChild(opt);
});

// files variables
const fileButton = document.getElementById("fileButton");
const fileURL = document.getElementById("fileURL");
const fileName = document.getElementById("fileName");

// sending a file
fileButton.addEventListener("change", function (e) {
  var file = e.target.files[0];
  var storageRef = firebase.storage().ref("files/" + file.name);
  var task = storageRef.put(file);

  task.on(
      "state_changed",
      function progress(snapshot) {
          uploader.style.display = "block";
          var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          uploader.value = percentage;
      },
      function error(err) {},
      function complete() {
          storageRef.getDownloadURL().then((downloadURL) => {
              fileURL.value = downloadURL;
          });

          fileName.value = file.name;
      }
  );
});

// sending a message
document.getElementById("send-message").addEventListener("submit", postChat);
function postChat(e) {
  db.ref("status/" + username + "/" + receiver).set({
      tpg: "no",
  });

  e.preventDefault();
  const timestamp = Date.now();
  const chatTxt = document.getElementById("chat-txt");
  const chatval = chatTxt.value;
  var message, file;
// posting a message to the database
  if(chatval)
  {
      message = chatTxt.value;
      file = " " +fileName.value + "";
      chatTxt.value = "";
      db.ref("messages/" + username + "/" + receiver + "/" + timestamp).set({
          usr: username,
          file: file,
          msg: message,
      });

      db.ref("messages/" + receiver + "/" + username + "/" + timestamp).set({
          usr: username,
          file: file,
          msg: message,
      });
      uploader.style.display = "none";
      fileButton.value = "";
      fileURL.value = "";
      fileName.value = "";
  }

// pushing the user's typing status to the sendTyping function
  var searchTimeout;
  document.getElementById("chat-txt").onkeypress = function() {
      if (searchTimeout != undefined)
          clearTimeout(searchTimeout);
      searchTimeout = setTimeout(callServerScript, 1000);
      sendTyping(true);
  }
}

// a function sending the user's typing status to the database (function)
function sendTyping(tmp)
{
  if (tmp) {
      db.ref("status/" + username + "/" + receiver).set({
              tpg: "yes",
      });
  } else {
      db.ref("status/" + username + "/" + receiver).set({
              tpg: "no",
      });
  }
}

// the user is not typing (function)
function callServerScript()
{
  sendTyping(false);
}

// calculating time from a timestamp variable (function)
function timeSince(date)
{
  var seconds = Math.floor((new Date() - date) / 1000);
  var interval = seconds / 31536000;

  if (interval > 1)
      return Math.floor(interval) + " years";
  interval = seconds / 2592000;

  if (interval > 1)
      return Math.floor(interval) + " months";
  interval = seconds / 86400;

  if (interval > 1)
      return Math.floor(interval) + " days";
  interval = seconds / 3600;

  if (interval > 1)
      return Math.floor(interval) + " hours";
  interval = seconds / 60;

  if (interval > 1)
      return Math.floor(interval) + " minute(s)";

  return "a few seconds";
}

// logging out (function)
function logout()
{
  firebase.auth().signOut().then(() => {
          window.location.replace("./index.html");
  }).catch((error) => {});
}

// checking if the message contains a link or is a link (function)
function urlify(text)
{
  var urlRegex = /((?:(?:http?|ftp)[s]*:\/\/)?[a-z0-9-%\/\&=?\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?)/gi
  return text.replace(urlRegex, function(url) {
          return '' + url + '';
  })
}

And this is the way I add script to the footer of the page using "Header and Footer Code Manager"

This is the way I add it to the Wordpress page:

Could someone help me and tell me a solution? I've been working on fixing it for days...

A: Looks like you use the Safari browser. The browser has problems with const and let declared in the code. Try to change those which are showed up as faulty in the browser's console to var.
Also if you use Wordpress website with you JS code you probably need to turn LScache off or exclude it on certain subpages. You can do this by entering the WP dashboard and in the Litespeed cache section open the cache options and exclude these which use JS.
Hope it helped, I used to be stuck with the same problem ;)


text:
Q: Navigation to call action for bean class I am using JSF 2.0 and PrimeFaces 3.0. I have uploaded the images and have to crop the image. The images are uploaded and successfully displayed in the upload pages.
When I select the images and click the crop button the corresponding crop bean is not called. If I don't select the image and click the crop button the corresponding crop bean class is called but a NullPointerException occurred. What is the problem?
The Facelet view is:
<h:form>
  <p:panel header="FILE UPLOAD WITH CROPPER" style="width:900px; margin: 0 auto; margin-top:0px">
    <p:fileUpload fileUploadListener="#{photoUploadAction.handleImageUpload}"
      mode="advanced"
      update="getImageId,messages" auto="false"
      allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>

    <p:growl id="messages" showDetail="true"/>
    <p:growl id="uploadMessages" showSummary="true" showDetail="true"/>

    <h:panelGrid columns="2" >
      <p:imageCropper value="#{photoUploadAction.croppedImage}" id="getImageId"
        image="images/#{photoUploadVO.imageName}"/>
    </h:panelGrid>

    <p:commandButton value="Crop" update="getImageId" action="#{imageCropperBean.crop}" />
  </p:panel>
</h:form>

BACKING BEAN for ImageCropper:
@ManagedBean(name="imageCrop")
@RequestScoped

public class ImageCropperBean {

    private CroppedImage croppedImage;
    private String newFileName;
    private String imageName;

    public String getImageName() {
        return imageName;
    }

    public void setImageName(String imageName) {
        System.out.println("TEH IMAGE NAME ===="+imageName);
        this.imageName = imageName;
    }

    public String getNewFileName() {
        return newFileName;
    }

    public void setNewFileName(String newFileName) {
        System.out.println("AAAAAAAAAAAAAA"+this.newFileName);
        this.newFileName = newFileName;
    }

    public CroppedImage getCroppedImage() {
            return croppedImage;
    }

    public void setCroppedImage(CroppedImage croppedImage) {
        System.out.println("cRRRRRRRRRRRRR"+croppedImage);
            this.croppedImage = croppedImage;
    }

    public ImageCropperBean(){

    }

    public String crop() {
        System.out.println("WELCOMEMMMMMMMMMMMMMM");

        FacesContext context = FacesContext.getCurrentInstance();
        ImageCropperBean imageCropperBean = (ImageCropperBean) context.getApplication().evaluateExpressionGet(context, "#{imageCropperBean}", ImageCropperBean.class);

            ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();

             newFileName = servletContext.getRealPath("") + File.separator + "cropImage"  + File.separator+ "croppedImage.jpg";

             System.out.println("FILE NAME NAME NAME NAME "+newFileName);

            String file = new File(newFileName).getName();
            System.out.println("DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"+file);

             imageCropperBean.setImageName(file);
             File fileFolder = new File("e:/Mecherie_project/image_web/WebContent/cropImages",file);

            System.out.println("FILE ANE"+file);

           // String target=null;

            FileImageOutputStream imageOutput;
            try {
                    imageOutput = new FileImageOutputStream(fileFolder);
                    System.out.println("HHHHHHHHHH=="+imageOutput);
                    imageOutput.write(croppedImage.getBytes(), 0, croppedImage.getBytes().length);
                    imageOutput.close();

                    FacesMessage msg = new FacesMessage("Succesful", file
                            + " is cropped.");

                    FacesContext.getCurrentInstance().addMessage(null, msg);

            } catch (FileNotFoundException e) {

                FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        "The files were not Cropped!", "");
                FacesContext.getCurrentInstance().addMessage(null, error);
                e.printStackTrace();

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

                    FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                            "The files were not Cropped!", "");
                    FacesContext.getCurrentInstance().addMessage(null, error);
            }

          //  System.out.println("ghfhgfghgh"+target);
            return "success";

            }
}


text:
Q: How to check if a Process is Running or Not I am starting a process using the below code
 QProcess* process = new QProcess();
 process->start(Path);

The start method will start a third party application.
If the process is already  running, I  should not call process->start(Path) again.
The process  pointer is private member of the class.

A: To complement the @jdi's answer with a real-life code example:
QString executable = "C:/Program Files/tool.exe";
QProcess *process = new QProcess(this);
process->start(executable, QStringList());

// some code

if ( process->state() == QProcess::NotRunning ) {
    // do something
};

QProcess::ProcessState constants are:
Constant              Value Description
QProcess::NotRunning    0   The process is not running.
QProcess::Starting      1   The process is starting, but the program has not yet been invoked.
QProcess::Running       2   The process is running and is ready for reading and writing.

Documentation is here.

A: From the docs for QProcess ...
There are at least 3 ways to check if a QProcess instance is running.
QProcess.pid() : If its running, the pid will be > 0
QProcess.state() : Check it again the ProcessState enum to see if its QProcess::NotRunning
QProcess.atEnd() : Its not running if this is true
If any of these are not working as you would expect, then you will need to post a specific case of that example.


text:
Q: Using IDENTITY while creating table I am learning SQL and totally new to this world. What I have learnt / read about using identity is: it is used to create an identity column with Seed and increment value ~ Identity (Seed, increment). However going through some sample database available on net, I came across this table creation script:
create table Customer
(
    Id                   int                  identity,
    FirstName            nvarchar(40)         not null,
    LastName             nvarchar(40)         not null,
    City                 nvarchar(40)         null,
    Country              nvarchar(40)         null,
    Phone                nvarchar(20)         null,
    constraint PK_CUSTOMER primary key (Id)
)
go

I tried creating table with this code and it was successful.
Can someone explain why IDENTITY here does not have seed and increment values? When should we use it like this (without seed and increment values) ?
TIA

A: When you use -->  Id int identity
It is equivalent to --->  Id int identity(1,1)
So the first value will be inserted into table with Id = 1 and incremented by 1 for next row. so this is the default value for identity if nothing is specified. In case if you want to start your Id with some specific number, for ex -  you want to create customerId column which should have at least 5 digit id than you have to define the column as ---> CustomerId int identity(10000 ,1)


text:
Q: How to filter data by an async method in EFCore? I want to filter my data by ef core and I'm trying to filter users by an async method that returns Task<bool>.
var query = _context.User.AsQueryable();
query.Where(async (arg) => await _userInterface.CheckUserAvabilityAsync(user, arg.Id) == true);

But with this code, I get this error
CS4010: Cannot convert async lambda expression to delegate type 'Func<User, bool>'. An async lambda expression may return void, Task or Task, none of which are convertible to 'Func<User, bool>'.
So how can i filter my asqueryable data by my method?

A: That error is telling you that you can't use async inside your predicate.
You need to change your approach, unfortunately, looping through in-memory data.
// Get all data, convert to list
List<User> userRecords = _context.User.ToList();
List<User> availableUsers = new List<User>();
foreach (User userRecord in userRecords)
{
    //Assuming you will always successfully receive a boolean
    if (await _userInterface.CheckUserAvabilityAsync(user, userRecord.Id))
        availableUsers.push(userRecord);
}
return availableUsers;

That should do the trick.


text:
Q: Derivative at $x=0$ for $\frac{1}{x\ln(2)} - \frac{1}{2^x - 1}$
A function $f$ is defined on $\Bbb R$ as $\frac{1}{x\ln 2 } - \frac{1}{2^x  -1}$ for $x \neq 0$ and $\frac{1}{2}$ for $x = 0$. Show that $f$ is continuous and find $f'(0)$

From my knowledge
$$f'(0) = \lim_{x\to 0}\frac{f(x) - f(0)}{x}\\
 =\frac{\frac{1}{x\ln(2)} - \frac{1}{2^x-1} - \frac{1}{2}}{x}\\
 = \frac{\frac{x \ln(2)}{2(2^x-1)} - \frac{1}{2}}{x}\\
 = \frac{x \ln(2) - (2^x -1)}{2x(2^x - 1)}\\
 = \frac{x^2 \ln^2(2)}{4x(2^x - 1)}$$
Which on using mclaurin series of $2^x$ gives $\frac{-\ln 2}{4}$ but the correct answer is $\frac{-\ln 2}{12}$

A: We have $$\frac{1}{x\ln(2)}-\frac{1}{2^x-1}-\frac{1}{2}=\frac{(2^x-1)2-2x\ln(2)-(2^x-1)x\ln(2)}{x\ln(2)(2^x-1)\cdot 2}$$

A: You did not include all terms in the series. In intermediate steps, there is also a term $\frac{x^3\ln^3(2)}{3!}$ which is missed.
$$\frac{\frac{1}{x\ln(2)} - \frac{1}{2^x-1} - \frac{1}{2}}{x} = \frac{2(2^{x}-1)-2(x \ln(2))-x\ln(2)(2^{x}-1)}{2x^2 \ln(2)(2^{x}-1)} \\
 = \frac{2(x\ln(2)+\tfrac{x^2 \ln^2(2)}{2}+\tfrac{x^3 \ln^3(2)}{6})-2x\ln 2 - x \ln(2)(x\ln(2)+\tfrac{x^2 \ln^2(2)}{2})}{2x^2 \ln(2)(2^{x}-1)}\\
 = \frac{-\tfrac{x^3 \ln^3(2)}{6}}{2x^2 \ln(2)(2^{x}-1)}$$
which will give $ \frac{-\ln(2)}{12}$ as the limit.


text:
Q: Why do frame breakers work cross-domain, and can you conditionally use frame breakers? I've been investigating frame breaking code recently and have come across some really bizarre behavior related to the same origins policy that I am having trouble understanding.
Suppose I've got a page Breaker.html on domain A, and a page Container.html on domain B.  The example frame breaker code would go into Breaker.html, like below:
if (top !== self) top.location.href = self.location.href;

This will successfully break Breaker.html out of Container.html, but I don't understand why it should.  From my reading of the same origins policy, top.location shouldn't be accessible at all, since Container.html is on a different domain than Breaker.html.  Even weirder, it appears that top.location write-only:
// Fails if Container.html is on a different domain than Breaker.html
alert(top.location);

This is problematic to me because I'm trying to write code that allows my page to be in an iframe, but only if it's on the same domain as its parent (or is on a configured allowable domain) .  However, it seems to be impossible to determine this, since the same origins policy denies me access to the parent's location.
So I've got two questions, basically:

*

*Why does the above frame breaker code work at all?

*Is there any way to break frames conditionally, or is the only check one can do is whether top !== self?  (In particular, I want to be able to read the domain, so that I can provide a list of allowable domains; simply checking whether I'm in the same domain or not would not be ideal.)

A: FOr your answer to number 1: In terms of security, there is a big difference between read access and write access.  Being able to read top.location.href is a security problem.  Being able to write to top.location.href is not.
As for the answer to your question, I don't know javascript well enough to be sure, but one idea would be to assumine that if reading top.location fails (check for exceptions), it is on a different domain.

A: The answer to question 1 is that the equality operator can be used against top.location.href for legacy reasons.  Breaker.html cannot read top.location.href but it can compare it with another value.
The answer to question 2 then becomes no, you must use the !== to part because you won't be able to do a substring on top.location.href from a cross domain breaker.html.
I could be wrong but that's my understand of the current iframe world.

A: This is for question number 2: If you want to take HREF of parent.location (not top.location), you can do this:
if ((window.top === window.parent) && (history.length==1)) parentHREF=document.referrer;

Basically what this code does is:[1] Checking if parent frame is the top one because you can take only parent's HREF even if it is not the top frame.[2] Checking if iframe's history was blank before loading its source, because if not... document.referrer will return the last HREF in this frame history.After that, you have a new problem: in case history.length's value is more than one, you can use a whitelist of hostnames to check if it has to be opened or not:
if ([location.hostname, 'stackoverflow.com'].indexOf(location.hostname)>=0) hasToBeOpened=true;

Note that you another option: can use a landing page to check if the "first" page has to open or not, use this code:
<head>
<script>
var parentHREF;
if ((window.top === window.parent) && (history.length==1)) parentHREF=document.referrer;
if (/*conditions mentiones above*/) document.write("<META http-equiv='refresh' content='0;URL=http://example.com/go-here.html'>");
</script>
</head>

Doing it this way, the "first" page will replace history's first (in this case it is first) value. That code is asuming "example.com" is your domain.


text:
Q: Multiple request ids In the request 2.0 documentation, they mention that the app can get request_ids, which is a comma delimited list of Request IDs that a user is trying to act upon.
I was wondering if someone can give an example when multiple ids will arrive. Usually for each request the user sees a single notification so how come several requests might be combined to a single call?

A: All request are grouped in left pane, showing the number of them next to app name, aren't they? It seems only logical that you get them all if you click on the app name there.


text:
Q: I am trying to create a payara cluster and I get an error during creation of a remote node I am trying to create a payara cluster and I get an error during creation of a remote node:
./asadmin create-node-ssh --nodehost 10.198.228.240  --sshkeyfile /root/.ssh/id_rsa --force true --install true computer2

Enter admin user name>  admin
Enter admin password for user "admin">
Created installation zip /root/payara5/glassfish/domains/domain1/config/glassfish1664073687432568371.zip
Successfully connected to root@10.198.228.240 using keyfile /root/.ssh/id_rsa
Copying /root/payara5/glassfish/domains/domain1/config/glassfish1664073687432568371.zip (146575218 bytes) to 10.198.228.240:/root/payara5
Installing glassfish1664073687432568371.zip into 10.198.228.240:/root/payara5
jar command failed while installing glassfish on host 10.198.228.240. Command output bash: jar: command not found

Command install-node-ssh failed.

Remote command output: bash: jar: command not found
Command create-node-ssh executed successfully.

Is there a solution for this issue?
jar command failed while installing glassfish on host 10.198.228.240. Command output bash: jar: command not found

A: the solution is :
1- add a path of jdj to /root/.bashrc :
    export JAVA_HOME=/opt/java-jdk/jdk1.8.0_201
    export PATH="$PATH:$JAVA_HOME/bin"
2- source .bashrc
3- check witch jar executable shell was trynig to execute :
  $ which jar
   /opt/java-jdk/jdk1.8.0_201/bin/jar
4- Now create a symbolic link to the jar executable file frome /usr/bin directory
    # cd /usr/bin/
    #  ln -s /opt/java-jdk/jdk1.8.0_201/bin/jar
    #  which jar
      /usr/bin/jar
after that create node-ssh frome computer1 :
root@computer1:~/payara5/bin# ./asadmin create-node-ssh --nodehost computer2  --sshkeyfile /root/.ssh/id_rsa --force true --install true computer2-node
    Enter admin user name>  admin
    Enter admin password for user "admin">
    Successfully installed Payara on computer2.
    Command create-node-ssh executed successfully.


text:
Q: Is getChildren() of ContentProvider called before treeExpanded() of ITreeViewerListener? I want to fetch data if a specific element of a tree is expanded.
public void treeExpanded(TreeExpansionEvent event) {
   Object element = event.getElement();
   if (element instanceof MyClass) {
      fetch.......
   }
}

The problem is that the content provider seems to trigger getChildren() before the treeExpanded()-method so I get a NullPointerException everytime I expand the element because the content provider tries to use the data which is never fetched. How can i solve this properly?

A: Your code should not depend on the order in which getChildren() and treeExpanded() is called. This is an implementation detail of the TreeViewer and may change in the future.
Fetch the elements to be shown in getChildren() or inputChanged() of the content provider.
If your fetch operation takes too long to be run in the UI thread, run it in a background thread and return a placeholder element that is replaced, once the fetch operation finishes. For an example, see the DeferredTreeContentManager of org.eclipse.ui.
Alternatively you can see if the JFace DeferredContentProvider fits your needs.

A: Yes the content provider getChildren is called before the treeExpanded event is fired. You cannot use this event to populate the tree.
If you want to delay getting parts of the tree perhaps you should be looking at a tree using the SWT.VIRTUAL flag and an ILazyTreeContentProvider content provider.


text:
Q: Determining whether a function is injective Question:
Let f : $\mathbb{R}$ $\to$ $\mathbb{R}$ via $ f(x) = \frac{x}{1+x^2}$. Is $f$ injective?
My attempt:
I am unable to find a counter example to prove that it is not injective.
Suppose $ f(a) = f(b)$ for some $a,b \in \mathbb{R}$.
$ \frac{a}{1+a^2}=\frac{b}{1+b^2}$
$a\ +\ ab^2\ =\ b\ +ba^2$
$ ab^2-b\ \ =ba^2-a$
$ b\left(ab-1\right)=a\left(ab-1\right)$
$ \left(b-a\right)\left(ab-1\right)=0$
Would this imply that $ a = b$? In questions where I cannot easily figure out a counter example to prove a function is not injective, what should I do? Should I try to prove that it is injective and then reach a contradiction?

A: Following your own computations, assuming continuity throughout the answer, the condition $(a-b)(ab-1)=0$ means equality is reached either when $a=b$ ( tautological) , or when $b=1/a$. Double-checking ( assume $a \neq 0$, which anyway does not satisfy $ab=1$):
$$ f(a):= \frac {a}{1+a^2}; f(1/a):= \frac {1/a}{1+(1/a)^2}=\frac {1/a}{(a^2+1)/a^2}=\frac {a}{1+a^2} $$ ( after cancelling the a's). Notice that for a function $f: \mathbb R \rightarrow \mathbb R $ to be injective , it must be monotone, EDIT : for surjectivity, we must have  $Lim f(x)_{x \rightarrow \infty} =\infty $ and $Lim f(x)_{x \rightarrow - \infty} = - \infty$ , or change the order of the infinities.

A: A function which is continuous and injective should be strictly monotonic
[else we can invoke the intermediate value theorem before and after any local extremum and find duplicated values]
Here since $1+x^2\neq 0$ then $f$ is continuous over $\mathbb R$.
Yet $f(0)=0$ and $\lim\limits_{x\to+\infty}f(x)=0$.
Since $f(x)>0$ for $x>0$ then $f$ cannot be strictly monotonic and furthermore injective.

A: It cannot be injective since $f(x) = \frac{1}{x+\frac{1}{x}}$ implies $f(x)=f\left(\frac{1}{x}\right)$ for any $x\in(0,1)$, for instance.

A: The continuous function $f$ defined on $\Bbb R$ satisfies
$f(0) = 0$
$f(1) = 1/2$
By the intermediate value theorem,
$\tag 1 f(\alpha) = 1/4$ for some $0 \lt \alpha \lt 1$.
Also
$f(1) = 1/2$
$f(10) = 10/101$
By the intermediate value theorem,
$\tag 2 f(\beta) = 1/4$ for some $1 \lt \beta \lt 10$
By (1) and (2) the function can't be injective.
If you are not familiar with the intermediate value theorem, sketch a rough graph. You might convince yourself that, say, $f(x) = 1/4$ has two solutions.
Solving for $x$,
$\frac{x}{1+x^2} = 1/4 \text { iff }$
$4 x = 1+x^2 \text { iff }$
$x^2 - 4x + 1 = 0$
Plugging into the quadratic formula, you get
$\alpha = 2 - \sqrt 3$
$\beta = 2 + \sqrt 3$
Observe that $\beta = \alpha^{-1}$.


text:
Q: No such file or directory when changing directory: Running shell script in ubuntu in windows 10 I have been having issues changing directories using a shell script in windows 10.
In notepad I created a file, test.sh, which has the following script:
#!/bin/bash
cd '/mnt/p/WMScriptTest/'

I then mounted the Ubuntu terminal to the location of the test.sh file by typing in cd /mnt/p/ which works. Next, I typed in ./test.sh and keep getting the following error message:
: No such file or directory/p/WMScriptTest/

I am new to using ubuntu and any help/suggestions are greatly appreciated.
Thank you