text:
Q: $\frac{\sin(z)}{z}$ Bounded on $\mathbb{C}-\{0\}$? Is $\frac{\sin(z)}{z}$ bounded on $\mathbb{C}-\{0\}$?
Based on real analysis intuition it is, and even though complex $\sin$ is not bounded the $\frac{1}{z}$ makes me think it is.

A: Consider the values that this function takes on the imaginary axis.
We have that
$$
\sin z = \frac{e^{iz} - e^{-iz}}{2i},
$$
and so if $z=ix$, where $x \in \mathbb R$,
then
$$
\sin ix = \frac{e^{-x}-e^x}{2i}.
$$
So we see that
$$
\left \vert
\frac{\sin ix}{ix}
\right \vert
=\left \vert
\frac{e^{-x} - e^x}{2x}
\right \vert
\to \infty,
$$
as $x \to \pm \infty$.

A: Notice that it does have a limit at $z=0$. This means it has a removable singularity there.
If it were bounded on $\mathbb{C}\setminus\{0\}$ it would be bounded everywhere. This is because it is also bounded near $z=0$.
Since it is holomorphic everywhere (notice at $z=0$, since it has a limit, it has a removable singularity), then by Liouville's theorem it would be constant.
But it is not, because if it were then $\sin(z)=Cz$, for some constant $C$. But you know that $\sin$ vanishes in ($z=\pi k, k\in\mathbb{Z}$) more places than $Cz$ so they can't be equal.

A: No, it is not bounded. Since this function is analytic in its domain. if it is bounded then it would be constant by Liouvill's Theorem but function is no constant.


text:
Q: How can I test a field for a specific character in SQL How do I determine if a SQL Server 2012 field contains a specific character or string without using fulltext commands using a select?

A: You could use the CHARINDEX() function if you just wanted to see if the string or character exists in the input rather than selecting the whole row:
DECLARE @string VARCHAR(50)
SET @string = 'string to search'

SELECT CHARINDEX('to',@string)

This code would return 8 (the start position of the string you searched for), if you searched for something that didn't exist, it would return 0, so you could determine if a string existed by looking for a return integer greater than 0.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaFX WebView throwing an Exception I am using JavaFX WebView as a "chat container", for messages.
Everytime a new message comes up, I call:
engine.executeScript("window.scrollTo(0, document.body.scrollHeight);");

(I also have an if-check, so I don't execute the line if the user has scrolled up)
However, this line appears to cause an exception every time that the scrollbar isn't visible, because the scrollbar is apparently lazily initialized.
java.lang.NullPointerException
    at com.sun.javafx.webkit.theme.ScrollBarThemeImpl.getThumb(ScrollBarThemeImpl.java:400)
    at com.sun.javafx.webkit.theme.ScrollBarThemeImpl.thumbPosition(ScrollBarThemeImpl.java:284)
    at com.sun.javafx.webkit.theme.ScrollBarThemeImpl.getThumbPosition(ScrollBarThemeImpl.java:380)
    at com.sun.webkit.WebPage.twkExecuteScript(Native Method)
    at com.sun.webkit.WebPage.executeScript(WebPage.java:1427)
    at javafx.scene.web.WebEngine.executeScript(WebEngine.java:948)

I tried to add another if-check in JavaScript: document.body.scrollHeight > document.body.clientHeight; but it didn't fix the issue.
Anyone have ideas how to get rid of the exception (besides filing a bug report :)?

A: Short answer
if (scene != null
    && scene.getWindow() != null
        && scene.getWindow().isShowing()) {
  engine.executeScript("window.scrollTo(0, document.body.scrollHeight);");
}

Long(er) answer
It fails because the WebView's ScrollBar's skin has not been set. To avoid that,

*

*the WebView must be attached to a Scene

*the Scene must be attached to a Window

*the Window must have been displayed at least once

OR, more specific:

*

*the WebView must be attached to a Scene

*WebView.applyCss() must have been called

There is a bug report which unfortunately has been closed unfixed.
I submitted a new bug report (because it's not possible to comment on existing ones -.-) and sent them an example to reproduce it.


text:
Q: Z_p flatness and irreducible components. I just used the following.
Lemma. Let $A$ be a $\mathbb{Z}_p$-flat ring, of finite type over $\mathbb{Z}_p$, and suppose that $A \otimes \mathbb{F}_p$ is a domain. Then $A$ is a domain.
Proof: Suppose $ab = 0$ in $A$. Then one of $a, b$ must lie in $pA$, so we can write (without loss of generality) $a = p a_1$. Then by flatness $a_1 b=0$.
Continuing in this manner, we find that one of $a$ and $b$ must be infinitely divisible by $p$. But the finite type hypothesis implies that this is impossible unless one of $a$ or $b$ is in fact zero.
Given the statement, it seems like there should be a more conceptual reason why this should be true. Can anyone supply one? (A proof using more general facts in EGA counts as conceptual).
Edit: Kevin Buzzard gives a compelling reason why I have never seen this "fact" used before. Thank you both for your answers.
Edit 2: I suppose that replacing "finite type" with "p in the radical" would work (with an application of the Krull intersection theorem). In particular, the result is true as stated for a local $\mathbb{Z}_p$-algebra.

A: Your proof seems wrong to me. I might be misunderstanding some things you wrote, but surely $\mathbf{Q}{}_p=\mathbf{Z}_p[X]/(pX-1)$ is finite type over $\mathbf{Z}_p$, and contains many elements which are infinitely divisible by $p$. Again if I've understood your definitions correctly, $\mathbf{Q}{}_p\times\mathbf{Z}_p$ is a counterexample to your assertion.

A: With assumptions of finite type, the relevant notion is purity (N.B. proper implies pure). Let me explain briefly.
Put $R=\mathbb{Z}_p$. Then one says that a flat finite type $R$-scheme $X$ is pure if the closure of any associated point of the generic fibre of $X$ meets the special fibre. If $X$ has reduced fibres, this essentially means that the valuative criterion of properness is satisfied at generic points of the generic fibre : thus the relation with irreducible components is quite clear.
Let us see what happens in the affine case. In the proof of your lemma, what you need is your ring $A$ to be separated for the $p$-adic topology, so that an element $a$ lying in the intersection of the ideals $(p^n)$ is $0$. Now a deep theorem of Raynaud and Gruson says that (in the particular case of a d.v.r. base ring) the following three conditions are equivalent :

*

*$A$ is separated for the $p$-adic topology

*$A$ is free as an $R$-module

*$X=Spec(A)$ is pure over $R$.

The notion of purity exists over a general base, and you can prove the following kind of statement : for a morphism of schemes $X\rightarrow S$ which is of finite presentation, flat and pure, the locus of points of $S$ where the geometric fibre is integral is open. See my paper "Effective models of group schemes", especially theorem 2.2.1 (on arxiv or on my webpage for most recent version).


text:
Q: Accessing "form" property of a form ElementRef shows TypeScript error I have this form in my template:
<form #heroForm="ngForm" (ngSubmit)="onSubmit()">

And I'm adding it as a ViewChild in the controller:
@ViewChild('heroForm') heroForm: ElementRef;

When I access the "form" property of it to see if it is valid, it shows a TypeScript error "Property 'form' does not exist on type 'ElementRef'.
".
if(this.heroForm.form.valid){
  this.submitted = true;
}

How can I get rid of this error?
Stackblitz example: https://stackblitz.com/edit/template-driven-form-demo-1tbb37?file=app%2Fuser-form%2Fuser-form.component.ts

A: Simply import ngForm directive
import {NgForm} from '@angular/forms';

change your form declaration
@ViewChild('heroForm', { read: NgForm }) heroForm: any;

change you form validation condition
if(this.heroForm.valid){
    this.submitted = true;
}

A: The ElementRef does not contain any property called form. However, the #heroForm that you have created is of type NgForm and it contains the form property.
You get the error because of the ts compilation. It cannot find a property named form in ElementRef and gives you error. At runtime, since its javascript, you dont get error and the code works fine.
To get rid of the error, you can read the property as NgForm, as given in @Boobalan's answer OR you can simply convert the type of the heroform to any instead of ElementRef.
Use @ViewChild('heroForm') heroForm: any;
instead of @ViewChild('heroForm') heroForm: ElementRef;

A: Though Boobalan's answer is right, just to stick with typed check, you can avoid any and simply use type NgForm like:
@ViewChild('heroForm') heroForm: NgForm;

if (heroForm.valid){
 ...
}

A: Read nativeElement property in ElementRef and in this invocation having some security vulnerabilities [1]. Try the below method.
this.heroForm.nativeElement
[1] https://angular.io/api/core/ElementRef


text:
Q: Split rows into multiple rows PL/SQL Is there an easy way to split the value of a row into multiple rows? For example, let's say I have the following table
Item       Date       Quantity   Type
2001    7/1/2014     5000        5
2001    7/6/2014     1000        1
2002    7/20/2014     3000     1
2003    7/1/2014     2000        5
2004    8/3/2014     4000        4
What I'm looking to do is take those items that are either type 4 or 5, take their quantities, divide said quantities by the type (e.g., 5000/5) and distribute the result evenly across the next n weeks, depending on the type (i.e., 5 weeks for type 5 and 4 weeks for type 4). Lastly, take that split result and add it to any other results in that week.
For example, we have 6000 of item 2001 for the month of July. Each week would have 1000 quantity of item 2001, except for the week starting 7/6 where there would be 2000.
Here is the output I'm seeking
The output would look something like this
Item       Date       Quantity
2001    7/1/2014     1000
2001    7/6/2014     2000 (1000 from the split and 1000 from Type 1 in the table above)
2001    7/13/2014     1000
2001    7/20/2014     1000
2001    7/27/2014     1000
I'm not really sure to employ. I suspect a subquery with a loop would be a start.

A: This one comes pretty close, but the split goes back exactly 7,14,21,28 days. In your example, 7/6/14 gets 1000 from 7/1/14, which the statement below wouldn't provide, since the split of 7/1/2014 goes to 7/8/2014, 7/15/2014 etc. Maybe this was just a little oversight in your question; otherwise, the query needs a bit more work to better match the dates.
create table sales (item number(4), sdate date, quantity number, stype number(1));

with dategenerator as (select to_date('1.1.2014')+(rownum-1) sdate from dual connect by rownum<=365),
prodlist as (select distinct item from sales),
salessplitted as (
select prodlist.item, dategenerator.sdate,
   (select nvl(sum(quantity),0) from sales where sdate=dategenerator.sdate and item=prodlist.item and stype=1)+
   (select nvl(sum(quantity/4),0) from sales where sdate in (dategenerator.sdate,dategenerator.sdate-7,dategenerator.sdate-14,dategenerator.sdate-21) and item=prodlist.item and stype=4)+
   (select nvl(sum(quantity/5),0) from sales where sdate in (dategenerator.sdate,dategenerator.sdate-7,dategenerator.sdate-14,dategenerator.sdate-21,dategenerator.sdate-28) and item=prodlist.item and stype=5) total
  from dategenerator, prodlist )
select item, sdate, total from salessplitted where total>0
order by item, sdate;


text:
Q: Meaning of "hit somewhere" In some song (it was like summer party song), they say:

We'll hit the beach, yeah, we'll hit the beach.

What's the meaning of hit in those sentence?

A: The verb hit in that context is a colloquial expression that means "visit".

I'll be there in a minute. I have to hit the john.
We are going to Paris and plan to hit the Louvre.

If used enthusiastically, it still has the same basic meaning but can connote extra energy; it might be paraphrased as "to storm onto" or "to run out onto".

They pulled into the seaside parking lot. It had been a very long ride. The boys hopped out of the car and yelled "Let's hit the beach!".

A: I like this definition, which is found at the end of a very long list on the Wordnik page:

hit (v.) reach a destination, either real or abstract

This is why a singer might say:

We'll hit the beach, yeah, we'll hit the beach

while a project manager might say:

We think we'll hit the first milestone next month.


text:
Q: ts-checker-webpack-plugin no puede encontrar una regla personalizada de tslint escrita en TypeScript Tengo un proyecto de TypeScript con Webpack con los siguiente en package.json
"ts-checker-webpack-plugin": "^0.3.0",
"tslint": "^5.9.1",
"typescript": "^2.8.3",

También tengo un regla personalizada de tslint hecha en TypeScript que es compilada por tsc durante la compilación de webpack pero tslint no puede encontrar el JS resultante. Muestra el siguiente error:
Could not find implementations for the following rules specified in the configuration:
    custom-check
Ya confirmé que si compilo manualmente customCheckRule.ts a JS, la regla es encontrada y usada por webpack y tslint.
¿Como puedo configurar webpack o ts-checker-webpack-plugin para asegurarme que la regla es compilada y usada durante el proceso de compilación?
Lo siguiente es la parte relevante de webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
...

module.exports = {
    ...,

    resolve: {
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    plugins: [
        ...,
        new TsCheckerWebpackPlugin({
            tsconfig: path.resolve("tsconfig.json"),
            tslint: path.resolve("tslint.json"), // optional
            memoryLimit: 512, // optional, maximum memory usage in MB
            diagnosticFormatter: "ts-loader", // optional, one of "ts-loader", "stylish", "codeframe"
        })
    ],

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            {
                test: /\.tsx?$/,
                use: [{
                    loader: 'babel-loader'
                }, {
                    loader: 'ts-loader',
                    options: {
                        transpileOnly: true
                    }
                }]
            },
            ...
        ]
    }
};


text:
Q: SVG Stripe Animation с изогнутыми формами Я пытаюсь анимировать этот svg, чтобы получить анимацию криволинейных полос, как на изображении ниже:
Изображение:
Это то, что у меня есть на данный момент:

<svg width="300" height="300" viewBox="0 0 120 120">
    <pattern id="diagonalHatch" width="30" height="10"
     patternTransform="rotate(30)" patternUnits="userSpaceOnUse">
         <animate attributeName="x" from="0%" to="100%" dur="5s" repeatCount="indefinite"/>
         <rect width="100%" height="100%" fill="#FB5D2E"></rect>
         <line x1="5" x2="5" y2="10" style="stroke:#16B4F2; stroke-width:10" />
         <line x1="15" x2="15" y2="10" style="stroke:#19214D; stroke-width:10" />
    </pattern>
    <path d="M20,31 C15.4189994,27.2225585 12.5023327,24.2225585 11.25,22 C10.2743515,20.6156479 10,19.6181623 10,18.1428571 C10,15.5113854 12.4883456,13 15,13 C17.3176009,13 18.9621484,13.8491346 20,15.5714286 C21.0382977,13.8491346 22.6828452,13 25,13 C27.5116544,13 30,15.5113854 30,18.1428571 C30,19.6181623 29.7256485,20.6156479 28.75,22 C27.497816,24.2225585 24.5811493,27.2225585 20,31 Z" stroke="none" fill="url(#diagonalHatch)" stroke-width="10"/>
</svg>

Однако я хочу, чтобы формы вместо прямых линий были изогнуты как на изображении

Свободный перевод вопроса SVG Stripe Animation with curved shapes от участника  @Oleksiy Chornobay.

A: Здесь я заменил две линии эллипсами. Это была моя первоначальная идея, но получить хорошую кривую и равное расстояние между цветами непросто. Как видите, оранжевого немного больше, чем двух других цветов.

<svg width="300" height="300" viewBox="0 0 120 120">
    <pattern id="diagonalHatch" width="20" height="50" y="-15"
     patternTransform="rotate(30)" patternUnits="userSpaceOnUse">
         <animate attributeName="x" from="0%" to="100%" dur="5s" repeatCount="indefinite"/>
         <rect width="100%" height="100%" fill="#FB5D2E"></rect>
         <ellipse cx="0" cy="25" rx="15" ry="20" stroke="#19214D" fill="transparent" stroke-width="6"/>
         <ellipse cx="0" cy="25" rx="9" ry="15" stroke="#16B4F2" fill="transparent" stroke-width="6"/>
    </pattern>
    <path d="M20,31 C15.4189994,27.2225585 12.5023327,24.2225585 11.25,22 C10.2743515,20.6156479 10,19.6181623 10,18.1428571 C10,15.5113854 12.4883456,13 15,13 C17.3176009,13 18.9621484,13.8491346 20,15.5714286 C21.0382977,13.8491346 22.6828452,13 25,13 C27.5116544,13 30,15.5113854 30,18.1428571 C30,19.6181623 29.7256485,20.6156479 28.75,22 C27.497816,24.2225585 24.5811493,27.2225585 20,31 Z" stroke="none" fill="url(#diagonalHatch)" stroke-width="10"/>
</svg>

Свободный перевод  ответа от участника  @chrwahl.


text:
Q: Angular - Navigate to current same URL with component reload not the whole page I am using Angular 5 library, I want to navigate to the current URL with reload (refresh) the whole component, not the page, I have read about navigation to current URL in Angular document.
And that it is what I need:
 /**
 * Define what the router should do if it receives a navigation request to the current URL.
 * By default, the router will ignore this navigation. However, this prevents features such
 * as a "refresh" button. Use this option to configure the behavior when navigating to the
 * current URL. Default is 'ignore'.
 */
onSameUrlNavigation: 'reload' | 'ignore';

Now, I have tried to set the onSameUrlNavigation property to reload and then navigate to the same URL, but nothing happend, like this:
this.router.onSameUrlNavigation = 'reload';
this.router.navigate(['view'], { queryParams: { QueryUUID: selectedId } });

Anyone who has used this before can help?

A: I have found this workaround method since the onSameUrlNavigation property in Angular 5.1 is not what I need.
I just need to override shouldReuseRoute, so added an exception for the component route that I want to refresh, if the current and future route are equal view.

And also I can navigate to other routes without problems, even for navigate from Angular Material sidenav.

this.router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot) {
  if (future.url.toString() === 'view' && curr.url.toString() === future.url.toString()) {
    return false;
  }
  return (future.routeConfig === curr.routeConfig);
};

