text:
Q: ARMA_NO_DEBUG in R package with RcppArmadillo I want to disable bound checks when accessing to matrix elements in RcppArmadillo.
The documentations of Armadillo says

Armadillo can be configured via editing the file
  include/armadillo_bits/config.hpp. Specific functionality can be
  enabled or disabled by uncommenting or commenting out a particular
  #define, listed below.

But in the context of an R package, how can I activate this directive?
I have tried to create a config.h  file with
#ifndef CONFIG_LOADED
#define CONFIG_LOADED
#define ARMA_NO_DEBUG
#endif

and then including it in every .cpp file of my /src folder, but I'm not sure whether it works properly or whether there is some other way other than adding a #include "config.h"in each .cpp file.

Currently I have one .cpp (the one that contains the main algorithm) that start with:
#include "configs.h"
#include <RcppArmadillo.h>

using namespace Rcpp;
using namespace arma;

// [[Rcpp::export]]
SEXP sample_gibbs_cpp(const arma::vec& v_n, const arma::mat& W,
arma::vec h_n, double alpha = 1, double beta = 1, int iter=100,
double burnin = 0.5){
... code ...
}

And then others that are just
#include <RcppArmadillo.h>

using namespace Rcpp;
using namespace arma;
... code ...

My DESCRIPTION file:
Package: mypackage
Title: What the Package Does (one line, title case)
Version: 0.0.0.9000
Authors@R: person("First", "Last", email = "first.last@example.com", role = c("aut", "cre"))
Description: What the package does (one paragraph).
Depends:
    R (>= 3.2.3)
License: What license is it under?
Encoding: UTF-8
LazyData: true
RoxygenNote: 5.0.1
Imports:
    ggplot2,
    dplyr,
    tidyr,
    rstan
LinkingTo: Rcpp, RcppArmadillo, RcppEigen
SystemRequirements: C++11

And I compile my package with:
devtools::load_all()

A: Order matters here. This #define statement must be included before the inclusion of #include<RcppArmadillo.h>
An example:
custom_config.h
#ifndef CONFIG_LOADED
#define CONFIG_LOADED
#define ARMA_NO_DEBUG
#endif

example_compiled_file.cpp
#include "custom_config.h"
#include <RcppArmadillo.h>

// [[Rcpp::export]]
void test_pkg(const arma::vec& x) {

   // Should not trigger error bound checking with debug flag on.
   double my_val_protected = x(0);

   // Never triggers error bound checking
   double my_val = x.at(0);
}

Note: As this is a package, the use of // [[Rcpp::depends(RcppArmadillo)]] is not required. Instead, you must specify RcppArmadillo and Rcpp in the LinkingTo: field of the DESCRIPTION file as well as including Rcpp in the Imports: field. You will have to minimally import from Rcpp a function (preferably: evalCpp).
e.g. DESCRIPTION must have:
Imports: Rcpp (>= 0.12.15)
LinkingTo: Rcpp, RcppArmadillo


text:
Q: .toPromise().then(...).catch(...).finally is not a function I'm getting this error on Firefox and I'm using rxjs 6.5.4 version:

Unhandled promise rejection TypeError:
this.service.getPastData2(...).toPromise().then(...).catch(...).finally
is not a function

