text:
Q: ORA-00942 SQLException with Hibernate (Unable to find a table) I'm trying to run a simple Hibernate application, but I get this error:
org.hibernate.exception.SQLGrammarException: could not execute query
java.sql.SQLException: ORA-00942: table or view does not exist

My Entity:
package beans;

import javax.persistence.*;

@Entity
public class Idt {
    @Id
    private int id;
    @Column(name="name")
    private String name;

    public Idt(){
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

My table is called IDT in the Hr user.
CREATE TABLE "HR"."IDT"
  (
    "ID"   NUMBER NOT NULL ENABLE,
    "NAME" VARCHAR2(20 BYTE),
    CONSTRAINT "IDT_PK" PRIMARY KEY ("ID") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ENABLE
  )
  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING STORAGE
  (
    INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT
  )
  TABLESPACE "USERS" ;

Hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

            <hibernate-configuration>

                <session-factory>

                    <!-- Database connection settings -->
                    <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
                    <property name="connection.url">jdbc:oracle:thin:@localhost:1521/xe</property>
                    <property name="connection.username">SYSTEM</property>
                    <property name="connection.password">19141914</property>

                    <!-- SQL dialect -->
                    <property name="dialect">org.hibernate.dialect.OracleDialect</property>

                    <!-- Echo all executed SQL to stdout -->
                    <property name="show_sql">true</property>

                    <property name="current_session_context_class">thread</property>

                    <mapping class="beans.Idt"/>

                </session-factory>

            </hibernate-configuration>

I guess that it is something with the mapping of the entity because of the SQLException:
java.sql.SQLException: ORA-00942: table or view does not exist

A: Perhaps you need to specify the schema, or something like that:
@Entity
@Table(schema = "HR")
public class Idt { ... }

Also make sure that account used by Hibernate (SYSTEM) has rights to access that table.

A: I ran into the same issue and after long time of trying to find out I was getting
java.sql.SQLException: ORA-00942: table or view does not exist

I found out its because the app did nto have access to the table stored in my database under schema called "system". The problem was solved by adding the following line inside my Hibernate.cfg.xml file : here is the line added to give absolute path/access to the table I created .
<property name="hibernate.default_schema">system</property>

Here is the full hibernate.cfg.xml configuration :
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:oracledb</property>
        <property name="hibernate.connection.username">usrname</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
        <property name="hibernate.default_schema">system</property>
        <property name="show_sql">true</property>
        <mapping resource="com/mkyong/user/DBUser.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

I hope this will help someone someday.

A: In my case, I was connected with Hibernate with a user without GRANT on the table and schema what I was trying to query.

A: Looks like you might be missing the '@Table' annotation.
You can add it like so:
@Entity
@Table(name="idt")
public class Idt {
    ...
}

A: Maybe you have chosen the wrong database:
jdbc:oracle:thin:@localhost:1521/xe
CREATE TABLE "HR"."IDT"

A: My Problem : In my case, I had two databases (DB-1 and DB-2) and the table where I needed to insert/modify was in DB-2 whene I'm connected to DB-1.
My solution : Creat a public synonymous in DB-1 with the DB-2.table name.
The script ( executed in DB-1 ) :
CREATE OR REPLACE PUBLIC SYNONYM "TABLE" FOR "SYNONYMOUS "."TABLE"@"PARAMETRAGE_LINK";

A:
java.sql.SQLException: ORA-00942: table or view does not exist.

This exception means that your table is not created, and you are performing queries on it. So to resolve this exception you have to create the table first...
Add this line to your configuration file. Here Hibernate will create your table automatically.
<property name="hbm2ddl.auto">create</property>

But if you want to update your table further use this instead,
<property name="hbm2ddl.auto">update</property>

A: use <property name="javax.persistence.schema-generation.database.action">create</property> in your hibernate config file. voila..!!

A: Issue could be with different table(might not exists or grant privilege is not for that table) mapped due to foreign key or synonym.
For me the issue was with a column in that table which had mapping with another schema-table, and it was missing.ex, public-synonym.

A: in my case synonym of the table was not there, and in code we were using table name directly, in this case the synonym should be there, or use query like select * from DBOwner.tablename in code

A: If you're working with Oracle DB, also check connection user's SELECT rights on the SEQUENCE used for that table. The same error occurs and it may be misleading..

A: if your table is new then check table grants for that user.


text: Q: MATLAB code, B = repmat(A, [1 1 1 13]). When I use the python equivalent numpy.matlib.repmat, I am not getting the desired result A 3-D matrix A has dimensions (181, 33, 65). The repmat function does the above operation and returns a 4-D matrix B of dimensions (181, 33, 65, 13). I tried in several ways in Python but was unsuccessful. Could someone suggest me a quick answer?

redpajama_set_name: RedPajamaStackExchange


text:
Q: PostgreSQL return a function with a Custom Data Type I want to create a function that returns a type that I made, but when I execute it, it says that the type doesn't exists. I assume that's cause it doesn't know about the custom type.
UDT:
CREATE TYPE building_code AS ENUM ('IT','EMS','HSB','ENG');

Function:
 CREATE FUNCTION roomCode(id int ) RETURNS building_code AS
$$
 SELECT building_code FROM venue as v WHERE id = v.id;
$$ LANGUAGE SQL;

A: This should just work. The enum should not be a problem. Tested with Postgres 9.1 and 9.2
CREATE TYPE building_code AS ENUM ('IT','EMS','HSB','ENG');
CREATE TEMP TABLE venue (id int PRIMARY KEY, building_code building_code);
INSERT INTO venue VALUES (1, 'ENG');

CREATE OR REPLACE FUNCTION room_code(_id int) --!
  RETURNS building_code AS
$func$
SELECT building_code FROM venue v WHERE v.id = $1 -- !
$func$ LANGUAGE SQL;

SELECT * FROM room_code(1);

Except ...

*

*In versions before 9.2 you can only use positional (numeric) parameters ($1) in SQL functions (unlike plpgsql functions).
In 9.2+ the column name would take precedence, so that the WHERE clause of your original code would always be TRUE and all rows would qualify - except that your function only returns the first, since it does not return a SETOF building_code.
Either rename your parameter or use positional parameter or, preferably, both.
If you must use conflicting parameter names, you can override the preference by using the function name to qualify the parameter. Like:
... WHERE v.id = room_code.id

*You shouldn't use the type name as column name.

*You should not use unquoted mixed case names like roomCode, which will be folded to lower case, unless you double-quote: "roomCode".

->SQLfiddle with 3 variants


text:
Q: Which linear maps on a finite field are field multiplications? I am mainly interested in the fields $\mathrm{GF}(2^n)$, but the question can be asked for any prime.
We can write out each element $x\in\mathrm{GF}(2^n)$ in base $2$ and note that its additive group combined with multiplication by elements of  $\mathrm{GF}(2)$ is isomorphic to the vector space $\left(\mathbb{Z}/(2\mathbb{Z})\right)^n$. Let $v:\mathrm{GF}(2^n)\to\left(\mathbb{Z}/(2\mathbb{Z})\right)^n$ stand for this "vectorisation" operation.
Linear maps on $\left(\mathbb{Z}/(2\mathbb{Z})\right)^n$ may be represented by $n\times n$, $\{0,1\}$-valued matrices.
Since field multiplication is linear for any $x\in\mathrm{GF}(2^n)$ there is a matrix $M_x$ such that for all $y\in\mathrm{GF}(2^n)$
\begin{align}
    M_x v(y) = v(x\cdot y),
\end{align}
There are, however $2^{n\times n}$ matrices and only $2^{n}$ field elements, so the question is what can we say about the structure of the set of matrices $\{M_x \mid x\in \mathrm{GF}(2^n)\}$ as a subset of the full set of matrices?
Loosely speaking - if I give you a matrix then how can you tell if it represents a field element?

A: We note that any finite field $GF(p^n)$ can be presented in the form $GF(p^n) = \Bbb Z_p[x]/\langle q(x)\rangle $, where $\Bbb Z_p = \Bbb Z/p\Bbb Z$ and $q$ is an irreducible polynomial of degree $n$.  Relative to the basis $\{1,x,\dots,x^{n-1}\}$, we find that the matrix $M_x$ corresponding to multiplication by (the distinguished indeterminate) $x$ is given by the companion matrix $C_q$ of $q$.  It follows that a matrix $M$ corresponds to a field element if and only if there exists there exists a polynomial $f$ for which $M = f(C_q)$.
Because the matrix $C_q$ is non-derogatory, it turns out that there is such a polynomial $f$ if and only if $C_q M = MC_q$ (cf. Horn and Johnson Matrix Analysis theorem 3.2.4.2).
We can get another perspective on this if we take the elements of the matrix to themselves be elements of $GF(p^n)$.  Any irreducible polynomial over $\Bbb Z_p$ splits into distinct linear factors over its splitting field.
It follows the polynomial $q$ splits into linear factors with
$$
q(x) = (x - a_1)\cdots (x - a_n), \quad a_i \in GF(p^n).
$$
It follows that the matrix $C_q$ is diagonalizable $GF(p^n)$. A matrix $M$ will commute with $\operatorname{diag}(a_1,\dots,a_n)$ if and only if it is also diagonal. So, given a matrix, it suffices to change bases and check whether the transformed matrix has the required block structure.
More specifically, the eigenvectors of $C_p$ correspond to the polynomials of multiplication by $x$, which are
$$
q_i(x) = q(x)/(x - a_i), i = 1,\dots,n.
$$
In particular, we can see that $xq_i(x) = a_i q_i(x)$, modulo $q(x)$. $M$ will correspond to multiplication by an element of $GF(p^n)$ if and only if $p_i(x)$ is an eigenvector of (the operator over $\Bbb Z_p/q(x)$ corresponding to) $M$ for all $i$.


text:
Q: LibGDX How to use viewport to support different screen sizes I have been looking for a way that works for me to use viewport in my android libgdx application but all of the ones I find never seem to work. I don't use a stage, so I'm wondering if that's my problem.
For example, if I add this code to my application:
private Viewport viewport;
private Camera camera;

public void create() {
    camera = new PerspectiveCamera();
    viewport = new StretchViewport(800, 480, camera);
}

@Override
public void resize(int width, int height) {
    viewport.update(width, height);
}

When I try this on a phone, it works, but then when I try it on a 7 inch tablet, all the objects in my app are too big, almost as if I need to zoom out. I have tried a lot of the viewports including FitViewport and FillViewport, but they don't seem to work. I have also tried changing the 800, 480 in the StretchViewport to 800, 600 because that's my background image size, but it didn't do anything.
This is what it looks like on a phone:

Then, on a tablet, it looks like this:

As you can see, the tablet is more zoomed in.
Here's my render() method:
@Override
public void render () {

    batch.begin();
    batch.draw(backgroundimg, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

    if(Gdx.input.justTouched()){

        isGoingUp = !isGoingUp;

    }

    if(gameState == 1) {

        if(obstacleX[scoringObstacle] + obstacle.getWidth() < Gdx.graphics.getWidth() / 2 + balls[0].getWidth()){

            if(obstacleY[scoringObstacle] < Gdx.graphics.getHeight() && obstacleY[scoringObstacle] + obstacle.getHeight() > 0) {

                score++;

                if(score > highscore){

                    highscore++;

                    highscorePref.putInteger("highscore", highscore);

                    highscorePref.flush();

                }

                if(score >= 10 && score < 20){

                    obstacleVelocity = 11;//6

                }

                else if(score >= 20 && score < 30){

                    obstacleVelocity = 12;//7

                }

                else if(score >= 30 && score < 40){

                    obstacleVelocity = 13;//8

                }

            }

            if(scoringObstacle < numberOfObstacles - 1){

                scoringObstacle ++;

            }

            else{

                scoringObstacle = 0;

            }

        }

        for (int i = 0; i < numberOfObstacles; i++){

            if (obstacleX[i] < - obstacle.getWidth()){

                obstacleX[i] += numberOfObstacles * distanceBetweenObstacles;

                obstacleY[i] = (randomGenerator.nextFloat() - 0.5f) * (Gdx.graphics.getHeight() * 1.5f);

                if (obstacleY[i] > Gdx.graphics.getHeight() - 200 || obstacleY[i] + obstacle.getHeight() < 200){

                    obstacleY[i] = Gdx.graphics.getHeight() / 2 - obstacle.getHeight() / 2;

                }

            }

            else {

                obstacleX[i] = obstacleX[i] - obstacleVelocity;

            }

            batch.draw(obstacle, obstacleX[i], obstacleY[i]);

            if(score >= 20){

                if(obstacleX[3] < - obstacle.getWidth()){

                    bhGone = true;

                }

                if(bhGone) {

                    bhChance = randomGenerator.nextInt(2);

                    bhGone = false;

                }

                if(bhChance == 0){

                    batch.draw(blackHole, obstacleX[3] - distanceBetweenObstacles / 2 + blackHole.getWidth() / 2, Gdx.graphics.getHeight() / 2 - blackHole.getHeight() / 2);

                    blackHoleCircle.set(obstacleX[3] - distanceBetweenObstacles / 2 + blackHole.getWidth(), Gdx.graphics.getHeight() / 2, blackHole.getHeight() / 2);

                }

            }

            obstacleRectangles[i] = new Rectangle(obstacleX[i], obstacleY[i], obstacle.getWidth(), obstacle.getHeight());

            if (Intersector.overlaps(ballCircle, obstacleRectangles[i])) {

                diedByBh = false;

                gameState = 2;

            }

            else if(Intersector.overlaps(ballCircle, blackHoleCircle)){

                diedByBh = true;

                blackHoleCircle.set(0, 0, 2);

                gameState = 2;

            }

        }

        for(int i = 0; i < numberOfBalls; i++) {

            if (!isGoingUp) {

                if(ballY[i] >= 0) {

                    ballY[i] = ballY[i] - ballVelocity;

                }

            }

            else{

                if(ballY[i] <= Gdx.graphics.getHeight() - balls[0].getWidth()) {

                    ballY[i] = ballY[i] + ballVelocity;

                }

            }

        }

        if (ballState < 7) {

            ballState++;

        } else {

            ballState = 0;

        }

    }

    else if(gameState == 0){

        infoFont.draw(batch, "Tap to move up and down", Gdx.graphics.getWidth() / 4 - fontBack, Gdx.graphics.getHeight() / 2);

        if(Gdx.input.justTouched()){

            gameState = 1;

        }

    }

    else if(gameState == 2) {

        if(diedByBh){

            balls[ballState] = new Texture("nothing.png");

        }

        else {

            balls[ballState] = new Texture("splatteredball.png");

        }

        infoFont.draw(batch, "Tap to play again", Gdx.graphics.getWidth() / 4 - fontBack, Gdx.graphics.getHeight() / 2);

        highscoreFont.draw(batch, "High Score: " + String.valueOf(highscore), Gdx.graphics.getWidth() / 4 - fontBack, Gdx.graphics.getWidth() / 4 - 100);

        if(showAd) {

            showAd = false;

            adNumber = 1;

            adsController.showInterstitialAd();

        }

        else {

            if(!adNumDone) {

                if (adNumber < 15) {

                    adNumber++;

                } else {

                    showAd = true;

                }

                adNumDone = true;

            }

        }

        isGoingUp = true;

        if (Gdx.input.justTouched()) {

            if(Gdx.input.getY() < viewport.getWorldHeight() / 2){

                adsController.showRewardedVideoAd();

            }

            else {

                adNumDone = false;

                gameState = 1;
                startGame();
                score = 0;
                scoringObstacle = 0;

            }

        }

    }

    batch.draw(balls[ballState], Gdx.graphics.getWidth() / 2 + balls[0].getWidth(), ballY[ballState]);

    ballCircle.set(Gdx.graphics.getWidth() / 2 + balls[0].getWidth() + balls[ballState].getWidth() / 2, ballY[ballState] + balls[ballState].getHeight() / 2, balls[ballState].getHeight() / 2);

    scoreFont.draw(batch, String.valueOf(score), 50, Gdx.graphics.getHeight() - 50);

    batch.end();

}

Any ideas would be greatly appreciated. Thanks in advance!


text:
Q: How to add api data as array to be displayed on excel (Angular) exportExcel(): void {

    const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(this.data);
    const data1 = [];
    XLSX.utils.sheet_add_aoa(ws, data1, {origin: "G13"});

    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    XLSX.writeFile(wb, this.fileName);

}

I tried to load API data as array data1 and export on excel. When I export the data is not displayed


text:
Q: Brightness native plugin shows -1.0 Can you tell me why brightness native plugin shows -1.0 as the first time?
When I changed it and get again it shows correctly.But first time having above issue.Because my device default brightness is 80%.It should show that as 0.8 by default no?
ionViewDidEnter() {
     this.platform.ready().then(() => {
        this.brightness.getBrightness().then((res: number) => {
          this.settings.brightness = Math.abs(res * 100);
          console.log('init:', res);
          }).catch((err) => {
          console.error(err)
        })
      });
  }

output
init: -1.0


text:
Q: Running Ubuntu on Windows (WSL) leads to SystemOutdated Error when trying to install bun I tried to install bun https://bun.sh/ on my windows machine and use Ubuntu 20.04 on WSL.
After running curl https://bun.sh/install | bash and trying to run a command I get the following error:
coding@DESKTOP-PO2H28R:~$ bun create app
Fetching package.json... error: Failed to initialize network thread: SystemOutdated.

I ran apt-get update and apt-get update before which did not solve the issue. I also ran wsl --update which did nothing.  Does anyone know how to fix that?

A: I can reproduce this when attempting to run bun under WSL1/Ubuntu 20.04.  However, WSL2 works fine, at least for this command.
Check your release by running wsl.exe -l -v.
WSL1 does not provide a real Linux kernel, but rather a pseudo-kernel that acts as a syscall translation layer between the Linux and Windows APIs.  It's pretty dang impressive, but it's quite a ways from 100% implementation.  The last report I saw showed that about 73% of the LTP tests passed on WSL1.
That may sound low, but those APIs seem to provide upwards of 99% of the functionality for most common developer tools and languages at the time.
However, it's not surprising that a new and extremely (apparently) optimized runtime like Bun might rely on something that isn't implemented in WSL1.  The networking stack is definitely a big area where WSL1 and the Linux kernel differ, since the Windows and Linux architecture is quite different.  The error that we're seeing definitely indicates that the problem is in that area.
If your system is capable of running WSL2, then you'll want to run Bun under a WSL2 instance.  You can keep your existing WSL1 Ubuntu if you'd like (there are some advantages of WSL1) for other purposes, or you can convert it entirely.
See this answer (among others) for some details of how to back up and clone the existing distribution.  When you do the --import step, specify the --version 2.
Or, after (optionally) backing up, use wsl --set-version <distro_name> 2.


text:
Q: $a-b,a^2-b^2,a^3-b^3...$ are integers $\implies$ $a,b$ are integers? Let $a,b$ be distinct real numbers such that $a^n -b^n$ is integer for every positive integer $n$ , then is it true that $a,b$ are integers ?

A: This answer is really just the same as barto's, but written up in a more self contained fashion. We may write, as barto has already shown,  $a = \frac{c}{d}, b = \frac{e}{d}$ with $ce$ relatively prime to $d$ and $c,d,e$ integers with $d >0.$ Now for every $d,$ we have $c^{n} \equiv e^{n}$ (mod $d^{n}$). Suppose that $d > 1.$ Then for every integer $n>0,$ we have $c^{n}-e^{n} = (c-e) \sum_{j=0}^{n-1}c^{j}e^{n-1-j}.$ Hence $\frac{c^{n}-e^{n}}{c-e} \equiv nc^{n-1}$ (mod $d$) But $c$ is relatively prime to $d,$ so whenever $n$ is relatively prime to $d,$ we conclude that $\frac{c^{n}-e^{n}}{c-e}$ is relatively prime to $d$. Hence $c-e$ is divisible by $d^{n},$ as $c^{n}-e^{n}$ is, a contradiction, as $d >1$  and $n$ can be arbitrarily large.

A: As many others have noticed, it readily follows that $a,b\in\mathbb Q$. Let $a=\frac cd$ and $b=\frac ef$ such that $\gcd(c,d)=\gcd(e,f)=1$ and $d,f>0$. Writing $\frac cd=z+\frac ef=\frac{fz+e}f$ with $z\in\mathbb Z$, we see that $d=f$.
Note that we have $d^n\mid c^n-e^n$ for every $n$.
I will use the following result, where $\nu_p(n)$ denotes the exponent (possibly $0$) of the prime $p$ in the prime factorization of $n$:
Lemma. Let $x$ and $y$ be (not necessarily positive) distinct integers and let $n$ be a positive integer. If $p$ is a prime such that $p\mid x-y$ but $p\nmid n,x,y$, then  $\nu_p(x^n-y^n)=\nu_p(x-y)$.
Proof. See here, Lemma 1 or by using the result from this earlier question. As you can see, the proof is elementary and very short.
Now suppose $p$ is a prime divisor of $d$, and let $k=\nu_p(c-e)$.
Consider the integers $n$ that are not divisible by $p$, for example $n=pm+1$. From $d^n\mid c^n-e^n$ and the above lemma it follows that $n\leqslant k$ for all such $n$, which is clearly a contradiction because $n$ can be arbitrarily large.
We conclude that no such $p$ exists. Hence $d=1$, and $a,b\in\mathbb Z$.


text:
Q: Q3.24 (d) Signals & Systems 2ed by A. Oppenheim 3.24 (d) Determine the Fourier series representation for the following signal:
a_k = 1 (k is even), 2 (k is odd)
The solution (see attached) breaks down the answer to two components:
y(t) and z(t). How is z(t) derived?

A: Let me start by the definition of the Fourier coefficients that I use:
$$f(t)=\sum_{k=-\infty}^{\infty}c_ke^{j2\pi kt/T}\tag{1}$$
with
$$c_k=\frac{1}{T}\int_{0}^Tf(t)e^{-j2\pi kt/T}dt$$
where \$f(t)\$ is periodic with period \$T\$. If you now look at the Fourier series of a Dirac comb
$$\sum_{k=-\infty}^{\infty}\delta(t-kT)=\frac{1}{T}\sum_{k=-\infty}^{\infty}e^{j2\pi kt/T}\tag{2}$$
and you compare (1) and (2), then you see that the Fourier coefficients of the signal \$y(t)\$ in your example are actually given by \$c_k=1/T\$ (for all \$k\$) with \$T=4\$, which differs from the coefficients \$b_k\$ in the example by a factor of 4. I'm not sure if this is a mistake in the book or if they use some other scaling. Anyway, I'll use the values of \$b_k\$ and \$c_k\$ as given in the example and I'll show how you can obtain \$z(t)\$. In order to get the factors right, I will use
$$y(t)=4\sum_{k=-\infty}^{\infty}\delta(t-4k)$$
which corresponds to Fourier coefficients \$b_k=1\$ for all \$k\$. From (1) the signal \$z(t)\$ is given by
$$z(t)=\sum_{k=-\infty}^{\infty}c_ke^{j2\pi kt/T}$$
Since \$c_k=0\$ for even \$k\$ we have
$$z(t)=\sum_{k\textrm{ odd}}c_ke^{j2\pi kt/T}=\sum_{k=-\infty}^{\infty}c_{2k+1}e^{j2\pi (2k+1)t/T}$$
And since \$c_{2k+1}=1\$ for all \$k\$ we can simply replace them by \$b_k\$:
$$z(t)=\sum_{k=-\infty}^{\infty}b_ke^{j2\pi (2k+1)t/T}=
\sum_{k=-\infty}^{\infty}b_ke^{j2\pi k(2t)/T}e^{2\pi t/T}=y(2t)e^{2\pi t/T}\tag{3}$$
Using \$\delta(at)=\delta(t)/|a|\$ we get
$$y(2t)=4\sum_{k=-\infty}^{\infty}\delta(2t-4k)=
4\sum_{k=-\infty}^{\infty}\delta(2(t-2k))=
2\sum_{k=-\infty}^{\infty}\delta(t-2k)\tag{4}$$
Combining (3) and (4) and using \$T=4\$ we get
$$z(t)=2\sum_{k=-\infty}^{\infty}e^{\pi t/2}\delta(t-2k)$$
which differs from the one given in your example by a factor 2. Anyway, given the definition (1) I'm pretty sure that this is correct.


text:
Q: How to let an A href link in the menu bar when clicked, it opens a closed accordion in the body? - html how the first accordion could be opened when clicked on the a href named "open 1st accordion" and the same thing for the second a href?? The accordion itself works 100% right, I just want to access it from outside it's scope, when clickng on an a href button in the menu bar.

$(".expand").on("click", function () {
    $(".right-arrow").text("+");
    $(".detail:visible").slideUp();
    if(!$(this).next().is(":visible")){

        $(this).next().slideDown(200);
        $(this).find(".right-arrow").text("-");
    }
});
/*Tips & Tricks Page*/
*,
*:before,
*:after {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

#trickslist {
    font-family: 'Open Sans', sans-serif;
    width: 80%;
    margin: 0 auto;
    display: table;
}
#trickslist ul {
    padding: 0;
    margin: 20px 0;
    color: #555;
}
#trickslist ul > li {
    list-style: none;
    border-top: 1px solid #ddd;
    display: block;
    padding: 15px;
    overflow: hidden;
    text-align: center;
}
#trickslist ul:last-child {
    border-bottom: 1px solid #ddd;
}
#trickslist ul > li:hover {
    background: #efefef;
}
.expand {
    display: block;
    text-decoration: none;
    color: #555;
    cursor: pointer;
}
.tipstricks {
    padding: 5px;
    margin: 0;
    font-size: 17px;
    font-weight: 400;
}

