text:
Q: Executing a shell script via Node.js won't work using gsutil command to move files to Google Cloud Storage buckets I'm trying to move a Ubuntu 17.10.1 directory to google cloud storage bucket via a node js app.  I've chosen to execute a shell script using the child process module. The script look like this.
#!/bin/bash

echo START $1
declare -r MODEL_NAME=$1
declare -r PROJECT_ID=XXX-XXXX
declare -r JOB_NAME="${MODEL_NAME}_$(date +%Y%m%d_%H%M%S)"
declare -r BUCKET_NAME="gs://XXX-XXXX-mlengine"
declare -r GCS_PATH="$BUCKET_NAME/$JOB_NAME"
gsutil -m cp -r ./training/$MODEL_NAME $GCS_PATH
echo ALL DONE!

This works as expected when called from a terminal.
When I call it from my node app it says it can't find gsutil and returns an error.  I'm using the child_process execFile to do the external shelling.  If I comment out the gsutil line all is well.  I've tried using "wait" to no avail.  Prior efforts with the child_proccess_promise module produced and error message saying it could not find gsutil.
const child = execFile('tensor_flow/file_process.sh', [trainingName], (error, stdout, stderr) => {
    if (error)  console.log(error);
    if (stderr)  console.log(stderr);
    if (stdout) console.log(stdout);
  });

