text:
Q: angular js to load initial data in context where should i load basic data in angularjs app. i have created factory initialy i want to load data into service so that whenever i will require data i will use my service instead of hitting back to server.
Hint:: My problem is i am applying ng-controller to different div's so many instance are created i dont want to load data from server with each instance.
app.factory('feedbackFactory', function ($http) {
   //factory code
});

app.factory('feedbackService', function ($http) {
   //service code
});

app.controller('feedbackController', function ($scope, feedbackService,feedbackFactory $filter) {
      // Constructor for this controller
init();

function init() {
   feedbackFactory.get(1234, 1, 20).then(function(data)
     {
        $scope.feedbackItems=data;
        // here load data into service
        });
    }
});

A: If your server supports caching $http will default to use the E-Tags and only actually get the data back from the server once (assuming it doesn't update and the e-tag changes). This will cause it to hit the server however but get a 304 response.
If you want to force your application to only ever talk to the server once you would need to setup some kind of variable that gets checked to see if it should hit the server or not...
app.factory('feedbackFactory', function ($http) {
    var checkServer = true;
    var results = [];
    function getStuff(x, y, z) {
        if (checkServer) {
            checkServer = false; // we don't want to check again! Maybe have a refresh button that sets this back to true?
            // do http call...
            $http.get("path").then(function(response) {
                // Here is the magic... use angular.copy to keep your results object the same but update its values!
                angular.copy(response, results);
            });
        }
        return results; // this will be updated by our inital call to the server!
    });
});

Thats probably not all valid code since I'm just typing off the top of my head, but it should get you close enough. Big ones are bind to the results object and use angular.copy(httpResponseData, results) to fill the data, you might want to return a $q.when(results) if you want to bind to the call itself in a promise instead of directly binding to the feedbackFactory.results;
app.factory('feedbackFactory', function ($http, $q) {
    var checkServer = true;
    var results = [];
    function getStuff(x, y, z) {
        if (checkServer) {
            checkServer = false; // we don't want to check again! Maybe have a refresh button that sets this back to true?
            // do http call...
            return $http.get("path").then(function(response) {
                // Here is the magic... use angular.copy to keep your results object the same but update its values!
                angular.copy(response, results);
                return results; // If you want to bind to the promise instead of .results directly
            });
        }
        return $q.when(results); // If you want to bind to the promise instead of .results directly
    });
});

A: You can use $http cache, so your data won't be fetched from server after the first time. See this answer to see how to use cache in $http.


text:
Q: How to implement Garbage Collection in Numpy I have a file called main.py, which references another file Optimisers.py which only has functions in it and is used in a for loop in main.py. These functions have different optimisation functions in them.
This Optimisers.py then references two other similar files with only functions in them as well, which are in while loops. All of these files use numpy.
I believe that is because of the loops with functions calling on and creating arrays in numpy, which is leading to a memory overload. Therefore I cannot finish some optimisation algorithms, or cycle through all the possible coordinates I would like to.
How do I ensure removal of variables in numpy? As I understand it, numpy's C libraries complicate the standard Python process. What does the %reset array command (from the link below) do? And where should I implement it?
P.S. I've read "Releasing memory of huge numpy array in IPython",
and gc.collect() does not work either.

A: When a numpy array is no longer referenced, it will be automatically freed by the GC. The C objects are wrapped in Python objects, so for you it should not matter how it's implemented.
Make sure that arrays are not referenced in global variables, since those stick around until overwritten or the program exits.
If you need to free an array from a local variable before it goes out of scope you can use del variablename (or just assign e.g. None), but that will not take care of any other references, just the one named.
For debugging where you are referencing an object, you can use gc.get_referrers(object).

P.S. I've read Releasing memory of huge numpy array in IPython and gc.collect() does not work either.

Unless you have cycles or have called gc.disable(), gc.collect() will not make the GC happen sooner.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Special case of Fatou's lemma Hi everyone: Suppose that $D$ is a domain of $\mathbb{R}^{n}$  $(n \geq1)$, $Y$ a locally compact topological space, and $\mu$ a measure on $Y$. Let $f(x,y): D\times Y\rightarrow[0,+\infty)$ be measurable.
My question is: How can we use Fatou's lemma (and under which condition(s)) to get
$$\int_{Y}\liminf_{\zeta\rightarrow x}f(\zeta,y)d\mu(y)\leq\liminf_{\zeta\rightarrow x}\int_{Y}f(\zeta,y)d\mu(y)?$$
Is there a smart trick to transform the above limit infimum into a sequencial limit infimum? Thanks for considering.

A: As long as the integrand on the left hand side is measurable, you can indeed reduce your question to the sequencial case:
There exists a sequence $(\zeta_n)_n$ in $\Bbb{R}^n$ with $\zeta_n \rightarrow x$ and
$$\liminf_{\zeta \rightarrow x} \int_Y f(\zeta, y)\,d\mu(y) = \lim_n \int_Y f(\zeta_n, y)\, d\mu(y).$$
This is true, because we are only talking about the liminf of a single(!) number here.
Fatou now yields
$$\int_Y \liminf_n f(\zeta_n, y) d\mu(y) \leq \liminf_n \int_Y f(\zeta_n, y) \, d\mu(y) = \liminf_{\zeta \rightarrow x} \int_Y f(\zeta, y) \, d\mu(y).$$
Noting $\liminf_{\zeta \rightarrow x} f(\zeta, y) \leq \liminf_n f(\zeta_n, y)$ for all $y \in Y$ completes the proof.
I am quite sure that in general the integrand on the left hand side of your equation does not have to be measurable. I will edit the post if I come up with an explicit counterexample.
EDIT: Let me elaborate a bit. If you have a sequence $(z_n)_n$ of real numbers, then there is always a subsequence $(x_{n_k})_k$ with $\lim_k x_{n_k} = \liminf_n z_n$ (show this!). This is what I meant with "the $\liminf$ of a single(!) number". Perhaps I should have said "of a single sequence".
Now consider the case of "not a single sequence", by which I mean e.g. a sequence of functions (like the integrand above). As an easy example, consider
$$
f_{n}:\left\{ 0,1\right\} \rightarrow\mathbb{R},x\mapsto\begin{cases}
\left(-1\right)^{n}, & x=0\\
\left(-1\right)^{n+1}, & x=1.
\end{cases}
$$
Here, $\liminf f_n \equiv -1$, but if you choose any subsequence $(f_{n_k})_k$, you always have $f_{n_k}(0) = - f_{n_k}(1)$, which shows that $(f_{n_k})_k$ can not converge pointwise to $-1$.
The same holds for the "continuous" liminf (i.e. $\liminf_{\zeta \rightarrow x}$), but here you have to replace the subsequence with an actual sequence $\zeta_n \rightarrow x$ (show this!). This is what I have done above for the liminf
$$
\liminf_{\zeta \rightarrow x} \int_Y f(\zeta, y) \, d\mu(y).
$$
Note that we are again in the case of a single "sequence" because the expression depends only on $\zeta$, not on $y$ (or any other variable).


text:
Q: all functions from the unit interval into a path connected space homotopic? I'm trying to give myself a quick introductory overview of homotopy theory, and I've run into this problem that I can't reconcile with my understanding of the fundamental group.
For spaces X and Y, let [X,Y] denote the set of homotopy classes of maps of X into Y. Let I=[0,1]. Show that if Y is path connected, [I,Y] has a single element.
The problem is from Munkres, and I've seen the solution online, and that solution seems reasonable. However, there is what seems to me to be a very simple counter-example, and I wonder what I'm misunderstanding about the problem that makes it not actually a counterexample:
Let Y=R^2 with the origin deleted. Let f:I->Y be such the constant function f(x)=(0,1). Let h(x)=(cos(2*pi*x), sin(2*pi*x)).
Then h is a loop around the origin, and it can't be homotopic to f. Right? Isn't one of the primary motivations of formulating the fundamental group that a space is simply connected iff the fundamental group at every point is trivial?

A: You don't have to keep the endpoints fixed during the homotopy, so the problem goes away.

A: The thing to take away from this is that there is a difference between:

*

*A homotopy between two paths, both of which start at $A$ and end at $B$

*A homotopy between paths starting at $A$ and ending at $B$


text:
Q: Need to turn char into lower case and replace it in Java So I need to make a basic cash register that accepts 5 items in an array with a price on them. Nevertheless, some items will have HST(tax) included with them. To know which items have tax and which don't. The user will press h or H before or after entering the dollar amount. I have got most of the program working, but I cannot get my code to recognize the upper case H to put the tax in it.
Here is my code, Thx in advance for any information:
// Import scanner class
import java.util.Scanner;

 // Create class and method
class Main {
public static void main(String[] args) {

// Create scanner object and set scanner variables
Scanner inp = new Scanner(System.in);
System.out.println("Press any key to start");
String key = inp.nextLine();
System.out.println("\nEnter the amount of each item");
System.out.println("Upto 5 inputs are allowed!\n");

// Initialize counter and index variables to use it in the while loop
int counter = 0;
int index = 0;

// Create a double array variable, and set the limit to 5
double[] numbers = new double[5];

// Create a boolean variable to use it in the while loop
boolean go = true;

while(go) {
    String value = inp.nextLine();
    value.toLowerCase();
    // Set the index value to "h" or "H"
    int indexOfh = value.indexOf('h');

    boolean containsh = indexOfh == 0 || indexOfh == (value.length()-1);

    if(containsh){ //Validate h at beginning or end
        numbers[index] = Double.parseDouble(value.replace("h", ""));
        index++;
          System.out.println("HST will be taken account for this value");
    }
    counter++;
    if (counter == 5){
      go = false;
    }
}
System.out.println("HST Values:");

for(int i=0; i< numbers.length; i++) {
        System.out.println(numbers[i]);
}
}
}

A: I would remove indexOfh  entirely: you can OR a bunch of statements together.  This is safe because >= is evaluated before ||.
// Set the index value to "h" or "H"
boolean containsh = value.indexOf('h') >= 0
    || value.indexOf('H') >= 0;

Also, you can make your requirement a little tighter by using startsWith and endsWith to ignore an 'H' or 'h' in the middle.
// Set the index value to "h" or "H"
boolean containsh = value.startsWith("h")
    || value.startsWith("H") || value.endsWith("h")
    || value.endsWith("H");

Additionally, you have a resource leak because you never close your Scanner: you can use try-with-resources to have Java manage this for you.  That, along with a few other simplifications, yields a new version like this.
// Import scanner class
import java.util.Scanner;

// Create class and method
public class so64283526 {
    public static void main(String[] args) {

        // Create scanner object and set scanner variables
        try (Scanner inp = new Scanner(System.in)) {
            System.out.println("Press any key to start");
            System.out.println("\nEnter the amount of each item");
            System.out.println("Upto 5 inputs are allowed!\n");

            // Initialize counter and index variables to use it in the while
            // loop
            int counter = 0;
            int index = 0;

            // Create a double array variable, and set the limit to 5
            double[] numbers = new double[5];

            while (counter++ < 5) {
                String value = inp.nextLine();
                value.toLowerCase();

                // Set the index value to "h" or "H"
                boolean containsh = value.startsWith("h")
                        || value.startsWith("H") || value.endsWith("h")
                        || value.endsWith("H");

                if (containsh) { // Validate h at beginning or end
                    numbers[index] = Double
                            .parseDouble(value.toLowerCase().replace("h", ""));
                    index++;
                    System.out.println(
                            "HST will be taken account for this value");
                }
            }
            System.out.println("HST Values:");

            for (int i = 0; i < numbers.length; i++) {
                System.out.println(numbers[i]);
            }
        }
    }
}

Results:
Press any key to start

Enter the amount of each item
Upto 5 inputs are allowed!

1
2H
HST will be taken account for this value
H3
HST will be taken account for this value
h4.7
HST will be taken account for this value
5.h6
HST Values:
2.0
3.0
4.7
0.0
0.0


