text:
Q: Are there any outstanding critical security issues for Sql Server 2000? Are there any outstanding (unpatched) security issues for Sql Server 2000?
This isn't really for me: I moved on from Sql Server 2000 long ago. However, when answering questions here and (more likely) on Stack Overflow, I'm in the habit of leaving a comment like the one at this question whenever coming across a Sql Server 2000 question. If you don't want to follow the link, it goes something like this:

Sql Server 2000 is end of life. It no longer gets any patches... not even critical security patches. It's irresponsible to continue using it. Convincing management to upgrade is job #1.

Aide from it being, well, Sql Server 2000, how much an issue is this really? In the year-plus since Sql Server 2000 went EOL, has anything big come up I could point to as a more concrete issue?
I'd look at official documentation, but as this is effectively abandonware I haven't found anything published directly by MS.

A:
Are there any outstanding critical security issues for Sql Server 2000?

Yes, there are no patches available for newly discovered issues like meltdown/spectre
Microsoft only releases security patches for SQL versions that are still supported. Also notice that if you are running a supported SQL version with an unsupported service pack, you MUST upgrade to a supported service pack to have an available security patch.

*

*4057122 Description of the security update for SQL Server 2017 GDR: January 3, 2018

*4058562 Description of the security update for SQL Server 2017 RTM CU3: January 3, 2018

*4058561 Description of the security update for SQL Server 2016 SP1 CU7: January 3, 2018

*4057118 Description of the security update for SQL Server 2016 GDR SP1: January 3, 2018

*4058559 Description of the security update for SQL Server 2016 CU: January 6, 2018

*4058560 Description of the security update for SQL Server 2016 GDR: January 6, 2018

*4057117 Description of the security update for SQL Server 2014 SP2 CU10: January 16, 2018

*4057120 Description of the security update for SQL Server 2014 SP2 GDR: January 16, 2018

*4057116 Description of the security update for SQL Server 2012 SP4 GDR: January 12, 2018

*4057115 Description of the security update for SQL Server 2012 SP3 GDR: January, 2018

*4057121 Description of the security update for SQL Server 2012 SP3 CU: January, 2018

*4057114 Description of the security update for SQL Server 2008 SP4 GDR: January 6, 2018

*4057113 Description of the security update for SQL Server 2008 R2 SP3 GDR: January 6, 2018

Protect SQL Server from attacks on Spectre and Meltdown side-channel vulnerabilities


text:
Q: Built-in search tool in shell scripts I have an input file "B", containing line numbers referring to specific
lines in file "A". I need to search for a text pattern using the line
numbers in "B", e.g. first 3 lines of B will be:
385
527
547

So I need to check whether the "pattern" is present between 386 and 526,
528 and 548 in the file "A". I can do this with some complex programming
and looping with the help of awk etc., but I want to know the built-in
tools and options available in Unix (Solaris) for searching, to make my
code simple, e.g., if there is a tool or option to search a pattern
between a given line range it will be useful.

A: No looping or complexity needed for awk to match (and print) in a range:
awk 'NR>start && NR<end && /pattern/'

A bit trickier to convert file B content to the right awk condition, but this does it:
echo "($(awk 'NR==1{r1=$1;next}
              NR>2{printf"||"}
              {printf"(NR>%d&&NR<%d)",r1,$1;r1=$1}
              END{if(NR<2)printf"0"}' B))&&/yourpattern/"|
  awk -f- A

Perhaps slightly simpler would be to pre-filter the ranges using sed, and then grep for the pattern:
awk 'NR==1{r1=$1;next}
     $1>r1+1{printf"%d,%dp\n",r1+1,$1-1;r1=$1}' B|
  sed -nf- A|
  grep 'yourpattern'

redpajama_set_name: RedPajamaStackExchange


text: Q: Trigonometric substitution, bounds and which root to pick. So I have been using trigonometric substitution for a while now, I can do it almost automatically. I understand it is a kind of "reverse" u-substitution. However, what concerns me are the bounds. How do we calculate the bounds? What is the rigor behind it? Also, when we do trig stuff, we usually pick $\sqrt{\tan^2{\theta}}=\tan{\theta}$. How do we pick which root we should choose? I assume it is dependent on the bounds?


text:
Q: How to compute that the unit digit of $\frac{(7^{6002} − 1)}{2}$? The mother problem is:

Find the unit digit in LCM of $7^{3001} − 1$ and $7^{3001} + 1$

This problem comes with four options to choose the correct answer from,my approach,as the two number are two consecutive even numbers hence the required LCM is  $$\frac{(7^{3001} − 1)(7^{3001} + 1)}{2}$$
Using algebra that expression becomes $\frac{(7^{6002} − 1)}{2}$,now it is not hard to see that unit digit of $(7^{6002} − 1)$ is $8$.
So the possible unit digit is either $4$ or $9$,As there was no $9$ as option I selected $4$ as the unit digit which is correct but as this last part is a kind of fluke I am not sure if my approach is right or not or may be I am unable to figure out the last part how to be sure that the unit digit of $\frac{(7^{6002} − 1)}{2}$ is $4$?

A: Your argument is great! To finish it off, note that $\frac{7^{6002}-1}{2}=\text{LCM}(7^{3001}-1,7^{3001}+1)$ is even, so it could not have a units digit of 9.

A: Here is another way: $\ $ by Euler $\phi\:,\ $ $\rm\:7^{3001}\: \equiv\ 7\pmod{20}$
thus $\rm\ n\: =\: (7^{3001}-1)\ (7^{3001}+1)\ \equiv\ 6\cdot 8\ \equiv\ 8\pmod{20}$
Therefore, since $\rm\:n\:$ is even, we obtain $\rm\:n/2\ \equiv\ 4\pmod{10}\ $ by cancelling $2\:.$
NOTE $\ $ If Euler $\phi$ is unknown then one may proceed simply as follows
$\mod\ 20:\ \ 7^2 \equiv 9\ \Rightarrow\ 7^4 \equiv\ 9^2 \equiv 1\ \Rightarrow\ \ 7^{3001}\ \equiv\ 7\ (7^4)^{750}\: \equiv\ 7$

A: We look directly at the mother problem. Exactly as in your approach, we observe that we need to evaluate
$$\frac{(7^{3001}-1)(7^{3001}+1)}{2}$$
modulo $10$.
Let our expression above be $x$.  Then $2x= (7^{3001}-1)(7^{3001}+1)$.  We will evaluate $2x$ modulo $20$.
Note that $7^{3000}$ is congruent to $1$ modulo $4$ and modulo $5$. Thus  $7^{3001} \equiv 7\pmod{20}$, and therefore
$$2x\equiv (6)(8)\equiv 8 \pmod{20}.$$
It follows that $x\equiv 4\pmod{10}$.

A: The elementary way: $7^2=50-1$ mod $100$ hence $7^4=1$ mod $100$ hence $7^{6000}=1$ mod $100$ because $6000$ is a multiple of $4$, hence $7^{6002}=7^2$ mod $100$ and your number is $\frac12(7^2-1)$ mod $50$. This is $24$ mod $50$ hence the last digit is $4$ (and a priori, the previous digit is either $2$ or $7$ but one just has to be a little more careful to prove that it is $2$).


text:
Q: The Diophantine equation $x^2 + 2 = y^3$ How to solve the Diophantine equation $x^2 + 2 = y^3$ with $x,y>0$ ?
($x,y$ are integers.)

A: I would like to supplement Mick's answer by adding in some explanation to part 2 of his answer. Here is why we can conclude that $x+\sqrt{-2}$ is a cube in $\mathbb{Z}[\sqrt{-2}]$:
If we have the prime factorization
$$x+\sqrt{-2} = \alpha_1\alpha_2\cdots \alpha_{3A}$$ then we also have the prime factorization $$x-\sqrt{-2} = \bar{\alpha_1} \bar{\alpha_2}\cdots \bar{\alpha_{3A}}$$
Suppose also that we have the prime factorization: $$y=\beta_1 \beta_2 \cdots \beta_{2A}$$ Then the equation $(x+\sqrt{-2})(x-\sqrt{-2})=y^3$ becomes:
$$\alpha_1\alpha_2\cdots \alpha_{3A} \bar{\alpha_1} \bar{\alpha_2}\cdots \bar{\alpha_{3A}} = \beta_1^3 \beta_2^3 \cdots \beta_{2A}^3$$
Suppose WLOG that $\alpha_1=\beta_1$, so $\alpha_1 | (x+\sqrt{-2})$. Then $\alpha_1 \not |(x-\sqrt{-2})$, since that would imply $\alpha_1 |[(x+\sqrt{-2})-(x-\sqrt{-2})]$, i.e. $\alpha_1 | \; 2\sqrt{-2}$. But since $\alpha_1$ is prime, this forces $\alpha_1=\pm\sqrt{-2}$, which is impossible, since $\pm\sqrt{-2}$ does not divide $x+\sqrt{-2}$.(We are here assuming $x \neq 0$). Therefore all of $\beta_1^3$ must divide $x+\sqrt{-2}$ (and similarly all of $\bar{\beta_1}^3$ must divide $x-\sqrt{-2}$). The only way this can happen then, is if, say $\alpha_1 = \alpha_2 =\alpha_3 = \beta_1$.
Continuing this grouping, we conclude that we can collect the prime factors of $x+\sqrt{-2}$ into groups of three, so it must be a cube number.

A: A completely elementary proof can be found on page 561 of the Nov 2012 edition of The Mathematical Gazette, where a descent mechanism first used by Stan Dolan in the March 2012 edition is adapted (as per his challenge to the "interested reader") to solve Fermat's two "elliptic curve" theorems. The method uses math which was clearly available in Fermat's time, and in particular to Fermat himself.
I personally believe this finally puts to rest any questions of whether Fermat could have had a proof of these two claims.

A: Lemma.
Let $a$ and $b$ be coprime integers, and let $m$ and $n$ be positive integers such that $a^2+2b^2=mn$. Then there are coprime integers $r$ and $s$ such that $m=r^2+2s^2$ divides $br-as$. Furthermore, for any such choice of $r$ and $s$, there are coprime integers $t$ and $u$ such that $a=rt-2su$, $b=ru+st$, and $n=t^2+2u^2$ divides $bt-au$.
Proof.
Assume the theorem is false, and let $m$ be a minimal counterexample. Evidently $m > 1$ since the theorem is trivially true for $m=1$.
Note that $b$ is coprime to $m$. Let $A$ be an integer such that $Ab \equiv a\!\pmod{m}$, chosen so that $\tfrac{-m}{2} < A \le \tfrac{m}{2}$. Then $A^2+2 = lm$ for some positive integer $l < m$. Clearly $l$ cannot be a smaller counterexample than $m$, and so there exist coprime integers $r$ and $s$ such that $m=r^2+2s^2$ divides $br-as$.
Let $t = \tfrac{ar+2bs}{m}$ and $u=\tfrac{br-as}{m}$. Direct calculation confirms the equations for $a$, $b$, and $n$. From $n=t^2+2u^2$, we deduce that $t$ is an integer because $u$ is an integer, and $t$ and $u$ are coprime because $\gcd(t,u)$ divides both $a$ and $b$. Finally, note that $n$ divides $bt-au=sn$.
Hence $m$ is not a counterexample, contradicting the original assumption. $\blacksquare$
Corollary.
Let $a$ and $b$ be coprime integers with $m$ an integer such that $m^3=a^2+2b^2$. Then there are coprime integers $r$ and $s$ such that $a=r(r^2-6s^2)$ and $b=s(3r^2-2s^2)$.
Proof.
Evidently $m$ is odd since $a^2+2b^2$ is at most singly even. And $a$ and $m$ must be coprime. Using the theorem, we have $m=r^2+2s^2$ and $m^2=t^2+2u^2$. Then $m$ divides $a(ur-ts)=t(br-as)-r(bt-au)$, and therefore $m \mid (ur-ts)$. The lemma can then be reapplied with $a$ and $b$ replaced by $t$ and $u$. Repeating the process, we eventually obtain integers $p$ and $q$ such that $p^2+2q^2=1$. The only solution is $q=0$ and $p=\pm1$. Ascending the path back to $a$ and $b$ (reversing signs along the way, if necessary) yields $a=r(r^2-6s^2)$ and $b=s(3r^2-2s^2)$, as claimed. $\blacksquare$
Theorem.
The Diophantine equation $X^3 = Y^2+2$ has only one integer solution, namely $(x,y) = (3, \pm 5)$.
Proof.
Evidently $y$ and $2$ are coprime. By the corollary, we must have $b=1=s(3r^2-2s^2)$ for integers $r$ and $s$. The only solutions are $(r,s)=(\pm 1,1)$. Hence $a=y=r(r^2-6s^2)=\pm 5$, so $(x,y)=(3,\pm 5)$. $\blacksquare$

