text:
Q: How to change the pixel quality and size of Image using Google Apps Script? I have a list of image URLs and I want to get all those images which are more than 14Mb in size or 14 Megapixel in quality and resize them to under 5Mb in size and 10 Megapixel in quality. I used Image library provided by @Tanaike on Github to manipulate image size and quality.
Here is the code snippet to download the image as a blob and check its size and dimension using ImgApp library:
 funtion CompressImage() {

    var url = "http://images.salsify.com/image/upload/s--PyaEswlb
--/f595bd4e42783097f42e4615e17024b6b82da014.jpg";

      var folderId = "Your Folder ID";
      var folder = DriveApp.getFolderById(folderId);

      var response = UrlFetchApp.fetch(url)
      var fileBlob = response.getBlob()

      var res = ImgApp.getSize(fileBlob);

       if((res.filesize/1000000)>14 || res.width>14000000)
       {

         ProcessImage(fileBlob , folder);

       }
}

The If statement in the above code checks the file size and pixel quality, if it is above the threshold (14Mb size, 14 Megapixel quality) then it executes the ProcessImage function. This function sets the width size, and replaces the old image with the newly resized image.
  function ProcessImage(fileBlob,folder)

  {

  var width = 3600; // Please set the size of width with the unit of pixels.
  var file = folder.createFile(fileBlob);

  var fileId = file.getId();
  var link = Drive.Files.get(fileId).thumbnailLink.replace(/\=s.+/, "=s" + width);
  var blob2 = UrlFetchApp.fetch(link).getBlob().setName("Compressed Image");
  var file = folder.createFile(blob2);

  var img = Drive.Files.get(file.getId()).webContentLink; //get the view link of image downloaded in drive
  Logger.log(img);
  Drive.Files.remove(fileId);

   }

The above two functions combine to get the resized image which is less than 14 Mb in size but I am not able to change the pixel quality of the image (less than 14 Megapixel). Can you please guide what am I doing wrong? Any help would be much appreciated. Thank you.

A: I believe your goal is as follows.

*

*You want to reduce the image size from 4480x4480 to 2000x2000. At this time, you want to reduce the lower quality of the image.

*You want to achieve this using Google Apps Script.

Issue and workaround:
I thought that in this case, for example, when you want to reduce the image size from 4480x4480 to 2000x2000, the following flow can achieve your goal.

*

*Reduce the image from 4480x4480 to 100x100.

*Increase the image from 100x100 to 2000x2000.

By this, the image quality can be reduced by keeping the size. But, unfortunately, the method using thumbnailLink cannot increase the image. By this, it is required to use another workaround.
In this answer, I would like to propose another workaround for changing the image size.
Usage
1. Install Google Apps Script library.
As one more Google Apps Script library, please install DocsServiceApp. You can see how to install it at here.
2. Sample script.
When your script is used, the modified script is as follows. In this case, I modified your function ProcessImage.
// Please run this function.
function CompressImage() {
  var url = "http://images.salsify.com/image/upload/s--54TepGAl--/2f76d5ec5400b654b6f3dbd068db7898a76389cf.jpg";
  var folderId = "root";
  var folder = DriveApp.getFolderById(folderId);
  var response = UrlFetchApp.fetch(url)
  var fileBlob = response.getBlob()
  var res = ImgApp.getSize(fileBlob);
  if ((res.filesize / 1000000) > 14 || res.width > 14000000) {
    ProcessImage(fileBlob, folder);
  }
}

function ProcessImage(fileBlob, folder) {
  var width1 = 100; // Please adjust this value.
  var width2 = 2000; // Please adjust this value.

  // Create original image as a file.
  var file1 = folder.createFile(fileBlob);
  var fileId1 = file1.getId();

  // Reduce original image size.
  var link1 = Drive.Files.get(fileId1).thumbnailLink.replace(/\=s.+/, "=s" + width1);

  // Increase converted image size.
  const object = { title: "temp", parent: "root", width: { unit: "pixel", size: width2 }, height: { unit: "pixel", size: width2 } };
  const sId = DocsServiceApp.createNewSlidesWithPageSize(object);
  const s = SlidesApp.openById(sId);
  const slide = s.getSlides()[0];
  slide.insertImage(link1).setWidth(width2 / 1.33333).setHeight(width2 / 1.33333);
  s.saveAndClose();

  // Retrieve result image.
  const link2 = Slides.Presentations.Pages.getThumbnail(sId, slide.getObjectId(), { "thumbnailProperties.thumbnailSize": "LARGE" }).contentUrl;
  var blob2 = UrlFetchApp.fetch(link2).getBlob().setName("Compressed Image");
  var file2 = folder.createFile(blob2);
  var img = Drive.Files.get(file2.getId()).webContentLink;
  Logger.log(img);

  Drive.Files.remove(fileId1);
  Drive.Files.remove(sId);
}

*

*IMPORTANT: In this workaround, as an important point, by the current specification of Slides API, the output image size can be selected only 3 patterns like LARGE (The thumbnail image width of 1600px.), MEDIUM (The thumbnail image width of 800px.), SMALL (The thumbnail image width of 200px.). I think that this is the bottleneck of this workaround.

*When this script is run, the image size of the original image is converted from 4480x4480 to 100x100 using thumbnailLink. And, the image of 100x100 is converted to 2000x2000 using DocsServiceApp and Google Slides. And, when an image is exported from Google Slides, an image with low quality with 1600x1600 is obtained.
Note:

*

*100x100 and 2000x2000 are the sample sizes. So, please modify the values of var width1 = 100; and var width2 = 2000; for your actual situation. By this, you can control the quarity of the image.

Reference:

*

*DocsServiceApp


text:
Q: CakePHP 1.3 HABTM model Pagination Have been having an issue sine using the HABTM relationship in models instead of using a JOIN in the paginate variable in the controller, data comes out fine but I can't set the limit of projects to 20.
I am selecting projects from the DB depeneding on their features.
I havea feature called urgent.
I'm on the urgent listing page.
this should fetch all projects marked with urgent, and it does this fine but it brings back all the results instead of the limit of 20 I set in the paginate function or if I try in the models. here's the pagien array code
$paginate = array(
   'Project' => array(
      'limit' => 20,//works fine when paginating just projects
   ),
   'Feature' => array(
      'limit' => 1, //did set this to 20 but when looking thought well its going to be the limit of the feature table which will only be 1 anyway, notl imit for the projects
      //also tried this below
      'Project' => array(
         'limit' => 20,//no luck with this
      ),
   ),
);

I use this to paginate in my controller
$this->paginate('Feature', array(..conditions..)); //this brings all my projects marked urgent but I only want 20!

A: Are you looking for the ContainableBehavior?
$paginate = array(
    'Feature' => array(
        'contain' => array(
            'Project' => array(
                'limit' => 20,
                ....
            )
        )
    )
);

A: I know this is a somewhat dated article, and you're looking for a 1.3 solution, but I used this technique for an application I wrote in 1.2 a while back and it definitely worked: Pagination of data from a HABTM relationship.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Thruk - Scripted Dashboard - get params from query string Is it possible to get query string in scripted dashboard ?
I tried to use CGI perl module in scripted dashboard, but with no success.
The idea is to use scripted dashboard as template to generate thruk maps on the fly by using query params.

A: That is not possible right now, but might be in future versions. It might be a bit tricky because there can be multiple dashboard opened at once which all have different parameters.


text:
Q: Problem with my LaTeX code not compiling i'm having problem compiling my LaTeX code. Recently i'm learning LaTeX to start writing my homework.The errors are: runaway argument?, Missing $ inserted.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[]{amsthm}
\usepackage[]{amssymb}
\usepackage{flexisym}
\usepackage{amsmath}

\title{Desarrollo}
\author{Example}
\date\today

\begin{document}
\maketitle
\subsection*{Desarrollo}
\textit{
\textbf{iii.} Encuentre los intervalos de concavidad y los puntos de inflexión.
}

\text{Calculemos $f\textprime\textprime(x)$}

\begin{align*}
    &\text{Teniamos anteriormente que la derivada era}\\
    f\textprime(x)&=\tan x \cdot \sec^{2}x\\\\
    f\textprime\textprime(x)&=\sec^{2}(x) + [(1)\cdot(\sec ^{2}x)\cdot + x\cdot(\sec ^2x)\textprime]\\
    &=\sec^{2}x+(\sec^{2}x+2\sec ^{2}x \cdot \tan x)\\
    &=\sec^{2}x+\sec^{2}x+2\sec ^{2}x \cdot \tan x\\
    &=2\sec^{2}x+2\cdot \sec^{2}x\cdot \tan x\\\\
    &\text{Podemos factorizar por $\sec^{2}x$}\\
    f \textprime \textprime(x)&=\sec ^{2}x (2+2 \tan x)\\\\
    &\text{Entonces calculamos sus puntos criticos}\\

\end{align*}

\clearpage

\end{document}

Bonus: if anyone has a good resource to start writing my homework in LaTeX, i would receive it gladly.

A: I would get rid of the extra blank lines in the align* environment, and I'd rearrange parts of the material so that there's more visual focus on novel part, i.e., the derivation of the second derivative. For instance, I see no need to use a displayed equation to re-state the formula for the first derivative. Do use \intertext to typeset asides and explanatory comments. I would also replace all instances \textprime with '. (I gather you loaded the flexisym package to access the \textprime macro, right?)

\documentclass{article}
%\usepackage[utf8]{inputenc} % that's the default nowadays
\usepackage[T1]{fontenc}
\usepackage[spanish]{babel}
\usepackage{amsthm,amssymb,amsmath}
%\usepackage{flexisym} % no longer needed

\begin{document}
\subsection*{Desarrollo}

\textit{\textbf{iii.} Encuentre los intervalos de concavidad y los puntos de inflexión.}

\medskip
Calculemos $f''(x)$.