text:
Q: How to append columns horizontally in R in a loop? I want to create a matrix of stockdata from n number of companies from a ticker list, though im struggling with appending them horizontally, it only works to append them vertically.
Also other functions like merge or rbind which i have tried, but they cannot work with the variables parsed as a string, so the hard part here is that i want to append n variables which are retrieved from the tickerlist which has n number of stocks. Other suggestions are welcome to get the same result.
Stocklist data:
> dput(stockslist)
structure(list(V1 = c("AMD", "MSFT", "SBUX", "IBM", "AAPL", "GSPC",
"AMZN")), .Names = "V1", class = "data.frame", row.names = c(NA,
-7L))

code:
library(quantmod)
library(tseries)
library(plyr)
library(PortfolioAnalytics)
library(PerformanceAnalytics)
library(zoo)
library(plotly)

tickerlist <- "sp500.csv"  #CSV containing tickers on rows
stockslist <- read.csv("sp500.csv", header = FALSE, stringsAsFactors = F)
nrstocks = length(stockslist[,1]) #The number of stocks to download
maxretryattempts <- 5 #If there is an error downloading a price how many
times to retry
startDate = as.Date("2010-01-13")

for (i in 1:nrstocks) {
  stockdata <- getSymbols(c(stockslist[i,1]), src = "yahoo", from =
startDate)
  # pick 6th column of the ith stock
  write.table((eval(parse(text=paste(stockslist[i,1]))))[,6], file =
"test.csv", append = TRUE, row.names=F)

}

A: This is exactly a great opportunity to talk about lists of dataframes. Having said that ...
Side bar: I really don't like side-effects. getSymbols defaults to using side-effect to saving the data into the parent frame/environment, and though this may be fine for most uses, I prefer functional methods. Luckily, using auto.assign=FALSE returns its behavior to within my bounds of comfort.
library(quantmod)
stocklist <- c("AMD", "MSFT")
startDate <- as.Date("2010-01-13")

dat <- sapply(stocklist, getSymbols, src = "google", from = startDate, auto.assign = FALSE,
              simplify = FALSE)
str(dat)
# List of 2
#  $ AMD :An 'xts' object on 2010-01-13/2017-05-16 containing:
#   Data: num [1:1846, 1:5] 8.71 9.18 9.13 8.84 8.98 9.01 8.55 8.01 8.03 8.03 ...
#  - attr(*, "dimnames")=List of 2
#   ..$ : NULL
#   ..$ : chr [1:5] "AMD.Open" "AMD.High" "AMD.Low" "AMD.Close" ...
#   Indexed by objects of class: [Date] TZ: UTC
#   xts Attributes:
# List of 2
#   ..$ src    : chr "google"
#   ..$ updated: POSIXct[1:1], format: "2017-05-16 21:01:37"
#  $ MSFT:An 'xts' object on 2010-01-13/2017-05-16 containing:
#   Data: num [1:1847, 1:5] 30.3 30.3 31.1 30.8 30.8 ...
#  - attr(*, "dimnames")=List of 2
#   ..$ : NULL
#   ..$ : chr [1:5] "MSFT.Open" "MSFT.High" "MSFT.Low" "MSFT.Close" ...
#   Indexed by objects of class: [Date] TZ: UTC
#   xts Attributes:
# List of 2
#   ..$ src    : chr "google"
#   ..$ updated: POSIXct[1:1], format: "2017-05-16 21:01:37"

Though I only did two symbols, it should work for many more without problem. Also, I shifted to using Google since Yahoo was asking for authentication.
You used write.csv(...), realize that you will lose the timestamp for each datum, since the CSV will look something like:
"AMD.Open","AMD.High","AMD.Low","AMD.Close","AMD.Volume"
8.71,9.2,8.55,9.15,32741845
9.18,9.26,8.92,9,22658744
9.13,9.19,8.8,8.84,34344763
8.84,9.21,8.84,9.01,24875646

Using "AMD" as an example, consider:
write.csv(as.data.frame(AMD), file="AMD.csv", row.names = TRUE)
head(read.csv("~/Downloads/AMD.csv", row.names = 1))
#            AMD.Open AMD.High AMD.Low AMD.Close AMD.Volume
# 2010-01-13     8.71     9.20    8.55      9.15   32741845
# 2010-01-14     9.18     9.26    8.92      9.00   22658744
# 2010-01-15     9.13     9.19    8.80      8.84   34344763
# 2010-01-19     8.84     9.21    8.84      9.01   24875646
# 2010-01-20     8.98     9.00    8.76      8.87   22813520
# 2010-01-21     9.01     9.10    8.77      8.99   37888647

To save all of them at once:
ign <- mapply(function(x, fn) write.csv(as.data.frame(x), file = fn, row.names = TRUE),
              dat, names(dat))

There are other ways to store your data such as Rdata files (save()).
It is not clear to me if you are intending to append them as additional columns (i.e., cbind behavior) or as rows (rbind). Between the two, I tend towards "rows", but I'll start with "columns" first.
"Appending" by column
This may be appropriate if you want day-by-day ticker comparisons (though there are arguably better ways to prepare for this). You'll run into problems, since they have (and most likely will have) different numbers of rows:
sapply(dat, nrow)
#  AMD MSFT
# 1846 1847

In this case, you might want to join based on the dates (row names). To do this well, you should probably convert the row names (dates) to a column and merge on that column:
dat2 <- lapply(dat, function(x) {
  x <- as.data.frame(x)
  x$date <- rownames(x)
  rownames(x) <- NULL
  x
})
datwide <- Reduce(function(a, b) merge(a, b, by = "date", all = TRUE), dat2)

As a simple demonstration, remembering that there is one more row in "MSFT" than in "AMD", we can find that row and prove that things are still looking alright with:
which(! complete.cases(datwide))
# [1] 1251
datwide[1251 + -2:2,]
#            date AMD.Open AMD.High AMD.Low AMD.Close AMD.Volume MSFT.Open MSFT.High MSFT.Low MSFT.Close MSFT.Volume
# 1249 2014-12-30     2.64     2.70    2.63      2.63    7783709     47.44     47.62    46.84      47.02    16384692
# 1250 2014-12-31     2.64     2.70    2.64      2.67   11177917     46.73     47.44    46.45      46.45    21552450
# 1251 2015-01-02       NA       NA      NA        NA         NA     46.66     47.42    46.54      46.76    27913852
# 1252 2015-01-05     2.67     2.70    2.64      2.66    8878176     46.37     46.73    46.25      46.32    39673865
# 1253 2015-01-06     2.65     2.66    2.55      2.63   13916645     46.38     46.75    45.54      45.65    36447854

"Appending" by row
getSymbols names the columns unique to the ticker, a slight frustration. Additionally, since we'll be discarding the column names, we should preserve the symbol name in the data.
dat3 <- lapply(dat, function(x) {
  ticker <- gsub("\\..*", "", colnames(x)[1])
  colnames(x) <- gsub(".*\\.", "", colnames(x))
  x <- as.data.frame(x)
  x$date <- rownames(x)
  x$symbol <- ticker
  rownames(x) <- NULL
  x
}) # can also be accomplished with mapply(..., dat, names(dat))
datlong <- Reduce(function(a, b) rbind(a, b, make.row.names = FALSE), dat3)

head(datlong)
#   Open High  Low Close   Volume       date symbol
# 1 8.71 9.20 8.55  9.15 32741845 2010-01-13    AMD
# 2 9.18 9.26 8.92  9.00 22658744 2010-01-14    AMD
# 3 9.13 9.19 8.80  8.84 34344763 2010-01-15    AMD
# 4 8.84 9.21 8.84  9.01 24875646 2010-01-19    AMD
# 5 8.98 9.00 8.76  8.87 22813520 2010-01-20    AMD
# 6 9.01 9.10 8.77  8.99 37888647 2010-01-21    AMD
nrow(datlong)
# [1] 3693


text:
Q: How to map output of Execute R Script to second port in ML Studio using maml.mapOutputPort Execute R Script box in ML Studio has two output ports. How does one send data to the second output port?

A: Currently ML Studio does not support the mapping of output data to a second port. This can be verified by executing the following code:
# Map 1-based optional input ports to variables
dataset1 <- maml.mapInputPort(1) # class: data.frame

# Select data.frame to be sent to the output Dataset port
maml.mapOutputPort("dataset1", 1);
maml.mapOutputPort("dataset1", 2);

which returns
---------- Start of error message from R ----------
Error: At this time, there is only 1 output dataset port that can be mapped. Please provide 1 as the portNumber

As a workaround you can output your data.frame with an additional column labeling which output set is intended. Then Clean Missing Data with action Remove entire row can be used to truncate the data to the correct output and Select Columns in Dataset and be used to remove the extraneous column.


text:
Q: Should a mechanical power switch float or ground main power when the system is off? Whenever I've put a mechanical switch on a design to allow a battery to be connected / disconnected, I've always just floated system power whenever the switch is open, like this:

However, a colleague asked during a design review whether it makes more sense to ground system power when the device is off:

From a basic functionality perspective, I believe that either should work. However, I was curious if there is a particular reason to choose to float or ground the main supply in the "off" state?

Edit: Several (very helpful!) initial answers and comments discuss potential harms or considerations if we do choose to ground the input. Are there any extra risks or considerations for leaving the input floating (the first design)?

A: If you are going to ground it, perhaps then through a high resistor, to avoid any instantaneous current spikes upon switching, or any severe back draining.
Generally, I connect input signal pins to ground, even internally unconnected pins. Open pins on active devices (which is not your case - yours is a power pin) can cause undesired noise or even signalling at device internals.

A: Shorting the input to ground can damage some regulators because the output capacitors and multifarious bypass capacitors which may be connected to the output discharge through the regulator. It's not necessarily easy to tell from the datasheet whether that is true. You could add a resistor between the switch and ground to reduce the chances of that happening.
Some regulators have a pull-down transistor on the output to quickly discharge the output capacitors so you can reset (say) a micro by quickly cycling the power. This particular one does not seem to. Discharging the input capacitor with a switch takes you part of the way there, but there is no guarantee the output capacitors will be discharged quickly (though they probably will).

A: I would ask what you are trying to achieve by switching the DC in to GND. No obvious benefit in most/typical applications, but with all the risks mentioned by others (back-driving the regulator, contact arcing due to C60 discharge, etc).


text:
Q: How to handle Ajax forms with collections in Symfony2.3 So I have this form that I'd like to submit with Ajax.
Normally this is quite easy to do, but as it is now it doesn't handle the embedded collection the right way, which is too bad.
I have a form where you can create a question with a collection of answers.
The form is created as following:
    {{ form_start(form, {'attr':{'class': 'form-horizontal', 'id': 'form'}}) }}

            {{ form_label(form.question, null, { 'label_attr': {'class': 'col-lg-2 control-label'} }) }}

                {{ form_widget(form.question, { 'attr': {'class': 'form-control'} }) }}

        {% for answer in form.answers %}

                {{ form_label(answer.answer, 'Answer '~loop.index, { 'label_attr': {'class': 'col-lg-2 control-label'} }) }}

                    {{ form_widget(answer.answer, { 'attr': {'class': 'form-control'} }) }}

        {% endfor %}

<input class="btn btn-primary pull-right" type="submit" />

    {{ form_end(form) }}

Now to submit the form, I've got this little javascript in place:
$('#form').submit( function() {
    $.ajax({
        type: "POST",
        url: "{{ url('questionCreateSubmit') }}",
        data: $(this).serialize(),
        success: function(data) {
            alert(data);
        }
    });

    return false;
});

Now in my controller I have this to test if it handles it right:
/**
 * @Route("/questions/create/submit", name="questionCreateSubmit")
 */