A: Although I prefer an answer without ring theory here is a solution by using the extension $\mathbb{Z}[\sqrt{-2}]$.
All variables in this proof are integers.
$x^2+2=y^3$ factors as $(x+\sqrt{-2})(x-\sqrt{-2})=y^3$.
Since
$1)$ $\mathbb{Z}[\sqrt{-2}]$ is a UFD.
$2)$ the LHS factors into $2$ conjugates which implies that the LHS must have $2n$ primefactors. (A conjugate factors analogue to its Original in a UFD , this is easy to show when using the norm)
3) the RHS must have $3m$ prime factors and the smallest common multiple of $2$ and $3$ is $6$.
We can conclude that :
$1)$ both LHS and RHS has $6A$ prime factors.
$2)$ Since we have two conjugates on the LHS we can conclude that $(x+\sqrt{-2})$ is a cube in $\mathbb{Z}[\sqrt{-2}]$.
Hence we get the equation $(x+\sqrt{-2})=(a+b\sqrt{-2})^3$
We proceed by  expanding the cube :
$x+\sqrt{-2} = a^3 - 6 a b^2 + (3 a^2 b-2 b^3)\sqrt{-2}$
We can solve the sqrt part $3 a^2 b-2 b^3 = 1$ because $b^2$ must be $1$ because $b$ is a factor on the LHS !!
Let $b=1$ then we get $3a^2 - 2 = 1$ hence $a=1$.
It follows $x=a^3 - 6a b^2 = 5$.
If we took $b=-1$ or factored $x-\sqrt{-2}$ we get the same or a negative solution for $x$ hence $x=5$ is the only positive solution.
We thus get $5^2 + 2 = 3^3$
Q.E.D.
mick


text:
Q: calling js function in PHP Post Request I'm trying to call a javascript function after making a POST request using Jquery $.post()
post request sends base64 image data and writes it down in the server the problem is that the post request is done and the file is uploaded but there is no javascript function called
getCounterNumber(); is not working, the function supposed to do this
function getCounterNumber(Path){
  Tesseract.recognize(
  Path,
  'eng',
  { logger: m => console.log(m) }
).then(({ data: { text } }) => {
   window.location.href = "getcounterreading.php?counterNumber="+text+"";
})
}

jQuery crop button click
            var base64data = reader.result;
            $.post('http://127.0.0.1/counter/uploadcounter.php', {image:base64data},
            function(response){
                  bs_modal.modal('hide');
                  alert("success upload image");
                      window.location.href = "uploadcounter.php";
                      console.log(response);

              });

uploadcounter.php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$folderPath = '../../uploads/counters/';

$image_parts = explode(";base64,", $_POST['image']);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . uniqid() . '.png';
file_put_contents($file, $image_base64);
echo ("image uploaded successfully.");
console.log($file);
echo '<script>getCounterNumber("'.$file.'")</script>';
}

A: Don't return a  tag.
Return a JSON instead.
Your Javascript
(I'm using $.ajax() instead of $.post() for no particular reason. Maybe because it's more descriptive):
let base64data = reader.result;
let postData = { image:base64data };

$.ajax({
    type: "POST",
    url: 'http://127.0.0.1/counter/uploadcounter.php',
    data: postData,
    success: (result) => {
        bs_modal.modal('hide');
        getCounterNumber(result.data.file);
        alert("success upload image");
        console.log(response);
    },
    error: (error) => {
        alert("There was an error. Check JS Console.");
        console.log(error);
    },
    dataType: 'json'
});

Your PHP
if ('POST' === $_SERVER['REQUEST_METHOD']) {
    $folderPath = '../../uploads/counters/';

    $image_parts = explode(";base64,", $_POST['image']);
    $image_type_aux = explode("image/", $image_parts[0]);
    $image_type = $image_type_aux[1];
    $image_base64 = base64_decode($image_parts[1]);
    $file = $folderPath . uniqid() . '.png';
    file_put_contents($file, $image_base64);

    header("Content-Type: application/json");
    echo json_encode(["file" => $file]);
    exit();
}

Please note that I haven't run nor tested the code. It's just an example that you can follow as an inspiration.


text:
Q: If certain URLs loaded, then interrupt not working I've got a webview, and it posts a login string, changes view, then loads the page:
    String url = uurrll;
            mWebview .postUrl(url, EncodingUtils.getBytes(fullpost, "BASE64"));
            mWebview.setWebViewClient(new WebViewClient() {

                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if(url.contains("/logout")) {
                        view.stopLoading();
                        setContentView(R.layout.preweb);
                        addListenerOnButton();
                        return true;
                    }
                    if(url.contains("/loginf")) {
                        view.stopLoading();
                        setContentView(R.layout.preweb);
                        addListenerOnButton();
                        return true;
                    }
                    else {
                        return false;
                    }
                }

            });

And within that, I'd like to constantly monitor what URL is being loaded.  If a user clicks a hyperlink within the page and the url contains a certain pattern, I want to stop the loading and redirect to whatever.  The above code is just an example of what I've got in there for testing right now.
I can't get it working.  If a URL pops up that has "loginf" in it, nothing happens at all.  I've tried moving the shouldOverrideUrlLoading to different parts in my code, but it doesn't work anywhere.
Any advice, or am I going about this completely wrong?
EDIT:  I believe this is because the new URL that the webpage is calling is through Javascript.  How do I read/interrupt the URL request when its coming from Javascript?

A: I think the key is setContentView(R.layout.preweb);, you use it in new WebViewClient()
If you want to redirect to another url , use mWebview.postUrl();
If you want to show other layout, use XXActivity.this.setContentView(R.layout.preweb);
Debug UI GUIDE
now, the tool locates at $ANDROID_HOME/tools/monitor


text:
Q: How can I identify non deterministic updates occurring in my SQL Server? SQL Server books online states

Use caution when specifying the FROM clause to provide the criteria
  for the update operation. The results of an UPDATE statement are
  undefined if the statement includes a FROM clause that is not
  specified in such a way that only one value is available for each
  column occurrence that is updated, that is if the UPDATE statement is
  not deterministic.

I need to try and identify cases where non deterministic updates are occurring in our database. It appears that SQL Server does not throw an error or warning in such a case.
Does anyone know if there is an easy way of identifying where these issues are occurring, querying plan cache etc?. Doing a full code review to identify these issues will be time consuming given the size and complexity of the application.
Tested on SQL Server 2008\2017 developer editions.
Here is an example:
declare @t1 table (id int, col int);
insert into @t1 values(1,1);

declare @t2 table (id int, col int);
insert into @t2 values(1,10), (1,20);

update t1
set t1.col = t2.col
from @t1 t1 join @t2 t2
         on t1.id = t2.id;

select *
from @t1;

A: SQL Server does not warn you of this when using its proprietary UPDATE syntax. The MERGE statement would throw an error "The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row."
The execution plan for your example is
update t1  set t1.col = t2.col  from @t1 t1 join @t2 t2           on t1.id = t2.id
  |--Table Update(OBJECT:(@t1 AS [t1]), SET:(@t1.[col] as [t1].[col] = @t2.[col] as [t2].[col]))
       |--Stream Aggregate(GROUP BY:([Bmk1000]) DEFINE:([t2].[col]=ANY(@t2.[col] as [t2].[col])))
            |--Nested Loops(Inner Join, WHERE:(@t2.[id] as [t2].[id]=@t1.[id] as [t1].[id]))
                 |--Table Scan(OBJECT:(@t1 AS [t1]))
                 |--Table Scan(OBJECT:(@t2 AS [t2]))

The Bmk column is output from the scan on @t1 to act as a unique row identifier. The, potentially multiple, joining rows from @t2 are then added and collapsed down to an arbitrary one per Bmk using the ANY aggregate. The plan may in some circumstances replace the ANY aggregate with a DISTINCT SORT
So one way would be to search the plan cache for all execution plans containing update operators that have a descendant operator using either ANY or DISTINCT SORT as this may be a sign that SQL Server was arbitrarily removing the duplicates before doing the update.
This is far from fool proof as they may appear in the plans for other reasons but should give some viable candidates to review.
WITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')
SELECT st.text
FROM   sys.dm_exec_cached_plans cp
       CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) qp
       CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st
WHERE  EXISTS(SELECT 1
              FROM   qp.query_plan.nodes('//Update') upd(n)
              WHERE  1 IN ( n.exist('//Aggregate[@AggType eq "ANY"]'),
                            n.exist('//RelOp[@LogicalOp eq "Distinct Sort"]') ))


text:
Q: Automatically mount network drive when available I have a NAT drive, that is accessible via SMB. I have an entry in fstab to mount it at boot.
But if the drive is not switched on it is not mounted during boot and I have to manually mount later.
(The NAT boots a lot slower than my PC and usually is not up at the point PC tries to mount it).
Is there a way to automatically mount the drive when it becomes available in the network?
Preferably if it can be done via command line tools, not involving GUI programs.
Using PCLinuxOS with KDE.

A: What you're looking for is AutoFS. Install the RPM, then make sure that it's running at start(RH/etc: chkconfig autofs on). Edit the file /etc/auto.master and add the following line: /media/ /etc/auto.media. If I were you, I would change "media" in both places to be the name of your root-level directory. Then edit the file /etc/auto.media and add finaldirname mount-options \\192.168.1.3\sharename
A quick google gives this page.


text:
Q: Como redireccionar una url con expresiones regulares Estoy usando el plugin redirection y quiero redireccionar de una url de categoría a una url de articulo.
De https://www.misitio.com/perros-gatos/razas/page/12/
a Url destino: https://www.misitio.com/razas/
Lo que yo habia hecho era redireccionar de https://www.misitio.com/perros-gatos/razas/ a https://www.misitio.com/razas/
Con este último todo funciona bien salvo en el paginado, donde estoy obteniendo errores 404.
https://www.misitio.com/perros-gatos/razas/page/12/
He estado probando:
de:  ^/perros-gatos/razas/([A-Za-z0-9-]*)/$
a:   misitio.com/razas/
Pero el código no me funciona.

A: Si mueves de misitio.com/perros-gatos/razas/page/12 a misitio.com/razas, estás perdiendo la paginación. Así que entiendo que lo que quieres es que el número de página esté oculto de alguna manera.
Si es así, no podrás usar el .htaccess para tal fin, ya que no puedes convertir peticiones GET en POST (mira esta pregunta en SO)
Una posible solución sería tener la página misitio.com/razas donde todos los datos/páginas se reciban vía peticiones AJAX. De esta manera, en la url de la página nunca se llegaría a ver el número de la misma. Iría como parámetro en las distintas peticiones AJAX que realices.