Teniamos anteriormente que la derivada era $f'(x)=\tan x \sec^2 x$.
\begin{align*}
    f''(x)&= \sec^2 (x) + [(1)(\sec ^2 x) + x(\sec^2 x)'\,]\\
          &= \sec^2 x+(\sec^2 x+2\sec^2 x \cdot \tan x)\\
          &= \sec^2 x+\sec^2 x+2\sec ^2 x \cdot \tan x\\
          &= 2\sec^2 x+2 \sec^2 x \tan x\\
\intertext{Podemos factorizar por $\sec^2 x$:}
    f''(x)&= 2\sec ^2 x (1+\tan x)\,.
\end{align*}
Entonces calculamos sus puntos criticos.

\end{document}

A:  \documentclass{article}
 \usepackage[utf8]{inputenc}
 \textwidth=16cm
  \oddsidemargin=1cm
  \usepackage{blindtext}
  \title{Desarrolo}
  \date{\today}
  \author{Example}
  \begin{document}
  \maketitle

   \section{Introduction}
    \blindtext

    \subsection*{Desarrollo}
    \textit{
     \textbf{iii.} Encuentre los intervalos de concavidad y los puntos de
     inflexión.
        }

    \vspace{1cm}

    \noindent
    \section*{Calculemos $f''(x)$}

        Teniamos anteriormente que la derivada era\medskip

    \hspace{2cm}{  f'(x)= $ tan\;x \cdot sec^{2}\left[x\right]$\medskip}

   \hspace{2cm}{\begin{tabular}{rl}
     f'(x)  = & $sec^{2}(x) + \left[(1)\cdot(sec ^{2}x)\cdot + x\cdot(sec
    ^2x)'\right]$  \\
    =& $sec^{2}{x}+(sec^{2}{x}+2sec ^{2}{x} \cdot tan {x})$\\
    =& $sec^{2}{x}+sec^{2}{x}+2 sec^{2}{x} \cdot tan {x}$\\
    = & $2 sec^{2}{x}+2\cdot sec^{2}{x}\cdot tan {x}$\\
    \end{tabular}\medskip }

    Podemos factorizar por $\sec^{2}{x}$\\\medskip

    {\hspace{2cm}{ f'(x) = =$ sec ^{2} x (2+2 tan x)$\medskip}

    Entonces calculamos sus puntos criticos\medskip

    \clearpage

    \end{document}

This is formulated with the simple latex statements. You can modify according to your requirements,


text:
Q: Error n tweets were requested but the API can only return 0 I am unable to retrieve any tweets using twitteR package in R. For example this request:
nbahash_tweets = searchTwitter("#nba",since='2013-01-01', until='2014-02-25',n=20)

Shows me this warning message:

Warning message: In doRppAPICall("search/tweets", n, params = params,
  retryOnRateLimit = retryOnRateLimit,  :   20 tweets were requested but
  the API can only return 0

What could be the reason of the problem?

A: From the official Twitter Search API documentation
https://dev.twitter.com/rest/public/search

The Twitter Search API searches against a sampling of recent Tweets published in the past 7 days.

so you can't search the API for tweets from 2013 - 2014

A: I also received this message when I was attempting to use the twitteR package to search Twitter-which brought me to this post.
However, when I used the search_twitter_and_store command in the same package I was able to retrieve 1702 messages and store them in MySQL.  Not exactly what I was shooting for but it did allow me to get and manipulate the data.  Might work for you too.


text:
Q: Comparing files and removing duplicates I have two files, test1 and test2. I would like to compare the files and remove any entries in test2 that are already present in test1.
Example:
test1
[ostrich@post-om1 test]$ cat test1|head
917010023586,UPE,RED 399
917023895388,UPE,RED 499
917023895389,UPE,RED 699
917024120800,UPE,RED 399
917024214387,UPE,RED 399
917027011096,UPE,RED 399
917027120457,UPE,RED 399
917027749420,UPE,RED 399
917030002266,UPE,RED 399
919389105220,UPE,RED 399

test2
[ostrich@post-om1 test]$ cat test2|head
917310106487
919839063308
917081106519
919389105220
919336429543
917081102867
919919804079
919936432138
919455329240
919839601519

Desired output
[ostrich@post-om1 test]$ cat test1
917010023586,UPE,RED 399
917023895388,UPE,RED 499
917023895389,UPE,RED 699
917024120800,UPE,RED 399
917024214387,UPE,RED 399
917027011096,UPE,RED 399
917027120457,UPE,RED 399
917027749420,UPE,RED 399
917030002266,UPE,RED 399

A: I need nine more characters...
grep -vFf test2 test1

A: I achieved above result by below command and it worked fine

awk -F ","  'NR==FNR {a[$1];next}!($1 in a) {print $0}' test2 test1


text:
Q: Glossary and list of figures have the same page number in the table of contents In my table of contents the glossary and the list of figures have the same page number. However, these two areas are not on the same page. Can anyone help me to get the correct number of pages set?
My glossary is called "Akronyme" because it is in German.

Here is my code:
\printglossary[type=\acronymtype,style=dontgroup]
\addcontentsline{toc}{chapter}{List of figures}
\listoffigures

A: Your issuing of
\addcontentsline{toc}{chapter}{List of figures}

comes too soon, since \listoffigures sets a new chapter (perhaps starred) that initiates itself with a page break. Inserting this page break as \clearpage before \addcontentsline flushes all unprocessed floats, inserts the appropriate page for the ToC while avoiding the default \clearpage issued by \chapter (from \listoffigures). So, your document structure should instead resemble:
\printglossary[type=\acronymtype,style=dontgroup]
\clearpage
\addcontentsline{toc}{chapter}{List of figures}
\listoffigures

If you're running in twoside mode use \cleardoublepage.
The above suggestion should work for most document classes.

A: To extend @Werner's answers I come about the case that using \cleardoublepage (or \clearpage) did not help. Here the package "hyperref" is apparently involved. Page references could still be wrong because the command \addcontentsline refers to a wrong location. The documentation of the package "hyperref" states

\addcontentsline refers to the latest previous location where an anchor is set.

This behavior can be corrected by using \phantomsection.
\printglossary[type=\acronymtype,style=dontgroup]
\clearpage
\phantomsection
\addcontentsline{toc}{chapter}{List of figures}
\listoffigures

See also: When do I need to invoke \phantomsection? or this answer.


text:
Q: Do homological holes correspond to polyhedra? Let $T$ be a collection of triangles in an abstract simplicial complex $A$ such that
$$\partial \left( \sum \limits_{t \in T} \sigma_t \cdot t\right) = 0$$
where $\sigma_t \in \{-1, 1\}$ is some appropriately-chosen collection of coefficients.
I want to know if the following statement is then necessarily true:

Conjecture: One can obtain $T$ by starting with the disjoint union of some polyhedra in $\mathbb{R}^3$ with triangular faces and then "gluing together" pairs of points some number of times (i.e. dragging two distinct points together in space so that they coincide and are equal)).  The resulting set of triangular faces, identified by their three nodes, is then isomorphic to $T$.

As followup questions, I'm also interested to know if the analogous statement is true for higher dimensions and for polyhedral complexes.


text:
Q: Taylor Theorem Differentiable Function I've got the following question

Let $g:\mathbb{R} \rightarrow \mathbb{R}$ be a twice differentiable
  function satisfying $g(0)=1, \  g'(0) = 0$ and $g''(x) - g(x) = 0$,
  for all $x \in \mathbb{R}$
i) Prove that $g$ has derivatives of all orders.
ii) Fix $x \in \mathbb{R}$. Show that there exists $M > 0$ such that for all $n \in \mathbb{N}$ and all $\theta \in (0,1)$
$|g^{(n)}(\theta x)| \leq M$
iii) Find the coefficients of the Taylor expansion of $g$ about $0$, and prove that this expansion converges to $g(x)$ for all $x \in
 \mathbb{R}$

I've done ( i ) and noted that $g^{(k)}(0) = 1$ if $k$ is even and $g^{(k)}(0) = 0$ if $k$ is odd. I'm struggling with the last two parts. For ( ii ) I've shown that, via Taylor's Theorem, we get
$g(x) = \displaystyle\sum_{k=0}^{n-1} \dfrac{g^{(k)}(0)}{k!} x^k + \dfrac{g^{(n)}(\theta x)}{n!} x^n$
But I don't see how to get an upper bound on $\dfrac{n! g(x)}{x^n} - \dfrac{n!}{x^n} \displaystyle\sum_{k=0}^{n-1} \dfrac{g^{(k)}(0)}{k!} x^k$ for some fixed $x \in \mathbb{R}$
I've also realised that $\displaystyle\lim_{n \to +\infty}\displaystyle\sum_{k=0}^{n-1} \dfrac{g^{(k)}(0)}{k!} x^k = \cosh(x)$
Any help greatly appreciated.
Thanks!

A: ii) Let $x \in \mathbb{R}$. Since $g$ is twice differentiable, it is $C^1$. Let $M = \sup_{\lambda \in [0,1]} \max(|g(\lambda x)|,|g'(\lambda x)|)$.
Since $g^{(2)}(x) = g(x)$, we have $g^{(2n)}(x) = g(x)$ for all $n$. Similarly, since $g^{(3)}(x) = g^{(1)}(x)$, we have $g^{(2n+1)}(x) = g^{(1)}(x)$ for all $n$. Consequently it follows that $|g^{(n)}(\theta x)| \le M$ for all $n$ and for all $\theta \in (0,1)$.
iii) The Taylor coefficients about zero follow from the above formula for $g^{(n)}$. In particular, $g^{(2n)}(0) = 1$, $g^{(2n+1)}(x) = 0$.
Following your notation above, to show that the Taylor series converges to $g(x)$, you need to show that for all $\epsilon>0$, we can find $N$ such that for $n \ge N$, $$\left|g(x)-\sum_{k=0}^{n-1} \dfrac{g^{(k)}(0)}{k!} x^k\right| < \epsilon.$$ From your estimate above, we have $$\left|g(x)-\sum_{k=0}^{n-1} \dfrac{g^{(k)}(0)}{k!} x^k\right| = \left|\dfrac{g^{(n)}(\theta x)}{n!} x^n\right| \le M \frac{|x|^n}{n!},$$ and since $\lim_n \frac{|x|^n}{n!} = 0$, it is clear that we can find such a $N$. Hence the Taylor series converges.
And, as you have noted, we have $g(x) = \cosh x$.


text:
Q: passing veriable in url weird behaviour I'm trying to pass a variable throught URL and it's doing something really weird in Chrome and Firefox, it seems is doing the same in OS.
The issue is that I'm trying to send a few variable in the URL this way:
document.location.href = 'http://www.ihaves.org/main.php?id='+facebookUser+'&first_name='+facebookName+'&last_name='+facebookName+'&locat='+locat_+'&locationlat='+facebookLat+'&locationlon='+facebookLon+'&mode=facebook';

The weird result is this:

http://www.ihaves.org/Vejer%20de%20la%20Frontera,%20Spain

when the expected result should be this one: (taken from IE)

http://www.ihaveseen.org/main.php?id=1215834998&first_name=Juanma%20De%20Los%20Santos&last_name=Juanma%20De%20Los%20Santos&locat=Vejer%20de%20la%20Frontera%20Spain&locationlat=36.25&locationlon=-5.96667&mode=facebook

I have detected that the problem is the variable called "locat", if I take it out then everything seems to go fantastic so I have thought that the comma of "Vejer de la Frontera, Spain" might be the problem so I have used:
var location_name = locationName.replace(/,/g, '');

But it keeps doing the same weird thing than before. Any idea? Does chrome accept an espace beetwen words? Remember firefox does exactly the same.  By the way, I'm using GET_ in the PHP.

A: You should use encodeURI() on the Parameters when constructing the URL.
document.location.href = 'http://www.ihaves.org/main.php?id=' + encodeURIComponent(facebookUser);

A: Use:
encodeURIComponent(facebookName)

encodeURIComponent
You should be using encoded key/value pairs.  Some characters will result in an invalid URL. For example:
mysite.com?name=Bed&Breakfast

will result in two values "name=Bed" and "Breakfast=" which is not what you would expect or want. Encoding would result in your URL:
mysite.com?name=Bed%26Breakfast

It may look funny but the URL is now valid and works as expected.


text:
Q: Is ++ syntactic sugar for += 1? As far as I understand, indexing a map returns a copy of the map value. With this in mind, consider the following code:
package main

import "fmt"

func main() {
    m := map[string]int{"xxx": 100}
    m["xxx"]++
    fmt.Println(m["xxx"]) // prints 101
}

The code above prints 101, whereas I expected 100.
My reasoning is that m["xxx"] returns a copy of the value assigned to the key "xxx" (i.e., 100), and the operator ++ increments this copy of the value but this doesn't affect the original value stored in the map – only the copy changes.
However, considering that we assign a value to a map key by putting the key within brackets and using = to specify the value (i.e., m[key] = value). Then, if m["xxx"]++ were translated to m["xxx"] += 1 by the compiler – which is, in turn, equivalent to m["xxx"] = m["xxx"] + 1 – this would explain the result of the code above.
My question is whether the increment operator (++) is syntactic sugar for the by-one addition assignment (+= 1). Otherwise, what am I missing?