Update:
For those they want to use the new onSameUrlNavigation property in Angular 5.1 you can refer to this blog:
https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

A: If I understand you correctly, this is how I do it:
ngOnInit(): void {
    this.route.params.subscribe(
        params => {
            const id = +params['id'];
            this.getMovie(id);
        }
    );
}

Or to watch query parameters:
ngOnInit(): void {
    this.route.queryParams.subscribe(param => {
        this.pageTitle = 'Movie List';
        this.getMovies();
    });
}

In the ngOnInit, I watch for changes to the parameters. When the parameters change, I re-retrieve the data.
Since the data is all bound, the page "refreshes" with the newly retrieved data.

A: In route module:
add below in each route declaration
runGuardsAndResolvers: 'always'

and
@ngModule({
 imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
 exports: [RouterModule],
 })

for e.g category/:id
and this below part will be under Component
ngOnInit() {
    this.activeRoute.queryParams.subscribe(queryParams => {
        // do something with the query params
    });
        this.activeRoute.params.subscribe(routeParams => {
        this.loadUserDetail(routeParams.id);
    });
}

for each route change say for e.g category/11 and category/12 it will call loadUserDetail function everytime.
So without refreshing page you will fetch data from server and update dom for same route with different roureParams.

A: In terms of rel-loading the entire page, the normal Reload Page tag works just fine for me. I tried using the "onSameUrlNavigation" function, but it was not reloading the entire page the way I want.

A: You can use the angular router events for this purpose.
import { takeUntil, filter } from "rxjs/operators";
import { Router, NavigationEnd } from "@angular/router";

this.router.events.pipe(
      filter((event): event is NavigationEnd => event instanceof NavigationEnd),
      takeUntil(this._unsubscribeAll),
).subscribe(() => {
      this.cache = {};
      this.cachedRows = [];
      this.getRollingJobs(this.page);
});


text:
Q: How to ensure that a Target in an msbuild file only gets called once? We've got a MsBuild.proj file which contains the following section (simplified):
<Target Name="WEB" DependsOnTargets="CleanResults;UpdateAssemblyInfo;Services;Business">

    <!-- Other build and release stuff -->
            <MSBuild Projects="$(CreateInstallValuesScriptProjectFile)" Properties="DatabaseStructureLocation=$(DatabaseDirectory)\Sandbox\002.Structure" />
        </Target>

Basically, the InstallValuesScript generates a .sql file in our databasedirectory, which will update the version of our application in the database. Fairly simple.
The build is called as such:
MSBuild msbuild.proj /m /t:WEB /p:Configuration=Release;DoRelease=true;DoSandBox=false;DoWix=false /fileLoggerParameters:LogFile=msbuild.log;Verbosity=normal;Encoding=UTF-8

However, what we're seeing is that the InstallValues section is called multiple times, and as a result this file is created a couple of times, and on different locations... Obviously when the build is compiled two or three times instead of only once, thats annoying but not really critical (just goes a bit slower), however for this Installvalues file, we really don't want multiple instances of it.
So what gives, can a target be called multiple times? Maybe caused by the compiling of a dependant assembly? Some light on this strange phenomenom would be highly appreciated.

A: In general, unless EDIT: even if you <CallTask>, MSBuild won't run a Target multiple times within a given top-level invocation of a build, even if you have duplicates in dependencies (the order matters, but once its done, its done).
Do you perhaps have some nesting of calls to project files which chain in some complex manner?
But The Truth is in the Logs [that you seem to be creating so assiduously!]


text:
Q: Discrete math three fundamental principles Suppose that there are 15 identical copies of The Great Gastby and 12 distinct biographies on a bookshelf.
(a) How many different selections of 12 books are possible?
(b) How many different selections of 10 books are possible?
I figured out (a)
$ 2 ^{12} = 4096$
But I'm stuck on b.
I tried $ 2^{10} = 1024$ but thats not the answer.

A: In order to find the ways of picking books, you're counting the number of ways to pick $k$ biographies at a time, as the other books are identical. So, in the first case this is
$$
\sum_{k=0}^{12}{12\choose k}=2^{12}=4096
$$
In the second case, it isn't possible to pick $12$ or $11$ of the biographies, so we subtract these choices off:
$$
4096-{12\choose 12}-{12\choose 11}=4096-1-12=4083
$$
Which is the answer in the second case.


text:
Q: Random Variable $X$ and $Y$ has a joint probability density function. Find $f_{X | Y}(x | y)$ Random Variable X and Y has a joint probability density function.
$$f_{X, Y} (x, y) =\begin{cases}
c(x + 3y)& 5 \leq x \leq y, 6 \leq y \leq10\\
0 & \text{otherwise }\\
\end{cases}
$$
(a) Find $f_{X | Y}(x | y)$
(b) $P(x \leq 5 | Y = 9)$

My attempt:
$f_{X | Y}(x | y) = \frac{f_{X, Y}(x, y)}{f_Y(y)}$
$$f_Y(y) = c\int_{5}^{y}(x+3y)dx = c/2 (-25 - 30 y + 7 y^2)$$
for $f_Y(y)$ has support $6 \leq y \leq 10$, 0 otherwise
$$f_{X | Y}(x | y) = \frac{0.5c(x+3y)}{(-25 - 30 y + 7 y^2)}$$
$f_{X | Y}(x | y)$ has support the same as the joint probability function
(b)
$f_{X | Y}(x | y = 9) = \frac{x+27}{272}$
$$P(x \leq 5 | Y = 9) = \int_{5}^{?} f_{X | Y}(x | y = 9)dx = $$
Not sure