text:
Q: Working Chainway C72 UHF sample code for Android 11 version From what I can gather Chainway changed the API to their hardware library with the move from Android 7 to Android 11 causing almost all the current packages for different frameworks out there to no longer work. Does anyone have working sample code for the Chainway C72 running on Android 11 other than this buggy Android Studio sample project? Biggest preference would be Xamarin/Maui or Flutter, but honestly any stable code would be greatly appreciated.
What we've tried:
We have noticed that most of the libraries use a deprecated API class called RFIDWithUHF.
We contacted Chainway technical support and they provided us with firmware update files and mentioned that we should use RFIDWithUHFUart class instead. They provided an Android Studio sample project, if you restart the device and run the project you are able to scan RFID tags, but it is extremely buggy and quickly crashes. Closing the app and restarting it unfortunately does not recover it from this state even though the code does a free and initialise on startup. You have to reboot the device to get it out of this state.
We attempted to use the following packages/libraries with the following results:

*

*Using these three Nuget packages on Xamarin 1 2 3 - Initialize method always return false and we're unable to scan tags

*Using this flutter package - We got the following printouts on our console:

An Observatory debugger and profiler on C72 is available at: http://127.0.0.1:61316/iEK5kGMghqQ=/
The Flutter DevTools debugger and profiler on C72 is available at: http://127.0.0.1:9101?uri=http://127.0.0.1:61316/iEK5kGMghqQ=/
I/DeviceAPI_DeviceCon(30538): getDeviceInfoFromFile configPath=/storage/emulated/0/PDAConfig.txt
D/DeviceAPI_DeviceCon(30538): cw.model2:
D/DeviceAPI_DeviceCon(30538): cw.model:mtk.6765.c72
D/DeviceAPI_DeviceCon(30538): 最终cw.model:mtk.6765.c72
I/DeviceAPI_DeviceCon(30538): model=C72,uartPath=/dev/ttyMT3,uartPath_Fingerprint=/dev/ttyMT0,uartPath_RFID=
I/DeviceAPI_DeviceCon(30538): getModel() model=C72
D/DeviceAPI(30538): UHF device = C72
D/DeviceAPI(30538): UHF_Init----------->DevIsOpen = 1
D/DeviceAPI(30538): UHF uart = /dev/ttyMT3
D/DeviceAPI_SerialPort(30538): [SerialPort_Open] [2]: No such file or directory
D/DeviceAPI(30538): UHF uhf_uart_fd = -1
I/DeviceAPI_UHF(30538): init() Uart = /dev/ttyMT3
E/DeviceAPI_UHF(30538): init() err UHFOpenAndConnect result:-1
E/DeviceAPI_UHF(30538): startInventory() err :-1

*

*This react package - Get the following build error:

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.
-----------
* Where:
Build file 'C:\Repos\Sandbox\ReactNative\c72ScannerReact\node_modules\c72-rfid-scanner\android\build.gradle' line: 23

* What went wrong:
A problem occurred evaluating project ':c72-rfid-scanner'.
> Plugin with id 'maven' not found.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
A problem occurred configuring project ':c72-rfid-scanner'.
> compileSdkVersion is not specified. Please add it to build.gradle

*

*We've also tried all the example code here with no luck either.

A: I am also looking at the same device (Xamarin).  I was not able to get the samples online working, but after contacting tech support I received working sample code.


text:
Q: Cleaning stdin buffer issue Say I have the following piece of code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main() {
    char choice;
    char name[5] = "";
    do {
        printf("a = new name or anything else to quit\nChoice: ");
        choice = getchar();
        //not doing any error handling....assuming you only click 'a'
        switch (choice) {
            case 'a':
                getchar();
                printf("Enter a name which is 4 characters or less: ");
                fgets(name, 5, stdin);
                printf("Name: %s\n", name);
                char c;
                while ((c = getchar()) != '\n' && c != EOF);
                printf("%c", c);
                c = '\0';
                break;
            default:
                break;
        }

    } while (choice == 'a');
    printf("Ending.....press enter now");
    getchar();
    return 0;
}

What I am try to test here is clearing buffer when I have more than 4 characters typed into. It works fine whenever I have a name which is 4 chars or more, however when I hit 3 chars or less, the problem becomes the while loop. It expects a getchar() from the stdin buffer, however this is empty. What way is there to work around this issue?

A: You need to check if name contains a newline character.  If it does, there's nothing in the buffer and you don't need to flush it.
    fgets(name, 5, stdin);
    printf("Name: %s\n", name);
    if (strchr(name, '\n') == NULL) {
        int c;
        while ((c = getchar()) != '\n' && c != EOF);
    }

A: We already discussed this in passing in the commentary on my answer to your previous question.  If there is room for it in the buffer, fgets() will consume the terminating newline, placing it in the buffer.  You can determine whether it has done so by looking for a newline in the buffer.  If you find one, then

*

*You probably want to remove it -- by replacing it with '\0', for example.

*You should avoid trying to drain the tail of the input line, because the stream has already advanced to the next line.

A: *

*Check the result of fgets().  Unless code does so, using the contents of name may be undefined behavior.  Avoid magic numbers: uses sizeof name.
        // fgets(name, 5, stdin);
        if (fgets(name, sizeof name, stdin) == NULL) Handle_EOF();

*Look for a potential '\n' in name[].
        char *eol = strchr(name, '\n');

*If one is found, overwrite with the null character, else consume the rest of the line
        if (eol) {
          *eol = '\0';
        } else {
          int ch;
          while ((ch = getchar()) != '\n' && ch != EOF);
        }

*Print name[]
        printf("Name: %s\n", name);


text:
Q: Defining the length of sequence instead of the step size I am new to python and want a function which produces a list that contains a number of integers i.e. [1,3,5,7....] like you can do with the range function i.e. range(1,21,2).
However instead of setting the upper limit I want to set how long the list should be, so I would state the starting point, the step and the number of integers I want in my list.  Does such a function exist?

A: No, but it's pretty easy to make one:
def myrange(start, step, count):
    return range(start, start + (step * count), step)

short demonstration:
>>> myrange(10, 2, 5)
[10, 12, 14, 16, 18]
>>> myrange(10, -2, 5)
[10, 8, 6, 4, 2]

In python 3 it'll return a range object, just like the regular range() function would:
>>> myrange(10, 2, 5)
range(10, 20, 2)
>>> list(myrange(10, 2, 5))
[10, 12, 14, 16, 18]

A: Martijn Pieter's answer is good for integers. If start orstep may be floats, you could use a list comprehension:
[start+i*step for i in range(count)]


text:
Q: opengl shader make color "disappear" I'm new to opengl and shaders. I'm trying to do some augmented reality on the iphone and messing about with shaders to alter a feed from the camera.
What I'm trying to achieve is the appearance that an object in a picture has disappeared by setting the color to match the surrounding colour. I have a yellow rectangle and in it is a small red circle. I want to give the impressed the red circle has disappeared by setting the colour to be yellow.
It won't always be solid colours but I'm just trying to get the basics down first.
Currently I have a simple shader which will make a red colour lighter but this isn't ideal because it doesn't get close to the surrounding colour and I want this to work for different coloured objects and different coloured surrounding.
I'm not even 100% shaders are what I need to be looking at or even opengl. I'm using it because of the performance it gives on the iPhone.
I'm basically asking if:

*

*Anyone has done or seen anything similar

*Am I barking up the wrong tree using opengl es and opengl sl?

*Is this even possible?

Cheers.

A: Have you heard of alpha blending?
Colors have 4 channels. Red, green, blue, and alpha (rgba). The alpha channel determines the transparency. You can set it to anything in between 0 (fully transparent/invisible) or 1 (fully solid).
To make your object invisible, simply set alpha to 0!
For example in your frag shader:
gl_FragColor.a = 0;

You can achieve this without using shaders by changing the alpha value from your program.
For example:
glColor4f(1.0, 0.0, 0.0, 0.5); //Draws something red with half transparency (hence the 0.5)
glVertex3f(...);
glVertex3f(...);
glVertex3f(...);

Just make sure you have alpha blending enabled:
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);


text:
Q: how to Extract a Field from a line wit tab delimer in java I have a c++ method extractField that I would like to use to axtract some fields from a line each field delimited by '\t' it works well in c++ could someone help me with the syntax for java. I would like to apply a similler method_ here is what I have:
    String ExtractField(String aline,int fieldnumber){
    Int seppos;
    String field;
    for (int fld = 0: fld< fieldnumber;fld++){
      seppos = aline.Pos('\t');
      field = aline.SubString(1,seppos-1);
      aline.delete(1.seppos);
    }
     If(seppos>0){return field;}
     else{return aline;}
    }

A: The folowing is in java, rewrote it for you ;)
private String ExtractField(String aline, int fieldnumber)
{
    Integer seppos = new Integer();
    String field;
    for (int fld = 0; fld < fieldnumber; fld++)
    {
      seppos = aline.indexOf('\t');
      field = aline.substring(1, seppos - 1);
      //aline.delete(1.seppos); what does this do?
    }
     If(seppos > 0)
     {
         return field;
     }
     else
     {
         return aline;
     }
}

A: Use StringTokenizer
 StringTokenizer st = new StringTokenizer(aline, "\t");
 while (st.hasMoreTokens()) {
     System.out.println(st.nextToken());
 }

A: I think this will do what you want.
public String extractField(String aline, int fieldNumber) {
    String[] fields = aline.split("\t");
    //Illegal field NUmber.
    if (fieldNumber < 0 || fieldNumber >= fields.length) {
        return null;
    }
    return fields[fieldNumber];
}


text:
Q: How to remove two objects with the same ID but different date values with LINQ to objects I have a List<dynamic> in which I have N records with the same ID but different ValidTo/ValidFrom values.
Say I had these objects:
Id: 1, ValidFrom: 1/1/2012, ValidTo: 1/1/2015
Id: 1, ValidFrom: 1/1/2013, ValidTo: 1/1/2015.
Id: 2, ValidFrom: 6/1/2012, ValidTo: 1/1/2015
Id: 2, ValidFrom: 6/1/2013, ValidTo: 1/1/2015
Id: 3, ValidFrom: 12/1/2012, ValidTo: 1/1/2015
Id: 3, ValidFrom: 12/1/2013, ValidTo: 1/1/2015

Given that, I'd want to either remove the old records from the current collection (for each ID, the one with the lowest ValidFrom date), or, just get a new collection that has each of the IDs, but the ones that have the greatest ValidFrom date.
So, the expected output would be:
Id: 1, ValidFrom: 1/1/2013, ValidTo: 1/1/2015.
Id: 2, ValidFrom: 6/1/2012, ValidTo: 1/1/2015
Id: 3, ValidFrom: 12/1/2013, ValidTo: 1/1/2015

That is, of the two records that had ID of 1, the one with the lowest ValidFrom got discarded, and so on for ID2 and ID3.
I think it'd be done through grouping, I'm just not sure how.
Thanks for the help.

A: list.GroupBy(x => x.Id)
    .Select(group =>
            group.OrderByDescending(record => record.ValidFrom).First())

This answer is from memory, and I don't have a compiler handy to check it.
I'm assuming that the dates are actually DateTime objects. If they're just strings, you would need to change the logic to account for that.


text:
Q: Pick random items from list without iterations I have the following code in Rails
@related = []
while @related.compact.size < 3
  @tag = @car.tag_list.sample #pick a tag from the @car's tag_list
  @sametags = Car.tagged_with(@tag) # get all cars with that tag
  @related.push(( @sametags - Array(@car) - @related.compact).sample) #put that car in @related
  @counter = @counter + 1 #increment
  break if @counter == 10 #stop if its taking too long
end

I am well aware this code is highly inefficient, but my ruby chops aren't up for it yet...
basically what I need to have done is to populate @related with 3 Car models with similar tags randomly in way which they will not repeat.