My code:
lineMap(criteria: ReportCriterionModel){

        this.service
            .getPastData2(
                criteria.deviceIds[0].toString(),
                criteria.vehiclePlates[0].toString(),
                criteria.startDate,
                criteria.finishDate)
            .toPromise()
            .then(
                (data) => {
                    this.loadDataToMap(data);
                    this.filterData = criteria;
                },
                (err) => {
                    if (err.status == 400) {
                        this.isLoadingFms.next(false);
                    }
                }
            )
            .catch(
                (err) => {
                    console.log(err);
                }
            )
            .finally(
                () => {
                    this.isLoadingFms.next(false);

                }
            )

    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get information from database excluding some data I have 3 tables in my database.
The first table is "Ordenes", in this table i have all the orders that the users create in the website, this table got information like: FechaFinal, FechaInicial, NoOrden, Cantidad, and Estado.
I have another table called "Cables", in this table i save all the cable that the users register per order.
For example, if i have a order row and the Cantidad says that is 200, so the user need register 200 cables to this order.
The Cables table have information like: Serial, IdOrden, and IdOperation.
The IdOperation is a foreign key of the Operations Tables, in this table i save information like: Name of operation, and its all.
So i want to do a sql query that show me this information:
FechaInicial (From Order Table), Fechafinal (From Order Table), NoOrden (From Order Table), Material (From Order Table), Cantidad (From Order Table), and Performed (This is a count of all cables that i have in my Cables Table for some Order)
I have it, and it works, but i want that the query ONLY COUNT the cables that doesn't are in some operation called 'Scrap'.
I have this SQL Query, and it works, but it also is counting the cables that are in the 'Scrap' Operation.
SELECT o.FechaInicial, o.FechaFinal, o.NoOrden, o.Material, o.Cantidad, COUNT(c.IdCable) as 'Hechos', o.Estado
FROM Ordenes o
LEFT JOIN Cables c ON o.IdOrden = c.IdOrden
LEFT JOIN Operaciones op ON c.IdOperacion = op.IdOperacion AND op.Nombre NOT IN ('Scrap')
GROUP BY o.FechaInicial, o.Fechafinal, o.NoOrden, o.Material, o.Cantidad, o.Estado;

I want to show ALL orders, even if a order doesn't have cables yet.

A: Change the count to COUNT(op.Nombre) or COUNT(op.idOperacion) if Nombre can be NULL.

A: The left join keeps all rows, even those that have scrap.  The best solution is to count the primary key or join key from the last table.  So, I would recommend:
SELECT o.FechaInicial, o.FechaFinal, o.NoOrden, o.Material, o.Cantidad,
       COUNT(op.IdOperacion) as Hecho, o.Estado
FROM Ordenes o LEFT JOIN
     Cables c
     ON o.IdOrden = c.IdOrden LEFT JOIN
     Operaciones op
     ON c.IdOperacion = op.IdOperacion AND op.Nombre NOT IN ('Scrap')
GROUP BY o.FechaInicial, o.Fechafinal, o.NoOrden, o.Material, o.Cantidad, o.Estado;

This counts only "matching" rows in Operaciones.
Note:  If you count a data column, you might be missing rows where that value is NULL in the original table.  That might be a good thing, depending on the intention of the query.  In general, it is safer to count something that cannot be NULL when a match occurs.


text:
Q: Input box 100% width, with label to the left I'm trying to have a fluid input box with 100% width, while having the label floated to the left.  Here's what I currently have:
.left {
  float: left;
}

input {
  width: 100%;
}

<form>
    Name:
    <input class="left" id="name" name="name"/>

</form>

This works, however it drops down below the label.  If I use a parent div to assign the floats, then it doesn't span 100%.  Any ideas?
Thank you!

A: I recently found out about calc in css:
width: calc(100% - 100px);

this can be used to solve this problem: jsfiddle here
HTML:

    label
    <input class="s2"/>

CSS:
.setting {
    position: relative;
    width: 100%;
}
.setting .s2 {
    position: absolute;
    left: 180px;
    width: calc(100% - 184px);
}

A: See: http://jsfiddle.net/r2769/ (resize the window)
CSS:
.left {
    float: left;
}

.left2 {
    overflow: hidden;
    display: block;
    padding: 0 4px 0 10px
}
.left2 input {
    width: 100%
}

HTML:
<form>
    Name:
    <input id="name" name="name" />
</form>

An explanation of the method is here.


text:
Q: multiple master and detail views in iPad split view, uisplitview Thanks ahead of time.  I am currently developing the iPad version of an app which on the iphone has 3 tabs,which each load 3 different rss feeds and then drill down to details with a navigation controller on the iPhone.  On the iPad what makes sense is that I join 2 of the feeds in the first splitview, and then have a separate master and detail for the 3rd feed.
what is the best practice to accomplish this.  I currently have setup a toolbar button in the first detailview, which calls the appdelegate which switches the master and detail as so
- (void)switchViews {

    VideoSelectorViewController *masterViewController = nil;
    VideoDetailiPadViewController *detailViewController = nil;
    UIViewController *tempDetail = [self.splitViewController.viewControllers objectAtIndex:1];
    UIViewController *tempMaster = [self.splitViewController.viewControllers objectAtIndex:0];
    [tempDetail.view removeFromSuperview];
    [tempMaster.view removeFromSuperview];
    [tempDetail release];
    [tempMaster release];
    tempDetail = nil;
    tempMaster = nil;

  //  if (row == 1) {
        VideoSelectorViewController *newMasterViewController = [[VideoSelectorViewController alloc] initWithNibName:@"VideoSelectorViewController" bundle:nil];
        masterViewController = newMasterViewController;

        VideoDetailiPadViewController *newDetailViewController = [[VideoDetailiPadViewController alloc] initWithNibName:@"VideoDetailiPadViewController" bundle:nil];
        detailViewController = newDetailViewController;

  //  }

    // Update the split view controller's view controllers array.
    NSArray *viewControllers = [[NSArray alloc] initWithObjects:masterViewController, detailViewController, nil];
    self.splitViewController.viewControllers = viewControllers;
    [viewControllers release];

/*  // Dismiss the popover if it's present.
    if (popoverController != nil) {
        [popoverController dismissPopoverAnimated:YES];
    }*/

    // Configure the new view controller's popover button (after the view has been displayed and its toolbar/navigation bar has been created).
   // if (detailViewController.popover != nil) {
        [detailViewController showRootPopoverButtonItem:detailViewController.rootPopoverButtonItem];
    //}

    [masterViewController release];
    [detailViewController release];

}

this works ok when the iPad is in landscape but on portrait the barbutton does not show up in the toolbar, how can i call - (void)splitViewController: (UISplitViewController*)svc willHideViewController programmatically?  Also memory management for my method, should i release and set to nil the previous master and detail as I am with those temp objects in my switchViews method?
The other method is to push the new master on to the old, and just replace the detail.  which is better, memory wise, performance, etc.  thanks again

A: Since nobody was able to give any insight, what I did was create a second view in the detailview which is only used with my second tableview

A: Your ViewController needs UISplitViewControllerDelegate
then it'll be called automatically
See http://developer.apple.com/library/ios/#documentation/uikit/reference/UISplitViewControllerDelegate_protocol/Reference/Reference.html


text:
Q: A formula that counts exactly the twin prime averages occuring in an interval $[a,b]$ is surprisingly succinct! Let $p_n$ denote the $n$th prime number. Let $p_n \lt a \lt b \lt p_{n+1}^2$ be any such integers.  Their oddness or divisibility does not matter as in my previous posts, which makes this formula particularly nice.
An inclusion-exclusion based & modular-arithmetical counting formula for the twin primes is:
$$f(a,b) = b - a + \sum_{1 \ \neq \ d \ \mid \ p_n\#} (-1)^{\omega(d)}\sum_{2 \ \nmid \ c \ \mid \ d}\left( \left\lfloor\dfrac{b - x_{c,d}}{d}\right\rfloor + \left\lfloor\dfrac{x_{c,d} - a}{d}\right\rfloor \right)$$
where $x = x_{c,d} =$ any solution in $\Bbb{Z}$ to the simultaneous & CRT system:
$$
x = 1 \pmod c \\
x = -1 \pmod {d/c}
$$
Note that the purpose of this formula is purely theoretical and is in no way optimal for counting up the twin primes in an interval.
Questions.
How can we relate this to the inclusion-exclusion formula for $\pi(x)$?
Found here:
"Algorithms evaluating $\pi(x)$".  It's very close because the alternating sum over divisors of $p_n\#$ does the same thing as that sum, except our sum is missing $d = 1$ and inside of our sum is another sum, and not just a floor of a fraction.
Many other MSE users including mathlove, BillyJoe, and JyrkiLahtonen have been helpful in developing this formula.

Attempt.
We know that $\sum_{d \mid p_n\#} (-1)^{\omega(d)} \lfloor\dfrac{z}{d} \rfloor = x + \sum_{1 \neq d \mid p_n\#} (-1)^{\omega(d)} \lfloor \dfrac{z}{d}\rfloor = \pi(z) - \pi(\sqrt{z}) + 1$ by the given link.
Thus $\sum_{1 \neq d \mid p_n\#} (-1)^{\omega(d)}\lfloor\dfrac{ z}{d} \rfloor =\pi(x) - x - \pi(\sqrt{x}) + 1$ if we can get the double sum into a sum of sums of this form.

The double summation naturally has the form of:
$$
-\sum_{1\ \neq\ cd \ \mid\ p_n\# \\ 2 \ \nmid\ c} (-1)^{\omega(d)} \left(\lfloor \dfrac{b - x_{c,d}}{cd}\rfloor + \lfloor \dfrac{x_{c,d} - a}{cd}\rfloor \right)
$$
where $x = x_{c,d} \in \Bbb{Z}$ is any solution to the simultaneous CRT system:
$$
x = 1 \pmod {c} \\
x = -1 \pmod {d}
$$

Here's what an example computation looks like, with the equivalent ceil's in place of floor around $a$'s expression:
$$
f(a,b) =
- a + b - \left\lceil{\frac{a}{6} - \frac{5}{6}}\right\rceil - \left\lceil{\frac{a}{6} - \frac{1}{6}}\right\rceil + \left\lceil{\frac{a}{3} - \frac{1}{3}}\right\rceil + \left\lceil{\frac{a}{3} + \frac{1}{3}}\right\rceil + \left\lceil{\frac{a}{2} - \frac{1}{2}}\right\rceil + \left\lfloor{\frac{b}{6} - \frac{5}{6}}\right\rfloor + \left\lfloor{\frac{b}{6} - \frac{1}{6}}\right\rfloor - \left\lfloor{\frac{b}{3} - \frac{1}{3}}\right\rfloor - \left\lfloor{\frac{b}{3} + \frac{1}{3}}\right\rfloor - \left\lfloor{\frac{b}{2} - \frac{1}{2}}\right\rfloor \\
= f(5,23) = 3
$$
There are precisely $3$ twin prime averages in the range $[5, 23]$. See verification code link for larger examples.
Here is actually the next example (as $n$ grows):
$$
f(a,b) =
- a + b + \left\lceil{\frac{a}{30} - \frac{29}{30}}\right\rceil + \left\lceil{\frac{a}{30} - \frac{1}{30}}\right\rceil + \left\lceil{\frac{a}{30} + \frac{11}{30}}\right\rceil + \left\lceil{\frac{a}{30} + \frac{19}{30}}\right\rceil - \left\lceil{\frac{a}{15} - \frac{11}{15}}\right\rceil - \left\lceil{\frac{a}{15} - \frac{1}{15}}\right\rceil - \left\lceil{\frac{a}{15} + \frac{1}{15}}\right\rceil - \left\lceil{\frac{a}{15} + \frac{11}{15}}\right\rceil - \left\lceil{\frac{a}{10} - \frac{9}{10}}\right\rceil - \left\lceil{\frac{a}{10} - \frac{1}{10}}\right\rceil - \left\lceil{\frac{a}{6} - \frac{5}{6}}\right\rceil - \left\lceil{\frac{a}{6} - \frac{1}{6}}\right\rceil + \left\lceil{\frac{a}{5} - \frac{1}{5}}\right\rceil + \left\lceil{\frac{a}{5} + \frac{1}{5}}\right\rceil + \left\lceil{\frac{a}{3} - \frac{1}{3}}\right\rceil + \left\lceil{\frac{a}{3} + \frac{1}{3}}\right\rceil + \left\lceil{\frac{a}{2} - \frac{1}{2}}\right\rceil - \left\lfloor{\frac{b}{30} - \frac{29}{30}}\right\rfloor - \left\lfloor{\frac{b}{30} - \frac{1}{30}}\right\rfloor - \left\lfloor{\frac{b}{30} + \frac{11}{30}}\right\rfloor - \left\lfloor{\frac{b}{30} + \frac{19}{30}}\right\rfloor + \left\lfloor{\frac{b}{15} - \frac{11}{15}}\right\rfloor + \left\lfloor{\frac{b}{15} - \frac{1}{15}}\right\rfloor + \left\lfloor{\frac{b}{15} + \frac{1}{15}}\right\rfloor + \left\lfloor{\frac{b}{15} + \frac{11}{15}}\right\rfloor + \left\lfloor{\frac{b}{10} - \frac{9}{10}}\right\rfloor + \left\lfloor{\frac{b}{10} - \frac{1}{10}}\right\rfloor + \left\lfloor{\frac{b}{6} - \frac{5}{6}}\right\rfloor + \left\lfloor{\frac{b}{6} - \frac{1}{6}}\right\rfloor - \left\lfloor{\frac{b}{5} - \frac{1}{5}}\right\rfloor - \left\lfloor{\frac{b}{5} + \frac{1}{5}}\right\rfloor - \left\lfloor{\frac{b}{3} - \frac{1}{3}}\right\rfloor - \left\lfloor{\frac{b}{3} + \frac{1}{3}}\right\rfloor - \left\lfloor{\frac{b}{2} - \frac{1}{2}}\right\rfloor
\\
= f(7,47) = 4
$$
As you can see, the number of terms we directly consider in the double summation seems to grow exponentially.  This doesn't matter, however.  The twin prime conjecture doesn't care.

The floor-free formula can be derived as follows.  Clearly $\lfloor \dfrac{z}{d}\rfloor = \dfrac{z - z_{(d)}}{d},$ for all $z \in  \Bbb{Z}$ and $d \in \Bbb{Z}, d \neq 0$.
$$
f(a,b) = b - a - \\ \sum_{1 \neq cd \mid p_n\# \\ 2 \nmid c} (-1)^{\omega(d)}\left(\dfrac{b - x_{c,d} - (b  - x_{c,d})_{(cd)}}{cd} + \dfrac{x_{c,d} - a - (x_{c,d} - a)_{(cd)}}{cd} \right) = \\
-\sum_{1 \neq cd \mid p_n\#  \\ 2 \nmid c} \left((-1)^{\omega(d)}\dfrac{ (b - x_{c,d})_{(cd)} + (x_{c,d} - a)_{(cd)}}{cd}\right)
$$
But for minimal residues $z_{(e)},z'_{(e)} \in \Bbb{Z}$ we clearly have that $(z + z')_{(e)} \leq z_{(e)} + z_{(e)}'$, and thus we have a lower bounding mechanism (perhaps?).

Here is proof of the formula.

A: Too long to insert in a comment. I don't think the formula can have any practical use.
Also, for large values of n it does not give an exact result.
Yet this exact formula which has a similar complexity but which has no practical use:
$\pi_{\text{twin}} (n) = 1 + \\ \sum \limits_{k=1}^{\left\lfloor{\frac{n-1}{6}}\right\rfloor} {\left\lfloor \left( \displaystyle 1 + \displaystyle\sum_{a=1}^{\left\lfloor\frac{1+\sqrt{-1+6\cdot k}}{6}\right\rfloor} {\left( \left\lfloor\frac{-1+6\cdot k}{-1+6\cdot a}\right\rfloor - \left\lfloor\frac{-2+6\cdot k}{-1+6\cdot a}\right\rfloor \right)} + \displaystyle\sum_{a=1}^{\left\lfloor\frac{-1+\sqrt{-1+6\cdot k}}{6}\right\rfloor} {\left( \left\lfloor\frac{-1+6\cdot k}{1+6\cdot a}\right\rfloor - \left\lfloor\frac{-2+6\cdot k}{1+6\cdot a}\right\rfloor \right)}  \\  + \displaystyle\sum_{a=1}^{\left\lfloor\frac{1+\sqrt{1+6\cdot k}}{6}\right\rfloor} {\left( \left\lfloor\frac{1+6\cdot k}{-1+6\cdot a}\right\rfloor - \left\lfloor\frac{6\cdot k}{-1+6\cdot a}\right\rfloor \right)} + \displaystyle\sum_{a=1}^{\left\lfloor\frac{-1+\sqrt{1+6\cdot k}}{6}\right\rfloor} {\left( \left\lfloor\frac{1+6\cdot k}{1+6\cdot a}\right\rfloor - \left\lfloor\frac{6\cdot k}{1+6\cdot a}\right\rfloor \right)} \right)^{-1}\right\rfloor}$


text:
Q: React HOC Using useEffect() So i am using a HOC for general error handling purposes in react like this:
import React, { useState, useEffect } from 'react'
import Modal from '../../UI/Modal/Modal'
const WithErrorHandler = (WrappedComponent, axios) => {
    const NewComponent = props => {
        console.log('UseState')
        const [error, setError] = useState(null)
        console.log('runs')
        useEffect(() => {
            const req = axios.interceptors.request.use(config => {
                console.log('request intercepted')
                return config
            })
            const res = axios.interceptors.response.use(null, error => {
                setError(error)
                return Promise.reject(error)
            })

            return () => {
                axios.interceptors.request.eject(req)
                axios.interceptors.response.eject(res)
            }
        }, [])
        return (

                {console.log('render')}
                {error ? (
                    <Modal clickHandler={() => setError(null)}> {error.message}</Modal>
                ) : null}
                <WrappedComponent {...props} />

        )
    }
    return NewComponent
}
export default WithErrorHandler

The problem i have run into is that i have a component which fires an axios request in it's useEffect().
When i try to wrap this component with my WithErrorHandler the useEffect of the wrapped component fires first then the useEffect of HOC withErrorHandler runs. This causes the axios request to be made faster than the HOC could register the axios interceptors. Any ideas on how to fix this would be aprreciated.

A: You can define an intermediate state which prevents from rendering wrapped component.
const WithErrorHandler = (WrappedComponent, axios) => {
  const NewComponent = (props) => {

    const [ready, setReady] = useState(false); // HERE

    console.log("UseState");
    const [error, setError] = useState(null);
    console.log("runs");
    useEffect(() => {
      const req = axios.interceptors.request.use((config) => {
        console.log("request intercepted");
        return config;
      });
      const res = axios.interceptors.response.use(null, (error) => {
        setError(error);
        return Promise.reject(error);
      });

      setReady(true); // HERE

      return () => {
        axios.interceptors.request.eject(req);
        axios.interceptors.response.eject(res);
      };
    }, []);

    if (!ready) return null; // HERE

    return (

        {console.log("render")}
        {error ? (
          <Modal clickHandler={() => setError(null)}> {error.message}</Modal>
        ) : null}
        <WrappedComponent {...props} />

    );
  };
  return NewComponent;
};

What it does is that it makes sure that axios interceptor is initialized and it is good to render wrapped component.
Instead of if (!ready) return null; you can return a more sensible state from your HOC for instance, if (!ready) return
Initializing...

A: You need an extra render for the NewComponent callback to run, adding a conditional rendering on WrappedComponent should do the trick.
Notice that we set isFirstRender on promise success, change it dependenly on your use case.
const WithErrorHandler = (WrappedComponent, axios) => {
  const NewComponent = (props) => {
    const [isFirstRender, setIsFirstRender] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
      if (isFirstRender) {
        const req = axios.interceptors.request.use((config) => {
          return config;
        });

        // Check req success
        if (req.isSuccess) { setIsFirstRender(false); }

        const res = axios.interceptors.response.use(null, (error) => {
          setError(error);
          return Promise.reject(error);
        });

        return () => {
          axios.interceptors.request.eject(req);
          axios.interceptors.response.eject(res);
        };
      }
    }, [isFirstRender]);

    return (

        {error ? (
          <Modal clickHandler={() => setError(null)}> {error.message}</Modal>
        ) : null}
        {!isFirstRender && <WrappedComponent {...props} />}

    );
  };
  return NewComponent;
};


text:
Q: ArcGIS for Desktop 10.3 vs ArcGIS Pro I'm trying to upgrade to the 10.3 version of ArgGIS (currently, I have Advanced Desktop 10.2). When I go to the download page in my ESRI account, I'm given the option to download ArcGIS for Desktop or ArcGIS Pro

Which one should I download? What's the difference between these two?
I use ArcGIS Advanced Desktop 10.2 to do the following:

*

*network analysis using the Network Analyst tool

*spatial statistics using Spatial Analyst

*Lots of tasks processing raster data

*Extensive python scripting using the arcpy module in python 2.7

Basically I want the one that is the fastest and can do the most while also allowing me to do all the things I currently do in 10.2

A: You should choose "ArcGIS for Desktop."  This should give you the latest version (10.3) of the software you are currently using.
ArcGIS Pro is a new, separate program that was released by ESRI in January 2015.  You can read more about it here at ESRI's website.  They have made it available to people who already have ArcMap licenses.

A: 10.3 is a "point" update to what you're currently using, 10.2. ArcGIS Pro is a new desktop product currently at version 1.0.


text:
Q: In which thread does block driver issue commands to block device? I'm currently reading "Understanding The Linux Kernel" book, as I've understood block I/O request order is like this; user space call => vfs call => I/O scheduler call => block device driver call.
What I want to know is where the block device driver issue commands to block device (hard disk etc)? Does it issue commands in a dedicated scheduled kernel thread or in the user process thread where the block I/O request begin?

A: If you're not doing synchronous IOs, the user doing the write will just create transactions for the kjournald thread to dequeue (note here: I'm using an ext3 file system with journal=ordered, traces given using Linux 3.0-rc7)
We can have a look at what is happening by putting a breakpoint on the IO scheduler elevator_dispatch_fn method, for example deadline_dispatch_requests for the deadline IO scheduler:
There are two ways the device queue will run:
either called from the kjournald thread that will run (ext3 file system, mounted with the default commit=5, and is therefore scheduled to run every 5s)
#0  deadline_dispatch_requests (q=, force=0) at block/deadline-iosched.c:246
#1  __elv_next_request (q=<optimized out>) at block/blk.h:86
#2  blk_peek_request (q=q@entry=) at block/blk-core.c:1829
#3  scsi_request_fn (q=) at drivers/scsi/scsi_lib.c:1511
#4  __blk_run_queue (q=) at block/blk-core.c:305
#5  queue_unplugged (q=, depth=1, from_schedule=<optimized out>) at block/blk-core.c:2673
#6  blk_flush_plug_list (plug=plug@entry=, from_schedule=from_schedule@entry=false) at block/blk-core.c:2755
#7  blk_finish_plug (plug=plug@entry=) at block/blk-core.c:2762
#8  journal_commit_transaction (journal=journal@entry=) at fs/jbd/commit.c:412
#9  kjournald (arg=) at fs/jbd/journal.c:152
#10 kthread (_create=) at kernel/kthread.c:96
#11 kernel_thread_helper () at arch/x86/kernel/entry_64.S:1161
#12 ?? ()

Either called from an interrupt:
#0  deadline_dispatch_requests (q=, force=0) at block/deadline-iosched.c:246
#1  __elv_next_request (q=<optimized out>) at block/blk.h:86
#2  blk_peek_request (q=q@entry=) at block/blk-core.c:1829
#3  scsi_request_fn (q=) at drivers/scsi/scsi_lib.c:1511
#4  __blk_run_queue (q=) at block/blk-core.c:305
#5  blk_run_queue (q=q@entry=) at block/blk-core.c:339
#6  scsi_run_queue (q=q@entry=) at drivers/scsi/scsi_lib.c:449
#7  scsi_next_command (cmd=cmd@entry=) at drivers/scsi/scsi_lib.c:502
#8  scsi_end_request (requeue=<optimized out>, bytes=<optimized out>, error=<optimized out>, cmd=) at drivers/scsi/scsi_lib.c:574
#9  scsi_io_completion (cmd=cmd@entry=, good_bytes=<optimized out>) at drivers/scsi/scsi_lib.c:822
#10 scsi_finish_command (cmd=cmd@entry=) at drivers/scsi/scsi.c:847
#11 scsi_softirq_done (rq=<optimized out>) at drivers/scsi/scsi_lib.c:1456
#12 blk_done_softirq (h=<optimized out>) at block/blk-softirq.c:34
#13 __do_softirq () at kernel/softirq.c:238
#14 call_softirq () at arch/x86/kernel/entry_64.S:1210
#15 do_softirq () at arch/x86/kernel/irq_64.c:80
#16 invoke_softirq () at kernel/softirq.c:325
#17 irq_exit () at kernel/softirq.c:340
#18 smp_apic_timer_interrupt (regs=<optimized out>) at arch/x86/kernel/apic/apic.c:862
#19 <signal handler called>
#20 irq_stack_union ()

Now if you are doing synchronous calls, the request_fn method will run directly within the write system call, as seen below:
#0  deadline_dispatch_requests (q=, force=0) at block/deadline-iosched.c:246
#1  __elv_next_request (q=<optimized out>) at block/blk.h:86
#2  blk_peek_request (q=q@entry=) at block/blk-core.c:1829
#3  scsi_request_fn (q=) at drivers/scsi/scsi_lib.c:1511
#4  __blk_run_queue (q=) at block/blk-core.c:305
#5  queue_unplugged (q=, depth=1, from_schedule=<optimized out>) at block/blk-core.c:2673
#6  blk_flush_plug_list (plug=<optimized out>, from_schedule=from_schedule@entry=false) at block/blk-core.c:2755
#7  blk_flush_plug (tsk=<optimized out>) at include/linux/blkdev.h:880
#8  io_schedule () at kernel/sched.c:5669
#9  sleep_on_page (word=<optimized out>) at mm/filemap.c:182
#10 __wait_on_bit (wq=, q=q@entry=, action=action@entry=<sleep_on_page>, mode=mode@entry=2) at kernel/wait.c:202
#11 wait_on_page_bit (page=page@entry=, bit_nr=bit_nr@entry=13) at mm/filemap.c:571
#12 wait_on_page_writeback (page=) at include/linux/pagemap.h:394
#13 filemap_fdatawait_range (mapping=mapping@entry=, start_byte=start_byte@entry=0, end_byte=end_byte@entry=511) at mm/filemap.c:292
#14 filemap_write_and_wait_range (mapping=, lstart=0, lend=511) at mm/filemap.c:371
#15 filemap_write_and_wait_range (mapping=mapping@entry=, lstart=lstart@entry=0, lend=lend@entry=511) at mm/filemap.c:378
#16 vfs_fsync_range (file=, start=start@entry=0, end=end@entry=511, datasync=0) at fs/sync.c:176
#17 generic_write_sync (file=file@entry=, pos=pos@entry=0, count=count@entry=512) at fs/sync.c:242
#18 generic_file_aio_write (iocb=<optimized out>, iov=, nr_segs=1, pos=<optimized out>) at mm/filemap.c:2614
#19 do_sync_write (filp=, buf=<optimized out>, len=<optimized out>, ppos=) at fs/read_write.c:348
#20 vfs_write (file=file@entry=, buf=buf@entry="", count=<optimized out>, count@entry=512, pos=pos@entry=) at fs/read_write.c:377
#21 sys_write (fd=<optimized out>, buf="", count=512) at fs/read_write.c:429

A: To my current understanding, the user space process asks the system to return I/O. Then, the process will Wait for an interrupt from the kernel that the work is done. User space does not and should not care how the kernel retrieves the data. It might be that vfs found the data somewhere in its cache, so the I/O scheduler is not relevant from the user process.


text:
Q: AngularJS: Required attribute working for some fields but not others? So I have a form with nested forms within. When I click submit, and if there are any required fields that are not filled, I want the boxes to highlight and for there to be an alert displayed.
What I have now works for all the fields within the Company Information field - the alert displays properly, the fields are highlighted, and the form does not get submitted. However, this does not work for the fields within Product Information. Even if there are unfilled required forms, the form continues to get submitted, and there is no invalid highlight.
I did notice, however, that if I had invalid fields in Company Information and invalid fields in Product information, all fields have invalid highlights and it does not proceed to submit. However the case where only Product Information has invalid fields does not work. Also, if I remove ng-class="{failedSubmit:model.failedSubmit}" from the product form attribute, then even in the case where both Company and Product have invalid fields, invalid Product fields do not highlight at all - so I'm puzzled as to why totalForm does not cover all the forms its wrapping.
Anyone have any insight? Thanks!
So here is my HTML:
    <form name="totalForm" ng-class="{failedSubmit:model.failedSubmit}">

Company Information

                <form class="form-horizontal" role="form" name="company">

                                Company Name

                                <input class="form-control" id="companyName-md" name="companyName"
                                       ng-show=type="text"
                                       ng-model="model.companyName"
                                       required/>

                                Company
                                    Description

                               <textarea class="form-control" id="companyDesc-md" name="companyDesc"
                                                      ng-model="model.companyDesc" rows="5" required> </textarea>

                </form>

Product Information

                <form class="form-horizontal" name="product" ng-class="{failedSubmit:model.failedSubmit}">

                            Product
                                Type

                                <select class="form-control" id="productType-md" name="productType"
                                        ng-options="item for item in productTypeList" rows="3"
                                        ng-model="model.productType" required></select>

                            Product
                                Description

                                <textarea class="form-control" id="productDesc-md" name="productDesc"
                                          ng-model="model.productDesc" rows="5" required></textarea>

                </form>

        </form>

And here is my CSS class:
    form.failedSubmit .ng-invalid
{
    border:1px solid #f00;
}

And here is the relevant javascript code - this is fired upon pressing a submit button:
             if (!$scope.totalForm.$valid || !$scope.product.$valid){
                    $scope.showAlerts.push($scope.alerts[0]);
                    window.scrollTo(0, 0);
                    $timeout(function(){
                        $scope.showAlerts.pop();
                    }, 3000);

                    $scope.model.failedSubmit=true;
                }

A: I'm answering without testing it so let me know if you need example... first, my recommendation is to use one form, with different divs that you can toggle with ng-show. is there a special reason you want nested forms? second, labels don't need to have the required field and you also wrote twice few lines with the col-md-12. third, where are you submitting your form? I didn't see it in your code. let me know if you solved it.


text:
Q: Adding horizontal scrolling shadows effect I want to add an inset shadow to indicate that there is more content to scroll. The best way I can explain it is with a drawing:

I'm using Bootstrap as a framework and this is exactly what I'm working on:
Below is the code:

        #
        Heading
        Heading
        Heading
        Heading
        Heading
        Heading
        Heading
        Heading
        Heading

        1
        Cell
        Cell
        Cell
        Cell
        Cell
        Cell
        Cell
        Cell
        Cell

        2
        Cell
        Cell
        Cell
        Cell
        Cell
        Cell
        Cell
        Cell
        Cell

        3
        Cell
        Cell
        Cell
        Cell
        Cell
        Cell
        Cell
        Cell
        Cell

A: You can do Horizontal scrolling shadows effect with following background css.
.table-responsive{
  background-image: linear-gradient(to right, white, white), linear-gradient(to right, white, white), linear-gradient(to right, rgba(0, 0, 20, .50), rgba(255, 255, 255, 0)), linear-gradient(to left, rgba(0, 0, 20, .50), rgba(255, 255, 255, 0));
  /* Shadows */
  /* Shadow covers */
  background-position: left center, right center, left center, right center;
  background-repeat: no-repeat;
  background-color: white;
  background-size: 20px 100%, 20px 100%, 10px 100%, 10px 100%;
  background-attachment: local, local, scroll, scroll;
  }

Demo: https://jsfiddle.net/3oxq1ju6/1/


text:
Q: why doesnt my button work on addEventListener alongside Ejs and Express? I tried to make a Twitter-shaped place where I can make tweets(posts) and the posts display on the same page. also, each post has an Edit  that is display:none as default. When I push the Edit button I need to change that display to Block so I could make it visible and edit my comment using that space.
But my button won't work!
i wanted to test my button so i put a console.log for its Event but it doesnt work. why?
it would be great if you could help me with my problem and also suggest ways to achieve my ultimate goal(making comments and editing them in the same place).
index.js(first code)/
home.ejs(second code)
    const express = require('express');
    const app = express();
    const path = require('path');`enter code here`
    const methodOverride = require('method-override');
    let allPosts = [];

    app.use(express.urlencoded({extended :true }));
    app.set('view engine','ejs');
    app.use(methodOverride('_method'));

    app.get('/',(req,res) => {
        res.render('home.ejs')
    })

    app.post('/post/new',(req,res) => {
        const {username,post} = req.body;
        allPosts.push({username,post});
        res.render('home.ejs',{allPosts});
    })

    app.listen(3000,() => {
        console.log('Server is listening on port 3000!')
    })

    <!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>homepage</title>

Welcome to the Wall!

tell me whats on your mind today!

        <form action="/post/new" method="POST">
            <input type="text" name='username' placeholder="username">
            <textarea name='post' placeholder="how do you feel today?"></textarea>
            <button>Submit</button>
        </form>

        <% for (p in locals.allPosts) { %>
            <% let post = locals.allPosts  %>

                <%= post[p].username %> : <%= post[p].post %>
                <button class="edit">Edit</button><button>Delete</button>

            <textarea id="edit" name="edit" style='display:none'></textarea>
        <% } %>

A: document.querySelector('#edit') selects the unique element with the ID edit.
The element which has that ID is a textarea, not a button and it is generated in a loop so it probably isn't unique.
If you want to select an element based on the classes it is a member of, use . not # and don't put special characters (like #) in the classname itself.
If you want to select multiple elements, use querySelectorAll and loop over the multiple results it gives.

A: Try changing the button attribute to id.Like following.
 <button id="edit">Edit</button><button>Delete</button>

And then i your script
 let edit = document.querySelector('#edit');


text:
Q: What does it mean for an algebraic integer to have an abelian galois group? What does it mean for an algebraic integer to have an abelian galois group ?
I thought all algebraic integers had an abelian galois group ?
Beware, I'm new to galois theory. Maybe examples and counterexamples will help me.

A: To say that an algebraic integer $\alpha\in\mathbb{C}$ has an abelian Galois group just means that the extension $\mathbb{Q}(\alpha)/\mathbb{Q}$ is a Galois extension whose Galois group is abelian. The Kronecker-Weber theorem can be viewed as a statement that all such algebraic integers are sums of roots of unity.
There certainly are algebraic integers for which this is not the case; take any finite non-abelian Galois extension $K/\mathbb{Q}$, and let $\alpha$ be a primitive element for $K$ (which exists by the primitive element theorem). You may then have to multiply $\alpha$ by an integer to ensure that it is an algebraic integer, and not just an algebraic number, but it will of course generate the same extension $K$.

An example is rather hard to give explicitly because any non-abelian extension is necessarily of degree $\geq 6$, so there is not necessarily going to be a nice expression in radicals.
However, Mathematica informs me that one (and hence, any) of the roots of
$$x^6 - 3 x^5 + 6 x^4 - 11 x^3 + 12 x^2 + 3 x + 1$$
is a primitive element of the field $K=\mathbb{Q}(\sqrt[3]{2},\zeta_3)$, which has Galois group $\mathrm{Gal}(K/\mathbb{Q})\cong S_3$. Because the polynomial above is monic and has integer coefficients, its roots are algebraic integers.


text:
Q: Cordova playing html5 video I use cordova to build a hybrid signage application. I need to display a video on part of the screen when I try to display it then I don't see any video but sound. When I display video as fullscreen there is no problem. But I need to display it on part of the screen for example width: 400px height:400px top:100px left:100px

<video
id="videoContent_0" src="file:///storage/emulated/0/DS/MediaFiles/1004.mp4" autoplay="" style="z-index: 100; display: inline-block;">
</video>

A: Better solution to use cordova plugin then you can achieve wanted result.

Installation

cordova plugin add com.moust.cordova.videoplayer

Using: Just call the play method with a video file path as argument. The video player will close itself when the video will be completed.

VideoPlayer.play(
    "file:///android_asset/www/movie.mp4",
    {
        volume: 0.5,
        scalingMode: VideoPlayer.SCALING_MODE.SCALE_TO_FIT_WITH_CROPPING
    },
    function () {
        console.log("video completed");
    },
    function (err) {
        console.log(err);
    }
);


text:
Q: Using TimelineView to use in a custom view modifier I am looking to use the Timelineview to automatically update the background colour for a popup sheet that is displaying a list.
I am trying to figure out how to only call it once so I can use it for multiple sections in one list and in different views that display the type of data but with different information.
I have custom colours that I would like to use and call them from the assets catalogue.
A Sample Code:
 List {

        Section(header: Text("Ear")
            .modifier(SectionHeaderModifer())) {

            ForEach(Ear.indices, id: \.self) {index in

                VStack {
                    VStack() {
                        Spacer()
                         Text(Ear[index].name)
                            .modifier(NameModifier())
                    }
                    HStack {
                        Text(String(format: "$%.2f", Ear[index].value))
                            .modifier(ValueModifier())

                       Text(Ear[index].code)
                            .modifier(CodeModifier())
                    }
                    .frame(width:270)
                }

                .modifier(RowFormatModifier())

                .listRowBackground(Color("\(hour)").opacity(0.9))
                .listRowSeparator(.hidden)
            }
        }

 Section(header: Text("Nose")
            .font(.title)
            .fontWeight(.thin)) {

                ForEach(Nose.indices, id: \.self) {index in

                    VStack {
                        VStack() {
                            Spacer()
                             Text(Nose[index].name)
                                .modifier(NameModifier())
                        }
                        HStack {
                            Text(String(format: "$%.2f", Nose[index].value))
                                .modifier(ValueModifier())

                           Text(Nose[index].code)
                                .modifier(CodeModifier())
                        }
                        .frame(width:270)
                    }

                    .frame(width: 330, height:95, alignment: .center)

                    .modifier(RowFormatModifier())

                    .listRowBackground(Color("18").opacity(0.9))
                    .listRowSeparator(.hidden)

                    }
                }

The second section is using the Color("18") which is in reference to 1800 just for reference as well.  I have custom colour for each hour and thus why I am using the Timeline view to update the variable
The hour variable would be updated by the Timelineview as:
     TimelineView(.animation) {context in
        let now = Date()
        let hour = Calendar.current.component(.hour, from: now)

    }

I am not sure and I have tried and failed to try to put this in a ViewModifier where I could update the list row colour.
struct ChangeRowColor: ViewModifier {

func body(content: Content) -> some View {
    content

    TimelineView(.animation) {context in
        let now = Date()
        let hour = Calendar.current.component(.hour, from: now)

    }
    .listRowBackground(Color("\(hour)").opacity(0.9))
}

I know this is wrong because it can't see the hour variable.
Any suggestions?  Where should I call the timeline to determine the hour?  I only want to do it once and pass this into the different sections and other views that are of similar format.
Thanks!


text:
Q: count number of pages in a pdf file using python's pypdf2 library what is the exact code to find the total number of pages in a PDF using Py2PDF library? The old method that is .numPages is deprecated

A: using .pages method
from PyPDF2 import PdfReader

reader = PdfReader("US_Declaration.pdf")
readpdf = len(reader.pages)


text:
Q: msxml3.dll Access Denied I have the following code:
Function filejson(json)
  Dim objStream, strData
  Set objStream = CreateObject("ADODB.Stream")
  objStream.CharSet = "utf-8"
  objStream.Open
  objStream.LoadFromFile(json)
  strData = objStream.ReadText()
  filejson = strData
End Function
Function http2json(url)
  Set http = CreateObject("Microsoft.XmlHttp")
  http.open "GET", url, FALSE
  http.send ""                                   '<------- Line 13
  http2json=http.responseText
End Function
Function str2json(json,value)
  Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
  scriptControl.Language = "JScript"
  scriptControl.AddCode("x="& json & ";")
  str2json= scriptControl.Eval( "x"& value )
End Function
Function get_json_from_file(json,value)
  get_json_from_file=str2json(filejson(json),value)
End Function
Function get_json_from_http(url,value)
  get_json_from_http=str2json(http2json(url),value)
End Function
Function save_json_from_http(url,loc)
  Set fso = CreateObject("Scripting.FileSystemObject")
  fullpath = fso.GetAbsolutePathName(loc)
  Dim objStream, strData
  Set objStream = CreateObject("ADODB.Stream")
  objStream.CharSet = "utf-8"
  objStream.Open
  objStream.WriteText http2json(url)
  objStream.SaveToFile fullpath, 2
  save_json_from_http=fullpath
End Function
Wscript.Echo save_json_from_http("http://api.themoviedb.org/3/authentication/session/new?api_key=#####some_api_key_example#####&request_token=#####some_default_request_token######&_ctime_json_=1372670635.164760555","tmdb\temp\_tmdb_sock_w.164519518.2109")

When I run this code, I get the following error.

If I remove &request_token=#####some_default_request_token###### it works just fine.
I also tried this: I added again the request_token, and I just typed a random character in it, for example, rexfuest_token, and strangely it worked. It seems there's a wrong parse in msxml3.dll. with request_token word.
Ideas?

A: This problem could be related to the security issues in Windows. The best way to fix it is to replace Microsoft.XmlHttp/MSXML2.XMLHTTP with MSXML2.ServerXMLHTTP.
I see the topic is almost 2 years old and most likely the topic starter has solved is issue. I have experienced the same issue couple hours ago and google provided me several links. There are some of them:

*

*https://social.msdn.microsoft.com/Forums/en-US/1abda1ce-e23c-4d0e-bccd-a323aa7f2ea5/access-is-denied-while-using-microsoftxmlhttp-to-get-a-url-link-in-vbscript-help?forum=xmlandnetfx

*https://support.webafrica.co.za/index.php?/Knowledgebase/Article/View/615/41/msxml3dll-error-80070005-access-is-denied---loading-xml-file

*http://www.experts-exchange.com/Programming/Languages/Scripting/ASP/Q_27305017.html

A: Also can change URL from http to https. Me helps

A: Try with a more recent version:
Set http = CreateObject("Msxml2.XMLHttp.6.0")

It could also be an issue with your Internet security settings (see here). Open the Internet Options applet in the Control Panel, select the zone for the website (probably "Trusted sites") in the Security tab and click Custom level….

In the section Miscellaneous set Access data sources across domains to Enabled.

A: For me the solution was to add the URL in trusted sites.
Internet explorer browser > Tools > Internet options > Security > Trusted sites > Sites > Add the URL under "Add this website to the zone: " and click add and save.


text:
Q: Help in understanding the derivation of Einstein equations I am working through the derivation of the Einstein field equations by varying the Einstein-Hilbert action. I need some help in understanding certain steps.
The first question that I have concerns the variation of the Reimann tensor. I am trying to show that
$$\delta R^{\rho}_{\phantom{\rho}\sigma\mu\nu}=\nabla_{\mu}\left(\delta\Gamma^{\rho}_{\phantom{\rho}\nu\sigma}\right)-\nabla_{\nu}\left(\delta\Gamma^{\rho}_{\phantom{\rho}\mu\sigma}\right)$$
In order to show the above, it is necessary that
$$\Gamma^{\lambda}_{\phantom{\lambda}\nu\mu}\delta\Gamma^{\rho}_{\phantom{\rho}\lambda\sigma}-\Gamma^{\lambda}_{\phantom{\lambda}\mu\nu}\delta\Gamma^{\rho}_{\phantom{\rho}\lambda\sigma}=0$$
Why is this true?
The second question that I have concerns the term
$$\int\nabla_{\rho}A^{\rho}\sqrt{-g}\,\mathrm{d}^4x=0$$
where
$$A^{\rho}=g^{\sigma\nu}\delta\Gamma^{\rho}_{\phantom{\rho}\nu\sigma}-g^{\sigma\rho}\delta\Gamma^{\mu}_{\phantom{\mu}\mu\sigma}$$
Why is the integral zero?

A: The expression $$\Gamma^{\lambda}_{\phantom{\lambda}\nu\mu}\delta\Gamma^{\rho}_{\phantom{\rho}\lambda\sigma}-\Gamma^{\lambda}_{\phantom{\lambda}\mu\nu}\delta\Gamma^{\rho}_{\phantom{\rho}\lambda\sigma}=(\Gamma^{\lambda}_{\phantom{\lambda}\nu\mu}-\Gamma^{\lambda}_{\phantom{\lambda}\mu\nu})\delta\Gamma^{\rho}_{\phantom{\rho}\lambda\sigma}=0$$ follows from the assumption that the connection $\nabla$ is a Levi-Cevita connection, i.e. there is zero torsion. This means the connection coefficients $\Gamma^\kappa_{\mu\nu}$ reduce to the Christoffel symbols and so are symmetric under exchange of the bottom indices. There's nothing that forces us to take torsion to be zero really, it just makes things simple and seems to be correct insofar as observations seem to be perfectly consistent with it.
As for the integral $$\int\nabla_{\rho}A^{\rho}\sqrt{-g}\,\mathrm{d}^4x=0.$$ This vanishes because the integrand is a total divergence and as such only depends on the values of $A^\rho$ at the boundaries of the integration, which we take to be zero on physical grounds. To see how this works, we need the following result: $$\Gamma^\mu_{\mu\nu}=\frac{1}{\sqrt{-g}}\partial_\nu\sqrt{-g}$$ (you can look up the derivation for this if you want, it's not very illuminating imo). Using this, we can re-express the integrand as
\begin{align*}
\sqrt{-g}\,\nabla_{\rho}A^{\rho}&=\sqrt{-g}(\partial_\rho A^\rho+\Gamma^\rho_{\rho\nu}A^\nu)\\&=\sqrt{-g}(\partial_\rho A^\rho+\frac{1}{\sqrt{-g}}\partial_\nu\sqrt{-g}A^\nu)\\&=\sqrt{-g}\partial_\rho A^\rho+A^\nu\partial_\nu\sqrt{-g}\\&=\partial_\rho(A^\rho\sqrt{-g})
\end{align*}
So now we have a genuine four-divergence. Applying the familiar divergence theorem, we arrive at $$\int_M\nabla_{\rho}A^{\rho}\sqrt{-g}\,\mathrm{d}^4x=\int_M\partial_\rho(A^\rho\sqrt{-g})\,\mathrm{d}^4x=\int_{\partial M}n_\rho A^{\rho}\sqrt{-h}\,\mathrm{d}^3x,$$ where $h_{\mu\nu}=g_{\mu\nu}+n_\mu n_\nu$ is the induced metric on the hypersurface $\partial M$ with unit normal vector $n_{\mu}$.
Enforcing that $A^\rho$ is zero on $\partial M$ (actually $A^\rho$ needs to vanish sufficiently quickly as one approaches the boundary) then gives the desired result. This is essentially equivalent to the statement that stuff happening in one spot doesn't have an effect on things at sufficiently large distances away, which is reasonable since physical effects are bounded by the speed of light and any physically realistic configuration will have only existed for a finite time (if you're specifically studying the asympotic behaviour of a system this may become a problem however).
This trick is used in a lot of places (particularly in deriving equations of motion such as you are doing) because it lets you move the derivative around in the integrand. If we let $A(x)$ and $B(x)$ be two functions such that $A(x)\rightarrow 0$ as $x\rightarrow\pm\infty$, then $$\int B(x)\partial A(x)\,dx=\left[A(x)B(x)\right]_{-\infty}^{\infty}-\int A(x)\partial B(x)\,dx=-\int A(x)\partial B(x)\,dx.$$
EDIT: As requested in the comments, I've expanded a bit on how the integrand is considered a four-divergence.


text:
Q: Lubuntu 14.04 no sound, can't install pulseaudio I have two PCs I've installed LUbuntu 14.04 on. On one sound is fine and pulseaudio was installed during the OS installation. On the other pulseaudio is missing, and there is no sound at all, not from audio jack nor from HDMI.
When typing sudo apt-get install pulseaudio I get this error:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 pulseaudio : Depends: libpulse0 (= 1:4.0-0ubuntu11) but 1:4.0-0ubuntu11.1 is to be installed
              Recommends: pulseaudio-module-x11 but it is not going to be installed
              Recommends: gstreamer0.10-pulseaudio but it is not going to be installed
              Recommends: rtkit but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

A: You try to install the pulseaudio (1:4.0-0ubuntu11) from the trusty repositories. But you have enabled trusty-updates, therefore libpulse0 (1:4.0-0ubuntu11.1) is to be installed.
The only explanation is that you have forgotten to start the command
sudo apt-get update

After that
sudo apt-get install --reinstall pulseaudio

and to upgrade the whole system
sudo apt-get dist-upgrade

A: Try this:
sudo apt-get remove libpulse0

sudo apt-get autoremove

And then try to install pulseaudio
sudo apt-get install pulseaudio

I had the same issue, but this helped for me.


text:
Q: How do I go about creating a flyout panel with JQuery or CSS3? Essentially I want to be able to hover-over my links in a left vertical column and have a panel pop-out on the right. Here's a screenshot of what I'm looking to achieve. Again, I'm a complete noob when it comes to JQuery, so if there's a strictly css3 way to do this, I'm all ears.
http://flic.kr/p/cTsG9E

A: There is probably a way to do this with CSS3 transitions. These may not be supported by all browsers.
The easiest would be to use jQuery.
Hover Over Me
. . .

I should not be using inline styles

Then in your JS:
$("#trigger-link").hover(function() {
    $("#target").show();
}, function() {
    $("#target").hide();
});

This is a very simple example. But it should be a good place to start.

A: Also look at jquery animation for easy cross browser animations.
http://api.jquery.com/animate/


text:
Q: Doing perspective correction per component in a fragment shader I'm currently trying to emulate an NVIDIA GPU but I have some problems with setting input variables from a shader. I require something like this in glsl:
layout(location = 0) in noperspective vec4 value1;
layout(location = 0) in smooth vec4 value1_alias;

Sadly that code is illegal in openGL. Interpolation aliasing is not permitted. In general, I want certain components of the vector to be "perspective corrected" and others to be obtained linearly. it's vital that this is done in the correct order for each component. I also must use the exact same attribute slot (location), I'm emulating a GPU thus each attribute is set by it and I cannot duplicate values.
What I tried doing was to take all values as noperspective and do the perspective correction inside the shader. My approach was simply multiply the value by (1 / glFragCoord.w). Sadly this does not seem to work. I'm not sure if the theory I'm following is flawed or the glFragCoord.w value I'm recieving from my fragment shader is incorrect. (I do set glPosition with w as 1.0)
With all this in mind? What approach could I take to do the perspective correction on independent values?


text:
Q: EF Code first, Insert record to auto generated table I Create Two class in Models folder Like this:
Material.cs:
public class Material
{
    public int MaterialId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Project> Project { get; set; }
}

Project.cs:
 public class Project
{
    [Key]
    public int ProjectId { get; set; }
    [Required]
    public string Name { get; set; }
    public DateTime Date { get; set; }

    public ICollection<Material> Material { get; set; }

}

Entity framework code first generate a new table with name MaterialProjects in my SQL server database. I use scaffolding to generate Controllers and Views.
MaterialProjects have two Columns like this:

*

*Material_MaterialId

*Project_ProjectId
In 1st step I add a new project record into Projects table.
In 2nd step I add a new material record into Materials table.
My question is: How can I add a record to MaterialProjects table. I cant access   this entity in my code.
UPDATE:
Have I do this in Materials controller create Action method?
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include = "MaterialId,Name,")] Material material)
    {
        if (ModelState.IsValid)
        {
            db.Materials.Add(material);
            //what to do here
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        return View(material);
    }

A: you dont have to add in that table it will be done by EF automaticaly . The only thing you need to do id to add your entities correctly  and the junction table will be filled by EF you dont have to do that .
In controller  you can do like this  .I tested with console application.

            [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include = "MaterialId,Name,")] Material material)
    {
        if (ModelState.IsValid)
        {

         using (var ctx = new SampleDbContext())
        {
            -- here context is the DBCOntext class of your application
            --var mat = new Material
            --{
            --    Name = "A",
            --    Project = new List<Project> {new Project {Name = "P1", Date = DateTime.Now}}
            --};

            ctx.Materials.Add(material);
            await db.SaveChangesAsync();

        }

            return RedirectToAction("Index");
        }

        return View(material);
    }

A: EF automatically handles the Many-Many junction tables.In your case, say you want to insert a new Project with two new Material entities. You can do this by assigning the materials collection to the Material collection of the new Project entity. EF will inset a new Project and two new materials and will automatically populate the junction table as well
Updating after OP updates the question
Hoping that you have already have the Project entity inserted (say, the id of that project is 100). So while adding new Material entity:
var proj = context.Projects.Find (100);
newMaterialObject.Projects.Add (proj);
context.SaveChanges();


text:
Q: iniciar sesion de acuerdo al rol indicado estoy creando un login en mvc asp.net y estoy usando sql server, en el cual dependiendo del rol va poder accerder al sistema, pero rol lo tengo en otra tabla llamada tiporol pero noce como llamar ese valor del rol dentro de usuarios ya que usuarios y rol estan relacionadas, pero al momento que yo mando llamar rol no me deja acceder a la vista que le corresponde solo me aparece llena todos los campos y esto es lo que tengo de mi codigo.
 [HttpPost]

        public ActionResult Login(string usuario, string contraseña,string rol)
        {
            if (!string.IsNullOrEmpty(usuario) && !string.IsNullOrEmpty(contraseña) && !string.IsNullOrEmpty(rol))
            {
                var pass = Encrypt.Hash(contraseña);

                var user = db.Usuarios.FirstOrDefault(e => e.numeroUsuario == usuario && e.contraseña == contraseña);
               var roles = db.TipoRols.FirstOrDefault(a => a.Roles == rol );

                if (roles.Roles == "administrador")
                {

                    FormsAuthentication.SetAuthCookie(roles.Roles, true);
                    Session["nombre"] = user.nombre;
                    Session["apellidos"] = user.apellidos;
                    return RedirectToAction("IndexAdministrador", "Home");

                }
                else

            if (roles.Roles == "tecnico")
                {

                    FormsAuthentication.SetAuthCookie(roles.Roles, true);
                    Session["nombre"] = user.nombre;
                    Session["apellidos"] = user.apellidos;
                    return RedirectToAction("IndexTecnico", "Home");

                }
 else
                {
                    return RedirectToAction("Login", new { message = "No reconocemos tus datos" });

                }
            }

            else
            {
                return RedirectToAction("Login", new { message = "Llena todos los campos para poder iniciar secion" });

            }

        }

A: Si tu usuario tiene referencia a un rol
var rolUsuario = db.TipoRols.where(a => a.Id== user.idRol ).FirstOrDefault();


text:
Q: Properly configuring a dotnet (ASP.NET Core 2.1) environment on CentOS / Linux I'm stuck, I'm really hoping someone can help or at least point me in the right direction. My end goal is to get my ASP.NET Core 2.1 app running on a CentOS Linux box. Since I'm using a mongo db in my actual app and wanted to eliminate any possible issues with that, I published a plain-jane asp.net core 2.1 mvc app, no authentication, and deployed it to a virtual host on my centos 7 box (apache upgraded via CoreIT to 2.4.37 since centos distros still deploy the older 2.4.6 version).
For the scope of this question I think I just need to make sure my reverse proxy is working properly and need help in pinning down that. I've followed instructions from here and the Microsoft setup doc from here. These 2 links are what I've been working with mainly.
When my app service is running, I can do a curl localhost:5000 and see the correct html of my homepage being returned. When I try from command line again with test.mydomain.com or test.mydomain.com:5000 it just times out. If I go to my app's conf (test.mydomain.com.conf in /etc/httpd/sites-available) and remove the ProxyPass, ProxyPassReverse and ProxyPreserveHost lines then I can hit test.mydomain.com from the outside with a browser and get my index.html file up and displaying properly (this is just one index.html file and not a part of the dotnet app though). It's only when I add the below back into my conf file it just hangs up when I try and hit the URL. I'm not sure what to look for in journalctl or maybe I should tail a specific log file to find out what it's waiting on and why it's taking so long.
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:5000/
ProxyPassReverse / http://127.0.0.1:5000/

Somehow is seems like my reverse proxy isn't set up right to be accessed from outside the box.
The rest of my app's config below.
<VirtualHost *:*>
        RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME}</VirtualHost>

