Q:

parse formdata request at nodejs server

How do you parse formdata at nodejs side?
I’m doing http POST requests to a nodejs server.
Here is a snippet of the Javascript(angular in it). My aim is to upload a file and add a JSON to it. So I’m uploading a picture and a json that has {account: xx , sitename:xyz, etc..}
$scope.upload[index] = $upload.upload({
                url :  'http://localhost:1215/facility',
                method: $scope.httpMethod,
                headers: {'Content-Type': 'multipart/form-data','X-Requested-With':'XMLHttpRequest'},
                data :  $scope.selectedSite,
                withCredentials:true,
                file: $scope.selectedFiles[index],
                fileFormDataName: 'myFile'
            }).then(function(response) {
                $scope.uploadResult.push(response.data);
            }, null, function(evt) {
                $scope.progress[index] = parseInt(100.0 * evt.loaded / evt.total);
            }).xhr(function(xhr){
                xhr.upload.addEventListener('abort', function(){console.log('aborted complete')}, false);
            });
}

I am using angular-upload-file that allows me to construct the formdata.It combines the selectedSite json with the file and the filename. Found it on github and it is doing the trick. [angular-file-upload][1] https://github.com/danialfarid/angular-file-upload. Fiddler confirms that.
The way that this library angular-file-upload works is that the http with XMLHTTPREQUEST will results in the body referring to the formdata which looks like this
{
   site:xyz,
   account:xxx,
   etc
   Myfile: somefile.txt: fileContent
}