public function questionCreateSubmitAction(Request $request)
{
    $question = new Question();

    $form = $this->createForm(new QuestionType(), $question);
    $form->handleRequest($request);
    die( var_dump( $form->getData() ) );

But it only sets the question attribute and ignores the collection of answers, this is what returns:
(
    [id:Acme\DemoBundle\Entity\Question:private] =>
    [question:Acme\DemoBundle\Entity\Question:private] => dfsdf
    [answers:Acme\DemoBundle\Entity\Question:private] => Doctrine\Common\Collections\ArrayCollection Object
    (
        [_elements:Doctrine\Common\Collections\ArrayCollection:private] => Array
            (
            )
    )
)

When I check the $_POST variables by dumping those, it clearly shows an array structure like this:
(
    [question] => Array
        (
            [question] => dfsdf
            [answers] => Array
                (
                    [0] => Array
                        (
                            [answer] => sdfsdf
                        )
                    [1] => Array
                        (
                            [answer] => dsfds
                        )
                    [2] => Array
                        (
                            [answer] => fsdfsdf
                        )
                )
            [_token] => cf8781508d9002504455472d676acb1073888e67
        )
)

Is there a way that the collections will be filled in automatically or do I have to make due with doing it all myself by iterating over the answers array and filling it in the question object?
Help would be much appreciated!

A: Nevermind, found the problem.
The problem was in my QuestionType which looked like this:
    $builder->add('answers', 'collection', array(
        'type' => new AnswerType()
    ));

but should've looked like this in my case:
    $builder->add('answers', 'collection', array(
        'type' => new AnswerType(),
        'allow_add' => true,
        'allow_delete' => true
    ));


text:
Q: Why doesn't sumBy(selector) return Long? sumBy(selector) returns Int
sumByDouble(selector) returns Double
Why doesn't sumBy return Long? Is there a workaround for this?

A: Optionally you can use fold function.
val totalLength = files.fold(0L) { acc, it -> acc + it.length() }

It's not much longer than sumBy code.

A: That's a decision Kotlin team made. Since it's not possible to have return type overloads in Java the sumBy* have to have different names depending on the return type.
It's easy enough to add your own sumByLong though:
inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long {
    var sum = 0L
    for (element in this) {
        sum += selector(element)
    }
    return sum
}

A: You can also use the sum() extension function which does have a Long variant, in conjunction with map()
val totalLength = files.map { it.length() }.sum()

Or you could wrap this into an extension function, though I don't see much benefit over the inline version:
inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long {
    return map { selector(it) }.sum()
}

A: As of Kotlin 1.4, you can use sumOf, which resolves the type based on the return type of the function argument:
// prints 2^31 - 1 = 2147483647
println((0..30).sumOf{ 1 shl it })

// prints -1 due to 32-bit overflow
println((0..31).sumOf{ 1 shl it })

// prints 2^32 - 1 = 4294967295 because it works with 64-bit longs
println((0..31).sumOf{ 1L shl it })

Try it in the Kotlin Playground


text:
Q: If not exists, checking for table by name I want to create idempotent scripts for agile database development with mysql. Here is a link if you want to see about it:
http://haacked.com/archive/2006/07/05/bulletproofsqlchangescriptsusinginformation_schemaviews.aspx/
drop table if exists is so wrong for this. I am looking for something like this:
IF NOT EXISTS
(
    SELECT *
    FROM information_schema.tables
    WHERE table_schema = 'foo'
    AND table_name = 'customer'
    LIMIT 1;
)
BEGIN
    CREATE TABLE customer(n int);
END

If it helps, I am looking for a functionality of:
If Not exists something
then
    statement1
    statement2
    ...
    statementN
else
    do nothing
fi

A: CREATE TABLE IF NOT EXISTS customer
    (n int);

See MySQL Manual


text:
Q: MsBuild task GenerateDeploymentManifest.CreateDesktopShortcut does not work In automating a ClickOnce publishing procedure we are using Mage to generate the application manifest and the MsBuild GenerateDeploymentManifest task.
<GenerateDeploymentManifest AssemblyName="App.exe.application"
                                AssemblyVersion="$(AppVersion)"
                                Product="Application"
                                Install="true"
                                UpdateEnabled="true"
                                UpdateMode="Foreground"
                                OutputManifest="$(PrepareFolder)\App.exe.application"
                                MapFileExtensions="true"
                                EntryPoint="@(RelativeApplicationManifestFile)"
                                CreateDesktopShortcut="true"
                                MinimumRequiredVersion="$(AppVersion)"
                                />

But the CreateDesktopShortcut has no effect and does not create the desired tag in the deployment manifest file.
Getting this:
<deployment install="true"
            mapFileExtensions="true"
            minimumRequiredVersion="2.19.13.0">

instead of
<deployment install="true"
            mapFileExtensions="true"
            minimumRequiredVersion="2.19.13.0"
            co.v1:createDesktopShortcut="true">

Am I missing something?

A: You need to add the TargetFrameworkVersion attribute to the GenerateDeploymentManifest task. It should be "3.5" or "4.0" depending on what framework version you are building for. The task default is "2.0" which is why you have to set it explicitly.
There is a check in the task that this must be set to "3.5" or greater in order for the CreateDesktopShortcut to actually generate anything.
<GenerateDeploymentManifest AssemblyName="App.exe.application"
                                AssemblyVersion="$(AppVersion)"
                                Product="Application"
                                Install="true"
                                UpdateEnabled="true"
                                UpdateMode="Foreground"
                                OutputManifest="$(PrepareFolder)\App.exe.application"
                                MapFileExtensions="true"
                                EntryPoint="@(RelativeApplicationManifestFile)"
                                CreateDesktopShortcut="true"
                                TargetFrameworkVersion="3.5"
                                MinimumRequiredVersion="$(AppVersion)"
                                />


text:
Q: Which quests from the first Witcher games matter in the second? I recently found out that I've lost my savegames from The Witcher. I decided, rather unwillingly, to replay the game in order to try and make the same decisions so that it'll be reflected correctly on the The Witcher 2 game.
However, I do not have enough time to replay it fully -- I want to go straight to the important quests, but of course I don't know which of those have impact on the second game.
That said, I'm not expecting a complete list of every quest available and whether or not it has any impact, but I wish to know which quests (other than the main, necessary quests) I have to do. Some examples (which I'll update as I remember):

*

*Does beating the Poker Dice quests change the game somehow?

*The weapon that you receive after collecting all Trophies gets carried over?

*The character build (talents) are reflected?

Please, pretty please, do not write any spoilers! I haven't played a single second of the game yet, and I love this game (enough the replay the old one just to get a working savegame).

A: An imported Witcher 2 save retains several items (see below), roughly 1% of your accumulated Orens, there are a few minor dialogue changes and free goodies depending on choices you've made.
Weapons retained:
Steel Swords

*

*Ard'aenye - (only available to saves imported from the original version of The Witcher. This item was removed from the Enhanced Edition.)

*D'Yaebl

*G'valchir

*Gwalhir
Silver Swords

*

*Aerondight

*Moon Blade
Additionally, Raven's Armor will carry over to a new Witcher 2 game if imported from the first game.
As for plot choices carrying over, there are three notable ones in addition to path selection. Spoilers follow.

 If you saved Thaler, he will send you a letter when you get to Flotsam. This contains the Dragon's Dream formula. Additionally, whether you choose to kill or spare Siegfried (if neutral or siding with the Scoia'tel, see below for more details), and Adda affects some minor bits of dialog and plot. There are no mechanical implications for these choices however.

As for the critical path decision:

 As noted, those that side with the Order in the first game can skip the sewer entrance to Loc Muinne that you're otherwise forced through if you align yourself with Iorveth - Siegfried hooks you up

If you sided with the Scoia'tel, Igor Vivaldi will extend a line of credit to you in Vergen.


text:
Q: Rails 3 - Turning multiple counts into a single query - OrderedHash I've got an initializer method that does a silly thing.  I need to optimize it down to one query, but my SQL skills are failing me at the moment.  I've conceived of using GROUP BY and UNION and all sorts of things, but I just made myself more confused.  I bequeath this to the community to shed some insight:
Class Stats
  # Turn these three queries into one query that we can then
  # load into the three different instance variables
  def initialize(question)
    # Integer = total number of answers for this question
    @total = total_answers(question.id)

    # Hash keyed by 0 (incorrect answers) and 1 (correct answers)
    @stats_total = load_stats_total(question.id) if @total > 0

    # Hash keyed by answer_id with values = total number of answers
    @stats_answers = load_stats_answers(question.id) if @total > 0
  end

  # Returns an int = the total number of answer attempts for
  # this question (right + wrong user_answers)
  # Excludes anonymous users
  def total_answers(question_id)
    UserAnswer.count(:conditions => ['u.anonymous = 0 AND q.id = ?', question_id], :joins => 'JOIN answers a ON user_answers.answer_id = a.id JOIN questions q ON q.id = a.question_id JOIN users u ON u.id = user_answers.user_id')
  end

  # Returns an OrderedHash =
  # {"0" => number of wrong user_answers for this question,
  #  "1" => number of correct user_answers for this question}
  # Excludes anonymous users
  def load_stats_total(question_id)
    UserAnswer.count(:conditions => ['u.anonymous = 0 AND q.id = ?', question_id], :joins => 'JOIN answers a ON user_answers.answer_id = a.id JOIN questions q ON q.id = a.question_id JOIN users u ON u.id = user_answers.user_id', :group => 'a.correct')
  end

  # Returns an OrderedHash =
  # {
  #  some_answer_id => total number of user_answers for this answer,
  #  some_other_answer_id => total number of user_answers for this answer
  #  ...
  # }
  # Excludes anonymous users
  def load_stats_answers(question_id)
    UserAnswer.count(:conditions => ['u.anonymous = 0 AND q.id = ?', question_id], :joins => 'JOIN answers a ON user_answers.answer_id = a.id JOIN questions q ON q.id = a.question_id JOIN users u ON u.id = user_answers.user_id', :group => 'a.id')
  end
end

If anyone has any thoughts, they'd be greatly appreciated!
Thanks.

A: I don't think you can do this cleanly in one query.
At least not without writing pure sql.
But lets try and find a nice solution in ActiveRecord
First of all, let's try to remove some of the sql
UserAnswer.count(:conditions => ['u.anonymous = 0 AND q.id = ?', question_id], :joins => 'JOIN answers a ON user_answers.answer_id = a.id JOIN questions q ON q.id = a.question_id JOIN users u ON u.id = user_answers.user_id')

can be rewritten
UserAnswer.joins(:user).where(:users => {:anonymous => false})\
  .joins(:answer => :question).where(:questions => {:id => question_id})\
  .count

lets just save this scope as a magic private method magic_scope
your current methods become
def total_answers(question_id)
  magic_scope(question_id).count
end

def load_stats_total(question_id)
  magic_scope(question_id).count(:group => "answers.correct")
end

def load_stats_answers(question_id)
  magic_scope(question_id).count(:group => "answers.id")
end

notably, of course, the total_answers method can be derived from summing up the results from either of the load_stats_* methods.
If ActiveRecord was a bit more clever we could do
def all_the_magic(question_id)
  magic_scope(question_id).count(:group => ["answers.correct", "answers.id"])
end

which would give us all the data we needed to do it in one query.
but as far as I'm aware that's not currently possible.
But I hope this gets you nearer.


text:
Q: Cake PHP Log permissions erro i have one issue on cake PHP and Angular5 webapp. After migrating PHP on release 7.12 i got this message when i try to save some data:
           failed to open stream: Permission
         denied in /var/www/data/back-end/releases
/20170712150145/back-end/vendor/cakephp/cakephp/
    src/Log/Engine/FileLog.php on line 133

here is my permissions:

A: Issue is related to libssl. Follow this thread i'm able to solve the issue.
https://github.com/wkhtmltopdf/wkhtmltopdf/issues/3001


text:
Q: Create a new dataframe with rownames paste0 from text and sequence number Hej,
This might have been reviewed before, plus my R skills are getting rusty, but I am trying to generate a new dataframe, where rownames will be generated from strings and effectif / sequence number from a two columns data frame.
To make more sense  I have a dataframe looking like :
IND Effect
A 3
B 2
C 4