span {
    font-size: 12.5px;
}
#left,#right{
    display: table;
}

.detail a {
    text-decoration: none;
    color: #C0392B;
    border: 1px solid #C0392B;
    padding: 6px 10px 5px;
    font-size: 14px;
}
.detail {
    margin: 10px 0 10px 0px;
    display: none;
    line-height: 22px;
    height: 150px;
}
.detail span{
    margin: 0;
}
.right-arrow {
    padding-top: 0px;
    margin-top: 0px;
    margin-left: 20px;
    width: 10px;
    height: 100%;
    float: right;
    font-weight: bold;
    font-size: 20px;
}

 Open 1st accordion

 Open 2nd accordion

+

Exploring your Motivations to Quit Tobacco

+

What to expect over time.

+

Getting Ready: Strategies to conquer urges & set a quit date

+

Quitting tobacco with medications

+

Dealing with depression or stress

+

Avoiding weight gain or alcohol

+

Making your plan stick: relapse prevention

Services.html (every a href in this menu should link to accordions in index.html and open them)

Who We Are

Our Services

Our Clients

Contact Us

A: Add a class to the top tags a:
 Open 1st accordion

 Open 2nd accordion

Next, using the each() method and the index parameter, write the logic of the click event on these a tags.
Use event.preventDefault() to disable the default behavior of the a tag.
And using the trigger() method, call click events on the .expand class using an eq() with the appropriate index:
$(".expand").eq(index).trigger('click');