At the server side, regardless of what I do I cannot get the value of the json key (e.g. xyz) or the content of the file. I am not yet trying to save the file or manipulate the json yet.
router.post('/', passport_utils.ensureAuthenticated,
    function(req, res)
    {
        var data ,file= {};//reconstruct site from formdata

        console.log("req.body"  + req.body);
        //jsonData = JSON.stringify(data);
        for(var field in req.body){
            console.log(field); //prints all the json elements but not the file or the filename
                if(field.match(‘site’))
                    console.log("HI    username "+ field.site) ;
                if(field.match('account'))
                    console.log("hi data " + field.name);
        res.send(200);
  }

I tried doing field[jsonkey] or field.jsonkey to get the value. The above for loop confirms that i have the keys but not the value.  All those result in "undefined" for the value.
The key value shows up but not the value

A:

It looks like you are using Express 4, if you are, you need to set the body parser in your server:
var bodyParser     = require('body-parser');
//...

var app            = express();
//...
app.use(bodyParser());  // pull information from html in POST

In earlier version of Express you only needed to add the body parser from the framework itself:
app.use(express.bodyParser());                      // pull information from html in POST

Since version 4 removed support for connect now you need to add your custom support for multipart/form data  to parser  multi/part POSTs, so you will have to to do something like:
var busboy = require('connect-busboy');
app.use(busboy());


Q:

DNS lookup >100ms when domain is an IP address?

I have a webpage on a device that is access only by IP address, not by a domain name (e.g. 172.16.4.33). The page performs a few ajax calls to the same server, and I noticed in firebug some of these calls show a non-zero DNS lookup time.
If no domain name needs to be translated into an IP address, why is any time taken for DNS lookup at all?

A:

There could be links in the page that point to domain names, or there might be reverse lookups happening.


Q:

Is Class variable in swift can only be accessed by class function...?

I cant access "price" variable without a class function , may i know why ?
here is the code.
class var price : Int {
      return 25000
    }

 class func display()
    {
        println("The \(name) with \(model) was released in \(year) with rs.\(price)")
    }

A:

A class var belong to a class, not the instance. You can access it via:

the class name: MyClass.price
self.dynamicType.price (for a function inside the class)
myVar.dynamicType.price (assuming myVar is an instance of the class).


Q:

Matrix multiplication in Common Lisp

I am writing the program in CL (with SBCL 1.2.15) that uses linear algebra. During the course of execution, it often multiplies a matrix by a vector.
Profiler showed that most of the time (80%) the program spends doing exactly that, multiplying matrix by vector. It also shows that this function does lots of consing (80,000,000 for ~100 calls for 100x100 matrices), which triggers GC as well. Having done something similar in F# (that has a benefit of static type-checking, but otherwise does not usually outperform SBCL), F# program runs 10 times faster.
Am I doing it wrong?
(defun matrix-mul (matrix vector dest)
  "Multiply MATRIX by VECTOR putting the result into DEST.
Optimized for DOUBLE-FLOAT vectors and matrices"
  (declare (type (array double-float (* *)) matrix)
           (type (vector double-float *) vector dest)
           (optimize (speed 3) (debug 0) (safety 0)))
  (destructuring-bind (rows cols) (array-dimensions matrix)
   (dotimes (i rows)
     (setf (aref dest i)
           (loop for j below cols sum (the double-float
                                           (* (aref matrix i j) (aref vector j))))))))

PS. I have also tried using DOTIMES instead of inner LOOP - no difference
PPS. Next option can be using BLAS from CL, but (i) I am not looking forward to making it work on Windows, (ii) will need marshaling matrices/vectors back and forth.

A:

The usual problem is that float arithmetic, here with double-floats, (independent of the surrounding code like matrix multiplication) conses.
Generally the first thing to do with SBCL in such cases:
Put the code into a file and compile it
The compiler will then output a lot of optimization problems, given that one compiles for speed. You would then need to examine the notes and see what you can do.
Here for example the LOOP sum lacks type information.
There is actually a LOOP syntax to declare the type of the sum variable. I don't know if SBCL takes advantage of that:
(loop repeat 10
      sum 1.0d0 of-type double-float)

SBCL 1.3.0 on 32bit ARM for your code:
* (compile-file "/tmp/test.lisp")

; compiling file "/tmp/test.lisp" (written 13 DEC 2015 11:34:26 AM):
; compiling (DEFUN MATRIX-MUL ...)
; file: /tmp/test.lisp

1)
; in: DEFUN MATRIX-MUL
;     (SETF (AREF DEST I)
;             (LOOP FOR J BELOW COLS
;                   SUM (THE DOUBLE-FLOAT (* # #))))
; --> LET* FUNCALL SB-C::%FUNCALL (SETF AREF)
; ==>
;   (SB-KERNEL:HAIRY-DATA-VECTOR-SET ARRAY SB-INT:INDEX SB-C::NEW-VALUE)
;
; note: unable to
;   avoid runtime dispatch on array element type
; due to type uncertainty:
;   The first argument is a (VECTOR DOUBLE-FLOAT), not a SIMPLE-ARRAY.

2)
;     (AREF MATRIX I J)
; --> LET*
; ==>
;   (SB-KERNEL:HAIRY-DATA-VECTOR-REF ARRAY SB-INT:INDEX)
;
; note: unable to
;   avoid runtime dispatch on array element type
; due to type uncertainty:
;   The first argument is a (ARRAY DOUBLE-FLOAT (* *)), not a SIMPLE-ARRAY.

3)
;     (AREF VECTOR J)
; ==>
;   (SB-KERNEL:HAIRY-DATA-VECTOR-REF ARRAY SB-INT:INDEX)
;
; note: unable to
;   avoid runtime dispatch on array element type
; due to type uncertainty:
;   The first argument is a (VECTOR DOUBLE-FLOAT), not a SIMPLE-ARRAY.

4)
;     (LOOP FOR J BELOW COLS
;           SUM (THE DOUBLE-FLOAT (* (AREF MATRIX I J) (AREF VECTOR J))))
; --> BLOCK LET SB-LOOP::WITH-SUM-COUNT LET SB-LOOP::LOOP-BODY TAGBODY SETQ THE
; ==>
;   (+ #:LOOP-SUM-8 (THE DOUBLE-FLOAT (* (AREF MATRIX I J) (AREF VECTOR J))))
;
; note: unable to
;   optimize
; due to type uncertainty:
;   The first argument is a NUMBER, not a (COMPLEX SINGLE-FLOAT).
;
; note: unable to
;   optimize
; due to type uncertainty:
;   The first argument is a NUMBER, not a (COMPLEX DOUBLE-FLOAT).

5)
; --> BLOCK LET SB-LOOP::WITH-SUM-COUNT LET SB-LOOP::LOOP-BODY TAGBODY WHEN IF
; --> >= OR LET IF OR THE = IF
; ==>
;   (= SB-C::X SB-C::Y)
;
; note: unable to open code because: The operands might not be the same type.

6)
;     (DOTIMES (I ROWS)
;       (SETF (AREF DEST I)
;               (LOOP FOR J BELOW COLS
;                     SUM (THE DOUBLE-FLOAT #))))
; --> DO BLOCK LET TAGBODY UNLESS IF >= IF
; ==>
;   (< SB-C::X SB-C::Y)
;
; note: forced to do static-fun Two-arg-< (cost 53)
;       unable to do inline fixnum comparison (cost 4) because:
;       The second argument is a INTEGER, not a FIXNUM.
;       unable to do inline (signed-byte 32) comparison (cost 6) because:
;       The second argument is a INTEGER, not a (SIGNED-BYTE 32).
;       etc.

7)
;     (LOOP FOR J BELOW COLS
;           SUM (THE DOUBLE-FLOAT (* (AREF MATRIX I J) (AREF VECTOR J))))
; --> BLOCK LET SB-LOOP::WITH-SUM-COUNT LET SB-LOOP::LOOP-BODY TAGBODY WHEN IF
; --> >= OR LET > IF
; ==>
;   (> SB-C::X SB-C::Y)
;
; note: forced to do static-fun Two-arg-> (cost 53)
;       unable to do inline fixnum comparison (cost 4) because:
;       The second argument is a REAL, not a FIXNUM.
;       unable to do inline (signed-byte 32) comparison (cost 6) because:
;       The second argument is a REAL, not a (SIGNED-BYTE 32).
;       etc.

8)
; --> BLOCK LET SB-LOOP::WITH-SUM-COUNT LET SB-LOOP::LOOP-BODY TAGBODY SETQ THE
; ==>
;   (+ #:LOOP-SUM-8 (THE DOUBLE-FLOAT (* (AREF MATRIX I J) (AREF VECTOR J))))
;
; note: forced to do static-fun Two-arg-+ (cost 53)
;       unable to do inline float arithmetic (cost 2) because:
;       The first argument is a NUMBER, not a DOUBLE-FLOAT.
;       The result is a (VALUES NUMBER &OPTIONAL), not a (VALUES DOUBLE-FLOAT
;                                                                &REST T).
;
; note: doing float to pointer coercion (cost 13), for:
;       the second argument of static-fun Two-arg-+
;
; compilation unit finished
;   printed 10 notes


Q:

Returned BBOX of a WMS with varying aspect ratio

WMS GetMap queries take a BBOX parameter for the map and a WIDTH and HEIGHT parameter for the image.
If the aspect ratio of the image (WIDTH/HEIGHT) doesn't match the aspect ratio of the BBOX (dx/dy) does the spec say it will distort the image into that WIDTH/HEIGHT aspect or does it say it will increase the area of the map returned in the image.
The server I'm playing with is doing the latter, but I see mentions on the web of the former behaviour.
In the case of increasing the area of the map, does the spec say that either the vertical or horizontal extent of the image will match the requested BBOX (depending on if its too tall or too wide)?
I suppose the safest thing is to always call with matching aspect ratios...
Here's some test grabs with three different aspect ratio WIDTH/HEIGHT settings and the same BBOX for your comparison:
wget -O test.png "http://www.osmgb.org.uk/OSM-GB/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=OSM-GB:__all__&SRS=
EPSG:27700&BBOX=532685,176236,542182,183918&FORMAT=image/png&WIDTH=400&HEIGHT=400"
wget -O test2.png "http://www.osmgb.org.uk/OSM-GB/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=OSM-GB:__all__&SRS
=EPSG:27700&BBOX=532685,176236,542182,183918&FORMAT=image/png&WIDTH=400&HEIGHT=800"
wget -O test3.png "http://www.osmgb.org.uk/OSM-GB/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=OSM-GB:__all__&SRS
=EPSG:27700&BBOX=532685,176236,542182,183918&FORMAT=image/png&WIDTH=800&HEIGHT=400"

A:

The WMS server in question passes these requests through to the "OGC Mapnik" WMS server, which is non-compliant to the standard. There is some discussion about this.
Solution is to only query with the aspect ratio the same.


Q:

Emacs opening and saving encoding

I have a Perl source file in utf-8 encoding, LF ending. It contains English and Chinese characters. The questions are:
1.When I open file, the encoding is windows-1251-unix. I have to run these commands:
Alt-x revert-buffer-with-coding-system
> Coding system for visited file (default nil):
utf-8-auto-unix
> Revert buffer from file file_name.pl?
y

How to automatically open it in utf-8-auto-unix?
2.When I edit the file and try to save it, Emacs gives me a question:
> Select coding system (default raw-text):
utf-8-auto-unix

How to automatically save the file in utf-8-auto-unix? And get rid of the question.

A:

You could add this comment to the top of the file:
# -*- coding: utf-8 -*-

A:

Use describe-variable(C-h v) to examine the variable current-language-environment; follow the customize link and set it to "UTF-8".


Q:

Problems trying to install using npm: "core-js@<3 is no longer maintained"

I've been following along with a web dev tutorial and I'm stuck at this part: https://btholt.github.io/intro-to-web-dev-v2/libraries#building-your-code
I've been trying for a couple of days to install parcel-bundler and can't figure out what I'm doing wrong. I also tried Prettier and get the same errors. I'm so frustrated and running out of ideas.
I'm running npm 6.14.4 and node 12.16.2.
This is the error npm install -g parcel-bundler in Users/myName (Catalina 10.15):
npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/Users/myName/.node_modules_global/bin/parcel -> /Users/myName/.node_modules_global/lib/node_modules/parcel-bundler/bin/cli.js

> parcel-bundler@1.12.4 postinstall /Users/myName/.node_modules_global/lib/node_modules/parcel-bundler
> node -e "console.log('\u001b[35m\u001b[1mLove Parcel? You can now donate to our open collective:\u001b[22m\u001b[39m\n > \u001b[34mhttps://opencollective.com/parcel/donate\u001b[0m')"

Love Parcel? You can now donate to our open collective:
 > https://opencollective.com/parcel/donate
+ parcel-bundler@1.12.4
updated 1 package in 18.055s

And if I try to run parcel --help I'm told: -bash: parcel: command not found
So I try to fix that first warning. I list the links to the SO articles that I tried at the bottom. I tried deleting node_modules in home directory and doing npm install again. I tried npm install --save core-js@^3. I tried doing a forced clean cache and reinstalling. I tried npm update.
This is my package.json:
{
  "name": "generic_package",  <-- manually changed from myName
  "version": "1.0.0",
  "description": "Test description", <-- manually added to remove "no description" error
  "main": ".mongorc.js",
  "dependencies": {
    "core-js": "^3.6.5",     <-- looks like it's using >3v
    "lodash": "^4.17.15",
    "parcel-bundler": "^1.12.4",  <-- looks like it's there??
    "prettier": "^2.0.4"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "node build/build.js" <-- manually added as per an SO article
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "repository": { <-- manually added this object as per an SO article
    "type": "git",
    "url": "https://github.com/npm/npm.git",
    "private": true <-- manually added as per another SO article
  }
}

Error: Please, upgrade your dependencies to the actual version of core-js@3
npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues
npm WARN deprecated core-js@2.6.11
How to update core-js to core-js@3 dependency?
Problems installing express using npm.

A:

The reason for the message npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained is because parcel-bundler has a transitive dependency on core-js@2.6.11, which is no longer supported.
It appears that parcel was installed correctly, so you should be able to run it.  On Linux systems, it would have created a symlink under /usr/local/bin/parcel.  Make sure that "/usr/local/bin" is in your PATH.
You can also run it as follows:
npm run-script parcel

On newer versions of NPM, you can run this:
npx parcel


Q:

Pauling's equation on the relationship between Electronegativity and Percentage Ionic Character

In Paulings eqn:
$$ \%~\ce{ionic~character} = \left[ 1−e^{−(Δχ/2)^2}\right] \times 100$$
What is $e$?
I for the love of me can't find it anywhere

A:

'e' is a natural exponential function, so not an actual measurement.
The equation is correctly written as:
% Ionic character $= (1 − e^{−(\frac{Δχ}{2})^2})×100$
where the $−(\frac{Δχ}{2})^2$ term is raised as a power of the natural exponent 'e'.
Source: The University of the West Indies page Lecture 3. Polarizability, you'll need to scroll down the page a bit to the section labelled 'Bond character based on electronegativity differences'.


Q:

Installing (python3) airflow does not create airflow directory

Having problem where installing airflow (in python3) does not create the airflow directory (unlike in the python2 version, where the directory is created automatically after pip install).
[airflow@airflowetl ~]$ pip3 --no-cache-dir install apache-airflow --user
Collecting apache-airflow
  Downloading https://files.pythonhosted.org/packages/d5/12/6e5e4207483df7e82ac87079281f8f500e6610247ceb1464ed5592f4ceed/apache_airflow-1.10.5-py2.py3-none-any.whl (5.9MB)
    78% |█████████████████████████▎      | 4.6MB 1.4MB/s eta 0:00:01debug2: channel 0: window 999183 sent adjust 49393
    100% |████████████████████████████████| 5.9MB 1.4MB/s
.....
Installing collected packages: apache-airflow
Successfully installed apache-airflow-1.10.5

[airflow@airflowetl ~]$ pwd
/home/airflow
[airflow@airflowetl ~]$ ls
Documents  Downloads  projects  tmp

Any idea what is happening here and how to fix?

A:

Found that unlike with python2, airflow in python3 does not create the ~/airflow dir until the first time airflow is run

The first time you run Airflow, it will create a file called airflow.cfg in your $AIRFLOW_HOME directory (~/airflow by default).
  https://airflow.readthedocs.io/en/1.9.0/configuration.html#setting-configuration-options

I am assuming this means any airflow ... CLI command, but in my case I just ran the next installation step (though I assume something like airflow list_dags would also work)...
[airflow@airflowetl ~]$ airflow initdb
[2019-10-18 13:36:56,916] {__init__.py:51} INFO - Using executor SequentialExecutor
DB: sqlite:////home/airflow/airflow/airflow.db
[2019-10-18 13:36:57,438] {db.py:369} INFO - Creating tables
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade  -> e3a246e0dc1, current schema
INFO  [alembic.runtime.migration] Running upgrade e3a246e0dc1 -> 1507a7289a2f, create is_encrypted
/home/airflow/.local/lib/python3.6/site-packages/alembic/ddl/sqlite.py:39: UserWarning: Skipping unsupported ALTER for creation of implicit constraint
  "Skipping unsupported ALTER for "
....
INFO  [alembic.runtime.migration] Running upgrade 939bb1e647c8 -> 004c1210f153, increase queue name size limit
WARNI [airflow.utils.log.logging_mixin.LoggingMixin] cryptography not found - values will not be stored encrypted.
Done.
[airflow@airflowetl ~]$ cd
[airflow@airflowetl ~]$ ls
airflow
[airflow@airflowetl ~]$ tree airflow/
airflow/
├── airflow.cfg
├── airflow.db
├── logs
│   └── scheduler
│       ├── 2019-10-18
│       └── latest -> /home/airflow/airflow/logs/scheduler/2019-10-18
└── unittests.cfg

4 directories, 3 files
[airflow@airflowetl ~]$ mkdir airflow/dags

* (For others having airflow install problems) Note also that the airflow CLI binary location was not initially in my path; had to do a quick
[airflow@airflowetl ~]$ cd
[airflow@airflowetl ~]$ pwd
/home/airflow
[airflow@airflowetl ~]$ find . -name airflow
./.local/lib/python3.6/site-packages/airflow
./.local/lib/python3.6/site-packages/airflow/bin/airflow
./.local/lib/python3.6/site-packages/airflow/www/templates/airflow
./.local/lib/python3.6/site-packages/airflow/www_rbac/templates/airflow
./.local/bin/airflow
[airflow@airflowetl ~]$ echo "PATH=$PATH:~/.local/bin" >> ~/.bashrc
[airflow@airflowetl ~]$ source ~/.bashrc

before could use the binary (another problem I did not have when installing airflow for python2).


Q:

Is there OnSlideShowPageChange like API in PowerPoint JavaScript API?

I am developing PowerPoint add-in using JavaScript API. This add-in needs to execute some action on change slides. But It seems that no API or methods get to achieve it.
I am looking for OnSlideShowPageChange(on VBA) like API.
Is there any solution?

A:

That API is not supported in the Office JavaScript APIs, but it is a great idea. Please suggest it at Office Developer Voice.


Q:

Show that $\frac{1}{\sqrt{r_3}}=\frac{1}{\sqrt{r_1}}+\frac{1}{\sqrt{r_2}}$ for three mutually tangent circles, each tangent to a common line

Three circles are tangents to the line $AB$. Being $r_1$ the radius of the biggest one, $r_2$ the radius of the middle one and $r_3$ the radius of the smallest. Show that $$\dfrac{1}{\sqrt{r_3}}=\dfrac{1}{\sqrt{r_1}}+\dfrac{1}{\sqrt{r_2}}.$$

Hint:show that $AB = 2\sqrt{r_1r_2}$.

I know I have to use the Pitagora`s Theorem.

A:

Let $A$ and $B$ be tangency points to the biggest circle and to the middle circle respectively.
Also, let $O_1$, $O_2$ and $O_3$ be centers of circles with radius $r_1$, $r_2$ and $r_3$ respectively
and let $O_3K$ and $O_3M$ be perpendiculars from $O_3$ to $O_1A$ and $O_2B$ respectively.
Thus, $O_1K=r_1-r_3$, $O_1O_3=r_1+r_3$ and by the Pythagoras's theorem we obtain:
$$O_3K=\sqrt{(r_1+r_3)^2-(r_1+r_3)^2}=2\sqrt{r_1r_3}.$$
Similarly $$O_3M=2\sqrt{r_2r_3}$$ and
$$AB=2\sqrt{r_1r_2}$$ and since $AB=O_3K+O_3M$, we obtain:
$$2\sqrt{r_1r_2}=2\sqrt{r_1r_3}+2\sqrt{r_2r_3}$$ or
$$\frac{1}{\sqrt{r_3}}=\frac{1}{\sqrt{r_1}}+\frac{1}{\sqrt{r_2}}.$$
Done!


Q:

vim: Why does the sh colour scheme highlight `$(...)` as an error?

For example:

I was under the impression that $(...) was recommended over `` because it's easier to nest.

A:

Because your .vimrc file does not contain
let g:is_posix = 1

See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=552108

A:

You are correct that $( ) is recommended over backticks as the latter has been depreciated.  You're also correct that $( ) is POSIX shell.  However, to the best of my knowledge, $( ) was added to the POSIX spec in 2004 and assuming you have the latest version of vim, it is quite likely that the sh.vim syntax highlight file has not been updated to reflect this change in the POSIX shell standard.


Q:

Role of dam methylase in bacteria

In bacteria, an enzyme called dam methylase (Deoxyadenosine methylase)  methylates adenines (A) in the sequence GATC in the new strand formed after replication.
What role does this methylation play?
I read that it has something to do with proofreading. If this is so, then how?

A:

The dam methylase has three different functions:

Correction replication errors, since the new DNA molecule
is only hemimethylated (the old strand is methylated, the newly
synthesized is not). Since the proof-reading only takes place on the
new strand, errors introduced during replication can be corrected.
Regulation of replication: The ori of the chromosome is methylated to ensure that is only replicated once.
Regulation of transcription: Methylation of GATC sequences promote the transcription of genes.

For further details see the references.
References:

The great GATC: DNA methylation in E. coli
The dam and dcm strains of Escherichia coli--a review.
Dam methylation: coordinating cellular processes.


Q:

How to scale html font size in Bootstrap 4 without breaking responsive navbar

I'm trying to scale a webpage the bootstrap 4 way (using html font-size and rem everywhere else) but it seems to break the responsive navbar's activation (i.e. it doesn't activate properly).
The actual problem is when you scale the view down, the responsive navbar is supposed to hide the menu options and provide the hamburger icon. However, if you scale the html font-size up, the responsive navbar does not activate when the menu will be outside the viewport. In the example provided, scale the view down with 22px font, and see how the menu goes to the next line. Then remove that CSS and scale the menu and it works just fine with 16px (default) font.
Any idea on how to remedy this problem, or am I doing responsive navbar and font scaling improperly?
https://jsfiddle.net/fsc6gpb8/3/
HTML

  <button class="navbar-toggler hidden-sm-up" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar2">
    ☰
  </button>

    Responsive navbar

        Home (current)

        Features

        Pricing

        About

CSS
html {
    font-size: 22px;
}

Documentation regarding my example and responsive navbar: http://v4-alpha.getbootstrap.com/components/navbar/#collapsible-content
Here is an image of the actual bug: http://i.imgur.com/bI9GWVN.png

A:

In bootstrap v4, the navigation can be collapsed sooner or later using different css classes
eg:

navbar-toggleable-xs
navbar-toggleable-md
navbar-toggleable-lg

With the button for the navigation:

hidden-xs-up
hidden-md-up
hidden-lg-up

And of course you can use media queries to do that.


Q:

Symfony2 set up

I'm trying to set up sample Symfony2 project as shown here
http://symfony.com/doc/current/quick_tour/the_big_picture.html
and after accessing config.php I have this:
Major problems have been detected and must be fixed before continuing:
Add "phar" to suhosin.executor.include.whitelist in php.ini*.

I added this:
suhosin.executor.include.whitelist="phar"

into php.ini, but config.php still show the same message.

A:

1) Check that you edited the correct php.ini, usually a PHP installation has several php.ini (one for CGI, one for CLI, one for APACHE2). Have a look in /etc/php5 for instance.
2) Check in phpinfo() that the parameter is taken in account.
3) Refer to this blog post:
[Solved] symfony 2 Major problems Major problems have been detected and must be fixed before continuing: Add “phar” to suhosin.executor.include.whitelist in php.ini*.
The post suggests ensuring suhosin is installed with
sudo apt-get install php5-suhosin


Q:

Why is temporal difference learning biased in reinforcement learning?

When I learn reinforcement learning from David Silver's online video, I saw "the objective of TD learning, $r_t + \gamma V(s_{t+1})$ is a biased target for learning value function. " I know the definition of "biased", but I'm not sure why TD learning is biased. The followings are my questions:

Under the framework of functional approximation for value function, is it because now the parameters of $V(s_{t+1})$ are not correct value during training, hence the current value of $V(s_{t+1})$ could be totally meaningless which causes it to be biased?
In that case, suppose the parameters will converge at the end of training procedure. In that case, is $r + V(s_{t+1})$ still biased or not?
For tabular cases, is $r + V(s_{t+1})$ still biased? I think it is now an unbiased estimator of value function. Suppose the process is episodic with total number of $T$ steps. The value function at the last time step $V(s_T)$ is clearly unbiased. This causes the estimation of $V(s_{T-1})$ to be unbiased. We can repeat the process to prove for any $t$, $V(s_t)$ is unbiased. Is this correct?

A:

1.question: You are right, that's the reason why it's biased.
2.question: Consider simple TD update rule
\begin{equation}
V(s) = V(s) + \alpha[R + \gamma V(s') - V(s)]
\end{equation}
let's assume for simplicity that $\gamma = 1$, that reward $R$ is deterministic and that you know the correct value of $V(s')$. Then recursively we have
\begin{align}
V_{n+1}(s) &= V_n(s) + \alpha[R + V(s') - V_n(s)] \\
&= (1-\alpha)V_n(s) + \alpha(R + V(s'))\\
&=(1 - \alpha)[V_{n-1}(s) + \alpha[R + V(s') - V_{n-1}(s)]] + \alpha(R + V(s'))\\
&= \ldots \\
&= (1-\alpha)^n V_1(s) + \sum_{i=1}^n \alpha(1 - \alpha)^{i-1} (R + V(s'))
\end{align}
so the starting value before any updates was random biased value $V_1(s)$ and it will keep affecting value $V_{n+1}(s)$ after $n$ updates but its influence will be $0$ as $n \rightarrow \infty$ because $(1- \alpha)^n \rightarrow 0$. So in conclusion it will still be biased but it will decrease with time, and since $V(s_{T})$  will be eventually unbiased then other states should converge to true values as well.
3.question: same analysis applies like for the above case since the starting state is also initialized to random value and $V(s_T)$ will be eventually unbiased.


Q:

How to extract polygons from raster?

The goal is to get the vector polygons from raster areas accordingly to their gray scale. For example:

Dark pixels to dark_relief.shp
Gray pixels to gray_relief.shp
Light pixels to light_relief.shp

First I got GeoTIFF from SRTM file using Raster – Analysis – DEM (Terrain models) in Hillshade mode:

Then I use Raster - Conversion - Polygonize (Raster to Vector), but result is too many small polygons. Obviously I should prepare the image before a conversion.
Any hints what to do?
May be other right way exists?
Regards!

A:

If you know the cut off points for each contour/band/classification you can reclassify your raster file in qGIS with the raster calculator. From there you can use raster to vector to create polygons only for the contours/bands/classifications you specified.
The example raster calculator calculation below should divide a layer into three pieces, areas below 1000, areas between 1000 and 1200, and areas above 1200.
("layer" > 1000) * 1 + ("layer" > 1200) * 1

With a starting raster of:

And the above calculation, I got:

Which will polygonize pretty easily and cleanly.


Q:

How to start Splunk Forwarder within a script

I would like to start to monitor our dockers with Splunk. To do it I want to add it to the docker buildfile.
The issue is that if its the first time you start the forwarder, it prompts you to agree for the license agreement, which breaks the script.
Is there a way to start the Splunk forwarder without being prompted?

A:

The arguments you are looking for are --accept-license --answer-yes --no-prompt.
A Splunk employee publishes some Docker images on his own time that can cater for this already. Have a look at SPLUNK_START_ARGS in the forwarders entrypoint.sh.
Also, Docker natively supports sending its own logs to Splunk. This includes the stdout and stderr of all containers so you may not need your own forwarder.


Q:

Gradle - Android - add version code number as versionNameSuffix to debug buildTypes

I want to add the version code as a suffix of versionNameSuffix.
Currently, I have:
    debug {
        versionNameSuffix ".debug"
    }

How can I have something like:
    debug {
        versionNameSuffix ".debug.versionCode"
    }

My version code is based on the productFlavors:
    productFlavors {
        free {
            versionCode 123
        }
    }

@Resolution: I move versionCode out from productFlavors to root level and use the accepted anwser to inject versionCode in versionNameSuffix

A:

Create constant version code in your app build.gradle
def versionCode = 1
Then in your flavours
debug {
    versionNameSuffix ".debug.${versionCode}”
}

Use the same version code in your defaultconfig also
defaultConfig {
    versionCode ${versionCode}
}


Q:

How to find a Window Handle on ProcessID C#

I am attempting to find a Process with certain name, see if the Class: CTX WndClass exists, if it does.. do nothing an loop through the check every 30secs.
If it does not, wait 30 secs check to see if it does now, if it doesn't close the Process.
This is what I have so far, but it's telling me it's expecting "}" on line 51 and I don't see why lol.
This is the problem, right before the else:
private static void FindMain(int handle)
            {
                // Get the class.
                StringBuilder sbClass = new StringBuilder(256);
                GetClassName(handle, sbClass, sbClass.Capacity);

                if (sbClass.Length == 0)
                    System.Threading.Thread.Sleep(30000);
                foreach (var process in Process.GetProcessesByName("ARS.exe"))
                {
                    process.Kill();
                }
                else
                 FindMain(handle);
            }
        }

.

A:

Your code should look like this:
if (sbClass.Length == 0)
{
     System.Threading.Thread.Sleep(30000);
     foreach (var process in Process.GetProcessesByName("ARS.exe"))
     {
         process.Kill();
     }
}
else
{
     FindMain(handle);
}

You're missing some curly braces. An 'else' sentense belongs to an 'if' sentence so the curly braces must match.
You should really format your code better with matching braces lined up, then you will avoid such problems.


Q:

how can I use built-in ASP.NET templates for sending emails?

Is there any samples on how to use ASP.NET built-in templates out of the page, just for rendering text with params. For instance, to build email message.
thanks in advance.

A:

You could use the class MailDefinition
Here you have a sample of how to use it.


Q:

Kegging vs. Bottling (force-carbonated), what's the difference in taste?

I'm achieving a rather bizarre sense of enlightenment and was hoping someone could explain the impact that force carbonation in a keg vs. force carbonation in a keg with eventually bottling off would have on a beer.
I ask this because I am now on my second beer, this one being an IIPA (Belgian yeast) that I've bottled straight from the keg after it being in the keg for 3-4 weeks, and now that I just cracked one, 2-3 weeks after putting it in the bottles, it tastes profoundly different than when it was in the keg.
I will admit that the hop aroma is dying off (which frankly, given the amount of dry hopping I did, is probably a good thing), the flavor is still mostly there, but it seems a lot more well-rounded and not as disjointed as it did while it was in the keg (bubble gum aroma, not much hop flavor, enamel stripping bitterness, it all seems to be centering on each other into a balanced mix now).
Is this just the effects of aging?  I saw the same thing with a smoked porter using peat malt.  I kegged it at the same time I did this IIPA, and had I not known that I put peated malt in it, I never would have tasted it.  After I bottled it (again, same day as this IIPA, I used 4-5% peated malt), and let it sit until last Thursday, it tasted like someone encapsulated the entire Amazonian rain forest after being burnt to the ground by a bunch of torch wielding 7 foot tall blonde beauties all in one bottle.  I never got that sense of flavor when it was kegged, not even close, and I'm depressed that I drank almost all of it before I could get this flavor out of it.
What gives?  Is it just age?  Does bottling with less head room for the CO2/beer to breathe have some sort of effect on flavor?  Is something else at work?

A:

There are many small things at play, but only one major difference. When you bottle from a keg, the CO2 level in the keg will be higher than that in the bottle. You lose some CO2 during bottling. (The higher the number of volumes, the more you'll lose ... also, the higher the temps the more CO2 lost). When bottling for competition this is even truer - but this is due to serving: pourings are small, swirled, left out for a time, etc.
In terms of flavor in the long-term, bulk aging will allow all the beer to age together while aging in bottles may cause different flavors in different bottles. Yeast may still be at work, but this is less likely under pressure.
It almost sounds as though you have the common problem of kicking the keg just as the flavor is peaking. The only difference is that you notice it while the beer's in bottles - the flavor either peaks or has passed its peak. Do you ever taste them side by side (ket, bottle) after the beer has been bottled for a month or so?
It's hard to say for sure why you're noticing what you're noticing. Flavor changes during aging are pretty complex -- hop aroma loss is the most understandable, but even that doesn't make a whole lot of sense when the beer's totally sealed up. Flavor compounds break down and change over time and even the experts can't fully explain it.


Q:

T-SQL DateDiff return absurd results

I tried datediff in my db and it returns absurd result. How it is possible? Where I do mistake? Can Anybody Help me?
Here is screen of my table in database
DECLARE @sql_statement nvarchar(250)
Declare @dal  date
declare @dat varchar(20)
set @dal = '07.08.2015'
SET @dat = Convert(Varchar(20),@dal,101)
SET @sql_statement = 'SELECT datediff(yy,'+@dat+',DateEx) FROM ExData '
EXECute sp_executesql  @sql_statement

A:

The main problem is that dynamic query:
SET @sql_statement = 'SELECT datediff(yy,'+@dat+',DateEx) FROM ExData '

should be (please note double single quotation marks added -> '''+@dat+''')
SET @sql_statement = 'SELECT datediff(yy,'''+@dat+''',DateEx) FROM ExData '

Without those quotation marks, query can be evaluated as
SELECT datediff(yy,07/08/2015,GETDATE())

and because
SELECT CONVERT(DATETIME, 07/08/2015) -- SELECT 07/08/2015 -> 0

gives
1900-01-01 00:00:00.000

the end result is 115.
Solution #1: I would use a static query (no EXEC sp_executesql)
SELECT datediff(yy,@dal,DateEx), ... FROM ExData

Solution #2: or I would use sp_executesql with parameters (but not in this case):
SET @sql_statement = 'SELECT datediff(yy,@pDate,DateEx), ... FROM ExData '
EXECute sp_executesql  @sql_statement, '@pDate DATE', @pDate = @dal


Q:

How string formats '%' operator is implemented?

How does string formats '%' operator is implemented in CPython 2.7?
Can't find any reference in the Python documentation.
Well, I fact I found the topic: String conversion and formatting, for PyOS_snprintfand PyOS_vsnprintf. But not sure it match my question.
See also my question Optional keys in string formats using '%' operator?

A:

The implementation is in the PyString_Format that is called by the string_mod function in Objects/stringobject.c. The latter in turn is a slot method stored in PyString_Type->tp_as_number->nb_remainder.
The functions PyOS_*snprintf are not really related to the implementation of str.__mod__.


Q:

Create a custom view group

I want to create a layout with number of childs in circular design and from centre of the view point i need to draw lines to every child.
Please find below image is childs in view are 4.

A:

You can get this by Overriding the drawchild method of android gallery.
Check out ArcMenu which may help you but you have to make some changes in this code according to your requirement.


Q:

CKEDITOR - How to enable hyphenation?

Is it possible to enable hyphenation in CKeditor?
I'm unable to find anything regarding this.
Thanks!

A:

Take a look on some articles auto hyphenation and MDN (also Can I use...). Then you'll find that this feature is available in some browsers only. Still you can add it to the editor using CKEDITOR.addCss if you really like.


Q:

Pandas mapping to TRUE/FALSE as String, not Boolean

When I try to convert some columns in a pandas dataframe from '0' and '1' to 'TRUE' and 'FALSE', pandas automatically detects dtype as boolean. I want to keep dtype as string, with the strings 'TRUE' and 'FALSE'.
See code below:
booleanColumns = pandasDF.select_dtypes(include=[bool]).columns.values.tolist()
booleanDictionary = {'1': 'TRUE', '0': 'FALSE'}

pandasDF.to_string(columns = booleanColumns)

for column in booleanColumns:
    pandasDF[column].map(booleanDictionary)

Unfortunately, python automatically converts dtype to boolean with the last operation. How can I prevent this?

A:

If need replace boolean values True and False:
booleandf = pandasDF.select_dtypes(include=[bool])
booleanDictionary = {True: 'TRUE', False: 'FALSE'}

for column in booleandf:
    pandasDF[column] = pandasDF[column].map(booleanDictionary)

Sample:
pandasDF = pd.DataFrame({'A':[True,False,True],
                   'B':[4,5,6],
                   'C':[False,True,False]})

print (pandasDF)
       A  B      C
0   True  4  False
1  False  5   True
2   True  6  False

booleandf = pandasDF.select_dtypes(include=[bool])
booleanDictionary = {True: 'TRUE', False: 'FALSE'}

#loop by df is loop by columns, same as for column in booleandf.columns:
for column in booleandf:
    pandasDF[column] = pandasDF[column].map(booleanDictionary)

print (pandasDF)
       A  B      C
0   TRUE  4  FALSE
1  FALSE  5   TRUE
2   TRUE  6  FALSE

EDIT:
Simplier solution with replace by dict:
booleanDictionary = {True: 'TRUE', False: 'FALSE'}
pandasDF = pandasDF.replace(booleanDictionary)
print (pandasDF)
       A  B      C
0   TRUE  4  FALSE
1  FALSE  5   TRUE
2   TRUE  6  FALSE


Q:

Why is the natural logarithm represented by $\ln$?

The natural logarithm is often represented by several different notations:

$\log_e x$
$\log x$ (although this is also used for logarithms with a base of 10)
$\ln x$

It is the third notation that has me wondering. Why is $\ln$ used, and not, say, $\text{nl}$? My two theories about this are

It is an abbreviation for "natural logarithm" in a non-English language
It is meant to correspond with the "$l$" in typical logarithmic notation.

Why is the notation $\ln$?

A:

As far as I am aware, the mathematical operator commonly spelled $\ln$ is an abbreviation of the Latin term,  logarithmus nātūrālis.
I am not sure who first used this abbreviation, but I suppose it very well may have been Napier.
I remember having seen ln written as an abbreviation of two words in the form $l.n.$

A:

According to Earliest Uses of Function Symbols :

$\ln$ (for natural logarithm) was used in 1893 by Irving Stringham (1847-1909) in Uniplanar Algebra (Cajori vol. 2, page 107).

Thnaks to KCd's reference in his comment, we have an earlier occurrence :

Anton Steinhauser, Lehrbuch der Mathematik für höhere Gewerbeschulen (1875), page 277.


Q:

What is wrong with this prepared SQL statement?

This does not seem to work, no errors, just doesn't return anything:
$stmt = $pdo->prepare('SELECT * FROM deadfrontier.items WHERE item LIKE "?"');
    $stmt->execute([$test]);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo $row['item'];
    }

But, this does:
$stmt = $pdo->prepare('SELECT * FROM deadfrontier.items WHERE item LIKE "RG6"');
    $stmt->execute();
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo $row['item'];
    }

What am I doing wrong? Thanks.
(Edit: Here's the $test variable: $test = "RG6";

A:

I'm not a PHP expert by any means (@Barmar is though), but I don't think you need to quote escape your strings inside the prepared statement.  Handling the escaping of strings is one of the very reasons why you would want to use a prepared statement.  Instead, just use a ? by itself to handle the string parameter and let PDO do the work for you:
$stmt = $pdo->prepare('SELECT * FROM deadfrontier.items WHERE item LIKE ?');
$stmt->execute([$test]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['item'];
}


Q:

Entity Framework Database First .Net Core

I have a .Net Standard 2.0 class library project and I want to add Entity Framework to it. I have added the Entity Framework Core package to the project but no Entity Framework Templates appear when I try to add a new item to the project. I have looked on the web and all I can seem to find is instructions for Code First!
How do I get the database first functionality back?

A:

EF Core does not, and will never, support the EDMX-based Database First workflow with the designer.  EF Core stores all object-to-database mapping in Attributes and Fluent API mapping in your source code.
In EF 6 the term "Code First" meant two very different things.  One is a code-first modeling workflow where your database was generated from your .NET classes.  The other meaning of "Code First" was just that the mapping metadata was embedded in your source code (Attributes/Fluent API) rather than in an EDMX file.  EF 6 supported two different database-first workflows.  Database-first with the EDMX, and the workflow officially called "Code First From an Existing Database", but which could have been called "Database-First with Code-Based Mapping".
In EF Core, your code will always have the mapping, and so in that sense it's "code first".  But you can still do a database-first design workflow, and write entities and mapping code that match your existing database.
And you can use the scaffold-dbcontext in the Package Manager Console, or dotnet ef dbcontext scaffold in the CLI command to generate entity classes and mapping metadata from an existing database. See Getting Started with EF Core on ASP.NET Core with an Existing Database


Q:

Definition of "algebra of sets"

Can I use the following definition?
Def.. let be $A$ a set and $B \in \mathscr{P}(\mathscr{P}(A))$, $(A,B)$ is algebra of sets if

$\emptyset \in B$
$\forall X \in B( (A-X) \in B)$
$\forall X,Y \in B((X \cap Y ) \in B)$

It is correct? Thanks in advance!

A:

If by "is it correct" you mean "is it equivalent to the normal definition" (closed under pairwise intersections, pairwise unions, contains $\emptyset$ and $A$) then the answer is "yes."
The second bullet asserts it is closed under complements and the third under intersections.
Suppose $S,T\in B$. Since $S\cup T=A\setminus((A\setminus S)\cap (A\setminus T))$, and the right hand side consists of complements and intersections of things in $B$, $S\cup T$ is in $B$ as well.
Finally, $A\setminus\emptyset=A$ is in $B$ also, so you have both identities.


Q:

How to remove a row from the Table on an action performed

I am create a table with the response object recievied from server .
In case the checkbox is unchecked , how can i remove the remove that particular row from the table ??
This is my code
$(document).on('change', 'input[type="checkbox"]', function() {
    var $this = $(this);
    var id = $(this).attr('id');
});

http://jsfiddle.net/vxe2d2hh/10/
could you please let em know how to do this .

A:

You can use this.checked to determine the checked state for current checkbox. If it is false, traverse to closest tr using .closest("tr") along with .remove() to remove it:
$(document).on('change', 'input[type="checkbox"]', function() {
 var $this = $(this);
 if(!this.checked)
    $(this).closest('tr').remove();
});

Working Demo


Q:

How to subtract a constant value from all elements of an array?

I have an array and for example I want to subtract  like 7 from all elements of the array. How can I do that except the below logic.
for (int i = 0; i < array.length; i++)
{
    array[i]-=7;
}

Anything related streams will be helpful.
Edit- It should not necessary be an array. It can be an ArrayList also.

A:

With streams you can use map like this :
int[] array = {-1, 8, 9};
array = Arrays.stream(array)
        .map(i -> i - 7)
        .toArray();

or if you are using List you can use :
List<Integer> array = new ArrayList<>(Arrays.asList(-1, 8, 9));
array = array.stream()
        .map(i -> i - 7)
        .collect(Collectors.toList());


Q:

How would climate be affected on a plateau 10 km above sea level?

I am curious as to what physical geographic features would be present on a plateau 10km above sea level. The Tibetan plateau is only 4km above sea level, so would more than doubling the height exaggerate the geographic features we already see in Tibet, or would new and strange climates and temperature start to form?

A:

10km is waaaaaaay too high.  On your world-building dashboard you have taken one of the dials, thought about turning it up to 11, and instead turned it up to 48.
But it is an interesting experiment to think about: what are the physical effects here?

Too heavy for the crust/mantle to support:  The Himalaya and tibetan plateau are the biggest features Earth can support.  Their height is facilitated by continental collision that can push up the thickened crust against the HUGE desire to sink down into the mantle like an icecube bobbing in a glass of water.  You need a fundamentally different kind of tectonics to support this kind of feature, meaning a planet that is either old or small, such that it has cooled off and has a thick elastic crust atop the viscous mantle (eg. Mars).
VERY COLD:  The atmosphere is, on average, 6.5K colder per Km elevation.  So you are 65 Kelvin colder than sea-level on that
plateau.
Not even normal atmosphere:  10km is near a point we call the tropopause, meaning the atmosphere is so thin that its temperature is
no longer kept in a normal thermal distribution by collisional
dynamics, and is instead radiatively-dominated.  That doesn't
actually affect much if you're living in it -- just feels like cold,
thin air -- but I want to highlight HOW thin and cold that air is.
Messes up global winds:  10km wall?  I can't even picture what than plateau does to airflow.  Blocking global air circulation with an insane Rossby wave on the leeward wide? huge hurricane force
gusts as air descends off the edge of the plateau? Some continual push of air to the outer edge of the plateau? Very disruptive to the global system.

A:

According to this source, the climate up there would be extremly harsh, at temperatures around -35°C with strong winds. Because of the thin air in these heights, those may won't feel as strong as at ground level. Nothing would be able to survive in such heights, as this is even worse than the arctic climate.


Q:

Merging Variable PHP

im confuse that...
like example:
$Q1 = "hello";
$Q2 = "world";
$Q3 = "StackOverflow";

$i = 1;

while($i < 3) {
  $a = "$Q".$i; //I think this is wrong.
  echo $a; // i tried ${$a} doesn't work =/

  $i++;
}

then output format:
$Q1
$Q2
$Q3

but there is not output like this:
hello
world
StackOverflow
I want like $Q + $i become $Q1 to answer is: "hello"...

A:

$varName = 'Q'.$i;
$a .= $$varName;

Or just
echo $$varName . "<br>\n";

A:

To create the variable variable, use:
$a = ${'Q'.$i};


Q:

How to display component in angular 2?

Just starting with angular 2 using the angular2-seed app: https://github.com/angular/angular2-seed. I have created a component but it wont display on the page,this component sits in a directory called external_components at the same level as components:
import {Component} from 'angular2/core';

@Component({
  selector: 'SiteQualification',
  template: '
hello service external
',
})
export class SiteQualification {

  constructor() {}

  ngOnInit() {

  }

}

This is the seed-app.ts:
import {Component} from 'angular2/core';
//import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';

import {Home} from './components/home/home';
import {About} from './components/about/about';
import {SiteQualification} from './external_components/sitequalification';
import {RepoBrowser} from './components/repo-browser/repo-browser';

@Component({
    selector: 'seed-app',
    providers: [],
    pipes: [],

    templateUrl: 'app/seed-app.html',
})

export class SeedApp {

    constructor() {
    }

}

In the seed-app.html I have:

    <siteQualification></siteQualification>

This is app.ts:
import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {HTTP_PROVIDERS} from 'angular2/http';
import {ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';

import {SeedApp} from './app/seed-app';

bootstrap(SeedApp, [
  HTTP_PROVIDERS,
  ROUTER_PROVIDERS,
  provide(LocationStrategy, {useClass: HashLocationStrategy})
])
.catch(err => console.error(err));

Also removed the router.
The problem is the component won't display? What am I missing?

A:

You need to list components and directives in the directives: [...] list of the component where they are used:
@Component({
    selector: 'seed-app',
    directives: [SiteQualification],
    ...
})


Q:

Server returns text/html header instead of application/json header

I have my RESTful service written in ZF2. It works properly in my local windows wamp. It returns text/html instead of application/json header in Ubuntu server. Any idea?

A:

Best way to return JSON formatted output with application/json header from your controller is enabling JsonStrategy in application configuration's view_manager section configuration.
To do that, open the module/Application/config/module.config.php file and :
return array(
 ...
    'view_manager' => array(
        //...
        'strategies' => array(
            'ViewJsonStrategy',
        ),
        //...
    ),
 ...
);

In the controller which you want to return JSON response:
<?php

namespace Application\Controller;

use Zend\View\Model\JsonModel; // Notice this line

class YourController extends AbstractActionController
{
    public function exampleAction() {
        $data = array('foo' => 'bar');
        return new JsonModel($data);
    }
}

Hope it helps!


Q:

Daily Ticket Sales

I looked around to see if there was a similar question, but couldn´t find one. I apologize if there is one and I missed it.
I have the amount of ticket sales per day for 10 different events. The amount of days is different for each event, as well as the number of ticket sold per event. Almost all events show a spike in ticket sales at the start of the selling period.
I want to be able to forecast the (multiple) ticket sales. I do not want to forecast each event individually, but one model that fits (more or less) all. I tried combining the data and use auto.arima (in R) on the combined data, but I have the impression the spikes influence too much the result.
What would be the best way to proceed? How can I take into account all events?
Example data:
tt <- list(
    c(6,3,532,162,54,69,84,43,27,42,54,44,27,21,45,34,26,32,15,27,17,14,5,19,6,
        21,12,10,27,30,22,19,13,22,41,14,211,22,4,27,28,13,15,19,5,13,8,23,33,25,16,41,
        18,36,24,26,25,27,42,37,24,32,32,32,34,49,33,72,28,73),
    c(12,4,4,14,8,15,2472,2144,1031,462,214,340,286,263,244,196,178,73,152,216,487,350,311),
    c(16,2,11845,2374,1492,2074,1654,1303,1090,978,912,542,968,832,1097,724,654,
        645,403,482,12,5740,988,50,8,843,137,6,754,585,111,194,247,162,248,111,122,201,
        208,166,49,2,78,168,446,106,78,1))

A:

Let's plot your data:
opar <- par(mfrow=c(1,length(tt)))
    for ( ii in seq_len(length(tt)) ) plot(tt[[ii]],type="o",xlab="",ylab="",main=ii)
par(opar)

We can already see a couple of things:

Your series have very unequal lengths.
You typically have a peak near the beginning - but the peak can also occur one third into the series (see series 2), with very low sales before that.
You may have a secondary peak around mid-way through your series (series 1 & 3), but not necessarily (series 2).
Your series differ very much in scale (which is not evident from the plots), with totals between 2786 (series 1) and 41908 (series 3).

This will be very, very hard to forecast if you have high hopes for accuracy.
"Typical" time series forecasting algorithms like ARIMA or Exponential Smoothing will not work here. They forecast univariate series out into the future.
I would start with a simple approach. For instance, we could first rescale your series to a target length. I'll use the median length of your series, but if you know that your actual data will have a length of 50, you can use that.
dest.length <- median(sapply(tt,length))

I'll rescale linearly, using an appropriate matrix. Check this for small values of nsource and ndest to understand what is happening here.
make.scale.matrix <- function(nsource, ndest) {
    zero <- matrix(0,nrow=ndest,ncol=nsource)
    f0 <- matrix(0:(ndest-1),nrow=ndest,ncol=nsource,byrow=FALSE)/ndest
    t0 <- matrix(1:ndest,nrow=ndest,ncol=nsource,byrow=FALSE)/ndest
    f1 <- matrix(0:(nsource-1),nrow=ndest,ncol=nsource,byrow=TRUE)/nsource
    t1 <- matrix(1:nsource,nrow=ndest,ncol=nsource,byrow=TRUE)/nsource
    pmax(zero,pmin(t1,t0)-pmax(f1,f0))*nsource
}

We rescale each entry of a list using lapply():
tt.rescaled <- lapply(tt,function(xx)(make.scale.matrix(length(xx),dest.length)%*%xx)[,1])

Let's plot the rescaled series:
opar <- par(mfrow=c(1,length(tt)))
    for ( ii in seq_len(length(tt)) ) plot(tt.rescaled[[ii]],type="o",xlab="",ylab="",main=ii)
par(opar)

As you can see, these still look similar to your original series, but now they are comparable, because they have the same length. In addition, the rescaling keeps the original totals over time:
> sapply(tt,sum)
[1]  2786  9476 41908
> sapply(tt.rescaled,sum)
[1]  2786  9476 41908

So, now we can do some extremely simple modeling and forecasting. For instance, we can simply take pointwise averages:
forecast <- colMeans(do.call(rbind,tt.rescaled))
plot(forecast,type="o",xlab="",ylab="")

As you see, this average is dominated by series 3, which has the highest sales. An alternative would be to forecast total sales (e.g., as the average or the median of total sales) and the "lifecycle" (as the average of each rescaled series' lifecycle) separately:
lifecycle <- colMeans(do.call(rbind,lapply(tt.rescaled,function(xx)xx/sum(xx))))
forecast.alt <- lifecycle*mean(sapply(tt,sum))
plot(forecast.alt,type="o",xlab="",ylab="")

We now see three peaks: the first and the third peak come from series 1 & 3, the second peak from series 2.
Is the first or the second forecast better? It's hard to tell. Of course, you could also start going over this with a kernel smoother or some such.
I would recommend using some very simple approach like this one. Don't overthink the statistical part. Instead, spend your time on getting more information. Can you find out:

why a series has a certain length
why a series has its initial peak right at the beginning or later
why a series has a second peak or not
why the total amount for a series is what it is

All data along these lines will help you understand your time series better, and you will be able to use this in forecasting. Until then, you should also work on the entire process. Is it a problem if you mistime a peak? Or not? Or is getting the total wrong worse?


Q:

How do you get a non-italic pound sign? (£)

How do you get a non-italic pound sign? (£)

A:

In the original cm fonts (OT1 encoding) £ was encoded as italic $ but in the
 8bit encoding (T1) it is not an issue:

\documentclass{article}
\usepackage[T1]{fontenc}
\begin{document}

\pounds\ and \textit{\pounds}

\end{document}


Q:

How to choose a switch?

There seem to be about 4 major flavors of transistors, and then there are NPN/PNP versions. There are also relays, SCRs, and TRIACs.
When I need an microcontroller-controlled switch, what rules of thumb should guide me in choosing? Are there a few common ones that people like to keep around for use when there are no particular high-performance specs?
I'd like to learn the general rules so I don't end up googling 37 variants of the same question.
For a concrete example, the application I am choosing for right now involves driving a 5 V, 160 mA (80 mA average at 50% duty cycle), 3.1 kHz buzzer with an output from a 3.3V MCU that can sink 8 mA or source 4 mA.

A:

Bipolar transistors and FETs work about the same on the output side when you are using them as switches in low power applications like you mentioned.  Both come in two flavors to make either high side or low side switches.  The NPN bipolar and N channel FET are the low side switches, and the PNP bipolar and P channel FET are the high side switches.
The difference between bipolar and FET is mostly how they are turned on and off.  Bipolars are turned on by running some current thru the base.  This allows a much greater current to flow thru the collector.  The ratio of the possible collector current to base current is the gain of the transistor.  FETs are controlled by voltage instead of current.  A basic N channel MOSFET might require 12-15 volts on the gate to be fully on, with 0V fully off.  There are things called "logic level" FETs that can switch between on and off well enough to be driven directly by 3.3V or 5V logic outputs.
I'm going to disagree with Starblue and say that for very simple switching applications for hobby use, get a handful of good logic level FETs like the IRLML2502.  They will cost of 10s of cents each, but are very fogiving as long as everything is limited to 20V.  I would certainly not start with that for a volume design done by a professional, but if you just want to get started with one answer that serves the most needs, this is a good first part to get used to.
Once you're ready to experiment with bipolars get 100 each of 2N4401 and 2N4403.  They are dirt cheap, widely available, and all around pretty robust for their size.  They would also be fine for switching 200mA loads, but you need to know a little more to use them well.  You can't just connect them directly to a microcontroller ouput in a switching application.

A:

Prefer the simplest and cheapest solution.
If an NPN transistor can do the job, use that. For your buzzer you could use some small power NPN transistor. Small signal NPN transistors are for currents less than about 100mA, small power for up to about 1A.
If that is not powerful enough, consider a MOSFET.
Relays, SCRs (thyristors) and triacs are more for switching higher voltages.


Q:

collision and intersection of player and squares

I am making a game where a player must dodge squares that are falling from the sky.
I am trying to make it so that when the player intersects or collides with a falling square, the program will notice.
I realize that i have to get the bounds of the falling squares and the player, but i do not know how to do so. Any help is much appreciated.
Player class
import javax.swing.*;
import java.awt.*;
import java.awt.Rectangle;

public class Player extends JPanel {
     private int XLocation;
     private int squareSize;
     private int YLocation ;
     private int MoveSpeed;
     int xMouse, yMouse;

public int XLocation(){
    return XLocation = 300;
}

public int YLocation(){
    return YLocation = 750;
}

public int SquareSize(){
    return squareSize = 20;
}

public void paint(Graphics g){
    g.setColor(Color.GRAY);
    g.fillRect(XLocation,YLocation,squareSize,squareSize);
}

public Rectangle bounds(){
 return(new Rectangle(XLocation,YLocation,20,20));
}

public int MoveSpeed(){
    return MoveSpeed = 23;
}

 public Player(){
    XLocation();
    SquareSize();
    MoveSpeed();
    YLocation();
}

   public void PlayerMove(java.awt.event.MouseEvent evt){
        XLocation = evt.getX();
        YLocation = evt.getY();
   }

}

The rectangle class
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.Random;

public class Square {

private int XLocation;
private int Size;
private int YLocation = -Size;
private int fallSpeed = 1;
Random rand = new Random();

public int generateRandomXLocation(){
    return XLocation = rand.nextInt(Game.WINDOW_WIDTH - Size);
}

public int generateRandomSquareSize(){
    return Size = rand.nextInt((30-17)+1)+17;
}

public int generateRandomFallSpeed(){
    return fallSpeed = rand.ints(3, 3, 8).findFirst().getAsInt();
}

public void paint(Graphics g){
    g.setColor(Color.BLACK);
    g.fillRect(XLocation,YLocation,Size,Size);
}

public Square(){
    generateRandomXLocation();
    generateRandomSquareSize();
    generateRandomFallSpeed();
}

public void update(){

    if(YLocation >= Game.WINDOW_HEIGHT){
        generateRandomXLocation();
        generateRandomFallSpeed();
        generateRandomSquareSize();
        YLocation = -Size;
    }

    //moves the square down if the square is inside the window
    if(YLocation <= Game.WINDOW_HEIGHT){
        YLocation += fallSpeed;
    }
}
public void GetBounds(){
    Rectangle rectangle = new Rectangle(XLocation,YLocation,Size,Size);
}
}

Game Class
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

public class Game extends JPanel {

public static final int WINDOW_WIDTH = 600;
public static final int WINDOW_HEIGHT = 900;

Square[] squareArray = new Square[20];

Player thePlayer = new Player();

public Game() {

    //initializes square objects
    for (int i = 0; i < squareArray.length; i++)
        squareArray[i] = new Square();

}

public void paint(Graphics graphics) {

    graphics.setColor(Color.WHITE);
    graphics.fillRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

    //paints square objects to the screen
    for (Square aSquareArray : squareArray) {
        aSquareArray.paint(graphics);
    }
    thePlayer.paint(graphics);

}

public void update() {
    for (Square aSquareArray : squareArray) aSquareArray.update();
}

  private void mouseMove(MouseEvent evt) {
      thePlayer.PlayerMove(evt);
}

 public void collision(){
  Rectangle rectangle1 = thePlayer.bounds();
  }

public static void main(String[] args) throws InterruptedException {

    Game game = new Game();
    Player thePlayer = new Player();

    JFrame frame = new JFrame();
    frame.add(game);
    frame.setVisible(true);
    frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setTitle("Raining Multiple Squares");
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);

    BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);

   Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(
cursorImg, new Point(0, 0), "blank cursor");

  frame.getContentPane().setCursor(blankCursor);

          frame.addMouseMotionListener(new    java.awt.event.MouseMotionAdapter() {
        public void mouseMoved(java.awt.event.MouseEvent evt) {
            mouseMove(evt);
        }

        private void mouseMove(MouseEvent evt){
            game.mouseMove(evt);
        }
    });

    while (true) {
        game.update();
        game.repaint();
        Thread.sleep(10);
    }
}

}

A:

You can test collision the same way you are painting  the squares.
 public void collision(){
     Rectangle rectangle1 = thePlayer.bounds();//player rectangle
     for (Square square: squareArray) {
        if(square.GetBounds().intersects(rectangle1)){//testing all squares vs player
            //if you are here a collision happened
            //you can remome square add score ...
        }
    }
 }

intersects method test this rectangle againts the rectagle you are passing to and returns true if the two rectagles are intersecting.
And don't forget to call your collisionmethod once every iteration of your game loop.


Q:

Why do some introductory words are always followed by a comma and others aren't?

Some examples.
However is always followed by a comma. Examples.
Mostly is almost always followed by a comma. Examples.
Rather is 50-50, I think. Examples. (I think this is the case with so too.)
Mainly is more often written without comma. Examples.
So my question is, how to tell which introductory words always require a comma and which don't? Also, do they belong to different categories?
I refer to these type of examples:

"Mostly the population is concentrated in the Zhovtnevy and the
  Prymorsky Raions."

They decided not to put a comma there ... but I think you could put a comma there also.

A:

From my point of view, the way we write should convey as close as possible what we speak. So even if there are no clear rules sometimes, or even in spite of some rules that hinder the use of language, I have some small rules (of my own) to decide how to write.
In the context of your question, I use the rule: does the sentence have (more or less) the same meaning if I remove the word? If yes, then I will (most likely) use a comma.
Compare:

However, I decided to continue walking.

and

I decided to continue walking.

Even though there is a subtle difference in meaning, the main message is still there: I continued walking.

Also compare:

However small the basket was, it seemed to never get full.

and

Small the basket was, it seemed to never get full.

In this case the resulting sentence does not really make any sense, so a comma must not be used.

You must be careful when analyzing. As mentioned by @J.R. in a comment, these words are not always introductory, but part of the sentences, phrases, idioms. In those cases, other rules may (and usually) apply.


Q:

Custom Drawing loop in Swing

I'm trying to learn how to do custom GUI stuff in Java for a group project I'm working on. I've done user form type GUIs in the past so I know the gist of what I'm doing here, but the custom drawing stuff still confuses me.
I copied this code from online and I've been trying to figure out how it works, but I don't get why I can't loop the drawing method. As a simple test I'm trying to make the program draw an oval on my cursor. It draws the oval on the cursor, but only once on runtime and then does nothing.
How can I make this loop so I can continue to draw things? Or is there a different way I need to call/use the methods?
public class BombermanGUI extends JFrame {
   public static final int CANVAS_WIDTH  = 640;
   public static final int CANVAS_HEIGHT = 480;

   private DrawCanvas canvas;

   public BombermanGUI() {
      canvas = new DrawCanvas();
      canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));

      Container cp = getContentPane();
      cp.add(canvas);

      this.setDefaultCloseOperation(EXIT_ON_CLOSE);
      this.pack();
      this.setTitle("......");
      this.setVisible(true);
   }

   private class DrawCanvas extends JPanel{
      @Override
      public void paintComponent(Graphics g){
         super.paintComponent(g);
         setBackground(Color.BLACK);

         int x, y;
         x = MouseInfo.getPointerInfo().getLocation().x - this.getLocationOnScreen().x;
         y = MouseInfo.getPointerInfo().getLocation().y - this.getLocationOnScreen().y;
         g.setColor(Color.YELLOW);
         g.drawOval(x, y, 10, 10);

      }
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
            new BombermanGUI();
         }
      });
   }
}

A:

Painting a complex series of callbacks and responses to changes within the system.  The first thing to remember is that you don't control the painting process, but rather make suggestions to the system so that it can make decisions about what and when it should repaint...
Take a look at Painting in AWT and Swing and Performing Custom Painting for more details.
Painting is a destructive process.  It is assumed that when a repaint occurs, that you will repaint the entire state of the current component.  This means that you will need some kind of model which maintains all the content that needs to be painted...
Have a look at 2D Graphics, in particular, have a look at the section on Shape
MouseInfo is a seriously crappy way to detect the location of the mouse for this purpose, instead, you should be using a MouseListener and/or MouseMotionListener to detect mouse events.
Basically, when the user presses a mouse button, you would record the location of the mouse press.  When the mouse is moved, you would calculate the width and height of the movement relative to the mouse press and update the "current" shape.  You would call repaint to request that the UI be updated and paint this shape via the paintComponent method (painting all the previous shapes first).
When the mouse button is released, you would commit the "current" shape to the model, so it will be painted every time paintComponent is called.


Q:

mySQL use id from newly inserted row in next insert

I am trying to write a query that will insert rows into two tables, tableA and tableB.  tableA is a list of emails that can be sent out to uses while tableB contains the actual text of said emails in the various languages that we support.  The auto-increment id from tableA gets stored in tableB to connect the email names with the text.
What is the best way to grab the id from the new row inserted into tableA to then use in the queries inserting into tableB?  I tried this but mySQL didn't like it (error 1064):
INSERT INTO tableA (eID, name, otherStuff) VALUES (NULL, 'emailName', 'otherValues');
INSERT INTO tableB (id, emailId, body, name, langId) VALUES (NULL, select max(tableA.eID) from tableA, 'email text', 'Default', '1');
INSERT INTO tableB (id, emailId, body, name, langId) VALUES (NULL, select max(tableA.eID) from tableA, 'other language text', 'Default', '2');

Any thoughts on how to make this work?
thanks

A:

use LAST_INSERT_ID(). It returns the last ID that was given to a new row (at the current connection).
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

A:

The mysql function LAST_INSERT_ID() will return you the id of the last inserted row.
So you could try
INSERT INTO tableA (eID, name, otherStuff) VALUES (NULL, 'emailName', 'otherValues');
SET @tableA_id = LAST_INSERT_ID();
INSERT INTO tableB (id, emailId, body, name, langId) VALUES (NULL, @tableA_id, 'email text', 'Default', '1');
INSERT INTO tableB (id, emailId, body, name, langId) VALUES (NULL, @tableA_id, 'other language text', 'Default', '2');


Q:

How does Audi Crown Gear Center Differential work?

I'm trying to understand how the engagement of the clutches is varied. I see the power is transmitted through the center input shaft and is transmitted through the four pinion gears, but I don't understand how the engagement of the clutch(s) is controlled based on which axle has more/less traction. Its it a centrifugal mechanism that is not clearly illustrated, or maybe even the shape(conical?) of the pinion gears them selfs? One point I have heard is the front and rear Crown gears are of a different diameters and the diameter determines the torque split(Some what illustrated, larger diameter being the rear axle which statically gets 60% assuming even traction).
One question I would like to answer from all this is, what would happen if traveling at a non-insignificant speed (45 Mph +), and the rear axle was stopped momentarily (imagine hitting the Emergency brake), what results could you expect?

A:

This set up is a quazai differential/planetary gear set. This can make it difficult to see how it functions.

Power comes in from the transmission and into the pinon gear carrier and pinon gears. The pinon gears then transfer power to the front and rear crown gears. While the speed of the front and rear axles is the same the pinons do not rotate on their axis. This guarantees that the differential housing is also rotating at the same speed.
When the front axle, for example, starts to spin faster because it lost traction the front crown will spin faster. Because the speed of the two crowns is not the same the pinon gears start to spin on their axis. The spinning causes the pinon carrier to spin faster which also causes the differential housing to spin faster. Because the differential housing has a set of clutches attaching it to the crown it will drag the slower crown along trying to speed it up. This sends power from the wheels that slip to the wheels that grip.

If you hit the parking break while driving at high speed and lets say lock up the wheels the front wheels will just roll. Because you shouldn't be hitting the gas pedal in the process the speed difference will get sent into the transmission which will be free wheeling.


Q:

Replacing sealed halogen bulb

I'm trying to replace my halogen downlighter in my bathroom. It was installed around 2009 and I'm in the UK. The downlighter is in a waterproof cover because it is directly above the shower. I can't work out how to access the bulb. I can pull the unit down from the ceiling about an inch, and I can twist the bottom of the unit about 1/8 turn, but nothing seems to come apart, and there are no visible screws. I've attached a photo. Can anyone advise on how to proceed? Thank you.

A:

It looks like Aurora series downlights:

for example, here is some catalog.
Judging from photos, their springs are above than that riveted steel, which is BTW might be another spring holding bottom cover (on the catalog many models with same or similar body but with different cover).


Q:

How to handle canvas unavailability in javascript?

I've a html page that uses HTML 5 canvas. I've used the below code for creating canvas object.
<canvas id="testCanvas" width="200" height="200">
    Canvas Not Supported
</canvas>

This works as expected and displays the text "Canvas Not Supported" in browsers like IE 8. However, there is a problem with the below javascript associated with the canvas.
<script>
    var testCanvas = document.getElementById("testCanvas");
    var testCanvasContext = testCanvas.getContext("2d");
</script>

The above code throws an error message Object doesn't support this property or method in browsers that don't support canvas. What's the correct approach to handle this in javascript?
Please do not suggest to use libraries like excanvas.

A:

TRY with the following :
<script>
   var testCanvas = document.getElementById("testCanvas");
   var testCanvasContext = window.CanvasRenderingContext2D && testCanvas.getContext("2d");
   if (testCanvasContext) {
      // do stuff
   }
</script>


Q:

Is it good to use fertilizer right after a Peace-Lily has been damaged from not being watered for several days?

I have had to cut 1/6th of the stems after it had not been watered for 11 days (don't blame me). Still, after three or four days some other leaves don't look as they used to yet. Spring is coming and seems to be a good moment to fertilize it. Should I do it as soon as possible or would it be to stressful for the plant to pass from a drought to "over-stimulation"?

A:

The leaves you've got present now probably will never return to their former state of glory because they were subjected to a period of serious drought. The most important thing is the plant still lives, so keep it well watered, though not waterlogged - and there's no reason not to start feeding it now, but only at normal rates and frequency for the product you're using.


Q:

Using jQuery ajax to make a request to a Rails API on localhost

I have a Rails API that is working with CURL, but not with $.ajax.  Here is the controller method that makes the API:
  def historic_returns
    start_date = Date.new(params[:start_year].to_i, params[:start_month].to_i)
    end_date = Date.new(params[:end_year].to_i, params[:end_month].to_i)

    @result = ShillerDataMonth.records_between_two_dates(start_date, end_date)

    respond_to do |format|
      format.json { render :json => @result }
    end
  end

Here is the CURL request that returns the expected output:
curl -H 'Content-type: application/json' -H 'Accept: application/json' -d '{"start_year":"2008","start_month":"1","end_year":"2008","end_month":"12"}' 'http://localhost:3000/historic_returns.json'

Here is the CoffeeScript that is executed when a button is clicked:
$ = jQuery

$ ->
  $('#return_calculator_button').click ->
    $.ajax ->
      url: "http://localhost:3000/historic_returns.json"
      contentType: "application/json"
      type: "GET"
      data: {"start_year":"2008","start_month":"1","end_year":"2008","end_month":"12"}
      dataType: "json"
      success: (data) ->
        alert("success #{data}")
      error: ->
        alert("failure")

When the contentType header is included in the $.ajax call I get the following error:
GET http://localhost:3000/function%20()%20%7B%20%20%20%20%20%20%20%20return%20%…0%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20%7D;%20%20%20%20%20%20%7D 400 (Bad Request)

When the contentType header is not included in the $.ajax call I get the following error:
GET http://localhost:3000/function%20()%20%7B%20%20%20%20%20%20%20%20return%20%…0%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20%7D;%20%20%20%20%20%20%7D 404 (Not Found)

EDIT:
Here is the code for the #return_calculator_button

    <button type="button" class="btn btn-primary" id="return_calculator_button">Calculate the Return</button>

EDIT 2: Mu is right, I had an extra -> in my CoffeeScript.  Here is the right code:
$ = jQuery

$ ->
  $('#return_calculator_button').click ->
    $.ajax
      url: "http://localhost:3000/historic_returns.json"
      #contentType: "application/json"
      type: "GET"
      data: {"start_year":"2008","start_month":"1","end_year":"2008","end_month":"12"}
      dataType: "json"
      success: (data) ->
        alert("success #{data}")
        console.log data
      error: ->
        alert("failure")

Thanks for the help.

A:

You're passing $.ajax a function:
$.ajax ->
# -----^^

That function happens to return the usual options object that $.ajax usually gets but that's incidental. The result is that $.ajax thinks you're using the $.ajax(url, [settings]) form rather than the usual $.ajax([settings]) form. So $.ajax thinks that your function is a URL and that mess in your logs is the result of URL encoding a stringified function.
Drop the ->:
$.ajax
  url: "http://localhost:3000/historic_returns.json"
  # as you have now...


Q:

Number of elements of order $11$ in any group of order $198$

This question was asked in my abstract algebra assignment which could not be discussed due to pandemic.

Question: Show that in all groups of order $198$ number of elements of order $11$ are same.

Attempt: I thought using Sylow theorems that there exists a unique Sylow subgroup of order $11$. So, the elements of order $11$ is fixed which is $10$.
Is this reasoning correct? If not kindly tell me the right reasoning.

A:

Let $P\leq G$ be the unique $11$-Sylow subgroup. Every non identity element in $P$ must have order $11$ by Lagrange's theorem, so there are $10$ such elements in $P$. But we also have to prove that these are all the elements of order $11$ in $G$.
So suppose $g\in G$ has order $11$. Then $\langle g\rangle\leq G$ is a subgroup of order $11$. Since $|G|=2\times 3^2\times 11$ it follows that $\langle g\rangle$ is an $11$-Sylow subgroup of $G$. Since there is only one such subgroup we get $\langle g\rangle=P$, and thus $g\in P$. So indeed there can't be any other elements of order $11$.


Q:

will_paginate gem not working

I'm having a problem with will_paginate that's pretty simple to express:
> Story.paginate(page: 1, per_page: 10).count
=> 20

Obviously, that number should be 10, not 20.
Am I somehow doing something wrong? Doesn't seem like there's much room for error here, but obviously something isn't right. What am I missing?

A:

You want Story.paginate(page: 1, per_page:10).size, not count. Count will actually return the total numbers of records generated by your query.


Q:

Adding new line using sed on specific pattern

I want to split "vulnid": "CVE-2018-17435 (hdf5)splitmehere" on the second space. How can I accomplish that using sed?
MY INPUT:
"vulnid": "CVE-2018-17435 (hdf5)splitmehere"
"stuff":"stuffhere(somedata)"
"vulnid": "CVE-2018-17435 (hdf5)splitmehere"
"stuff":"stuffhere"
"vulnid": "CVE-2018-17435 (hdf5)splitmehere"
"stuff":"stuffhere"

EXPECTED OUTPUT:
"vulnid": "CVE-2018-17435"
"product:" (hdf5)splitmehere"
"stuff":"stuffhere(somedata)"
"vulnid": "CVE-2018-17435"
"product:" (hdf5)splitmehere"
"stuff":"stuffhere"
"vulnid": "CVE-2018-17435"
"product:" (hdf5)splitmehere"
"stuff":"stuffhere"

I have tried is to use a variant of this expression:
sed -r 's/(*.*) (*.*) (*.*)/\1 \2 \3/'

A:

One possible solution:
$ sed 's/\("vulnid":\) \(.*\) \(.*\)"/\1 \2"\n"product": "\3"/' file
"vulnid": "CVE-2018-17435"
"product": "(hdf5)splitmehere"
"stuff":"stuffhere(somedata)"
"vulnid": "CVE-2018-17435"
"product": "(hdf5)splitmehere"
"stuff":"stuffhere"
"vulnid": "CVE-2018-17435"
"product": "(hdf5)splitmehere"
"stuff":"stuffhere"


Q:

Provable ROI for call center rest periods?

Think you can help make life better for a nation of call center workers?
At a large insurance company, I used to work in the call center for both Auto Claims and then Homeowner Claims, before I was promoted on to other things.  It's a complicated and stressful position, where customers are already upset because they have just gotten in a car accident or their house just burned down.
Call volume varies, but tends to be constant during many busy periods. As soon as you're done with one call, sometimes there's a lull, but usually another call is waiting.
The problem is that this leads to people taking a breather during "After Call Work," purposefully inflating their call time in order to catch a break from the stressful calls.
A potential solution, I've always wondered, is to pre-program an automatic break of no calls for X minutes after Y calls. (e.g. a 1 minute break after every 3 calls.)
My question is, would there be any scientific basis that could help justify a Return On Investment? Is a rest period worth the drain on phone coverage?  Or is it more beneficial to leave it up to the workers, to sacrifice their Average Handling Time at will to decompress at their own pace?

A:

This is the paper you would want to read on this topic. The paper empirically compares four modes of managing interruptions. It is a great (and long) read so I'll try to summarize the bit for you:
There are thus four modes of managing interruptions:

Immediate interruptions. There is no management whatsoever. As soon there is a distracting stimulus/task, it has to be attended to. In your case, you could think of being in a conversation with one costumer and immediately being switched to another. You can already imagine this is not a very good one.
Negotiated interruptions. You can decide all by yourself whether and when to attend to the interruptions. You could choose to finish a difficult part of one task and only attend to the interrupting task when that is done.
Mediated interruptions. Some other metric decides when an interruption is deemed appropriate. A well known metric is workload, as measured by pupil dilation. To bigger you pupil is, the higher workload is. Interrupting would be best in low workload situations (Salvucci and Bogunovic,2010)). What you suggested, the cooldown time, is also a mediated system.
Planned interruptions. Interruptions only come at moments you have planned. Though this may seem nice, in many situations, such as yours, this is not possible. Even if you could plan the moments, in dynamic environments you cannot predict the best moments. You could have an incredible high workload on one day, and have nothing to do on another.

So which is best?
The results show that the best interruption management systems are a combination of negotiated and mediated management (believe me on this one, I do not want to discuss 20 pages of results here haha). Mediated management systems will determine the best moments of interruptions which is incredibly useful. However, if workload is very high for a longer period of time, the callers may be on hold for too long.
The negotiated management of interruptions allows people to work as hard as they can/want. Some people perform better under pressure than others and may choose to wait for a shorter period of time. The downside, however, is the fact that people are bad at this. Some people stress themselves out and never wait (Asking for reference here) and some people wait to long and may get distracted by other things (Katidioti et al.,2014).
A combination would thus be best. Mediate the interruptions, but allow the employees to continue working when they want to. In you case, you could have a short mandatory pause duration and a suggested longer pause duration (or conversely, an maximum pause duration). You could then determine the duration of the pause based on the length of the last call(s) for instance.
I hope this answers your question and if you have any questions just let me know.
EDIT: The literature I described above mainly focuses on multitasking, while your question is about sequential tasking. Nevertheless I do believe the above can be generalized to your problem. The interruptions are now in fact the breaks.
A final note, if people purposefully inflate there call time, this may be an indicator that workload is indeed too high. Talk with the people and ask what they think of the situation and what they think may be a good solution. When changing an interface/task/process, people accept the changes much more quickly if they are involved in the process (Asking for reference).
References:
Daniel C. McFarlane (2002): Comparison of Four Primary Methods for Coordinating the Interruption of People in Human–Computer Interaction
Salvucci and Bogunovic (2012): Multitasking and Monotasking: The Effects of
Mental Workload on Deferred Task Interruptions
Katidioti and Taatgen (2014): CHOICE IN MULTITASKING: How delays in the primary task turn a rational into an irrational multitasker


Q:

Mounted disk disappears after reboot

I've got a Centos 7 dedicated server with a SSD + a nvme ssd with 400gb. I followed a tutorial to mount + format (as xfs filesystem) the nvme disk so that I could setup my NoSQL databases on that drive. However every time I reboot my server the disk disappears and the mounted folder is empty again.
What commands I ran to mount the disk:
fdisk -l

Returned:

Disk /dev/nvme0n1: 400.1 GB, 400088457216 bytes, 781422768 sectors
  Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical):
  512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512
  bytes
Disk /dev/sda: 275.1 GB, 275064201216 bytes, 537234768 sectors Units =
  sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512
  bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes
  Disk label type: dos Disk identifier: 0x000b09ac
Device Boot      Start         End      Blocks   Id  System
  /dev/sda1   *        2048     2050047     1024000   83  Linux
  /dev/sda2         2050048   528844799   263397376   83  Linux
  /dev/sda3       528844800   537233407     4194304   82  Linux swap /
  Solaris

mkfs.xfs /dev/nvme0n1 -f (-f was required after the first time)
mkdir /database
mount /dev/nvme0n1 /database

Afterwards it lists the drive when I run df -h, but once I restart it also disappears from that list. What am I doing wrong?

A:

Try adding this to /etc/fstab:
/dev/nvme0n1 /database xfs defaults 0 0

That should do the trick.


Q:

Angular setValidity not working when HTML is produced in a Directive

I have dynamic html that i make in a directive, and it includes an input element with validation.
Example HTML produced with error message:
<input id="bob" class="personCheckbox" name="bob"
                   type="checkbox" value="bob"
                   ng-model="foobar"
                   validate-foo/>

Need Summary

<input type="text" name="summary-bob" id="summary-bob"/>

The tag in the page for the directive that makes the HTML:

The directive that makes the dynamic HTML, i have a watch b/c 'people' is from a promise:
app.directive('nameCheck', function($compile){

  return {
    replace : true,
    restrict: 'A',
    scope: false,
    link: function($scope, $element, $attrs) {

        $scope.$watch('people', function(newValue, oldValue) {
            var personNames= [];
            for(var i=0; i< newValue.length; i++){
                personNames.push(newValue[i].drugName);
            }

            if(personNames.length > 0) {
                replaceElement($scope, $element, $compile, personNames.sort());
            }
        });
    }
}
});

The replaceElement function:
function replaceElement($scope, $element, $compile, peopleNames){

  var html=  "\
"
            + "\
"
            + "\People";

  for(var i=0; i < peopleNames.length; i++){

    html += "\
";
    html += "<input id='" + peopleNames[i] + "' ";
    html += " class='drugCheckbox' name='" + peopleNames[i] + "' ";
    html += " type='checkbox' value='" + peopleNames[i] + "' ";
    html += " ng-model='" + peopleNames[i] + "' ";
    html += " validate-foo/>";
    html += peopleNames[i];

    html += "Need Summary";

    html += "<input type='text' ";
    html += " name='summary-" + peopleNames[i] +"' ";
    html += " id='summary-" + peopleNames[i] + "' ";
    html += "\
";

}
html += "\

";

var DOM = angular.element(html);

var $e =$compile(DOM)($scope);
$element.replaceWith($e);
}

The directive that does the validation:
app.directive('validateFoo', function(){
   return{
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attr, ctrl) {

        ctrl.$parsers.unshift(function (viewValue) {
            var id= attr.id;
            if(viewValue) {
                var val= document.getElementById('summary-' + id).value;
                if(val.length == 0) {
                    ctrl.$setValidity("summary", false);

                }
                else {
                    ctrl.$setValidity("summary", true);
                    return viewValue;
                }
            }
        });
    }

}
});

The dynamic HTML produced shows on the page like it should, but the validation does not work.
When I hard code some example HTML, and use the validator, it works fine.
I cannot figure out why validation does not work (the error message will not show) when I have the HTML produced from a directive?

A:

I had the similar issue the other day, and found solution here:

Form Validation and fields added with $compile

The trick is to firstly append newly created HTML snippet to DOM, and then compile. This way it will be propagated to parent FORM. Example:
directive = '
'+directive+'
';
// Do Not compile the element NOT beeing part of the DOM
//$(element).append($compile(directive)(scope));

// Firstly include in the DOM, then compile
var result = $(directive).appendTo(element);
$compile(result)(scope);

The fiddler before and after


Q:

Calling some functions before main in C

I'd like to do some stuffs before main function. I have multiple source files. In each file, there is some work that needs to be done before main. It was no problem in C++, but problematic with C.
In C++, this can be done by two ways:

Exploiting a constructor of a global class/struct.
Calling a function to a global variable

For example, static const int __register_dummy_ = __AddRegisterMetaInfo(...);
However, in C, either ways is impossible. Obviously, there is no constructor. So, the first option is inherently impossible.
I thought that the second option would be possible, but not compiled in C (I tested only with Visual C++. It gives C2099.). C only allows a constant to a non-automatic variable.
Is there any way to call some functions before main?

EDIT: It seems that many people just got misunderstand what I really wanted to do. Sorry for writing this question in a simplified way.
What I needed to do is implementing a sort of C++ runtime class information feature, just like MFC's approach. In this approach, I need to get some information from all source code. For example, say each source file has a definition of a class, and I'd like to see all information (e.g., class names and the parent class). The easiest way is placing a static constructor in each file, and each constructor accesses a global data structure and register its information. But, I also wanted to find a way to implement a similar thing in C. So, simply calling a pre_main_job in main can't be an answer to me.
Note that this abuse of static constructor also can be found in LLVM compiler suite. Each optimization/analysis feature is implemented as a pass. All these passes are registered via a static constructor.

A:

For a number of compiler specific solutions you can take a look at the fips_premain.c file from the OpenSSL distribution (you can view it online in a bunch of places, here for instance).
The MSVC specific part looks something like (FINGERPRINT_premain being the function to be executed before main):
# ifdef _WINDLL
  __declspec(dllexport) /* this is essentially cosmetics... */
# endif
  void FINGERPRINT_premain(void);
  static int premain_wrapper(void) { FINGERPRINT_premain(); return 0; }
# ifdef _WIN64
# pragma section(".CRT$XCU",read)
  __declspec(allocate(".CRT$XCU"))
# else
# pragma data_seg(".CRT$XCU")
# endif
  static int (*p)(void) = premain_wrapper;
  /* This results in pointer to premain to appear in .CRT segment,
   * which is traversed by Visual C run-time initialization code.
   * This applies to both Win32 and [all flavors of] Win64. */
# pragma data_seg()

A:

You might be able to use compiler specific extensions to achieve this, eg. gcc allows you to use the constructor function attribute (and the matching destructor attribute) to cause code to be run before main and after main (or exit)

A:

Assuming you are not mixing C++ in with your C... (because then you could do the static constructors on your c++ class, which is maybe what you're asking!)
Crt0 is the platform-specific runtime setup traditionally called before main(). You could override that, but that's pretty deep.
Some embedded platforms provide a _pre_main() and _post_main() kind of procs. But that's nonstandard I think.
Really, your main entry point is, well, main()!
If you're in control of the Makefile, you could force main to be something else, with something like
gcc app.c -Dmain=not_really_main

And then link in your real main() to call not_really_main().

edit: one more approach: The gcc linker has a variable called ENTRY which is the first thing executed, usually crt0. Again, this is pretty heavyweight, and you'll have understand the platform pretty deeply to pull it off, but it's another place you can "subvert main".


Q:

Javaのコンストラクタ

@Component
public class Test {
    // MessageSourceインスタンス
    private static MessageSource messageSource;

    // MessageSource DIインスタンス
    @Autowired
    private MessageSource diMessageSource;

    private static Locale locale = new Locale("ja_JP");

    // 初期化
    @PostConstruct
    public void init() {
        MessageUtils.messageSource = diMessageSource;
    }

    // プロパティから文字列読み出し
    public static String getMessage(String id) {
        return messageSource.getMessage(id, null, locale);
}

こんな感じのクラスを
jp.co.TestProject(プロジェクト名).testこのパッケージ配下に置いていた場合は
初期化処理が呼ばれた後に実施されていたのですが
jp.co配下に移動させると
なぜかプロパティ文字列読み出しが先に呼ばれてしまいます。
コンストラクタが先に呼ばれるものと思っていたのですが異なるのでしょうか？

A:

パッケージ移動云々に関しては原因がよくわからないため、以下の点のみに注目して回答します。

コンストラクタが先に呼ばれるものと思っていたのですが異なるのでしょうか？
  質問を「init()が呼ばれる前に、getMessage()が呼ばれることはあり得るか？」と解釈しました。
  @PostConstructが付与されたメソッドはTestクラスがインスタンス化される際に呼ばれます。
  （＝インスタンス化されなければ呼ばれません）
  そして、質問にあるTestクラスのgetMessageメソッドはstaticメソッドです。
  staticメソッドはクラスをインスタンス化せずとも呼び出せます。

つまり、Testクラスをインスタンス化する処理よりも先に、getMessage()を呼び出す処理があるならば、先にgetMessageが呼ばれることはありえます。