A: (a) Everything is done okay, save that the final answer should be $$f_{X\mid Y}(x\mid y)=\dfrac{2(x+3y)}{7y^2-30y-25}\mathbf 1_{5\leqslant x\leqslant y, 6\leqslant y\leqslant 10}$$

(b) Whatever value of $Y$, the support for $X$ indicates that it is impossible to have $X\leqslant 5$.  $$\mathsf P(X{\leqslant}5\mid Y{=}9)=0$$


text:
Q: TOTAL HOURS CALCULATION I have a table of times Attancdence from where I want to generate the report to display Total Time Group by User and Day.
INPUT TABLE
0 = IN TIME
1 = OUT TIME

USERID CHECK TIME CHECK TYPE
1396 2022-05-30 08:40:47 0
1396 2022-05-30 09:21:40 1

OUTPUT REQUIRED
USERID TOTAL TIME
1396 5


text:
Q: Can't compile android cocos2d file --Android-Studio Getting some error even for sample cocos2d helloworld file.
Android NDK: android-13 is unsupported. Using minimum supported version android-14.
[armeabi] Compile++ thumb: cocos2dxandroid_static <= ProcessCpuTracker.cpp
/home/user/Documents/cocos2d-x-3.15.1/game/cocos2d/cocos/platform/android/jni/ProcessCpuTracker.cpp: In function 'std::vector<_CpuInfo> readProcStat()':
/home/user/Documents/cocos2d-x-3.15.1/game/cocos2d/cocos/platform/android/jni/ProcessCpuTracker.cpp:69:54: error: 'read' was not declared in this scope
     const int len = read(fd, buffer, sizeof(buffer)-1);
                                                      ^
/home/user/Documents/cocos2d-x-3.15.1/game/cocos2d/cocos/platform/android/jni/ProcessCpuTracker.cpp:70:13: error: 'close' was not declared in this scope
     close(fd);

how to solve?

A:
Android NDK: android-13 is unsupported. Using minimum supported
  version android-14.

Add APP_PLATFORM := android-14 in Application.mk file
If you do not have that line then version of your SDK is taken from project.properties files.

#include <unistd.h> header is missing in ProcessCpuTracker.cpp file for NDK v15
check this answer for more detail.


text:
Q: SQL multiple rows calculate I have a table in SQL Server and I am trying to calculate if a number is bigger than a selected row, but only if the rows that exist are greater than 1.
I've looked online and looked into Union, Intersect and Exist but cannot see a way to do it and of course I may have to program the calculation in C++ but would rather do it in SQL as it will be faster.
The example is as follows: the table lists a number of horse races and data (needs to sorted by date and time in the selection):
Date        Time        Course      OF  Win
-------------------------------------------
2018-10-16  15:45:00    Huntingdon  5   LC
2018-10-16  15:45:00    Huntingdon  3   W
2018-10-16  16:10:00    Punchtown   1   LC
2018-10-16  16:10:00    Punchtown   2   W
2018-10-16  16:20:00    Huntingdon  3   LC
2018-10-16  16:20:00    Huntingdon  2   W
2018-10-16  16:30:00    Hereford    5   W
2018-10-16  16:30:00    Hereford    4   LC
2018-10-16  16:45:00    Punchtown   3   W

In the above data I wouldn't be interested in the last record as only one for that date and time exists. From the other four races I would like to calculate how many races that have a 'W', have a 'OF' value greater than the 'LC' line.  The output would count how many races have this condition.
A further complication is there may be more than two records for that date and time. I've looked at this for two days now without success so just before I do program it I thought I'd ask.
SG

A: Something like this (I did not test it):
--Outer query will join the subquery. Needed to figure out the win
select time, course, of, win
from table t1
inner join
   -- subquery to get the last OF for each time, course.
   (select time, course, max(OF) maxof
    from table t2
    group by time, course) as t2
on t1.time = t2.time, t1.course = t2.course, t1.of = t2.maxof
where win = 'lc' -- If there's only a win, this will show nothing.

A: Based on your sample data, the following should do the trick...
IF OBJECT_ID('tempdb..#TestData', 'U') IS NULL
BEGIN   -- DROP TABLE #TestData;
    CREATE TABLE #TestData (
        [Date] DATE NOT NULL,
        [Time] TIME(0) NOT NULL,
        Course VARCHAR(20) NOT NULL,
        [OF] INT NOT NULL,
        Win CHAR(2) NOT NULL
        );

    INSERT #TestData (Date, Time, Course, [OF], Win)
    VALUES
    ('2018-10-16', '15:45:00', 'Huntingdon', 5, 'LC'),
    ('2018-10-16', '15:45:00', 'Huntingdon', 3, 'W'),
    ('2018-10-16', '16:10:00', 'Punchtown ', 1, 'LC'),
    ('2018-10-16', '16:10:00', 'Punchtown ', 2, 'W'),
    ('2018-10-16', '16:20:00', 'Huntingdon', 3, 'LC'),
    ('2018-10-16', '16:20:00', 'Huntingdon', 2, 'W'),
    ('2018-10-16', '16:30:00', 'Hereford  ', 5, 'W'),
    ('2018-10-16', '16:30:00', 'Hereford  ', 4, 'LC'),
    ('2018-10-16', '16:45:00', 'Punchtown ', 3, 'W')
END;

--========================================================

WITH
    cte_LagVal AS (
        SELECT
            td.Date,
            td.Time,
            td.Course,
            td.[OF],
            td.Win,
            LC_OF = LAG(td.[OF], 1) OVER (PARTITION BY td.Date, td.Time, td.Course ORDER BY td.Win)
        FROM
            #TestData td
        )
SELECT
    lv.Date,
    lv.Time,
    lv.Course,
    lv.[OF],
    lv.Win,
    lv.LC_OF
FROM
    cte_LagVal lv
WHERE
    lv.LC_OF IS NOT NULL;


text:
Q: iPhone 4 screen resolution (code-wise)? I had an epiphany just now.
In some places in my very first iPhone app I have hardcoded values referring to the screen width and/or height (320, 460).
now I realize that i never noticed this because in the iPhone 4 simulator i dont notice any drawing issues.
So does this mean the iPhone 4 internally converts 320 to be whatever the width for its screen resolution? i doubt it. But then again, why would i be seeing everything appearing to be fine when i run?
Example:
If I make a ball draw at position (320, 100) I can clearly see that it is drawing at the far right edge of the screen.
What is going on here?

A: No it does not adapt the screen it's standard 320 for the iphone. It actually adapts the simulator to the mac screen makes it bigger.  And about the ball 320 is from left to right 0---320, and the 460 is from up to down  0----460. sow putting the ball at 320,100 should place it in the fa right.


text:
Q: WordPress installation error "access denied" I am installing WordPress on my Localhost but i am not redirecting to my WordPress installation. I am using xampp server and WordPress version 4.0.
It shows access denied in browser when i try to open my WordPress installation.

A: Go To Xampp > PhpMyAdmin > and edit Config.inc.php with your favorite editor.
It will look like the below code , just change the $cfg['Servers'][$i]['password'] = 'Password'; to $cfg['Servers'][$i][''] = ''; and hit save.
        $cfg['Servers'][$i]['verbose'] = 'localhost';
        $cfg['Servers'][$i]['host'] = 'localhost';
        $cfg['Servers'][$i]['port'] = '';
        $cfg['Servers'][$i]['socket'] = '';
        $cfg['Servers'][$i]['connect_type'] = 'tcp';
        $cfg['Servers'][$i]['extension'] = 'mysqli';
        $cfg['Servers'][$i]['auth_type'] = 'config';
        $cfg['Servers'][$i]['user'] = 'root';
        $cfg['Servers'][$i]['password'] = 'PasswordWillBeHere';
        $cfg['Servers'][$i]['AllowNoPassword'] = false;


text:
Q: Strip span from h1 in Python (Beautiful soup) I'm unable to delete the span from the H1 - I need just the H1 text without the text within the span:
page = requests.get("https://www.bbc.co.uk/weather/524901")
soup = BeautifulSoup(page.content, 'html.parser')
weather_desc_today = soup.find(class_="wr-day__weather-type-description").get_text()
weather_location = soup.find('h1').text
print (weather_location)

Outputs:
Moscow - Weather warnings issued

When I need just 'Moscow'
Here's the HTML:

Moscow - Weather warnings issued

A: You can use find.
weather_location = soup.find('h1').find(text=True)

OUT: Moscow


text:
Q: How can I prevent someone from gaining root access through the bootloader? On Ubuntu 10.10 I can login as root without the root password by replacing ro quiet splash with rw init=/bin/bash. How can I secure my machine and disable this backdoor?