A: "My reasoning is that m["xxx"] returns a copy of the value" — I don't think this is a fair assumption. The specs under index expressions only say the following:

A primary expression of the form a[x] denotes the element of the [...] map a indexed by x

and

if the map contains an entry with key x, a[x] is the map element with key x

The verbs "denotes" and "is" arguably do not imply a copy. A copy is made only when you assign the result of the index expression to a variable.
The map index expression is simply not addressable, so that you can't memory alias the values stored in the map.
As for whether the increment operator ++ is syntactic sugar for += 1 or not, the specs explicitly state that:

The following assignment statements are semantically equivalent:

IncDec statement    Assignment
x++                 x += 1
x--                 x -= 1

So op++ has the same meaning of op += 1, and a[x]++ increments the operand a[x] which "denotes/is" the map element with key x.

A: The language specification says that the ++/-- operators should work with a map index expression as the operand.
https://go.dev/ref/spec#IncDec_statements

The "++" and "--" statements increment or decrement their operands by
the untyped constant 1. As with an assignment, the operand must be
addressable or a map index expression.

How that functionality should be implemented is not specified and may therefore be different across different compilers or different versions of the same compiler.

If you search the cmd/compile/internal directory of your Go installation, which is the source code of the Go compiler if I'm not mistaken, you'll find a number of lines that seem to confirm your guess. I have nowhere near enough knowledge about the code to provide a conclusive answer however.
Examples: one and two
And the gccgo implementation of the spec, which I've never looked at, may or may not do the IncDec the same way.