As such, we get the following code. Just add it to your main code.
$('.accord').each(function(index) {
  $(this).click(function(event) {
    event.preventDefault();
    $(".expand").eq(index).trigger('click');
  });
});

EDIT:
Modified the jquery code taking into account the localStorage().

$(document).ready(function () {
    $(".expand").on("click", function () {
        $(".right-arrow").text("+");
        $(".detail:visible").slideUp();
        if (!$(this).next().is(":visible")) {
            $(this).next().slideDown(200);
            $(this).find(".right-arrow").text("-");
        }
    });

    let click_state = localStorage.getItem("click_state");
    let ind = localStorage.getItem("ind");

    if (click_state == 1) {
        $(".expand").eq(ind).trigger("click");

        localStorage.removeItem("click_state");
        localStorage.removeItem("ind");
    } else {
    }

    $(".accord").each(function (index) {
        $(this).click(function (event) {
            event.preventDefault();

            localStorage.setItem("click_state", 1);
            localStorage.setItem("ind", index);
        });
    });
});
/*Tips & Tricks Page*/
*,
*:before,
*:after {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

#trickslist {
    font-family: 'Open Sans', sans-serif;
    width: 80%;
    margin: 0 auto;
    display: table;
}
#trickslist ul {
    padding: 0;
    margin: 20px 0;
    color: #555;
}
#trickslist ul > li {
    list-style: none;
    border-top: 1px solid #ddd;
    display: block;
    padding: 15px;
    overflow: hidden;
    text-align: center;
}
#trickslist ul:last-child {
    border-bottom: 1px solid #ddd;
}
#trickslist ul > li:hover {
    background: #efefef;
}
.expand {
    display: block;
    text-decoration: none;
    color: #555;
    cursor: pointer;
}
.tipstricks {
    padding: 5px;
    margin: 0;
    font-size: 17px;
    font-weight: 400;
}

span {
    font-size: 12.5px;
}
#left,#right{
    display: table;
}

.detail a {
    text-decoration: none;
    color: #C0392B;
    border: 1px solid #C0392B;
    padding: 6px 10px 5px;
    font-size: 14px;
}
.detail {
    margin: 10px 0 10px 0px;
    display: none;
    line-height: 22px;
    height: 150px;
}
.detail span{
    margin: 0;
}
.right-arrow {
    padding-top: 0px;
    margin-top: 0px;
    margin-left: 20px;
    width: 10px;
    height: 100%;
    float: right;
    font-weight: bold;
    font-size: 20px;
}

 Open 1st accordion

 Open 2nd accordion

+

Exploring your Motivations to Quit Tobacco

+

What to expect over time.

+

Getting Ready: Strategies to conquer urges & set a quit date

+

Quitting tobacco with medications

+

Dealing with depression or stress

+

Avoiding weight gain or alcohol

+

Making your plan stick: relapse prevention


text:
Q: Continuous random sampling with replacement. Construct a set $s\subseteq[0,1]$ by sampling points in $[0,1]$ with uniform probability density $x\leq1$ so that $|s|=x$. Interpret this as a sampling frame during which data is captured. Now, consider a decreasing function $f(t)$ with domain $[0,1]$. One can calculate the expected integral sum of the observed values of $f(t)$ (where the expectation is over every possible permutation of $s$) as $$\int_0^{1}\!x f(t)\,dt.$$
Now, fix a truncation point $T\in\mathbb{N}$ and construct a new, periodic, function $g(t)$ as follows: $$g(t)=f(t)$$ if $t<1/T$, and $$g(t)=g[t-(1/T)]$$ if $t\geq 1/T$. How can one calculate the expected integral sum of the unique observed values of $g(t)$ given $s\subseteq[0,1]$?
I had thought that one could approach this problem by saying that repeating the first $1/T$ seconds of signal $f$ $T$ times was equivalent to supposing that $s\subseteq[0,1/T]$ with the density of each point in $s$ being $T\min\{x,1/T\}$. The integral would then be
$$\int_0^{1/T}\!T\min\{x,1/T\} f(t)\,dt.$$
Suppose $x=1/T$. The above integral then becomes $$\int_0^{1/T}\!f(t)\,dt,$$ which corresponds to observing $f(t)$ at every point in $[0,1/T]$ with probability 1. This seems counterintuitive because there are many permutations of $s$ (such as $s=[0,1/2T]\cup[1/T,3/2T]$) in which some positive measure of $f(t)$ are observed more than once.


text:
Q: Couchbase CRUD API We're extending the .NET couchbase client to add some additional functionality (something analogous to transactions, or rather rollback) and one of the things on my radar is support for record locking.
I'm aware of check-and-set which would prevent updates without having the CAS value, but what I'm trying to do is prevent dirty reads by using the getlock functionality of couchbase (which is available on the Python client and therefore presumably the server, but not the .NET client)
My first thoughts were that it might be available by the REST API, but after doing some research it looks as though the API can only be used for querying views. I'm aware that memcached has a telnet interface but it's probably too much to hope that it's available there. If it were as simple as just making a call server-side I guess it would already be in the client...
Could use the lease out model but would prefer not to go down that route if the functionality is there just tantalizingly out of reach.