A: You need to secure several things, as leaving any of these open introduces a door (it's not really a backdoor since it's all well documented) of similar impact. (Exception: if at step 1 you can physically secure the console as well, then you don't need to do anything else.)

*

*Physically secure the computer. You must prevent attackers from disconnecting the disk from the computer and connecting it to another computer that they control, and from resetting the firmware access control.

*Protect the boot process in computer's BIOS (or other boot firmware) with a password (or other form of access control). Make sure the internal hard disk is the only selected boot medium, so as to prevent attackers from booting from a live CD, USB or other media. Of course, lock access to the BIOS as well, so that the attacker can't change that setting.

*Protect the bootloader so that booting anything but the default command line requires providing a password.

Steps 1 and 2 are about your hardware and not about the operating system, so if you have trouble with them, ask on Super User. For step 3, what to do depends on your bootloader (which you haven't indicated). The default bootloader on Ubuntu is Grub 2.
First, generate a password hash with grub-mkpasswd-pbkdf2.
Next, declare a user and password by creating an executable (mod 755 or 700) file called /etc/grub.d/01_users (it matters that the file beings with 01) with these contents (where grub.pbkdf2.….DEADBEEF is what grub-mkpasswd-pbkdf2 produced):
#!/bin/sh -e
## Declare users and passwords
cat <<EOF
set superusers="torayeff"
password_pbkdf2 torayeff grub.pbkdf2.sha512.10000.DEADBEEF
EOF

Only authenticated superusers may edit menu entries or enter a command line. Other users may only boot prepared entries.
If you want to also restrict some boot entries to authenticated user, replace menuentry "name" by menuentry "name" --users "user1 user2" in the place where they are generated. The entries for your Linux installation, memtest86 and any other OS you may have on that machine are in /etc/grub.d/10_linux, /etc/grub.d/20_memtest86+ and /etc/grub.d/30_os-prober respectively.
When you've made changes in /etc/grub.d, run sudo update-grub before rebooting.


text:
Q: Onmouseenter/Onmouseleave fadeOut wont work When hovering the .f_bb div, it should simply show up .f_bloc and add a class to it. When the hovering is over (when the cursor is out of it), it should fade out and hide. But I can't make it work, for some reason.
HTML

test

roat

CSS
.test {color: red}
.f_bloc {display: none}

JS
$(document).ready(function() {
    $("#fc3 .f_bb").onmouseenter(function() {
        $(this).closest(".f_bloc").show();
        $(this).closest(".f_bloc").addClass("test");
    });
});

$(document).ready(function() {
    $("#fc3 .f_bb").onmouseleave(function() {
        $(this).closest(".f_bloc").fadeOut( 1000, function() {
            $(this).closest(".f_bloc").hide();
        });
    });
});

Jsfiddle : https://jsfiddle.net/ebcm08tL/
UPDATED https://jsfiddle.net/ebcm08tL/2/

A: A good way to do it is to unbind any existing events (can assign names) first to avoid duplications:
    $("#fc3 .f_bb").unbind('mouseenter.fc3').on('mouseenter.fc3', function (event) {
        // mouseenter actions
    });

    $("#fc3 .f_bb").unbind('mouseleave.fc3').bind('mouseleave.fc3', function (event) {
        // mouseleave actions
    });

A: jQuery uses .mouseenter() and .mouseleave(), not .onmouseenter() and .onmouseleave().

A: The problem is that you used .closest() method. With .children() method works fine to me, and you also have to include jquery if you didn't.

$(document).ready(function() {
$("#fc3 .f_bb").mouseover(function() {
  $(this).children(".f_bloc").show();
  $(this).children(".f_bloc").addClass("test");
 });
});

$(document).ready(function() {
$("#fc3 .f_bb").mouseleave(function() {
  $(this).children(".f_bloc").fadeOut( 1000, function() {
  $(this).children(".f_bloc").hide();
  });
 });
});
.test {color: red}
.f_bloc {display: none}

test

roat

A: Try adding an id to your div which contains roat text and try using children() instead of closest() as the div you are trying to find is actually children.
Working demo

$(document).ready(function() {
  $("#fc3 .f_bb").mouseenter(function() {

    $(this).children("#block").show();
    $(this).children("#block").addClass("test");
  });

  $("#fc3 .f_bb").mouseleave(function() {
    $(this).children("#block").fadeOut(1000, function() {
      $(this).children("#block").hide();
    });
  });
});
.test {
  color: red
}
.f_bloc {
  display: none
}

test

roat

A: I think thath your problem is with closest(), i use find() to find The class you want

$(document).ready(function() {
  $("#fc3 .f_bb").mouseenter(function() {
    var f_bloc = $(this).children(".f_bloc");
    f_bloc.show();
    f_bloc.addClass('test');

  });
  $("#fc3 .f_bb").mouseleave(function() {
    var f_bloc = $(this).children(".f_bloc");
    f_bloc.fadeOut( 1000, function() {
      f_bloc.hide();
    });
  });
});
.test {color: red}
.f_bloc {display: none  }

    test

 roat


text:
Q: How to set message label using Weborb(Producer) and MSMQ I`m adding a message in MSMQ by my flex program using this code:
            producer = new Producer();
            producer.destination = "VendingMachineBack";
            var m:AsyncMessage = new AsyncMessage("",{'MSMQLabel':"VS-GetSaleTypes"}) ;
            producer.send(m);

and my weborb messaging-config.xml it`s the following:
<destination channels="weborb-rtmp" id="VendingMachineBack">
    <properties>
      <msmq>
        <path>.\private$\ClassicBackEndQueue</path>
        <deliverPastMessages>-1</deliverPastMessages>
        <BasePriority>0</BasePriority>
        <Category>00000000-0000-0000-0000-000000000000</Category>
        <MaximumQueueSize>4294967295</MaximumQueueSize>
        <UseJournalQueue>false</UseJournalQueue>
        <MaximumJournalSize>4294967295</MaximumJournalSize>
      </msmq>
    <message-service-handler>Weborb.Messaging.PubSub.Msmq.MessagingServiceHandler</message-service-handler>
    </properties>
    <channels>
        <channel ref="weborb-rtmp"/>
    </channels>
</destination>

The thing is, how can I set the message label in the AsyncMessage that I`m sending?

A: I think this document will help you. It looks like you are missing the label reference entirely.
http://www.themidnightcoders.com/products/weborb-for-net/developer-den/technicalarticles/msmq-data-push.html

A: I found the solution after while! there is no why to set a message label using webOrb, so I just migrate to FluorineFX: http://www.fluorinefx.com/
and then I did it: http://www.fluorinefx.com/docs/fluorine/messagingmsmq.html


text:
Q: Creating a drag and drop with rangy When I inspect my code it has the draggable attribute but the onDragStart is missing in the browser.
 rangy.createClassApplier(foo, {
        normalize: true,
        elementTagName: 'mark',
        elementProperties: {
          draggable: 'true',
          onDragStart: drag(event),
        },
    elementAttributes: {
     id: `drag${id}`,
    }
  }

On inspection this is what I see:
<mark id="drag2" draggable='true'>
here is some more
</mark>

what am I missing?


text:
Q: Dúvida com arquivos excel Tenho uma lista de datas em um arquivo BTH.cvs excel. Quero copiar todo o arquivo para outro novo.cvs, porém o a.exe para de funcionar.
#include <stdio.h>
#include <stdlib.h>

int main(int argc,char **argv){
    FILE *in = fopen("BTH.csv", "r");
    FILE *out = fopen("novo.csv", "w");

        while(!feof(in)){
            int num;
            fscanf(in, "%d", &num);

            fprintf(out, "%d", num);

        }

    fclose(in);
    fclose(out);

    return 0;
}

A: O problema é que o arquivo csv tem mais coisas para alem de números que não irá conseguir ler com %d. Apesar de poder tentar alterar o seu algoritmo para esse caso, por exemplo com sscanf acho que é mais facil seguir por outro caminho.
Utilizando a mesma ideia de esta minha outra resposta pode fazer assim:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *in = fopen("BTH.csv", "r");
    fseek (in, 0, SEEK_END); //posicionar-se no fim
    long dimensao = ftell (in); //descobrir a dimensão
    fseek (in, 0, SEEK_SET); //voltar ao inicio

    //alocar espaço para ler tudo
    char *dados = (char*) malloc(dimensao * sizeof(char));

    if(dados){ //se conseguiu alocar
        fread (dados, 1, dimensao, in); //ler tudo
        FILE *out = fopen("novo.csv", "w"); //abrir o destino para escrita
        fwrite(dados, dimensao, 1 , out); //escrever todo o conteudo
        fclose(out);
    }

    fclose(in);
    return 0;
}

Tem várias outras alternativas também como por exemplo, executar uma copia de arquivo pelo sistema operativo com o comando apropriado.
Seria também relevante escrever as respetivas mensagens de erro quer para quando não conseguiu alocar o espaço necessário de leitura, quer para quando a abertura de qualquer um dos FILE* não teve sucesso.


text:
Q: Breadth first search with a twist Given a binary matrix where 0's represent obstacle and 1's represent a path, find the minimum number of steps to reach from a given source to a destination (traversal allowed in 4 directions only). This is a typical BFS question.
Source: (0,0) Destination: (2,0)
1 1 0
 0 1 1
 1 1 1

Answer: 5
However the next part of this question is tricky, you are allowed to turn a zero into a one with a magic wand. Now how will you find the shortest path in this condition.
If we flip (1,0) we can get to destination with 3 steps.
A typical brute force solution is to do a BFS on every matrix by changing a zero into a one. How can we do better?
This was asked in one of the popular companies.. Any help will be appreciable.

A: This is the solution I thought of:
For simplicity, I will treat the matrix as a graph.
So, denote the start position as s (vertice) and the destination as d
 (vertice).
Now, we will run BFS once with source s and once with source d.
So we have for each vertice v the minimal distance from s to v and the minimal distance from v to d (distance can be infinity, for example all vertices with value 0 in the matrix are with distance infinity).
Now, for each vertice v with value 0 in the matrix, do the following:
for each pair of neighbors of v (in the matrix, max 4) WHERE THE ORDER MATTERS, that means, the pair of vertices a and b are different from b and a.
There are maximum of 4!/2! = 12 pairs.
Denote the pair of vertices a and b and calculate the following distance:
s->a + 1 + 1 + b->d (s->a, b->d is given, this is the distance for the path s->a->v->b->d).
Pick the minimum from those distances  (max 12 of those) and this is the minimum distance from s to d with v flipped.
Now, you can know which one to flip, and also the minimum distance.
Complexity = O(V + E)
EDIT:
If the matrix is of n x n size , then V = n ^ 2 and as each vertice has at most 4 edges then E = O(n^2) => O(n ^ 2).


text:
Q: How to properly absolute positioning in reactjs The whole thing is a misunderstanding on my part please ignore!
I have tried to research this problem but the only solution that came up were for react native. My problem basically is that the CSS behaves differently in reactjs environment then in a regular one. Here is what I mean:

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
     items: [
       { text: "Learn JavaScript", done: false },
        { text: "Learn React", done: false },
        { text: "Play around in JSFiddle", done: true },
        { text: "Build something awesome", done: true }
      ]
    }
  }

  render() {
    return (
        <form>

        {/* Cart Header */}

EDIT

PAYMENT

COMFIRM

        {/* Cart Body */}

        {/* Personal information */}

Personal information

          <fieldset id="info-fieldset">

                <input type="text" placeholder="First Name"/>
                First Name

                <input type="text" placeholder="Last Name"  />
                Last Name

              <input type="email" placeholder="Email" />
              Email

              <input type="text" placeholder="Number" />
              Number

                <input type="text" placeholder="Address" />
                Adress

                <input type="text" placeholder="Apt, Unit, etc" />
                Apt, Unit, etc

                <input type="text" placeholder="Zip" />
                Zip

                <input type="text" placeholder="City" />
                City

                <select id="state-select">
                  <option value="AL">AL</option>
                  <option value="AK">AK</option>
                  <option value="AS">AS</option>
                  <option value="AZ">AZ</option>
                  <option value="AR">AR</option>
                  <option value="CA">CA</option>
                  <option value="CO">CO</option>
                  <option value="CT">CT</option>
                  <option value="DE">DE</option>
                  <option value="DC">DC</option>
                  <option value="FM">FM</option>
                  <option value="FL">FL</option>
                  <option value="GA">GA</option>
                  <option value="GU">GU</option>
                  <option value="HI">HI</option>
                  <option value="ID">ID</option>
                  <option value="IL">IL</option>
                  <option value="IN">IN</option>
                  <option value="IA">IA</option>
                  <option value="KS">KS</option>
                  <option value="KY">KY</option>
                  <option value="LA">LA</option>
                  <option value="ME">ME</option>
                  <option value="MH">MH</option>
                  <option value="MD">MD</option>
                  <option value="MA">MA</option>
                  <option value="MI">MI</option>
                  <option value="MN">MN</option>
                  <option value="MS">MS</option>
                  <option value="MO">MO</option>
                  <option value="MT">MT</option>
                  <option value="NE">NE</option>
                  <option value="NV">NV</option>
                  <option value="NH">NH</option>
                  <option value="NJ">NJ</option>
                  <option value="NM">NM</option>
                  <option value="NY">NY</option>
                  <option value="NC">NC</option>
                  <option value="ND">ND</option>
                  <option value="MP">MP</option>
                  <option value="OH">OH</option>
                  <option value="OK">OK</option>
                  <option value="OR">OR</option>
                  <option value="PW">PW</option>
                  <option value="PA">PA</option>
                  <option value="PR">PR</option>
                  <option value="RI">RI</option>
                  <option value="SC">SC</option>
                  <option value="SD">SD</option>
                  <option value="TN">TN</option>
                  <option value="TX">TX</option>
                  <option value="UT">UT</option>
                  <option value="VT">VT</option>
                  <option value="VI">VI</option>
                  <option value="VA">VA</option>
                  <option value="WA">WA</option>
                  <option value="WV">WV</option>
                  <option value="WI">WI</option>
                  <option value="WY">WY</option>
                </select>

          </fieldset>

        {/* Credit Card Information */}

Credit Card Information

        <fieldset id="cc-fieldset">

        <input type="number" placeholder="Credit Card Number" />

        <input type="text" placeholder="MM/YY" />

        <input type="text" placeholder="CVV"  />

        </fieldset>

        cart total:
        something

        cart total:
        something

        cart total:
        something

        <input type="checkbox" id="tc-checkbox" value="0" />
        Bla bla bla

        {/* Cart Footer */}

        <input type="text"/>

        <button>hello</button>

      </form>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))
:root {
  --gold: #e5cb51;
  --silver: #666666;
  --light-silver: #ddd;
}

::placeholder {
  color: var(--silver);
}

h2 {
  text-align: center;
  color: white;
  color: var(--light-silver);
  font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
}

body {
  background-color: black;
}

p {
  font-family: Raleway;
}

#cart {
  margin: auto;
  margin-top: 100px;
  width: 800px;
  display: grid;
  grid-template-areas:
    "h h"       /* Header */
    "bl br"     /* Body left right */
    "fl fr";    /* Footer left right */
}

#cart-header {
  background-color: black;
  border: 1.5px solid var(--gold);
  border-bottom: 0px;
  border-top-left-radius: 1em;
  border-top-right-radius: 1em;
  grid-area: h;
  display: flex;
  justify-content: center;
  padding: 1em 0;
}

#cart-body-left {
  grid-area: bl;
}

#cart-body-right {
  grid-area: br;
  border-left-width: 0;
}

#cart-footer-left {
  grid-area: fl;
  border-bottom-left-radius: 1em;
}

#cart-footer-right {
  grid-area: fr;
  border-bottom-right-radius: 1em;
}

.cart-body {
  width: 400px;
  height: 400px;
  border: 1.5px solid var(--gold);
  background-color: black;
}

.cart-footer {
  height: 50px;
  width: 400px;
  background-color: var(--gold);
}

#email {
  box-sizing: border-box;
  padding-bottom: 1em;
}

#number {
  box-sizing: border-box;
}

#state > select{
  height: 100%;
  border: 1.5px var(--silver) solid;
  border-radius: 3px;
}

#cc-paypal-option {
  padding-left: 50%;
  margin: 1em;
  border: 1px solid white;
  border-bottom-left-radius: .5em;
  border-bottom-right-radius: .5em;
  padding-bottom: 1em;
}

#cc-paypal-option > button {
  height: 31px;
}

#cart-stats {
  margin: 1em;
  border: 1.5px var(--gold) solid;
  border-radius: .5em;
}

#cart-stats > div:nth-child(2) {
  border-top: 1px var(--gold) solid;
  border-bottom: 1px var(--gold) solid;
  padding: .5em 0;
  margin: .5em 0;
}

#coupon {
  height: 40px;
  width: 300px;
  margin: 5px 50px;
  background-color: black;
  display: flex;
}

#coupon > div {
  width: 200px;
  position: relative;
}

#coupon-input input {
  position: absolute;
  height: 100%;
  right: 0;
  width: 0;
  opacity: 1;
  transition: all .2s ease-in;
}

#coupon-button button {
  height: 100%;
}

#cart-footer-left:hover input[type="text"] {
  width: 100px;
  opacity: 1;
  transition: all .2s ease-out;
}

.header-line {
  width: 75px;
  height: 0px;
  border: 1px solid var(--gold);
  margin: auto 0;
  background-color: var(--gold);
}

.header-icon {
  height: 2em;
  width: 120px;
  border: 1.5px solid var(--gold);
  border-radius: 4px;
  margin: .5em 0px;
  padding-top: .1em;
}

.active-icon {}

.header-icon:hover {
  background-color: var(--gold);
}

.header-icon:hover > p{
  color: black;
}

.header-icon > p {
  text-align: center;
  color: var(--light-silver);
  font-weight: bold;
  font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
  font-size: 1.2em;
  letter-spacing: 2px;
  line-height: 1.45;
}

.input-label {
  visibility: visible;
  position: absolute;
  display: block;
  color: white;
  top: 0;
  font-size: 1em;
  opacity: 1;
  transform: translateY(-1.5em);
  transition: all 0.2s ease-out;
  margin-left: 10px;
  display: inline;
}

input:placeholder-shown + label {
  opacity: 0;
  visibility: hidden;
  text-align: center;
  transform: translateY(.5em);
}

.input-div-container {
  display: flex;
}

.input-div {
  position: relative;
  padding: 1em;

  /* height: 33px; */
}

/* #first-name,
#last-name {
  width: 198.5px;
} */

.input-div > input {
  width: 100%;
  padding: 5px 10px;
  border-radius: 3px;
  border: 1.5px var(--silver) solid;

  display: block;
}

.input-div > input:focus, #state > select:focus {
  outline: none;
  border: solid var(--gold) 1.5px;
  box-shadow: 0 0 5px var(--gold);
}

.stats {
  margin: .5em;
  display: flex;
  justify-content: center;
}

.stats > span {
  padding: 0 1em;
  color: var(--light-silver);
}

.checkbox {
  position: relative;
  margin: 1em;
  margin-top: 1.3em;
}

.checkbox input[type="checkbox"] {
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
  opacity: 0;
  pointer-events: none;
}

.checkbox label::before {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 28px;
  height: 28px;
  background-color: white;
  content: '';
}

.checkbox input[type="checkbox"]:checked + label::before {
  background-color: var(--gold);
  color: white;
}

.checkbox input[type="checkbox"]:checked + label::after {
  display: block;
  position: absolute;
  top: 1px;
  left: 8.5px;
  width: 10px;
  height: 20px;
  /* background: black; */
  border: solid black;
  border-width: 0 3px 3px 0;
  transform: rotate(45deg);
  content: '';
}

@media screen and (max-width: 900px) {
  #cart {
    width: 400px;
    display: grid;
    grid-template-areas:
      "h"
      "bl"
      "fl"
      "br"
      "fr";
  }

  #cart-header {
    width: 400px;
  }

  .header-icon {
    width: 75px;
  }

  .header-icon p {
    font-size: .7em;
    letter-spacing: 2px;
    line-height: 2.5;
  }

  #cart-body-right {
    border-left-width: 1.5px;
  }

  #cart-footer-left {
    border-radius: 0px;
  }

  #cart-footer-right {
    border-bottom-left-radius: 1em;
    border-bottom-right-radius: 1em;
  }
}

Here is how it looks like when I render it without react
How it looks like after I paste my code into jsx
I hope I have provided enough code and if not I can add on to it

A: I'm not sure this is a react specific issue. I pasted your code into JSFiddle and did not run into the same issues you are having. Positioned elements will only default to root if there are no other positioned ancestors. Might be worth looking through your HTML to see if there is a positioned parent or ancestor messing with your positioning.


text:
Q: Adding a parameter to the default query I'm using ACF to create a "Featured" post section of the index.php and I'm having trouble then excluding that post from the main query.
        <?php

        $tmp = $posts;

        $isPaged = (get_query_var('paged') == 0) ? false : true;

        $posts = get_posts(array(
            'numberposts'   => 1,
            'post_type'     => 'post',
            'meta_key'      => 'featured_post',
            'meta_value'    => true
        ));

        if( !$isPaged && !is_archive() && $posts ): ?>

            <?php foreach( $posts as $post ): setup_postdata( $post ) ?>

                <?php $excludeID = $post->ID; ?>

                ... html stuff ...

            <?php endforeach; ?>

            <?php wp_reset_postdata(); ?>

        <?php endif; ?>

I then have the $excludeID with the ID of the post I need to filter out, however, I don't know how to add a posts_not_in to the main query. If this was a custom query I'd have no problem, but I'd like to leave it as the default query if possible. I tried doing this with pre_get_posts but the way I tried is clearly not the right way as there was a memory error.
Is there some sort of thing like pre_get_posts I can use before the main query?
I can't just filter out featured posts using pre_get as I only want it to show the most recent featured post, and all others just display as normal in the main query. I also can't just do and if post id == $excludeID because it messes up the posts per page. I'm sure this is possible it's just not something I've come across yet :)
Thanks.

A: I think the cleanest method here is just run a custom query, get the ID and then remove that post from the main query with post__not_in. You can additionally run a query inside a function and then call the function in your featured section and in pre_get_posts. There is another way, using a global to pass the ID from your custom query to your main query, but you should never go this route. You must avoid creating globals at all cost, they are evil
Just a note on globals and variables, avoid using $posts, $post and $wp_query as variables and assinging custom values to it. These three are globals variables used by Wordpress whichholds the main query object and post objects from the main query. Assigning any other custom value to it breaks these globals. The only time you should use any of these globals is when you use get_posts() with setup_postdata(). setup_postdata() only works with the $post global, any other global name will not work. That is why you should use wp_reset_postdata() after your foreach loop when you used setup_postdata() to reset the $post global to the last post in the main query
Example:
$q = get_posts( 'posts_per_page=1' );
if ( $q ) {
    foreach ( $q as $post ) {
       setup_postdata( $post );
       // Run loop as normal with template tags
    }
    wp_reset_postdata();
}

Now, lets look at the real problem at hand. What we will do here is create a function which we can use in our featured section and pre_get_posts.
(The following code is untested and requires PHP 5.4+. Feel free to modify as needed)
function get_featured_custom_post( $main_query = false )
{
    /*
     * For the purpose of performance, I have created a variable called $main_query with a value of false
     * When we run this function in pre_get_posts, we just need the post id, nothing more. For this, our argumaents will change
     * The default is meant to return the complete post object, that is for the featured section
     */
    if ( $main_query == true ) {
        $fields = ['fields' => 'ids'];
    } else {
        $fields = ['fields' => 'all'];
    }

    // Build our query arguments
    $defaults = [
        'numberposts'   => 1,
        'post_type'     => 'post',
        'meta_key'      => 'featured_post',
        'meta_value'    => true
    ];
    $args = wp_parse_args( $defaults, $fields );

    $q = get_posts( $args );

    return $q;
}

The value from our function get_featured_custom_post will either hold an array with the featured post id or the complete post object. Now, lets put that to use
IN pre_get_posts
add_action( 'pre_get_posts', function ( $q )
{
    if (     $q->is_home() // Targets the home page only
         && $q->is_main_query() // Targts the main query only
    ) {
        // Get the post to exclude, remeber, we need id only, so set $main_query to true
        $exclude = get_featured_custom_post( true );
        if ( $exclude ) // Only set post__not_in if we have a post to exclude, otherwise the result might be unexpected
            $q->set( 'post__not_in', (array) $exclude );
    }
});

FEATURED SECTION
In our featured section we can use the function as follow
$q = get_featured_custom_post(); // We need the complete post object, so leave $main_query at default which is false
if ( $q ) {
    foreach ( $q as $post ) {
       setup_postdata( $post );
       // Run loop as normal with template tags
    }
    wp_reset_postdata();
}


text:
Q: Backbone.JS single page app support for bulk print How can I implement "bulk print" in a Single Page application built using Backbone.JS?
Are the techniques similar to adding support for Search Engine to crawl SPA webapp?


text:
Q: Create a Confluence Page using Python API I am trying to create a page in Confluence with the python API. I tried it like written here:
How can I create a new page to confluence with Python
This is my code:
from atlassian import Confluence
import requests
import json
from requests.auth import HTTPBasicAuth

confluence = Confluence(
url='..',
username='...`,
password='...')

page_title = 'My New Page'
page_html = '
This page was created with Python!
'

parent_page_id = ...
space_key = '...'

auth_token = ".."
basic_auth = HTTPBasicAuth('mail', auth_token)

url = 'https://.../rest/api/content/'

# Request Headers
headers = {
'Content-Type': 'application/json;charset=iso-8859-1',
}

# Request body
data = {
'type': 'page',
'title': page_title,
'ancestors': [{'id':parent_page_id}],
'space': {'key':space_key},
'body': {
'storage':{
'value': page_html,
'representation':'storage',
}
}
}

try:

r = requests.post(url=url, data=json.dumps(data), headers=headers, auth=basic_auth)

# Consider any status other than 2xx an error
if not r.status_code // 100 == 2:
print("Error: Unexpected response {}".format(r))
else:
print('Page Created!')

except requests.exceptions.RequestException as e:

# A serious problem happened, like an SSLError or InvalidURL
print("Error: {}".format(e))

my first question: where do I get the token? With this token https://id.atlassian.com/manage-profile/security/api-tokens it doesn't work.
second the output is:
Unexpected response <Response [401]>
I think the authentication doesn't work. But i dont know how to authenticate....
If I try this:
oauth_dict = {
    'access_token': 'access_token',
    'access_token_secret': 'access_token_secret',
    'consumer_key': 'consumer_key',
    'key_cert': 'key_cert'}
https://atlassian-python-api.readthedocs.io/index.html

Where do i get the secret token, the consumer key and the key_cert??
pls help..

A:
my first question: where do I get the token? With this token
https://id.atlassian.com/manage-profile/security/api-tokens it doesn't
work.
second the output is:
Unexpected response <Response [401]> I think the authentication
doesn't work. But i dont know how to authenticate....

I believe I can answer this part of the question. If I understand it correctly you paste your token into the password field in the part below.
 confluence = Confluence(
    url='..',
    username='...',
    password='...')

If using a Personal Access Token (PAT) then you need to change password -> token. See below:
 confluence = Confluence(
    url='..',
    username='...',
    token='PAT goes here')


text:
Q: Can't get rid of the parentheses! LaTeX invoice package I am trying to write an invoice in LaTeX using the invoice package. However, I do not want there to be a currency or parentheses after "amount". I can easily get rid of the currency by leaving the field blank, but I have been unable to remove the parentheses.
My code:
\documentclass{letter}
\usepackage{invoice}
\address{Name\\Business\\etc.}

\date{\today}

\begin{document}
\begin{letter}{Customer name }
\opening{}

\begin{invoice}{}{0}
  \ProjectTitle{Invoice}
  \Fee{Example} {25.99} {1}
\end{invoice}

\closing{}
\end{letter}
\end{document}

This gives me:

As I said above, I am trying to remove the parentheses after "amount".

A: To remove the parentheses you have to redefine the internal \Fee@Title command:
\documentclass{letter}
\usepackage{invoice}
\address{Name\\Business\\etc.}

\date{\today}

\makeatletter
\renewcommand{\Fee@Title}{%
    \\
    \noindent\textbf{\Activity}&&\UnitRate&\Count&\Amount\\% removed part in parentheses here
    \hline%
}
\makeatother

\begin{document}
\begin{letter}{Customer name }
\opening{}

\begin{invoice}{}{0}
  \ProjectTitle{Invoice}
  \Fee{Example} {25.99} {1}
\end{invoice}

\closing{Bye}
\end{letter}
\end{document}

Result:

A: The first argument for the invoice environment is used to specify the Base Currency (or \BC) and is placed after Amount automatically. Either redefine \Fee@Title - the macro responsible for setting the header in the invoice table, or patch it via etoolbox:
\usepackage{etoolbox}
\makeatletter
\patchcmd{\Fee@Title}{\ (\BC)}{}{}{}% Remove "\ (\BC)" from \Fee@Title
\makeatother

\documentclass{letter}
\usepackage{invoice}

\address{Name\\Business\\etc.}

\usepackage{etoolbox}
\makeatletter
\patchcmd{\Fee@Title}{\ (\BC)}{}{}{}% Remove "\ (\BC)" from \Fee@Title
\makeatother

\date{\today}

\begin{document}
\begin{letter}{Customer name }
\opening{}

\begin{invoice}{}{0}
  \ProjectTitle{Invoice}
  \Fee{Example} {25.99} {1}
\end{invoice}

\closing{Thanks}
\end{letter}
\end{document}


text:
Q: Android: navigation drawer with custom adapter onItemClickListener I've been trying set custom ListView adapter for navigation drawer it derived from BaseAdapter so when I set OnItemClickListener it doesn't work on either ListView.OnItemClickListener and AdapterView.OnItemClickListener.
Googled around but all examples derive from ArrayAdapter since BaseAdapter desired.
Can anyone help me on this?
NavigationDrawer fragment onCreateView
drawerItems = new ArrayList<DrawerItem>();
drawerItems.add(DrawerItem.create(1, getString(R.string.ideas), getDrawable(R.drawable.ic_action_diamond)));
drawerItems.add(DrawerItem.create(2, getString(R.string.categories), getDrawable(R.drawable.ic_action_categories)));
drawerItems.add(DrawerItem.create(3, getString(R.string.priorities), getDrawable(R.drawable.ic_action_priorities)));

mDrawerListAdapter = MenuAdapter.newInstance(getActivity(), drawerItems);
mDrawerListView.setItemsCanFocus(true);

mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.d(TAG, String.valueOf(position));
                selectItem(position);
    }
});