<VirtualHost *:80>
    ServerName test.mydomain.com
    DocumentRoot /var/www/test.mydomain.com/public_html
    ErrorLog logs/dashboard.crtv1.com.errorlog
    CustomLog logs/dashboard.crtv1.com.access_log combined
</VirtualHost>

A: I think I addressed the issue although I'm not sure what issues I was actually having at the time of posting. I ended up through process of elimination and curl to find another service was running and using port 5000 in another virtual host - we're doing development and need a test, staging and production set of virtual hosts. Also I found I had some code in my app (UseUrls) that was specifically stating to use port 5000 so multiple copies of it within the same environment had resource conflicts. I'll circle back and update which environments will use which ports and hopefully have a nice set up.


text:
Q: Use a React Component in Redux form "Field" Component I have to implement a react-phone-number package in a redux form. I am new to reactjs and redux. I have to tranform my React code to one of the field in redux form. Here is the react code.
import React from 'react';
    import ReactDOM from 'react-dom';
    import IntlTelInput from 'react-intl-tel-input';
    import '../node_modules/react-intl-tel-input/dist/main.css';
    import '../node_modules/react-intl-tel-input/dist/libphonenumber.js';

    const loadJSONP = (url, callback) => {
      const ref = window.document.getElementsByTagName('script')[0];
      const script = window.document.createElement('script');
      script.src = `${url + (url.indexOf('?') + 1 ? '&' : '?')}callback=${callback}`;
      ref.parentNode.insertBefore(script, ref);
      script.onload = () => {
        script.remove();
      };
    };

    const lookup = (callback) => {
      loadJSONP('http://ipinfo.io', 'sendBack');
      window.sendBack = (resp) => {
        const countryCode = (resp && resp.country) ? resp.country : '';
        callback(countryCode);
      }
    };

    const handler = (status, value, countryData, number, id) => {
      console.log(status, value, countryData, number, id);
    };

    ReactDOM.render(
      <IntlTelInput
        onPhoneNumberChange={ handler }

        preferredCountries={['us','ca']}
        css={ ['intl-tel-input', 'form-control'] }
      />,
      document.getElementById('root'),
    );