A: Getl support is not currently implemented in the .NET client right now (2/20/13), but it is scheduled to be added soon (http://www.couchbase.com/issues/browse/NCBC-231). One thing to also note is that getl does not prevent other connections from reading, but only prevents other connections from writing to a locked key.
Also, I don't quite understand why you are trying to prevent dirty reads since Couchbase does not allow you to read from replica servers. In other words every read will always return the most recent value in Couchbase.
*Note Couchbase does have a replica read api, but by calling this you are explicitly saying your okay getting an old item.


text:
Q: pyqt print to pdf page breaks I have a python code like this which converts url to pdf
 import sys
from PyQt5 import QtWidgets, QtWebEngineWidgets
from PyQt5.QtCore import QUrl, QTimer, QSizeF
from PyQt5.QtGui import QPageLayout, QPageSize
from PyQt5.QtWidgets import QApplication
import argparse

def _fullScreenRequested(request):
    request.accept()
    loader.showFullScreen()

def main():
    parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("--url", help="Type url")
    args = parser.parse_args()
    config = vars(args)
    url = config['url']

    app = QtWidgets.QApplication(sys.argv)
    loader = QtWebEngineWidgets.QWebEngineView()
    loader.setZoomFactor(1)
    layout = QPageLayout()
    layout.setPageSize(QPageSize(QSizeF(13, 20), QPageSize.Unit.Inch, "4x6 in page", QPageSize.SizeMatchPolicy.ExactMatch))
    layout.setOrientation(QPageLayout.Portrait)
    loader.load(QUrl(url))
    loader.page().pdfPrintingFinished.connect(lambda *args: QApplication.exit())

    def emit_pdf(finished):
        QTimer.singleShot(2000, lambda: loader.page().printToPdf("test.pdf", pageLayout=layout))

    loader.loadFinished.connect(emit_pdf)
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

I want to add page breaks to that pdf using my python code
mainly these two
https://developer.mozilla.org/en-US/docs/Web/CSS/page-break-after
https://developer.mozilla.org/en-US/docs/Web/CSS/break-after
is it possible to add page breaks in my python code ?


text:
Q: Marking a questionnare answer as deleted. Where is the information stored? In forms.office.com we created a form that is backed by an excel spreadsheet.
If I look at the responses and delete one of the responses, the response is gone from the list. However, if I open the excel spreadsheet, the answer is still there. What is unclear to me is, how does it know that the given row in the excel file is "deleted" and should not be visualised anymore? I don't see any additional column with a deletion flag or similar.


text:
Q: Why TabContainer doesnot show?
I had my TabContainer but when I run the TabContainer didn't display .

<asp:TabContainer ID="TC_Article" runat="server" ActiveTabIndex="0" Width="100%"
        Visible="true">
        <asp:TabPanel ID="Add" runat="server">
            <HeaderTemplate>
                Add New</HeaderTemplate>
            <ContentTemplate>

                                <asp:Label ID="lbl_Body" runat="server" Text="Article_Body"></asp:Label>

                                            <cc1:Editor ID="Ed_Body" runat="server"  Height="340px" Width="100%" />

            </ContentTemplate>
        </asp:TabPanel>
    </asp:TabContainer>

I added the Register

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit.HTMLEditor"
TagPrefix="cc1" %>

A: There is problem in Register tag in Namespace and also add script manager in page. Try this.
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>


text:
Q: Maximal inequality for time-continuous martingales: counter-example The following can be regarded as the generalization of the maximal inequality for time-continuous martingales:
Let$ (X_t)_{t \ge 0}$ be a supermartingale with right-continuous sample paths. Then, for any $t > 0$ and every $\lambda > 0$:
$$\lambda \mathbb{P}(\sup_{0 \le s \le t} |X_s| > \lambda) \le \mathbb{E}[|X_0|] + 2\mathbb{E}[|X_t|]$$
The proof relies on the fact that I can use the discrete-time version on $D \cap [0,t]$ where $D$ is some dense, countable subset of $\mathbb{R}_{+}$
with $0, t \in D$. Due to the right-continuity of the sample paths, we then have $\sup_{s \in D \cap [0,t]} |X_s| = \sup_{s \in [0,t]} |X_s|$.
This is clear to me, yet I can't come up with an example of a supermartingale with non-right-continuous sample paths that does not fulfill this maximal inequality.


text:
Q: Spring Boot DataJpaTest unit test reverting to H2 instead of mySql I've got a simple little "hello world" Spring Boot app.  It has a single entity ("IssueReport") and it's configured to run mySQL (instead of the default H2 embedded database).
The app itself runs fine.  I created a mySql database and user, Spring Boot/Hibernate created the table and successfully populates and reads the mySQL data when I run the app.  Life is Good - there are no problems with mySQL and my Spring Boot app itself.
Q: Now how do I use mySQL (instead of the embedded H2) in unit tests?

*

*I created a second, separate mySQL database: test2_test_db.

*I'm using Spring Boot 2.0.6; Eclipse Photon on STS 3.9.6; Ubuntu Linux.

*I created application-test.properties in src/test/resources/:
spring.datasource.url=jdbc:mysql://localhost:3306/test2_test_db
spring.datasource.username=springuser
spring.datasource.password=springuser
spring.jpa.hibernate.ddl-auto=create

*Here's the entire unit test:
package com.hellospring.example;

import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import javax.transaction.Transactional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.hellospring.example.entity.IssueReport;
import com.hellospring.example.repositories.IssueRepository;

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@Transactional
@DataJpaTest
public class IssueRepositoryIntegrationTests {

     @Autowired
     private TestEntityManager entityManager;

     @Autowired
     private IssueRepository issueRepository;

     @Test
     public void addNewIssue() {
         System.out.println("addNewIssue()...");  // <-- This prints in the console
         final String email = "test@test.io";
         List<IssueReport> resultSet = issueRepository.findAll();  // <-- We get an exception in here...
     }
}

*Here's the console error:
2018-10-25 22:20:16.381  INFO 13637 --- [           main] c.v.e.IssueRepositoryIntegrationTests    : The following profiles are active: test
2018-10-25 22:20:16.405  INFO 13637 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@d554c5f: startup date [Thu Oct 25 22:20:16 PDT 2018]; root of context hierarchy
2018-10-25 22:20:17.059  INFO 13637 --- [           main] beddedDataSourceBeanFactoryPostProcessor : Replacing 'dataSource' DataSource bean with embedded version
2018-10-25 22:20:17.060  INFO 13637 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] with [Root bean: class [org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2018-10-25 22:20:17.308  INFO 13637 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Starting embedded database: url='jdbc:h2:mem:979b3ce9-604e-4efd-a6d4-79576c3d67e9;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
2018-10-25 22:20:17.685  INFO 13637 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
  ...  <= I do *NOT* want H2!  I want mySQL!

2018-10-25 22:20:19.315  WARN 13637 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 42102, SQLState: 42S02
2018-10-25 22:20:19.316 ERROR 13637 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Table "ISSUE_REPORT" not found; SQL statement:
  ...  <= Here's the exception from running the test...

Q: What's the EASIEST change so I can run my unit tests with mySQL, just as I'm able to run my Spring Boot app with mySQL?
Q: Is "@DataJpaTest" the best choice here, or should I try a different annotation?
Q: Must I create a separate "Bean" class?  If so, can you point to an example?
================================================================
Thank you for all your replies. Including Simon Martinelli's (now deleted) response.
RESOLUTION:

*

*My original application-test.properties was OK as-is.

*I put it in the wrong place: all application.properties files for any profile should typically go in the same project folder: src/main/resources
<= EXAMPLE: src/main/resources/application-test.properties

*@Transactional wasn't relevant here - I removed it.  I kept it @ActiveProfiles("test").

*Per Karthik R's suggestion, I added @AutoConfigureTestDatabase(replace=Replace.NONE).

*At that point, the test successfully read application-test.properties and used MySQL instead of H2.

*Final annotations:
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@DataJpaTest
@AutoConfigureTestDatabase(replace=Replace.NONE)
public class IssueRepositoryIntegrationTests {

I found this link particularly helpful: Spring Boot – Profile based properties and yaml example
<= I've always found all the material on http://www.mkyong.com extremely good!

A: By default, the @DataJpaTest uses in memory H2 database for repo tests. Should you need to use the actual DB, you can consider either to disable the auto Configurations or use @SpringBootTest where the whole application web mvc is enabled.
To disable auto config:
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@Transactional
@DataJpaTest
@AutoConfigureTestDatabase(replace=Replace.NONE)
public class IssueRepositoryIntegrationTests

@AutoConfigureTestDatabase configures the test H2 DB for you. You can specifically mention not to by above or you can exclude this auto configuration as :
@EnableAutoConfiguration(exclude=AutoConfigureTestDatabase.class)

P.S: : I have not tried the above exclusion myself yet.
For more info on that go thru javadoc: https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabase.html

A: From @DataJpaTest documentation:

By default, tests annotated with @DataJpaTest will use an embedded
  in-memory database (replacing any explicit or usually auto-configured
  DataSource).

If you go to documentation you can see this annotation aggregates a lot of other annotations.
@Transactional annotation behaves in different way in test context than in application context:
From spring documentation:

Annotating a test method with @Transactional causes the test to be run
  within a transaction that is, by default, automatically rolled back
  after completion of the test.

I believe I provided enough information which answering your question, additionaly you can take a look at following articles:
Configuring Separate Spring DataSource for Tests
Testing with @Configuration Classes and Profiles


text:
Q: Python corrupted: how do I clean a failed install or reinstall a fresh instance? I was given wrong advice to install DEEPIN SOFTWARE CENTER on Ubuntu 10.04.3. I learned later that this app was not built for Ubuntu 10.x, but for 11.x.  The developer has not helped at all with any troubleshooting.The person who recommended for me to install it has also been unable to help me resolve the problem, apart from providing a generic apt-get purge < package > command, which didn't work.
Deepin Software Center initially screwed up my installation/updating procedures.  I managed to purge all instances of the Deepin Software Center, from disc, except in Python, which STILL retains information on an unable-to-be completed Deepin install, and tries valiantly every time I update a package, to complete it.
How can I purge this unfinished install information from Python ?  Alternatively, can I simply download a fresh instance of Python, & overwrite the corrupted one ?
If so, please advise on the steps necessary to do this.  I'm happy to reinstall Python, if it clears the residual problem ..
All help most gratefully appreciated

A: I'm trying to do the same thing, because of a similar (I belive) bug. But the reinstall process just doesn't work. Here is my question:
Update Manager won't open (error related to pythonverbose)

A: Since you're not providing error output, or a description in what sense python is broken, it's harder to help you.
The general way to reinstall a package is sudo apt-get install --reinstall python

A: I also faced this problem. My project was using pymongo module in python2 and this pymongo internally uses the abc library. I tried lot of solution and searched a lot but none of the solution worked out.  So I planned to re-installed or remove the python completely from my Ubuntu 16.04 machine.  But sudo apt-get install --reinstall python2.7  command was also failing and was throwing same abc module not found error.  So I finally Did few hacks and cracks. Here are the steps -

Removing all python version manually

*

*sudo rm -rf /usr/bin/python2.x as well as python3.x

*sudo rm -rf /usr/lib/python2.x as well as python3.x

*sudo rm -rf /usr/local/lib/python2.x as well as python 3.x

Updating Ubuntu

*

*sudo apt-get update

In Between if you get this error The package  needs to be reinstalled ubuntu Then  Run following command
sudo vi /var/lib/dpkg/status

And delete all the lines from above file for the package above package_name
Now download a python tgz file from https://www.python.org/downloads/ and unzip it and CD into it
./configure
make test
sudo make install

Python should be installed now.  Check by running python


text:
Q: How to create a month range picker in Angular I came across many similar questions on stackoverflow. But trust me I implement at least ten solutions but I'm not getting correct results and also that most of them are using jquery or javascript while I've to use typescript. I'm creating a simple month range picker with no other rocket science features. After implementing one solution after the other my actual code has become very dirty. So I'm creating a fresh minimal project on stackblitz, here. Also I'm giving my code before making any changes.
My monthpicker.component.html:

    <input  placeholder="{{sampletext}}, {{inputText}}">

      <input type="number" value="2018" min="2018" max="2024" [(ngModel)]="inputText">

        {{ x }}

monthpicker.component.ts
import ...;

@Component({
  ...
})
export class MonthpickerComponent implements OnInit {
  dt = new Date( );
  arr = [
    'Jan', 'Feb', 'Mar', 'Apr',
    'May', 'Jun', 'Jul', 'Aug',
    'Sep', 'Oct', 'Nov', 'Dec'
  ];

  sampletext = ""+this.arr[this.dt.getMonth()];
  inputText :number = this.dt.getFullYear();
  clickCount: number=0;

  n = 4;
  matrix = Array
    .from({ length: Math.ceil(this.arr.length / this.n) }, (_, i) => i)
    .map(i => this.arr.slice(i * this.n, i * this.n + this.n));

  constructor() { }

  onClick(x) {
    this.clickCount++;
    console.log("Month: " + x);
    this.sampletext = x;
    console.log("Year: " + this.inputText);
    console.log("Clicked "+this.clickCount +" times.");
    if(this.clickCount%2==0) {
      this.sampletext+=" " +this.sampletext+", "+this.inputText;
    }
  }

  ngOnInit() {
  }
}

Please suggest a solution.
PS: I don't want to use any third party library. Not even bootstrap. I've to make it from the scratch.

A: You can simply use two select menus or auto completes for selecting month and year. For example you can have a simple code like this:
<form [formGroup]="MonthYearFormGroup">

Select a month here:

  <mat-form-field>
    <mat-label>Month</mat-label>
    <mat-select formControlName="selected_month">
      <mat-option *ngFor="let month of monthList" [value]="month.value">
        {{month.viewValue}}
      </mat-option>
    </mat-select>
  </mat-form-field>

Select a year here:

  <mat-form-field>
    <mat-label>Year</mat-label>
    <mat-select formControlName="selected_year">
      <mat-option *ngFor="let year of yearList" [value]="year.value">
        {{year.viewValue}}
      </mat-option>
    </mat-select>
  </mat-form-field>
  <button (click)="save()">Save Selected Date</button>
</form>

import {Component} from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

export interface MonthYear {
  value: string;
  viewValue: string;
}

@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
  styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample {

  public MonthYearFormGroup: FormGroup();

 yearList: MonthYear[] = Array(50).fill(1).map( (_, index) => { return { value: String(index + 2019), viewValue: String(index + 2019) } })

  monthList: MonthYear[] = [
    {value: '1', viewValue: 'Jan'},
    {value: '2', viewValue: 'Feb'},
    {value: '3', viewValue: 'Mar'},
    {value: '4', viewValue: 'Apr'},
    {value: '5', viewValue: 'May'},
    {value: '6', viewValue: 'Jun'},
    {value: '7', viewValue: 'Jul'},
    {value: '8', viewValue: 'Aug'},
    {value: '9', viewValue: 'Sep'},
    {value: '10', viewValue: 'Oct'},
    {value: '11', viewValue: 'Nov'},
    {value: '12', viewValue: 'Dec'},
  ];

  constructor(
    private _formBuilder: FormBuilder,
  ) { }

  ngOnInit() {
    this.MonthYearFormGroup= this._formBuilder.group({
      selected_month: [{ value: '', required: true }],
      selected_year: [{ value: '', required: true }],
  });

  save() {
   //Your process here...
   console.log(this.MonthYearFormGroup.value.selected_month);
   console.log(this.MonthYearFormGroup.value.selected_year);
  }
}


text:
Q: How can I run function before the process killed? I have a python script. How can I do something before the process will be terminated?
For example I want to print something on display or write to log file.
OS: Windows 11 x64
python version: 3.8.10
I tried this one, but it doesn't work:
import signal
import sys
import time

def handle_iterrupt():
    print("Handling interrupt")
    sys.exit(0)

if __name__ == '__main__':
    signal.signal(signal.SIGTERM, handle_iterrupt)
    for x in range(100):
        print(x)
        time.sleep(1)

Update:
If the process is terminated from the task manager, or cmd is closed, or the process is terminated with taskkill /F /PID {PID}, I want to run some function or write something to a log file.


text:
Q: Adding an object to an arraylist causes the object's fields to become null I have this code:
    blocks.clear();
    if(onStart.parts==null){System.out.println("null before");}
    blocks.add(onStart);
    if(blocks.get(0).parts==null){System.out.println("null after");}

where blocks is an initialized ArrayList<Block>, and parts is a field of Block of type ArrayList<BlockPart>. For some reason, that snippet of code only outputs "null after". Why does the parts field become null?
EDIT: I have added the following code:
    System.out.println(blocks.get(0)==onStart?"same":"not same");
    System.out.println(blocks.get(0).parts==onStart.parts?"same":"not same");

The output is now:
same
not same

Strangely, the null after isn't showing in the console anymore.
EDIT 2: Replacing parts with name causes only null after to show. I don't know why the issue with the parts field somehow fixed itself. Before, I made the parts field final, but then removed the final modifier from it because I thought that I might want to change .parts later on. Now, it fixed itself. IDK why.

A: Your final statement:
System.out.println(blocks.get(0)==onStart?"same":"not same");
System.out.println(blocks.get(0).parts==onStart.parts?"same":"not same");

implies that it's something in your syntax that is changing the way your objects are being accessed.  Break the second one down:
Block newblock=blocks.get(0)

then if newblock == onStart, newblock.parts MUST == onStart.parts
if that proves out then you can delve in to examining why the syntax doesn't chain together well.


text:
Q: MongoDB: is possible to handle a custom deserializer for just one property? I've made some google searches but still I couldn't found nothing.. It's pretty easy to set a custom serializer but how to handle a custom deserialization of just one property of a class?

A: You can achieve this using projections, here is a Slazure example:
First, install the Slazure NuGet package:
PM> Install-Package Slazure.MongoDB

Then run the following C# code example in Visual Studio:
using System;
using System.Linq;
using MongoDB.Bson;
using SysSurge.Slazure.Core.Linq.QueryParser;
using SysSurge.Slazure.MongoDB;
using SysSurge.Slazure.MongoDB.Linq;

namespace ProjectionJsonExample
{
    class Program
    {
        static void CreateDocument()
        {
            // Create a MongoDB document.
            dynamic storage = new DynStorage("mongodb://localhost/ConsoleExample");

            // Get reference to the Employees document collection - it's created if it doesn't already exist
            dynamic employeesCollection = storage.EmployeesColl;

            // Create a document in the Employees collection for John with his email as the document id - the document is created if it doesn't already exist
            var employee = employeesCollection.Document("j.doe@example.org");
            employee.Name = "John Doe";
            employee.Salary = 50000; // John earns $50k/year
            employee.Birthdate = new DateTime(1995, 8, 18); // John was born 08/18/1995

            // Save the document to the MongoDB database
            employee.Save();
        }

        static DynDocument QueryDocument()
        {
            // Build a document query that return employees that has a salary greater than $40k/year using a dynamic LINQ query filter.
            dynamic storage = new QueryableStorage<DynDocument>("mongodb://localhost/ConsoleExample");

            QueryableCollection<DynDocument> employeesCollection = storage.EmployeesColl;
            var employeeQuery = employeesCollection
                // Query for salary greater than $40k and born later than early '95.
                .Where("Salary > 40000 and Birthdate > DateTime(1995, 1, 1)")
                // Projection makes sure that we only return Birthdate and no other properties.
                .Select("new(Birthdate)");

            // Execute the query and return the first document
            return employeeQuery.Cast<DynDocument>().First();
        }

        static void DeleteCollection()
        {
            dynamic storage = new DynStorage("mongodb://localhost/ConsoleExample");

            // Delete EmployeesColl collection if it exists to make sure we start with fresh data
            storage.Delete("EmployeesColl");
        }

        static void Main(string[] args)
        {
            // Delete EmployeesColl collection if it exists to make sure we start with fresh data
            DeleteCollection();

            // Add a employee document to the MongoDB database
            CreateDocument();

            // Get employee
            var employee = QueryDocument();
            var json = employee.GetBsonDocument().ToJson();
            Console.WriteLine(json);

            Console.WriteLine("Press a key to continue...");
            Console.ReadKey();
        }
    }
}

The result from running this tiny example is as follows:
{ "_id" : "79868b41-17d5-4737-b99d-c92e492bb502", "Birthdate" : ISODate("1995-08-17T22.00.00Z") }
Press a key to continue...

As you can see above, even though the document we created had a Name and Salary property these were not retrieved from the MongoDB server due to the projection that we specified with Select("new(Birthdate)") in our code.


text:
Q: Why mini-css-extract-plugin does not creating css file for less? I tried extract-text-webpack-plugin to extract css file, but it failed. The version of webpack is 4.16.3, so I use mini-css-extract-plugin to do that, failed too! I think it is not about the configuration of these plugins. There is my webpack config. the code repo is here. Success packaging,but no css file.
const baseConfig = require('./webpack.config.base')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const merge = require('webpack-merge')
const path = require('path')
const productionConfig = merge(baseConfig, {
  mode: 'production',
  entry: {
    app: path.join(__dirname, '../src/index.js'),
    vendor: ['vue', 'vue-router', 'vuex', 'axios', 'element-ui']
  },
  output: {
    path: path.join(__dirname, '../build/public'),
    filename: 'js/[name].bundle.js',
    chunkFilename: 'js/[name].[chunkhash:8].chunk.js',
    publicPath: './public'
  },
  module: {
    rules: [
      {
        test: /\.css/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader'
        ],
        include: [
          path.resolve(__dirname, 'node_modules')
        ]
      },
      {
        test: /\.less/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'less-loader'
        ],
        include: [
          path.resolve(__dirname, 'node_modules')
        ]
      },
      {
        test: /\.(gif|jpg|jpeg|png|svg)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 1024,
              name: '[name].[hash:8].[ext]',
              publicPath: './public/img',
              outputPath: '/img'
            }
          }
        ]
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'file-loader',
           options: {
              limit: 80000,
              name: '[name].[hash:8].[ext]',
              publicPath: './public/fonts',
              outputPath: '/fonts'
          }
        }
      ]
    },
    optimization: {
      splitChunks: {
        cacheGroups: {
           vendor: {
              test: /[\\/]node_modules[\\/]/,
              name: 'vendor',
              chunks: 'all'
          }
        }
      },
      runtimeChunk: true
    },
    plugins: [
      new MiniCssExtractPlugin({
        filename: '[name].[chunkhash:8].css',
        chunkFilename: '[id].css'
      })
    ]
})
module.exports = productionConfig