text:
Q: Putting .sty file into ~/texmf-dist/tex/latex But still getting Error I installed texLive 2013 on a mac. And I am using texmaker to typeset my documents. I have my threads regarding where to locate .sty files in mac. And I located my stackengine.sty in the following path
\usr\local\texlive\2013\texmf-dist\tex\latex
This is where all the packages are. So I believe putting my stackengine.sty in there will make sense, which is what I did.
I then tried to compile my tex file. But it failed miserably with the following error message in the log:
(/usr/local/texlive/2013/texmf-dist/tex/latex/base/latin9.def
File: latin9.def 2008/03/30 v1.1d Input encoding file
))
! LaTeX Error: File `stackengine.sty' not found.

I already placed the stackengine.sty in that path already. I even placed the entire stackengine there as well. Still, the same error kept coming up. What have I done wrong here ?


text:
Q: checkbox in listview doesn't save status when scrolling Android I have a list view from SQLite with checkboxes ..
It is all working fine , but when I click on one or more checkboxes and change their status then scroll down .. the checkbox status changes back to the original value (when the listview first created)
here is my code .. hope you can tell me how to solve it :
     public void showSQL(){
              /*
       *  Open the same SQLite database
       *  and read all it's content.
       */
    mySQLiteAdapter = new SQLiteAdapter(this);
    mySQLiteAdapter.openToRead();

    Cursor cursor = mySQLiteAdapter.queueAll();
    startManagingCursor(cursor);

    from = new String[]{SQLiteAdapter.NUMBER_CONTENT};

     to = new int[]{R.id.text};

    SimpleCursorAdapter cursorAdapter =
            new SimpleCursorAdapter(this, R.layout.row, cursor, from , to);

    cursorAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder(){
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            String number ;
            String is_star ;
            if (columnIndex == cursor.getColumnIndex("numbers")) {
                // If the column is IS_STAR then we use custom view.
                number = cursor.getString(1);
                is_star = cursor.getString(cursor.getColumnIndex("status"));

                if (is_star.equals("true")) {
                    // set the visibility of the view to GONE
                    ((CheckBox) view).setText("        " + number);
                    ((CheckBox) view).setChecked(true);
                    return true;
                }else{
                    ((CheckBox) view).setText("        " + number);
                    ((CheckBox) view).setChecked(false);
                    return true;
                }
                //return true;

            }
            return false;

        }

    });
    stopManagingCursor(cursor);

    listContent.setAdapter(cursorAdapter);

    listContent.setOnItemClickListener(listContentOnItemClickListener);

    mySQLiteAdapter.getAllNumbers();

    mySQLiteAdapter.close();

}

private ListView.OnItemClickListener listContentOnItemClickListener
        = new ListView.OnItemClickListener(){

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        // TODO Auto-generated method stub
        Cursor cursor = (Cursor) parent.getItemAtPosition(position);
        int item_id = cursor.getInt(cursor.getColumnIndex(SQLiteAdapter.NUMBER_ID));
        String item_content1 = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.NUMBER_CONTENT));

        mySQLiteAdapter = new SQLiteAdapter(getBaseContext());
        item = (CheckBox) view;

        mySQLiteAdapter.openToRead();
        String check = null;
        Cursor c = mySQLiteAdapter.getNumberStatus(item_id);
        if (c.moveToFirst()){
            check = c.getString(c.getColumnIndex(SQLiteAdapter.NUMBER_STATUS));
        }
        mySQLiteAdapter.close();

        //The change color logic is here!
       if(item.isChecked()) {
           mySQLiteAdapter.openToWrite();
           mySQLiteAdapter.updateNumberStatus(item_id,"false");
           mySQLiteAdapter.close();
          // Toast.makeText(MainActivity.this, "deleted" +" "+ check, Toast.LENGTH_LONG).show();
           item.setChecked(false);

       }
       else {
           mySQLiteAdapter.openToWrite();
           mySQLiteAdapter.updateNumberStatus(item_id,"true");
           mySQLiteAdapter.close();
          // Toast.makeText(MainActivity.this, item_content1 +" "+ check , Toast.LENGTH_LONG).show();
           item.setChecked(true);

       }

    }};

A: The issue with CheckBox inside ListView is that the view gets recycled due to recycling of view.
To, maintain the state to CheckBox there has to be something that can store the state of Checkbox.
Refer this link,it is very nice example explained here.
Link 1

A: You have to make a class to get and set state of checkbox . that will be used as arraylist to save state of checkbox. and use it to show checked item.


text:
Q: On a columns chart from highcharts, how to set xAxis labels at columns edges? I am using a column chart from highcharts. I would like to know how to have a xAxis displayed like that ? (Don't pay attention to the vertical line)

I tried to use xAxis with categories but without real success. I also tried to add a point interval but in both cases, labels are displayed under columns at center.

I'm not finding a way on highcharts documentation to have this result.
Thank you for your help.

A: Setting the pointPlacement to between is a solution which you are looking for.
Demo: https://jsfiddle.net/BlackLabel/mnce2r9q/
  series: [{
        type: 'column',
        pointPlacement: 'between',
    data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
  }]

API: https://api.highcharts.com/highcharts/series.column.pointPlacement


text:
Q: How to extract information from stdClass object? In the build function of my Mailable I extract information from a database like so:
$this->data = DB::select('select * from newsletter_mails order by id desc limit 1')[0];

\Log::info(print_r($this->data, true));

$this->subject = $this->data->subject;
$this->content = $this->data->content;

\Log::info(print_r($this->subject, true));
\Log::info(print_r($this->content, true));

which yields the log:
[2021-11-13 15:49:41] production.INFO: stdClass Object
(
    [id] => 2
    [from] => test@test.com
    [subject] => testSubject
    [content] => testMessage
    [file] =>
    [created_at] => 2021-11-13 15:49:10
    [updated_at] => 2021-11-13 15:49:10
)

[2021-11-13 15:49:41] production.INFO: testSubject
[2021-11-13 15:49:41] production.INFO: testMessage

As you can see data variable is a stdClass Object and the information gets extracted correctly. But now I want to get the from value:
$this->from = $this->data->from;

\Log::info(print_r($this->from, true));

This outputs two things in the log. First the correct output for $this->form:
[2021-11-13 15:55:25] production.INFO: test@test.com

But also an error:
[2021-11-13 15:55:25] production.ERROR: Cannot access offset of type string on string {"userId":1,"exception":"[object] (TypeError(code: 0): Cannot access offset of type string on string at C:\\Users\\Artur\\PhpstormProjects\\stuttard.de\\vendor\\laravel\\framework\\src\\Illuminate\\Mail\\Mailable.php:360)
[stacktrace]

What am I doing wrong?

A: You store the data in $this->data property and also overriding all other properties of the Mailable class.
You should store the data from the database in a local variable like this:
$data = DB::select('select * from newsletter_mails order by id desc limit 1')[0];
$from = $data->from;

\Log::info(print_r($from, true));


text:
Q: Send to back functionality in HTML5 I'm having the following use case that I want to achieve in HTML
I've two div element with background red and blue. The blue div is added later of which a part overlaped with red div.
I have the option of "send to back" which sends the selected div to back of other div.
If I apply this to blue div and select blue div it should look like below image

Basically I'm trying to minic the functionality of Arrange --> Order --> Send to back of Google Presentation
I did try z-index with no success. I can use background-gradient with the overlaped part of blue div transparent but that will invole some calculations which I want to avoid.
How to acheive this in HTML?
Any help is appreciated.
Note: All div elements are placed with position: absolute
Update: The red div lies above the blue div as its z-index is higher than blue div. When red div is selected it should look like below (with border highlighted).

Now if I select the blue div a part of it that overlapes with red div does not appear (obviously since its z-index is lesser) but I want its border to appear when I select.it.

A: As you've commented, I guess what you need is this, also, just call a class on a div which you want to stack up.
Final Demo

I am not getting your question quiet well, but I assume you want to bring an element above another when it is clicked, than you can do it this way
Demo
Explanation:
What am doing here is, am simply applying z-index on the div you click using jQuery.
Demo 3 (As you updated your question)

Using border to mark the current selected div
$(".wrap div").click(function(){
    $('.wrap div').removeAttr('style');
    $(this).css({"z-index":"1", "border":"1px solid #000"});
});

Demo 2
Code Reference :
$(".wrap div").click(function(){
  $(this).css("z-index","1");
});

.wrap {
    position: relative;
}

.wrap div {
    position: absolute;
    height: 100px;
    width: 100px;
}

.wrap div:nth-of-type(1) {
    background: #f00;
    left: 10px;
}

.wrap div:nth-of-type(2) {
    background: #0f0;
    left: 80px;
}


text:
Q: GridGain with SpringBoot I've compiled a docker image of GridGain Pro and run this.
with Java i do the following...
Create the following @Configuration file
@Configuration
@EnableCaching
public class CustomConfiguration extends CachingConfigurerSupport {

@Bean
@Override
public KeyGenerator keyGenerator() {
    return (target, method, params) -> {
        StringBuilder sb = new StringBuilder();
        sb.append(target.getClass().getName());
        sb.append(method.getName());
        for (Object obj : params) {
            sb.append("|");
            sb.append(obj.toString());
        }
        return sb.toString();
    };
}

@Bean("cacheManager")
public SpringCacheManager cacheManager(IgniteConfiguration igniteConfiguration){
    try {
        SpringCacheManager springCacheManager =  new SpringCacheManager();
        springCacheManager.setIgniteInstanceName("ignite");
        springCacheManager.setConfiguration(igniteConfiguration);
        springCacheManager.setDynamicCacheConfiguration(new CacheConfiguration<>().setCacheMode(CacheMode.REPLICATED));
        return springCacheManager;
    }
    catch (Exception ex){

    }
    return null;
}

@Bean
@Profile("!dev")
IgniteConfiguration igniteConfiguration() {

    GridGainConfiguration gridGainConfiguration = new GridGainConfiguration();
    gridGainConfiguration.setRollingUpdatesEnabled(true);
    IgniteConfiguration igniteConfiguration = new IgniteConfiguration()
    .setPluginConfigurations(gridGainConfiguration)
    .setClientMode(true)
    .setPeerClassLoadingEnabled(false)
    .setIgniteInstanceName("MyIgnite");
    DataStorageConfiguration dataStorageConfiguration = new DataStorageConfiguration();
    DataRegionConfiguration dataRegionConfiguration = new DataRegionConfiguration();
    dataRegionConfiguration.setInitialSize(20 * 1024 * 1024);
    dataRegionConfiguration.setMaxSize(40 * 1024 * 1024);
    dataRegionConfiguration.setMetricsEnabled(true);
    dataStorageConfiguration.setDefaultDataRegionConfiguration(dataRegionConfiguration);
    igniteConfiguration.setDataStorageConfiguration(dataStorageConfiguration);
    TcpDiscoverySpi tcpDiscoverySpi = new TcpDiscoverySpi();
    TcpDiscoveryVmIpFinder tcpDiscoveryVmIpFinder = new TcpDiscoveryVmIpFinder();
    tcpDiscoveryVmIpFinder.setAddresses(Arrays.asList("192.168.99.100:47500..47502"));

    tcpDiscoverySpi.setIpFinder(tcpDiscoveryVmIpFinder);
    igniteConfiguration.setDiscoverySpi(tcpDiscoverySpi);
    return igniteConfiguration;
}

}
Start spring and get the following error.
2018-04-18 12:27:29.277  WARN 12588 --- [           main] .GridEntDiscoveryNodeValidationProcessor : GridGain node cannot be in one cluster with Ignite node [locNodeAddrs=[server/0:0:0:0:0:0:0:1, server/10.29.96.164, server/127.0.0.1, /192.168.56.1, /192.168.99.1], rmtNodeAddrs=[172.17.0.1/0:0:0:0:0:0:0:1%lo, 192.168.99.100/10.0.2.15, 10.0.2.15/127.0.0.1, /172.17.0.1, /192.168.99.100]]
2018-04-18 12:27:29.283 ERROR 12588 --- [           main] o.a.i.internal.IgniteKernal%MyIgnite     : Got exception while starting (will rollback startup routine).
I'm trying to use gridgain as a replacement for redis and use the @Cacheable annotation.
Does anyone have a working gridgain example?
What is causing the error above?
G.

A: GridGain node cannot be in one cluster with Ignite node is pretty self-explanatory.

*

*Either you have forgot to stop some local Apache Ignite from earlier experiments.

*Or you have deliberately tried to make GridGain join an Ignite cluster.

*Or better yet, there is an instance of Apache Ignite running somewhere in your local network, and you have set multicast discovery or other kind of too-broad discovery, so they're seeing each other.

*Maybe gridgain-core.x.x.x.jar jar is miising from one of nodes' classpath. Check and add it if necessary.

A: 1) okay seems the issue was not providing H2 as a dependency.
2) using GridGain professional instead of GridGain Enterprise.
G.


text:
Q: Making a grid item span all the rows without affecting the other grid items I'm trying to make a dynamic grid where each new item goes into a new row inside a single column, but the last item must break into a new column and fill the entire grid-column, without affecting the other rows in the first column.
Note that the amount of items is dynamic, so I cannot use any fixed values and selectors to define the layout.
The layout im looking for:

What I've tried
As you can see, the rows in the first column have an equal height. I want the item inside the first row of the first column to keep its height relatively to its content like the other rows in the first column.
The height of the only item in the second column is irrelevant in this case, its height value will always be higher than the height of the other items in the grid.

ul {
  margin: 0;
  list-style-type: none;
  display: grid;
  grid-auto-flow: row;
  grid-template-columns: auto auto;
  grid-gap: 20px;
  max-width: 600px;
}

li {
  grid-column-start: 1;
  border: 1px solid black;
}

li.last {
  grid-column-start: 2;
  grid-row: 1/-1;
}

img {
max-width: 100%;
}

here's some content

here's some content

here's some content

here's some content

A: I think you have the right idea in your code for the last item:
li.last {
  grid-column-start: 2;
  grid-row: 1/-1;
}

This tells the last item to span from top to bottom.
The problem is that numeric indexes (1 / -1) only work with explicit grids. In other words, grids with defined columns and rows. You're using an implicit grid, where columns and rows are automatically generated, as needed.
Considering your requirements ("cannot use any fixed values and selectors to define the layout") this method won't work.
You could try flex, but even then, a height would have to be defined. Here's the concept:

ul {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  gap: 20px;
  max-width: 600px;
  margin: 0;
  list-style-type: none;
  padding: 0;
  height: 80vh;
}

li {
  flex: 1;
  border: 1px solid black;
}

li.last {
  flex-shrink: 0;
  height: 100%;
}

img {
  width: auto;
  height: 100%;
}

here's some content

here's some content

here's some content

here's some content

jsFiddle demo
More info:

*

*Make a grid item span to the last row / column in implicit grid

*Using negative integers with implicit rows in CSS Grid

*Make a grid column span the entire row

*Make a div span two rows in a grid


text:
Q: jQuery stopImmediatePropagation() issue with mouseenter and click events I've created a menu that is supposed to respond to hover (mouseenter/mouseleave) and click events so it will work with a mouse and touchscreen.
Here is a very simplified version:

$('.menu-item')
  .on('click', function(e) {
    $(this).toggleClass('active');
  })
  .on('mouseenter', function(e) {
    e.stopImmediatePropagation();
    $(this).addClass('active');
  })
  .on('blur mouseleave', function(e) {
    $(this).removeClass('active');
  });
.menu-item {background:red; text-align:center; padding:20px 0;}
.active {background:green;}

test

The problem I'm having is touchpad triggers both mouseenter and click events when the element is touched, which causes the 'active' class to be added, and then toggled off.  I have added the stopImmediatePropagation(), but both handlers are still triggered by the same event.


text:
Q: Tensorflow Module Not Found Error when running MNIST TPU I'm new to tensorflow and was trying to follow the tutorial here https://cloud.google.com/tpu/docs/quickstart to run the MNIST TPU model.
I got error from
  python3 mnist_main.py \
  --tpu=$TPU_NAME \
  --model_dir=$MODEL_DIR \
  --data_dir=$DATA_DIR \
  --train_epochs=10 \
  --distribution_strategy=tpu \
  --download

Error message
  Traceback (most recent call last):
  File "mnist_main.py", line 31, in <module>
    from official.vision.image_classification.resnet import common
  File "/usr/share/models/official/vision/image_classification/resnet/common.py", line 26, in <module>
    import tensorflow_model_optimization as tfmot
ModuleNotFoundError: No module named 'tensorflow_model_optimization'

Any idea about to solve it ? Thank you.

A: You need to install it using command line (or terminal).
pip install --user --upgrade tensorflow-model-optimization

A: In Google Colab, if you are running a notebook using qkeras you need to do the following:
!git clone https://github.com/google/qkeras.git
import sys
sys.path.append('qkeras')
!pip install git+https://github.com/keras-team/keras-tuner.git
!pip install tensorflow_model_optimization
import tensorflow_model_optimization as tfmot


text:
Q: Huge delay of scrolling images I am using rssFeed to load url image with following code. However, once images loaded into iPhone, there was huge delay of scrolling. I have been googling for solutions. Besides, changing to LazyImageLoad, is any easier solution that can fix my issue?? Thank you.
    NSString *imageURLString = [rssFeed objectForKey:@img"];
    NSURL *imageURL = [NSURL URLWithString:imageURLString];

    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

    cell.imageView.image = [UIImage imageWithData:imageData];

A: You have to download the images on a separate thread not on the ui thread. Is your choice if you download on demand or if you do a cashing algorithm.
And you should resize the images to a small size (preferable the size of your imageView) and then assign them to the imageView. In the table view you should only see an preview of the image.
If you want fast scrolling you have to build your own custom cell (not xib) by subclassing UITableViewCell and draw everything in the drawContentView.


text:
Q: How to solve MultiValueDictKeyError 'icon'? from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .models import Product
from django.utils import timezone

def home(request):
    return render(request, 'products/home.html')

@login_required
def create(request):
    if request.method == 'POST':
        if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.POST['icon'] and request.POST['image']:
            product = Product()
            product.title = request.POST['title']
            product.body = request.POST['body']
            product.url = request.POST['url']
            product.icon = request.FILES['icon']
            product.image = request.FILES['image']
            product.pub_date = timezone.datetime.now()
            product.hunter = request.user
            product.save()
            return redirect('home')
        else:
            return render(request, 'products/create.html', {'error':'all info is required'})
    else:
        return render(request, 'products/create.html')

A: Lol guys i solved my problem because
request.POST['icon'] and request.POST['image']
that request is post and i try to upload files in database
request.FILES['icon'] and request.FILES['image']
this is correct
thanks for your reply guys


text:
Q: How to connect multiple i2c-interface devices into a single pin A4 (SDA) and A5 (SCL) on Arduino? I want to add a real time clock module into my little project. I want to display both time and date on my existing i2c 2x16 LCD module.
Both i2c-interface real time clock module and 2x16 LCD module use the same pin A4 (SDA) and A5 (SCL) on Arduino Uno. After hours of searching on the net the i2c bus can actually take many serial devices. This is possible because each device has its own unique address.
My question is how to physically wire the two i2c-interface devices into a single A4 and A5? Thanks.

A: Some folks are having a hard time visualizing things connected together, so here's a picture:
(Serving suggestion)

simulate this circuit – Schematic created using CircuitLab
I2C is a bus, so like-named signals are connected together. The addressing scheme allows the microcontroller to select which device it's talking to. On the Arduino, the 10kΩ pull-up resistors go to VDD (Usually +5V or +3.3V).

A: Connect two pins A4-sda to A5-scl(on both board uno-uno) and connect resistor from 5v from each corresponding sda-scl lines.

A: For I2C, if all the slave devices have different device addresses, all of the SDA pins should be connected together, and all of the SCL pins should be connected together. It's as simple as that.
Naturally, you should also include pull-up resistors on both lines, as required for I2C. How to choose the resistor values has been discussed here before.

A: I2C is a data transfer protocol developed by Philips. Also known as two-wire interface since it uses two wires for communication. SCL-Serial Clock Line. SDL-Serial Data Line. So you need to connect corresponding pins of the i2c devices be it an eeprom or lcd to SCL and SDL pins of micro controller you are using with a pullup resistor to VDD. Since it is an addresses protocol having 7-bit address for each device connected you can address upto 2^7 different devices. But normally I2C address of a slave device is predefined with some bits to be hardwired by the developer. This helps in connecting same type of devices with different hardwired address part on the same bus.

A: Also you should check the pull up resistors. If you use already made boards, not only the chip, that boards usually have pull up resistors on board between buss and vcc. So when you connect every thing in parallel, the resistors are also in parallel, so total resistor value drop and your communication may fail.


text:
Q: How do I use dictionary to store the filename generated by a method in Python? I am using a method to generate multiple xml files.
I want to keep track of the files generated by the method using dictionary
map = {}
dstFile = f'path-to-dir\\{self.name}.xml'
with open(dstFile,'w') as f_out:
    f_out.write( u'<?xml version="1.0" encoding="UTF-8"?>'+'\n')
    f_out.write( ET.tostring(self.root).decode('UTF-8')
map = {f'{self.name}':f'{self.name}.xml'}

But using the map dictionary this way, previous values in the dictionary got overwritten
I want that when the method generate a file, its name will get added to the dictionary keeping the older  key value pairs also.
Thanks.

A: You can use dict's method update for example like this:
map.update(f'{self.name}'=f'{self.name}.xml')

A: This line
map = {f'{self.name}':f'{self.name}.xml'}

creates a new dictionary and assigns it to the variable map. You want to add a new key-value pair to the existing dictionary.
You can do this the following way:
map[self.name] = f"{self.name}.xml"


text:
Q: How to update Map using monocle I'd like to try Monocle library.
But i could not find help resources for base syntax.
In short i need optics Map[K,V] -> A having optics V -> A, how could i define this?
Suppose i have some
import monocle.macros.GenLens

case class DirState(opened: Boolean)

object DirState {
  val opened = GenLens[DirState](_.opened)
}

type Path = List[String]
type StateStore = Map[Path, DirState]

Next I encounter place where i need simple StateStore => StateStore, so  I'm importing
import monocle._
import monocle.std._
import monocle.syntax._
import monocle.function._

And trying to define first:
def setOpened(path: Path): StateStore => StateStore =
  at(path) composeLens DirState.opened set true

Getting here

ambiguous implicit values:  both method atMap in trait MapInstances of
  type [K, V]=> monocle.function.At[Map[K,V],K,V]  and method atSet in
  trait SetInstances of type [A]=> monocle.function.At[Set[A],A,Unit]
  match expected type
  monocle.function.At[S,Path,A]

Trying to change my definition to
def setOpened(path: Path): StateStore => StateStore =
  index(path) composeLens DirState.opened set true

Getting now:

type mismatch;  found   :
  monocle.function.Index[Map[Path,Nothing],Path,Nothing]
      (which expands to)  monocle.function.Index[Map[List[String],Nothing],List[String],Nothing]
  required:
  monocle.function.Index[Map[Path,Nothing],Path,A]
      (which expands to) monocle.function.Index[Map[List[String],Nothing],List[String],A]
Note:
  Nothing <: A, but trait Index is invariant in type A. You may wish to
  define A as +A instead. (SLS 4.5)

A: import monocle.function.index._
import monocle.std.map._
import monocle.syntax._

def setOpened(path: Path)(s: StateStore): StateStore =
  (s applyOptional index(path) composeLens DirState.opened).set(true)

let's have a look at the type of index
def index[S, I, A](i: I)(implicit ev: Index[S, I, A]): Optional[S, A] =
  ev.index(i)

trait Index[S, I, A] {
  def index(i: I): Optional[S, A]
}

So index summon an instance of type class Index of type Index[S, I, A].
This permits to use index for Map, List, Vector and so on.
The problem is that scala compiler needs to infer 3 types: S, I and A at the call site of index. I is easy, it is the type of the parameter you pass to index. However,S and A are only know when you call set.
The apply syntax has been created to guide type inference for such scenario, basically applyOptionalcaptures S which is Map[Path, DirState]. This gives enough information for the compiler to infer A =:= DirState.

A: Lots of examples of how to do this and many other handy tips are available in the Monocle repo:
https://github.com/julien-truffaut/Monocle/blob/master/example/src/test/scala/monocle/function/
More specificically for this scenario:
https://github.com/julien-truffaut/Monocle/blob/master/example/src/test/scala/monocle/function/FilterIndexExample.scala


text:
Q: Groups and Abelian I have these homework problems:
Is this statement true or false:
The set $$\left \{x \in \mathbb{R} \colon x \ge 0 \right \}$$ is a group under the binary operation $\circ$ defined
by $$a \circ b = \sqrt{ab}.$$

*Is the statement true or false:
The set

$$S=
\begin{bmatrix} a & b \\ c & d \end{bmatrix}
\big|
ad-bc=0$$
is a group under matrix addition.
If it is false, explain.
For question 2, I thought that a proof by contradiction could be used.

A: The first is false because the binary is not associative. (a*b)c = $\sqrt{\sqrt{abc^2}}$ $\neq$ $\sqrt{\sqrt{a^2bc}}$ = a(b*c)
For the second question, yes, it is a group under addition. (1) associative (2) identity matrix exists (3) for each element in S, there is an inverse element in S.


text:
Q: How to return several records in resulting RDD mapping one record in input RDD After several joins I've got an RDD which contains following records:
(Int, ((Int, Option[Iterable[Int]]), Option[Iterable[Int]]))

It is:
(id_of_client, ((id_of_order, products_in_order), all_products_client_ever_bought)

I need to transform it to (Int, Int, Boolean):
(id_of_order, all_products_client_ever_bought._1, was_this_product_in_this_order)
(id_of_order, all_products_client_ever_bought._2, was_this_product_in_this_order)
(id_of_order, all_products_client_ever_bought._3, was_this_product_in_this_order)
...

There should be as many, records in resulting RDD as there were items in all_products_client_ever_bought of all records of input RDD. So I'm mapping my input RDD, rdd.map(transform_df(_))
def transform_df(row: (Int, ((Int, Option[Iterable[Int]]), Option[Iterable[Int]]))) = {
    //(order_id, user_product_id, if_order_contains_product)
    val order_products = row._2._1._2.get.toList
    val user_products = row._2._2.get
    for (product_id <- user_products) {
        (row._2._1._1, product_id, order_products.contains(product_id))
    }
}

as a result I get RDD of the same length as input, but with empty tuples. How can I transform the RDD?

A: You are right, you need to "explode" your dataset, that is mapping each record to more than 1 records. With the RDD API, as well as in most functional programming languages, you need to use the flapMap function (explode is for dataframes).
See map-map-and-flatmap-in-scala for more detail on how to use flatmap. Basically, to each record of type A, you map a sequence of type Seq[B] and you get a RDD of type RDD[B] where everything is flattened out.
Another very convenient method in Spark is flatMapValue, with works on a pairRDD (key-value RDD) and only flattens the value.
In your example, you could first start by mapping your RDD to something that only contains what you need and which is more convenient to manipulate.
rdd.map{ case (id_of_client, ((id_of_order, products_in_order), all_products)
           => id_of_order -> (products_in_order.get.toSet, all_products.get) }

Note BTW that using pattern matching instead of the ._1._2._2 notation is a good practice to make your code more readable. I also transformed the products of the order into a Set because we will need to make requests on it afterwards.
Then you would only need to use flatMapValues to get what you want.
.flatMapValues{ case (products_in_order, all_products) =>
        all_products.map(p => p -> product_in_order.contains(p)) }
.map { case (a,(b,c)) => (a,b,c) }

The last line only transforms the results into exactly what you wanted.


text:
Q: Story Identification: Roald Dahl (?) Tale of Resurrected Mice Can anyone identify this story which traumatised me as a child?
The story concerned a small boy at a boarding house, or apartment and his creeping upstairs to spy on the old woman who lived upstairs. He was watching her through the keyhole.
He watched her singing a strange song and slicing the heads off mice with a carving knife in a strange ritualistic way. She then changed songs and somehow magically reattached and resurrected the dead mice, before looking directly at the protagonist and telling him that he'd seen too much and...
That's where my memory fails me, and I think as a child I had a fit of fright, threw the book away and ran screaming to my parents.
I think that this was a Roald Dahl short story - possibly one of the Tales of the Unexpected, or in his 'Henry Sugar' collection (though I can't find it in those collections.) like the Swans story which also upset me.
Sadly googling for "Roald Dahl" and Mice just brings up the sweet-shop story in 'Boy' or 'The Witches.' I may be entirely mistaken by the Dahl connection, but it's stuck in my mind and haunted my nightmares for years. It seems gruesome and weird enough for him.
Thanks!

A: This question was answered and accepted on Reddit as "The Loaf and the Knife" by Michael Rosen.

An old woman boasts that she can deal with vermin, but tells the
narrator not to watch. They watch through a keyhole though, and see
the woman sticking a knife, blade up, into a loaf of bread, then
hypnotising the mice to slit their throats on it. She then comes over
to the door and opens it: the narrator is crouching there frozen in
fear, and the woman tells them that she warned them not to watch, and
that now the memory will be with them forever.

The story appears in the collection Nasty! by Michael Rosen which can be borrowed from the Internet Archive.
You can also watch Michael Rosen tell the story on his YouTube channel.


text:
Q: Drupal: Completely override search functionality but use Drupal's template system (from a module) I'm writing a custom Drupal 7 module which will completely override the search page and search method for a website.  Here is what I have so far:
/**
 * Custom search.
 */
function mymodule_search_page() {
  drupal_add_css('css/search.css');

  // Perform a search (not important how)
  $result = do_custom_search('foo');

  return '
Results:
';
}

Now, as you can see, it's not complete. I don't know how to properly return structured HTML from this. How would I go about using Drupal's built-in template system to render the results?

A: you have to make use of drupal inbuilt functions. i hope you are looking for something like this http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_render/7

A: This is what I ended up doing:
/**
 * Implements hook_menu().
 */
function mymodule_search_menu() {
  $items = array();
  $items['search'] = array('page callback' => 'mymodule_search_page',
                       'access callback' => TRUE);
  return $items;
}

/**
 * Mymodule search page callback.
 */
function mymodule_search_page() {
  $variables = array();

  // Add stuff to $variables.  This is the "context" of the file,
  // e.g. if you add "foo" => "bar", variable $foo will have value
  // "bar".
  ...

  // This works together with `mymodule_search_theme'.
  return theme('mymodule_search_foo', $variables);
}