read.table(text = "IND Effect
A 3
B 2
C 4", h = T)

And I want something like
IND
A_1
A_2
A_3
B_1
B_2
C_1
C_2
C_3
C_4

on a new data frame. I tryed :
new = mapply(function(x, y) paste0(rep(x, y), collapse = "_"), IND , Effect)

but doesn't work as I would like....

A: You may nee the help of the seq_len() function:
df <- data.frame(ind = c("A", "B", "C"),
                 effect = c(3, 2, 4))

paste(rep(df$ind, df$effect),
      unlist(sapply(df$effect, seq_len)),
      sep = "_")
[1] "A_1" "A_2" "A_3" "B_1" "B_2" "C_1" "C_2" "C_3" "C_4"

A: with mapply:
m <- mapply(paste, df$ind, sapply(df$effect, seq), sep = "_")

output
unlist(m)
#   A1    A2    A3    B1    B2    C1    C2    C3    C4
#"A_1" "A_2" "A_3" "B_1" "B_2" "C_1" "C_2" "C_3" "C_4"

#or, as a data.frame object:
data.frame(new = unname(unlist(m)))
#  new
#1 A_1
#2 A_2
#3 A_3
#4 B_1
#5 B_2
#6 C_1
#7 C_2
#8 C_3
#9 C_4

data
df <- data.frame(ind = c("A", "B", "C"),
                 effect = c(3, 2, 4))


text:
Q: Integrate $\int\frac{dx}{x\sqrt{x^2+1}}$ I would like to ask for some help regarding the following indefinite integral, tried integration by parts and trigonometric substitution which both brought me to $\int\frac{\sec\theta}{\tan\theta}d\theta$, and from this point it is messy to integrate by parts, any help would be appreciated.
$$\int\frac{dx}{x\sqrt{x^2+1}}$$

A: Multiply the integrand by $\dfrac{x}{x}$, we will have
$$
\int\frac{x\ dx}{x^2\sqrt{x^2+1}}\ dx.
$$
Now, set $u^2=x^2+1\ \Rightarrow\ u\ du=x\ dx$ then
\begin{align}
\int\frac{x\ dx}{x^2\sqrt{x^2+1}}\ dx&=\int\frac{1}{u^2-1}\ du\\
&=\frac12\int\left[\frac1{u-1}-\frac1{u+1}\right]\ du.
\end{align}
The rest should be easy.

A: $$\int \frac{\sec \theta}{\tan\theta} = \frac{\frac 1{\cos \theta}}{\frac {\sin\theta}{\cos\theta}}\,d\theta = \int \frac 1{\sin\theta}\,d\theta = \int \csc\theta \,d\theta$$
Alternatively, given $$\int\frac{dx}{x\sqrt{x^2+1}} = \int\frac{x\,dx}{x^2 \sqrt{x^2 + 1}}$$
$$\text{Put }\;x^2 + 1 = u^2\;\iff \;x^2 = u^2 - 1\; \implies \;u\,du = x\,dx$$
This gives us the integral, after substitution: $$\int \frac{u\,du}{(u^2-1)u}=\int \frac{du}{(u^2-1)} = \frac 12\int \left(\frac 1{u-1} - \frac 1{u+1}\right)\,du$$
I'm sure you can take it from here.

A: Even another aproach to the integral (albeit rather in "philosophical" form in some sence); by substitution $x=1/t$ :
$$\int\frac{\mathrm{d}x}{x\sqrt{1+x^2}}=-\int\frac{\mathrm{d}t}{\sqrt{1+t^2}} = -\operatorname{arcsinh}t = -\operatorname{arcsinh}\frac{1}{x} = -\operatorname{arccsch}x + C $$

A: $$
\begin{aligned}
\int \frac{d x}{x \sqrt{x^{2}+1}} =& \int \frac{1}{x^{2}} d\left(\sqrt{x^{2}+1}\right) \\
=& \int \frac{1}{\left(\sqrt{x^{2}+1}\right)^{2}-1} d (\sqrt{x^{2}+1} )\\
=& \frac{1}{2} \ln \left|\frac{\sqrt{x^{2}+1}-1}{\sqrt{x^{2}+1}+1}\right|+C
\end{aligned}
$$

A: Let $x=\sinh(y),$ hence $$\int\frac1{x\sqrt{x^2+1}}\,\mathrm{d}x=\int\frac1{\sinh(y)\sqrt{\cosh{y}^2}}\cosh(y)\,\mathrm{d}y=\int\frac1{\sinh(y)}\,\mathrm{d}y=\int\frac2{e^y-e^{-y}}\,\mathrm{d}y=\int\frac{2e^y}{e^{2y}-1}\,\mathrm{d}y.$$ Let $z=e^y=e^{\operatorname{arsinh}(x)}=x+\sqrt{x^2+1},$ hence $$\int\frac{2e^y}{e^{2y}-1}\,\mathrm{d}y=\int\frac2{z^2-1}\,\mathrm{d}z=\int\frac{(z+1)-(z-1)}{z^2-1}\,\mathrm{d}z=\int\frac1{z-1}-\frac1{z+1}\,\mathrm{d}z=\begin{cases}\ln\left(-\frac{z-1}{z+1}\right)+C_0&|z|\lt1\\\ln\left(\frac{z-1}{z+1}\right)+C_1&|z|\gt1\end{cases}=\begin{cases}\ln\left(-\frac{x+\sqrt{x^2+1}-1}{x+\sqrt{x^2+1}+1}\right)+C_0&x\lt0\\\ln\left(\frac{x+\sqrt{x^2+1}-1}{x+\sqrt{x^2+1}+1}\right)+C_1&x\gt0\end{cases}$$

A: $\displaystyle\int\frac{dx}{x\sqrt{x^{2}+1}}$
$\displaystyle z^{2}=x^{2}+1\Rightarrow 2zdz=2xdx\Rightarrow xzdz=x^{2}dx=
(z^{2}-1)dx$
$\displaystyle\Rightarrow \frac{dz}{z^{2}-1}=\frac{dx}{xz}$
$\displaystyle\int\frac{dx}{x\sqrt{x^{2}+1}}=\int\frac{dz}{z^{2}-1}=\frac{1}{2}\int(\frac{1}{z-1}-\frac{1}{z+1})dz$
$\displaystyle\int\frac{dx}{x\sqrt{x^{2}+1}}=\frac{1}{2}ln\left| \frac{\sqrt{x^{2}+1}-1}{\sqrt{x^{2}+1}+1} \right|+c$


text:
Q: python-social-auth and facebook login: what is the whitelist redirect url to include in fb configuration? I was getting this facebook login error:

URL Blocked
  This redirect failed because the redirect URI is not
  whitelisted in the app's Client OAuth Settings. Make sure Client and
  Web OAuth Login are on and add all your app domains as Valid OAuth
  Redirect URIs.

Facebook login requires whitelisting of the call-back url.
what is the call back url for django-social-auth or  python-social-auth ?

A: include a url to your website that is the absolute url version of this relative url:
/complete/facebook/
how to find this out?
use Chrome browser dev tools, enable preserve log, try to login to your app.
This question / answer is for django-social-auth but likely applies to python-social-auth too.


text:
Q: How do I rotate a html canvas shape by only using a transform? I am wondering how you can rotate an image by only using the transform function. From my understanding this is not possible, since the only things you can do with transform are the following:

*

*Horizontal scaling

*Horizontal skewing

*Vertical skewing

*Vertical scaling

*Horizontal moving

*Vertical moving

Source: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Transformations
And I don't see how any of these would be able to rotate the shape, is this even possible. I assume it must be possible, since rotate is in-fact a type transformation.

A: 2D transform basics
6 values as 3 vectors
The transform is a set of 6 numbers. The 6 numbers as 3 pairs represent the direction and scale of the x axis, the direction and scale of the y axis, and the position of the origin.
Default transform AKA Identity matrix
The default transform (called the identity matrix) has the values ctx.setTransform(1, 0, 0, 1, 0, 0) meaning that

*

*the x axis is 1 transformed pixel per CSS pixel in the direction {x: 1, y: 0} left to right

*the y axis is 1 transformed pixel per CSS pixel in the direction {x: 0, y: 1} top to bottom

*the origin is at pixel location {x: 0, y: 0} top left corner

Scaling
If we scale the transform we increase the length of the first two vectors. To scale by 2 the transform is ctx.setTransform(2, 0, 0, 2, 0, 0);

*

*the x axis is 1 transformed pixel for every 2 CSS pixel in the x direction {x: 2, y: 0} left to right

*the y axis is 1 transformed pixel for every 2 CSS pixel in the y direction {x: 0, y: 2} top to bottom

*the origin is still top left {x: 0, y: 0}

Rotate and translation
If we want to rotate by 90deg a square 256 by 256 image then the transform is ctx.setTransform(0, 1, -1, 0, 256, 0)

*

*the x axis is 1 transformed pixel per CSS pixel down in the y direction {x: 0, y: 1}

*the y axis is 1 transformed pixel per CSS pixel across in the negative x direction {x: -1, y: 0} right to left

*the origin (where the image 0, 0 will be on the canvas) is  {x: 256, y: 0}

Thus if we run
ctx.setTransform(0, 1, -1, 0, 256, 0);
ctx.drawImage(myImage, 0, 0, 256, 256); // will draw image rotated 90deg CW

We get a rotated image.
A vector
A vector is two values that have a x and y value. The vector defines a direction and length.
Create a rotated unit vector
To convert a direction to a vector we use sin and cos
const myDirection = angle;
const myDirectionAsRadians = angle * (Math.PI / 180);  // convert angle to radians

const x = Math.cos(myDirectionAsRadians)
const y = Math.sin(myDirectionAsRadians)

If we set myDirection to 90 (deg) then x = 0 and y = 1 pointing down the canvas
Using sin and cos creates a vector in any direction. It has a special property in that its length is always 1. We call such a vector a Unit vector. You may sometimes see a vector being normalized. This converts a vector of any length to a unit vector. It is done by dividing the vector x and y by its length.
 function normalize(vector) {
     const length = Math.hypot(vector.x, vector.y);
     vector.x /= length;
     vector.y /= length;
 }

NOTE a vector with zero length eg x: 0, y:0 can not be normalized. Not because it has no length (the length is 0) but because it has no direction.
Scale a rotated vector
We can define an angle and a scale
const myDirection = -90;
const myDirectionAsRadians = -90 * (Math.PI / 180);  // -90 as radians
const myScale = 2;

const x = Math.cos(myDirectionAsRadians) * myScale
const y = Math.sin(myDirectionAsRadians) * myScale

Now for -90 deg the vector is x = 0 and y = -2 pointing up and two CSS pixels long.
Quick rotate vector 90deg CW
For a uniform scale and rotation (the image is always square) all we need is a single vector. For example from the above. x = 0 and y = -2 (pointing up) can be rotated 90 CW by swapping the two components and negating the new x. eg xx = -y and y = x to get xx = 2 and y = 0 2 CSS pixels from left two right. Thus we have the direction and scale of both the x and y axis. With the y axis always 90 CW from the x.
Using the transform to draw
Create rotated and scaled transform
To create a transform that rotates any angle and scales by any amount
 function scaleAndRotate(scale, rotate) { // rotate is in radians
     // get direction and length of x axis
     const xAX = Math.cos(rotate) * scale;
     const xAY = Math.sin(rotate) * scale;
     // get direction and length of y axis that is 90 deg CW of x axis and same length
     const [yAX, yAY] = [-xAY, xAX];  // swap and negate new x

     // set the transform
     ctx.setTransform(xAX, xAY, yAX, yAY, 0, 0);

 }

Drawing an image
Lets create a function that will draw an image anywhere on the canvas that is rotated and scaled uniformly. We will use the center of the image as the reference point
 function drawImageScaleRotate(img, x, y, scale, rotate) {
      // define the direction and scale of x axis
      const xAX = Math.cos(rotate) * scale;
      const xAY = Math.sin(rotate) * scale;

      // create the transform with yaxis at 90 CW of x axis and origin at x, y
      ctx.setTransform(xAX, xAY, -xAY, xAX, x, y);

      // Draw the image so that its center is at the new origin x, y
      ctx.drawImage(img, -img.width / 2, -img.height / 2);

   }

There is much more
When we set the transform with ctx.setTranform we replace the existing transform. This transform remains current. If we use ctx.transform, ctx.rotate, ctx.scale, ctx.translate the transforms are applied to the current transform, you build a transform in stages.
The transform functions are relatively expensive in terms of CPU cycles. That is way using sin and cos to build the matrix is much faster than using ctx.scale, ctx.rotate, ctx.translate to do the same thing starting from default.
Building transforms can become tricky as we need to keep track of what stage we are at.
We generally only use these function not to transform a single image (text, path, or what ever)  but to create linked transforms.
For example a game object like a tank. The body of the tank is transformed (rotated and positioned) then the turret which is rotated with the body but has an additional independent rotation by using ctx.rotate. Full explanation is beyond the scope of this question.
The final function
From all this we can create a simplified function that will draw an image with its center at any location, that is uniformly scaled and rotated
 function drawImageScaleRotate(img, x, y, scale, rotate) {
      const xAX = Math.cos(rotate) * scale;
      const xAY = Math.sin(rotate) * scale;
      ctx.setTransform(xAX, xAY, -xAY, xAX, x, y);
      ctx.drawImage(img, -img.width / 2, -img.height / 2);
   }

To reset the transform to the default use ctx.resetTransform NOTE not fully supported yet or use ctx.setTransform(1,0,0,1,0,0);
Animated transforms faster than CSS + HTML or SVG
Using the above function is the 2nd fastest way to draw animated rotated scaled images, faster than CSS + HTML or SVG. You can literally fill the screen with animated images.
Demo

var w,h;
var image = new Image;
image.src = "https://i.stack.imgur.com/C7qq2.png?s=328&g=1";
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.style.position = "absolute";
canvas.style.top = "0px";
canvas.style.left = "0px";
document.body.appendChild(canvas);
const resize = () => { w = canvas.width = innerWidth; h = canvas.height = innerHeight;}
const rand = (min,max) => Math.random() * (max ?(max-min) : min) + (max ? min : 0);
const DO = (count,callback) => { while (count--) { callback(count) } }

resize();
addEventListener("resize",resize);

const sprites = [];
DO(500,()=>{
    sprites.push({
       xr : rand(w), yr : rand(h),
       x : 0, y : 0, // actual position of sprite
       r : rand(Math.PI * 2),
       scale : rand(0.1,0.25),
       dx : rand(-2,2), dy : rand(-2,2),
       dr : rand(-0.2,0.2),
    });
});

function drawImage(image, spr){
    const xAX = Math.cos(spr.r) * spr.scale;
    const xAY = Math.sin(spr.r) * spr.scale;
    ctx.setTransform(xAX, xAY, -xAY, xAX, spr.x, spr.y);
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
}

function update(){
    var ihM,iwM;
    ctx.setTransform(1,0,0,1,0,0);
    ctx.clearRect(0,0,w,h);
    if(image.complete){
      var iw = image.width;
      var ih = image.height;
      for(var i = 0; i < sprites.length; i ++){
          var spr = sprites[i];
          spr.xr += spr.dx;
          spr.yr += spr.dy;
          spr.r += spr.dr;
          // keeps images in canvas adds space to all sides so that image
          // can move completely of the canvas befor warping to other side
          // I do this to prevent images visualy popping in and out at edges
          iwM = iw * spr.scale * 2 + w;
          ihM = ih * spr.scale * 2 + h;
          spr.x = ((spr.xr % iwM) + iwM) % iwM - iw * spr.scale;
          spr.y = ((spr.yr % ihM) + ihM) % ihM - ih * spr.scale;

          drawImage(image,spr);
      }
    }
    requestAnimationFrame(update);
}
requestAnimationFrame(update);

If you are wondering which is the fastest way to draw animated content. That is via webGL. The above can draw 1000 scaled rotated images on most devices at a good frame rate. WebGL can easily draw 10000 (with extra features eg colored) in the same time.

A: You can rotate your image easily. You can specify angles by which you wants to apply rotation.
Source : https://www.w3schools.com/cssref/css3_pr_transform.asp

A: use transform "rotate".and use it as below

p{
  color:red;
  font-size:12px;
  text-align:center;
}

.rotate1{
  transform:rotate(45deg);
    margin-top:40px;
}

.rotate2{
  transform:rotate(90deg);
  margin-top:40px;
}

.rotate3{
  transform:rotate(180deg);
  margin-top:40px;
}

ROTATE1

ROTATE2

ROTATE3

A: You have ctx.rotate(radians) function.
Read below:
https://www.w3schools.com/tags/canvas_rotate.asp


text:
Q: Rails says task must exist when trying to create a submission I want to create a submission model where a user can create submissions for tasks. Each submission should have a user_id and a task_id. When I try to create a submission, rails returns an error saying that the task must exist.
task model:
has_many :submissions

user model:
has_many :submissions

submission model:
belongs_to :user
belongs_to :task

routes:
resources :tasks do
  resources :submissions
end

submissions controller:
def create
  @task = Task.find(params[:task_id])
  @submission = current_user.submissions.build(submission_params)
  if @submission.save
    flash[:success] = "Submitted!"
    redirect_to task_submission_path(@task, @submission)
  else
    puts @submission.errors.full_messages
    render 'new'
  end
end

def new
  @task = Task.find(params[:task_id])
  @submission = Submission.new
end

def show
  @submission = Submission.find(params[:id])
end

private

  def submission_params
    params.require(:submission).permit(:description)
  end

tasks/show.html.erb:
<% if user_signed_in? %>
  <%= link_to "Submit", new_task_submission_path(@task) %>
<% end %>

submissions/new.html.erb:

Submit

<%= form_for [:task, @submission] do |f| %>

<%= hidden_field_tag :task_id, @task.id %>

    <%= f.text_area :description, placeholder: "File description" %>

  <%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>

submission migration:
def change
  create_table :submissions do |t|
    t.string :description
    t.integer :user_id
    t.integer :task_id

    t.timestamps
  end
end

A: You are not assigning the task, you are only finding it in your create method. Please do this instead:
def create
  @submission = current_user.submissions.build(submission_params)
  @submission.task = Task.find(params[:task_id])
  if @submission.save
    flash[:success] = "Submitted!"
    redirect_to task_submission_path(@task, @submission)
  else
    puts @submission.errors.full_messages
    render 'new'
  end
end

But Rails is able to perform this automatically, if you change the whitelisted params:
def create
  @submission = current_user.submissions.build(submission_params)
  if @submission.save
    flash[:success] = "Submitted!"
    redirect_to task_submission_path(@task, @submission)
  else
    puts @submission.errors.full_messages
    render 'new'
  end
end

private

def submission_params
  params.require(:submission).permit(:description, :task_id)
end


text:
Q: Batch move files & folders including structure with combine Wrote a batch file that was supposed to move folder & file structure from one parent directory to the other on each drive while also combining any existing folders only to find out the MOVE command isnt able to combine.  Cannot use Xcopy or Robocopy because they copy the source to the destination and then delete the source.  Files/folders being moved are very large, so looking for a solution that will move instead of copy/delete...  Code I have written so far is below.  Currently it will move the files/folders that don't need to be combined and then use robocopy to do the rest, but its still taking over 24 hours where a manual CTRL+X and CTRL+V for each drive is instant...  Anyone able to help?
@echo off
REM Last Edited 12/19/21 2:48PM
REM Enter Old Camera Name, New Camera Name
setlocal enableDelayedExpansion
set OldCamName=%~1
set NewCamName=%~2

REM Determine Camera Physical ID from Camera Name

for /F "skip=1" %%F in ('wmic LogicalDisk WHERE DriveType^=3 GET DeviceID') do (
    echo Moving Low Quality on drive %%F%...
    set oldDirectory="%%F%\DW Spectrum Media\low_quality\!OldCamName!"
    set newDirectory=%%F%\DW Spectrum Media\low_quality\!NewCamName!
    FOR /d %%i IN (!oldDirectory!\*) DO (
        move /Y "%%i" "!newDirectory!"
        robocopy "%%i" "!newDirectory!\%%~ni" /E /J /MOVE /NJH /NJS
    )
    echo Moving High Quality on drive %%F%...
    set oldDirectory="%%F%\DW Spectrum Media\hi_quality\!OldCamName!"
    set newDirectory=%%F%\DW Spectrum Media\hi_quality\!NewCamName!
    FOR /d %%i IN (!oldDirectory!\*) DO (
        move /Y "%%i" "!newDirectory!"
        robocopy "%%i" "!newDirectory!\%%~ni" /E /J /MOVE /NJH /NJS
    )
)

A: If you can use PowerShell, it will simplify things greatly. The Move-Item Cmdlet is all you need.

The Move-Item cmdlet moves an item, including its properties, contents, and child items, from one location to another location. ... When you move an item, it is added to the new location and deleted from its original location.

$PathFormat = '{0}:\DW Spectrum Media\{1}\{2}'
$Qualifiers = @( 'low_quality' , 'hi_quality' )

$OldCamName = Read-Host 'Old Camera Name'
$NewCamName = Read-Host 'New Camera Name'

ForEach ( $DriveLetter in (( Get-Volume | Where DriveType -eq 'Fixed' ).DriveLetter -ne $Null ))
{
    $Qualifiers | ForEach{
        $Splat = @{
            'Path'         = ( $PathFormat -f $DriveLetter , $_ , $OldCamName ) + '\*'
            'Destination'  = $PathFormat -f $DriveLetter , $_ , $NewCamName
        }
        ###   Create destination directory if it doesn't exist
        If ( ! (Test-Path $Splat.Dest) ) { mkdir $Splat.Dest }
        Move-Item @Splat  #Boom! :D
    }
}

*

*ForEach-Object

*-f (Format operator)

*about Splatting


text:
Q: mv: Cannot stat - No such file or directory I have piped the output of ls command into a file. The contents are like so:
[Chihiro]_Grisaia_no_Kajitsu_-_01_[1920x816_Blu-ray_FLAC][D2B961D6].mkv
[Chihiro]_Grisaia_no_Kajitsu_-_02_[1920x816_Blu-ray_FLAC][38F88A81].mkv
[Chihiro]_Grisaia_no_Kajitsu_-_03_[1920x816_Blu-ray_FLAC][410F74F7].mkv

My attempt to rename these episodes according to episode number is as follows:
cat grisaia | while read line;
   #get the episode number
   do EP=$(echo $line | egrep -o  "_([0-9]{2})_" | cut -d "_" -f2)
   if [[ $EP ]]
      #escape special characters
      then line=$(echo $line | sed 's/\[/\\[/g' | sed 's/\]/\\]/g')
      mv "$line" "Grisaia_no_Kajitsu_${EP}.mkv"
   fi
done

The mv commands exit with code 1 with the following error:

mv: cannot stat
  '\[Chihiro\]_Grisaia_no_Kajitsu_-01\[1920x816_Blu-ray_FLAC\]\[D2B961D6\].mkv':
  No such file or directory

What I really don't get is that if I copy the file that could not be stat and attempt to stat the file, it works. I can even take the exact same string that is output and execute the mv command individually.

A: If you surround your variable ($line) with double quotes (") you don't need to escape those special characters. So you have two options there:

*

*Remove the following assignation completely:
then # line=$(echo $line | sed 's/\[/\\[/g' | sed 's/\]/\\]/g')`

or

*Remove the double quotes in the following line:
mv $line "Grisaia_no_Kajitsu_${EP}.mkv"

Further considerations

*

*Parsing the output of ls is never a good idea. Think about filenames with spaces. See this document for more information.

*The cat here is unnecessary:
cat grisaia | while read line;
    ...
done

Use this instead to avoid an unnecessary pipe:
while read line;
    ...
done < grisaia

Why is good to avoid pipes in some scenarios? (answering comment)
Pipes create subshells (which are expensive), and you can also make some mistakes as the following:
last=""

cat grisaia | while read line; do
    last=$line
done

echo $last # surprise!! it outputs an empty string

The reason is that $last inside the loop belongs to another subshell.
Now, see the same approach wothout pipes:
while read line; do
    last=$line
done < grisaia

echo $last # it works as expected and prints the last line


text:
Q: Bootstrap 5.2 Carousel wo'nt show the third image I'm trying to have a 3 page carousel that displays my products image and callouts but somehow it's only showing only 2 images it wont go to the third one.
In the {% render 'meliades' %} part I'm only including the image and callout from different page everything is the same except call out position and images.

.BornHS__Wrapper {
  position: relative;
}

.BornHS__Wrapper .BornHS__Close {
  display: none;
}

.BornHS__Wrapper .Content__Wrapper {
  position: relative;
}

.BornHS__Wrapper .BornHS__Modal__Content {
  background: #2b2b2bcc;
  border-radius: 4px;
  box-shadow: 0 0 24px rgba(0, 0, 0, 0.22);
  color: #2b2b2b;
  opacity: 0;
  position: absolute;
  transition: all 0.3s ease-in-out;
  visibility: hidden;
  z-index: 4;
}

.BornHS__Wrapper .BornHS__Modal__Content .Content__Wrapper {
  padding: 10px;
}

.BornHS__Wrapper .BornHS__Modal__Content .Content__Wrapper .BornHS__Title {
  font-size: 16px;
  text-transform: uppercase;
  color: #f4f4f4;
}

.BornHS__Wrapper .BornHS__Modal__Content .Content__Wrapper p {
  font-size: 14px;
  margin: 0;
  padding: 0;
}

.BornHS__Wrapper .BornHS__Input {
  height: 0;
  opacity: 0;
  overflow: hidden;
  position: fixed;
  text-indent: -9999px;
  width: 0;
  z-index: -1;
}

.BornHS__Wrapper .BornHS__Input+.BornHS__Label {
  background: #f4f4f480;
  border-radius: 50%;
  cursor: pointer;
  height: 20px !important;
  position: absolute;
  transition: all 300ms ease;
  width: 20px !important;
  z-index: 2;
}

.BornHS__Wrapper .BornHS__Input+.BornHS__Label:before,
.BornHS__Wrapper .BornHS__Input+.BornHS__Label:after {
  background: #2b2b2b;
  content: "";
  cursor: pointer;
  display: block;
  left: 50%;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
}

.BornHS__Wrapper .BornHS__Input+.BornHS__Label:before {
  height: 2px;
  width: 40%;
}

.BornHS__Wrapper .BornHS__Input+.BornHS__Label:after {
  height: 40%;
  width: 2px;
}

.BornHS__Wrapper .BornHS__Input~.BornHS__Overlay {
  display: none;
  height: 100%;
  left: 0;
  position: absolute;
  width: 100%;
  top: 0;
  z-index: 3;
}

.BornHS__Wrapper .BornHS__Input:checked+.BornHS__Label {
  transform: rotate(45deg);
}

.BornHS__Wrapper .BornHS__Input:checked~.BornHS__Modal__Content {
  opacity: 1;
  visibility: visible;
}

.BornHS__Wrapper .BornHS__Input:checked~.BornHS__Overlay {
  display: block;
}

.BornHS__Wrapper.BornHS__Blur figure {
  -webkit-filter: blur(2px);
  -moz-filter: blur(2px);
  -o-filter: blur(2px);
  -ms-filter: blur(2px);
  filter: blur(2px);
}

.BornHS__Wrapper.BornHS__Blur .BornHS__Input {
  display: none;
}

.BornHS__Wrapper.BornHS__Blur .BornHS__Input+.BornHS__Label {
  opacity: 0.5;
  pointer-events: none;
}

.BornHS__Wrapper.BornHS__Blur .BornHS__Input:checked {
  display: inline-block;
}

.BornHS__Wrapper.BornHS__Blur .BornHS__Input:checked+.BornHS__Label {
  opacity: 1;
  pointer-events: auto;
}

.BornHS__Modal {
  bottom: 0;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  right: 0;
  width: 100%;
  z-index: 1;
}

.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close {
  background: #2b2b2b;
  border-radius: 50%;
  cursor: pointer;
  display: block;
  height: 20px;
  right: -5px;
  position: absolute;
  top: -5px;
  transition: all 300ms ease;
  transform: rotate(45deg);
  width: 20px;
  z-index: 5;
  display: none;
}

.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close:before,
.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close:after {
  background: #fff;
  content: "";
  cursor: pointer;
  display: block;
  left: 50%;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
}

.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close:before {
  height: 2px;
  width: 40%;
}

.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close:after {
  height: 40%;
  width: 2px;
}

/* START - 428 - START */

@media (max-width: 428px) {
  .BornHS__Wrapper .BornHS__Modal__Content .Content__Wrapper .BornHS__Title {
    font-size: 12px;
    text-transform: uppercase;
  }
  .callOutProductTitle {
    font-size: 20px !important;
  }
  .callOutProductSKU {
    font-size: 14px !important;
  }
  .callOutProductPage {
    font-size: 12px !important;
    color: #9b8642 !important;
  }
  #meliades-circle-1 {
    left: 67%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 30%;
    top: 48%;
  }
  #meliades-circle-4 {
    left: 47.5%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 46.5%;
  }
  #meliades-circle-6 {
    left: 93%;
    top: 21.5%;
  }
  #meliades-content-1 {
    left: 7%;
    top: 26%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 6%;
    top: 37%;
  }
  #meliades-content-4 {
    left: 13%;
    top: 68%;
  }
  #meliades-content-5 {
    left: 57%;
    top: 55%;
  }
  #meliades-content-6 {
    left: 47.5%;
    top: 11%;
  }
}