Now I want to somehow use it in "Field" component of Redux-Form which is something like below.
const FieldCountryCode = ({
  name,
  label,
  placeholder,
  value,
  showsRequired,
}: PropsT) => (
  <Field
    name={name}
    component={IntlTelInput}
    props={{
      label,
      placeholder,
      type: 'tel',
      value,
      showsRequired,
    }}
  />
);

export default FieldCountryCode;

The Problem I am facing is that when I try to do something with the component attribute of Field it loses its CSS contents. Here is the link to describe how actually it should work. link

A: Try removing this line
import '../node_modules/react-intl-tel-input/dist/main.css';

from the above component and add it to the top of your main App.js file in the root.
If that doesn't work than try copying the file itself and include it in your index.html directly using the HTML <link /> tag. (Just make sure you create the copy of that file and add it in your public folder. You won't be able to refer it from the node_modules directory.)

A: If my understanding of the docs here is correct, the props property is used to pass down props to the component actually being rendered, with the component prop. In other words, do <Field component={IntlTelInput} props={{ test: 123 }} /> and the Field component does something along the lines of <IntlTelInput test={123} />.
The solution is to put the appropriate props needed in the Field's props prop. Given your first example, it should be something like this:
<Field
  name={name}
  component={IntlTelInput}
  props={{
    preferredCountries: ["us", "ca"],
    css: ["intl-tel-input", "form-control"],
    onPhoneNumberChange: onChange,
  }}