/**
 * Idea stolen from: http://api.drupal.org/comment/26824#comment-26824
 *
 * This will use the template file custompage.tpl.php in the same
 * directory as this file.
 */
function mymodule_search_theme() {
  return array ('mymodule_search_foo' =>
                array('template' => 'custompage',
                      'arguments' => array()));
}

Hope this helps someone!


text:
Q: Data fetching using Spring Data JPA Stream From DB2 Database Trying to implement Stream in Spring Data JPA to stream a resultSet from the DB2 table, but getting an error as below - (I am following this SO answer: https://stackoverflow.com/a/66792134/9884497, and a blog - https://www.geekyhacker.com/2019/03/26/high-performance-data-fetching-using-spring-data-jpa-stream/ )
I am using spring-boot-starter-data-jpa:2.5.8
  org.hibernate.exception.GenericJDBCException: Could not determine if resultset is empty due to exception calling isBeforeFirst or isAfterLast()
at
.....
org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.ibm.db2.jcc.am.SqlException: [jcc][t4][10179][10900][4.24.92] This method should only be called on ResultSet objects that are scrollable (type TYPE_SCROLL_SENSITIVE or TYPE_SCROLL_INSENSITIVE). ERRORCODE=-4476, SQLSTATE=null

I can see this problem listed at https://hibernate.atlassian.net/browse/HHH-13556 which was supposed to be solved at 5.3 Hibernate ORM Version but spring-boot-starter-data-jpa:2.5.8 already packed with Hibernate-core:5.4.33
Tried to find a solution but could not see any if we can use Stream in Spring Data JPA with DB2 Databases. Looked at the documentation as well but sadly no success. Posting here if anyone has used/is aware of the solution for DB2 Database.
So my questions are:

*

*Does DB2 supports Spring Data JPA Stream which can return Stream?

*What are the required configurations eg: the value of HINT_FETCH_SIZE

*How to get a Scrollable Result Set using Spring Data JPA Stream for DB2.

Meanwhile - I am able to solve this problem by StatelessSession but here looking if Spring Data JPA Stream works for DB2.


text:
Q: ImageButton in RemotesView stretches I'm making an application which shows a customized notification bar. The problem I'm facing is the ImageButtons in the view are stretched horizontally.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:weightSum="4" android:gravity="center_horizontal">

    <ImageButton
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/a"
            android:scaleType="centerInside"
            android:background="@drawable/a"/>
    <ImageButton
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/b"
            android:scaleType="centerInside"
            android:background="@drawable/b"/>
    <ImageButton
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/c"
            android:scaleType="centerInside"
            android:background="@drawable/c"/>
    <ImageButton
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/d"
            android:scaleType="centerInside"
            android:background="@drawable/d"/>
</LinearLayout>
..
RemoteViews rv = new RemoteViews(getPackageName(), R.layout.notification);
notification.contentView = rv;

The size of images I used is 72x72. The images are even worse when my device is tilted to landscape mode as the images tend to fill up the notification bar.
Is there a way to make sure images are scaled(down) uniformly and also leave some spaces between each ImageButton to make the notification look better?

A: To anyone who has similar question, the solution is to fitCenter instead of centerInside in the android:scaleType attribute.


text:
Q: Convert a datatime in UTC to epoch time (seconds) I want to convert a timestamp in UTC, e.g. May 27, 2020, 22:35 (UTC) to epoch seconds.  I will be hard coding the time in my code, so don't need to parse any string.  I am using the Calendar class as follows:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.set(2020, Calendar.MAY, 22, 22, 35);
calendar.getTimeInMillis();

The epoch time is correct to the second level, but the milliseconds part seems random on every run.  Example run output:
Time : 1590618900110

Is there a way I can set the millisecond to zero in Calendar object, or a better option, possibly from the java.time framework?
Edit:
The following worked fine for me, since I am hardcoding the UTC time in code:
Instant instant = Instant.parse("2020-05-27T22:35:00.00Z");
long timeInMillisEpoch = instant.toEpochMilli();

Thank you,
Ahmed.

A: since you already know the "exact datetime" and I guess you want to avoid the parsing, you can use this .of() method from java.time.OffsetDateTime, e.g.:
$ jshell

jshell> import java.time.*

jshell> OffsetDateTime odt = OffsetDateTime.of(2020, 5, 27, 22, 35, 0, 0, ZoneOffset.UTC)
odt ==> 2020-05-27T22:35Z

jshell> odt.toEpochSecond()
$14 ==> 1590618900

jshell> odt.toInstant().toEpochMilli()
$19 ==> 1590618900000

edit: rewrite following @Andreas advices


text:
Q: customize the code for tab view with using href Actual html file
It is coded for table but i need it for anchor

        click me

        click me

        click me

        click me

        click me

script.JS
var rows = document.getElementsByTagName('tr');

function rowHighlight() {
    var selectedRows = document.getElementsByClassName('selected');

    for (var n = 0; n < selectedRows.length; n++) {
        selectedRows[n].className = '';
    }
    this.className = 'selected'
}

for (var i = 0; i < rows.length; i++) {
    rows[i].addEventListener('click', rowHighlight);
}

css file
.selected {
    background-color:red;
}
table:hover {
    cursor:pointer;
}

The above code are the actual code but i want to customize it for my below code
html file
it is my code for tab view in ionic

        Top News

        Latest News

        Popular News

A: Here is the fiddle!

.red
{
 background-color:red;
}

        Top News

        Latest News

        Popular News

Hope it helps!


text:
Q: Is there a way to start mitmproxy v.7.0.2 programmatically in the background? Is there a way to start mitmproxy v.7.0.2 programmatically in the background?
ProxyConfig and ProxyServer have been removed since version 7.0.0, and the code below isn't working.
from mitmproxy.options import Options
from mitmproxy.proxy.config import ProxyConfig
from mitmproxy.proxy.server import ProxyServer
from mitmproxy.tools.dump import DumpMaster

import threading
import asyncio
import time

class Addon(object):
    def __init__(self):
        self.num = 1

    def request(self, flow):
        flow.request.headers["count"] = str(self.num)

    def response(self, flow):
        self.num = self.num + 1
        flow.response.headers["count"] = str(self.num)
        print(self.num)

# see source mitmproxy/master.py for details
def loop_in_thread(loop, m):
    asyncio.set_event_loop(loop)  # This is the key.
    m.run_loop(loop.run_forever)

if __name__ == "__main__":
    options = Options(listen_host='0.0.0.0', listen_port=8080, http2=True)
    m = DumpMaster(options, with_termlog=False, with_dumper=False)
    config = ProxyConfig(options)
    m.server = ProxyServer(config)
    m.addons.add(Addon())

    # run mitmproxy in backgroud, especially integrated with other server
    loop = asyncio.get_event_loop()
    t = threading.Thread( target=loop_in_thread, args=(loop,m) )
    t.start()

    # Other servers, such as a web server, might be started then.
    time.sleep(20)
    print('going to shutdown mitmproxy')
    m.shutdown()

from BigSully's gist

A: You can put your Addon class into your_script.py and then run mitmdump -s your_script.py. mitmdump comes without the console interface and can run in the background.
We (mitmproxy devs) officially don't support manual instantiation from Python anymore because that creates a massive amount of support burden for us. If you have some Python experience you can probably find your way around.
What if my addon has additional dependencies?
Approach 1: pip install mitmproxy is still perfectly supported and gets you the same functionality as the standalone binaries. Bonus tip: You can run venv/bin/mitmproxy or venv/Scripts/mitmproxy.exe to invoke mitmproxy in your virtualenv without having your virtualenv activated.
Approach 2: You can install mitmproxy with pipx and then run pipx inject mitmproxy <your dependency name>. See https://docs.mitmproxy.org/stable/overview-installation/#installation-from-the-python-package-index-pypi for details.
How can I debug mitmproxy itself?
If you are debugging from the command line (be it print statements or pdb), the easiest approach is to run mitmdump instead of mitmproxy, which provides the same functionality minus the console interface. Alternatively, you can use PyCharm's remote debug functionality, which also works while the console interface is active (https://github.com/mitmproxy/mitmproxy/blob/main/examples/contrib/remote-debug.py).

A: This example below should work fine with mitmproxy v7
from mitmproxy.tools import main
from mitmproxy.tools.dump import DumpMaster

options = main.options.Options(listen_host='0.0.0.0', listen_port=8080)
m = DumpMaster(options=options)
# the rest is same in the previous versions

A:     from mitmproxy.addons.proxyserver import Proxyserver
    from mitmproxy.options import Options
    from mitmproxy.tools.dump import DumpMaster
    options = Options(listen_host='127.0.0.1', listen_port=8080, http2=True)
    m = DumpMaster(options, with_termlog=True, with_dumper=False)
    m.server = Proxyserver()
    m.addons.add(
            // addons here
    )
    m.run()

Hi, I think that should do it


text:
Q: emit signal with custom type objects array parameter from c++ and receive in qml I would like to emit a signal from a Qt C++ class which includes a parameter that is an array of custom objects (inherited from QObject) and receive the parameter in its qml slot, but i'm afraid it is not available at qml code.
Let's say, for instance, that I have my class
class TestType : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString name READ name)
    Q_PROPERTY(qint32 id READ id)