/* END - 428 - END */

/* START - 768 - START */

@media (min-width: 768px) {
  #meliades-circle-1 {
    left: 71%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 29%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 48%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 49%;
  }
  #meliades-circle-6 {
    left: 95%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 18%;
    top: 30%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 11.5%;
    top: 43%;
  }
  #meliades-content-4 {
    left: 22.5%;
    top: 64%;
  }
  #meliades-content-5 {
    left: 56%;
    top: 53%;
  }
  #meliades-content-6 {
    left: 64.5%;
    top: 16%;
  }
}

/* END - 768 - END */

/* START - 1024 - START */

@media (min-width: 1024px) {
  #meliades-circle-1 {
    left: 71%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 30%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 57%;
    top: 48%;
  }
  #meliades-circle-6 {
    left: 95%;
    top: 23%;
  }
  #meliades-content-1 {
    left: 31.5%;
    top: 32%;
  }
  #meliades-content-2 {
    left: 82%;
    top: 45%;
  }
  #meliades-content-3 {
    left: 17%;
    top: 44%;
  }
  #meliades-content-4 {
    left: 50%;
    top: 63%;
  }
  #meliades-content-5 {
    left: 58%;
    top: 51%;
  }
  #meliades-content-6 {
    left: 72%;
    top: 18%;
  }
}