mDrawerListView.setAdapter(mDrawerListAdapter);
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);

My custom adapter
public class MenuAdapter extends BaseAdapter {
    private static final String TAG = "AD:MENU";

    private final LayoutInflater mLayoutInflater;
    private List<DrawerItem> items;
    private Context context;

    public MenuAdapter(Context ctx, List<DrawerItem> items) {
        this.items = items;
        this.context = ctx;
        this.mLayoutInflater = LayoutInflater.from(ctx);
    }

    public static MenuAdapter newInstance(Context ctx, List<DrawerItem> items) {
        return new MenuAdapter(ctx, items);
    }

    @Override
    public int getCount() {
        return items == null ? 0 : items.size();
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View v, ViewGroup parent) {
        DrawerItem item = (DrawerItem) getItem(position);
        ViewHolder holder;

        if (v == null) {
            v = mLayoutInflater.inflate(R.layout.drawable_item, parent, false);
            holder = new ViewHolder();

            if (v != null) {
                holder.title = (TextView) v.findViewById(R.id.menu_title);

                holder.title.setTag(item.id);
                v.setTag(holder);
            }
        } else {
            holder = (ViewHolder) v.getTag();
        }

        holder.title.setText(item.title);
        holder.title.setCompoundDrawablesWithIntrinsicBounds(item.icon, null, null, null);

        Log.d(TAG, item.title);

        return v;
    }