A: Array#sample accepts a number, size of the sample. So I think, your code can be simplified to this:
@tag = @car.tag_list.sample
@sametags = Car.tagged_with(@tag)
@related = (@sametags - [@car]).sample(3)

A: You can use random ordering to do this.
@related = Car.limit(3).order('rand()').tagged_with('blood red')

UPDATE: without @car
@tag = @car.tag_list.sample
@related = Car.where('id != ?', @car.id).limit(3).order('rand()').tagged_with(@tag)

UPDATE: if you are using acts_as_taggable_on
@related = Car.where('id != ?', @car.id).limit(3).order('rand()')
  .tagged_with(@car.tag_list, any: true)

A: Use scramble to shuffle the array first and then just pick the top three items.
[1,2,3,4].scramble => [3,1,2,4]


text:
Q: Is Amazon S3's ListObjectsV2 self-consistent over multiple pages? ListObjectsV2 can only return 1000 results, at which point you have to go back for another page.
Since Amazon S3 is now strongly consistent, and other updates can be happening to the bucket while I am listing its contents, is the second page going to be more results from the same point in time as the first page? Or is it going to reflect the state of the bucket at the point in time when the second page was requested?
For example, if I list a bucket, get the first page, delete a key which would have appeared on the second page, and then get the second page, will I still see the key that is now deleted?

A: Indeed, Amazon S3 is now strongly consistent.  This means once you upload an object, all people that read that object are guaranteed to get the updated version of the object.  This does not meant that two different API calls are guaranteed to be in the same "state".  Notably, for downloads, there is a situation where one download can get parts of two versions of the object if it's updated while being downloaded.  More details are available in this answer.
As for you question, the same basic rules apply:  S3 is strongly consistent from one call to the next, once you make a change to the bucket or objects, any call after that update is guaranteed to get the updated data.  This means as you page through the list of objects, you will see the changes as each API call gets the latest state:
import boto3

BUCKET='example-bucket'
PREFIX='so_question'

s3 = boto3.client('s3')

# Create a bunch of items
for i in range(3000):
    s3.put_object(Bucket=BUCKET, Key=f"{PREFIX}/obj_{i:04d}", Body=b'')

args = {'Bucket': BUCKET, 'Prefix': PREFIX + "/",}
result = s3.list_objects_v2(**args)
# This shows objects 0 to 999
print([x['Key'] for x in result['Contents']])

# Delete an object
s3.delete_object(Bucket=BUCKET, Key=f"{PREFIX}/obj_{1100:04d}")

# Request the next "page" of items
args['ContinuationToken'] = result['NextContinuationToken']
result = s3.list_objects_v2(**args)
# This will not show object 1100, showing objects 1000 to 2000
print([x['Key'] for x in result['Contents']])

The upside of this and there's no way to get a list of all objects in a bucket (assuming it has more than 1000 items) in one API call: there's no way I'm aware of to get a complete "snapshot" of the bucket at any point, unless you can ensure the bucket doesn't change during listing the objects, of course.


text:
Q: Assigning user-determined coordinates to a nested array I have two integers, range1 and range2, and a nested integer array distance[][].
I also have two integer arrays, elasticity[] and resistance[], both containing a group of user-determined values. The aforementioned range1 is equal to the length of elasticity[], whilst range2 is equal to the length of resistance[].
What I'm trying to do is set each location in distance[][] to a specific "coordinate". As an example, assume range1 = 2 and range2 = 3:
    distance[0][0] = elasticity[0] * resistance[0];
    distance[0][1] = elasticity[0] * resistance[1];
    distance[0][2] = elasticity[0] * resistance[2];
    distance[1][0] = elasticity[1] * resistance[0];
    distance[1][1] = elasticity[1] * resistance[1];
    distance[1][2] = elasticity[1] * resistance[2];

and so forth. Obviously I can't use anything like the above example, because the values of range1 and range2 are a result of the user's input to elasticity[] and resistance[], and so may be different every time the program runs. I attempted to use a nested for loop, like so:
    int distance[range1][range2];

    for(int i = 0; i <= range1; i++)
    {
        for(int j = 0; j <= range2; j++)
        {
            distance[i][j] = elasticity[i] * resistance[j];
        }
    }

which, as far as I can tell, should work, but Xcode just spat runtime errors at me.
Anyway, I'm not sure what I can do to fix this; the program is supposed to take three values from the user (the minimum + maximum resistance values, and an increment size for the elasticity) in order to calculate the maximum distance of a projectile and output the results in the form of a table.
Help!