This produces these error messages:
tensor_flow/file_process.sh: line 12: gsutil: command not found
training-prep.js:26
tensor_flow/file_process.sh: line 14: wait: `PID': not a pid or valid job spec
START T2
training-prep.js:27
ALL DONE!

Any help or insight would be appreciated or ... if you could point me to a "move the directory to a bucket" via node directly I'd like to know about that.
Thanks,
JJ
PS. I've sudo'd all of the above in the course of this effort and I've done this with and without the wait/PID stuff.

A: If you are using NODE.js you can use the Google Cloud Storage Node.js Library.
You should use the createWriteStream method to upload a file to your GCS bucket:
var fs = require('fs');
var storage = require('@google-cloud/storage')();
var myBucket = storage.bucket('my-bucket');

var file = myBucket.file('my-file');

//-
//
Uploading a File

//
// Now, consider a case where we want to upload a file to your bucket. You
// have the option of using {@link Bucket#upload}, but that is just
// a convenience method which will do the following.
//-
fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
  .pipe(file.createWriteStream())
  .on('error', function(err) {})
  .on('finish', function() {
    // The file upload is complete.
  });

If you want to make a parallel upload using gsutil command being executed by node.js you can follow this thread. There I combined the third solution by @hexacyanide with the official gsutil docs and it worked for me:
const { exec } = require('child_process');
exec('gsutil -m cp -r /full_path_to_your_directory gs://your-bucket', (err, stdout, stderr) => {
 if (err) {
   // node couldn't execute the command
   return;
 }
 // the *entire* stdout and stderr (buffered)
 console.log(`stdout: ${stdout}`);
 console.log(`stderr: ${stderr}`);
});

The child_process package is a Node.js native module.


text:
Q: Google Firebase hosting not provisioning SSL for custom domain I'm trying to map a Firebase Hosting app to a custom domain. I've followed this process more than 40 times on other apps but for some reason, this site just isn't playing ball.
In Firebase Hosting I've added the custom domain and validated the domain with a txt record. Google Webmaster Central is showing that the domain has been validated and I'm a verified owner. I then added the a- record and this has fully propagated (added over 7 days ago). It is definitely the correct IP address.
TXT record google-site-verification=K4i4LrHOe9pcXXUbcanyZ_IUsz1E5Sq2kjR6c9Yn4H0 shown on https://www.whatsmydns.net/#TXT/kingston.ac.uk
A-record shown on https://www.whatsmydns.net/#A/experience.kingston.ac.uk and this is working as the site loads when you bypass the security error.
Firebase has switched to saying the custom domain is "Pending" but normally the SSL is provisioned within an hour or two. It's been stuck at this stage for 7 days and Firebase Support have not responded to my support ticket for more than 4 days now.
I tried removing the custom domain and added it again but it didn't make any difference.
Thanks!

A: It turns out the reason the SSL wouldn't provision was that the domain was utilising CAA records that restricted SSL provisioning to certain CA providers. Once CAA records had been added to the sub-domain as follows it was provisioned within minutes.
experience.kingston.ac.uk.  IN  CAA 0 issue "pki.goog"
experience.kingston.ac.uk.  IN  CAA 0 issue "letsencrypt.org"
experience.kingston.ac.uk.  IN  CAA 0 issuewild ";"

redpajama_set_name: RedPajamaStackExchange


text:
Q: eventReactive with 2 action button across 2 tabs I have an app with 2 tabs, each has an action button. I want the same process to be triggered if either buttons is pressed. So I wrote it the following way:
library(shiny)

ui <- fluidPage(
  tabsetPanel(
    tabPanel("tab1",
      actionButton("btn1","Button 1"),
      textOutput("text")
    ),
    tabPanel("tab2",
      actionButton("btn2","Button 2")
    )
  )

)

server <- function(input, output) {
  data=eventReactive(c(input$btn1,input$btn2),{
    print("Button is pressed!")
    print(input$btn1)
    print(input$btn2)
    iris
  })
  output$text=renderText({
    req(data())
    print(head(data()))
    "Really? Button is pressed!"
  })
}

# Run the application
shinyApp(ui = ui, server = server)

And I don't understand why the eventReactive expression is triggered when the app initialize, before any button is pressed.
If I only work with 1 button, i.e. input$btn1 instead of c(input$btn1, input$btn2) then I get the expected behaviour, but not with 2 dependencies.
Can someone enlighten me?

A: eventReactive has a argument ignoreInit, which defaults to False, see help(eventReactive).
Your issue is resolved my modifying the following line:
data=eventReactive(c(input$btn1,input$btn2),{

to
data=eventReactive(c(input$btn1,input$btn2),ignoreInit = T,{

I hope this helps!

A: My guess is that the expression automatically evaluates to TRUE and hence it executes on load. Rather you should be using {} to listen from two buttons.
Modified code:
library(shiny)

ui <- fluidPage(
  tabsetPanel(
    tabPanel("tab1",
             actionButton("btn1","Button 1"),
             textOutput("text")
    ),
    tabPanel("tab2",
             actionButton("btn2","Button 2")
    )
  )

)

server <- function(input, output) {
  data=eventReactive({
    input$btn2
    input$btn1},{
    print("Button is pressed!")
    print(input$btn1)
    print(input$btn2)
    iris
  })
  output$text=renderText({
    req(data())
    print(head(data()))
    "Really? Button is pressed!"
  })
}

# Run the application
shinyApp(ui = ui, server = server)


text:
Q: How to get some common data in a custom ConstraintValidator I am validating a input class using Java validation api and hibernate validator.
i have created few custom annontation for some business validation and i am using these annotation on the input class. below is an example of such annotation validator -
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class DBColumnConstraintValidator implements   ConstraintValidator<DatabaseColumnConstraint, Object> {

private DBColumnConstraintValidator databaseColumnConstraint;

private final List<DatabaseConstraintValidationStep> steps = new ArrayList<DatabaseConstraintValidationStep>();

@Override
public void initialize(DBColumnConstraintValidator  databaseColumnConstraint) {

}

@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {

    //Validation logic

}

}
I want to use some data for my validation logic inside isValid() method and this data is common and will be used by few other validator classes as well.
is there any way to set or make  that common data available to isValid() method?

A: If you are using CDI or Spring, you can simply use dependency injection (e.g. using @Inject) within your constraint validator implementation to obtain whatever contextual service or data your need.


text:
Q: Ajuste de branches locais antes de dar commit Sou novato no Git e preciso fazer um ajuste de forma rápida em meus branches.
Comecei a uma atividade em um branch local errado "X".
Gostaria de migrar as alterações para um branch local "Y" para dar commit a partir de "Y" e desfazer as alterações em X.
Como faço para criar um branch Y a partir de X local antes de desfazer as alterações de X?
Estou utilizando Visual Studio 2017 com a extensão do Git para VS.

A: Primeiro você cria uma branch nova:
git branch Y

Ela já estará com as modificações feitas na branch X. Se quiser verificar se está tudo certo, faz um git checkout Y e testa as modificações feitas.
Na branch X para você retornar ao ultimo commit é só utilizar:
git revert HEAD~1

Lembrando que o HEAD~1 irá voltar apenas um commit(o ultimo) se você utilizar HEAD~2 irá voltar a dois commits e assim por diante.


text:
Q: How does $E$ closed follow from the upper semicontinuity of the spectrum? Let $f$ be an analytic function for a domain $D$ of $\mathbb{C}$ into a Banach algebra $A$. Suppose that, for all $\lambda \in D$, $\text{Sp}f(\lambda)$ is finite or a sequence converging to $0$.
Suppose that $\mu \neq 0$ and $\mu \in \text{Sp}f(\lambda_0)$ for some $\lambda_0 \in D$.
Consider the set $E = \{ \lambda \in D: \mu \in \text{Sp}f(\lambda) \}$.
B. Aupetit mentions in a proof he writes for Theorem 3.4.26 in his book A Primer on Spectral Theory, that this set $E$ is closed by the upper semicontinuity of the spectrum. I am struggling to see why this is true.
Can anyone please point me in the right direction as to how I can show that $E$ is closed by the upper semicontinuity of the spectrum?

A: Upper semicontinuity of the spectrum is the following statement: if $U$ is a neighbourhood of $\text{Sp}(x)$, then there is a neighbourhood $V$ of $x$ such that $\text{Sp}(y) \subset U$ for all $y \in V$.
Suppose $\lambda \in D \backslash E$.  That is, $\lambda \in D$ but $\mu \notin \text{Sp}(f(\lambda))$.  Thus $U = \mathbb C \backslash \{\mu\}$ is a neighbourhood of $\text{Sp}(f(\lambda))$.  By upper semicontinuity of the spectrum, there is a neighbourhood $V$ of $f(\lambda)$ such that $\mu \notin \text{Sp}(y)$ for all $y \in V$.
Since $f$ is continuous, $f^{-1}(V)$ is a neighbourhood of $\lambda$,
and this is disjoint from $E$.  Thus $D \backslash E$ is open.


text:
Q: Scapy is quiting after receiving packet I tried to sniff some packets with scapy. I used this code from http://www.secdev.org
 sniff(filter="icmp and host 66.35.250.151", count=2)

(with an existing host, of course)
but when scapy receive the first packet, scapy quits by itself and nothing else happens. It returns to the standard terminal (as if I had typed in quit() )
I use:
Python 2.7.2
Mac 10.8.5

A: Looking at the example on the site you referenced it seems you need more code to view what was captured. Looking at the demo page there are a few more calls going on;
>>>  sniff(filter="icmp and host 66.35.250.151", count=2)
<Sniffed: UDP:0 TCP:0 ICMP:2 Other:0>
>>>  a=_
>>>  a.nsummary()
0000 Ether / IP / ICMP 192.168.5.21 echo-request 0 / Raw
0001 Ether / IP / ICMP 192.168.5.21 echo-request 0 / Raw
>>>  a[1]
<Ether dst=00:ae:f3:52:aa:d1 src=00:02:15:37:a2:44 type=0x800 |<IP version=4L
 ihl=5L tos=0x0 len=84 id=0 flags=DF frag=0L ttl=64 proto=ICMP chksum=0x3831
 src=192.168.5.21 dst=66.35.250.151 options='' |<ICMP type=echo-request code=0
 chksum=0x6571 id=0x8745 seq=0x0 |<Raw load='B\xf7g\xda\x00\x07um\x08\t\n\x0b
 \x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d
 \x1e\x1f !\x22#$%&\'()*+,-./01234567' |>>>>
>>> sniff(iface="wifi0", prn=lambda x: x.summary())
802.11 Management 8 ff:ff:ff:ff:ff:ff / 802.11 Beacon / Info SSID / Info Rates / Info DSset / Info TIM / Info 133
802.11 Management 4 ff:ff:ff:ff:ff:ff / 802.11 Probe Request / Info SSID / Info Rates

(this is a small snippet from the demo page itself for example only)


text:
Q: Sometimes Date() returns January 1st Sometimes I'm experiencing the following issue and I've been struggling with it for months now - also couldn't find any solutions yet:
I'm creating a new Date() object but it's not today's date, but this year's January 1st.
This happens both on Simulator and actual devices and the only way to fix it is to use NSDate() instead. Any ideas why this is happening?
let date = Date()
print(date) // prints 2019-12-31 22:00:00 +0000 - Jan 1st adjusted to CEST timezone

let date = NSDate()
print(date) // prints 2020-07-29 07:50:25 +0000

Edit: Updated with screenshot


text:
Q: Question about Definition of Boundary in Stokes' Theorem I was wondering if what my teacher said was correct and complete in that in Stokes' Theorem the "boundary curve" of a surface can be defined as the mapping along the boundary of the two-dimensional region from which the surface is parameterized. For example, if a surface $\mathbf r(u,v)$ is a mapping from the u-v plane to x-y-z space, then the boundary of $\mathbf r(u,v)$ is the curve that you get from mapping from the u-v plane to x-y-z along the boundary of the domain region in the u-v plane.
Thanks in advance!
Edit: I was discussing with my teacher and we think the above is the case (although I would really like someone to please confirm) but interestingly depending on how you parameterize a surface you may get similar but not exactly the same results for the boundary curve by following the above method, although you do get equivalent results if you account for direction, and the same answer via two parametrization makes me think I'm on the right track. To demonstrate what I mean let me use an example. Call the surface S the part of the sphere $x^2+y^2+z^2=4$ above the plane $z=1$. The boundary curve is obviously the intersection of the plane and the sphere, that is the circle $x^2+y^2=3$ (and $z=1$). It seems from the fact that we can get this result using the method that traces the out the boundary curve by mapping to the surface along the domain using two different parametrizations that this definition of a boundary curve is correct (though note that the spherical one requires that two parts cancel each other out). Example:
Cartesian Coordinates
We can write the surface S as $\mathbf r(x,y)= \big<x,y,\sqrt{4-x^2-y^2}\big>$ (where we take the positive root since $z\geq1 \rightarrow z\geq0$). Now, the surfaces is a mapping of  all $(x,y)$ from the "filled-in circle" $x^2+y^2\leq3$ to it via $z=\sqrt{4-x^2-y^2}$, so tracing along the boundary of the planar domain region $x^2+y^2\leq3$, that is, $x^2+y^2=3$, and mapping to the surface gives the boundary curve $x^2+y^2=3$ with $z=1$ (the first part of which is given by the fact that the domain of the curve we are tracing along the surface is $x^2+y^2=3$ and the $z=1$ part we got from plugging in). Now in spherical coordinates we get a similar result for the boundary curve.
Spherical Coordinates
We can write S as $\mathbf r(\phi,\theta) = \big<2\sin\phi\cos\theta,2\sin\phi\sin\theta,2\cos\phi\big> $ where $0\leq\theta\leq2\pi$ and $0\leq\phi\leq\frac{\pi}{3}$. This gives us a rectangular domain in the "$\phi$-$\theta$" plane (where $\phi$ is where the x-axis would be and $\theta$ where the y-axis would be and the surface is a mapping from the rectangle into x-y-z space) bounded by the coordinate axis and the lines $\theta = 2\pi$ and $\phi=\frac{\pi}{3}$. Update: Here's an image:

Going along the bottom ($\theta =0, \phi$ varying to $\frac{\pi}{3}$) gives us a downward arch along the sphere from the top to the bounding circle. Similarly, going along the right gives us the bounding circle, going along the top gives the arch but in the opposite direction (so they cancel -- I presume) and at $\phi=0$ moving down the last side of the rectangle (where $\theta$ is varying from $2\pi$ back to $0$) all we get is a point which doesn't contribute to the curve leaving us with the same boundary curve to S. To recap, as we map to the surface alone the boundary of the domain, we go from the "north pole", down a longitude to the 60-degree latitude, around the latitude 360 degrees and back up the same longitude to the north pole, gibing us the boundary circle.
In both cases you get the "boundary ring" by mapping to the surface along the boundary of the planar domain region. I was wondering if this method can be a general definition of the boundary of a surface. If someone could confirm or correct that would be great.

A: You are asking a very good question. The problem, however, that a proper answer to it lies beyond the class you are taking. You should consider reading, say, Spivak's Calculus on Manifolds
or  the book by Guillemin and Pollack Differential Topology.
Here is the upshot: There is a concept of an (oriented) differential manifold with boundary, it is a bit abstract, but the key is that it allows you to define the notion of boundary which is independent of the parameterization that you use. A 2-dimensional manifold is simply a surface. Instead of trying to "parameterize" a surface $S$ (or, more generally, a manifold $M$) via a single map of a planar region, you consider a collection of maps from the closed upper half-plane $\{(x,y): y\ge 0\}$ to your surface. These maps $f_i$ (called charts) are required to be 1-1, which allows you to consider the compositions $f_i^{-1} \circ f_j$. These compositions are called transition maps. Each transition map is required to be differentiable (say, infinitely-differentiable, just to be on the safe side). The boundary points of the $S$  are defined as points which are images of points of the x-axis under charts. One verifies that if $p$ is in the image of the x-axis under one chart, then the same is true for any other chart whose image contains $p$.
Another useful thing that you learn by reading either of these books is that Stokes' theorem holds not only for surfaces with boundary but for manifolds with boundary of arbitrary dimension and in this form it includes all fundamental theorems of multivariable calculus (Stokes, Green, Gauss) and can be written as
$$
\int_{M} d\omega = \int_{\partial M} \omega,
$$
where $M$ is a compact $k$-dimensional manifold with boundary $\partial M$,  $\omega$ is a differential form of degree $k-1$ on $M$  (this is a replacement of vector fields which you see in the multivariable calculus), while $d\omega$ is the exterior derivative of $\omega$, which is the proper replacement of Curl and divergence.


text:
Q: Redirecting to page with a slug First off, I'm not using any PHP frameworks nor do I currently have an htaccess file. I plan to add an htaccess file soon once I'm complete.
I'm trying to have my page redirect to a variant of a page using a slug after pressing a submit button.
The page's url is: abc.php?user=$username. The page has an edit button where the user can edit the contents of the table's row. I started off trying to just update an image using the code shown below:
else{
    $username = $_GET['user'];

    $users = $db->prepare("
        SELECT * FROM users WHERE username = :username LIMIT 1
    ");
    $users->bindParam(':username', $_SESSION['user']['username']);
    $users->execute(['username' => $username]);
    $users = $users->fetch(PDO::FETCH_ASSOC);

if(isset($_FILES['files'])) {       // uploads picture to the database
            foreach($_FILES['files']['name'] as $file => $name) {
                $filename = $name;
                try{
                    if(move_uploaded_file($_FILES['files']['tmp_name'][$file],'uploads/'.$filename)) {
                        $stmt = $db->prepare("UPDATE users SET image = :image WHERE id = :id");
                        $stmt->bindParam(":image", $filename);
                        $stmt->bindParam(":id", $_SESSION['user']['id']);
                        $stmt->execute();
                    }
                } catch(Exception $e) {
                    echo $e;
                }
            }
        }

My problem is that when I submit the changes through the edit page, it redirects to abc.php without any slug. I have tried adding

header("Location: abc.php?user=".$username);

Question: How can I get it to redirect to the page with a slug?

A: Oh, I figured out that it was just the action in my form(not shown).
For anyone experiencing this issue, the form should be looking like this:
<form action="abc.php?user=<?php echo $username; ?>" method="POST">

</form>


text:
Q: Is there any way to change the mac dock's position with a keyboard shortcut? I don't think there are default shortcuts for that. But I assume you could make one using AppleScript or other automation programs.
I found this post from 2012 asking the same question. I tried making the script provided in the comments but couldn't make it work.
I'm not sure if it isn't working because Apple Scripts are different now, or because the script per se doesn't work or because there are steps I'm skipping.
When I try to save the script it says

"Expected "given", "with", "without", other parameter name, etc. but found identifier."

Any idea?

A: The reason you get the Syntax Error:

Expected "given", "with", "without", other parameter name, etc. but found identifier.

From:
defaults write com.apple.Dock orientation -string left;killall Dock

In Script Editor is because it is not AppleScript code!
It's a compound command to run in Terminal; however, it can be run in AppleScript by using the do shell script command:
do shell script "defaults write com.apple.Dock orientation -string left;killall Dock"

That said though, I'd choose not to use it because the result of killall Dock with unhide all hidden windows and can be very disruptive and messy.
An alternative is to use UI Scripting1 with System Preferences, and this can be done in a less disruptive manner then killall Dock. 1Note that using UI Scripting may require accessibility privileges be granted.
The following example AppleScript code will toggle the position of the Dock between the Bottom and the Left side of the screen:
This was tested in Script Editor and works under macOS High Sierra.
if running of application "System Preferences" then
    try
        tell application "System Preferences" to quit
    on error
        do shell script "killall 'System Preferences'"
    end try
end if

repeat while running of application "System Preferences" is true
    delay 0.01
end repeat

tell application "System Preferences" to ¬
    reveal anchor "Main" of pane id "com.apple.preference.dock"

tell application "System Events" to tell application process "System Preferences"
    repeat while not (exists (window "Dock"))
        delay 0.1
    end repeat
    tell radio group 1 of window "Dock"
        if value of radio button "Bottom" is 1 then
            click radio button "Left"
        else if value of radio button "Left" is 1 then
            click radio button "Bottom"
        end if
    end tell
end tell

quit application "System Preferences"

This example AppleScript code can be used in an Automator Service (Quick Action in macOS Mojave) using a Run AppleScript action, and assigned a keyboard shortcut in: System Preferences > Keyboard > Shortcuts > Services

Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

A: This AppleScript code works for me using the latest version of macOS Mojave.
tell application "System Events" to tell dock preferences
    if screen edge is bottom then
        set screen edge to left
    else if screen edge is left then
        set screen edge to bottom
    end if
end tell

In Automator, create a new Service or Quick Action and add a run AppleScript action to that workflow, adding the above AppleScript code.  Then in System Preferences you can create a keyboard shortcut for that new service.


text:
Q: Why is it that the equation of a massless scalar field *must* be conformal invariant? I'm reading a paper [1], p.111 where it is said that:

However, the equation of scalar field with zero mass must be conformal
  invariant while equation $\square\varphi=0$ does not satisfy this
  requirement by any means. The conformal invariant equation is:
  $$\square \varphi + \frac{n-2}{4(n-1)}R\varphi = 0 $$
  where $R$ is the
  scalar curvature of space-time and $n$ is its dimensionality.

Question: why is it that the equation of a massless scalar field must be conformal invariant?
This question is related to this other question: https://mathoverflow.net/q/270088/

*

*[1] : Quantum theory of scalar field in de Sitter space-time, N. A. Chernikov and E. A. Tagirov, 1968


text:
Q: Can i revert back to syncdb after installing SOUTH I installed SOUTH and migrated few apps. now i want to go back to syncDB and uninstall SOUTH.
Can i go back

A: Yes.

*

*Stop your server.

*First, backup your database to be on
the safe side.

*Execute:
./manage.py sqlclear south | ./manage.py dbshell
(this is
probably buggy on windows.  Use copy
and paste instead of the pipe.)

*Remove south from your
INSTALLED_APPS settings.


text:
Q: JS/CSS : transition not occurring unless within a setTimeout If I make a loop to dynamically add elements that do a transition on the transform , why does this example not work:
function changeSize() {
   for (let x = 0; x < 99; x++) {
      let el = document.createElement('div');
      el.style.translate = 'transformX(0px)';

      el.style.translate = 'transformX(150px)';
      el.style.transition = 'all 2s ease';

      let body = document.body;
      body.appendChild(el);
   }
}

but this does work as long as I add even a really small timeout:
function changeSize() {
   for (let x = 0; x < 99; x++) {
      let el = document.createElement('div');
      el.style.translate = 'transformX(0px)';

      // now it will transition
      setTimeout(() => {
         el.style.translate = 'transformX(150px)';
         el.style.transition = 'all 2s ease';
      }, 50)

      let body = document.body;
      body.appendChild(el);
   }
}

A: When you set transform and then reset it within the same thread, it just changes the value and takes on the later value. The setTimeout brings everything to a different thread on the browser level (not the javascript level, because js is single-threaded), causing the animation to occur when the value is changed. However, javascript like this is often unpredictable in different browsers - rather, use a css to make such transitions.

function changeSize() {
  for (let x = 0; x < 99; x++) {
    let el = document.createElement("div");
    el.innerHTML = "hi"
    el.style.transition = "all 2s ease";
    setTimeout(function() {
      el.classList.add("transition");
    }, 1)  /*Brings everything to a different thread.
When the browser sees this, it's like - oh look, a setTimeout, I need to move this to a time thread,
so when the time completes I can execute the function! So it does that.
Since the time is very little, it completes within a short amount of time.
The browser sees this, and realizes that it needs to execute the function - so it removes it from it's
execution stack and executes it.
When executing, it sees that the thread is asking for a classList change for the element el.
So, it changes the class, triggering any css with it (in this case the transform css).
Since the element has a transition, it appropriately transitions during the translation.
*/
    document.body.appendChild(el);
  }
}
changeSize()
.transition {
  transform: translate(100px, 0);
}

Note the value 1 for the setTimeout, because some browsers don't wait for the value 0 (as in move it to a separate stack).
Now, you might be wondering, why is this 'unpredictable'? Well, this is because with such a short timeout period, it can execute along with other code in the main thread. If you have code in the main thread that changes the element's css, then the browser will have a clash, and will do different things depending on which one gets executed first. However, if you use a class and then change the element's style itself later on, the style will override the class since it is applied to the element directly rather than through the means of a class.


text:
Q: Problems getting network traffic logs from loaded webpage using python and webdriver Using Python and webdriver (selenium)
I need to load a web-page in webdriver and capture network traffic from it.
I have read alot of useful information by googling that helped me on the way.
ie. Selenium - python. how to capture network traffic's response
I can get some of the logs, but i can not get the network-traffic-log

Basically, i do something similar to the below:
(i can not show all the code here, but this basically it):
d = DesiredCapabilities.CHROME
d['goog:loggingPrefs'] = {'browser': 'ALL'}

driver = webdriver.Chrome(chrome_options=my_options,
                          executable_path=my_driver_destination,
                          desired_capabilities=d,
                          service_args=["--verbose"])

Open a webpage and perform some magic
driver.get("http://somethingsomething")

By calling get_log at this point, can i get some logs out (depending on what state my loaded page is)
logs_for_me = driver.get_log("driver")  # "performance" "browser" "server" "client"

However, i can not find any network-logs at this point (only driver and browser -logs). What am i missing ?
If i cant' get it as a parseable object, can i force the driver itself to spool the log to file so i can get it there?


text:
Q: Woocommerce addons showing twice for a product in multiple categories I have a the premium woocommerce addons plugin. I've added the fields for most of the categories however it appears if a product is added into multiple categories, it'll showing the addon options twice.
I figured it would be a priority setting but that only changes the order on the page rather than ruling it on or the other.
Is it possible to set one product addon set as having priority over another?


text:
Q: Handling multiple QNA KBs & skill bots in Luis Essentially, my company has a dispatch model chatbot built in Botframework, Luis & QNA Maker. We typically have one skill bot and one KB per subject area, which is leading to some issues in the dispatch model not knowing how to route an utterance because the skill bot intent & KB intent have so much overlapping vocabulary. Wondering the best way to handle this -- I've tried to clean up our utterances to make it clearer, but I'm wondering if I should just create a KB intent within the skillbot, and only let the dispatch route to skill bots. It just doesn't seem to fit within the design recommendations from Microsoft.
Current design:
     - Dispatch model
         - Area 1 skill bot intent
         - Area 1 KB intent
         - Area 2 skill bot intent
         - Area 2 KB intent
     - Skill bots
         - Area 1 skill bot
         - Area 2 skill bot

If no intents have a high confidence rating, then route to a chitchat KB.
My idea to fix the AI confusion:
- Dispatch model
     - Area 1 skill bot intent
     - Area 2 skill bot intent
- Skill bots
     - Area 1 skill bot
         - Area 1 KB intent
         - Area 1 other intents
     - Area 2 skill bot
         - Area 2 KB intent
         - Area 2 other intents

Thoughts?


text:
Q: How to handle Camel Exchange differently depending on where it originated? I have a route with multiple entry points (servlet and direct). It needs to do certain work when activated through the servlet. This work must be done for servlet requests (even in the presence of bad actors). In the case of exchanges that come through direct, this work must not be done. Here is an example in code:
// In a Route Builder somewhere.
from("servlet:///myService").inOut("direct:myService");
from("direct:myService").process(new ConditionalProcessor());

// Implementation of processor above.
public class ConditionalProcessor implements Processor {

    @Override
    public void process(Exchange exchange) throws Exception {
        if(comesFromServlet(exchange)){
            // Logic for Servlet.
        } else {
            // Logic for direct and other.
        }
    }

    /**
     * Must return true if the exchange started as a request to the servlet.
     * Otherwise must return false.
     *
     * @param exchange
     * @return
     */
    public boolean comesFromServlet(Exchange exchange){
        // What goes here?
    }

}

A: There is also an API on Exchange that tells you from which endpoint it was created.
http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/Exchange.html#getFromEndpoint()
exchange.getFromEndpoint().getEndp

An alternative is that if you assign id's to your routes, you can also obtain this
String fromRoute = exchange.getFromRouteId();

You can use .routeId("myRouteId") to assign id to a route
from("servlet:///myService").routeId("myRouteId")

A: I was inspired by this comment from another post. Here is my solution:
// In a Route Builder somewhere.
from("servlet:///myService")
    .setHeader(ConditionalProcessor.PROPERTY, constant(true))
    .inOut("direct:myService");
from("direct:myService").process(new ConditionalProcessor());

// Implementation of processor above.
public class ConditionalProcessor implements Processor {
    public static final String PROPERTY = "came.from.servlet";
    @Override
    public void process(Exchange exchange) throws Exception {
        if(comesFromServlet(exchange)){
            // Logic for Servlet.
        } else {
            // Logic for direct and other.
        }
    }

    public boolean comesFromServlet(Exchange exchange){
        return exchange.getProperty(PROPERTY, true, Boolean.class);
    }

}


text:
Q: Why does this program 'stop-short' - not trying all permutations? I am trying to write a simple Noughts-and-Crosses (Tic-tac-Toe) evaluator in Prolog.
The first thing I am trying to do is to have the program calculate all possible winning boards. The logic isn't complete yet - it doesn't check for valid boards that could result from the actual playing of the game - it is simply looking for any 'lines-of-3'.
The problem is, the program 'stops-short' : it correctly detects lines-of-3 and unifies the variables that make up the line-of-3 - but doesn't show the combinations of the other variables. (The cells which do not lie on the winning-line that is).
Here's my program and an example output:
/*
Attempting to create a program that will output 'x' ,'o' or 'none'
given a (filled-in) tic-tac-toe board.
'x' - 'x' has won. (Literally there is a line of x's)
'o' - 'o' as above
'none' : no winners on the given board.

This does NOT check whether the board is in a valid state for tic-tac-toe!
*/

/* Define board states as facts */
cell(none).
cell(x).
cell(o).

/* Define winning line of 3 */
win_line(C1, C2, C3, Winner) :-
        cell(C1),
        cell(C2),
        cell(C3),
        C1 \== none,
        C1==C2,
        C2==C3,
        Winner=C1.

/* define the board rule: variables are 'encoded' for each cell by a coordinate (col,row) */
board(  C11, C12, C13,
        C21, C22, C23,
        C31, C32, C34, Winner) :-
        win_line(C11, C12, C13, Winner); /* Test the three rows */
        win_line(C21, C22, C23, Winner);
        win_line(C31, C32, C33, Winner);
        win_line(C11, C21, C31, Winner); /* Test the three columns */
        win_line(C12, C22, C32, Winner);
        win_line(C13, C23, C34, Winner);
        win_line(C13, C23, C34, Winner); /* Test the two diaganols */
        win_line(C11, C22, C34, Winner);
        win_line(C13, C22, C31, Winner).

My query , with the output follows:
| ?- board(C11,C12,C13, C21,C22,C23, C31,C32,C33, o).

C11 = o
C12 = o
C13 = o ? a

C21 = o
C22 = o
C23 = o

C31 = o
C32 = o

C11 = o
C21 = o
C31 = o

C12 = o
C22 = o
C32 = o

C13 = o
C23 = o
C33 = o

C13 = o
C23 = o
C33 = o

C11 = o
C22 = o
C33 = o

C13 = o
C22 = o
C31 = o

(4 ms) yes

Version information:
GNU Prolog 1.3.0
By Daniel Diaz
Copyright (C) 1999-2007 Daniel Diaz
| ?-

A: I see you've fixed your first problem.
One way to get all possible results to a query is using findall/3:
?- findall([A,B,C,D,E,F,G,H,I], board(A,B,C,D,E,F,G,H,I,o), Results).
Results = [[o,o,o,_,_,_,_,_,_],
           [_,_,_,o,o,o,_,_,_],
           [_,_,_,_,_,_,o,o,o],
           [o,_,_,o,_,_,o,_,_],
           [_,o,_,_,o,_,_,o,_],
           [_,_,o,_,_,o,_,_,o],
           [_,_,o,_,_,o,_,_,o],
           [o,_,_,_,o,_,_,_,o],
           [_,_,o,_,o,_,o,_,_]]

Note that it only takes into account the values that actually matter in this case, leaving the other values alone.
If you need to have the other values locked to actual atoms, there are ways to do that, though it involves writing another couple of predicates to find all possible combinations of values to get you that result, for each result in Results.

A: Got it, I think - I have altered the board rule like this:
/* define the board rule: variables are 'encoded' for each cell by a coordinate (col,row) */
board(  C11, C12, C13,
        C21, C22, C23,
        C31, C32, C34, Winner) :-
        cell(C11), cell(C12), cell(C13),
        cell(C21), cell(C22), cell(C23),
        cell(C31), cell(C32), cell(C33),
        win_line(C11, C12, C13, Winner); /* Test the three rows */
[...]as before

So add in the further clauses that every variable unifies with a cell fact...Not 100% sure why I needed to do that...but it seems to work...


text:
Q: django/south : redundant add_column? I made a change, adding a unique constraint to a model, within the abc application and did a
 ./manage.py schemamigration abc --auto

That created a migration file but as well as the expected change the new migration file also contained a number of add_column statements which are adding columns which were previously added in an earlier migration (and which have been the subject of a migrate)
I'm really puzzled as to why this has happened and what to do about it.
Will the add_column statements just be ignored if I do another migrate ?

A: OK thanks to the #django-south irc channel I've figured this out.
This type of problem can arise when activity has taken place in different source control branches and, as a result of a merge, the dictionary of frozen models, which appears at the bottom of a south migration file, is missing some stuff which has already taken place. The result of this is that the next schemamigration tries to produce the "missing" changes.
The fix is to manually edit the migration file which was created by the schemamigration before doing migrate. This will get things back into synch.
There's some information about issues in the later part of this section : http://south.readthedocs.org/en/latest/tutorial/part5.html#team-workflow .
Thanks to carljm and maney on #django-south for helping me with this.


text:
Q: how can I remove direct debit payment option from PayPal Plus's payment selection page I have integrated PayPal Plus that is working fine. But as per PayPal plus its showing payment selection option wall that is showing by default three options - 1 - PayPal 2 - Direct debit 3 - credit card
I want to remove direct debit as our system doesn't want to get payments from direct debit, how can I remove Direct Debit payment option from PayPal Plus's payment selection page ?
I have tried to read out PayPal plus documentation and try to find out what would be the possible ways to remove direct debit. but I could not find one. any insight would be really appreciated. Thank You

A: I checked with someone familiar with PayPal Plus integrations in Germany, and this is not possible to do. You cannot disable individual payment methods, you either get them all or you go back to the basic PayPal option.


text:
Q: Avoid rendering of specific .md files from blogdown::serve_site() I have a file located at
content/post/data_for_posts/my_file.md
I have it there because it's quite easy to do htmltools::includeMarkdown("data_for_posts/my_file.md") and recycle this file in different posts.
My problem is that when I serve_site() this creates a public/post/data_for_posts/index.html, which means, it gets posted to my website (as a January 1 of 0001). I guess I could change the date to year 10000, but I would rather handle it the way I handle the .Rmd and other files, as suggested here
I have tried to modify my config.toml but have not managed to solve the issue.
ignoreFiles = ["\\.Rmd$", "\\.Rmarkdown$", "_files$", "_cache$", "content/post/data_for_posts/my_file.md"]

A: Here are a couple techniques that I use to do this:

*

*Rename data_for_posts/my_file.md so it uses a file extension that hugo does not interpret as a known markup language, for example change .md to .markd or mdn.[*]

*Rename data_for_posts/my_file.md so it includes a string that you will never use in a real content file, for example data_for_posts-UNPUBLISHED/my_file.md. Then add that string (UNPUBLISHED or whatever) to your config ignoreFiles list.[**]

[*] In the content/ directory, a file with one of the following file extensions will be interpreted by hugo as containing a known markup language: .ad, .adoc, .asciidoc, .htm, .html, .markdown, .md, .mdown, .mmark, .pdc, .pandoc, .org, or .rst (this is an excerpt of something I wrote).
[**] The strings listed in ignoreFiles seem to be case sensitive so I like to use all-upper-case characters in my ignored file names (because I never use upper-case chars in real content file names). Also note that there is no need to specify the path and my experience is that path delimiters (/ or \) cause problems.


text:
Q: is there any limit in key and value for hashtables in powershell 5.1? I  am using PowerShell 5.1 and adding the key, value content in hashtables. but I see, it is not adding the complete content in value when the value is too large around 6000 characters. So, my question is:  Is there any limit while we use PowerShell hashtables, if yes, what could be the other way to save the content as key and value pair.
    $inputFileJson = @{}
$inputFileJson.Add($config.NAME,$config.VALUE)
$inputFileJson | ConvertTo-Json -Depth 20 | Out-File -Encoding utf8 $localDir\"\\input.json\" -Force

A: There is not a limit to hashtables, but there is a -Depth 20 limit you defined for how many levels deep ConvertTo-Json will convert nested values to JSON-format. You are likely hitting the depth limit, not a content size limit. Once this limit gets hit, the next object will simply be a .ToString() representation of the object, and will not delve into further nested values.
You can specify up to 100 levels deep with ConvertTo-Json -Depth 100. However, I find that determining how deep my object actually is, determining how much additional depth to account for, etc. is more trouble than it's worth. Unless you really need to truncate objects more than a certain level deep, just use -Depth 100.


text:
Q: Equivalent norm on $X$ in which $X$ is strictly convex
Let $(X,\left\|\cdot\right\|)$ be a separable normed space and $\left\{x_{n}\right\}$ be a dense subset of $\{x \in X:\|x\|=1\}$. Show that there is a sequence $\left\{f_{n}\right\}$ in $BL(X, \mathbb{K})$ such that $\left\|f_{n}\right\|=1$ for all $n$ and for every $x \neq 0$ in $X, f_{n}(x) \neq 0$ for some $n$. Moreover,
$$
\|x\|_{0}=\left(\sum_{n=1}^{\infty} \frac{\left|f_{n}(x)\right|^{2}}{2^{n}}\right)^{1 / 2}
$$
$\|\cdot\|_{0}$ defined above for $x \in X$ is a norm on $X$, in which $X$ is strictly convex and $\|x\|_{0} \leq\|x\|$, for all $x \in X$. Consequently, show there is an equivalent norm on $X$ in which $X$ is strictly convex.

I will be be using Hahn-Banach Extension theorem and the following lemma: Let X be a normed linear space over $\mathbb{K} = \mathbb{C}/\mathbb{R}$ and $0\ne a \in X$ , then there exists $f \in X' = BL(X,\mathbb{K})$ such that $f(a)=\|a\| \ne 0$ and $\|f\|_{op} = 1$.
My attempt: Construct a sequence of functions $f_n$ from the above lemma such that $f_n(x_n) = \|x_n\| = 1\ne 0$ for given sequence $x_n$ and $\| f_n\|_{op}=1$. Now, for every $x \ne 0 \in X$, there exists $m \in \mathbb{N}$ such that $x/\|x\|$ lies in a $\epsilon$-ball centered at $x_m$ where the linear functional $f_m$ is non zero as $f_m(x_m) \ne 0$ (I am a little unsure about this). This finishes the proof of the first part. Now we will show that $\| \cdot\|_{0}$ is a norm. Notice that $$ \|x\|_{0}=\left(\sum_{n=1}^{\infty} \frac{\left|f_{n}(x)\right|^{2}}{2^{n}}\right)^{1 / 2} \le \|x\|\left(\sum_{n=1}^{\infty} \frac{1}{2^{n}}\right)^{1 / 2} = \|x\|$$ If $x \ne 0$, then there is a $m \in \mathbb{N}$ such that $f_m(x) \ne 0$, which implies $\|x\|_{0} \ne 0$. If $x=0$, then  $f_{n}(x)=0$ for all $n$ as they are linear, therefore $\|x\|_{0}=0$. Clearly $\|\lambda x\|_{0} = \lambda \|x\|_{0}$ (follows from linearity of $f_n$'s). I believe that the triangle inequality will follow from Minkowski's inequality (we also take the limit on dimension). If $\| x\|_{0}=\|y\|_{0}=1$ then we need to show $\|x_0+y_0\| <2$. I am stuck with this for sometime and the consequence part. Any hints? Are there any mistakes in my approach ?

Edit 1: I was able to show that $\| \cdot\|_0$ is strictly convex thanks to @daw. Now I am only stuck in showing that there is an equivalent norm in which $X$ is strictly convex. Consider the norm $\|\cdot\|_1$ defined by $\|x\|_1= \|x\|_0+\|x\|$ where $\|\cdot\|$ is the original norm on $X$. Then $\|x\| \le \|x\|_1 \le 2\|x\|$. Therefore, it is equivalent with $\|\cdot\|$. How do I show from here that $\|x\|_1$ is strictly convex?

A: A norm $\|\cdot\|$ is strictly convex if for all $x,y \in X$, with $x \ne y$, we have $\| \lambda x +(1-\lambda)y\| $ $<$ $ \lambda\|x\|+(1-\lambda)\|y\|$ for all $\lambda \in (0,1)$. Now, to show $\|\cdot\|_1$ is strictly convex, observe that $\| \lambda x +(1-\lambda)y\|_1=\| \lambda x +(1-\lambda)y\| +\| \lambda x +(1-\lambda)y\|_0$ is strictly less than $\lambda \|x\|+(1-\lambda)\|y\|+\lambda \|x\|_0+(1-\lambda)\|y\|_0 = \lambda \|x\|_1 + (1-\lambda)\|y\|_1$.


text:
Q: In pygame, how do I make an image the background This is my code so far but I'm wondering if I can just set an image as a background. I've just started using pygame and I don't know much about it
import pygame

pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A bit Racey')

black = (0,0,0)
white = (255,255,255)

clock = pygame.time.Clock()
crashed = False
carImg = pygame.image.load('space.gif')
def car(x,y):
    gameDisplay.blit(carImg, (x,y))

x =  (display_width * 0.001)
y = (display_height * 0.01)

A: Load a back ground image (e.g. 'background.jpg'), scale it to the size of the screen with pygame.transform.smoothscale and blit it on the display surface:
background = pygame.image.load('background.jpg').convert()
background = pygame.transform.smoothscale(background, gameDisplay.get_size())

gameDisplay.blit(background, (0, 0))

Furthermore you have to implement and application loop and the scene has toi be redrawn in every frame. The typical PyGame application loop has to:

*

*handle the events by either pygame.event.pump() or pygame.event.get().

For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.

*update the game states and positions of objects dependent on the input events and time (respectively frames)

*clear the entire display or draw the background

*draw the entire scene (blit all the objects)

*update the display by either pygame.display.update() or pygame.display.flip()
import pygame
pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()

background = pygame.image.load('background.jpg').convert()
background = pygame.transform.smoothscale(background, gameDisplay.get_size())

black = (0,0,0)
white = (255,255,255)

crashed = False
carImg = pygame.image.load('space.gif')
def car(x,y):
    gameDisplay.blit(carImg, (x,y))

x = round(display_width * 0.001)
y = round(display_height * 0.01)

run = True
while run:
    clock.tick(60)

    # handle the events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # update the game states and positions of objects
    keys = pygame.key.get_pressed()
    x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 5
    y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * 5
    x = x % gameDisplay.get_width()
    y = y % gameDisplay.get_height()

    # draw the background
    gameDisplay.blit(background, (0, 0))

    # draw the entire scene
    car(x, y)

    # update the display
    pygame.display.flip()

A: A solution using Python Image Library aka PIL:
from PIL import Image
import pygame
#link to cat image:https://icatcare.org/app/uploads/2018/07/Thinking-of-getting-a-cat.png
w,h = 500,500
win = pygame.display.set_mode((w,h))

#open the image
img = Image.open("cute-cat.png")
#resize the image
img = img.resize((w,h))
#convert to a pygame surface
img = pygame.image.frombuffer(img.tobytes(),(w,h),"RGB")

#blit to screen
win.blit(img,(0,0))
#update the screen
pygame.display.flip()


text:
Q: DFS algorithm: 'list' object has no attribute 'depth' I use python to realize the DFS search algorithm but when I ran the code it said"  'list' object has no attribute 'depth' ".Actually, the object 'node' in my code is an instance of the class Nodes, which will have the attribute 'depth' as I definite before.
Here is my code:
import numpy as np
class Nodes():   # definite a nodes class. It contains state/parent/depth/action properties 'action' means it is generated by which action, which includes 'UP, DOWN, RIGHT, LEFT'

    def __init__(self, state, parent=None, depth=0, action=None):
        self.state = state
        self.parent = parent
        self.depth = depth
        self.action = action
    #  ....

    def DFS(self, goal, limit):
        opentable = []
        opentable.append(self)
        while True:
            if len(opentable) > 0:
                node = opentable.pop(0)
            if node.depth < limit:   # the problem is here
                if (node.state == goal).all():
                    moves = []
                    temp = node
                    i = 0
                    while True:
                        moves.insert(i, temp.action)
                        if temp.depth == 1:
                            break
                        temp = temp.parent
                        i += 1
                     return moves
                 opentable.append(node.generatenodes())
                 opentable.reverse()

if __name__ == '__main__':
     initial = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0],['A', 'B', 'C', 'G']])
     start = Nodes(initial)
     goal = np.array([[0, 0, 0, 0], [0, 'A', 0, 0], [0, 'B', 0, 0],[0, 'C', 0, 'G']])
     start.DFS(goal, 8)


text:
Q: Categories not working with qtranslate + ajax call on wordpress I'm using qTranslate on a custom wordpress theme, I have a jQuery ajax call that load the correct 'admin-ajax.php/?lang=' value and call the construction on functions.php
When you call the Ajax (check it at new.whatonline.org, the 'Load more' button before the footer, if you are in the english version you will have the new thumbs translated, but not the categories).
I tried different solutions (_e(), select the language before, etc) but I didn't arrive to fix it, the code I call for functions is
foreach((get_the_category()) as $category) {
    if (!($category->cat_ID==894) && !($category->cat_ID==895) && !($category->cat_ID==902) && !($category->cat_ID==903) && !($category->category_parent==902)){
        echo 'term_id );
        echo '" >';
        echo $category->cat_name;
        echo ', ';
    }
}

It works when the page loads but not with the AJAX call. I also printed the $category value and I saw all the array but there isn't the translated value, on other contents like 'the_content' I can see the <--:en--><--:es--> if I output the original value but not for categories (I didn't found the structure on the mySQL database) so I guess the problems comes from a first plugin function, no?
PS. The last category is translated because it isn't a real category and I use _e(XXXX, 'qtranslate') hack
Thanks.

UPDATE
Here is the ajax call from jQuery...
jQuery.ajax({
    type: 'POST',
    cache: false,
    url: idioma,
    data: {"action": "listposts", cat : categories, neworder : order, offset : postoffset}
})
.success(function(data) {
    //Añadimos los nuevos posts a la cola y borramos los anteriores
    $(".results").append(data).show();
    datosact.remove();
    postoffset = postoffset + 20;
    //Vovlemos a poner los textos bien y devolvemos el fondo de carga a su estado inicial
    $('#loadmore').children('a').text( morearticles );
    $('#loading').removeClass('active');
    return false;
});

and the php function for the construction
function listposts() {
global $post;

$output = '';
$cat_id = $_POST[ 'cat' ];
$orderby  = $_POST[ 'neworder' ];
$offset  = $_POST[ 'offset' ];

$metakey ='';

if ($orderby == "by_views"){
    $orderby = "meta_value_num";
    $metakey = 'views';
}
    $args = array (
    'category__and'      => $cat_id,
    'meta_key'           => $metakey,
    'post__not_in'       => get_option( 'sticky_posts' ),
    'orderby'            => $orderby,
    'post_status'        => 'publish',
    'posts_per_page'     => 20+$offset
);

$listposts = new WP_Query($args);
while($listposts->have_posts()) : $listposts->the_post();

    $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'listado' );
    $str = get_post_meta($post->ID, 'subcat', true);

    $vistas = get_post_meta( get_the_ID(), 'views', true );

    echo "

";
    echo $vistas;
    echo "

";
    echo render_socialcounter();
    echo "

";
    the_title();
    echo "

";

//This function do the loop that I posted before
what_categories();

    echo "";
    echo _e($str, 'qtranslate');

    echo "

";

    echo $content = "
".new_excerpt(180)."...
";
    echo "

";

endwhile;

die($output);
}

add_action('wp_ajax_listposts', 'listposts');
add_action('wp_ajax_nopriv_listposts', 'listposts'); // not really needed

A: As per your code, There are two things missing in your code

*

*AJAX url

*Action

These are required values to send via ajax to use Wordpress AJAX.
jQuery.ajax({
    type: 'POST',
    cache: false,
    action: 'listposts',
    url: <?php echo admin_url( 'admin-ajax.php' ) ?>,
    data: {"action": "listposts", cat : categories, neworder : order, offset : postoffset}
})
.success(function(data) {
    //Añadimos los nuevos posts a la cola y borramos los anteriores
    $(".results").append(data).show();
    datosact.remove();
    postoffset = postoffset + 20;

    //Vovlemos a poner los textos bien y devolvemos el fondo de carga a su estado inicial
    $('#loadmore').children('a').text( morearticles );
    $('#loading').removeClass('active');

    return false;
});

You can't call ajax without action parameter because then there will be no way to identify ajax request uniquely.
Reference
http://codex.wordpress.org/AJAX_in_Plugins
Using AJAX in a WordPress plugin


text:
Q: how to position a div with respect to bottom of browser window I have some blocks of div with different heights and want to position a div say "scroll" that should be 100px above the bottom of the window irrespective of the window size in each block of div. how to do it in jquery?

A: You can use css
#scroll {
         position:fixed;
         bottom:100px;
        }


text:
Q: Induction. Circular track and fuel stations The sides of a circular track contain a sequence of cans of gasoline. The total amount in the cans is sufficient to enable a certain car to make one complete circuit of the track, and it could all fit into the car's gas tank at one time. Use mathematical induction to prove that it is possible to find an initial location for placing the car so that it will be able to traverse the entire track by using the various amounts of gasoline in the cans that it encounters along the way.
This question has been asked here before but I don't really understand the answers. I'd like to solve this by induction.

A: We proceed by induction on $n$, which is the number of cans.
In the case that $n=1$, it is clear that the result holds since the $1$ can that exists contains sufficient fuel for the car to travel around the track, and so we can place the car at this $1$ can of fuel, let it fill up with the fuel that is in the can, and then travel around the track.
Now suppose that the result holds for every possible placement of $n$ cans and any possible division of the total fuel into those cans.
Consider an arrangement of $n+1$ cans. Since the total amount of the fuel in the cans is sufficient to travel around the track, at least one of the cans contains enough fuel for the car to travel to the next can. (As otherwise the total amount of fuel would only be enough to cover a distance strictly smaller than the total distance between the cans, which is of course the distance around the track.)
Consider this can that contains enough fuel to get to the next can. Call it $C$. Let the can which appears after $C$ be called $D$, and imagine adding the fuel contained in $D$ to the fuel contained in $C$. This gives us an (imaginary) arrangement of $n$ cans which together contain enough fuel to travel around the track, and so by the induction hypothesis, there is a point on the track where we can place the car so that it can travel around the track.
Place the real (non-imaginary) car at the same point on the track and let it start circling the track. It is then able to travel to $C$ since the real cans before $C$ are identical to the imaginary cans before $C$. There is enough fuel in the real can $C$ for it to reach the real can $D$, and so it can reach $D$. Once it reaches $D$, it tops up with the fuel contained in $D$, and then it has exactly the same amount of fuel as the imaginary car contains at this point on the track. Its journey from here on is therefor identical to the imaginary car's, and so it follows that it will be able to complete its journey around the track.
There is thus a location on the track where we can place the car such that it completes its journey around the track, and so the result follows by induction.

A: suppose there was one can, then it can be placed at the start. now suppose there are n cans positioned, this can get you $n/l$ of the track of length $l$. if you have $n+1$ cans then you have enough $n$ cans and can get $n/l$ at least with some combo if $n$ cans by first assumption. now you either have enough gas to make it around the track or the next gas can is placed within reach $n-$amount of gas of small can in distance$/l$ and you can get around the track.


text:
Q: lamejs not working with angular 8 -- Uncaught ReferenceError: Lame is not defined I added "lamejs": "^1.2.0", in package.json , and then in app.component.ts i added these lines :
var lamejs = require("lamejs");
    let channels = 1; //1 for mono or 2 for stereo
    let sampleRate = 44100; //44.1khz (normal mp3 samplerate)
    let kbps = 128; //encode 128kbps mp3
    let mp3encoder = new lamejs.Mp3Encoder(channels, sampleRate, kbps);
    var mp3Data = [];

    let samples = new Int16Array(44100); //one second of silence (get your data from the source you have)
    let sampleBlockSize = 1152; //can be anything but make it a multiple of 576 to make encoders life easier

    var mp3Data = [];
    let sampleChunk;
    for (var i = 0; i < samples.length; i += sampleBlockSize) {
        sampleChunk = samples.subarray(i, i + sampleBlockSize);
        var mp3buf = mp3encoder.encodeBuffer(sampleChunk);
        if (mp3buf.length > 0) {
            mp3Data.push(mp3buf);
        }
    }
    var mp3buf = mp3encoder.flush();   //finish writing mp3

    if (mp3buf.length > 0) {
        mp3Data.push(new `Int8Array(mp3buf));`
    }

    var blob = new Blob(mp3Data, { type: 'audio/mp3' });
    var url = window.URL.createObjectURL(blob);
    console.log('MP3 URl: ', url);

i am getting this error in console ,
index.js:17 Uncaught ReferenceError: Lame is not defined
at Object../node_modules/lamejs/src/js/index.js
when i open this index.js at that line , i see Lame = require('./Lame.js');
Lame variable is being used without declaration , how do i proceed , i kept fixing these kind of errors of declaration issue but the list just goes on and on .

A: Download lame.all.js and lame.min.js files from https://github.com/zhuker/lamejs and place them into your assets folder.
src/assets/lamejs/lame.all.js
src/assets/lamejs/lame.min.js

Add a script tag to your index.html file
<script src='assets/lamejs/lame.all.js'></script>

Decalare a variable of lamejs after all imports in component.ts or service.ts then you can use it.
declare var lamejs;


text:
Q: Javascript/JQuery annoymous function variable issue I'm having a small problem to do with capturing variable values in anonymous functions.
Here's my code.

function register(email, username, password) {

    var postFields = {
        email: email,
        username: username,
        password: password
    };

    var response = null;

    $.post("../ajax/register/", postFields, function(result) {
        response = result;

        //I can print the contents of the variable response here
        console.log("First " + response);
    });

    //But it prints null when I try to print it here
    console.log("Second " + response);

    return JSON.parse(response);
}

The post request returns a perfectly fine JSON response so I'm wondering what the issue could be.
Any help on this would be appreciated.


text:
Q: Reducing Flash FPS from 24 to 12 Without Pacing Lose I haven't used Flash is years. Is there anyway to change a 24fps animation to a 12fps while still retaining the speed? This broadcaster has a crazy spec of 40kb claiming their system can't handle anything more (which seems like crap) but I have to comply.
So far I've removed every single graphic element and also converted all of my motion tweens to classic frame by frame. There's seems to not be too much more I can do.

A: If host supports version 11.1+, then is possible to compress vectors using LZMA (much smaller swf size).
At publish settings choose JPEG quality to be 70 - 99% (70% usually seems fine) and you can specify each library item (if its picture) render specifics under it's properties. Compression there must not be losless. Deblocking smoothes out if compression quality is low.
In publish settings check "generate size report" to follow it frame by frame, and see where is impact.
As well if you use script working with fonts - embed only characters used, not whole font. (characters used will show up in size report too)
I believe better to use motion tween instead of frame by frame animation (for swf size performance - see the generated size report) Otherwise you do not use swf purpose in creating animations - you just get gif principle there, when each frame contains new image.
Try using vectors were possible, png format.. (sometimes picture is wining over vector if vector shape is complex)
Vectors simplify via Illustrator and images export to web via Photoshop.
40 kbs per distributable 280x280 swf file is achievable!
If you step from 24 fps to 12 you only win on computing resources per frame, not size of swf.
there is all to it, at the top of my head. Anything more to add? swf size is important topic.


text:
Q: How to display another form with datagridview just below a textbox to filter grid data I have created a usercontrol. It has two textbox one for description and another for id.
Next I have created a form with datagridview. Datasource for this datagridview is sent from predefined usercontrol. It will have only two colums ID and Description.
Now I want when text on usercontrol textbox for description is changed, form with datagridview displays just below textbox and displays matching data as reference. Form should keep on displaying till user press enter or leaves the textbox. While displaying form user should be able to type text on usercontrol textbox for filter.
And when user leaves the textbox or presses enter, value from selected row of datagridview id column and descriptions column should be passed to usercontrol.
I did everything well but when form with datagridview appears, displayed form becomes active and I can not continue writing in searching textbox of usercontrol.

A: You could try showing the form inactive with the following extension method:
public static class FormExtensions
{
    #region Show inactive top-most

    const int  SW_SHOWNOACTIVATE =  4,
                HWND_TOPMOST      = -1;
    const uint SWP_NOACTIVATE    = 0x0010;

    [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
    static extern bool SetWindowPos(int  hWnd,            // window handle
                                    int  hWndInsertAfter, // placement-order handle
                                    int  X,               // horizontal position
                                    int  Y,               // vertical position
                                    int  cx,              // width
                                    int  cy,              // height
                                    uint uFlags);         // window positioning flags

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    public static void ShowInactiveTopMost(this Form form)
    {
        ShowWindow(form.Handle, SW_SHOWNOACTIVATE);

        SetWindowPos(form.Handle.ToInt32(),
                        HWND_TOPMOST,
                        form.Left,
                        form.Top,
                        form.Width,
                        form.Height,
                        SWP_NOACTIVATE);
    }

    #endregion
}


text:
Q: What is does the regular expression /^\s*$/ do? What does this expression in Perl programming do?
$variable =~ /^\s*$/;

A: That's looking for a line start (^), followed by zero or more whitespace (\s*) characters, followed by a line end ($).
It's essentially looking for blank/empty lines.
I'd expect the expression to be used in something like:
if ($v =~ /^\s*$/) {
   # found a blank line
}

in order to perform the check and a following action.

A: Nothing, since you are not assigning the result of this operation to any variable, and since it has no side effects that you are likely to test for.
However, if you said
if ($variable =~ /^\s*$/)
{
  print "something";
}

You would be answering the question:
Does the value in variable consist of an empty line or a line consisting of nothing but non printing whitespace characters such as spaces and tabs?

A: =~ is a match operator.
The statement returns true if $variable only consists of spaces, or is simply empty.
So it just checks if the string is empty or not.

A:  if ( $variable =~ /^\s*$/ )

is the same as
 unless ( $variable =~ /\S/ )

or
 if ( $variable !~ /\S/ )


text:
Q: In Flutter 3.x, ReorderableListView is not working I'm trying to implement ReorderableListView in my Flutter app. The code is simple:
import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(home: MyHomePage()));

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void _onReorder(int oldIndex, int newIndex) => setState(
        () => items.insert(
          newIndex > oldIndex ? newIndex -= 1 : newIndex,
          items.removeAt(oldIndex),
        ),
      );

  var items = ['Item A', 'Item B', 'Item C'];

  @override
  Widget build(context) => Scaffold(
        body: ReorderableListView(
          onReorder: _onReorder,
          children: items.map((item) {
            var index = items.indexOf(item);
            return ListTile(
              key: Key('$index'),
              tileColor: Colors.white,
              title: Text(item),
              onTap: () {
                // Handle tap
              },
            );
          }).toList(),
        ),
      );
}

I can't make the code work. The items can't be reordered. flutter --version command tells me:
Flutter 3.3.8 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 52b3dc25f6 (3 days ago) • 2022-11-09 12:09:26 +0800
Engine • revision 857bd6b74c
Tools • Dart 2.18.4 • DevTools 2.15.0

And flutter doctor tells me:
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.3.8, on macOS 13.0.1 22A400 darwin-x64, locale en-ID)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.3)
[✓] IntelliJ IDEA Ultimate Edition (version 2022.2.1)
[✓] VS Code (version 1.73.1)
[✓] Connected device (4 available)
[✓] HTTP Host Availability

• No issues found!

What is wrong with my code?

A: After many hours of trial and error with many samples and tutorials all over the internet, I have found the cause: In Flutter 3.x, ReorderableListView will only work if we use ReorderableDragStartListener. This is the 1 link that led me to the right direction: https://github.com/flutter/flutter/issues/114783. How to use the listener? I have to modify my code, and update the ListTile part as follows:
ListTile(
  key: Key('$index'),
  tileColor: Colors.white,
  title: Text(item),
  onTap: () {
    // Handle tap
  },
  trailing: ReorderableDragStartListener(
    index: index,
    child: const Icon(Icons.drag_handle),
  ),
)

I hope this answer will help people, and no one gets through all the frustrating hours like I did.


text:
Q: Fetching relation to PFObject cloud code I have a PFUser that has a days relation to a Day PFObject.
In my database it looks like this:
{
    "_id": "WjLAnMuRmp",
    "name": "c",
    "_created_at": {
        "$date": "2016-08-04T15:28:51.759Z"
    },
    "_updated_at": {
        "$date": "2016-08-24T19:44:44.774Z"
    },
    "days": [
        {
            "__type": "Pointer",
            "className": "Day",
            "objectId": "BrQwmKAbJC"
        },
        {
            "__type": "Pointer",
            "className": "Day",
            "objectId": "6wuDMl4kKI"
        }
    ]
}

Pretty straight forward. In my cloud code, I'm trying to send up a PFUser objectId, then fetch all the days they have and iterate over them. For some strange reason I keep getting 0 returned when I do a relation query.
Here is what I'm working with:
Parse.Cloud.define("getDayAveragesForUser", function(request, response) {

  console.log("-getDayAveragesForUser");

  // Create the query on the User class
  var fetchedUser = new Parse.User({id:request.params.userObjectId});

  console.log("the fetched user: " + fetchedUser.id);

  var relation = fetchedUser.relation("days");

  var query = relation.query();
  query.limit(365);
  query.ascending("createdAt");
  query.find({
    success: function(results) {
      console.log("Successfully retrieved " + results.length + " Days.");
    },
    error: function(error) {
      console.log("Error: " + error.code + " " + error.message);
    }
  });
});

When I print the fetchedUser.id it's correct so I know I'm on the right user. This seems based on the documentation example:
var relation = user.relation("likes");
relation.query().find({
  success: function(list) {
    // list contains the posts that the current user likes.
  }
});

This should be working fine.
===
I just add this to my Cloud Code to test:
  var days = fetchedUser.get("days");

  console.log("type of: " + typeof days);

which from this I get:
type of: undefined

A: The reason is that your days are not saved as relations but as a pointers. And in parse relations and pointers are handled in different ways.
In order to fetch the days pointer you need to change your query to look like the following:

var userQuery = new Parse.Query(Parse.User);
userQuery.include("days"); // include the days pointer in the results
userQuery.get(request.params.userObjectId, {
  success: function(user) {
    // This function will *not* be called.
    console.log(user.get("days")); // print the days to console
  },
  error: function(error) {

  }
});


text:
Q: Rails: Routing error I have a button_to tag in my show.html.erb file.
  <%= link_to 'Click HERE to open file', @user.image.url  %>

<%= label_tag(:q, "Parse CSV File:") %>

<%= button_to 'Parse CSV', {:controller => "users_controller", :action => "process" } %>
  <% end %>

Then I have this added to my users_controller.rb file
# GET /users/1/process
def process
 puts 'To be Implemented'
end

Im getting an error in the routing file
No route matches [POST] "/assets"

This is how my routing file looks:
resources :users

resources :listings

What should I change. Im a bit confused, woould really appreciate some help.

A: 1) In view, use the controller name like 'users', not the 'users_controller' .
<%= button_to 'Parse CSV', {:controller => "users", :action => "process" } %>

2) rails define few routes by default , but for other you need to define yourself .
Declare the routes like :
  resources :users do
    :member => {
     :process => :get
    }
  end

Hope that help .

A: Please correct your route and define like this
<%= button_to 'Parse CSV', {:controller => "users", :action => "process" } %>

Then in route file
    resources :users do
      collection do
         get: process
     end
    end

It will sure work


text: Q: Is there any search algorithm that finds out a specific key(hint) and data related to it in a file efficiently? I have to write a logger class in PHP. I will save all my logs in file because I don't want to overload the database server. The only problem is that, I don't know how to efficiently search for logs saved in a file on a specific date (or between two dates). Is there an algorithm to pull out data efficiently by taking a hint (i.e. date) as input? There may be a million of logs in a file. In that case, it is very important to efficiently search for logs inserted on a given date (or between two dates).


text:
Q: Hide element on one page only
body.943 .ish-button-small {display:none;}

I want to hide the class ".ish-button-small" on the page with the id 943.
Keep in mind only on that page. What is the best way to do this?

A: try this:
body#943 .ish-button-small {display:none;}

A: #943 .ish-button-small {display:none;}

A: Can't just use CSS for that, this should work with Javascript
$(document).ready(function () {
  if (window.location.href.indexOf("943") != -1) {
    $("#.ish-button-small").hide();
  }
});

Checks if the URL contains 943 and if it does it hides the element with the class .ish-button-small


text: Q: ñ with UTF-8 and ASCII in PHP I have two variables $var1=Ñ and $var2=Ñ. The $var1 according the function mb_detect_encoding is ASCII and the $var2 is utf-8. In the browser when I make echo of these variables I see Ñ and Ñ, i.e I see the two equals. But, when I compare these using if ($var1 == $var2) echo "OK"; else echo "KO". I get KO. I need a way to interpret that is the same symbol, Could you help me please?


text:
Q: Jenkins - Email attachment with dynamic pdf files Using Editable Email Notification in Jenkins how do we get dynamic (report file name changing in workspace after every build) .pdf files attached in e-mail from workspace.
Example: Root/TestResults/*.pdf
Above will give all pdf attachments
Example: Root/TestResults/Final_Report_2015_11_07_06_47.pdf
Above path is giving same file when exist.
But file name is getting changed dynamically, i.e. Final_Report_XXXX_XX_XX_XX_XX.pdf.
Is there any way to get latest file based one dynamic report file name check.


text:
Q: PHP - split JSON file (array) into multiple files I have a big json file containing an array of objects. The file is too big (15MB) to be parsed by json_decode. How could I split this array-file into multiple array-files?
The array contains objects, which may also contain objects within it.

A: you can try array chunking -
$halved_array = array_chunk($original_array, ceil(count($original_array)/2));

A: You can't chuck the file without having the whole string in memory at any time. You may need to work on the source of the problem (if you can) instead of trying to deal with it.
However you can setup a cron than will have for only job to chuck this JSON file into multiple JSON files.


text:
Q: How to enter data for 3 index parameter in CPLEX OPL? I have a variable X[i][j][k] in my problem. How do I enter data for this in .dat file in CPLEX ?
Lets suppose i=2, j=2, k=3
Supplier 1(i)  Component 1(j)  20 30 40
               Component 2     50 20 10
Supplier 2     Component 1(j)  20 80 40
               Component 2     10 20 10

A: You can have a look at the example:
CPLEX_Studio127\opl\examples\opl\models\YieldStochastic

where you will see in the .mod:
{string} classes = {"First", "Business", "Economy"};
int capacity[classes] = [37, 38, 47];

// Planned periods
range periods = 1..3;

// 3 scenarios are studied with their corresponding probability
range scenarios = 1..3;
float probaScenarios[scenarios] = [0.1, 0.7, 0.2];

// 3 pricing options for each class and period
range options = 1..3;
int priceOptions[periods][classes][options] = ...;

and then in the .dat:
priceOptions =
  [[[1200,1000,950],
    [900,800,600],
    [500,300,200]],
   [[1400,1300,1150],
    [1100,900,750],
    [700,400,350]],
   [[1500,900,850],
    [820,800,500],
    [480,470,450]]];


text:
Q: Using ajax and json to ge the driving distance between two addresses Is it possible to use the jQuery ajax function and the Google directions API to asynchronous calculate the distance in miles between two given addresses? I've found a few examples that show how to do this using PHP, but nothing that doesn't require a page reload

A: Yes just implement your calculation in php, and call your script asynchronously using ajax:
$.ajax({
    url: "calcdist.php?address1="+addr1+"&address2="+addr2,
    success: function(result){
        alert("Distance is "+result+" miles);
    }
});

and in your script (calcdist.php):
<?php
$a1 = $_GET['address1'];
$a2 = $_GET['address2'];

$ll1 = getLatLong($a1);
$ll2 = getLatLong($a2);

$dist = haversine($ll1, $ll2);

echo $dist;
?>

You just need to implement the haversine and getLatLong functions in your php
see Haversine formula with php + http://code.google.com/p/gogeocode/ for help with these


text:
Q: React AppendChild Component doesn't work I've been looking everywhere and cannot find a solution to this.
I'm simply trying to do the following:
import ComponentOne from '../components/component-one'
import ComponentTwo from '../components/component-two'

class Home extends Component {
    constructor( props ) {
        // So I can dynamically call a Component, found no other way
        this.components = {
            ComponentOne: <ComponentOne />,
            ComponentTwo: <ComponentTwo />
        }
    }

    [...code removed for brevity...]

    _appendStep( step ) {
        var component = React.cloneElement(this.components[step])
        this.steps.appendChild( component )
    }
}

This seems pretty simple to me. I have

 this.steps = ref}>

that I need to dynamically appendChild components too. The thing is, the "steps" I append to this
 absolutely need to be one of the components I've created, needs to allow me to add multiple component children, and even duplicate (that's why I'm using React.cloneElement()) Components.
Once I have all the "steps" appended, a later process will then parse each and every step to determine how to run a recipe.
The following works just fine, but I'm not needing to create a simple DOM node, I need to use a Component I already have built and append that
var basicElement = document.createElement('h1')
basicElement.innerHTML = "This works, but I need a component to work too"
this.steps.appendChild( basicElement )

I get the following error when I try to this.steps.appendChild( component ):
Error:
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

I guess my main question is this: how can I convert my React Component into a node that can be used with this.steps.appendChild()?
OR: is there a "React way" to dynamically append children components to my this.steps?

A: this.steps should be an array, then, you will be able to render that array using the map function.
Also you should store your array in your state in order to auto re-render the component after you add new steps.
It should look like this
 constructor( props ) {
    this.state = {
       steps: []
     }
    this.components = {
        ComponentOne: <ComponentOne />,
        ComponentTwo: <ComponentTwo />
    }
}
_appendStep( step ) {
        let componentToAdd= this.components[step];
        this.setState({steps: this.state.steps.concat([componentToAdd])})
    }

render(){
     ....
    {this.state.steps.map(function(comp,i){
        return
{comp}

    })}

}


text:
Q: Equation with sine and cosine - coefficients I have some trouble with the conceptual understanding of the way we solve this kind of equations. Let's say we have:
$$(3-3b^2)\sin(bx)+3a\cos(2x)=6\cos(2x)$$
The method employed on classes was equating coefficients on both sides of the equation. For example there's no sine function on the right hand side, so $(3-3b^2)=0$. Therefore we're left with $3a\cos(2x)=6\cos(2x)$ so obviously $3a=6$. From that it follows that $a=2, b=1$ or $-1$. This is logical to me but I still can't understand why the sine and the cosine on LHS can't "coexist" (not sure how to phrase that) and give together the result on RHS. Example of what I think if that's not clear:
$$\underbrace{(3-3b^2)\sin(bx)}_n+\underbrace{3a\cos(2x)}_m=\underbrace{6\cos(2x)}_{n+m}$$

A: You're being quite vague in a way that large numbers of students are.  They see something like
$$
(3-3b^2)\sin(bx)+3a\cos(2x)=6\cos(2x) \tag 1
$$
and think that this specifies an problem to be solved.  But the words you wrote after that make it clear that whoever posed this said more than what you've told us.
A set of exercises in a textbook may say "Solve the following equations for $x$."  It it had said that, that would be a very different problem from what you write about in your paragraph beginning with "The method employed".  There is no reason why the coefficient of the sine term should not be $0$ if it says "Solve this equation for $x$."
But if it said that $(1)$ is an identity true of all values of $x$, and asks you to find the coefficients, then, because of the word all, we can conclude that the coefficient of the sine term is $0$.
If $x=0$ then the sine term vanishes and the cosine terms are equal to $1$, and we get $3a=6$ so $a=2$.  Then if $x$ has some value that makes the sine nonzero, we get
$$
(3-3b^2)\cdot(\text{some number other than 0}) + 6\cos(2x) = 6\cos(2x).
$$
Subtracting $6\cos(2x)$ from both sides, we get
$$
(3-3b^2)\cdot(\text{some number other than 0}) = 0,
$$
and from that we can conclude that the coefficient is $0$.

A: You probably want to find $a$ and $b$ such that, for all $x$,
$$
(3-3b^2)\sin(bx)+3a\cos(2x)=6\cos(2x)
$$
If this is the problem, then you can plug in whatever value of $x$; for instance, when $x=0$, we get
$$
(3-3b^2)\sin(b\cdot0)+3a\cos(2\cdot0)=6\cos(2\cdot0)
$$
that becomes
$$
3a=6
$$
so $a=2$. With this information we remain with
$$
(3-3b^2)\sin(bx)=0
$$
for all $x$. If $b=0$, the equality surely holds. If $b^2\ne1$ and $b\ne0$, there surely are values of $x$ such that $\sin(bx)\ne0$, for instance $x=\frac{\pi}{2b}$. So we have the equality holding for all $x$ if and only if $b^2=1$ or $b=0$.


text:
Q: Feedforward Vs. Backpropagation Neural Network I was taking the "Machine Learning-Coursera (Standford) by Andrew Ng" course.
In Week 4 and Week 5 we have given programming assignments, Where we have to do digit classification.
In Week 4 programming assignment we have used Feed forward Neural Network for classifying digits and we get an accuracy of around 97.5%. Then in Week 5 programming assignment we have used Neural Network with Backpropagation which gives us the accuracy of around 95%.
For this particular application (Character Classification) will Feedforward Neural Network always dominate Neural Network with Backpropagation?

A: When you used a Feedforward Neural Network during week 4, that network has been already trained using backpropagation by Andrew, and provided to you to use for the classification task.
In week 5, you went further and trained a network yourself using backpropagation. As you can see, there's no such thing as a feedforward only or a backprop only neural network. All neural networks are trained using backpropagation.
For various reasons, you got a different accuracy score than Andrew's network. It's hard to say why, but I bet Andrew used his experience and knowledge to push the training further.
Again, there was no difference in the nature of the networks.


text:
Q: htaccess on heroku for django app The title pretty much sums up my question.  I would like to to password protect some files in my django app that lives on heroku.
If I can't use htaccess does anyone have suggestions on what else I could use?
Thanks.

A: I was able to use .htaccess files on heroku with the cedar stack.

*

*Procfile needs to specify a script for the web nodes:
web:    sh www/conf/web-boot.sh

*The conf/web-boot.sh slipstreams the include of a apache configuration file, e.g.:

*A conf/httpd/default.conf then can allow override, as you know it from apache.

You can then just use .htaccess files. The whole process is documented in detail in my blog post PHP on Heroku again of which one part is about the apache configuration. The step in 2. including your own httpd configuration basically is:
sed -i 's/Listen 80/Listen '$PORT'/' /app/apache/conf/httpd.conf
sed -i 's/^DocumentRoot/# DocumentRoot/' /app/apache/conf/httpd.conf
sed -i 's/^ServerLimit 1/ServerLimit 8/' /app/apache/conf/httpd.conf
sed -i 's/^MaxClients 1/MaxClients 8/' /app/apache/conf/httpd.conf

for var in `env|cut -f1 -d=`; do
  echo "PassEnv $var" >> /app/apache/conf/httpd.conf;
done
echo "Include /app/www/conf/httpd/*.conf" >> /app/apache/conf/httpd.conf
touch /app/apache/logs/error_log
touch /app/apache/logs/access_log
tail -F /app/apache/logs/error_log &
tail -F /app/apache/logs/access_log &
export LD_LIBRARY_PATH=/app/php/ext
export PHP_INI_SCAN_DIR=/app/www
echo "Launching apache"
exec /app/apache/bin/httpd -DNO_DETACH

I hope this is helpful. I used this for .htaccess and for changing the webroot.

A: As @mipadi said, you can't use htaccess on Heroku, but you can create a middleware for that:
from django.conf import settings
from django.http import HttpResponse
from django.utils.translation import ugettext as _

def basic_challenge(realm=None):
    if realm is None:
        realm = getattr(settings, 'WWW_AUTHENTICATION_REALM', _('Restricted Access'))
    # TODO: Make a nice template for a 401 message?
    response =  HttpResponse(_('Authorization Required'), mimetype="text/plain")
    response['WWW-Authenticate'] = 'Basic realm="%s"' % (realm)
    response.status_code = 401
    return response

def basic_authenticate(authentication):
    # Taken from paste.auth
    (authmeth, auth) = authentication.split(' ',1)
    if 'basic' != authmeth.lower():
        return None
    auth = auth.strip().decode('base64')
    username, password = auth.split(':',1)
    AUTHENTICATION_USERNAME = getattr(settings, 'BASIC_WWW_AUTHENTICATION_USERNAME')
    AUTHENTICATION_PASSWORD = getattr(settings, 'BASIC_WWW_AUTHENTICATION_PASSWORD')
    return username == AUTHENTICATION_USERNAME and password == AUTHENTICATION_PASSWORD

class BasicAuthenticationMiddleware(object):
    def process_request(self, request):
        if not getattr(settings, 'BASIC_WWW_AUTHENTICATION', False):
            return
        if 'HTTP_AUTHORIZATION' not in request.META:
            return basic_challenge()
        authenticated = basic_authenticate(request.META['HTTP_AUTHORIZATION'])
        if authenticated:
            return
        return basic_challenge()

Then you need to define in settings.py:
BASIC_WWW_AUTHENTICATION_USERNAME = "your user"
BASIC_WWW_AUTHENTICATION_PASSWORD = "your pass"
BASIC_WWW_AUTHENTICATION = True

A: You can't use .htaccess, because Heroku apps aren't served with Apache. You can use Django authentication, though.
Or you can serve the files from another server that is using Apache.


text:
Q: setInterval By the minute On the minute To the javascript enthusiasts,
how would you program a setTimeOut (or setInterval) handle to fire by the minute on the minute. So for example, if it is the 51 second of the current time, then fire it in 9 seconds, if it is the 14th second then fire it in 46 seconds
thanks

A: var nextTick = function() {
  return 60000 - (new Date().getTime() % 60000);
}, timerFunction = function() {
  // do stuff
  // do stuff
  // do stuff
  setTimeout(timerFunction, nextTick());
};
var timeout = setTimeout(timerFunction, nextTick());

A: At first, I used the solution proposed by Joel Potter. His solution is good enough in most cases. However, because the javascript is doing one thing at a time (unless you are using Workers), it may be late with first timeout, so your first timeout is executed eg. 5 seconds too late and you get interval on every 5 seconds after the minute.
So, here is my implementation:
function setMyFunctionInterval()
{
    var currentDateSeconds = new Date().getSeconds();
    if (currentDateSeconds == 0) {
        setInterval(myFunction, 60000);
    }
    else {
        setTimeout(function () {
            setMyFunctionInterval();
        }, (60 - currentDateSeconds) * 1000);
    }

    myFunction();
}

setMyFunctionInterval();

A: var date = new Date();

setTimeout(function() {
    setInterval(myFunction, 60000);
    myFunction();
}, (60 - date.getSeconds()) * 1000);

Obviously this isn't 100% precise, but for the majority of cases it should be sufficient.

A: First, let's make sure we know how much time do we have until the next minute:
var toExactMinute = 60000 - (new Date().getTime() % 60000);

Now, if you want to work with setTimeout, then
setTimeout(yourfunction, toExactMinute);

If you want to do a setInterval:
setTimeout(function() {
    setInterval(yourFunction, 60000);
    yourFunction();
}, toExactMinute);

A: var seconds = (new Date()).getSeconds();

Use 60-seconds as the timeout time. Granted, setTimeout lets you specify milliseconds, which means you should also be checking milliseconds, but this will give you "close enough" for most applications. If anything, this should make you overshoot the minute some fraction of a second, but it's better to overshoot than undershoot. Undershooting would cause catastrophic failure with this method.

A: var d = new Date();
var milisecondsUntilMinuteChanges = 60000 - d.getMilliseconds() - (1000 * d.getSeconds());

A: Although too late for the response, I have had similar problem to solve recently and thought of sharing my approach. My problem was to run a timeout after a specified seconds based on how far it is away from a minute, and subsequently run interval function each minute. Here is what I did.
Let's say the date is javascript date object created using date = new Date();

*

*Get the seconds left to reach a minute secondsLeft = 60 - date.getSeconds();

*Then set a timeout function to run after secondsLeft, and inside the function set an interval function to run each minute as:
setTimeout(function() {
  // perform the action **A**;
  minuteMS = 60 * 1000; // seconds * milliSeconds
  setIntervalId = setInterval(function() {
  // perform the action **A**;
 }, minuteMS);
}, secondsLeft);

*Using above format/algorithm you should be able to achieve similar problems be the seconds supplied in any format. The idea is to get the difference of seconds and 60, run a timeout after those seconds, and inside timeout function run interval function with interval as a minute/or anything as such based on requirement.

A: function waitForNewMinute() {
    if (new Date().getSeconds()>1) {
        setTimeout(waitForNewMinute, 500);
    } else {
        setInterval(doMyThing,60000);
    }
}

waitForNewMinute();

A: I used the ' (60 - date.getSeconds()) * 1000);' method on a data refresh function and, while it worked, it 'drifted' over time (14 seconds late before I changed it!)
As the data needed to be updated ON the minute (and that was obviously not happening as we have a clock on the same page!), here's the solution I came up with:
setInterval(function () {
    if(moment().format('ss') === "00"){
        console.log('we are at the 0 - update the data!');
        refresh_data();
    }
}, 1000);

This of course uses moment.js to find the '0' time and it certainly does what the OP asked - fires on the minute - every time!

A: I believe all the answers are flawed. Once you have started the setInterval, the interval time cannot be changed without creating a new setInterval object. So you will only use the initial calculated time for each iteration.
You can create new setInterval objects, but that has to be costly.
See: How do I reset the setInterval timer?
My recommendation is to create a looping function that utilizes the setTimeout instead.
Here's some code:
var duration = 5; //in minutes. This is just to control the total length
var startTime = new Date().getTime(); //must be in milliseconds

function myOnTheMinuteTimer(){
    setTimeout(function(){
        var currentTimeMS = new Date().getTime();
        var diffMs = Math.abs(startTime - currentTimeMS);
        diffMs = diffMs/1000; //take out the milliseconds
        var seconds = Math.floor(diffMs % 60);
        diffMs = diffMs/60;
        var minutes = Math.floor(diffMs % 60);
        var minutesLeft = duration - minutes;
        console.log("Time passed:", minutes + "m :" + seconds + "s");

        if(minutes <= duration){
            console.log("Timer expired.");
        } else {
            myOnTheMinuteTimer();
        }
    }, setIntervalTimeToNextMinute());
}

//Initialize timer
myOnTheMinuteTimer();

//Get our time until the next minute
function setIntervalTimeToNextMinute(){
    var currentDateSeconds = new Date().getSeconds();
    if(currentDateSeconds == 0){
        return 60000;
    } else {
        return (60 - currentDateSeconds) * 1000;
    }
}

My use case for this was a session timout:
startTime - allows me to pass in any milliseconds time. This way I can avoid lapses in page loading. Say user logins in at a certain time. I capture that time, then pass it into initial function and it will adjust back to the on minute calculation.
duration - I use the duration check for a timeout setting. If the application has a 20 minute timeout, then I need to route the user to the login screen.
optionally - you can add more variations. Say you wish to give the user a 2 minute warning that they will be logged out. Simply add to the conditional an else if for 2 minutes.
Hope that helps! Happy coding!

A: This can actually be done fairly simply by combining setTimeout with setInterval. I'll first demonstrate how to do this in long-form, and then provide a shorthand one-liner function below which will accomplish the same thing.

function setEmomInterval(expr, ...rest) {
  setTimeout(function() {
    expr(...rest);
    setInterval(expr, 60000, ...rest);
  }, 60000 - new Date().getTime() % (60 * 1000));
}

setEmomInterval(() => console.log(`The time is now ${new Date().getHours()}:${new Date().getMinutes()}`));

This has the added benefit of not only being accurate to the second, but in fact accurate to the millisecond, minus any minimal lag due to computation time.
As a one-liner, it would look like this:

const setEmomInterval = (expr, ...rest) => setTimeout(() => (expr(...rest), setInterval(expr, 60000, ...rest)), 60000 - new Date().getTime() % (60 * 1000));

setEmomInterval(() => console.log(`The time is now ${new Date().getHours()}:${new Date().getMinutes()}`));

As mentioned, there is some delay due to what is known as "drift" in the computation time. To work around this, if you need the most accurate time, use the driftless library by Dan Kaplun (@dbkaplun on GitHub).

A: The Above answers fulfill the job but still wanted to solve this with a better approach.
You can solve this by using setInterval & clearInterval
let job = setInterval(function() {
    /* Do you stuff */
},1000);

setTimeout(function() {
    clearInterval(job);
},60000);


text:
Q: Annual school events How would you call these kind of events organized by schools at the end of the year generally in June where children (6 to 12 years old) sing, dance or act?
In French we say :
"Fête annuelle de l'école"
"Kermesse de l'école"

A: My first instinct would be to say "school pageant," but my vocabulary is old-fashioned and I don't really know 21st-century popular culture; "pageant" might be exactly the wrong word at this point in history. "Christmas pageants" used to be a staple of schools, but aren't so common anymore; "beauty pageants" are common and could give connotations to the word "pageant" that are horribly wrong in this context.
"Spring Program" is Kristina Lopez' recommendation for this. The term sounds vague and anodyne to my ear, but it might be a better suggestion than mine; the hearer wouldn't learn much about what the event was, but at least he or she wouldn't come out with an incorrect or embarrassing impression.
In this context, "pageant" refers (or formerly referred) to a theatrical performance or series of performances, not depicting a single story or organized into acts and scenes, probably performed by amateurs, in which the quality of the performance is much less important than the fact of participating in it. (Apparently these evolved from the medieval mystery plays.) If this isn't something exclusively theatrical, or if it has competitive elements, "pageant" is not appropriate no matter how archaic your vocabulary may be.
Note that all this is an answer in the US context; from other answers here, it sounds like "school fête" would be perfectly comprehensible in England. (And Wales, Cornwall, and Scotland? Ireland? All of Great Britain? Everywhere in the world that spells "color" with a "u"?)
(This has been edited to reflect Kristina Lopez' and Choster's comments. Thanks!)

A: How about "Talent Show" or "Annual Talent Show" to emphasize that it's a recurring event?

A: *

*Fête is also used in English to mean approximately the same thing. (England)

*Summer Fair is also used to mean a celebration or gathering.