/* END - 1024 - END */

/* START - 1280 - START */

@media (min-width: 1280px) {
  #meliades-circle-1 {
    left: 58%;
    top: 39%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49.2%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 45.5%;
  }
  #meliades-circle-6 {
    left: 72%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 58.8%;
    top: 44%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 29.5%;
    top: 40%;
  }
  #meliades-content-4 {
    left: 49.8%;
    top: 65%;
  }
  #meliades-content-5 {
    left: 55.5%;
    top: 51%;
  }
  #meliades-content-6 {
    left: 72.7%;
    top: 14%;
  }
}

/* END - 1280 - END */

/* START - 1366 - START */

@media (min-width: 1366px) {
  #meliades-circle-1 {
    left: 58.1%;
    top: 38%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49.3%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 46%;
  }
  #meliades-circle-6 {
    left: 72%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 58.6%;
    top: 43%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 30.2%;
    top: 41%;
  }
  #meliades-content-4 {
    left: 49.8%;
    top: 65%;
  }
  #meliades-content-5 {
    left: 55.7%;
    top: 51%;
  }
  #meliades-content-6 {
    left: 72.7%;
    top: 15%;
  }
}

/* END - 1366 - END */

/* START - 1440 - START */

@media (min-width: 1440px) {
  .imageSize {
    width: 50%;
  }
  #meliades-circle-1 {
    left: 60%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49.2%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55.5%;
    top: 45%;
  }
  #meliades-circle-6 {
    left: 72.5%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 60.5%;
    top: 41%;
  }
  #meliades-content-2 {
    left: 82%;
    top: 45%;
  }
  #meliades-content-3 {
    left: 30.5%;
    top: 42%;
  }
  #meliades-content-4 {
    left: 49.5%;
    top: 64%;
  }
  #meliades-content-5 {
    left: 56%;
    top: 49%;
  }
  #meliades-content-6 {
    left: 73.2%;
    top: 15%;
  }
}

/* END - 1440 - END */

/* START - 1920 - START */

@media (min-width: 1920px) {
  #meliades-circle-1 {
    left: 57%;
    top: 40.5%;
  }
  #meliades-circle-2 {
    left: 76%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 50%;
  }
  #meliades-circle-4 {
    left: 49.5%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 46.5%;
  }
  #meliades-circle-6 {
    left: 73%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 57.5%;
    top: 44%;
  }
  #meliades-content-2 {
    right: -20%;
    top: 45%;
  }
  #meliades-content-3 {
    left: 33%;
    top: 44%;
  }
  #meliades-content-4 {
    left: 50%;
    top: 64%;
  }
  #meliades-content-5 {
    left: 55.5%;
    top: 50%;
  }
  #meliades-content-6 {
    left: 73.5%;
    top: 17%;
  }
}

/* END - 1920 - END */

/* START - 2560 - START */

@media (min-width: 2560px) {
  #meliades-circle-1 {
    left: 60.5%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49.5%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 47%;
  }
  #meliades-circle-6 {
    left: 73%;
    top: 23%;
  }
  #meliades-content-1 {
    left: 60.8%;
    top: 40%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 34.8%;
    top: 45%;
  }
  #meliades-content-4 {
    left: 49.8%;
    top: 62.5%;
  }
  #meliades-content-5 {
    left: 55.4%;
    top: 49.5%;
  }
  #meliades-content-6 {
    left: 73.4%;
    top: 19%;
  }
}

/* END - 2560 - END */

@-webkit-keyframes sonar {
  from {
    box-shadow: 0 0 0 0 #f4f4f4, 0 0 4px 2px rgba(0, 0, 0, 0.4);
  }
  to {
    box-shadow: 0 0 0 10px rgba(255, 147, 223, 0), 0 0 4px 2px rgba(0, 0, 0, 0.4);
  }
}

@keyframes sonar {
  from {
    box-shadow: 0 0 0 0 #f4f4f4, 0 0 4px 2px rgba(0, 0, 0, 0.4);
  }
  to {
    box-shadow: 0 0 0 10px rgba(255, 147, 223, 0), 0 0 4px 2px rgba(0, 0, 0, 0.4);
  }
}

.sonar {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #000000;
  border: 1px solid #2b2b2b;
  -webkit-animation: sonar 1300ms ease-out infinite;
  animation: sonar 1300ms ease-out infinite;
}

.callOutProductTitle {
  font-size: 30px;
}

.callOutProductSKU {
  font-size: 18px;
}

.callOutProductPage {
  font-size: 14px;
  color: #9b8642 !important;
}