/>

The lack of styling was probably due to the missing css prop. Also remember to define that onChange prop to this component.


text:
Q: A Tricky Limit: $(1 - \frac{c}{n}\log n )^{1-n}$ I'm stuck with this limit $(1 - \frac{c}{n}\log n )^{1-n}$ as $n \rightarrow \infty$ where $c < 1$. I tried to plot the limit and it looks like it goes to infinity, although very slowly, but I can't prove it. Any ideas?

A: Near $x=0$, $\log(1+x)=x+O(x^2)$ so as $n\to\infty$, we get that
$$
\begin{align}
(1-n)\log(1-\frac{c}{n}\log(n))
&=(1-n)\left(-\frac{c}{n}\log(n)+O\left(\left(\frac{\log(n)}{n}\right)^2\right)\right)\\
&=\frac{c(n-1)}{n}\log(n)+O\left(\frac{\log(n)}{n}\log(n)\right)\\
&\to\infty\text{ (like }c\log(n)\text{)}
\end{align}
$$
if $c>0$. Thus, $(1 - \frac{c}{n}\log n )^{1-n}\to\infty$ like $n^c$.

A: You can factor out $(1 - {c \over n}\log(n))$ which converges to $1$ and thus you are looking for
$$\lim_{n \rightarrow \infty} (1 - {c \over n}\log(n))^{-n}$$
$$= \lim_{n \rightarrow \infty} \bigg((1 - {c \over n}\log(n))^{{n \over c \log n}}\bigg)^{-c\log n}$$
Since ${\displaystyle \lim_{\epsilon \rightarrow 0} (1 - r)^{1 \over r} = {1 \over e}}$, the expression inside the large parentheses goes to ${1 \over e}$ as $n$ goes to infinity. Since $({1 \over e})^{-c\log n} = n^c$, this means the expression diverges to infinity as $n^c$ does. (Well faster than $n^{c'}$ for any $c' < c$.)

A: Some graph samples shows that as x gets larger the limit goes larger.

Edit:
I removed my steps due to corrections suggested below.


text:
Q: Why is there a line above and below my SVG in my html? I am trying to use an SVG to create a curve look on my page. I have the SVG's inside of the page already and they look good on desktop screens, but when I view the page on mobile there are small lines that appear above and below the svg and I want them gone but do not know how.
Pictures of issue
Line near nav bar
Lines above and below picture
I would appreciate some help.
I have already tried setting the width and height to 100%.
Again they ONLY appear on Mobile.
I obtained the svg from https://getwaves.io/
Here is a link to the page https://okctechhelp.com/

        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Arvo:ital,wght@0,400;0,700;1,400;1,700&family=Heebo:wght@100;200;300;400;500;600;700;800;900&family=Outfit:wght@100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
        <link rel="stylesheet" href="styles/style.css">

                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

                </button>

        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="#050038" fill-opacity="1" d="M0,128L48,122.7C96,117,192,107,288,96C384,85,480,75,576,106.7C672,139,768,213,864,240C960,267,1056,245,1152,245.3C1248,245,1344,267,1392,277.3L1440,288L1440,0L1392,0C1344,0,1248,0,1152,0C1056,0,960,0,864,0C768,0,672,0,576,0C480,0,384,0,288,0C192,0,96,0,48,0L0,0Z"></path></svg>

Need some help?

Need some help?

Technology can be a big hastle. Schedule the help you need right now, and lets get your problem solved.

                            <button class="btn btn-lg btn-primary">Get Help</button>

            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="#3f53d9" fill-opacity="1" d="M0,128L48,122.7C96,117,192,107,288,96C384,85,480,75,576,106.7C672,139,768,213,864,240C960,267,1056,245,1152,245.3C1248,245,1344,267,1392,277.3L1440,288L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path></svg>

        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="#3f53d9" fill-opacity="1" d="M0,128L48,122.7C96,117,192,107,288,96C384,85,480,75,576,106.7C672,139,768,213,864,240C960,267,1056,245,1152,245.3C1248,245,1344,267,1392,277.3L1440,288L1440,0L1392,0C1344,0,1248,0,1152,0C1056,0,960,0,864,0C768,0,672,0,576,0C480,0,384,0,288,0C192,0,96,0,48,0L0,0Z"></path></svg>

  [1]: https://i.stack.imgur.com/hL3UG.png
  [2]: https://i.stack.imgur.com/iWUiO.png

A: With the HTML you provided I see no lines in the svg, usually it's a browser Dev Tools issue when you have a zoom (in or out).
Try changing this:

to 100% and see if it's solved.
Edit:
Now I can see the issue, in the head tag you must add:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
To make this website responsive, the other way it's scaling down and not having a responsive behavior. See the docs for further information


text:
Q: Redirect Server IP subdirectory to Hostname in .htaccess file on apache I am trying to redirect my server IP to my hostname using mod_rewrite on my WordPress .htaccess file.
This is what I've tried -
  <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^X\.XXX\.XXX\.XX$
    RewriteRule (.*)$ http://www.example.com/$1 [R=301,L]
  </IfModule>

This works fine if I visit the IP address directly but if I visit the IP with a subdirectory path it does not redirect.
For example:
IP XX.XX.XX.XX - Redirects fine
IP XX.XX.XX.XX/phpmyadmin - NO redirection

Anyone have any idea what is wrong with my query. Any help is appreciated.

UPDATE:
Here is my .htaccess file having implemented the solution from @MrWhite, but it's still not working.
RewriteCond %{HTTP_HOST} !=www.XXXX.co.uk
RewriteRule (.*) https://www.XXXX.co.uk/$1 [R=301,L]

# BEGIN WP Security
#AIOWPS_BASIC_HTACCESS_RULES_START
<Files .htaccess>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order deny,allow
Deny from all
</IfModule>
</Files>
ServerSignature Off
LimitRequestBody 10485760
<Files wp-config.php>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order deny,allow
Deny from all
</IfModule>
</Files>
#AIOWPS_BASIC_HTACCESS_RULES_END
#AIOWPS_DISABLE_INDEX_VIEWS_START
Options -Indexes
#AIOWPS_DISABLE_INDEX_VIEWS_END
# END WP Security

#AIOWPS_BASIC_HTACCESS_RULES_END
# END WP Security

# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Options -Indexes

A:
This works fine if i visit the IP address directly but if i visit the IP with a sub directory path it does not redirect.

This sounds like you've put the directives in the wrong place. If you've put the rule at the end of the file, after the WordPress code block then your redirect will only be triggered for requests to the document root (the homepage) since the WP code block effectively ignores any request for the homepage itself (since mod_dir triggers the subrequest for index.php - the WP front-controller).
However, any request for a "sub directory", ie. a virtual URL-path, will be routed to the WP front-controller before your rule has a chance to be triggered.
You need to move your rule to the top of the file, importantly before the # BEGIN WordPress code block.
You do not need the <IfModule> wrapper and you do not need to repeat the RewriteEngine On directive, since this will already occur later in the file inside the WP code block.

RewriteCond %{HTTP_HOST} ^X\.XXX\.XXX\.XX$
RewriteRule (.*)$ http://www.example.com/$1 [R=301,L]

Instead of checking that the requested hostname is the IP address, you could instead check that the requested hostname is not your canonical hostname. You will catch requests for non-www (or www) as well and you are not tied to an IP address.
For example:
RewriteCond %{HTTP_HOST} !=www.example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

The ! prefix on the CondPattern negates the expression. The = operator makes this a lexicographic string comparison, not a regex. So no need to backslash-escape the literal dots. (This would also make it easier to match IP addresses, eg. =203.0.113.111.)


text:
Q: absolute div not show in container bootstrap 4 I have this code for show div with absolute position inside div with container using bootstrap 4.
Code:

    text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo

But In action div with absolute position not show true in container(show outer of container). how do fix this problem?!
Demo jsfiddle

A: Using positions in your divs sounds strange. In any case I would suggest to wrap your content into a row:

.container {
    height: 500px;
    background-color: #eee;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

            text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text
            demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo
            text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text
            demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo
            text demo text demo text demo

A: There is padding in the container, again you use w-100 that means 100%, padding, and 100% width conflicting themselves. just remove the padding from container will solve the problem

.container{
  height:500px;
  background-color:#eee;
  padding: 0px;
}

    text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo text demo


text:
Q: Tensorflow / keras: How to train CNN with custom image files (.FITS images) I'm currently trying to train a CNN (EfficientNet) using .FITS image files, but I believe this would apply to other image types also. This kind of image requires the library astropy in order to be opened, and in my case, in order to access the image data, I simply type:
from astropy.io import fits
path = "path/to/file.fits"
hdul = fits.open(path)
image = hdul[1].data

This variable image will then have type numpy.ndarray. I first tried using keras' image_dataset_from_directory and, as expected, it didn't work out. I then checked out tf.data over here: https://www.tensorflow.org/tutorials/load_data/images#using_tfdata_for_finer_control. I tried creating a similar pipeline and it all worked out up until the decode_img function. Since I'm not dealing with a jpeg I tried making a workaround so that I get:
data_dir = home/astro/train
class_names = np.array(sorted([item.name for item in data_dir.glob('*')]))
# class_names = ["stars", "galaxies"]

def get_label(file_path):
    parts = tf.strings.split(file_path, os.path.sep)
    one_hot = parts[-2] == class_names
    return tf.argmax(one_hot)

def decode_img(img):
    hdul = fits.open(img)
    data = hdul[1].data
    data = data.reshape((data.shape[0], data.shape[1], 1))
    data = np.pad(data, [(0,0), (0,0), (0, 2)], 'constant') # padding to create 3 channels
    img = tf.convert_to_tensor(data, np.float32)
    return tf.image.resize(img, [img_height, img_width])

def process_path(file_path):
    label = get_label(file_path)
    img = decode_img(file_path)
    return img, label

And it actually works out pretty well, in a way that when I print process_path I get two tensors, one for the image and one for the label with the correct shapes and values that I want.
THE PROBLEM:
By following the tutorial, when I get to:
AUTOTUNE = tf.data.experimental.AUTOTUNE
train_ds = train_ds.map(process_path, num_parallel_calls=AUTOTUNE)
val_ds = val_ds.map(process_path, num_parallel_calls=AUTOTUNE)

I get the following error:
TypeError                                 Traceback (most recent call last)
 in
      1 AUTOTUNE = tf.data.experimental.AUTOTUNE
      2
----> 3 train_ds = train_ds.map(process_path, num_parallel_calls=AUTOTUNE)
      4 val_ds = val_ds.map(process_path, num_parallel_calls=AUTOTUNE)

~/anaconda3/lib/python3.7/site-packages/tensorflow/python/data/ops/dataset_ops.py in map(self, map_func, num_parallel_calls, deterministic)
   1700           num_parallel_calls,
   1701           deterministic,
-> 1702           preserve_cardinality=True)
   1703
   1704   def flat_map(self, map_func):

~/anaconda3/lib/python3.7/site-packages/tensorflow/python/data/ops/dataset_ops.py in __init__(self, input_dataset, map_func, num_parallel_calls, deterministic, use_inter_op_parallelism, preserve_cardinality, use_legacy_function)
   4082         self._transformation_name(),
   4083         dataset=input_dataset,
-> 4084         use_legacy_function=use_legacy_function)
   4085     if deterministic is None:
   4086       self._deterministic = "default"