A: First of all, if using plain C, you need to provide constant values for the matrix dimensions (you need to set maximum values for range1 and range2, like this for instance:
int distance[200][200];

This means the maximum of range1 and range2 is 200
Then, in the loop condition, you need to take into account that array indexing is 0-based. Therefore, if you have say, 4 elements in an array, their indexes will be 0, 1, 2 and 3.
So, you need to change your code like this:
for(int i = 0; i < range1; i++)
{
    for(int j = 0; j < range2; j++)
    {
        distance[i][j] = elasticity[i] * resistance[j];
    }
}

so that the index is always less than the array dimension.
I hope this helps.
Cheers.


text:
Q: MySQL eats up all the memory from the RHEL OS Currently, I have MySQL server installed in the AWS RHEL EC2 instance.
The team was running heavy data processing in the DB and we found out that every now and then the DB restarted itself. After troubleshooting, we realized that the DB was actually killed by the OS! Because the MySQL is so hungry that it consumes all the memory in the OS.
The OS has 124GB RAM and 68GB is allocated to innodb_buffer_pool_size.
Attached my.cnf file
Question:
How do we prevent the OS from killing the mysqld?
    [mysqld]
# Server configuration
user=mysql
port=3306
socket=/home/mysql/server/run/mysql.sock

# File locations
datadir=/mysql/data
basedir=/home/mysql/server
lc_messages_dir=/usr/share/mysql-8.0
plugin-dir=/lib64/mysql/plugin
innodb_log_group_home_dir=/redolog/redologfiles
innodb_data_file_path=ibdata1:12M:autoextend
log-error=/home/mysql/server/logs/mysqld.log
innodb_log_file_size=2147483648
innodb_log_files_in_group=8
innodb_page_size=16384
innodb_checksum_algorithm=crc32
innodb_buffer_pool_filename=ib_buffer_pool
innodb_undo_tablespaces=2
innodb_buffer_pool_filename=ib_buffer_pool
skip-log-bin

# New server config
character-set-server=latin1
collation-server=latin1_swedish_ci
connect_timeout=31530000
net_read_timeout=31530000
net_write_timeout=31530000
innodb_buffer_pool_size=68719476736
innodb_buffer_pool_instances=64
innodb_temp_data_file_path=ibtmp1:512M:autoextend:max:512000M
innodb_max_undo_log_size=4294967296
innodb_read_io_threads=16
binlog_expire_logs_seconds=259200
#expire_logs_days=10
max_binlog_size=1073741824
sql_mode = ''
max_connections=300
log_timestamps=SYSTEM
local_infile = 1
max_digest_length = 3072
performance_schema_max_digest_length=10240
max_digest_length=10240
performance_schema_max_sql_text_length=10240
innodb_adaptive_hash_index = 0

interactive_timeout  = 86400
mysqlx_interactive_timeout  = 86400
mysqlx_wait_timeout  = 86400
wait_timeout  = 86400

general_log = OFF
general_log_file = /home/mysql/server/logs/mysqld_db.log
[client]
port=3306
socket=/home/mysql/server/run/mysql.sock

#slow_query_log_file=/home/mysql/server/logs/mysql-slow.log
#slow_query_log=ON
#general_log_file=/home/mysql/server/logs/mysql_gen_db.log
#general_log=ON

A: 9 times out of 10 this is due to a hungry query. Set long-query-time to something < 2 and once you have a good sample size analyse the log file using the Percona tool pt-query-digest. This should give you a good place to start.
Try splitting your transactional and analytical workloads. Running them on different hardware is common place.


text:
Q: A little question of injectivity and density on $C[-1,1]$ Let $T$ be the linear map $T: C[-1,1] \to C[-1,1]$ given by $Tx(t)=\int_{0}^{t}x(s)ds$.

*

*I try to to show that $T$ is 1-1. $Tx=0 \Rightarrow 0=Tx(t)=\int_{0}^{t}x(s)ds$. By the fundamental theorem of calculus, $x(t)=0$ for all $t \in [0,1]$. How can I conclude that $x(t)=0$ for all $t \in [-1,1]$?

*I try to show that the range of $T$ is dense in $C[-1,1]$. I can see that $T$ is not onto: Suppose $T$ is onto and $y \in C[-1,1]$ with $y(0) \neq 0$. Then $\exists x \in C[-1,1]$ such that $Tx=y$ i.e. $\int_{0}^{t}x(s)ds=y(t) \Rightarrow x(t)=y(t)$ for all $t \in [0,1] \Rightarrow y(t)=Tx(t)=Ty'(t)= \int_{0}^{t}y'(s)ds=y(t)-y(0)$ for all $t\in [0,1]$, contradiction. But how can I conclude that T is not dense in $C[-1,1]$?
Thanks.

A: *

*Use the other version of the fundamental theorem of calculus (what is the derivative of $Tx$?)

*The image is not dense, because it is contained in the closed(!) strict subspace
$$
\{f \in C([-1,1]) \mid f(0) = 0\}.
$$


text:
Q: How to use GUI in C? I'm learning C and want to write programs with GUI. Personally I'm OK with terminal in Linux or the black window in Windows. However, I want to write something that could be used by other non-professional users. So I wrote this post to ask how to write a GUI program in C (C++ is OK). What kind of books should I read? Or anything else I need to know. Thank you.

A: For pure C, you could use GTK+, but if you're familiar with C++ too, i 'd recommend Qt Framework from Nokia. There are over 100 of youtube videos for mastering Qt. Follow this link: Qt training

A: For cross-platform (linux/windows/mac) in C, I think GTK is predominant but note that GTK is unlikely to be installed on most non-linux systems.
For cross-platform in C++, WxWidgets is popular because it uses the underlying native GUI library, hence the applications have a look and feel that blends in.  There's also Qt, but this does not use the native infrastructure, so the applications do not blend in (unless the system is predominantly Qt, just as GTK does not blend in, unless the system is predominantly GTK).
Windows and linux have a native C GUI API (for linux, GTK, which as mentioned is also portable).  I would guess that OSX uses objective C natively.

A: Depending on the OS, you'll have to look at some form of API that will communicate with said OS in order to program a GUI application.
On Windows it'd be good to become familiar with the Win32 API. Microsoft has a basic tutorial
I'm personally not a fan of their documentation but it's a place to start.
For OSX, you have Cocoa, (although for that you'd have to learn Objective-C, which is based off C).
As for linux, it would appear that there are various toolkits you can use to program a GUI, such the previously mentioned GTK. (Which is cross-platform.)

A: Since you clarified C under Linux, you would do well to learn GTK+.
If you want to use a text based user interface you can use the curses library.
Here is a book you might pick up to learn GTK+


text:
Q: Infinity Blade 2 on my Ipod When I download the game Infinity Blade 2 on my Ipod, I open it and it appears to me that the Ipod sensed a saved progress of the game. It was my first time playing Infinity Blade 2 on my iPod and it has a saved game. Why is that? Also, when I play the game, it is very laggy on my iPod but not on my familiy's iPad.

A: Could it be that someone played it first on the iPad? Then the saved game transferred to your iPod through iCloud.
As for the lag, it is probably due to the hardware, your iPad must have better components than your iPod. You can compare them in this list of iOS devices.

A: turn off or delete icloud on infinity blade(that will fix save problem). try cleaning space(will fix lag problems)


text:
Q: Module Not Found: Can't resolve 'http2' when importing firebase-admin         Failed to compile
    ./node_modules/@grpc/grpc-js/build/src/channel.js
    Module not found: Can't resolve 'http2' in '/Users/Michael/Development/Projects/mpsa-ntcs/node_modules/@grpc/grpc-js/build/src'

This error occurred during the build time and cannot be dismissed.

I keep getting this error when importing firebase-admin to my app. I tried updating GRPC, tried downgrading/upgrading node, reinstalled node + npm... everything!!
Anyone know any workarounds for this?
Thanks!

A: I believe you need to install the deprecated 'http2' package. Try running:
npm install http2

A: I have changed to use yarn.
Remove
yarn remove firebase-admin
Install again
yarn add firebase
yarn add firebase-admin
yarn add http2
And my code can work.
I think yarn is better than npm.
Note: http is supported from node version 9.0.0. My Node version is 13.


text:
Q: What's difference between C parity and charge? I know C parity as an operator :
$$
C\psi=\pm\psi
$$
has two eigenvalues like parity operator P. But what I wonder is, i.e, is it true to say for a negative charged particle has (-) eigenvalue? If not what is the way to relate them?

A: The charge parity operator $\newcommand{\C}{\mathcal C}\C$ takes each particle to its antiparticle, which has opposite charge. As such, its eigenstates are those states that remain the same if you change all particles for their antiparticles. This can happen, for example,

*

*in a state that contains two particles which are each other's antiparticle, such as one electron and one positron, in which case switching the electron to a positron and the positron to an electron does not change the total particle content of the state, or

*in a state that only contains particles that are their own antiparticles, like bosons or Majorana fermions.

A state that contains a single electron, on the other hand, will not be an eigenstate of $\C$. Instead, it is an eigenstate of the total charge operator $\mathcal Q$, for which its eigenstate is indeed $-1$.


text:
Q: Mule request-reply - why can't we use transactional VM or JMS inside the scope Mule doc says that, VM or JMS connectors that are set up to be transactional can't be used inside a request-reply scope. I do not understand it well.
Can any one please explain it with an example?

A: What are you trying to achieve?
The URL that you point to explains exactly why it isn't possible.
VM or JMS connectors that are set up to be transactional can't be used inside a request-reply scope. Both VM and JMS connectors allow you to perform transactions of several different types, but none of these are compatible with how the request-reply scope works. This is because the request that is to be sent out by the request-response isn't sent until the transaction is committed – but the transaction in turn is not committed until the entire flow has been executed (including the execution of the request-response scope). This leads to a situation where both processes are blocking each other: the flow isn't fully executed because it's still waiting for the response on the request-reply scope, but this response will never arrive since the request hasn't been sent yet (as mentioned before, this message is sent only once the transaction is committed).


text:
Q: Check if Gradient is too light javascript I'm trying to add a gradient to every element to each page, for now, I've achieved it but I've run into a problem.
If the gradient is too light my text is not visible, is there any way to check if the gradient color is too light and then change the text to black?
Here is my code
This is the gradients element =  https://github.com/ghosh/uiGradients/blob/master/gradients.json
const cards = document.querySelectorAll('.card');
    cards.forEach((card)=>{
            let i = Math.floor(Math.random() * gradients.length);
            const color = gradients[i].colors;
            color.forEach((color)=> {
                let finalGradient = `background: linear-gradient(to right, ${color}, ${color}, ${color}) !important;`;
                card.style.cssText = finalGradient;
            })
        })

A: Here a function that I use to detect if a color is light or dark. You can use it and adapt to your code:
function isLightOrDark(color) {

    // Variables for red, green, blue values
    var r, g, b, hsp;

    // Check the format of the color, HEX or RGB?
    if (color.match(/^rgb/)) {

        // If HEX --> store the red, green, blue values in separate variables
        color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);

        r = color[1];
        g = color[2];
        b = color[3];
    }
    else {

        // If RGB --> Convert it to HEX: http://gist.github.com/983661
        color = +("0x" + color.slice(1).replace(
        color.length < 5 && /./g, '$&$&'));

        r = color >> 16;
        g = color >> 8 & 255;
        b = color & 255;
    }

    // HSP (Highly Sensitive Poo) equation from http://alienryderflex.com/hsp.html
    hsp = Math.sqrt(
    0.299 * (r * r) +
    0.587 * (g * g) +
    0.114 * (b * b)
    );

    // Using the HSP value, determine whether the color is light or dark
    if (hsp>127.5) {

        return 'light';
    }
    else {

        return 'dark';
    }
}


text:
Q: Modifying state of other objects in a constructor: design no-no? I'm refactoring some code and found this (simplified of course, but general idea):
class Variable:
    def __init__(self):
        self.__constraints = []

    def addConstraint(self, c):
        self.__constraints.append(c)

class Constraint:
    def __init__(self, variables):
        for v in variables:
            v.addConstraint(self)

The fact that the constructor of Constraint modifies other object's states instead of its own smells a little funky to me.  What do other people think - is this OK, or is it a prime candidate for refactoring?
Edit: My concern is not the parent/child relationship, but that it is linked up inside the constructor rather than in a separate method.

A: I see it as a self registration pattern. "Hello I'm new here, please allow me to join."
I might prefer to have a differently named method so that the purpose is more clear, but I do actually quite like the approach.

A: I entirely concur with @djna's answer that the specific use case is perfectly legit -- here, it's an example of an object needing to en-register itself with a specified set of registries "at birth".
A very sharp and extremely common subcase of that would be an observer object that exists strictly for the purpose of observing a given observable -- perfectly fine to pass the observable to the observer's initializer, and exactly the right way to ensure the class invariant "instances of this observer class are at all times connected to exactly one observable", which would be not established "at birth" if the registration was carried out only after the completion of initialization.
Other similar cases include for example a widget object that must at all time exist within a container window: it would somewhat weird to implement it otherwise than having the widget take the parent as an initializer argument and tell the parent "hi, I'm your new child!".
At least in those 1-many cases you could imagine forcing the parent or observable to have a method that both creates and enregisters the new object.  In a many-many case like this one, the somewhat inside-out nature of that approach gets revealed -- since the constraint must be registered with multiple variables, it would be "against the grain" to ask any specific one of them to create the constraint.  The code you supply on the other hand is perfectly natural.
Only for cases that cannot reasonably be framed as the new object "enregistering itself" would I feel some doubt (there are a few other legit ones, such as objects creating and enregistering other auxiliary ones at birth, but they're nowhere near as common).

A: I agree with you. That's backwards. There may be some good reason for why, but it's unclear programming and it likely to bite someone if the foot sooner or later.

A: This is common usage when you have two objects that are closely related (i.e. where only one of them alone doesn't make sense). Most common case: Parent child relations. When you add a child to a parent (i.e. parent.children.append(child)), you often also update the child.parent pointer.

A: I personally am not necessarily opposed to this, but...
I would choose one usage pattern, and stick with it.  In your case, since Variable already has a clean addConstraint method, my preference would be to use it.
Otherwise, you'll need to add good checking to prevent the user from constructing a Constraint, and then adding it to the Variable class (thereby adding it twice).
That being said, with something like a Constraint, though, I would probably not do this.  A Constraint seems like a conceptually independent entity from a Variable.  I see no logical reason the same constraint couldn't be added to two separate variables.  I would just make it so you construct your constraint, then add them manually, specifically for this reason.


text:
Q: how to use Amazon S3 Uri links to download image? The scenario is, I got s3:// type links to work with and i am supposed to write a script to download images from that links, I don't have much idea how to do it, tried reading some posts, docs did not help much, ended up with script which was throwing some exception which I did not understand, I used boto3 here.
So basically I got these kind links s3://some-name-with-hyphens/other/and_one_more/some.jpg I need write python script to download that object.
These images are hosted on public AWS S3 bucket.
Here is Script I used, I am showing here fake s3 uri:
import boto3
def find_bucket_key(s3_path):
    """
    This is a helper function that given an s3 path such that the path is of
    the form: bucket/key
    It will return the bucket and the key represented by the s3 path
    """
    s3_components = s3_path.split('/')
    bucket = s3_components[0]
    s3_key = ""
    if len(s3_components) > 1:
        s3_key = '/'.join(s3_components[1:])
    return bucket, s3_key

def split_s3_bucket_key(s3_path):
    """Split s3 path into bucket and key prefix.
    This will also handle the s3:// prefix.
    :return: Tuple of ('bucketname', 'keyname')
    """
    if s3_path.startswith('s3://'):
        s3_path = s3_path[5:]
    return find_bucket_key(s3_path)

client = boto3.client('s3')
bucket_name, key_name = split_s3_bucket_key(
    's3://some-name-with-hyphens/other/and_one_more/some.jpg')
response = client.get_object(Bucket=bucket_name, Key=key_name)

And the exception I got:
File "C:\Users\BASAVARAJ\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\botocore\auth.py", line 373, in add_auth
raise NoCredentialsError()
botocore.exceptions.NoCredentialsError: Unable to locate credentials

A: If you don't have AWS credentials to perform the request, then you need to perform an unsigned request.  Replace the client creation with this to create a client that won't sign any requests:
import boto3
from botocore import UNSIGNED
from botocore.config import Config
client = boto3.client('s3', config=Config(signature_version=UNSIGNED))


text:
Q: Where does Firefox save currently open tabs on disk For example Chrome saves here: ~Library/Application Support/Google/Chrome/Default/Current Tabs and Safari here ~/Library/Safari/LastSession.plist. What about Firefox? I found this folder ~/Library/Application Support/Firefox/Profiles/sewzwkcf.default but I cannot spot the right file.

A: Since version 33, Firefox saves the open session in /sessionstore-backups/recovery.js, inside
your Profile Folder.
Yoric says in this blog post:

• sessionstore-backups/recovery.js
  contains the state of Firefox ≤ 15 seconds before the latest shutdown or crash...
  ...
  All these files use the JSON format.

You can see all your open tabs, windows and session info in just a single file, being updated every few seconds.


text:
Q: Udemy-dl is not recognised inspite of installing it
C:\Users\User>pip install udemy-dl
Requirement already satisfied: udemy-dl in
  c:\python27\lib\site-packages
Requirement already satisfied: requests in
  c:\python27\lib\site-packages (from udemy-dl)
Requirement already satisfied: unicode-slugify in
  c:\python27\lib\site-packages (from udemy-dl)
Requirement already satisfied: colorlog in
  c:\python27\lib\site-packages (from udemy-dl)
Requirement already satisfied: future in c:\python27\lib\site-packages
  (from udemy-dl)
Requirement already satisfied: urllib3<1.23,>=1.21.1 in
  c:\python27\lib\site-packages (from requests->udemy-dl)
Requirement already satisfied: idna<2.7,>=2.5 in
  c:\python27\lib\site-packages (from requests->udemy-dl)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in
  c:\python27\lib\site-packages (from requests->udemy-dl)
Requirement already satisfied: certifi>=2017.4.17 in
  c:\python27\lib\site-packages (from requests->udemy-dl)
Requirement already satisfied: six in c:\python27\lib\site-packages
  (from unicode-slugify->udemy-dl)
Requirement already satisfied: unidecode in
  c:\python27\lib\site-packages (from unicode-slugify->udemy-dl)
Requirement already satisfied: colorama; sys_platform == "win32" in
  c:\python27\lib\site-packages (from colorlog->udemy-dl)
C:\Users\User>udemy-dl 'udemy-dl' is not recognized as an internal or
  external command, operable program or batch file.

A: udemy-dl works as a module (udemy_dl). To invoke it, you need to call as follows:
python -m udemy_dl [URL of the course you are trying to download]

It would then ask you to input your Username & Password.
Let us know if that worked.

A: udemy-dl is possibly not installed as executable; but it is installed as python module. Find out the module's name.
Open a python interpreter in Windows command prompt:
C:\Users\User>python

In python interpreter prompt, type following command to list modules:
>>> help('modules')

Look for udemy module. It might be named as udemy_dl or similar.
Exit the python interpreter prompt:
exit()

Run udemy downloader as python module (replace udemy_dl with the module name looked earlier):
python -m udemy_dl --help


text:
Q: trying to understand this random error i get //swift class Personnage {
    var vie = arc4random_uniform(10) + 1;
    var force = arc4random_uniform(8) + 1;
    var chance = arc4random_uniform(2);
    func attaquePar(joueur1:Personnage) ->String {
        var differenceForce = self.force - joueur1.force
        var coup = differenceForce + chance
        if coup >= self.vie {
            return "tu mas eu"
        } else if coup < self.vie {
            self.vie = self.vie - coup
            return "jai rien senti macaque \(self.vie)"
        } else {
            return "heu?"
        }
}
}
let toto = Personnage()
let cafard = Personnage()
toto.attaquePar(cafard)

Hi, I am having an error message at line 6. It works some times and other it does not. Here it is : Execution was interrupted, reason EXC_BAD_INSTRUCTION (code=EXC I386_INVOP subcode=0x0).
I imagine that there is an invalid operation, but i don't undestant why i get this.

A: The return type from arc4random_uniform() is UInt32, and computing
the difference
var differenceForce = self.force - joueur1.force

will abort with a runtime exception the second operand is greater
that the first operand, i.e. the result is not representable as the (unsigned) UInt32. Unlike in some other
programming langages, results are not implicitly promoted to Int
or wrapped around.
A simple example:
let a = UInt32(3)
let b = UInt32(5)
let c = a - b //

A possible solution is to convert all
numbers to Int, so that differences can be computed without problems:
var vie = Int(arc4random_uniform(10)) + 1
var force = Int(arc4random_uniform(8)) + 1
// etc

A: Thank you Martin. You were totally right.
Converting the variable type from UInt32 to Int was the solution.
var life = arc4random_uniform(10)
var life = int(arc4random_uniform(10))


text:
Q: How to assign an existing SSL certificate to a new IIS site through code? I'm working on a simple tool for a test environment where I have to set up a few dozen sites through C# code. Thus I have a list of (sub)domain names (and other properties) in an array and I run through it to create the sites with their bindings. This works fine, except for the HTTPS bindings where I need to bind the proper SSL certificates from the store. For whatever reason, all sites end up with the same certificate.
The code is relatively straightforward. I first open the certificate store like this:
var store = new X509Store("MY", StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly);

I then find for each domain the certificate where Certificate.Subject.EndsWith(domain.Domain) which also works fine. I display the hash and name and these are correct.
I then move on to create each domain with basic binding on port 80:
var site = manager.Sites.Add(domain.Name, "http", $"*:80:{domain.Domain}", domain.Folder);

And if a certificate is found, I'll also bind the HTTPS connection:
site.Bindings.Add($"*:443:{domain.Domain}", domain.Certificate.GetCertHash(), "MY");

I also write the hash to the console just to make sure I have the right value! And afterwards manager.CommitChanges(); gets called to commit the added site.
Then I check in IIS which certificate is attached and it turns out to be the wrong one! So each site has a certificate error and I don't understand why it goes wrong as everything seems to be correct.
So after the commit I again print the hash by enumerating the bindings to the console and it still shows the right hash. This is becoming really annoying!
As for the certificate that does gets picked... It seems to be the certificate for the last domain in my list. But why it gets assigned to all other bindings?
Is this a bug in the IIS manager?

A minor discovery: I went to IIS and changed the certificate to the proper one. This results in this message in IIS:

This is interesting as it will change the certificates for all the sites when I click "Yes". If I click "No" then I get back to the edit dialog so that doesn't solve anything. Don't think it's related, though...

A: Dum! Dum! Dumb! Solved it...
site.Bindings.Add($"*:443:{domain.Domain}", domain.Certificate.GetCertHash(), "MY", SslFlags.Sni);

It's the SslFlags.Sni flag in the end, as 5th parameter, that does the trick. It stands for "Server Name Indication", duh! And apparently you need it if you bind certificates by domain name...
Such a minor thing can be so annoying...


text:
Q: find the value of $f(0)$, given $f(f(x))=0$ has roots as 1 & 2
find the value of $f(0)$, given $f(f(x))=0$ has roots as 1 & 2, $f(x) = x^2 + \alpha x + \beta$

My attempt:
If $k_1$, $k_2$ are the roots of $f(x)$, $f(x) = k_1$ has roots 1 & 2 $\therefore \alpha = -3, \beta-k_1 = 2 \text{ or } \beta-k_2 = 2$ and $f(x) = x^2 -3x+\beta$. I could not proceed further with this approach
Another line of thought is that $f(f(x))$ would be a quartic equation, which means that for it to have 2 roots, it will either have 2 real, 2 imaginary roots or just 2 roots (x-axis would be tangent to this curve at 1 and 2). This information doesn't seem very helpful in solving the problem.

A: Note that $f(f(x))= (x^2+ax+b)^2 + a(x^2+ax+b) + b$
Put $x=1,x=2$ and set to 0:
$(1+a+b)^2 + a(1+a+b) + b = 0$ _(i)
$(4+2a+b)^2 + a(4+2a+b) + b =0$ _(ii)
Subtracting first equation from second yields
$(a+3)(4a+2b+5)=0$
If $a=-3$, then putting value of $a$ in (i) will give a quadratic with no real solutions in $b$.
So, $4a+2b+5=0$
or
    $a=\frac{-5-2b}{4}$
Putting this value in (i) will lead to $b=\frac{-3}{2}$
So, $$f(0)=b=-\frac{3}{2}$$

A:
$$f(x) = x^2 + \alpha x + \beta$$

Since $f(f(x))=0$ has root at $x=1$ and $x=2$, it implies $f(f(1))=0$ and $f(f(2))=0$
$$f(f(1))=0 \implies f(\alpha + \beta + 1) = 0$$
$$f(f(2))=0 \implies f(2 \alpha + \beta + 4) = 0$$
$\implies f(x)$ has at least $1$ roots $\implies Δ \geq 0$
Case $1$: $Δ = 0$

*

*$f(x) \text{ has only 1 root} \implies \alpha + \beta + 1 = 2 \alpha + \beta + 4 \text{ and } \implies \alpha = -3$

*Then $f(\beta - 2) = 0 \implies (\beta - 2)^2 - 3(\beta - 2) + \beta = 0$ which has 2 imaginary roots: $\beta = 3 \pm i$. Therfore:

$$f(0) = \beta = 3 \pm i$$

Case $2$: $Δ > 0$

*

*$f(x) \text{ has 2 distinct roots which is } \alpha + \beta + 1 \text{ and } 2 \alpha + \beta + 4$

*By Vieta's Formula:
$$(\alpha + \beta + 1) + (2 \alpha + \beta + 4) = -\alpha \text{ (1) }$$
$$(\alpha + \beta + 1) \cdot (2 \alpha + \beta + 4) = \beta \text{ (2) }$$
$\text{(1) } \implies 4\alpha + 2\beta + 5 = 0 \implies 2 \alpha + \beta + 4 = \frac{3}{2} \text{(1')}$
Substitute $(1')$ into $(2)$:
$\text{(2) } \implies \alpha + \beta + 1 = \frac{2}{3} \beta \implies \alpha + \frac{1}{3} \beta + 1 = 0 \text{ (2')}$
Solving $(1')$ and $(2')$ to get:

$$\alpha = -\frac{1}{2}, \beta = -\frac{3}{2}$$

Therefore:

$$f(0) = \beta = -\frac{3}{2}$$


text:
Q: How to validate presence of an array in Rails with Rspec? My specs work fine validating login and in that validation I have access to some_array but in the validation for some_array it fails because I don't have access to it. Is there some special thing I need to do to test for arrays?
model
  validates_presence_of :login, :some_array

rspec
  it { should validate_presence_of(:login) }
  it { should validate_presence_of(:some_array) }

A: Not much info to go on so...
What you need to think is how is the array getting set in the first place?
With each of those it { } blocks a brand new WhateverModel is created.
Is Whatever.some_array populated on creation?
it { expect(WhateverModel.some_array).to_not eq([]) }
it { expect(WhateverModel.some_array).to be }

it { expect(WhateverModel.some_array).to be_kind_of Array }

If your "array" is some kind of model relation then there are other matchers for that.
There are tons of matchers you might see something more useful in the docs: https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers


text:
Q: Trying to program a "to_class" general decorator Suppose I have defined:
def to_class(cls):
  """ returns a decorator
  aimed to force the result to be of class cls. """
  def decorating_func(func):
    def wrapper(*args, **kwargs):
      return cls(func(*args, **kwargs))
    return wrapper
  return decorator(decorating_func)

I wish to use it to create decorators which turn function results to objects of a given class. However, this will not work:
class TestClass(object):
  def __init__(self, value):
    self._value = (value, value)

  def __str__(self):
    return str(self._value)

  @staticmethod
  @to_test_class
  def test_func(value):
    return value

to_test_class = to_class(TestClass)

as test_func will look for to_test_class and will not find it. On the other hand, putting the assignment to to_test_class before the class definition will fail as well, as TestClass will not be defined yet.
Trying to put @to_class(TestClass) above the definition of test_func will also fail, as the method is constructed before the class (if I am not wrong).
The only workaround I have found is to define to_test_class manually as a decorator, and not as one returned from the general "to_class" def.
It might be important to mention that this is only a basic example, but I wish to use to_class for many applications, such as modifying the returned value before 'plugging' it into the class' constructor; and I wish to use it as a decorator for other class' methods as well.
I am sure some think a "to_class" decorator is pointless; manipulations can be done within the decorated method, instead. Though, I find it convenient, and it helps me with readability.
Finally I wish to add that this interests me 20% for practical reasons and 80% for studying reasons, as I find this is something I do not fully understand about decorators in Python in general.

A: Indeed, at class construction time, the class object itself has not yet been constructed, thus you cannot use it as the basis of a decorator.
One work-around I can think of, is to not use the staticmethod decorator. Instead, internally in your own decorator, re-use the classmethod decorator. That way you ensure that Python at the very least passes in the associated class for you:
def to_class(func):
    """ returns a decorator
    aimed to force the result to be of class cls. """
    def wrapper(cls, *args, **kwargs):
        return cls(func(*args, **kwargs))
    return classmethod(wrapper)

Then use it like this:
class TestClass(object):
    def __init__(self, value):
        self._value = (value, value)

    def __str__(self):
        return str(self._value)

    @to_class
    def test_func(value):
        return value

Demonstration:
>>> def to_class(func):
...     """ returns a decorator
...     aimed to force the result to be of class cls. """
...     def wrapper(cls, *args, **kwargs):
...         return cls(func(*args, **kwargs))
...     return classmethod(wrapper)
...
>>> class TestClass(object):
...     def __init__(self, value):
...         self._value = (value, value)
...     def __str__(self):
...         return str(self._value)
...     @to_class
...     def test_func(value):
...         return value
...
>>> TestClass.test_func('foo')
<__main__.TestClass object at 0x102a77210>
>>> print TestClass.test_func('foo')
('foo', 'foo')

A generic version of your decorator is not easy; the only other workaround to your conundrum is to use a metaclass hack; see another answer of mine where I describe the method in more detail.
You basically need to reach into the class-under-construction namespace, set a temporary metaclass, and then rely on there being at least one instance of the class before your decorator will work; the temporary metaclass approach hooks into the class creation mechanisms to retrieve the constructed class at a later time.
Seeing as you are using this decorator as an alternative class factory however, that is probably not going to be ideal; if someone used your decorated functions to create class instances exclusively the metaclass would be called too late.

A: Well, you forgot that class is the first parameter passed to method decorated with classmethod, so you can write it like this:
def to_this_class(func):
    def wrapped(cls, value):
        res = func(cls, value)
        return cls(res)
    return wrapped

class TestClass(object):
    def __init__(self, value):
        self._value = (value, value)

    def __str__(self):
        return str(self._value)

    @classmethod
    @to_this_class
    def test_func(cls, value):
        return value

x = TestClass('a')

print x.test_func('b')

A: The problem is that a decorator gets evaluated upon defining the thing it decorates, so when defining the method test_func(), the decorator to_test_class gets called, and even if it already exists, the thing it shall work on (the class TestClass) does not exist yet (as this is created after all methods are created).
Maybe you can use a placeholder at the point where the class is used and later (after the class is created) fill in that value (the class) at the point of the placeholder.
Example:
lazyClasses = {}
def to_lazy_class(className):
  """ returns a decorator
  aimed to force the result to be of class cls. """
  def decorating_func(func):
    def wrapper(*args, **kwargs):
      return lazyClasses[className](func(*args, **kwargs))
    return wrapper
  return decorating_func

class TestClass(object):
  def __init__(self, value):
    self._value = (value, value)

  def __str__(self):
    return str(self._value)

  @staticmethod
  @to_lazy_class('TestClass')
  def test_func(value):
    return value

lazyClasses['TestClass'] = TestClass

>>> TestClass.test_func('hallo')
<__main__.TestClass object at 0x7f76d8cba190>


text:
Q: Scraping multiple web pages with Cheerio I'm learning to use Cheerio to scrape data from web pages. I know already how to get data from a single page but now I'm trying to figure out how to do the same with multiple pages.
I have two separate functions, one for both url. In my index.js I'm using the functions like this:
const express = require('express');
const scraper = require('./scraper');
const fs = require('fs');
const app = express();
 app.get('/search/:title', (req, res) => {
  scraper.func1(req.params.title).then(cars => {
    res.json(cars);
    fs.writeFile(
      './json/cars.json',
      JSON.stringify(cars, null, 2), // optional params to format it
nicely
       err =>
         err
          ? console.error('Data not written!', err)
          : console.log('Data written!')
    );
  });
  scraper.func2(req.params.title).then(cars => {
    res.json(cars);
    fs.writeFile(
      './json/cars2.json',
      JSON.stringify(cars, null, 2), // optional params to format it
nicely
      err =>
        err
          ? console.error('Data2 not written!', err)
          : console.log('Data2 written!')
    );
  });
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Listening on ${port}`);
});

Obviously these two functions don't work when chained like this. Seperately they both work just fine. So my question is, how should I chain these two functions to use them correctly?

A: I would use the async / await syntax for this purpose, it will keep the code a bit cleaner.
We'll call each function in sequence, then combine the response and send back to the client.
const express = require('express');
const scraper = require('./scraper');
const fs = require('fs');
const app = express();

function writeJsonToFile(fileName, data) {
    fs.writeFile(fileName,
        JSON.stringify(data, null, 2), // optional params to format it nicely
        err =>
        err
            ? console.error('Data not written!', err)
            : console.log(`Data written to file: ${fileName}!`)
    );
}

app.get('/search/:title', async (req, res) => {

    try {
        let cars1 = await scraper.func1(req.params.title);
        writeJsonToFile('./json/cars1.json', cars1);

        let cars2 = await scraper.func2(req.params.title);
        writeJsonToFile('./json/cars2.json', cars2);

        let combinedResponse = { cars1, cars2 };
        res.json(combinedResponse);

    } catch (err) {
        res.json({ error: `Something bad happened: ${err.message}` });
    }
})

const port = process.env.PORT || 3000;
    app.listen(port, () => {
    console.log(`Listening on ${port}`);
});


text:
Q: javascript Date Object how long ago I'm trying to show how long ago a video was uploaded, i cant seem to get the hours and minutes Date Object Methods to work in this script. I'm working of a script called YouMax 2.0 and i have been editing the function getDateDiff, i have come up with this edit of the function. Thank you for any help on this.
function getDateDiff(timestamp) {
if (null === timestamp || timestamp === "" || timestamp === "undefined") return "?";
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var d1 = new Date();
var d1Y = d1.getFullYear();
var d2Y = parseInt(splitDate[0], 10);
var d1M = d1.getMonth() + 1;
var d2M = parseInt(splitDate[1], 10);
var d1D = d1.getDate();
var d2D = parseInt(splitDate[2], 10);
var d1H = d1.getHours();
var d2H = parseInt(splitTime[0], 10);
var d1T = d1.getMinutes();
var d2T = parseInt(splitTime[1], 10);
var diffInMinutes = (d1T + 59 * d1H + 23) - (d2T + 59 * d2H + 23);
if (diffInMinutes <= 1) return "1 Minute";
else if (diffInMinutes <= 59) return diffInMinutes + " Minutes";
var diffInHours = (d1H + 23 * d1M) - (d2H + 23 * d1M);
if (diffInHours <= 1) return "1 Hour";
else if (diffInHours < 23) return diffInHours + " Hours";
var diffInDays = (d1D + 30 * d1M + 12 * d1Y) - (d2D + 30 * d2M + 12 * d2Y);
if (diffInDays < 7) return diffInDays + " days";
else if (diffInDays > 7 && diffInDays < 14) return "1 week";
else if (diffInDays >= 14 && diffInDays < 30) return Math.floor(diffInDays / 7) + " weeks";
var diffInMonths = (d1M + 12 * d1Y) - (d2M + 12 * d2Y);
if (diffInMonths <= 1) return "1 month";
else if (diffInMonths < 12) return diffInMonths + " months";
var diffInYears = Math.floor(diffInMonths / 12);
if (diffInYears <= 1) return "1 year";
else if (diffInYears < 12) return diffInYears + " years";
}

my new function only returns minutes and other and wont update to change of day

A: I assume you are fetching the timestamp from a mysql database. This was also answered here. The top answer is in php but it is not really different from Javascript. I do suggest using php for this however.

A: you can see that your splitting was not correct...
this is working fine..
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var splitTime1 = ((splitTime[2].toString().split('Z'))[0]).split('.');

splitDate[0] = Year;
splitDate[1] = Month;
splitDate[2] = Day;

splitTime[0] = Hours;
splitTime[1] = Minutes;
splitTime1[0] = Seconds;
splitTime1[1] = MilliSeconds;

you can now perform what ever you want to..


text:
Q: Disable Firefox's Auto-fill Is it possible to disable Firefox's auto-fill feature without disabling auto-complete?
I know I can do this:
autocomplete="off"

But I don't want to disable auto-complete, just the auto-fill.
Firefox is populating some of our hidden fields which are meant to be empty
This is mostly a problem when the user refreshes the page. The form fields are re-populated with values from pre-refresh. An example of this being a problem is old-school place-holder. Where we populate the field with a value, and remove it on submit. The value is re-populated on refresh and we don't know if it's the place-holder or use value.

A: Firefox only honors autocomplete="off" on the form, not individual elements (unlike IE).
Another option is to change the field names to strange things like name="_u_sern_ame" to confuse any field recognition systems if you want to disable the autofill of someones details.

A: I've had a similar issue for the password field in a form on the page.
If there is an input tag with type = password in a form tag on the page Firefox is just automatically populating the password:
<form>
    <input type='password' />
</form>

Here's the code I used to fix this specific issue:
$('input[type=password]').val('')

A: what worked for me is
autocomplete="new-password"

A: I had this problem myself. Mike's answer is close, but not perfect in my opinion: it empties elements, even if a value attribute may want to set it.
On pageload, I do the following. It uses only a little jQuery.
// Reset input elements to their HTML attributes (value, checked)
$("input").each(function(){
    // match checkbox and radiobox checked state with the attribute
    if((this.getAttribute('checked')==null) == this.checked)
        this.checked = !this.checked;
    // reset value for anything else
    else this.value = this.getAttribute('value')||'';
});

// Select the option that is set by the HTML attribute (selected)
$("select").each(function(){
    var opts = $("option",this), selected = 0;
    for(var i=0; i<opts.length; i++)
        if(opts[i].getAttribute('selected')!==null)
            selected = i;

    this.selectedIndex = selected||0;
});

No jQuery?
Use document.getElementsByTagName to select the inputs and selects, then iterate over them and replace this by the iterated element. Select the options with .getElementsByTagName('option').

A: autocomplete='off' will not prevent whether in input or form
put a
<input type='password' style='display: none;' />

before your real password input.

A: In some cases, the browser will keep suggesting autocompletion values even if the autocomplete attribute is set to off. This unexpected behavior can be quite puzzling for developers. The trick to really forcing the no-autocompletion is to assign a random string to the attribute, for example:
autocomplete="nope"

https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
Tried in major browsers and it works!

A: Putting two dummy fields in between the actual username field and the actual password field worked for me, e.g.:
<input name = "Username" type="text" autocomplete="off">
<input name = "DummyUsername" type="text" style="display:none;">
<input name = "DummyPassword" type="password" style="display:none;">
<input name = "Password" type="password" autocomplete="new-password">

This prevented the autofill of the username, as well as the autofill of the password.
autocomplete="new-password" is apparently not fully implemented, but can help with some browsers. I doubt that it was helpful with FireFox, but it is there for future versions in case the feature is more widely adopted.

A: If the problem is that FF is populating the fields when the user refreshes, this is actually a feature of Firefox to try to help the user in the case of accidental refresh so they don't lose whatever they have typed. I don't think you can override this with the HTML. You could use JavaScript to clear/reset all the relevant form values on page load. If a form.reset() on the form doesn't work, you will have to iterate over the form elements and clear them like this:
for (i = 0; i < frm_elements.length; i++)
{
    field_type = frm_elements[i].type.toLowerCase();
    switch (field_type)
    {
    case "text":
    case "password":
    case "textarea":
    case "hidden":
        frm_elements[i].value = "";
        break;
    case "radio":
    case "checkbox":
        if (frm_elements[i].checked)
        {
            frm_elements[i].checked = false;
        }
        break;
    case "select-one":
    case "select-multi":
        frm_elements[i].selectedIndex = -1;
        break;
    default:
        break;
    }
}

A: This post suggest to use (other) dummy fields which will be autofilled, you can hide those with css. But this would probably work better with password fields than others.

A: This actually works with a password field in FireFox:
$(window).load(function(){
    $('#pass').val('');
});

A: If it is indeed a Firefox bug, you could use an onSubmit event to clear out the hidden fields. In the form code:
<form onSubmit="clearFieldsIfPopulated(this)">
  <input type="hidden" name="field1"> <input type="submit">
</form>

Example Javascript function:
function clearFieldsIfPopulated(form) {
  if (form.field1.value != "") {
    form.field1.value == "";
  }
}


text:
Q: how to get ansible sequence number of running Here is run.yml and rozofs.yml, I want to get the sequence number of each running.
there is 4 IP address, 90,91,92,93, I want to know where I can get 1,2,3,4 from each running. I am use "echo " to put each IP address, I  want to the sequence number too.
$ run.yml

---
- hosts: "{{ store }}"
  remote_user: root
  vars_files:
    - /vars/rozofs.yml
  tasks:
    - name: mount fs
      command: echo "{{ inventory_hostname }}" >> /root/temp.sh
    - name: sequence number
      command:  echo ??? >> /root/temp.sh

$ rozofs.yml
---
store: 192.168.2.90 192.168.2.91 192.168.2.92 192.168.2.93

$ temp.sh
192.168.2.90
1

$ temp.sh
192.168.2.93
4

A: Since store is a string, split it on space which will give a list of hosts. You can then find the index of the inventory_hostname.
- name: mount fs
  shell: echo "{{ inventory_hostname }}" >> /tmp/temp.sh
- name: sequence number
  shell: echo "{{ store.split(' ').index(inventory_hostname) | int + 1 }}"  >> /tmp/temp.sh


text:
Q: Celery interval schedule doesn't executes on given interval
*

*I found that IntervalSchedule function of celery doesn't execute the tasks if the task interval is greater than 24 Hours.

The interval scheduler django_celery_beat.models.IntervalSchedule
 runs at a specifically given interval.
from django_celery_beat.models import PeriodicTask, IntervalSchedule
    #should executes every 26 hours.
    >>> schedule, created = IntervalSchedule.objects.get_or_create(
    ...     every=26,
    ...     period=IntervalSchedule.HOURS,
    ... )

https://django-celery-beat.readthedocs.io/en/latest/

*

*Now I'm creating a task to print("Hello World!") with different IntervalSchedule.HOURS Time Hours (5,10,14,23,27,32) Hours.

*I Noticed that this above 27,32 hour task never executes, whereas tasks which are under 24 Hours i.e (5,10,14,23) of period gets executed every day
######## CELERY : CONFIG
CELERY_BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = "Asia/Kolkata"
CELERYBEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'

*

*Versions :

celery (4.2.1)
django-celery (3.2.2)
django-celery-beat (1.3.0)

What are the possible reasons causing this & how do I debug to find the root cause?


text:
Q: SQL limit by group by This is probably not very correct title of the question, but failed to figure out better name.
I have following table structure:
id | lat  | lon  | trajectory_id | time
1  | 15.8 | 17.1 | 162           | 10:01
2  | 11.5 | 59.7 | 162           | 10:02
3  | 16.4 | 79.9 | 162           | 10:03
4  | 29.5 | 10.3 | 180           | 11:12
5  | 58.2 | 11.1 | 180           | 11:13
6  | 54.5 | 14.1 | 180           | 11:14
7  | 14.9 | 15.2 | 166           | 13:40
8  | 15.0 | 13.1 | 166           | 13:42

And I would like to get first point of each trajectory (ordered by time). This means following:
id | lat  | lon  | trajectory_id | time
1  | 15.8 | 17.1 | 162           | 10:01
4  | 29.5 | 10.3 | 180           | 11:12
7  | 14.9 | 15.2 | 166           | 13:40

How can I do that? I tried to group by trajectory_id and then applying limit 1, but it limits trajectories, not points itself.

A: WITH CTE AS
(SELECT id,lat,lon,trajectory_id,time,
ROW_NUMBER() OVER(PARTITION BY trajectory_id ORDER BY time) rn
FROM t)
SELECT id,lat,lon,trajectory_id,time FROM CTE WHERE rn=1

A: Use ROW_NUMBER() per trajectory_id in order to only retrieve the first row per trajectory_id.
select id, lat, lon, trajectory_id, time
from
(
  select
    mytable.*,
    row_number() over (partition by trajectory_id order by time) as rn
  from mytable
) numbered
where rn = 1;


text:
Q: Connecting to https with soapClient I've spent the last couple of days trying to figure out why my soap client can't connect, any help is appreciated.  Very straightforward issue, my soap client;
$soapClient = new SoapClient("AXLAPI.wsdl", array('trace'=>true, 'exceptions'=>true,'location'=>"https://ip_address:8443/axl",
'login' => "username",'password'=> "password"));

Yields this very common error;
Fatal error: Uncaught SoapFault exception: [HTTP] Could not connect to host in /var/www/html/axl_test.php:18 Stack trace: #0 [internal function]: SoapClient->__doRequest('<?xml version="...', 'https://ip_address...', 'CUCM:DB ver=8.5...', 1, 0) #1 /var/www/html/axl_test.php(18): SoapClient->__call('getLine', Array) #2 /var/www/html/axl_test.php(18): SoapClient->getLine(Array) #3 {main} thrown in /var/www/html/axl_test.php on line 18

I run this exact same code on another server and it runs fine.  I'm positive this is related to an SSL issue because a wireshark capture several retransmissions.  Also, when I purposefully change the username and password to something false, the error stays the same.  So, it must be occuring during the handshake.  I can access the remote server from the soap client server with no problems and am able to log in.
The error seems to show that it's trying to connect via HTTP, but my URL specifically calls for HTTPS to be used.  I really don't understand where the issue can be.

A: After days of working through this issue, I solved the problem.  Some of the answers here were correct, there was a problem with the self-signed certificate (so the Soap client has to be made to not care), but another issue was the url itself.  For whatever reason, putting in an IP address did not work, using the FQDN did.  So, the complete code looks like this;
<?php
error_reporting(E_ALL);
ini_set('display_errors', True);
?>

<!DOCTYPE html>

<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style1.css">
<title>AXL Test</title>

<?php

$context = stream_context_create(array('ssl' => array('verify_peer' => false, 'allow_self_signed' => true)));

$soapClient = new SoapClient("AXLAPI.wsdl", array('stream_context' => $context, 'trace'=>true, 'exceptions'=>true,'location'=>"https://hostname.domain.name:8443/axl",'login' => "username",'password'=> "password"));
$response = $soapClient->getLine(array("routePartitionName"=>"partitionName", "pattern"=>"pattern"));
echo "
" .  $response->return->line->description . "	";

?>

This issue was particularly vexing because I was using tried-and-true code from another server where self-signed ceritificats and FQDNs didn't matter.  Now it did, and I don't know why.  In any case, I got it working.  Thank you to everyone who provided feedback, I hope this helps others.


text:
Q: Livewire loading state disappers if leaving the tab or window I use Livewire loading state to show Processing message on submit event. The loading message disappered when I click on other browser tab or window while the task at server-side still running.
Is there anyway to keep loading message still show untill the the task finished?


text:
Q: Package pgfkeys Error: I do not know the key '/pgfplots/horizontal sep' with groupplot using pgfplot I am trying to draw multiple plots with groupplot and am getting the errors below.
Package pgfkeys Error: I do not know the key '/pgfplots/horizontal sep', to which you passed '20pt', and I am going to ignore it. Perhaps you misspelled it. ]
Package pgfkeys Error: I do not know the key '/pgfplots/vertical sep', to which you passed '20pt', and I am going to ignore it. Perhaps you misspelled it. ]
Package pgfkeys Error: I do not know the key '/pgfplots/x unit', to which you passed '\si {\byte }', and I am going to ignore it. Perhaps you misspelled it. ]
Package pgfkeys Error: I do not know the key '/pgfplots/y unit', to which yout. ]

The offending code:
\documentclass{standalone}
\usepackage[x11names,table]{xcolor}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepgfplotslibrary{groupplots}
\usepackage[binary-units = true]{siunitx}

\begin{document}
    \begin{tikzpicture}
        \begin{groupplot}
            [
            group style={group size=2 by 1},
            horizontal sep=20pt,
            vertical sep=20pt,
            width=0.5\columnwidth,
            every x tick scale label/.style={at={(rel axis cs:1,0)},yshift=-1.5em,anchor=north east,inner sep=1pt},
            every y tick scale label/.style={at={(rel axis cs:0,1)},xshift=-1.75em,anchor=south east,inner sep=1pt},
            xmin = 0,
            ymin = 0,
            grid=major,
            grid style={dashed,gray!30},
            xlabel=X Axis $\mathcal{N}$,
            ylabel=Y Axis $Time$,
            x unit=\si{\byte},
            y unit=\si{\second},
            legend cell align={left},
            legend style={at={(0.5,-0.4)},anchor=north}
            ]

            \nextgroupplot
            \addplot[color=teal,only marks]
            table[x=Message Length,y=Insertion Time,col sep=comma,scatter] {data.csv};
            \addlegendentry{Insertion}
            \addplot [mark=none,color=Aquamarine2]
            table[x=Message Length,y={create col/linear regression={y=Insertion Time}},col sep=comma] {data.csv};
            \addlegendentry{Insertion Regression Line}

            \nextgroupplot
            \addplot[mark=none,color=Cyan4,thick]
            table[x=Message Length,y={create col/linear regression={y=Extraction Time}},col sep=comma] {data.csv};
            \addlegendentry{Extraction Regression Line}
    \end{groupplot}
    \end{tikzpicture}

\end{document}

Output:

I am in pursuit to prevent the ylabel from overlapping for the plot for which I have resorted to using horizontal sep=5cm as provided here and in the documentation. The error is what I assume is preventing the solution from working as intended. Any guidance is appretiated.
Sample from data.csv:
Message Length,Insertion Time,Extraction Time
1000000,2882.6947407000002,2891.3703151000004
2000000,5969.4817235,5931.724818600001
3000000,8480.4446118,8307.060654199999
4000000,11374.857455500001,10956.432963199999
5000000,13943.201667899999,13806.727052399998
6000000,16637.710391300003,16383.8475286
7000000,19527.7743606,19134.5409173
8000000,22427.304584700003,21726.507952400003

A: You did only two minor mistakes which lead to the error messages. Have a look at the comments in the code how to fix them. I also gave two hints how to prevent "the overlapping".
(Please note that I have heavily simplified your code to show only relevant stuff.)
% used PGFPlots v1.18.1
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
    \usepgfplotslibrary{
        groupplots,
        % missed to load the library to make `x unit` and friend work
        units,
    }
    % (add this to `compat` level or higher to make use of the advanced positioning
    % of the axis labels)
    \pgfplotsset{compat=1.3}
\usepackage[binary-units=true]{siunitx}
\begin{document}
\begin{tikzpicture}
    \begin{groupplot}[
        group style={
            group size=2 by 1,
            % moved the next two to this style
            horizontal sep=40pt,    % (<-- increased value to prevent overlapping)
            vertical sep=20pt,
        },
        x unit=\si{\byte},
        y unit=\si{\second},
    ]

    \nextgroupplot
        \addplot {x};

    \nextgroupplot
        \addplot {x^2};
    \end{groupplot}
\end{tikzpicture}
\end{document}


text:
Q: iOS - Link from web browser opens an app in iOS app although it should be redirected to web browser There is an iOS app.
There is a link on a web:
<a href="https://somedomain.com/forgotPassword?key=<some_hash>"
In iOS app, there is an apple-app-site-association file with config
{
  "applinks": {
    "apps": [],
    "details": [
      {
         "appID": "....",
         "paths": ["NOT /forgotPassword", "*"]
      },
      {
         "appID": "....",
         "paths": ["NOT /forgotPassword", "*"]
      }
    ]
  }
}

but the redirection happens from that link on a web to the iOS app, although this is in configuration: "NOT /forgotPassword" and redirection to iOS app should be intercepted and blocked.
( I followed instructions from: How to support Universal Links in iOS App and setup server for it? )
I tried "paths": ["NOT /forgotPassword", "*"] as well as "paths": ["*", "NOT /forgotPassword"]
How do I configure it so opening links in browser would be redirected to iOS app (this part is working), EXCEPT when client calls https://somedomain.com/forgotPassword...
Sidenote:
This part: opening links in browser would be redirected to IOS app - was working fine and still works fine when I had "paths": ["*"]
but when I introduced NOT clause, as is suggested in the stack overflow link above that I provided, this doesn't work.
Should I format it in some other way?
P.S. I'm a web developer, so if there are steps to be taken on iOS part, please be as concise and detailed as possible so I can forward it to iOS team.
EDIT:
In the meantime, I also tried these combinations:
"paths": ["*", "NOT /forgotPassword?key=?"]
"paths": ["NOT /forgotPassword?key=?", "*"]

A: The problem was solved when mobile team built a new app. All the time they were just retrying while I was reconfiguring apple-app-site-association file and recycling pool in IIS.
However, they needed to rebuild their app in order for this to work.