text:
Q: MATLAB: adding element of vector until reach to a particular number I get stuck in one question in my textbook. The question is to determine the number of random numbers it takes to add up to 20 (or more).
I use a loop for this situation. I am not sure about my code below.
a=rand(1000,1)
count =1
for(a=rand(1000,1))
   count = count + 1
   sum(a((count),1))
   if sum(a(count),1)>20
       break
   end
end

What I want to do is to add up the elements in that vector until it reaches   20 or more.

A: This option use a low memory
a = rand(1000,1);
Limit = 20;
Acu = 0;
N = 1;
while Acu < Limit
    Acu = Acu + a(N, 1);
    N = N +1;
end
disp(N-1);

A: A straightforward method in MATLAB is to create a random list that is plenty long enough to have a sum much greater than your limit, then run the cumsum function on it to cumulatively sum the vector, and then just select the lowest elements of the original random vector based on the value in the summed vector.
limit = 20;

randnums = rand(1, limit*10);  % Create a sufficiently long vector of random numbers
sumnums = cumsum(randnums);    % Compute the cumulative sum of the random vector
limitedrandnums = randnums(sumnums<=limit);  % Select the values from the random vector based on the sum

disp(limitedrandnums);
disp(sum(limitedrandnums));


text:
Q: Rails changing variable name in for loop I have 5 fields in my Rails app in my Student's table such as food_desc_one, food_desc_two, etc. all the way up to five. I am writing a method in my Student controller which loops over to check the values that are null. I thought the best way to do it would be with a for loop, so I did the following:
for i in 0..5
  if student.food_desc_"#{in_words(i)}" != ''
    . . .
  end