~/anaconda3/lib/python3.7/site-packages/tensorflow/python/data/ops/dataset_ops.py in __init__(self, func, transformation_name, dataset, input_classes, input_shapes, input_types, input_structure, add_to_graph, use_legacy_function, defun_kwargs)
   3369       with tracking.resource_tracker_scope(resource_tracker):
   3370         # TODO(b/141462134): Switch to using garbage collection.
-> 3371         self._function = wrapper_fn.get_concrete_function()
   3372         if add_to_graph:
   3373           self._function.add_to_graph(ops.get_default_graph())

~/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/function.py in get_concrete_function(self, *args, **kwargs)
   2937     """
   2938     graph_function = self._get_concrete_function_garbage_collected(
-> 2939         *args, **kwargs)
   2940     graph_function._garbage_collector.release()  # pylint: disable=protected-access
   2941     return graph_function

~/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_garbage_collected(self, *args, **kwargs)
   2904       args, kwargs = None, None
   2905     with self._lock:
-> 2906       graph_function, args, kwargs = self._maybe_define_function(args, kwargs)
   2907       seen_names = set()
   2908       captured = object_identity.ObjectIdentitySet(

~/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)
   3211
   3212       self._function_cache.missed.add(call_context_key)
-> 3213       graph_function = self._create_graph_function(args, kwargs)
   3214       self._function_cache.primary[cache_key] = graph_function
   3215       return graph_function, args, kwargs

~/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   3073             arg_names=arg_names,
   3074             override_flat_arg_shapes=override_flat_arg_shapes,
-> 3075             capture_by_value=self._capture_by_value),
   3076         self._function_attributes,
   3077         function_spec=self.function_spec,

~/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
    984         _, original_func = tf_decorator.unwrap(python_func)
    985
--> 986       func_outputs = python_func(*func_args, **func_kwargs)
    987
    988       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

~/anaconda3/lib/python3.7/site-packages/tensorflow/python/data/ops/dataset_ops.py in wrapper_fn(*args)
   3362           attributes=defun_kwargs)
   3363       def wrapper_fn(*args):  # pylint: disable=missing-docstring
-> 3364         ret = _wrapper_helper(*args)
   3365         ret = structure.to_tensor_list(self._output_structure, ret)
   3366         return [ops.convert_to_tensor(t) for t in ret]

~/anaconda3/lib/python3.7/site-packages/tensorflow/python/data/ops/dataset_ops.py in _wrapper_helper(*args)
   3297         nested_args = (nested_args,)
   3298
-> 3299       ret = autograph.tf_convert(func, ag_ctx)(*nested_args)
   3300       # If `func` returns a list of tensors, `nest.flatten()` and
   3301       # `ops.convert_to_tensor()` would conspire to attempt to stack

~/anaconda3/lib/python3.7/site-packages/tensorflow/python/autograph/impl/api.py in wrapper(*args, **kwargs)
    256       except Exception as e:  # pylint:disable=broad-except
    257         if hasattr(e, 'ag_error_metadata'):
--> 258           raise e.ag_error_metadata.to_exception(e)
    259         else:
    260           raise

TypeError: in user code:

    :17 process_path  *
        img = decode_img(file_path)
    :7 decode_img  *
        hdul = fits.open(img)
    /home/marcostidball/anaconda3/lib/python3.7/site-packages/astropy/io/fits/hdu/hdulist.py:154 fitsopen  *
        if not name:
    /home/marcostidball/anaconda3/lib/python3.7/site-packages/tensorflow/python/autograph/operators/logical.py:29 not_
        return _tf_not(a)
    /home/marcostidball/anaconda3/lib/python3.7/site-packages/tensorflow/python/autograph/operators/logical.py:35 _tf_not
        return gen_math_ops.logical_not(a)
    /home/marcostidball/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/gen_math_ops.py:5481 logical_not
        "LogicalNot", x=x, name=name)
    /home/marcostidball/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:493 _apply_op_helper
        (prefix, dtypes.as_dtype(input_arg.type).name))

    TypeError: Input 'x' of 'LogicalNot' Op has type string that does not match expected type of bool.

Does anyone know of a way to fix this? I searched around for ways to train a CNN using directly a numpy array such as the one that I get before doing the tensor conversion and found some examples using MNIST with standalone keras. I'd like to apply the usual data augmentation and batch training, though, and I'm not sure if this is possible by following something such as what I've seen.
Thanks a lot!

A: I ran into the same issue. What I think the problem is (but I do not know for sure) is that when you make train_ds it is saying sort of "this will happen when we actually want the next batch". astropy.io.fits expects to run when it is called so complains when the file names it is given don't yet exist (or are place holders).
The solution I came up with was to write code to load the fits files without using astropy. You can get it from this GitHub Repo. It's probably buggy as you like but it works for me to open fits images (I have not figured out tables yet).


text:
Q: Darle formato json a datos Tengo este código que lo que hace es realizar búsquedas con unos api.
Quisiera darle formato json para que sea más amigable a la hora de hacer consultas y pintar los datos.
Actualmente me devuelve la información así:
Array
(
    [
    0
] => Array
        (
            [nombre
] => The Mixed Tape
            [longDescription
] =>
            [imagen
] => https: //video-ssl.itunes.apple.com/itunes-assets/Video128/v4/f9/9b/55/f99b554c-24fa-136f-5bb4-0590931573d6/mzvf_5528930120957315186.640x480.h264lc.D2.p.m4v [busquedaobtenidade
] => itunes
        )

    [
    1
] => Array
        (
            [nombre
] => You And Your Heart
            [longDescription
] =>
            [imagen
] => https: //video-ssl.itunes.apple.com/itunes-assets/Video115/v4/f0/92/0c/f0920ce2-8bb7-5e62-b44c-36ce701fe7b1/mzvf_6922739671336234286.640x352.h264lc.U.p.m4v [busquedaobtenidade
] => itunes
        )

)

Pero quisiera que me devuelva así la información en un formato más limpio:
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Éste es mi código PHP:
<?php
error_reporting(E_ALL & ~E_NOTICE);

$a_resultados = array();
$counter = 0;

// $search_val = $_GET['search_val'];

if (!empty($_GET['search_val'])) {
    $search_val = $_GET['search_val'];
    $content=file_get_contents("https://itunes.apple.com/search?term=" .$search_val. "&entity=musicVideo");
    $json = json_decode($content);
    // print_r($json);
    foreach ($json->results as $res) {
        $a_resultados[$counter]["nombre"] = $res->trackName;
        $a_resultados[$counter]["longDescription"] = $res->longDescription;
        $a_resultados[$counter]["imagen"] = $res->previewUrl;
        $a_resultados[$counter]["busquedaobtenidade"] = "itunes";
        $counter++;
    }

    $contenttwo = file_get_contents("http://api.tvmaze.com/search/shows?q=".$search_val);
    $jsontwo = json_decode($contenttwo,true);

    //print_r($jsontwo);

    foreach ($jsontwo as $res) {
        $a_resultados[$counter]["nombre"] = $res["show"]["name"];
        $a_resultados[$counter]["longDescription"] = $res["show"]["summary"];
        $a_resultados[$counter]["imagen"] = $res["show"]["url"];
        $a_resultados[$counter]["busquedaobtenidade"] = "tv maze";
        $counter++;
    }
}

if (!empty($_GET['search_val'])) {
    print_r($a_resultados);
    // print_r(json_encode($a_resultados));
    // print_r(json_decode(json_encode($a_resultados)));
} else {
    print_r("Ingrese una busqueda, por ejemplo ?search_val=jack ");
}

?>
<?php

?>

A: Sustituye tus print_r por echo
En cuanto a tu resultado imprimelo asi
echo json_encode($a_resultados);

acerca del comentario de la url:

var elJson = '{"url":"http:\/\/www.tvmaze.com\/shows\/3661\/jack-irish"}';
var elObj = JSON.parse(elJson);
console.log(elObj)
document.write(`<a href="${elObj.url}">${elObj.url}</a>`)

A: Te dejo comentarios en el código:
<?php
error_reporting(E_ALL & ~E_NOTICE);

if (empty($_GET['search_val']) === false) {
    /* Inicializa la variable */
    $a_resultados = [];
    /* No uses variables transitorias innecesarias y usa urlencode() */
    $content = file_get_contents(
       "https://itunes.apple.com/search?term=". urlencode($_GET['search_val']) ."&entity=musicVideo"
    );
    $json = json_decode($content);
    foreach ($json->results as $res) {
        /* Agregamos un elemento nuevo a los datos */
        array_push($a_resultados, [
            "nombre" => $res->trackName,
            "longDescription" => $res->longDescription,
            "imagen" => $res->previewUrl,
            "busquedaobtenidade" => "itunes",
        ]);
    }

    /* No olvides urlencode() */
    $contenttwo = file_get_contents(
        "http://api.tvmaze.com/search/shows?q=". urlencode($_GET['search_val'])
    );
    $jsontwo = json_decode($contenttwo, true);

    foreach ($jsontwo as $res) {
        /* Agregamos un elemento nuevo a los datos */
        array_push($a_resultados, [
            "nombre" => $res["show"]["name"],
            "longDescription" => $res["show"]["summary"],
            "imagen" => $res["show"]["url"],
            "busquedaobtenidade" => "tv maze",
        ]);
    }
    /* Declaramos el tipo de datos entregados y finalizamos tras enviarlos al navegador */
    header("Content-type: application/json; charset=utf-8");
    die(json_encode($a_resultados, JSON_PRETTY_PRINT));
}
?>
Ingrese una busqueda, por ejemplo ?search_val=jack

Te destaco los siguientes puntos:

*

*Debes declarar el tipo de dato entregado con la cabecera HTTP Content-type: application/json; charset=utf-8.

*Puedes exportar datos nativos de PHP en formato JSON a través de la función json_encode(), pero debes usar una función de salida para enviar el resultado al navegador, como echo o die(). No uses print_r() ni var_export() ni funciones que alteren el contenido exacto del resultado.

*Escapa siempre los datos GET agregados a una URL mediante urlencode().

*Evita el uso de variables transitorias, son un mal hábito y proclives a errores.


text:
Q: How do I get my projects to use a global .eslintrc file by default? I use atom text editor.
Here are the steps I took to get my linter working with React and ES6:

*

*install atom-react package

*when I start a new project, I run npm install --save eslint

*create an .eslintrc file in my project folder (this can be done either manually or running command eslint --init, which helps create the file with a series of questions that I answer on the command line)

I don't want to have to create the .eslintrc everytime I start coding a new project. I want to use the global .eslintrc file, which I found when I:

*

*Go to Atom > Preferences

*Click on Open Config Folder

*Click on .atom > packages > linter > .eslintrc

How can I make it so that when I fire up a new file and start coding I already get the options defined in this global file?
In particular, this is the setup I am using in individual projects:
{
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "sourceType": "module"
  },
  "env": {
    "es6": true
  },
  "plugins": [
    "eslint-plugin-react"
  ]
}

And I want this to be the default.

A: Go to settings --> packages --> linter-eslint settings. On that menu, look for the .eslintrc Path option. For your particular preference, you would put ~/.atom/packages/linter/.eslintrc in that field. Your .eslintrc is now being used globally across all of your projects.

A: You could use the configuration cascading to your advantage :
http://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy
workspace
     |
     |_ .eslintrc (global, root = true)
     |
     |_ project-1
           |
           |_ .eslintrc (project specific, if you need to overwrite some rules)

From the eslint documentation:


text:
Q: SQL cartesian product turns I am trying to understand the cartesian product with the SELECT command
but when I try different combinations I get different results like when I type
select X.A,Y.A,Z.A
From X,Y,Z

i get XxYxZ
but if i try
select X.A,Y.A,Z.A
From X,Y,Z
where (conditions)

depending on how I put the conditions also I get more different combinations

A: Depending on the database you are using, you want to fiddle with cross join.
Also, the results vary depending on data, to achieve persistent order you want to use order by clause.


text:
Q: How can I scale the $k$-th moment of a time series to a different time frequency? I have a time series, let's say N daily log-returns.
I want to study the moments (possibly the distribution) of the weekly returns.
I have two ways:
1) Using the time-additivity property of logarithms, I just add 5 consequent daily log-returns to get a weekly return. I will get a series of length N/5, so I will lose data. But I can calculate the descriptive stats on this weekly series. Displayed hereby are the histograms of the series calculated as described above.

I also add the table of the descriptive statistics of the three series.

2) I'm not familiar with this method, hence the question. I know I can scale the moments of the daily returns in order to obtain the moments for other time frequencies, i.e. from the first column of the table to pass to the second and third thanks to a scaling law which is a function of the tail exponent $\alpha$ here. I obtained my $\alpha$ by fitting a Lèvy-Stable distribution to my time series, and what I got is $\alpha = 1.596$
Here is the scaling laws I found to pass from the distribution of the daily returns $f_{day}$ to the distribution of the weekly returns $f_{week}$
For $\alpha < 2$ (returns asymptotically lévy-stable distributed):
$$f_{\tau}(r) = \Bigg( \frac{1}{\tau}^\alpha \Bigg) f_{day}(\Bigg( \frac{1}{\tau}^\alpha r \Bigg)) $$
where $\tau$ is the frequency we are seeking to obtain (e.g for weekly data, it will be $\tau=5$ just considering the working days).
Since I'm interested in the numerical implementation though, I cannot use this formula. But I could calculate the general law that governs the scaling of the $k$-th moment. I managed for the case $\alpha < 2$ to obtain:
$$ E[r_{\tau}^k] = (\tau)^{k/ \alpha} E[r_{day}^k] $$
My question is:
Does this relation hold? Once I implement it should I expect the same values I got in the above table? Why someone even studied this if I can get the moment by aggregating the log-returns?
Any comment is very much appreciated, I can't find literature to help me in the empirical analysis, just very theoretical stuff.
Edit
Here is the way I implemented it in Python (ptf being my daily time series), and alpha is the parameter obtained by fitting a Lèvy-Stable distribution to ptf (alpha = 1.596)
# Scaling: methods of moments

# mean
mu = np.mean(ptf) # empirical daily mean (see table)
mu_t= [(np.mean(ptf))*(i**(1/alpha)) for i in range(1,40)] # scales daily mean up to 40 days

# std
std = np.std(ptf) # daily std
std_t= [std*(i**(1/alpha)) for i in range(1,40)]

# skewness
r_skew=[ptf[i]**3 for i in range(len(ptf))] # daily skew
skew_t= [np.mean(r_skew)*(i**(3/alpha))for i in range(1,40)]

# kurtosis
r_kurt=[ptf[i]**4 for i in range(len(ptf))] # daily kurt
kurt_t= [np.mean(r_kurt)*(i**(4/alpha))for i in range(1,40)]

And here it the graphical result, which seems pretty wrong to me (the point being the values obtained as in method 1, see Table above)


text:
Q: MYSQL Set 1 field to equal another field - but add text I'm wondering if there's a way to use
    update your_table
     set B = A
But I'd like to add some numbers at the front
So it's more like
    update your_table
    set B = ('00',A)

A: update your_table
set B = concat('00', A)

A: This represents bad relational data storage practice. Rather than duplicating data which may result in headaches later (you now need to update two columns to change one set of data) you should concatenate the results upon retrieval.