    public class ViewHolder {
        TextView title;
    }

}


text:
Q: If $T \in \cal{L}(V)$ and every vector in $V$ is an eigenvector of $T$ then $T=cI$ for some $c \in \cal{F}$ Suppose $T$ is an operator on a vector space $V$ (i.e. a linear map from $V$ to itself) such that every vector $v \in V$ is an eigenvector of $T$. To show that $T$ is a scalar multiple of the identity operator.
Let be the underlying field of $V$. From the construction it is clear that for all $v \in V$, there exists $\lambda_v \in \cal{F}$ such that $Tv=\lambda_vv$
But I have to show that, as I understand it, $Tv=cv$, for all $v \in V$, for some $c \in \cal{F}$, i.e. the same $c$ works for all $v \in V$. How can I show that $\lambda_v$ is independent of $v$?
Any help would be much appreciated.

A: Choose a basis $B$ of $V$ and show that two members of $B$ have the same Eigenvalue:
If $v_1,v_2\in B$ and $\lambda_1,\lambda_2$ are their Eigenvalues it follows: $T(v_1+v_2) = \lambda_1v_1 + \lambda_2v_2$
On the other hand $v_1+v_2$ ist an Eigenvector too. Also an Eigenvalue $\eta$ exists with $T(v_1+v_2)=\eta(v_1+v_2)$. Hence you get $\lambda_1=\eta$ and $\lambda_2=\eta\,$ form thel inear independence of $v_1$ and $v_2$. So you see that only one Eigenvalue exists and you are done.

A: Suppose every vector in $V$ is an eigenvector. For contradiction, assume that $v_1, v_2$ are (non-zero) eigenvectors whose corresponding eigenvalues $\lambda_1, \lambda_2$ are distinct.
Can you show that $v_1, v_2$ are linearly independent?
But $v_1 + v_2$ is an eigenvector too. Show that this contradicts the linear independence of $v_1, v_2$.


text:
Q: instance().setState function doesn't work on unit test test i have an unit test to check if page is created well. But i have an problem. I define an empty array as users on constructor method and then assign an array with a method which is called on componentDidMount method. Everything works well when i test it myself on a device. But jest test throws error because of users array is undefined (i guess its impossible because i define it as [] at constructor method).
Part of Users.js;
export default class Users extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [],
      firmId: 0,
      key: 0,
      isLoading: true,
    };
  }

componentDidMount() {
    this.getData();
}

getData() {
    return fetch("censored url" + this.state.firmId)
      .then(response => response.json())
      .then(responseJson => {
        this.setState(
          {
            users: responseJson.users,
            isLoading: false
          },
          function() {}
        );
      })
      .catch(error => {
        console.error(error);
      });
  }

Users.spec.js;
// other imports
import { users } from "../../jest/mock-data";

describe("<Users>", () => {
  function func(){
    return "2"
  }
  const navigation = { navigate: jest.fn(), getParam: func };

  it('fetches data from server when server returns a successful response', done => { // 1
    const mockSuccessResponse = users;
    const mockJsonPromise = Promise.resolve(mockSuccessResponse); // 2
    const mockFetchPromise = Promise.resolve({ // 3
      json: () => mockJsonPromise,
    });
    jest.spyOn(global, 'fetch').mockImplementation(() => mockFetchPromise); // 4

    const component = shallow(<Users navigation={navigation}/>);    // 5

    component.instance().setState({
      users: [],
      isLoading: false
    });

    expect(global.fetch).toHaveBeenCalledTimes(2); //success
    expect(global.fetch).toHaveBeenCalledWith("censored url/2"); //success

    process.nextTick(() => { // 6
      expect(component.state()).toEqual({
        users: users,
        isLoading: false,
        firmId: "2",
        key: "2"
      });  // THROWS ERROR

      global.fetch.mockClear(); // 7
      done(); // 8
    });
  });
 });