public:
    explicit TestType(QObject *parent = 0) : QObject(parent) {}
    qint32 id() const { return m_id; }
    void setId(qint32 id) { m_id = id; }
    QString name() const { return m_name; }
    void setName(QString name) { m_name = name; }
private:
    qint32 m_id;
    QString m_name;
};

The type is registered this way:
qmlRegisterType<TestType>(uri, 0, 1, "TestType");

and I have a class where i emit a signal like this
Q_SIGNALS:
    void mySignal(QList<TestType *> array);

if I emit the signal with the array populated with several elements, if I try to read in qml slot:
onMySignal: {
  console.log("element:" + array[0]);
}

I see "undefined" as array[0] and, obviously, any class member the array element has. When I have made tests sending a standalone TestType object as signal parameter I have got it in qml slot without any problem, but I'm not able to send an array of them.
I've tried to use QList, QmlListProperty or QVariantList with the same result. Is there any way of sending an array of custom type inherited from QObject elements as a signal parameter?

A: I've got it!
This article explains how to do it perfectly
The solution is inserting TestType's in a QVariantList by using qVariantFromValue method. Then, the signal uses QVariantList as the type for all parameters that are lists
TestType *tt = new TestType(this);
QVariantList list;
list.append(qVariantFromValue((TestType*)tt));
Q_EMIT mySignal(list);

the signal is declared so:
Q_SIGNALS:
  void mySignal(QVariantList list);