end

where in_words is a helper method I have defined earlier. However, I get the error undefined method 'food_desc_' for #<Student:0x0000000b2e75d8> which I assume is because of me trying to append the number at the end of the variable .. is there another way to accomplish this? Or will I have to check each field seperately? All help is appreciated!

A: try:
student.send("food_desc_#{in_words(i)}")


text:
Q: ASP.NET: Access ListView's DataSource object programatically I have bound my ListView to a database. I've used SqlDataSource to do the work. I want to change the datasource programatically but this is where it all goes wrong. I try to get the current datasource by doing so:
SqlDataSource oldSource = lstContacts.DataSource as SqlDataSource;

Then I want to save the SelectCommand of the SqlDataSource in a string:
string oldSelectCommand = oldSource.SelectCommand;

I am doing this because I want to check if the select statement contains an order by clause and if it does, to take it away and change it with another order by clause :)
However, I am getting this:
"System.NullReferenceException: Object reference not set to an instance of an object."

Anyone? Please (:

A: This happens when you set ListView's DataSourceID in the markup like below:
<asp:ListView ID="ListView1" runat="server"
    DataKeyNames="AccountID" DataSourceID="SqlDataSource1" >

The property DataSource is null if the binding comes by the DataSourceID property.
If you databind the ListView in your code, you can access them until there's any postback.ListView DataSource is not stored in viewstate, so it is lost until you set the datasource and rebind the ListView again.
Workaround:
In the given scenario I would use a hidden field to store Order By clause, and set datasource of the ListView in code:
<asp:HiddenField ID="hdnOrderBy" runat="server" />
    <asp:ListView ID="ListView1" runat="server" DataKeyNames="AccountID">
        ... ... ...

And in the code:
private void BindListView()
{
    string orderBy = hdnOrderBy.Value;
    //Your conditions here
    if (orderBy.Contains("By AccountID"))
    {
        orderBy = " Order By CompanyName";
        hdnOrderBy.Value = orderBy;
    }

    string selectCommand = "SELECT [AccountID], [CompanyName], [CompanyID]  FROM [Account] ";
    SqlDataSource1.SelectCommand = String.Format("{0} {1}",selectCommand,orderBy);
    ListView1.DataSource = SqlDataSource1;
    ListView1.DataBind();
}

Hope it helps!


text:
Q: MS Word - Change footnote/endnote icon to brackets with numbers I'm using Word 2016. I have a Word document that contains multiple endnotes. I don't like the superscript number at all. It is way too hard to see. I want to change it to regular (non-superscript) text and make the symbols [1], [2], [3], and so on (similar to how Wikipedia does reference links). Is this possible?

A: You can accomplished as followed.

*

*Press Ctrl+H to open the Find and Replace dialog box.

*Put your cursor in the Find what box.

*Click More, click Format, then Font. Select Superscript.

*On the Replace by box, enter: [^&].

*Click Format, then Font. Remove Superscript and Subscript from the selection.

*Click Format, then Styles. Select Normal.

The Find and Replace dialog box will look like this:

*Click replace all.


text:
Q: How to seperate  and  HTML tags Here is my footer:

© 2022 Moonlight™ All rights reserved.

Terms

Privacy Policy

My problem is, is that it shows like this: "© 2022 Moonlight™ All rights reserved.TermsPrivacy Policy" on our website. How can I add a " " between the
 and . And I did try putting a space in the

A: Any time you use
 your elements will have a break and create a second line. What I would do is use
 to wrap your links. However, you can still use
 and create the layout you are trying to achieve. You will want to put this code into your stylesheet (.css) in the
Try this:
footer.center a,footer.center p
{
display: inline-block;
vertical-align:top;
margin: 0 5px;
}

A:   is also and alternative to

A: The p tag is a block elememt. You are wrapped the block element with a anchor element. if you would like to have:

*

*© 2022 Moonlight™ All rights reserved.

*Terms

*Privacy Policy
You can replace the first p tag with a span and

            © 2022 Moonlight™ All rights reserved.

                Terms

                Privacy Policy

A: You can use   code to add " " to somewhere.


text:
Q: Error with plotting bar graph with multiple colors I am trying to plot a simple bar graph with 8 bars, all the even bars in one color, all the odd bars in a different color. Below is what I've done:
info = [mean1 mean2 mean3 mean4 mean5 mean6 mean7 nean8];
sky_blue = [86, 180, 233] / 256;
orange = [230, 159, 0] / 256

for d=1:length(info)
plot_bar(d)=bar(info(1,d), 'BarWidth', 0.5);
    if mod(d,2)==0
       set(plot_bar(d),'FaceColor', sky_blue);
    else
       set(plot_bar(d),'FaceColor', orange);
    end
hold on;
end

For some reason, the bars are stacked vertically, one on top of the other. Could anyone tell me how to seperate the bars horizontally?
Also, how would I go about make a legend which will indicate sky_blue color as the control group and orange as the medicated group? Thanks!

A: that has a quick solution!
In each of the iteration, you are ploting anew bar plot without spedifiying its X coordinate, therefore all of them are ploted in X=1
Change yout code to (note the only change in bar() function) :
info = [mean1 mean2 mean3 mean4 mean5 mean6 mean7 nean8];
sky_blue = [86, 180, 233] / 256;
orange = [230, 159, 0] / 256

for d=1:length(info)
plot_bar(d)=bar(d,info(1,d), 'BarWidth', 0.5);
    if mod(d,2)==0
       set(plot_bar(d),'FaceColor', sky_blue);
    else
       set(plot_bar(d),'FaceColor', orange);
    end
hold on;
end

Output:

NOTE: you may probably want to use XtickLabel to label your plots, it seems it doesnt take it very well this method

A: You can do it without loops: all orange bars in one go, then all sky-blue bars in one go. Note the aditional division by 2 in 'BarWidth'.
info = [mean1 mean2 mean3 mean4 mean5 mean6 mean7 nean8];
sky_blue = [86, 180, 233] / 256;
orange = [230, 159, 0] / 256

bar(1:2:numel(info), info(1:2:end), 'BarWidth', 0.5/2, 'Facecolor', orange);
hold on
bar(2:2:numel(info), info(2:2:end), 'BarWidth', 0.5/2, 'Facecolor', sky_blue);


text:
Q: PHP array_shift_recursive() I'm trying to do an equivalent to array_shift_recursive() and apparently my google ans SO search fails me.:
Take the following multi-dimension array continaing strings:
$array = [
   'shift6th'    => [
      'shift3rd' => [
         'shift1st', //string
         'shift2nd', //string
      ],
      'shift4rd', //string
      'shitf5th', //string
   ],
   'shift11th' => [
      'shift10th', //string
      'shift9th' => [
         'shift7th', //string
         'shift8th', //string
      ],
   ],
   'shift12th', //string
];

The point is to return and remove the end element in a recursive way since the array can have many (theatrically unlimited) dimensions. I've named the string and keys in the order i figured i needed to shift.

I have tried to replicate a function but it aint working because array_shift is returning the element and not the array it makes it difficult to recurse the dimension with an function. This doesn't work and keeps returning me shift1st (that i expect) but the array stays the same and is not shifted.

function array_shift_recursive(array $array) {
  // recurse 1st child if it's array
  if( !empty($array) && is_array(reset($array)) ){

    return array_shift_recursive(reset($array));
  }
  //shift element from current array.
  else{
    return array_shift($array);
  }
}

I know it must be something about reference. Knowing how reference works i still have to learn how and when to exploit it. this said, little reminder that array_shift(&$array); argument is natively passed by reference.
I found a way to make it happening by switching the value to false and then filter the array for empty element (that false is evaluated as) but this seems (is to me way too much) long and inefficient. read below if you like but the point is to avoid doing that ;)
function array_filter_recursive(array $array, $filter = null) {
  foreach( $array as &$v ){
    if( !empty($v) && is_array($v) ){
      $v = array_filter_recursive($v, $filter);
    }
  }
  return array_filter($array, $filter);
}

function isnot_empty(&$v) {
  if( !empty($v) ){
    return true;
  }
  return false;
}

function turn_false(array $array = []) {
    foreach( $array as $k => &$v ){
      if( !empty($v) && is_array($v) ){
        $array[ $k ] = turn_false($v);
        break;
      }
      else{
        $array[ $k ] = false;
        break;
      }
    }
    return $array;
  }

and then i can do
//This for now gives me the element i'm looking for as expected
$shifted=array_shift_recursive($array);

/** @TODO : get rid of this to remove the shifted element. */

//Replicate the top dimension path with a empty end element.
$empty=turn_false($array);

//Replace the array'S dimension with the empty dimension path
$replaced=array_replace_recursive($array,$empty);

//Remove the empty element (as a bonus it also strip empty array left behind after removing the element)
$array=array_filter_recursive($replaced,'isnot_empty');

/* OR (how i use it to combine those 3 lines in (kind of) one)
$array = array_filter_recursive(
   array_replace_recursive(
      $array, turn_false($array)
   ), 'isnot_empty'
);
 */

A: i'm using the same logic than before except i use a foreach loop instead of reset to get the 1st element in the array. Reset only point the marker back and return the element at the pointer so i guess it was again making a copy.
If you want to skip ahead the empty dimension you can use array_filter to filter out the empty elements before rerunning the function.
Thanks to the commentators for the head up.
Consireding this input :
$array = [
   'abc' => [
      'def',
      'ghi' => [
         'jkl', 'mno'
      ],
   ],
   'pqr' => [
      'stu', 'vwx'
   ],
   'yz1',
   '234' => [ '456' => [ '789' ] ]
];

using this function :
function array_shift_recursive(array &$array) {
  foreach( $array as &$v ){
    if( (!empty($v) && is_array($v) ) ){
      return array_shift_recursive($v);
    }
    else{
      return array_shift($array);
    }
  }
}

we get the expected result seen with :
var_dump(array_shift_recursive($array)); //string(3) "def"
var_dump(array_shift_recursive($array)); //string(3) "jkl"
var_dump(array_shift_recursive($array)); //string(3) "mno"
var_dump(array_shift_recursive($array)); //array(0) { } //dimension 'ghi'
var_dump(array_shift_recursive($array)); //array(0) { } //dimension 'abc'
var_dump(array_shift_recursive($array)); //string(3) "stu"
var_dump(array_shift_recursive($array)); //string(3) "vwx"
var_dump(array_shift_recursive($array)); //array(0) { } //dimension 'pqr'
var_dump(array_shift_recursive($array)); //string(3) "yz1"
var_dump(array_shift_recursive($array)); //string(3) "789"
var_dump(array_shift_recursive($array)); //array(0) { } //dimension '456'
var_dump(array_shift_recursive($array)); //array(0) { } //dimension '234'
var_dump(array_shift_recursive($array)); //NULL // Array is empty (yay!)