I pointed the test which is throws error with THROWS ERROR comment.
Error on cmd;
 ● <Users> › fetches data from server when server returns a successful response

    expect(received).toEqual(expected) // deep equality

    - Expected
    + Received

      Object {
        "firmId": "2",
        "isLoading": false,
        "key": "2",
    -   "users": Array [
    -     Object {
    -       "createdAt": 1547939031000,
    -       "email": "test@firm.com",
    -       "firstName": "Test",
    -       "id": 5,
    -       "lastName": "User",
    -       "phone": "45454545454",
    -       "status": null,
    -       "updatedAt": 1547939031000,
    -     },
    -   ],
    +   "users": undefined,
      }

      48 |
      49 |     process.nextTick(() => { // 6
    > 50 |       expect(component.state()).toEqual({
         |                                 ^
      51 |         users: users,
      52 |         isLoading: false,
      53 |         firmId: "2",

I guess component.instance().setState is not works well but i'm not sure. I will be glad if you know the answer and help me to fix that problem.
edit: I tried to add a new variable at setState function which is contains in test file. And when i test it on expect it worked well. So its just not working for users variable.

A: After setting the state we need to call the update on the instance so that it forces re render adn we have updated values in the state of the component.
    component.instance().setState({
      users: [],
      isLoading: false
    });
    // Add this line
    component.instance().update();

A: I solved that problem. Problem was about my mocking fetch way. I'm newbie and not good at mocking. I'm still not sure why but lifecycle methods was defining users variable as undefined. On this stackoverflow question's answer i saw and method to block lifecycle methods run when shallow function runs. So i used that method instead of mocking fetch and blocked lifecycle methods calls fetching function (i named it getData() on my project). And declared mocked data to users variable.
This is how to block lifecycle methods on shallow function;
const navigation = { navigate: jest.fn(), getParam: jest.fn() };
const component = shallow(<Users navigation={navigation}/>, { disableLifecycleMethods: true });    // 5

Navigation part is about to mocking react-navigation


text:
Q: How to initialize an array that is private in a class using constructor at runtime? I have made a class Graph when I have made a pointer in private access in the class named visited. In the constructor I have initialized the array with zero at all places but when I am checking if all the values are zero in  another method ,It is showing garbage values in the array but when I print it in the constructor itself then it showing all zeroes.
#include<iostream>
#include<vector>
#include<list>
using namespace std;

class Graph {
private:
  int vertices,edges;
  vector <list<int>> graph;
  vector <int> vs;
  int *visited;
public:
  Graph (int vertices)
  {
    this->vertices = vertices;
    list <int>l;
    for (size_t i = 0; i < vertices; i++) {
      graph.push_back(l);
      vs.push_back(i);
    }
    edges=0;
// #######  made a new array, initialized all values with zeroes and assigned it to the instance variable visited  #########
    int a[vertices]={0};
    this->visited = a;
// ########  in the constructor it is showing correct values below  #######
    for (size_t i = 0; i < vertices; i++) {
      std::cout << this->visited[i] << ' ';
    }
    std::cout << '\n';
  }
  virtual ~Graph ()
  {

  }
  void showList()
  {
// just printing the graph in the form of adjacency list
// it is working fine
    for (size_t i = 0; i < vertices; i++)
    {
      list <int>::iterator p = graph[i].begin();
      std::cout << i ;
      for (; p != graph[i].end() ; p++)
      {
        std::cout << " -> " << *p ;
      }
      std::cout << " -> NULL" << '\n';
    }
// ########  when I am checking the values here then it is printing garbage values
    for (size_t i = 0; i < this->vertices; i++) {
      std::cout << this->visited[i] << ' ';
    }
  }
  void addEdge(int source, int destination)
  {
    graph[source].push_back(destination);
  }
};

int main()
{
  Graph g(6);
  g.addEdge(0,1);
  g.addEdge(0,2);
  g.addEdge(1,0);
  g.addEdge(1,3);
  g.addEdge(1,4);
  g.addEdge(2,0);
  g.addEdge(2,4);
  g.showList();
  return 0;
}

when i call the showList method the it should print the adjacenct list and all zeroes(contents of array named visited)

A:
I have made a class Graph.

Yes you have.
class Graph {

I have made a pointer in private access in the class named visited.

Yes you have.
private:
  int *visited;

In the constructor I have initialized the array with zero at all places.

Yes you have.
int a[vertices]={0};

But I would note that this is a variable that is local to the constructor. It is not visible to any other methods. Also when the constructor finishes the lifespan of this object ends. Any attempt to accesses this array after its lifetime ends is undefined behavior. So accessing this by some sneaky mechanism (like savings its address in a pointer) is going to cause bad things to happen.
Here you are doing something sneaky (and very bad):
this->visited = a;

but when I am checking if all the values are zero in another method

You are accessing the array through a pointer visited. This is pointing to an array that no longer exists because the array is local to another function.
    std::cout << this->visited[i] << ' ';  // This is broken code.

It is showing garbage values in the array

You are very unlucky. It would have been nicer if the program had crashed and made it more obvious that something bad is happening. Unfortunately you have discovered that undefined behavior can do anything (including simply return some random values).

but when I print it in the constructor itself then it showing all zeroes.

It is still valid in the constructor so accessing it is not a problem.
So what is the solution.
In general pointers you should avoid pointers (especially when brand new). You need to get some basic concepts down first.
In this case simply replace:
 int*   visited;

With
 std::vector<int> visited;

In the constructor fill this with the appropriate zero values.


text:
Q: Qt Signal/Slots: passing function returning pointer as receiver argument: is it possible? Say I have the function...
const QMainWindow* MainWindow::getThis(){
    return this;
}

would it be possible to call this function for the third argument of my SIGNAL/SLOT connection...
QAction* myAction = new QAction("my action!");
connect(myAction, &QAction::triggered, getThis(), &MainWindow::someAction);

(qt creator doesnt like this)


text:
Q: Why do we multiply in the total wave function but add in the LCAO method? If to particles with wave functions $\psi_a$ and $\psi_b$ are "combined" their total wave function is given by:
$$\psi(r_1,r_2)= A[\psi_a(r_1)\psi_b(r_2) \pm \psi_b(r_1)\psi_a(r_2)]$$
(+ for bosons and - for fermions, $A$ is a constant, here I'm ignoring spin.)
But if we combine the wave functions of two atomic orbitals $\psi_c$ and $\psi_d$ it is done by a simple Linear Combination of Atomic Orbitals (LCAO):
$$\psi = C_1\psi_c + C_2\psi_d$$
Where the $C_1$, $C_2$ are constants.
These two processes of generating the total wave function out of existing ones feel to me as if they should be carried out in the same way. And I understand that we do it this way in the first case since we can't tell the particles apart and the total wave function therefore has either to be symmetric or antisymmetric. So what is the justification that we can simply add them in the second LCAO case?

A: These formulae do different things. The first one takes 2 (or more) single-particle wavefunctions and gives you a multiple-particle wavefunction that can be interpreted as having one particle in one state and another particle in another state. The second one instead produces a single-particle wavefunction that can be interpreted as a single particle in a superposition of the states. Since they do different things, they look different too.
In quantum chemistry, the overall wavefunction of all the electrons together is often assumed to be of the first form (called a Slater determinant), combining $N$ single-electron spin-orbital wavefunctions. (Reduces to your formula for $N=2,$ replace the determinant with the permanent for bosons.) (In general, the wavefunction may be a linear superposition of these.)
$$\psi(\vec r_1,\ldots,\vec r_N)=\frac1{\sqrt{N!}}\begin{vmatrix}\psi_1(\vec r_1)&\ldots&\psi_1(\vec r_N)\\\vdots&\ddots&\vdots\\\psi_N(\vec r_1)&\ldots&\psi_N(\vec r_N)\end{vmatrix}$$
The problem of finding the overall wavefunction is now reduced to finding $N$ single-electron wavefunctions (the molecular (spin-)orbitals $\psi_n$). LCAO provides plausible candidates for these by combining atomic orbitals. The two types of combination work together to produce the final wavefunction. You cannot replace one with the other.


text:
Q: removeRange() function gives empty string in Swift 2 The removeRange: is giving me an empty string in Swift 2 and I don't understand why.
The example in the apple documentation is:
var welcome = "hello!"
let range = welcome.endIndex.advancedBy(-6)..<welcome.endIndex
welcome.removeRange(range)
//I get "" as result rather than "hello" where the exclamation mark is removed

What could be the problem?

A: You start at the endIndex and then you go back by 6. You are now at the beginning of the word. Then you make a range to the end index and you remove the content of this range: of course there's nothing left. :)
For example, it could be this instead:
var welcome = "hello!"
let range = welcome.endIndex.advancedBy(-1)..<welcome.endIndex
welcome.removeRange(range)

Or this:
var welcome = "hello!"
let range = welcome.startIndex.advancedBy(5)..<welcome.endIndex
welcome.removeRange(range)

There's many possible combinations.

A: the string in apple documentation is
at the time of remove range
var welcome = "hello there!"

A: The value of welcome.endIndex is 6 so advancedBy(-6) means it goes to 0. Then the range = 0..<6 that means the the range cover the whole string.
If you want "hello" then change only advancedBy(-1).
var welcome = "hello!"
let range = welcome.endIndex.advancedBy(-1)..<welcome.endIndex
welcome.removeRange(range)


text:
Q: C# BitConverter.ToSingle equivalent in Python I have some code in C# that converts bytes to float using BitConverter.ToSingle function, like this:
float tmp_float = BitConverter.ToSingle(jobBff, cnt);

As I found out from this link:
http://en.wikipedia.org/wiki/Single-precision_floating-point_format
four bytes go in (just not sure in what order), use 1 bit for sign, 8 bits for exponent, and the rest of the bits for the fraction.
In C# I just inform a buffer, the starting position, and C# does the rest of the job. Is there an equivalent function for that on Python? Or how can I convert those 4 bytes to a float?
Thanks!

Solution: as suggested by Kyle in the answer, I ended up using the code below, which worked for me.
def prepare_bytes_on_string(array):
    output = ''
    for i in range(0, len(array), 1):
        #Just as a reminder:
        #hex(x)                    #value: '0xffffbfde1605'
        #hex(x)[2:]                #value: 'ffffbfde1605'
        #hex(x)[2:].decode('hex')  #value: '\xff\xff\xbf\xde\x16\x05'
        output += hex(array[i])[2:].decode('hex')
    return output

bytes_array = [0x38, 0xcd, 0x87, 0xc0]
val = prepare_bytes_on_string(bytes_array)
output = unpack('f', val)
print output

A: Python has the struct module.  You would want the struct.unpack( 'f', buffer ) method (possibly with some endianess adjustment, see the documentation for that).


text:
Q: How to send message to Whatsapp to specified number without opening whatsapp app I want to send message to whatsapp to specified number without opening whatsapp app on button click
Thanks in advance


text: Q: Facebook Network Audience - Optimisation in progress, ads are not showing I have created a mediation group on admob with admob ads and Facebook Network Audience. However, the admob ads are showing, but for the Facebook Network Audience, it says "optimisation in progress". I do not know how to solve this problem, any help will be great. Thank you!


text:
Q: Skip MSI if already installed I have a WIX installer in which I install my program and .NET Core 1.0.5. The .NET Core is installed in silent mode:
<ExePackage InstallCommand="/q" Id = "DotNetCore.Setup" SourceFile="..\DotNetCore\DotNetCore.exe" />

On a clean system, the installer just goes fine. If I try to reinstall it, I get a reboot. Probably the .NET installer detected to be already installed and triggered the repair feature on its own. Is there any way to skip the .NET Core installation if it's already installed?
I tried looking for command line parameters but nothing seems useful

A: The ExePackage element has the DetectCondition property. This means that you can specify a condition such that, if the condition evaluates to false, the package will be installed. You can combine this with an util:RegistrySearch element which can be used to search through the registry to detect if the .NET Core has already been installed.
In order to perform the registry search, you will first need to find a registry key which is present whenever .NET is installed.
Find the "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\",
(or "HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\" on 64-bit machines) key in your registry, then locate the subkey which corresponds to the .NET Core - this key should have a value for "DisplayName" which should be ".NET Core" or something similar.
The correct key, once found, should have a name which is a string of hex characters - this is one of the GUIDs corresponding to the .NET Core program. You can then use the following code to allow the installer to search for the presence of this key:
<util:RegistrySearch Id="VCRedistTest32" Root="HKLM" Key="SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{YOUR_GUID_HERE}" Result="exists" Variable="DOTNETPresent" Win64="no"/>

(Use Win64="yes" instead for the 64-bit registry)
You can then use the following for the ExePackage:
<ExePackage InstallCommand="/q" Id = "DotNetCore.Setup" SourceFile="..\DotNetCore\DotNetCore.exe" DetectCondition="DOTNETPresent"/>

Don't forget to add the reference to the util extension to the top-level wix element:
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
 xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">

A: You need to use DetectCondition attribute and registry search that assign property in case the .net Core is installed.
ExePackage Element - DetectCondition
"A condition that determines if the package is present on the target system. This condition can use built-in variables and variables returned by searches. This condition is necessary because Windows doesn't provide a method to detect the presence of an ExePackage. Burn uses this condition to determine how to treat this package during a bundle action; for example, if this condition is false or omitted and the bundle is being installed, Burn will install this package."


text:
Q: Excel - using INDEX / MATCH to retrieve data from a table based upon multiple matches I have a rota listing names (down the side) and dates (across the top) and there is also an additional column for region/area for each name e.g.:
--Name--------Region-------13/12/19--------14/12/19--------15/12/19--------16/12/19-----------17/12/19
John Smith    North           IN             IN              OFF              IN                OFF
Jane Doe      North           OFF            IN              IN               IN                OFF
Bob Newhart   South           IN             IN              OFF              OFF               OFF

I also have a list of jobs completed by each person e.g.:
--Name--------Region-----Job#---CompletedDate-----JobType
John Smith                22        14/12/19         xx
John Smith                23        14/12/19         yy
John Smith                24        16/12/19         zz
Bob Newhart               25        14/12/19         aa

I know how to look up the Region from the name =INDEX(table[Region],MATCH(A2,table[Name],0),0)
and I've even worked out how to look up whether they're in or off based on a 2-way INDEX/MATCH (e.g. =INDEX(Rota!B:B,MATCH(A2,Rota!A:A,0),MATCH(D2,Rota!1:1,0))
My issue is when a person changes region e.g. John Smith moves from North to West:
--Name--------Region-------13/12/19--------14/12/19--------15/12/19--------16/12/19-----------17/12/19
John Smith    North           IN             IN              OFF
John Smith    West                                                            IN                OFF
Jane Doe      North           OFF            IN              IN               IN                OFF
Bob Newhart   South           IN             IN              OFF              OFF               OFF

I need to look up what their region was on the day the job was done so I can summarise the jobs done per region separately from the number of jobs done per person.
I'm guessing that it is something like the 2nd INDEX/MATCH above but with some form of "if the cell is blank then move down to the next match of their name in the same column". Does that even make sense?
Any help would be appreciated.
Thanks,
Alan

A: What about creating a helper column that combines person + region? e.g. you'll have a (hidden) column containing values like John Smith~north (you'll want a separator that properly handles Jane South).
Additionally, I think the first index function you've created can be substituted by a VLOOKUP:
=VLOOKUP(A2,rota!$A:$E, 2, FALSE)
// look for value A2
   in the first column of A:E on the Rota sheet, then
   copy over the value from the 2nd
   Don't approximate matches

The second could be re-created with a simple COLUMN() reference to itself if the dates are entirely congruent between the sheets (i.e. if the dates are the same for each column).
EDIT
Took a second (closer) look - You're kind of pushing Excel to the limits of what it is designed for. You could try and hack around this, e.g. by wrapping the second INDEX function in an IF that checks if the outcome of the index is not empty and if it is, moves the match down one. But this will not tackle an example where John moves between three regions.
Conceptually, you're working on three tables:
 1. Name/date with in or out values
 2. Name/date with region values
 3. Job/date with name values
Because your ROTA table is merging 1 and 2, you are getting multiple rows for one individual, and that is giving you trouble in the third table. Maybe in your design you can split these, which will make it easier to grab them with the functions you use. This starts to look a lot like a database though...
But maybe you add the region in the fields of the ROTA table?
--Name----------13/12/19--------14/12/19--------15/12/19--------16/12/19-----------17/12/19
John Smith      IN~N            IN~N            OFF~N           IN~S               OFF~S

This means that for the region you can use the function that you'll already used, if you use one appended character in all cases:
=LEFT(INDEX(table[Region],MATCH(A2,table[Name],0),0), LEN(INDEX(table[Region], MATCH(A2,table[Name],0),0)) -2)
=RIGHT(INDEX(table[Region], MATCH(A2,table[Name],0),0), 1)

Or if you want to use the delimiter (~ in the example)
=LEFT(INDEX(table[Region],MATCH(A2,table[Name],0),0), FIND("~", INDEX(table[Region],MATCH(A2,table[Name],0),0) -1)
=RIGHT(INDEX(table[Region],MATCH(A2,table[Name],0),0), FIND("~", INDEX(table[Region],MATCH(A2,table[Name],0),0) -1)


text:
Q: Import contents of Text file into a List in Python This is Regarding the projecteuler problem 42.
I want to import the content of this text file (https://projecteuler.net/project/resources/p042_words.txt) in to a list  in python.
I want the list to be like
list = ["A","ABILITY",........]
Any help is greatly appreciated.

A: use following code:
mylist=[]
with open('p042_words.txt','r') as f:
    mylist=f.readlines()
l=[]
for i in mylist:
    l=l+i.split(',')
print(l)

if you want remove '"' character from each word use following code:
import re
mylist=[]
with open('p042_words.txt','r') as f:
    mylist=f.readlines()

l=[]
for i in mylist:
    j=re.sub('["]','',i)
    l=l+j.strip('"').split(',')
print(l)

A: The values in the file are comma separated so you can use the csv reader. It will take care of everything for you.
import csv

with open('p042_words.txt', 'r') as infile:
    lst = [item for item in csv.reader(infile)][0]

the [0] is because there is only one line in the CSV file.
lst will now contain:
['A', 'ABILITY', 'ABLE', 'ABOUT', ...

A: You'll have to split the words once you load them, then strip the quotation marks from them to get the desired result, i.e.
with open("p042_words.txt", "r") as f:
    words = [word.strip("\"' \t\n\r") for word in f.read().split(",")]

print(words)
# ['A', 'ABILITY', 'ABLE', 'ABOUT', 'ABOVE', ...]

Technically, for this file simple stripping of quotation marks should be enough, but I've added the common whitespace and single quotation marks just in case.


text:
Q: How to store and access voxel sphere in array? I generate a voxel sphere (ellipsoid) in the code below.
        struct Volume {
          private int3 r; // radiuses of ellipsoid (3 integers for 3 axes)

          public IEnumerable<int3> Iterate()
          {
            for (var x = -r.x; x <= r.x; x++)
            for (var y = -r.y; y <= r.y; y++)
            for (var z = -r.z; z <= r.z; z++)
                if (x * x + y * y + z * z <= r.x * r.y * r.z)
                    yield return int3(x, y, z);
          }
          // return number/index of a point generated in the method above
          public int IndexOf(int3 point) => ???
        }

Then I collect all the entries in a list
            var sphere = new Volume(3);  // radius of sphere is 3
            var pointsInSphere = sphere.Iterate().ToArray();

Is there way to implement the method IndexOf without searching the point in the array?
For example, we can easily do that for a cuboid of voxels: index = point.x*sizeY*sizeZ + point.y*sizeZ + point.z, but I find it too complicated to do the same for a sphere and don't know if that's even possible.

A: Well this also interests me. Way to go is if you can order voxals in some orderly fashion, so you can mathematically describe its position.
For example if you have 2D array represented in array, You will do int(width*height) instead of int(height)(width).
Also reverting with :
Count = width * height
Width = count % width
Height = count / width

So we are essentially looking to make array of arrays that would represent sphere and coordinates needed to be mappable to indexes of those arrays.


text:
Q: How can I call all entries in an arraylist to be displayed on a graph in MPAndroidChart? I apologize if I worded this poorly but for the sake of clarity I will explain as best I can. I'm using MPAndroidChart to draw a line graph and I followed this tutorial to get it up and running https://www.numetriclabz.com/android-line-chart-using-mpandroidchart-tutorial/#Defining_X-axis_labels. I've made some adjustments to suit my needs and so on.
On button click, I call a method that adds another entry using the value of the edit text field, at the position that i increment each button press so the code is something like entries.add(new Entry(editTextValue, numEntries));This does what I want it to do while I'm looking at the current activity screen, with the previous value remaining, and the next value being added. However, once i leave that activity and return to it, only the last value remains. My understanding is that I need to have a for loop that will iterate over each element in arraylist when I call the drawGraph method that I'm using, but I haven't had any luck with this. I've tried to use for(Entry e: entries) and use e in place of numEntries, but the data type is not compatible. Any help is greatly appreciated!
EDIT: `public class testActivity extends AppCompatActivity {
    int counter = 0;
    public ArrayList entries = new ArrayList<>();
    public static int lifetimeNums;
    public static int nums = 0;
    public static int numEntries;
public static String entryLabel = Integer.toString(numEntries);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    reDrawGraph();
}

// Graphing method
public void reDrawGraph(){

    LineChart chart = (LineChart) findViewById(R.id.chart);

    XAxis xAxis = chart.getXAxis();
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

    chart.getAxisLeft().setAxisMaxValue(100);
    chart.getXAxis().setAxisMaxValue(100);

    //Creating list of entries

    LineDataSet dataset = new LineDataSet(entries, "# of Calls");

    // creating labels
    ArrayList<String> labels = new ArrayList<String>();
    for (int i = 0; i < 10 + numEntries; i++) {
        labels.add(Integer.toString(i));
    }

    LineData data = new LineData(labels, dataset);

    entries.add(new Entry(testActivity.nums, numEntries));

    chart.animateXY(1000,1000);
    chart.notifyDataSetChanged();
    chart.invalidate();
    chart.setData(data); // set the data and list of lables into chart

}

public void counterClicked(View view){

    try {

        EditText inputText = (EditText) findViewById(R.id.edit_text_val);
        int localNums = Integer.parseInt(inputText.getText().toString());

        if (counter < 3) {
            nums += localNums;
            counter++;
            numEntries++;

            Toast.makeText(this, "Total Entries" + entries.get(0),
                    Toast.LENGTH_SHORT).show();
            reDrawGraph();
            inputText.getText().clear();
        }

        if (counter == 3){
            lifetimeNums++;
            numEntries++;
            Intent intent = new Intent(this, SelectionActivity.class);

            startActivity(intent);
        }

    }catch (Exception e) {

        Toast.makeText(this, "Please enter a value",
                Toast.LENGTH_SHORT).show();
    }`


text:
Q:  in structure Given that I have this function which fills a member of nicInfo's structure:
nicList()
{
    std::string num;
    std::string nic_name_command;
    nicInfo* nic = {};
        nic = new nicInfo[nic_numbers];
        for (int i = 0; i < nic_numbers; i++)
        {
            nic_name_command = "ls /sys/class/net | sed -n -s " + std::to_string(i+1) + "p";
            nic[i].name = sshObj->exec_ssh_command(nic_name_command);
        }

    return nic;
}

and this is nicInfo :

struct nicInfo
{
    const char* name = {};
    const char* ipAddr;
};

for example if I have 3 nic cards(nic_numbers = 3), after debugging, nic[4].name is not null or 0. it has this content: +name  0x1 <error: Cannot access memory at address 0x1>    const char *. I  want to print names in a while loop like this :
int i = 0 ;
while ((nic + i)->name )
    {
        printf("nic name : %s\n", (nic + i)->name);
        i++;

but it crashes on i = 4, because it's content is not null. what should I do?
( my function and structure are in c++ but while loop for testing is in c)

A: The loop
while ((nic + i)->name )
    {
        printf("nic name : %s\n", (nic + i)->name);
        i++;

will go out of bounds of the memory you allocated for nic. Doing that leads to undefined behavior.
You need to use a for loop to only  iterate over the elements you actually have:
for (size_t i = 0; i < nic_numbers; ++i)
{
    // ...
}

This of course requires that nic_numbers use in the loop matches nic_numbers used when allocating the memory. If you don't have the size, then you can't use a condition like yours to find the end. You need the actual size of the array.
My suggestion is to program everything in C++, as then you could use std::string and std::vector<nicInfo> instead, and that would simplify matters quite a lot.

On a side-note: For any pointer p and index i, the expression *(p + i) is exactly equal to p[i]. For your case that means (nic + i)->name is exactly equal to nic[i].name. The latter is usually easier to read, and less to write.