.callOutProductPage:hover {
  color: #9b8642 !important;
  text-decoration: underline;
}

.callOutDiv {
  padding-top: 20px;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

      {% render 'meliades' %}

      {% render 'white-matera' %}

      {% render 'mezuzah' %}

  <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleInterval" data-bs-slide="prev">

    Previous
  </button>

  <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleInterval" data-bs-slide="next">

    Next
  </button>


text:
Q: como enviar objeto a un componente en Angular? Hola ya conozco el concepto de enviar un componente con ayuda de Input, el problema es quiero enviar datos que estan siendo sacados por medio de un NgFor
Mi componente padre es el 'modify.component.ts' y genera una variable de tipo Alumno (es una clase)
Mi 'padre es este' es el que enviara los datos y la variable que enviare sera alumno
export class ModifyComponent implements OnInit {

  alumno : Alumno[];
  res : number;
  show : boolean;

  @ViewChild('err')err:ElementRef; //referencia a objeto del html
  @ViewChild('help')help:ElementRef;

  constructor(private listarService : ListarService) { }

  ngOnInit(): void {
    this.obternerAlumnos();
  }

  obternerAlumnos(){
  this.listarService.obtenerAlumnos().subscribe(
  respuesta => {
    this.res = Object.keys(respuesta).length;
    if(this.res >= 1){
      this.alumno = respuesta;
      this.alumno.forEach(a => a.show = false);
    }else{
      this.err.nativeElement.style.display = 'block';
    }
  }
);

}
}
El html del padre es este:
<form action="submit" class="container-fluid">

Selecciona que estudiante quieres modificar

-- Sin datos :( --

{{a.nombre}}

    <button (click)="a.show = !a.show" type="button">
      mode
    </button>

<ng-template #elseBlock><app-mod-help [a] = "alumno"></app-mod-help></ng-template>

</form>

Con un for recorro el conjunto de 'alumnos' y cuando presiono el botón abre un componente dependiendo cual alumno haya seleccionado, por ejemplo, si imprimo 3 datos y le pico al botón 2, debajo de este se ejecuta el ng-template llamando a mi componente app-mod-help entonces a ese le quiero enviar el 'alumno' de ese índice
Mi componente hijo es el siguiente
export class ModHelpComponent implements OnInit {

@Input() a: Alumno;

constructor() { }

ngOnInit(): void {
     console.log(a);
}
}

Y me tira estos errores:

A: El problema que veo esta acá
<ng-template #elseBlock><app-mod-help [a] = "alumno"></app-mod-help></ng-template>

justo en [a]="alumno" en el for tu declaras let a of alumno entonces el código debería ser
<ng-template #elseBlock><app-mod-help [a]="a"></app-mod-help></ng-template>


text:
Q: How to have a Python glue job return when called in step function? I have a glue job, in python, that I call from a step function. The step function successfully starts the job. The job successfully finishes. But the step function never moves to the next step. Is there some required configuration/permission for the step function to respond to job success? Something to do in the python script?
Here is the step function (state machine) definition:
"MyGlueTask": {
  "Type": "Task",
  "Resource": "arn:aws:states:::glue:startJobRun.sync",
  "Parameters": {
    "JobName": "my_glue_job"
  },
  "ResultPath": "$.MyGlueTask",
  "Next": "NextGlueJob"
}

A: The solution to my actual problem was permissions. You need four permissions when running a startJogRun.sync:

*

*glue:StartJobRun

*glue:GetJobRun

*glue:GetJobRuns

*glue:BatchStopJobRun

Those are actually the Terraform values, but should help anybody struggling with this.

A: Are you sure it never moves to the next step? Maybe it does, but, for instance, in 5 minutes?
I'm asking that because Step Functions has the limitation: even if your Glue job executes in a few seconds, Step Functions polls the results from Glue job once every 5 minutes actually.
A kind of workaround you could implement is to change arn:aws:states:::glue:startJobRun.sync to arn:aws:states:::glue:startJobRun — then Glue job task just will trigger the Glue job and will move to the next step.
Most likely, you will need to wait the Glue job finished and get some result out of there. Therefore, you need to wrap the previous state with a few more ones.

*

*The main purpose is to merely start the Glue job. Apart from that, we need Glue job RunJobId.
I don't know if it can be retrieved from Glue job itself, so I've created a Lambda to run the Glue job using boto3 start_job_run function and then get RunJobId from the response.

*Create a Lambda which will be grabbing the status (JobRunState) of the Glue job (via boto3 get_job_run function) by RunJobId from the previous step.

*Using Wait Step Functions state type, run the Lambda you created every N seconds.

*Use Choice state type to filter Glue job statuses out.

*

*If RUNNING, go back to the Wait step.

*If SUCCEEDEED, then go ahead to the next state.

*If [FAILED | STOPPED], go wherever else.

Finally, it looks something like this.


text:
Q: Slide Panel Up and Down I have the following Fiddle Example:

  Close

  Close
  Lorem ipsum dolor sit amet

  Open Map

  Open Text

    Integer mattis felis in felis eleifend ...

#map {border: solid 1px red;}

#text {border: solid 1px blue;}

img {display: block;}

div.panel {
  position: relative;
  overflow: hidden;
  display: none;
}

div.panel a {
  background-color: yellow;
  color: @red;
  display: inline-block;
}

I need the following:

*

*When a trigger is clicked slide down / up toggle the panel with id the same as in its href.

*When the button Close inside a panel is clicked slide up that panel.
I was able to kind of solve it using the following:
$('#open-map').click(function(){
    var $helper = $('#map');
    $helper.animate({
        height: "toggle"
    }, {
        duration: 200,
        progress: function(){
           $helper.scrollTop( $helper[0].scrollHeight );
        }
    });
});

*

*I do not know how to use the Trigger class and how to make the Close work.

*I am also not sure if animate is the best option.

A: WORKING FIDDLE
$('#open-map').click(function(){
    $('#map').slideToggle('slow');
});
$('#open-text').click(function(){
    $('#text').slideToggle('slow');
});
$('.close').click(function(){
    $(this).parent().slideUp('slow');
});

Works for map and text both.

A: One further approach, which makes it a little more expandable (so long as you associate the  elements' href attribute with the id of the targeted element) is:
// binding a click-handler to the  elements:
$('a.close').on('click', function (e) {
    // slide-toggling the closest
 ancestor element,
    // although slideUp() could be used, since if the element is hidden the
    // a.close element can't be clicked:
    $(this).closest('.panel').slideToggle();
});

// binding a click handler to the .trigger elements:
$('.trigger').on('click', function () {
    // getting a reference to the clicked-element:
    var clicked = $(this),
        // forming an array of all the sibling .trigger elements,
        ids = clicked.siblings('.trigger')
                  // adding back the clicked element:
                  .addBack().map(function () {
                      return this.getAttribute('href');
                  }).get();
    // finding all the elements associated with those .trigger elements:
    $(ids.join(',')).each(function () {
        // iterating over the collection with each(),
        // if the href attribute (not property) of the clicked element
        // contains the string of the id of the current element at
        // an index of 1:
        if (clicked.attr('href').indexOf(this.id) === 1) {
            // we slideToggle() the relevant element:
            $(this).slideToggle();
        } else {
            // otherwise we simply close the element:
            $(this).slideUp();
        }
    });
});

$('a.close').on('click', function(e) {
  $(this).closest('.panel').slideToggle();
});

$('.trigger').on('click', function() {
  var clicked = $(this),
    ids = clicked.siblings('.trigger').addBack().map(function() {
      return this.getAttribute('href');
    }).get();
  $(ids.join(',')).each(function() {
    if (clicked.attr('href').indexOf(this.id) === 1) {
      $(this).slideToggle();
    } else {
      $(this).slideUp();
    }
  });
});
.panel {
  display: none;
}
.trigger {
  display: block;
}

 Close

 Close
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce imperdiet, urna id dignissim venenatis, mi metus convallis purus, et tincidunt nunc leo sit amet lectus. Nullam vitae efficitur purus. Nulla facilisi. Praesent mauris massa, ullamcorper ut
  varius vitae, porttitor id augue.

 Open Map
  Open Text

References:

*

*JavaScript:

*

*Element.getAttribute().

*String.prototype.indexOf().

*jQuery:

*

*addBack().

*closest().

*get().

*map().

*on().

*siblings().

*slideToggle().

*slideUp().

A: $('#close-map').click(function(){
var $helper = $('#map');
$helper.animate({
            height: "toggle"
        }, {
        duration: 200,
        progress: function(){
            $helper.scrollTop( $helper[0].scrollHeight );
        }
    });
});

just add this block to make close link work , where #close-map is id of close link


text:
Q: How often does garbage collector gets called in Xamarin.Android application? I have the following class:
public class CurrentOrder
{
    //contains current order values which is global to all application
    public static List<OrderArticleViewModel> listOfOrderArticles = new List<OrderArticleViewModel>();
    public static string orderCustomerName;
    public static string orderCustomerId;
    public static string orderNumber;
    public static string orderDateAndHour;
    public static DateTime executionOrderDate = DateTime.Now.AddDays(1);

    private CurrentOrder()
    {
    }

}

I use its fields throughout the whole application as global variables for example like that: CurrentOrder.orderNumber . When I am on certain activity and press the back button I want to clear all class fields values and I am doing it like that:
CurrentOrder.listOfOrderArticles = new List<OrderArticleViewModel>();
CurrentOrder.orderCustomerName = null;
CurrentOrder.orderCustomerId = null;
CurrentOrder.orderNumber = null;
CurrentOrder.orderDateAndHour = null;
CurrentOrder.executionOrderDate = DateTime.Now.AddDays(1);

But as far as I know the value of these fields stays in memory, the only thing is now my variables point to another place. If I click the back button 1000 times I will have 1000 times the fields in the memory nothing referencing them. I've heard that the garbage collector takes care to destroy the values that nothing is pointing at them but how often that occurs? Is it posible to press back button 100 times without the garbage collector cleaning?

A: There is no fixed time interval between garbage collections. Garbage collector called based upon the size of the remaining allocatable memory. Both c# and java are object-oriented language, so we don't need to allocate and release memory manually like c/c++.
Garbage collector will help developer to release memory. Xamarin.Android is using c# language, so it needs CLR to help process to manage memory(Native Android based on ART and Dalvik).
Here are conditions that when the GC will be called:

Garbage collection occurs when one of the following conditions is true:
1.The system has low physical memory. This is detected by either the low memory notification from the OS or low memory indicated by the host.
2.The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
3.The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

And I think memory churn will prove that GC called doesn't have a fixed interval.
About your question:

Is it posible to press back button 100 times without the garbage collector cleaning?

It is based on your Android system environment( Your app is foreground or background? Is there enough memory?). But it will be gc finally.
So, about memory question, I think the memory leak and OOM( mainly due to Bitmap) should be got more attention. And memory churn also should be avoid, because it will effect Android render(UI Performance).


text:
Q: React Apollo Query/Mutation Typescript I need help trying to typescript a mutation and Query. The documentation and examples are limited and i'm struggling to manage to understand how to do it. I don't really understand the last property from the documentation. It seems to be input, response, variables, ?. https://www.apollographql.com/docs/react/recipes/static-typing
query and mutation below where I had to use any:
interface Data {
  loading: DataValue<boolean> | undefined;
  isLinkValid: DataValue<boolean> | undefined;
}
interface InputProps {
  location: {
    search: string;
  };
  showToast: Function;
}
interface Variables {
  id: string | string[] | null | undefined;
}

const validateLinkQuery = graphql<InputProps, Data, Variables, Data>(VALIDATE_LINK_MUTATION, {
  options: ({ location }) => {
    const params = QueryString.parse(location.search);
    const id = params.id;
    return {
      variables: { id },
    };
  },
  props: ({
    ownProps,
    data,
  }: {
    ownProps: {
      showToast: Function;
    };
    data?: any;
  }) => {
    const { validateLink, loading, error } = data;
    if (error) {
      ownProps.showToast(
        Type.ERROR,
        get(error, 'graphQLErrors[0].message', 'An error occured on the validate link query')
      );
    }
    return {
      isLinkValid: validateLink,
      loading,
    };
  },
});

const validateUserMutation = graphql(
  VALIDATE_CARD_MUTATION,
  {
    props: ({ ownProps, mutate }) => ({
      validateCard: (access: SubmitAccessInput) =>
        mutate({
          variables: {
            access,
          },
        })
          .then((response: any) => response)
          .catch((error: any) => {
            ownProps.showToast(
              Type.ERROR,
              get(error, 'graphQLErrors[0].message', 'An error occurred while signing up for an account')
            );
          }),
    }),
  }
);```

A: I would use https://github.com/dotansimha/graphql-code-generator library which generator type and React Apollo HOC component with type based on your graphql schema.
After you can do something like this.
import * as React from "react";
import { Mutation } from "react-apollo";
import { gql } from "apollo-boost";
import { RouteComponentProps } from "react-router-dom";

import { LoginMutationVariables, LoginMutation } from "../../schemaTypes";
import { meQuery } from "../../graphql/queries/me";
import { userFragment } from "../../graphql/fragments/userFragment";
import { Form } from "./Form";

const loginMutation = gql`
  mutation LoginMutation($email: String!, $password: String!) {
    login(email: $email, password: $password) {
      ...UserInfo
    }
  }

  ${userFragment}
`;

export class LoginView extends React.PureComponent<RouteComponentProps<{}>> {
  render() {
    return (
      <Mutation<LoginMutation, LoginMutationVariables>
        update={(cache, { data }) => {
          if (!data || !data.login) {
            return;
          }

          cache.writeQuery({
            query: meQuery,
            data: { me: data.login }
          });
        }}
        mutation={loginMutation}
      >
        {(mutate, { client }) => (
          <Form
            buttonText="login"
            onSubmit={async data => {
              // optional reset cache
              await client.resetStore();
              const response = await mutate({
                variables: data
              });
              console.log(response);
              this.props.history.push("/account");
            }}
          />
        )}
      </Mutation>
    );
  }
}

Here LoginMutationVariables and LoginMutation type are being generated through graphql-code-generator.
graphql-code-generator also generate `React Apollo Mutation/Query Hoc component with type for all mutation and queries. So you don't even need to pass these type.  After generating HOC component, you can write same component like this
<LoginMutationComponent>
... rest of the code
</LoginMutationComponent>

rather than doing like this
<Mutation<LoginMutation, LoginMutationVariables>

But you need to configure graphql-code-generator. if you want to generate HOC component for queries and mutation


text:
Q: When converting mkv to mp4, the audio is lost I have converted my .mkv file into an .mp4 by using the command:
sudo avconv -i input.mkv -codec copy output.mp4

I am trying to play the mp4 file in the browser, but the audio is not playing. The video player shows that it is on mute, but the button is disabled so you cannot turn it off of mute.
Other mp4s are working, but they were not converted from .mkv. Any help would be much appreciated.

A: In an MP4 container, browsers usually support only H.264 video and either AAC or MP3 audio.  The output from your avconv command should show the format of your video and audio; look under "Input #0" for the lines that start with "Stream #".  If you audio is not already AAC or MP3 you will want to convert it instead of just copying it to the MP4 container.  You can copy the video and convert only the audio with a command like this:
avconv -i input.mkv -c:v copy -c:a libmp3lame -q:a 2 output.mp4

The -c:v copy will copy the video, and -c:a libmp3lame will convert the audio to MP3 using the libmp3lame encoder.  -q:a 2 sets the audio quality; use a lower number for better quality (and a larger file).  You could instead convert to AAC audio if your avconv was configured with non-free codecs enabled and a good quality AAC encoder.


text:
Q: batch for opening explorer window in path I've been toggling between commandlines and windows explorer recently and I'd prefer a smoother transition.  So, if I could open an explorer window to the current directory it'd be nice, and easier to shut down a pile of windows.
I tried ex.bat
%~d1
cd "%~p1"
start "" "explorer.exe %~dp1"

but the result opens to default location.  I feel like I'm close and it's a syntax error , OR it has an interesting solution.  Thanks for any help!

A: I believe what you are looking is following
start "explorer ."

. represents current directory.
Or you could simply use explorer . without start command


text:
Q: ReferenceError when trying to new up 'Audio' object within web worker function buildBlobUrl(func) {
  let blobUrl = URL.createObjectURL(new Blob(['(',
    func.toString(),
    ')()'
  ], {
    type: 'application/javascript'
  }));
  return blobUrl;
}

function webWorkerFunction() {
  let audio = new Audio();
}

let blobUrl = buildBlobUrl(webWorkerFunction);
let webWorker = new Worker(blobUrl);

If I run the above code, I get an error saying Uncaught ReferenceError: Audio is not defined. Is there anyway I can utilize the Audio object within my web worker function?

A: No,
The Audio constructor does return an HTMLAudioElement DOM Element, and Web Workers don't have access to the DOM, we thus can't create DOM Elements from there.
And since we still can't really have a BaseAudioContext in a Worker either, there is no true alternative to playing this media 100% from the Worker.


text:
Q: Parrallel ongoing for each file loop? I want to continuously monitor some log files. What I have below works if I switch the tail -F for cat $log_file. When I use -tail -F the first log file works but because its process doesn't finish it blocks the top while loop.
How can I background each process so that the outer while read log_file starts a process for each log file? (also tried adding & in various places to background the inner while loop)
ls /var/log/myApp-*.log | while read log_file ; do
  tail -F $log_file while read log ; do
    echo send $log to external tracker for $log_file if X
  done
done

A: This solution uses awk to parse the output of tail and call a command with system() if the event is detected.
Also, you might want to avoid parsing the output of ls and using globbing instead.
for log_file in /var/log/myApp-*.log; do
    tail -F $log_file | awk '{l=gensub(/.+\"level\": ([0-9]+).+/,"\\1","g",$0); if(l>50 && l!= $0){system("echo command")}}' &
done


text:
Q: Find the number of rearrangements of the string 12345 in which none of the sequences 12, 23, 34, and 45 occur. My attempt: Let $A_{1}$ denote where 12 occurs, $A_{2}$ denote where 23 occurs, $A_{3}$ denote where 34 occurs, $A_{4}$ denote where 45 occurs.
|$A_{1} \cup A_{2} \cup A_{3} \cup A_{4}$|= |$A_{1}$|+|$A_{2}$|+|$A_{3}$|+|$A_{4}$|-(|$A_{1}A_{2}$|+|$A_{1}A_{3}$|+|$A_{1}A_{4}$|+|$A_{2}A_{3}$|+|$A_{2}A_{4}$|+|$A_{3}A_{4}$|)+|$A_{1}A_{2}A_{3}$|+|$A_{1}A_{2}A_{4}$|+|$A_{1}A_{3}A_{4}$|+|$A_{2}A_{3}A_{4}$|-|$A_{1}A_{2}A_{3}A_{4}$|
I don't know if I'm doing this write or not. I tried to glue the 12, 23, 34, and 45 together but I don't think this is correct. The total ways this can be done with no restrictions is |U|=5!
The actual answer is: 5!-[96-3+8-1]=53.
If someone can tell me how to get this answer that would be excellent.

A: Yes, your approach is correct. Note that $|A_i|=4\cdot 3!=24$, $|A_iA_j|=6$, $|A_iA_j A_k|=2$ and $|A_1A_2A_3A_4|=1$. Hence
$|A_{1} \cup A_{2} \cup A_{3} \cup A_{4}|$ is equal to
$$\binom{4}{1}\cdot |A_i|-\binom{4}{2}\cdot |A_iA_j|+\binom{4}{3}\cdot |A_iA_j A_k|-\binom{4}{4}\cdot |A_1A_2A_3A_4|.$$
which implies that the number of those permutations is $|U|-|A_{1} \cup A_{2} \cup A_{3} \cup A_{4}|$:
$$5!-(4\cdot 24-6\cdot 6+4\cdot 2-1)=120-(96-36+8-1)=53.$$
Alternative approach. Let $p(n)$ be the number of permutations of $[1,\dots,n]$ having no substring $[k,k+1]$ with $1\leq k\leq n-1$. Then  $p(1) = 1$,
$p(2) =1$ and, for $n\geq 2$ it satisfies the recurrence
$$p(n+1) = n p(n) + (n-1)p(n-1).$$
Hence $p(3)=2p(2)+p(1)=3$, $p(4)=3p(3)+2p(2)=11$ and $$p(5)=4p(4)+3p(3)=44+9=53.$$

A: This is basically the right approach. You just have to work out the sizes of the various intersections. A couple of examples. Consider $A_2\cap A_3$.
This consists of permutations where $2$ is followed by $3$ and $3$ by $4$.
So these are arrangements of "blocks", $1$, $234$ and $5$, so
$|A_2\cap A_3|=3!$ of these. On the other hand $A_2\cap A_4$ counts
arrangements of blocks $1$, $23$ and $45$ so again
$|A_2\cap A_4|=3!$, etc.


text:
Q: ReactJS with NGINX: How to run an SPA alongside other proxied locations on NGINX? I have successfully deployed a MERN stack website to a Ubuntu 20.x server using pm2 and nginx.  The issue I'm facing is that URL links manually entered, or links redirected from my Express routes don't work.  This is because I have my nginx config file set up like this:
        location / {
                root /root/amfmfx.com/build;
                index index.html;
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a
                # 404.
                try_files $uri $uri/ =404;
        }

        location /user {
                proxy_pass http://loadbalancer;
                proxy_buffering         on;
        }

        location /api {
                proxy_pass http://loadbalancer;
                proxy_buffering         on;
        }

        location /email {
                proxy_pass http://loadbalancer;
                proxy_buffering         on;
        }

The /usr, /api, and /email locations are my backend route receivers.  I have Routes and Links set up in React that work perfectly when clicked on, but if I type in 'http://mywebsite.com/login' it comes back with an nginx error, because it's trying to send /login to the backend apparently.
How can I configure my nginx web server to allow for manual link entries to be read by the front end, while still sending route requests to my Express server?
Thanks!

A: As you have the root and index in your root location any non-matching location will not have a default webroot. I would change the configuration for your react app to

server {
        // listen, server_name and friends ...

        root /root/amfmfx.com/build;
        index index.html;

        location / {
          try_files $uri $uri/ /index.html;
        }

        location /user/ {
          proxy_pass http://loadbalancer;
          proxy_buffering         on;
        }

        location /api/ {
          proxy_pass http://loadbalancer;
          proxy_buffering         on;
        }

        location /email/ {
          proxy_pass http://loadbalancer;
          proxy_buffering         on;
        }
}

I would define the locations for your backend services using a trailing slash like /api/ and /email/ for example. Reason is that without the slash nginx would match your user location for a incomming request to  /userbob in the same it would do for user.
2nd the proxy_buffering can be removed IF your are not turning it off on server or http level as on is default.
https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering


text:
Q: Spring '18 Component lightning:recordEditForm Not Working as Expected <aura:component>
<lightning:recordEditForm objectApiName="Contact">
    <lightning:messages />
    <lightning:inputField fieldName="FirstName" />
    <lightning:inputField fieldName="LastName" />
    <lightning:inputField fieldName="CleanStatus" />

    <lightning:button class="slds-m-top_small" variant="brand" type="submit" name="update" label="Update" />
</lightning:recordEditForm>

While run the above component on app, I got following error

This page has an error. You might just need to refresh it.
   [Error in $A.getCallback() [Cannot read property 'value' of undefined]]

Anyone can say the reason and solution for this?

A: I found the solution for the above case. It is a Field Accessibility issue. While I check the Field Accessibility of that particular field, that exist with 'Hidden' for that particular record type. When I changed that to 'Editable', it works fine.