Then, it can be read perfectly from qml:
onMySignal: {
    console.log("name of first TestType in list: " + list[0].name;
}


text:
Q: Array of 20000000 elements limits For a university project, I have to sort a CSV file of 20 million records (wich are represented in 2^64 bit, for example, 10000000 or 7000000, so I used unsigned long long) using MergeSort. So, I developed this C file:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

// Path to the dataset
#define DATASET_PATH "/Volumes/HDD/Lorenzo/Unito/2 Anno/ASD/Progetto/Progetto 2017-2018/laboratorio-algoritmi-2017-18/Datasets/ex1/integers.csv"
#define ELEMENTS_TO_SCAN 1000000 // the numbers of elements to be scanned

void mergeSort(unsigned long long * arrayToSort, int leftIndex, int rightIndex);
void merge(unsigned long long * arrayToSort, int left, int center, int right);
void read();
void printArray();

// from "Introduction to Algorithms" of T. H. Cormen
void mergeSort(unsigned long long * arrayToSort, int leftIndex, int rightIndex){
    if(leftIndex < rightIndex){
        int center = (leftIndex + rightIndex) / 2;
        mergeSort(arrayToSort, leftIndex, center);
        mergeSort(arrayToSort, center + 1, rightIndex);
        merge(arrayToSort, leftIndex, center, rightIndex);
    }
}

// from "Introduction to Algorithms" of T. H. Cormen
void merge(unsigned long long * arrayToSort, int left, int center, int right){
    int n1 = center - left + 1;
    int n2 = right - center;

    unsigned long long leftSubArray[n1+1];
    unsigned long long rightSubArray[n2+1];

    leftSubArray[n1] = ULLONG_MAX; // here Cormen use infinite
    rightSubArray[n2] = ULLONG_MAX; // here Cormen use infinite

    for(int i = 0; i < n1; i++)
        leftSubArray[i] = arrayToSort[left + i];
    for(int j = 0; j < n2; j++)
        rightSubArray[j] = arrayToSort[center + j + 1];

    int i = 0;
    int j = 0;
    int k = 0;

    for(k = left; k <= right; k++){
        if(leftSubArray[i] <= rightSubArray[j]){
            arrayToSort[k] = leftSubArray[i];
            i++;
        } else {
            arrayToSort[k] = rightSubArray[j];
            j++;
        }
    }
}

// it reads all the dataset, and saves every line (wich contains a single element)
// in a position of an array to sort by MergeSort.
void read(char pathToDataset[], unsigned long long arrayToFill[]) {
    FILE* dataset = fopen(pathToDataset, "r");
    if(dataset == NULL ) {
        printf("Error while opening the file.\n");
        exit(0); // exit failure, it closes the program
    }

    int i = 0;
    while (i < ELEMENTS_TO_SCAN && fscanf(dataset, "%llu", &arrayToFill[i])!=EOF) {
        //printf("%llu\n", arrayToFill[i]); // ONLY FOR DEBUG, it wil print 20ML of lines!
        i++;
    }
    printf("\nRead %d lines.\n", i);
    fclose(dataset);
}

void printArray(unsigned long long * arrayToPrint, int arrayLength){
    printf("[");
    for(int i = 0; i < arrayLength; i++) {
        if (i == arrayLength-1) {
        printf("%llu]", arrayToPrint[i]);
        }
        else {
            printf("%llu, ", arrayToPrint[i]);
        }
    }
}

int main() {
    unsigned long long toSort [ELEMENTS_TO_SCAN] = {};
    read(DATASET_PATH, toSort);

    mergeSort(toSort,0,ELEMENTS_TO_SCAN-1);
    printf("Merge finished\n");

    return 0;
}

after some testing, if ELEMENTS_TO_SCAN is bigger than 500000 (= 1/4 of 20 million) i don't know why, but the output on the terminal is
Segmentation fault: 11

Someone can help me?

A: You're doing a local variable declaration (eg on stack). If you're dealing with larger arrays, consider making them global, or use dynamic arrays — in general dynamic would be better. Using globals makes it easier to get into bad habits.
Why are global variables bad, in a single threaded, non-os, embedded application
Segmentation fault 11 because of a 40 MB array in C

A: As people pointed out, this type of allocation can't be done on Stack. I would try dynamically allocating it, for that you just need to change the code like so:
int main() {
    unsigned long long *toSort;
    toSort = (unsigned long long) malloc(ELEMENTS_TO_SCAN*sizeof(unsigned long long));
    read(DATASET_PATH, toSort);

    mergeSort(toSort,0,ELEMENTS_TO_SCAN-1);
    printf("Merge finished\n");

    free(toSort);
    return 0;
}

As you pointed the merge is the one causing problems. Just to note, if you use things like:
int array[n];

You will run into problems eventually, that's a given. If you don't know how much memory you will use at compile time, either use a data structure that supports the resizing like linked lists or dynamically allocate it .


text:
Q: OpenMapTiles: Generate boundary admin_level 6 at lower zoom levels I am wanting to show admin_level 6 boundaries at lower zoom levels (8, 7, 6), currently they start showing at zoom level 9.
I realize that I need to modify the import script so that this data is saved into the .mbtiles file. I have edited the boundary.sql file to change WHERE admin_level <= 4 to WHERE admin_level <= 6 for boundary_z6, boundary_z7 and boundary_z8.
I see the .sh file at /var/lib/docker/overlay/d9c758ee5fef79d79f0412880332a2efe66fd5c3d9614d6a710211c87e7bc04c/root/usr/src/app/import_osmborder_lines.sh, however I don't know if that will be overwritten at some point?
However, after a new import boundaries are still not shown at levels 8, 7, 6.
Looking deeper, it appears that I need to also modify the import_osmborder_lines.sh script so those lines get imported, but that is in its own docker file that I don't know how to edit so the quickstart.sh will use it.
How can I edit the import-osmborder docker file and have my quickstart.sh script use this for import? Or, am I going about this completely wrong?

A: I ended up editing the import_osmborder_lines.sh that is in the /var/lib/docker/ directory. This worked, but I still am not sure this is the ideal method.


text:
Q: pathos multiprocessing objects I have a piece of code I am writing using pathos multiprocessing, which is producing an error. The problem is that distributing processes using pathos.multiprocessing.pool over a set of objects seems to do the work on a different object than that initialised in the class definition.
class Training_Set:

    def __init__( self, configurations ):
        print("Train init",configurations)
        self.configurations = configurations
        self.forces   = np.concatenate( [ c.reference_forces   for c in configurations ] )
        self.dipoles  = np.concatenate( [ c.reference_dipoles  for c in configurations ] )
        self.stresses = np.concatenate( [ c.reference_stresses for c in configurations ] )

    def run( self, config ):
        print("Train: run config",config)
        ran_okay = config.run( clean = True)
        if not ran_okay:
                return( False )
        return( True )

    def run_multi(self):
        pool_size = mp.cpu_count()
        pool = mp.Pool(processes=pool_size,maxtasksperchild=1,)
        print("Train run_multi: configs",self.configurations)
        pool_outputs = pool.map(self.run, self.configurations)
        pool.close()
        pool.join()

        if "False" in pool_outputs:
             return( False)
             self.ran_okay = False
        else:
             return( True)
             self.ran_okay = True

@property
def new_forces( self ):
            print("Train: New forces config",self.configurations)
            return np.concatenate( [ c.new_forces for c in self.configurations ] )

The configuration objects initialised in __init__, run_multi() and in new_forces are the same. So these configurations are those used in the call to pool.map:
 pool_outputs = pool.map(self.run, self.configurations)

But the objects being referred to in the run definition occupy a different part of memory.
Any ideas what might be causing this would be appreciated!
Thanks!


text:
Q: Degeneration of curves inside a family of surfaces We are interested in understanding how a higher genus curve in a smooth surface of general type can degenerate into the non-normal locus of the limit of a degeneration of surfaces. More precisely:
Let $\mathscr{X} \to B$ be a family of surfaces over a smooth curve $B$ so that the general fiber $X_\eta$ is a smooth surface, the special fiber $X_0$ has semi log canonical singularities, and the canonical sheaf $\omega_{X_b}$ of every fiber is ample. This corresponds to a map from $B$ to the KSBA moduli space of stable surfaces.
Assume that the double locus of $X_0$ (i.e. the non-normal locus of $X_0$) has an irreducible component which is a rational curve $D$.
Question 1. Let $C_\eta \subset X_\eta$ be a smooth curve whose genus is $\geq 2$, and let $\mathscr{C} \to B$ be the family of curves obtains as the closure of $C_\eta$ inside $\mathscr{X}$. Denote by $C_0$ the special fiber $\mathscr{C} \cap X_0$. Can $C_0$ contain $D$ as an irreducible component?
We are additionally interested in how this can generalize to the case of pairs. In this setting, now suppose there is a divisor $\Delta \subset \mathscr{X}$ so that the pair $(X_b, \Delta_b)$ has slc singularities and the log canonical sheaf $\omega_{X_b} + \Delta_b$ is ample for every fiber, where $\Delta_b = X_b \cap \Delta$. Equivalently now there is a map from $B$ into the moduli space of stable pairs of dimension 2.
Question 2. If Question 1 is true, is it possible that $\Delta$ intersects $D$ (the component of $C_0$ inside the double locus of $X_0$) transversally at a smooth point of $C_0$ and that $\Delta \cap C_\eta \neq \emptyset$?

A: Let $S$ be the "usual" pinch point surface defined by $x^2t=y^2z$ in $\mathbb P^3$ and $T\subseteq \mathbb P^3$ an arbitrary general surface of degree $d-3\geq 2$. Let $X_0=S\cup T$. Note that then $\deg X_0=d$. Let $\ell\subseteq S$ be the double line and $H\subseteq \mathbb P^3$ a general surface of sufficiently high degree such that  $\ell\subseteq H$ and let $C_0=H\cap X_0$.
Since $T$ is general, it is smooth and intersects $S$ transversally, so I think $X_0$ is even semi-smooth, but for sure slc. Now choose a smoothing of $X_0$ as a degree $d$ surface in $\mathbb P^3$, i.e., let $f:\mathscr X\to B$ be a family of degree $d$ surfaces in $\mathbb P^3$ parametrized by a smooth curve such that $X_0$ is a fiber of $f$ and the general fiber $X_\eta$ is smooth. Since $d\geq 5$, $\omega_{X_b}$ is an ample line bundle for every $b\in B$.
Now let $\mathscr C$ be the collection of curves $C_b=H\cap X_b$ for $b\in B$. The general member will be smooth and $C_0$ contains $\ell$ as an irreducible component. So this seems to answer your first question.
For the second, take the same example, but add a $\Delta$, i.e., let $\Gamma\subseteq \mathbb P^3$ be a high degree general surface and let $\Delta_b:=\Gamma\cap X_b$ and $\Delta\subseteq \mathscr X$ the preimage of $\Gamma$ in $\mathscr X$. Then $\Gamma$ and hence $\Delta$ intersects $\ell$ transversally at a point which is smooth on $C_0$ and since $\Gamma$ is ample, $\Delta\cap C_\eta\neq\emptyset$.


text:
Q: ListPlot Presentation I would like to show the all the values on the horizontal axis. The default is an increment by 2. I am wanting to show 0 to 9 on the horizontal by increment of one so I can see the values aren't shown 1,3,5,7,9
a = {1, 3, 5, 7, 9, 11, 13, 15, 17};
b = {2, 4, 6, 8, 10, 12, 14, 16, 18};
ListPlot[{a, b}, PlotLabel -> "List ",
PlotMarkers -> {●, ▲},
PlotLegends -> {A, B}, GridLines -> All, PlotTheme -> "Scientific",
DataRange -> All]

A: FrameTicks -> {{Range[20], None}, {Range[9], None}}

or
FrameTicks -> {{Automatic, None}, {Range[9], None}}

DataRange -> {0,9} or DataRange -> {0,8} set the proper range but do force the ticks to be incremented by 1.


text:
Q: How big is the Windows Recycle Bin? I was deleting old files and folders and got this:

So I thought to myself, how big is the Recycle Bin?

A: The size of the Recycle Bin is customizable.

A: The Recycle bin is actually a folder.You can see it on C drive (or other drive if it also has recyling bin) if you enable show hidden files and show system files.If you want to you can also remove the folder.
The recycle bin on desktop is actually shortcut to real folder.
Any folder doesnt take up any disk space only its contents.So the more files it contains the "bigger" it is


text:
Q: ASP.NET file system permissions I always thought the user running the app pool was used to, for instance, access the file system when an application is trying to write a file.
I have an application in IIS, setup with Windows Integrated Authentication, that tries to write a file to the file system. I always get an error unless I give permissions on the file system to the specific domain user that logged in through Windows Integrated Authentication.
Any reason why I´m observing this behaviour?
Thx in advance

A: Are you using Impersonation? This would use the User's identity to do stuff, rather than the one of the AppPool. If you're using a third party ASP.net Application, check if they use Impersonation (for example, SharePoint does).
There is a way to revert the identity of the AppPool. Check this question which includes the RevertToSelf and HostingEnvironment.Impersonate methods. The Question is about SharePoint, but these two answers are the non-SharePoint way of reverting to the apppool, so they apply.


text:
Q: Do transaction in Django make things faster I have a Django application.
This Django application makes an api call to Twitter and gets my 100 recent tweets. I need to insert the tweets into the database.
I have a method to act on all 100 tweets. This method has a for loop where I create a model instance out of each Tweet and call instance.save() on each instance separately.
I found things slower and thought that transactions might make things faster.
So outside the method I added @method_decorator(transaction.atomic). I still have a for loop where I created model instance and do instance.save() but now the method is decorated with transaction.atomic.

*

*Is transaction.atomic supposed to make insertions to database faster for me?

*Will each instance.save() call still issue a database call?

*If it makes things faster, then how?

A: *

*No. The purpose of database transactions is to ensure data integrity. See Wikipedia for more information.

*Yes. Using transactions won't affect this.

*It doesn't.
What should make your code faster is submitting your new records all at once, in a single query, rather than one at a time. Look into Django's bulk_create. It's always hard to predict performance, but I suspect that will noticeably improve things.

A: In an atomic transaction, a series of database operations either all occur, or nothing occurs.
Decorating a method as atomic will guarantee atomicity on the database for the block of code within that method. If the method is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.
1. Transactions will not make your code any faster as per your use case. Infact, it will just guarantee that either all the tweets will be saved to the database or none of the tweets will be saved in the  case of an exception.
2. Yes, each instance.save() call will be a database call. So, there  would be 100 database calls each time.
3. Again, Transactions won't make this any faster for your use case.
How to make things faster then?
You can use Django's bulk_create to create all the tweets in a single query.
Tweet.objects.bulk_create([tweet1, tweet2, ...., tweet100]) # single query

This inserts the list of tweet objects into the database in an efficient manner in only 1 query.


text: Q: Proof of a R-sq formula when X is scaled to 1 While discussing with labmates about linear regression $Y =~ X\beta +\epsilon$ where $\epsilon_i\sim N(0, \sigma^2_e)$, someone suggests that when $X$ is scaled to variance of 1, the coeficient of determination $R^2$ can be written as $R^2=\frac{\beta^2}{\beta^2+\sigma^2_e}$. I tried to check this using R through simulated data, which turns out that this formula was correct. Could anyone provide the steps of derivation, preferrably through linear algeraic expressions.


text:
Q: JavaScript, regex: How to fetch mail address in mailto: links Is there a jquery plugin or may be a regex which can be used to all the fields in query string of a mailto: link. It should support the mailto syntax.
Say if I have a link like ...
Some msg

The regex should give me the mail addresses in mailto: link - astark1@unl.edu, id@internet.node. It should also support links like

For a link like
tell a friend

I would pass value and the function and get an associative array of email addresses and other fields passed in query string.

A: Parsing URLs, and especially their query strings, is not a job for regexes. You could use a proper URL-parsing library or perhaps just a query string parsing one.

A: I'm not sure how accurate this is, but it might be improved if you feel a necessity to use regex.
function getEmails(str) {
// returns a list of email addresses in 'str'
    var tags = str.match(//gi);
    var res = [];
    if (!tags.length) return res;
    for (var i = 0; i < tags.length; i++) {
        tags[i] = tags[i].replace(/^$/,'$2');
        var arr = tags[i].replace(/\s/g,'').split(',');
        for (var j = 0; j < arr.length; j++) res.push(arr[j]);
    }
    return res;
}

I'm not sure what you mean in the last part by the way so I tried to answer the first part.

A: If you know what you are doing :
var href = 'mailto:hello@world.com?subject=My+Subject&body=My+Body';

function getMailto(s) {
    var r = {};
    var email = s.match(/mailto:([^\?]*)/);
            email = email[1] ? email[1] : false;
  var subject = s.match(/subject=([^&]+)/);
            subject = subject ? subject[1].replace(/\+/g,' ') : false;
    var body = s.match(/body=([^&]+)/);
            body = body ? body[1].replace(/\+/g,' ') : false;

  if(email) {r['email'] = email;}
  if(subject) {r['subject'] = subject;}
  if(body) {r['body'] = body;}

  return r;
}

console.log(getMailto(href));

Demo : https://jsfiddle.net/l2aelba/qov9wpk5/

A: This works for me.
function parseMailTo(mailto) {
  var url = new URL(mailto)
  var query = parseQuery(url.search)
  return {
    to: {url.pathname}
    subject: {query.subject}
  }
}

function parseQuery(queryString) {
  var query = {};
  var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
  for (var i = 0; i < pairs.length; i++) {
      var pair = pairs[i].split('=');
      query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
  }
  return query;
}


text:
Q: Compile CPLEX in C++ in Linux: Command line I am a new user of CPLEX C++. I want to compile a C++ program on Linux. I tried the following command line for a C program and it works well. But I cannot compile a C++ program.
The command line which I use:
g++ hello.cpp \
  -I/<path>/CPLEX/CPLEX_Studio1261/cplex/include \
  -I<path>/CPLEX/CPLEX_Studio1261/concert/include \
  -L/<path>/CPLEX/CPLEX_Studio1261/cplex/lib/x86-64_linux/static_pic \
  -L/<path>/CPLEX/CPLEX_Studio1261/concert/lib/x86-64_linux/static_pic \
  -lilocplex -lconcert -lcplex -lm -lpthread

And errors:
In file included from
    <'path'>/CPLEX/CPLEX_Studio1261/concert/include/ilconcert/iloenv.h:21,
                     error: iostream.h: No such file or directory
    <'path'>/CPLEX/CPLEX_Studio1261/concert/include/ilconcert/ilosys.h:376:21: error: fstream.h: No such file or directory

... and many more errors like this.
What should I change in my command to be able compile C++ programs as well?
Any help would be appreciated.


text:
Q: Rails dark mode flickering I implemented dark mode for my Rails application but after I enable it, when I want to change the page using link_to my background is flickering. This happens twice.
This is my body, adding the class depending on the theme user choose.
  %body.pb-md-0.pb-3{class: cookies[:theme]}

And this is the way I change the theme
          =link_to theme_path(theme: :dark) do
             ....image here

this is the theme_path
  def display
      cookies[:theme] = {
          value: params[:theme].to_sym
      }
    redirect_to language_and_theme_path
  end

The only thing that works is refreshing the page, but I don't really want to refresh the page after every theme change.


text:
Q: Uncaught TypeError: Cannot read properties of undefined while looping objects So , I have 2 objects that are made of products , the main and the secondary , i have made a loop that searches in the main , and if it does not find the product , it deletes is from the secondary, Even though , with 10 products it worked, now that i have 1470 products the loop stops on the 4th repeat and says << Uncaught TypeError: Cannot read properties of undefined (reading 'name') >> , Here is the code

function deleter(){
        let main = main_products;
        let secondary= secondary_products;
        let i;
        let counter = 0;
        console.log(main);
        console.log(secondary); // just to be sure the data is ok
        for (i=0;i<1550;i++){
            counter = 0;
            while (secondary[i].name !== main[counter].name){
                counter ++;
                if (counter === 1550){
                    break ;
                } // i did this with break i dont know why i did though
            }
            if (secondary[i].name === main[counter].name){
                console.log("found  -> " + secondary[i].name);
            }
            else {
                console.log("did not find product -> "+ secondary[i].name +" on the main database . . .  ");console.log("initializing product deletion . . .");
                console.log(secondary[i].id);
                deletedata();
                document.getElementById("delete").innerHTML = "Done ✔";
            }
        }

    }

when i loop 10 products it works fine every time . Do i need to do something else now that the products are significantly more?
Edit
So the objects are made like this and i take the from woocommerce

[
{
"id": 67537,
"name": "test 10",
"slug": "",
"type": "simple",
"status": "draft",
"featured": false,
"catalog_visibility": "visible",
"description": "allagi\n",
"short_description": "",
"sku": "1230975071-1-1-1-1-1-1-1-1-1",
"price": "123122",
"regular_price": "123123",
"sale_price": "123122"
}
{
"id": 67536,
"name": "test 9",
"slug": "",
"type": "simple",
"status": "draft",
"featured": false,
"catalog_visibility": "visible",
"description": "allagi\n",
"short_description": "",
"sku": "1230975071-2",
"price": "123122",
"regular_price": "123123",
"sale_price": "123122"}]

Here is a picture
both objects are from woo

A: The problem is - you are running out of the bounds of you product array. It's caused by:

*

*You have 1470 products, but iterating over 1550 for (i = 0; i < 1550; i++). Can be fixed with for (i = 0; i < secondary.length; i++)

*No additional checks do we have next element or not in while loop

So I suppose fixed and optimized version of code may look like this:

  const main_products = [{id: 1, name: 'blabla1'}, {id: 2, name: 'blabla2'}, {id: 3, name: 'blabla3'}];
  const secondary_products = [{id: 2, name: 'blabla2'}, {id: 4, name: 'blabla4'}, {id: 5, name: 'blabla5'}];
  deleter();

  function deleter() {
    let main = main_products;
    let secondary = secondary_products;

    for (let i = 0; i < secondary.length; i++) {
      const productWeFound = main.find((product) => secondary[i].name === product.name);

      if (productWeFound) {
        console.log("found  -> " + secondary[i].name);
      } else {
        console.log("did not find product -> " + secondary[i].name + " on the main database . . .  ");
        console.log("initializing product deletion . . .");
        console.log(secondary[i].id);
        // deletedata();
        // document.getElementById("delete").innerHTML = "Done ✔";
      }
    }
  }


text:
Q: How can I change velocity by a certain factor for a certain time, while remaining consistent at different framerates? This is for a game, and I want the velocity of a certain object to decrease at a rate of 98% per frame, when the framerate is 30 frames per second. But, the framerate can be anything between 30 and 60 frames per second. The best solution I came up with was the following:
velocity *= 1.0 - 0.02 * (delta / maxDelta);
So in this case, if the framerate is 30 fps, the velocity will be multiplied by 1.0 - 0.02 * 1.0 = 0.98. If the framerate were 60 fps, the velocity would be multiplied by 1.0 - 0.02 * 0.5 = 0.99. But this is not exactly correct, since at 60 fps, after 2 frames the factor will be 0.9801, not 0.98. Almost there, but not exactly. Is there a simple way to do this more precisely? Thanks.

A: Imagining for a moment that your FPS will always be 30, can we express the velocity as a straightforward analytic function of the frame number, rather than as an incremental algorithm?
Yes we can, v = 0.98 ^ frame_number. The ^ is exponentiation.
Then we can reformulate that as a function of time (in seconds): v = 0.98 ^ (total_time_elapsed * 30). But then we notice this function is continuous and doesn't depend on the frame length.
If you really need to make it an incremental formula, it can be worked back into v = v * 0.98 ^ (time_elapsed_since_previous_frame * 30).

A: Basically I suppose you want to achieve determinism. You want the output to be independent of the frame rate.
Most physics engines perform uniform time stepping to be deterministic. You can read about uniform time stepping here, and a tutorial to implement the same.

Benefits:

*

*After implementing uniform time-stepping, you can simply implement constant acceleration which would look realistic without using complex hacky velocity formula.

*While this may look as some additional work, this is the time-tested approach used by most physics engines. So many resources that you find would be more relevant too.

*Implementing this would give you freedom to toy with more complex velocity logic without worrying about frame rate.
Good luck.


text:
Q: Why are resistors used in a Zener clamp circuit? A data acquisition channel is fed by a signal which first passes through a clamping circuit as I draw below. Here in the figure Output goes into the data acquisition board after a 8V clamp circuit:

When I opened the clamp box I saw 2 resistors in series both with input and output of the clamp. Why would those 2 resistors needed along with the Zener diode?
What might be problematic if do not have R1?
What might be problematic if do not have R2?
What might be problematic if do not have both R1 and R2?/Why not only use Zener for clamp?
I could't figure out scenarios when those resistors needed and how to choose in case.

A: In case input probe is connected to a point with a higher voltage than zenner's, it will draw a lot of current from that point if it is not limited by R1. Without R1, taking a measurement could break the circuit which is tested, the probe, or even the acquisition board, in case of a high voltage.
R2 may be there to protect high voltages which come back from acquisition board, maybe in case of malfunction.

A: R1 limits the current into the zener to protect the zener from abnormal input voltages. R2 limits the current into whatever circuit follows.


text:
Q: How to toggle auto open run tab when running application in Android Studio? Is there a way to make Android Studio toggle auto open the run tab when running an app?

A: The solution is to go to Run -> Edit Configurations -> select miscellaneous tab and check Show logcat automatically.


text:
Q: Symfony - DomCrawler get element by custom attribute I need filter this tag
<div dir=3D"ltr">

I tried it
$crawler = $crawler->filter('div[dir=3D"ltr"]');

But not work...
Expected "]", but <identifier "D" at 6> found.

Any ideas?

A: You're trying to work with data that is quoted-printable encoded. You need to decode the data before treating it like HTML. PHP has the built-in function quoted_printable_decode() to do this for you.
$html = quoted_printable_decode($html);
$crawler = new Crawler($html);
$crawler = $crawler->filter('div[dir="ltr"]');

A:             $crawler->filter('div')->each(function (Crawler $node, $i) {
                if ($node->attr('dir') == '3D"ltr"') {
                    // It's the element
                }
            });

This is the best way I know of to do it. Not sure if it's the best but it will work.