text:
Q: What is the difference between "security.oauth2.resource" and "security.oauth2.client"? I created a spring boot app and using oauth2 for authenticating. I find this tutorial, it works but I am not sure for what are the mentioned properties used to.
https://medium.com/@bcarunmail/securing-rest-api-using-keycloak-and-spring-oauth2-6ddf3a1efcc2
And here is my properties file:
rest.security.issuer-uri=http://localhost:8180/auth/realms/dev
security.oauth2.resource.id=employee-service
security.oauth2.resource.token-info-uri=${rest.security.issuer-uri}/protocol/openid-connect/token/introspect
security.oauth2.resource.user-info-uri=${rest.security.issuer-uri}/protocol/openid-connect/userinfo
security.oauth2.resource.jwt.key-value=-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtLXaZjNl+vVB58mjJUkNH4noJieFAWn8ny+ONkqD4Y/EDrx+6pEZynZjNxNcOylI9KU2YqiFVzbVJLsQ35+qWaxO1f0w3XLTnzZ78mV1fLRK8oOX5IpLdQip+VuuUvcwGGs9UfnCEhLc/Tq+AuRxuvT3xIBHAMG/P1ZlhAww9A6hqyYiLy5YBrrZQeFCqYKT/hCpoebeR8M0/iAjOaJ7+qV44Mp6xtYN0f8Xk5jy2k4fbXBgr/1yqsUDJjJuOeJDSRSPwu18NeR70ldbB0lLcpW15d7GTkGLTCTDUia9JbxRuI7tXX93md3LxEpJq224qKxiPTY/7cyxx/AKbEEnywIDAQAB-----END PUBLIC KEY-----

security.oauth2.client.client-id=employee-service
security.oauth2.client.client-secret=b0ea9376-778a-4dc9-b400-90118f32958c
security.oauth2.client.user-authorization-uri=${rest.security.issuer-uri}/protocol/openid-connect/auth
security.oauth2.client.access-token-uri=${rest.security.issuer-uri}/protocol/openid-connect/token
security.oauth2.client.scope=openid
security.oauth2.client.grant-type=client_credentials

(Don't worry about the secret, this keycloak runs on my localhost just for testing purposes)
What is the "client" used for?
And what is the "resource" used for?
Thanks in advance.

A: OAuth 2 is an authorization method to provide access to protected resources over the HTTP protocol.
OAuth defines four roles –

*

*Resource Owner - The user of the application.

*Client – the application (user is using) which require access to user data on the resource server.

*Resource Server – store user's data and http services which can return user data to authenticated clients.

*Authorization Server – responsible for authenticating user's identity and gives an authorization token. This token is accepted by resource server and validate your identity.

The properties/configuration listed above is the parameter to define/list these entities together.


text:
Q: Why this move constructor is not called wtih rvalue temporary? I have this piece of code. I was expecting d3 to be created with move constructor as well, as I passed a rvalue temporary.
#include <iostream>

using namespace std;

struct Data {
    Data(): x(1)
    {
        cout << "constructor" << endl;
    }

    Data(const Data& original): x(2)
    {
        cout << "copy constructor" << endl;
    }

    Data(Data&& original): x(3)
    {
        cout << "move constructor" << endl;
    }

    int x;
};

int main() {
    Data d1; // constructor
    cout << "d1:" << d1.x << endl << endl;

    Data d2(d1); // copy constructor
    cout << "d2:" << d2.x << endl << endl;

    Data d3(Data{}); // move constructor?
    cout << "d3:" << d3.x << endl << endl;

    Data d4(move(Data{})); // move constructor?
    cout << "d4:" << d4.x << endl << endl;

    return 0;
}

I saw output as:
constructor
d1:1

copy constructor
d2:2

constructor
d3:1

constructor
move constructor
d4:3

Although d4 is constructed with move constructor as I expected, I don't understand why d3.x got value 1. It seems d3 is constructed by the default constructor?


text:
Q: Webpack url-loader dynamic public path I'm using webpack's url-loader plugin and have it configured like this:
module.exports = {
    entry: './src/admin.planningview.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: 'http://poc.local/dist/'
    },
    module: {
        rules: [
            {
                test: /\.(png|woff|woff2|eot|ttf|svg)$/,
                loader: 'url-loader?limit=100000'
            }
        ]
    }
};

Inside my base.css there is the following line:
@font-face {
    font-family: 'open_sansregular';
    src: url('fonts/opensans-regular-webfont.eot');
    src: url('fonts/opensans-regular-webfont.eot?#iefix') format('embedded-opentype'), url('fonts/opensans-regular-webfont.woff') format('woff'), url('fonts/opensans-regular-webfont.ttf') format('truetype'), url('fonts/opensans-regular-webfont.svg#open_sansregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

This files are located in the sub folder 'fonts'.
My dist folder looks like this:

Now I'm trying to load all these files based on a dynamic publicPath variable (so overriding the http://poc.local/dist/ url) for the chunks and assets.
I added this is my entry point file:
__webpack_public_path__ = window.cdnURL;

The window.cdnURL contains something like : http://cdn.local/dist/
Now my problem is the chunks are being loaded properly but the fonts / woff files are not.. This seems to be something with the url-loader I think.
When I check the bundle.js in debug mode I see the following, it's the old URL:

Any idea's?

A: As far as my understanding goes, the file-loader (fallback for url-loader) will stringify the path at build time.
In order to use dynamic data, you need to use postTransformPublicPath:
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        loader: 'file-loader',
        options: {
          publicPath: '/some/path/',
          // add the following. This could remove/replace "http://poc.local/dist/"
          // you would have to write JS code as a string.
          postTransformPublicPath: (p) => `__webpack_public_path__ + ${p}`,
        },
      },
    ],
  },
};

A: Use the css-loader alias option:
https://github.com/webpack-contrib/css-loader#alias


text:
Q: Side-by-side barplot with line plot overlay in R Ok, I have data in a dataframe, would like to take two variables y1 and y2 and create a side-by-side barplot comparison in which bar height is equal to the value of each element in y1 and y2. Then I want to superimpose a line with the ratio of the two variables, with a second y-axis for these values. My specific problem is that I cannot scale the second y axis appropriately (so in my example reduced the ratio so that it would fall in graph).
More generally, I have a poor understanding of how barcharts work in base graphics and feel like I had to hack my way through it - in spite of reading the multiple posts on this, and a number of tutorials which mostly don't go into enough detail. Some things I am not clear about; A. What is the best way to go from data in a df to data suitable for a barchart - do the data have to be transposed into a barchart matrix as I do here, and why? B. What determines the x-axis placement of the bars (ie what is the "myplot" object and how do the values get determined? Is there a way to set x locations of my points/lines more elegantly? I had to force it using somewhat ugly coding because I don't really understand how it works. C. Not sure about how I would go from row names in my df if I had any, to category (x-axis) names in my bar chart. I sort of had to force this in my plot parameters. D. Is there a definitive discussion about barcharts somewhere that goes into depth a bit more on the inner workings of the bar chart?
rm(list = ls(all = TRUE))
df <- data.frame(y1 = runif(10, min=0, max=1), y2 = runif(10, min=1, max=2))
df$ratio <- df$y2/df$y1
df

barmatrix <- t(df[,1:2])
barmatrix

par(mfrow = c(1,1))
myplot <- barplot(barmatrix, main="My Barchart", ylab = "Values", ylim = c(0,3), cex.lab = 1.5, cex.main = 1.4, beside=TRUE, names.arg=c("0","1","2","3","4","5","6","7","8","9"))
lines(x = myplot[1, ] + 0.5, y = df$ratio/3)
points(x = myplot[1, ] + 0.5, y = df$ratio/3)
axis(4, ylim = c(0, 20))

A: you can scale down by 10 to fit on the plot, then scale the numbers (that is, the labels) on your added axis.
par(mfrow = c(1,1))
myplot <- barplot(barmatrix, main="My Barchart", ylab = "Values", ylim = c(0,3), cex.lab = 1.5, cex.main = 1.4, beside=TRUE, names.arg=c("0","1","2","3","4","5","6","7","8","9"))
lines(x = myplot[1, ] + 0.5, y = df$ratio/10)
points(x = myplot[1, ] + 0.5, y = df$ratio/10)
axis(4, at=0:6/2,labels=0:6*5)

Update:
to dynamically scale
rm(list = ls(all = TRUE))
df <- data.frame(y1 = runif(10, min=0, max=1), y2 = runif(10, min=1, max=2))
df$ratio <- df$y2/df$y1
df

barmatrix <- t(df[,1:2])
barmatrix

sf <- max(pretty(df$ratio/3)) # scale factor
# divide by 3 since that is your limit on the barplot ylim
sf

par(mfrow = c(1,1))
myplot <- barplot(barmatrix, main="My Barchart", ylab = "Values", ylim = c(0,3), cex.lab = 1.5, cex.main = 1.4, beside=TRUE, names.arg=c("0","1","2","3","4","5","6","7","8","9"))
lines(x = myplot[1, ] + 0.5, y = df$ratio/sf)
points(x = myplot[1, ] + 0.5, y = df$ratio/sf)
axis(4, at=0:3,labels=0:3*sf)

Update 2: To answer more of your question.
Each row of your matrix myplot has the x positions for each series. You can find the average for each column to more flexibly find the midpoint for multiple series.
You can also label with the row.names directly.
And with type="o" you can plot lines and points at one go.
rm(list = ls(all = TRUE))
df <- data.frame(y1 = runif(10, min=0, max=1), y2 = runif(10, min=1, max=2))
df$ratio <- df$y2/df$y1

row.names(df) <- LETTERS[1:10]
df
barmatrix <- t(df[,1:2])
barmatrix

sf <- max(pretty(df$ratio/3)) # scale factor
# divide by 3 since that is your limit on the barplot ylim
sf

par(mfrow = c(1,1))
myplot <- barplot(barmatrix, main="My Barchart", ylab = "Values", ylim = c(0,3),
   cex.lab = 1.5, cex.main = 1.4, beside=TRUE, names.arg=row.names(df))
lines(x = colSums(myplot)/nrow(myplot), y = df$ratio/sf,type="o")

axis(4, at=0:3,labels=0:3*sf)


text:
Q: 404 on reload with vue-router and Ingress-Nginx I have a single web page application in Vue.js which has 3 menus.
Using the vue-router the url changes from / to :

*

*/users

*/groups

*/teams
When on any of thoses pages if I hit ctrl + R I'll get a 404.
What I have
This is my original Ingress:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri
    nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth
  name: my-ing-oauth2-proxy
spec:
  ingressClassName: nginx
  rules:
  - host: myhost.com
    http:
      paths:
      - backend:
          service:
            name: myservice
            port:
              number: 8080
        path: /
        pathType: Prefix

This produces 404 on /users etc
What I have tried
I tried multiple annotations

*

*rewrite-target

*app-root

*use-regex
Each time aiming to redirect all routes toward /. All failed with white pages, 404 etc.

What kind of works but isn't perfect...
In the end I made a second ingress which deals with the routes I mentionned and then redirects the user to /.
It's working but there are 2 issues with this :

*

*I now have two ingresses (even more as I use oauth2-proxy...)

*I have to hardcode the path as I can't find a way to match all routes

*

*

*Using a regex like /.+ isn't working

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri
    nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth
    nginx.ingress.kubernetes.io/permanent-redirect: https://myhost.com  # <= here
    nginx.ingress.kubernetes.io/use-regex: "true"
  name: my-ing-oauth2-proxy-routes
spec:
  ingressClassName: nginx
  rules:
  - host: myhost.com
    http:
      paths:
      - backend:
          service:
            name: myservice
            port:
              number: 8080
        path: /groups
        pathType: Prefix
      - backend:
          service:
            name: myservice
            port:
              number: 8080
        path: /teams
        pathType: Prefix
      - backend:
          service:
            name: myservice
            port:
              number: 8080
        path: /users
        pathType: Prefix

What I would like
I would like all routes (/*) to redirect to / using one ingress.
If it's not possible at least find a way to have the second ingress to match all possible routes instead of hardcoding them. We only have three but it's still a very bad solution.
Using

*

*nginx : 2.4.1

*ingress-nginx helm chart : nginx-ingress-0.15.1

*Kubernetes : 1.24.3

Thx


text:
Q: How on OS X to programmatically force initial adjustment the size of image in an ImageWell, as ImageWell changes size due to LayoutConstraints NSWindow
  NSImageWell - with constraint to all four side of the Window's containerView
    NSImage - is put in Well via NSPageControl

Using the mouse, I resize the Window and the ImageWell expands or contracts with the Window as desire.
The image in the Well remains the same size regardless of Window size.
The image does resize correctly, based on the size change of Window, if I drag the image a bit with the mouse.
How and where do I send a message to get this size to change "automatically" ?
Do I need to monitor size changes in the Window using Notifications?
Sorry, I was not clear. I want the image in the image well to maintain its
aspect ratio and to resize itself each time the Window is resized. Currently, when the window is resized, the user sees no change in the size of the image. He can however, cause the image to resize correctly by click dragging on the image or Window content view. I want the user to see this
resizing take place immediately, without needing to use the mouse. For example of an image that has an aspect ratio of 4/3. if the window is 4" x 4" , then when the image is added, it appears as 4" by 3". If the window goes to 8" x 8", then the image should automatically go to 8" x 6".
Guilherme was good enough to send me his demo NSView app. If, like in his app, I set an image in IB, my app also successfully resizes not only the ImageView but also the Image itself.
The problem appears to be because I put the images into the ImageView via an NSPageController. The only way to get the image to resize is to do a two finger drag inside the window.contentView
After Resizing window:
New Image Appears

Then following a two-finger drag on image :
<https://www.dropbox.com/s/d2he6bdzxbeefok/Screen%20Shot%202015-09-12%20at%2013.26.50.png?dl=0>

Below is relevant code:
AppDelegate follows:
#import "AppDelegate.h"
#import "MyImageView.h"

@interface AppDelegate ()
@property (strong, nonatomic) IBOutlet NSWindow *window;
@property (strong, nonatomic) IBOutlet NSPageController *pageController;
@property (strong, nonatomic) IBOutlet MyImageView *imageView;
@property (weak) IBOutlet NSTextField *infoLabel;
@property NSArray *imageArray;
@end

@implementation AppDelegate

#pragma mark Window delegate

- (void)windowDidResize:(NSNotification *)notification{
    //[_window layoutIfNeeded];
    //[_imageView doSelfLayout];
}

- (void)awakeFromNib {
    [_window setDelegate:self];
    [_imageView setTranslatesAutoresizingMaskIntoConstraints:NO];
    _imageArray = @[ [NSImage imageNamed:@"eggplant.png"],
                     [NSImage imageNamed:@"sandwich.png"],
                     [NSImage imageNamed:@"yoghurt.png"]];

    [_pageController setDelegate:self];
    [_pageController setArrangedObjects:_imageArray];
    [_pageController setTransitionStyle:NSPageControllerTransitionStyleStackBook];

    // Set info label's text
    NSString *info = [NSString stringWithFormat:@"Image %ld/%ld", ([_pageController selectedIndex]+1), [_imageArray count]];
    [_infoLabel setStringValue:info];
}

#pragma mark Page Controller delegate methods:

- (void)pageController:(NSPageController *)pageController didTransitionToObject:(id)object {
    /* When image is changed, update info label's text */
    NSString *info = [NSString stringWithFormat:@"Image %ld/%ld", ([_pageController selectedIndex]+1), [_imageArray count]];
    [_infoLabel setStringValue:info];
    //[_window layoutIfNeeded];
}

- (NSString *)pageController:(NSPageController *)pageController identifierForObject:(id)object {
    NSString *identifier = [[NSNumber numberWithInteger:[_imageArray indexOfObject:object]] stringValue];
    return identifier;
}

- (NSViewController *)pageController:(NSPageController *)pageController viewControllerForIdentifier:(NSString *)identifier {
    /* Create new view controller and image view */
    NSViewController *vController = [NSViewController new];
    NSImageView *iView = [[NSImageView alloc] initWithFrame:[_imageView frame]];
    [iView setImage:(NSImage *)[_imageArray objectAtIndex:[identifier integerValue]]];
    [iView setImageFrameStyle:NSImageFrameNone];

    /* Add image view to view controller and return view controller */
    [vController setView:iView];
    return vController;
}
@end

A: What option have you selected for the scaling property in IB?

Here's a sample project, the image resizes automatically with Proportionally Up or Down selected.

A: I have made a demo Cocoa project zipfile below that has what I was looking for, namely an OS X app that :
- uses NSPageController in History mode to display an array of images (Portrait and Landscape) in a resizeable window
- imageView maintains imagefile aspect ratio as it automatically resizes
- images list can be traversed using a PreviousButton and a NextButton, or using a touch pad, with a two-finger swipe.

https://www.dropbox.com/s/7qgmg5dr1bxosqq/PageController3%203.zip?dl=0
It is pretty basic stuff, but I post it with the hope it can same someone else some time. Mark


text:
Q: How is this derivation possible in a context-free grammar? Suppose we have the rules:
$R \rightarrow XRX | S$
$S \rightarrow aTb | bTa$
$T \rightarrow XTX | X | \epsilon$
$X \rightarrow a | b$.
My textbook says that $T \stackrel{*}\implies T$ is possible. Could this be a mistake because I am almost certain this cannot be. Or else I must not be understanding correctly.
Start with $T$. We have three choices
$T \implies XTX$. But now that we have $X$ involved, we will have $a's$ and/or $b's$ involved.
$T \implies X$. Again we will have $a$ or $b$ involved.
$T \implies \epsilon$. But $\epsilon \not= T$.
This is exercise 2.3 (i) in Michael Sipser's Theory of Computation 3rd edition (not homework)

A: I think this is notation problem:

*

*The star in $X\stackrel{*}\Longrightarrow Y$ denotes zero or more steps. In other words $T \stackrel{*}\Longrightarrow T$ is true, because relation $\stackrel{*}\Longrightarrow$ is reflexive. You can think about it a bit like $\leq$ relation (depending on the grammar it might actually be a non-strict partial order).

*On the other hand, $X\stackrel{+}\Longrightarrow Y$ denotes one or more steps and in result $T\stackrel{+}\Longrightarrow T$ is in your case false. You can think of it a bit like the strict version $<$ (depending on the grammar it might actually be a strict partial order).

I hope this helps $\ddot\smile$


text:
Q: Job runs randomly in Hangfire I have wrote cron expression which should run the method on after every 5 minutes but it runs continuously after random interval.
Here is my code
 public partial class Startup
{
    HomeController home = new HomeController();
    public void Configuration(IAppBuilder app)
    {
        GlobalConfiguration.Configuration.UseSqlServerStorage("HangFireCon");
        app.UseHangfireDashboard();
        //app.UseHangfire(config=> {

        //    config.UseServer(1)

        //});
        var options = new BackgroundJobServerOptions { WorkerCount = 1 };
        RecurringJob.AddOrUpdate("UAERR284SSSSSS" + System.DateTime.Now.ToString("yyMMddHHmmss"),() => home.GenerateFile(), "0 */5 * ? * *");
        app.UseHangfireServer(options);
    }
}

A: According to crontab.guru you may try
*/5 * * * *

for your CRON expression


text:
Q: Seaborn countplot show wrong results on Titanic dataset I'm working on the Titanic dataset which I've got it from this website:
https://public.opendatasoft.com/explore/dataset/titanic-passengers/table/?flg=fr
I want to show the number of male and female persons for each survived class (yes or no).
First of all I got the whole number of male and female persons using:
bysex=data1['Sex'].value_counts()
print(bysex)

This gave me these results:
male      577
female    314
Name: Sex, dtype: int64

The results show that the number of male persons is greater than female persons.
But when I use seaborn to show the number of male and female persons for each survived class using this code:
plot1 = sns.FacetGrid(data1, col='Survived')
plot1.map(sns.countplot,'Sex')

Then I get this results:
enter image description here
Here it shows that the number of female is greater than the number of male and for no survived class the number of female (around 450) is even greater than the total number of female persons (314).
How is this possible?

A: I think there is something wrong with the mapping.
In the left plot Sex are interchanged.
data1.loc[data1["Survived"] == "No", 'Sex'].value_counts()
male      468
female     81
Name: Sex, dtype: int64

and the second plot is right.
data1.loc[data1["Survived"] == "Yes", 'Sex'].value_counts()
female    233
male      109
Name: Sex, dtype: int64

On the other hand when you use
ax = sns.countplot(x="Survived", hue="Sex", data=data1)

you get the right results.


text:
Q: How to assure security for a video streaming using Lighttpd? I need to stream a video which is present on server say xyz.com. If I access the correct path of the video everyone is able to see that video. What I need to do is that create a MD5sum corresponding to the every particular video which has an unique video id.
So that from now onwards if the user is accessing the video as before ie :
it should not load for the below.

http:/xyz.com/video.mp4

It should load only for the following url

http:/xyz.com/video.mp4?md5=202cb962ac59075b964b07152d234b70

Any suggestions?

A: I think you would be better using a scripting language such as php for this. However if you are adamant on doing it inside of lighttpd you can do this with mod_magnet using lua.
http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs:ModMagnet

A: Lighttpd also offers a module called "SECDownload", it is very easy to install. It enables you to make a url available for a limited time.
Tutorial is here:
http://redmine.lighttpd.net/projects/1/wiki/Docs_ModSecDownload
This only creates a temporary link, the url is not limited to a IP. If one url is created, every user may access it (at least if you don't do anything to prevent this).


text:
Q: QLineEdit Focus Event I have two widget mainwindow123 and second-class. In my MainWidget.cpp have one lineedit and button field. Initially I can set the focus on the line edit. But after come from the second.cpp Widget then I could not set the focus on the lineedit. Please help me.. Which place I did the mistake? Thanks in advance.
This is my code
MainWidget.cpp
MainWidget::MainWidget(QWidget *parent) :
        QWidget(parent),
        ui(new Ui::MainWidget)
    {
        ui->setupUi(this);
        s = new second();
        connect(ui->pushButton, SIGNAL(clicked()),this,SLOT(callSecond()));

    }

    MainWidget::~MainWidget()
    {
        delete ui;
    }
    void MainWidget::callSecond()
    {
       s->show();

     }

second.cpp
second::second(QWidget *parent) :
    QWidget(parent)
{
    QPushButton *first = new QPushButton("first");
    first->setStyleSheet(
         "background-color:black;"

    );
    QGridLayout *d = new QGridLayout();

    d->addWidget(frist,0,0,1,1);
    setLayout(d);
    connect(first,SIGNAL(clicked()),this,SLOT(first()));
}

void second:: first()
{
    this->hide();
}

A: It's because your focus goes to button after you clicked it. You could achieve it by:

*

*Setting a focusProxy http://doc.qt.io/qt-4.8/qwidget.html#setFocusProxy

*Disabling strong focus on button: http://doc.qt.io/qt-4.8/qwidget.html#focusPolicy-prop

*Connecting buttons clicked signal to setFocus slot of your QLineEdit