text:
Q: What does Computer-in-the-loop or CIL mean related to embedded systems Im trying to learn more about embedded systems. During some of my research I have come across references to CIL or HWIL (apparently Computer-In-Loop or Hardware-In-Loop). I have not found much of an explanation in terms of CIL. Could someone elaborate a bit more on what this typically references? Is it possibly related to testing scenarios in a simulation environment?

A: These are terms I have never used before because I was never in the 'merican military which use 3 and 4 letter abbreviations like crazy.  But basically you start with precise parameters and values for every source of error on every interface and then validate the design on those parameters.
e.g.

Monte Carlo runsets using known CIL/HWIL interface errors, such as scale factor, bias and noise, are used to create minimum-maximum boundary value plots.

Although I have worked for and with many American Corporations, the common terms we used are: Design Specs; DVT plan, PVT plan, HALT, HASS and Tolerance Stackup.

*

*DVT = Design Verification ( or Validation) Test plan (& results) that verfies EVERY spec and in my case, test to failure or margin to failure. Uses every Design Spec.

*PVT= Production or Process Verification Test  Uses DVT results to fine tune for production tolerance verification and ALL design Specs.

*HALT= Highly Accelerated Life Testing ( like shock and vibe with Temp stress while running voltage margins on supply with crystal tolerance errors , then increase until failure occurs)

*HASS = Highly Accelerated Stress Screening ( like above but not to stressed to failure mode) and used for quality screening and burnin.

*For complex process with many e.g. 10 variables such as pre-flux and wave-soldering, Taguchi Method is used.

*For embedded code work, this means doing worst case input and output test vectors to ensure all faults are detected, reported or corrected. and every Function is validated.  Design Specs are a MUST for HIPO design specs. Heirarchical Input Process Output. ( an IBM acronym)  For complex IO processes, TAguchi Method can be used to reduce number of experiments to determine process sensitivity of each variable.

A: When I have hear of CIL used in the context of embedded programming, it usually means automated testing done on a mock system, rather than simulation.
One way to test an embedded microcontroller would be run in a simulator, wither by mocking the IO routines or using logs generated by the simulator.  So your test is "under stimulus X, data Y needs to be sent to peripheral Z within t clock cycles."  This is nice if you can do it because it can be run completely in software.  This makes it easy to automate with a build system and do lots and lots of runs.  It also may be easier to inject faults or do internal inspection like monitor state machine transitions.
This approach has some limitations as well.  First, it is simply difficult to do.  Embedded systems are designed to "talk to the world" constantly, and generating a simulation environment that captures that sufficiently well can be difficult.  Second, the tests don't necessarily reflect the true constraints -- lets say that peripheral Z above is some SPI or CAN bus chip.  What you actually care about is that the peripheral does what it is supposed to.  If your test doesn't capture the timing requirements of that peripheral, then your test won't detect that type of error.
So a HWIL test would mean that when you build the program, you flash it to a "test" platform, then perform the tests on real hardware, and e.g., log the results with a logic analyzer or oscilloscope.  If your test is that "if the accelerometer goes above some value, fire the airbag", then you are actually testing the pulse that would go to the airbag inflater, rather than simply that the correct IO routine gets called on the microprocessor.

A: While there are probably official definitions for the terms, the line between CIL and HWIL often vary from group to group.  Ask your customer for clarification as to what they generally mean.
As I am lead to understand it, CIL means you have the actual computer in the loop, meaning the actual CPU and other data processing chips.  You then exercise the software using simulated inputs and outputs.
As I am lead to understand it, HWIL means you have not only the actual computer, but you also have other hardware devices such as sensors or actuators involved.  HWIL testing lets you shake down errors which may arise from the sensors and actuators not behaving exactly as they did in simulation. (because we all know that every hardware product behaves exactly as simulated)
As an example, if you had an embedded solution which was a motion detector using an IR camera, a CIL setup might generate simulated imagery and pipe it into the CPU as a stream of data. A HWIL setup testing the same product might generate simulated imagery, project it onto a screen in front of a real IR camera, and attach the IR camera to the CPU.


text:
Q: How to restrict public access to a webapplication? I have created a web application with Spring framework in which users can login/register and other. The client wants to upload the application to a hosting provider so that he can access it.
The problem is that the client doesn't want to be public. He wants to access the URL, prompts him for an user and a password and after that to be able create accounts to the application, login and other stuff.
Any idea how to restrict public access to the application without changing the existing Spring Security authentication mechanism?

A: You can make some additional authorization. For nginx there is http://nginx.org/en/docs/http/ngx_http_auth_basic_module.html where you specify login and password to whole site and then proxy pass it to your spring server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Improve speed of GCP SQL Failover I've been trying out GCPs SQL high availability options. Is there a way to improve the fail over speed?
Attempting manual failovers through the UI takes literally over 5 minutes where mysql is completely unavailable.
I am using the smallest second generation 5.7 instances possible currently with no traffic hitting it.
It looks like it's actually stopping and starting instances. I'm having trouble seeing how this is an option for "HA" meaning minimal downtime.

A: There isn't anything you can do to improve the failover time, but you can add a read replica to have read access to your data while your instance is recovering.
If you aren't locked down to MySQL, you should also try the Postgres version of Cloud SQL - it uses a faster method for recovery and from my personal experience is generally down for ~30-60 seconds. Each version has it's own page on HA, which talks about how they work: MySQL, Postgres

A: Unfortunately you are at the mercy of the managed service provider there. GCPs managed database offering isn't that great, they lag quite far behind the others, they want to steer you onto BigTable, BigQuery and Cloud Spanner. If you are committed to GCP and have a hard requirement for HA then your best option is probably Spanner. – Gaius


text:
Q: Add a line in between two lines in a file from bash I have file named user.rb as like:
class User < ApplicationRecord
end

I want to add a new line and after adding line it will look :
class User < ApplicationRecord
  include Company
end

But I want to add this additional line from bash script or terminal.
 I tried it with this bash code:
sed -i '' 's/end/include Company\n\end/' app/models/user.rb

But it does not return new line after adding line.
Please help me.

A: With sed, append (a) the desired portion after match (here i am matching < ApplicationRecord at the end of the line):
sed '/<[[:blank:]]*ApplicationRecord$/a\    include Company' file.rb

To edit the file in-place with original one backed up with a .bak extension:
sed -i.bak '/<[[:blank:]]*ApplicationRecord$/a\    include Company' file.rb

Without any backup:
sed -i '' '/<[[:blank:]]*ApplicationRecord$/a\    include Company' file.rb

Example:
$ cat file.rb
class User < ApplicationRecord
end

$ sed '/<[[:blank:]]*ApplicationRecord$/a\    include Company' file.rb
class User < ApplicationRecord
    include Company
end

A: On OSX you can use this sed command:
sed -i.bak '/ApplicationRecord$/,/^end$/{/end$/i\
include Company
}' file


text:
Q: no font could be found for family "CM Roman" error I am plotting rolling correlations using chart.RollingCorrelation from PerformanceAnalytics package. I want to use "CM Roman" font for the title of the plot as it looks the same like latex's default font. The following code is to reproduce the error:
library("extrafont")
library("fontcm")
font_install("fontcm")
loadfonts()

set.seed(2)
x<-ts(rnorm(100), start=c(1,1900))
y<-ts(rnorm(100), start=c(1,1900))
chart.RollingCorrelation(x,y,width=12, ylab="")
title(main= "x and y", family="CM Roman")

I checked that "CM Roman" font is registered by fonts(). However, it throws to me the following error:
Warning messages:
1: In title(main = "x and y", family = "CM Roman") :
  no font could be found for family "CM Roman"
2: In title(main = "x and y", family = "CM Roman") :
  no font could be found for family "CM Roman"
3: In title(main = "x and y", family = "CM Roman") :
  no font could be found for family "CM Roman"

Any thought why it gives me that error?


text:
Q: Замена позиций таблицы sql Формулировка задания: Поменять местами цвета самой тяжелой и самой легкой детали. Если таких цветов несколько, то выбрать первый по алфавиту.
Таблица p:
|n_det|cvet    |ves|
___________________
|  P1 |Красный |12 |
|  P5 |Синий   |12 |
|  P6 |Красный |19 |
___________________

Если написать select запрос, вопросов не возникает, выборка делается верная:
select
(CASE WHEN p.ves=  (select max(ves)
                      from p p1
       THEN (select p2.cvet cvet1
             from p p2
             order by p2.ves, cvet1
             limit 1
            )
       ELSE (select p4.cvet cvet2
             from p p4
             order by p4.ves desc, cvet2
             limit 1
            )
       END
), n_det
from p
WHERE p.ves IN (select min(ves)
                 from p p6
               )
OR p.ves = (select max(ves)
              from p p7
           )

Стоит использовать update, вместо select, результат начинает выдаваться рандомный:
update p set cvet =
(CASE WHEN p.ves=  (select max(ves)
                      from p p1
                   )
      THEN (select p2.cvet cvet1
            from p p2
            order by p2.ves, cvet1
            limit 1
           )
      ELSE (select p4.cvet cvet2
            from p p4
            order by p4.ves desc, cvet2
            limit 1
           )
END)
WHERE p.ves IN (select min(ves)
                  from p p6
               )
OR p.ves = (select max(ves)
              from p p7
           )


text:
Q: Guardar coordendas XY en una lista por filas Quiero guardar una serie de valores en una lista (coordenadas XY de diferentes puntos). Yo se obtener los puntos e incluso guardarlos en una lista, el problema es que se me guardan con el siguiente formato:
COORDS : (175, 303, 177, 335, 182, 368)

Y yo querría algo visualmente así:
COORDS :(175, 303,
         177, 335,
         182, 368)

Y es que así cada fila representa a las coordenadas X (primera columna) e Y (segunda columna) de mis puntos previamente obtenido. A continuación muestro mi último intento:
puntos = (1,2,3)
coords = ()
for punto in puntos:
    coords = coords + (landmarks.part(punto).x, landmarks.part(punto).y)

print('COORDS',':', coords)

¿Cómo debería escribirlo para conseguir mi objetivo? Mi idea no es modficar el print, si no la tupla, si no me equivoco sería pasarla a dos dimensiones.
¡Salud y gracias!

A: NEA, como no incluiste los import de tu código, no pude probarlo, pero podrías cambiar la variable coords de tupla a lista, y anexar a ella, con append, una tupla con las  coordenadas que quieres:
puntos = (1,2,3)
coords = []
for punto in puntos:
    coords.append((landmarks.part(punto).x, landmarks.part(punto).y))

print('COORDS',':', coords)

A: Este print te puede alinear tus coordenadas
print('COORDS:({0},{1},\n{2:>11},{3},\n{4:>11},{5})'.format(*COORDS))

Aqui hago un salto de linea "\n" cada dos números, hago una alineación de 11 espacios a la derecha ">" de estas líneas, con *COORDS se desempaca la tupla para que corresponda con los 6 elementos.
Hay muchas más variantes.
Si necesitas hacer más formateos te recomiendo esta respuesta en inglés donde exponen diferentes librerias para hacerlo más cómodo.
https://stackoverflow.com/a/26937531/8512548


text:
Q: How to add button at the end of a loop with twig UPDATE : I answer to my question with a solution who work. See below.
I created a loop that displays posts. Each two iteration a new row is created.
My loop iterate around this list of posts. The button is not considered in this array.
But my problem is that I would like to add a button in the last col.
In the options of my back office I give the possibility to show or not this button. So sometime I don't need to add a last col with this button.
Furthermore I need to add col-md-push-2 on each column on two because I use a Bootstrap grid (even on the column of the button when the button is active in the back office).

I wrote this code who work fine. But I don't know where to add my button.

        {% for post in posts %}

                Col content

            {% if buttonIsActive %}

                Button

            {% endif %}

{% if loop.index % 2 == 0 and not loop.last %}

{% endif %}
        {% endfor %}

I don't know where can I add the code for my button. I know that I actually have my button in each row :-(
Example of html I try to generate.

                Col content

                Col content

                Col content

                Col content

                Button

A: I answer to my question with a variant who work and use batch.
{% for row in posts|batch(2) %}

        {% for item in row %}

                Col content

        {% endfor %}
        {% if btn_statut == true and loop.last and posts|length is not divisible by(2) %}

                Button

        {% endif %}

{% if btn_statut == true and loop.last and posts|length is divisible by(2) %}

                Button

{% endif %}
{% endfor %}

A: In order to place the button at the right spot, inside an open row, or open a new row you could check if the count of the items inside posts is even or not. Do note, u'd need to do the test twice, once for even and once for uneven

        {% for post in posts %}

                Col content

            {% if loop.last and posts|length % 2 != 0 %}

                Button

            {% endif %}

{% if loop.index % 2 == 0 and not loop.last %}

{% endif %}
        {% endfor %}

    {% if posts|length % 2 == 0 %}

                Button

    {% endif %}

demo


text:
Q: Wordpress with mysqli My system is: freebsd 10.3 apache24 php5.6 mysql  Ver 14.14 Distrib 5.6.30
 WordPress 4.6.1
My site on WP works perfectly, but when I install extension php56-mysqli-5.6.28 (for another project), it gives me error on main page:

Invalid query: No database selected Whole query: SELECT count(*)    AS 'count' FROM wp_posts WHERE    post_type = 'dc_headfoot';

So when I disable mysqli in File /usr/local/etc/php/ext-20-mysqli.ini:
#extension=mysqli.so

My site works perfectly again. What am I doing wrong?
How do I fix this problem? I need mysqli and Wordpress at the same time.
Thank you!


text:
Q: Laravel - Homestead env shows "404 File Not Found" I've set up Laravel local envroment using Homestead.
When I accessed to "http://homestead.app/", browser showed "404 File Not Found".
[Local - homestead.yaml]
ip: "192.168.15.10"
folders:
     - map: ~/Code
       to: /home/vagrant/Code

sites:
     - map: homestead.app
       to: /home/vagrant/Laravel/public
       hhvm: true
     - map: firstapp.local
       to: /home/vagrant/firstapp/public
       hhvm: true

[Homestead]
vagrant@homestead:~$ ls
Code  firstapp  Laravel

The directory I created is built by following composer command.
composer create-project laravel/laravel firstapp --prefer-dist
composer create-project laravel/laravel Laravel dev-develop

What's the problem? If possible, could you tell me how to create Laravel project.

A: folders:
     - map: ~/Code
       to: /home/vagrant/Code

You map your code to home/vagrant/Code
But your sites: references a different folder
sites:
     - map: homestead.app
       to: /home/vagrant/Laravel/public
       hhvm: true
     - map: firstapp.local
       to: /home/vagrant/firstapp/public
       hhvm: true

Change /home/vagrant/Laravel/public and /home/vagrant/firstapp/public to
/home/vagrant/Code/Laravel/public and /home/vagrant/Code/firstapp/public


text:
Q: Webpack Unexpected token (React) may need loader - already has one So I get this error:

ERROR in ./web/index.js Module parse failed:
  C:\git\personal\blog\web\index.js Unexpected token (17:4) You may need
  an appropriate loader to handle this file type. SyntaxError:
  Unexpected token (17:4)
      at Parser.pp$4.raise (C:\git\personal\blog\node_modules\webpack\node_modules\acorn\dist\acorn.js:2221:15)
      at Parser.pp.unexpected (C:\git\personal\blog\node_modules\webpack\node_modules\acorn\dist\acorn.js:603:10)
      at Parser.pp$3.parseExprAtom (C:\git\personal\blog\node_modules\webpack\node_modules\acorn\dist\acorn.js:1822:12)
      at Parser.pp$3.parseExprSubscripts (C:\git\personal\blog\node_modules\webpack\node_modules\acorn\dist\acorn.js:1715:21)

It is referring to:
1:  import 'babel-polyfill';
2:  import React from 'react';
3:  import {render} from 'react-dom';
4:  import {Provider} from 'react-redux';
5:  import configureStore from './store/configureStore';
6:  import {Router, browserHistory} from 'react-router';
7:  import routes from './routes';
8:  import './styles/styles.css';
9:  import './css/font-awesome.min.css';
10: import es6Promise from 'es6-promise';
11:
12: es6Promise.polyfill();
13:
14: const store = configureStore();
15:
16: render(
17:    <Provider store={store}>
18:         <Router history={browserHistory} routes={routes} />
19:     </Provider>,
20:     document.getElementById('app')
21: );

Here is my package.json:
{
  "main": "index.js",
  "scripts": {
    "start": "npm-run-all --parallel open:src lint:watch test:watch",
    "open:src": "babel-node server/index.js",
    "lint": "node_modules/.bin/esw webpack.config.* web server",
    "lint:watch": "npm run lint -- --watch",
    "test": "mocha --report progress tests/testSetup.js \"tests/**/*.spec.js\"",
    "test:watch": "npm run test -- --watch"
  },
  "dependencies": {
    "aurelia-fetch-client": "^1.1.0",
    "babel-polyfill": "^6.16.0",
    "bcrypt-nodejs": "0.0.3",
    "bootstrap": "^3.3.7",
    "cookie-parser": "^1.4.3",
    "es6-promise": "^4.0.5",
    "express-session": "^1.14.2",
    "fontawesome": "^4.5.0",
    "isomorphic-fetch": "^2.2.1",
    "moment": "^2.17.0",
    "numeral": "^2.0.3",
    "react": "15.0.2",
    "react-dom": "15.0.2",
    "react-redux": "4.4.5",
    "react-router": "2.4.0",
    "react-router-redux": "4.0.4",
    "react-select2-wrapper": "^1.0.3",
    "redux": "3.5.2",
    "redux-thunk": "2.0.1",
    "toastr": "2.1.2",
    "underscore": "1.8.3"
  },
  "devDependencies": {
    "babel-cli": "^6.18.0",
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.7",
    "babel-plugin-react-display-name": "^2.0.0",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-react-hmre": "^1.1.1",
    "babel-register": "^6.18.0",
    "bluebird": "^3.4.6",
    "body-parser": "^1.15.2",
    "colors": "^1.1.2",
    "compression": "^1.6.2",
    "cross-env": "^3.1.3",
    "css-loader": "^0.25.0",
    "elasticsearch": "^12.0.1",
    "enzyme": "^2.5.1",
    "eslint": "^3.9.1",
    "eslint-plugin-import": "^2.0.1",
    "eslint-plugin-react": "^6.5.0",
    "eslint-watch": "^2.1.14",
    "eventsource-polyfill": "^0.9.6",
    "expect": "^1.20.2",
    "express": "^4.14.0",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.9.0",
    "jsdom": "^9.8.3",
    "mocha": "^3.1.2",
    "nock": "^9.0.2",
    "npm-run-all": "^3.1.1",
    "open": "0.0.5",
    "react-addons-test-utils": "^15.3.2",
    "redux-immutable-state-invariant": "^1.2.4",
    "redux-mock-store": "^1.2.1",
    "rimraf": "^2.5.4",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "^1.13.3",
    "webpack-dev-middleware": "^1.8.4",
    "webpack-hot-middleware": "^2.13.1"
  }
}

The command I use is npm start -s
webpack.config.js:
import webpack from 'webpack';
import path from 'path';

export default {
    debug: true,
    devtool: 'inline-source-map',
    noInfo: false,
    entry: {
        app: [
            'eventsource-polyfill', // hot reloading with IE
            'webpack-hot-middleware/client?reload=true', // reloads the page if hot module reloading fails
            'isomorphic-fetch',
            path.resolve(__dirname, './web/index')
        ],
        login: [
            'eventsource-polyfill', // hot reloading with IE
            'webpack-hot-middleware/client?reload=true', // reloads the page if hot module reloading fails
            'isomorphic-fetch',
            path.resolve(__dirname, './web/login')
        ]
    },
    target: 'web',
    output: {
        path: __dirname + '/dist',
        publicPath: '/',
        filename: '[name].bundle.js'
    },
    devServer: {
        contentBase: path.resolve(__dirname, './web')
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin()
    ],
    module: {
        loaders: [
            {test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
            {test: /(\.css)$/, loaders: ['style', 'css']},
            {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
            {test: /\.(woff|woff2)$/, loader: 'url?prefix=font/&limit=5000'},
            {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=100000&mimetype=application/octet-stream'},
            {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=100000&mimetype=image/svg+xml'},
            {test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
            {test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" }
        ]
    }
};

.babelrc:
{
    "presets": ["react", "es2015"],
    "env": {
        "development": {
            "presets": ["react-hmre"]
        }
    }
}

A: Nailed it:
    module: {
        loaders: [
            {test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
            {test: /(\.css)$/, loaders: ['style', 'css']},
            {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
            {test: /\.(woff|woff2)$/, loader: 'url?prefix=font/&limit=5000'},
            {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=100000&mimetype=application/octet-stream'},
            {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=100000&mimetype=image/svg+xml'},
            {test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
            {test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" }
        ]
    }
};

That first line i do path.join(__dirname, 'src')
Needed to do path.join(__dirname, 'web')


text:
Q: Why does restarting/resetting the router work? So, I'm a technology guy and sometimes I have to troubleshoot a home network, including my own. I make sure the wires are in securely and that the lights suggest there's an actual internet connection. Usually after that point I just reset the router( and possibly the cable modem) and that fixes things most of the time.
The problem is I'd like to know what sort of issue I could possibly be fixing by resetting the router.
EDIT: Just to clarify, I was speaking more about reset as in turning the router off and on. Still, any information about a hard reset(paperclip in the hole) is useful. So the more accurate term would probably be restarting
Also, personally I usually have to deal with D-Link or Linksys home routers. I generally only bother messing around with stuff if I can't make a connection to the internet at all.

A: Sometimes you may have bad hardware (I have seen a number of Linksys Wireless APs where the transmitter would just stop after a while and needed to be reset by a physical power cycle)
Sometimes a software bug will lead to the router becoming unresponsive over time (e.g a memory leak)
Usually though it is just a workaround for something that can be done another way, but it is just quicker to reboot  (I had a cable modem that would drop from time to time.  It would come back up eventually after a timeout, but it was usually quicker to power cycle it to force the renegotiation).

A: Software reloads often fix things like memory leaks and hung processes.  I'm assuming your router runs a version of Unix that just isn't quite up-to-snuff.
What kind of router do you have?  What firmware is it running?  What problems are occurring?

A: Many sorts of problems can be fixed by restarts. Not only with routers, but with computers in general. :)
Usually this is a solution when, for some reason, the operating system of the machine in question (be it router, PC, phone, or pretty much anything else) becomes unresponsive for some reason - most probably due to a bug which leads to memory leaks, which over time slow down the system.

A: When I need(ed) to reset my router, I discovered that it was almost always because it couldn't renew its IP address. I've since learned that I can just log in to the router via its web interface and click Release and Renew and it nearly always solves the problem. It saves me a trip to the computer room.

A: Every router has it's original firmware stored somewhere on it.
When you reset the router you overwrite the current firmware and config with the original one. What usually is fixing the problem is that the config is overwritten with the original one. But in some cases you have an updated router that isn't working for some reason.

A: Restarting the router empties the DNS cache inside of it.  There are times when a DNS cache contains out of date page info, and clearing it can make things work better.  Windows and Linux have commands for flushing the dns cache without a restart.  I can't say about routers.
The paper clip in hole generally causes a reset to factory condition.  This can erase configuraton information that you need to make the network functional.  For example, if your router is also a DSL modem/home gateway,  you will lose the authentication info the router uses to log you onto the internet gateway.


text:
Q: Spring Restfull Jax-RS annotation support I have following class and web.xml files.  Does spring framework supports jax-rs annotation such as @PATH, and @PUT, @Consumes...etc.
In other word can I use @PATH instead of @RequestMapping
Java:
import org.springframework.stereotype.Controller;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;

@Controller
@Path("/register")
public class RegisterServices {
    @PUT
    @Path("/create")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({"application/json"})
    public Response create(@Context HttpServletRequest requestContex,
                           @HeaderParam("Authorization") String authorization,
                           String xMsisdn, String param) {}
}

web.xml
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

A: Just put your JAX-RS (I'm using Jersey 2) annotations on a class, annotate that class with @Component to make it a Spring bean, and you have full JAX-RS support with Spring dependency injection.
So Spring hasn't reinvented the wheel by implementing JAX-RS itself, but integrates very easily with Jersey for example.
Here's a simple Spring boot example:
http://spring.io/blog/2014/11/23/bootiful-java-ee-support-in-spring-boot-1-2

A: If you want to develop the webservices using only Spring framework then Spring provides Spring MVC. Spring MVC has its own set of annotations. For e.g. "@RequestMapping". Spring MVC doesn't even adhere to the JAX-RS principles.
There are various opensource frameworks (like Jersey) which supports "JAX-RS" and can be integrated with Spring.
However, just in case you want to compare the Spring MVC with Jersey then below is the comparison. I personally support Jersey over SPring MVC as Spring MVC is not originally meant for webservices but for UI application.

*

*Same relative paths in multiple @Controllers not supported

*@ExceptionHandler is controller-centric

*Standard content negotiation can't respond with a fixed response type (SPR-6937)

*JSR 303 bean validation not applied in @Controllers (SPR-6928, scheduled for 3.1)

*Formatting responses (i.e. Date) not working using Spring formatter annotations

*You cannot return a bean from an exception handler and expect it to be automatically serialized to xml or json based on the incoming accept header.

HTH...

A: No, you cannot use javax.ws.* annotations in spring. You can use something like resteasy with spring. It is rather easy. If you need I can provide with an example. (Jersey and CXF has good JAX-RS implementations too.)
AFAIK Springsource has no idea to provide an implementation to JAX-RS. So if you want to use the features described in JAX-RS you will not get it directly from spring. But you can develop a rest web service using spring. That's a different story. A question was found on SO on that.
Update
Depending on PaulNUK's answer below, I need to clarify my answer. End of the day rest is a specification, and someone needs to implement it in first place.
Question clearly asks, whether we can replace the annotations, you cant do it, unless you add an external dependency like Jersey to your classpath. That case implementation is provided by Jersey.
Therefore you would never be able to use spring implemented JAX-RS annotation ever.


text:
Q: Can I uninstall Java ambiguos version Can I uninstall Java Update 8 131 if I also have Java Update 8 131 (64-bit)? It looks like waste of space. I'am running Windows 10 64-bit.

A: You can uninstall Java Update 8 131 32bit, if you wish. Most Java apps will happily run with 64bit.
That said, it's possible an app you have on your machine requires one of the features only provided by 32bit Java, and thus will break if you remove it.
Try it, as it's simple enough to reinstall from Java.com


text:
Q: Require selecting the tag in the form I want to require the user to select the tag.
To select from the options not for the field.
Because if the field is required, then after the tag selection, something should be written in the field.

if( !function_exists('qa_tag_template') ):
function qa_tag_template(){
    ?>

    <?php
}
endif;**strong text**


text:
Q: Exposition of the Calabi complex I am interested in a complex derived by Eugenio Calabi in his article "On compact Riemannian manifolds with constant curvature".
The complex is referenced as "Calabi complex" in various citing publications, but the article itself remains nowhere to be found, not even on the AMS sites who published it some decades ago.
Do you know a modern exposition of the Calabi complex? I am particularly interested in the (covariant) form of the operators in the complex, which also appear in linearized elasticity.

A: A modern exposition with lots of explicit formulas can be found in my article

Khavkine, Igor, The Calabi complex and Killing sheaf cohomology, J. Geom. Phys. 113, 131-169 (2017). arXiv:1409.7212 ZBL1364.53066.

Ironically, while my paper first appeared on the arXiv a few months after this question, I've only noticed it just now.


text:
Q: How to know the reason why my docker container exits? I run my Jenkins as a Docker container with the command below
docker run \
  -u root \
  --rm \
  -d \
  -p 8081:8080 \
  -p 50000:50000 \
  -v /data/jenkins-data:/var/jenkins_home \
  -v /var/run/docker.sock:/var/run/docker.sock \
  jenkinsci/blueocean

From time to time, the jenkins container will exit. I even can't find it with "docker ps -a" command, so that I can't get any logs for troubleshooting.
Is there any way I can check the reason why a docker container exits like this?

A: I think the best way to check where it exits from is first creating a yaml file out of that docker run command and then doing a docker-compose up without the -d. this will continue logging all the messages from the container until it exits and maybe will stop there(sometimes it continues to log for those containers that have a restarting problem).
Read more about the yaml files here


text:
Q: WPF Datagrid not displaying itemSource data I am passing a list as a itemsource  of datagrid but datagrid not showing any data in interface. Help me I am new to wpf.I tried many times i didnt get my output results properly.
public partial class Home : Window
{
    List<Member> members = new List<Member>();
    public Home()
    {
        InitializeComponent();
        LoadData();

        memberGrid.ItemsSource = members;
    }
    void LoadData()
    {
        Member member = new Member()
        {
            id = 1,name="raj",dob="monday",mobileno="27487228"
        };
        members.Add(member);
    }
}
public class Member
{
    public  int id;
    public   string name;
    public  string dob;
    public string mobileno;
}

A: hello please set the properties to getter setter
problem in Class
DataGrid generates columns automatically only for properties, because each column creates a binding and WPF bindings require properties. DisplayTable class declares fields.
instead of
public  int id;
try this
public class Member
{
    public int id { get; set; }
    public string name { get; set; }
    public string dob { get; set; }
    public string mobileno { get; set; }
}


text:
Q: How to figure out if there is only 100mi of course space left in the names page.. I have access to KubernetesClient object How to get the limits.cpu value from kubernetesClient object. I need to check the cpu quota before creating a new pod in kubernetes. (JAVA)
I came across Client.top.node... but I need some equivalent of
Kubectl describe quota
Basic ask is to check if there is 100mi of quota left before creating a pod


text:
Q: PHP MYSQLI Unable to delete a row of data from database i want to delete a row of data for example userid number 4 when i click on the delete button but nothing happen.It just pop out "Are you sure you want to delete '4undefine"  Can someone help?
index.php
<?php
  $connection = mysqli_connect("localhost","root","","userdatabase");
  mysqli_select_db($connection, "userdatabase");
  $sql_query="SELECT * FROM user";
  $result_set=mysqli_query($connection,$sql_query);
  if(isset($_GET['delete_id']))
  {
    $sql_query="DELETE FROM user WHERE userid=".$_GET['delete_id'];
    mysqli_query($sql_query);
    header("Location: $_SERVER[PHP_SELF]");
  }
?>

This is the confirmation

<?php
 if(mysqli_num_rows($result_set)>0)
 {
    while($row=mysqli_fetch_row($result_set))
    {
        $userid = $row[0];
        $username = $row[1];
        $password = $row[2];
        $email = $row[3];
        $workplace = $row[4];
        $role = $row[5];
        ?>

        <?php echo $userid; ?>
        <?php echo $username; ?>
        <?php echo $password; ?>
        <?php echo $email; ?>
        <?php echo $workplace; ?>
        <?php echo $role; ?>

        <a href="javascript:delete_id(<?php echo $row[0]; ?>)">

        <?php
    }
  }

A: So your first problem is that you've defined your function like this:
function delete_id(userid,username,password,email,workplace,role)

But are calling it like this:
delete_id(<?php echo $row[0]; ?>)

Is it any wonder that username is undefined? Then your syntax is incorrect on your call to mysqli_query(), as pointed out in the comments above. It takes two parameters in the procedural style you're using.
Next thing you need to worry about is what would happen if someone went to http://your.site/adminhome.php?delete_id=4%20or%201=1. I suggest you learn about preventing SQL injections ASAP.


text:
Q: mongodb - nin & regex on an array I have 2 collections, and I'm trying to get all records from Coll_A where a certain field (Field1) is not present in Coll_B.
The issue I'm running into is that this Field1 in Coll_A, which contains a string value, is padded at the end with white spaces up to a certain length, but this padding is absent in the other collection.
So, for the below query, the vals array has records that aren't padded, so when I use the db.Coll_A.find, it returns incorrect results.
vals = db.Coll_B.find({},
                      {"Field1" : 1, _id: 0})
                .map(function(a){
                      return a.Field1;
                    });
db.Coll_A.find({ "Field1": { $nin: vals }});

How can I get around this? I looked up using regex for ignoring whitespaces, but I'm not sure how that can be used here. Any assistance would be really appreciated. Thanks.

A: I would suggest to fix inconsistent data in the collection. Update all the records with trimming white space around the field.
If for some reason you can't or don't want to do it, then you can use forEach and manually do the checking
var results = [];
db.Coll_A.find({}).forEach(function(row){
   if(row.Field1.trim().indexOf(vals) === -1){
     results.push(row);
   }
});

A: You could simply, modify the return value to an array of regular expressions and use it in your $nin operator.
code:
var exp = db.Coll_B.find({}, {"Field1" : 1, _id: 0}).map(function(a){
                                 return new RegExp(a.Field1+"\\s*$");
                             });
db.coll_A.find({"Field1":{$nin:exp}});

You cannot use $regex operator inside the $nin or $in operators.


text:
Q: Why some asp.net developers encrypt ConnectionStrings?  I seen some asp.net developers encrypt ConnectionStrings that was included in separate config file. Why they did that ? I know that config files are unreadable from the client side/browser! Is it possible to access to this kind of files ?

A: They can be accessed by maintenance personnel, backup operators or others that have access to the disk without going through the website. That´s one example.

A: If you upload your web.config file with custom errors set to "off", any errors produced by your web application will display your code. This could even include lines from your config files and this could include the "ConnectionStrings" making them visible to the public.

A: To every organization the most important thing to them is their data

*

*This is done where there are multiple developers working on the same
application

*Sometimes, new developers are also enrolled in the team. Exposing each & every aspect of your database, system, login name, machine name is never a good approach

*There is chance of information leak in production, testing Q/A phase etc.

*This comes really handy when there is a code theft within an organization, atleaset your data is safe from an outside intrusion as the connection strings were encrypted

*Can you bear the risk if someone has access to your database & perform a table/schema drop or a delete all from your tables?
MSDN: How to secure connection strings when using a datasource

A: You can't rule out that the web box is compromised.
Also, you don't want the web admins to know passwords to databases.
You need to remember that config files cannot be obtained by the browser just because .config extension is in the list of restrictions in IIS metadata. It may be possible to get them from the server in other way or some misconfiguration problem may allow them to be downloaded.


text:
Q: H5 file with images in Python: Want to randomly select without replacement I have familiarized myself with the basics of H5 in python. What I would like to do now is two things:

*

*Write images (numpy arrays) into an H5 file.

*Once that is done, be able to pick out $M$ randomly.

What is meant here is the following: I would like to write a total of $N=100000$ numpy arrays (images), into one H5 file. Once that is done, then I would like to randomly select say, $M=50$ images from the H5 file at random, and read them. Then, I would like to pick another $M=50$ at random, and read them in as well, etc etc, until I have gone through all $N$ images. (Basically, sample without replacement).
Is there an elegant way to do this? I am currently experimenting with having each image be stored as a separate key-value pair, but I am not sure if this is the most elegant.
Another solution is to store the entire volume of $N$ images, and then randomly select from there, but I am not sure that is elegant either, as it requires me to read in the entire block.

A: An elegant way for sampling without replacement is computing a random permutation of the numbers 1..N (numpy.random.permutation) and then using chunks of size M from it.
Storing data in an h5py file is kind of arbitrary. You could use a single higher dimensional data set or a group containing the N two dimensional data sets. It's up to you. I would actually prefer to have the two dimensional data sets separately (gives you more flexibility) and to iterate over it using Group.iteritems.


text:
Q: iOS 7 Custom UILabel Font, text beyond the edges of the label Since iOS 7 , Arabic fonts are now supported, but when i use the:
   lbl.font=[UIFont fontWithName:@"Scheherazade" size:33];

The text reaches the edges of the UILabel and some of the words cannot be read !!
How to fix this problem?? here is describing my problem.
here is my code:
lbl  = [[UILabel alloc]initWithFrame:CGRectMake(20, 50, 280, 320)];
lbl.text = @"شِّرِ ٱلَّذِينَ ءَامَنُوا۟ وَعَمِلُوا۟ ٱلصَّٰلِحَٰتِ أَنَّ لَهُمْ جَنَّٰتٍۢ تَجْرِى مِن تَحْتِهَا ٱلْأَنْهَٰرُ ۖ كُلَّمَا رُزِقُوا۟ مِنْهَا مِن ثَمَرَةٍۢ رِّزْقًۭا ۙ قَالُوا۟ هَٰذَا ٱلَّذِى رُزِقْنَا مِن قَبْلُ ۖ وَأُتُوا۟ بِهِۦ مُتَشَٰبِهًۭا ۖ وَلَهُمْ فِيهَآ أَزْوَٰجٌۭ مُّطَهَّرَةٌۭ ۖ وَهُمْ فِيهَا خَٰلِدُونَ";
lbl.font=[UIFont fontWithName:@"Scheherazade" size:33.0];
lbl.backgroundColor = [UIColor whiteColor];
lbl.lineBreakMode = NSLineBreakByCharWrapping;
[self.view addSubview:lbl];
lbl.numberOfLines = 0;
lbl.textAlignment = NSTextAlignmentCenter;

A: I am seeing the same issue in iOS 7. I think there is a bug where NSLineBreakByCharWrapping is always treated as NSLineBreakByWordWrapping. I have submitted to Apple.

A: I was having a similar problem where my custom font was cut off on the bottom (especially in iOS 7), and I found a few answers on this post to be quite helpful where I edited the font file directly and changed the ascender and/or descender attributes.
Custom installed font not displayed correctly in UILabel
In your case there might be other attributes in that font file that you can edit to prevent it from being cut off on the left and ride sides.

A: Try setting UILabel's preferredMaxLayoutWidth to the width of its superview (optionally with a left/right padding).

A: I just changed the line break mode "NSLineBreakByWordWrapping". I think it issue occurs due to arabic text.
UILabel * lbl  = [[UILabel alloc]initWithFrame:CGRectMake(20, 50, 280, 320)];
lbl.text = @"شِّرِ ٱلَّذِينَ ءَامَنُوا۟ وَعَمِلُوا۟ ٱلصَّٰلِحَٰتِ أَنَّ لَهُمْ جَنَّٰتٍۢ تَجْرِى مِن تَحْتِهَا ٱلْأَنْهَٰرُ ۖ كُلَّمَا رُزِقُوا۟ مِنْهَا مِن ثَمَرَةٍۢ رِّزْقًۭا ۙ قَالُوا۟ هَٰذَا ٱلَّذِى رُزِقْنَا مِن قَبْلُ ۖ وَأُتُوا۟ بِهِۦ مُتَشَٰبِهًۭا ۖ وَلَهُمْ فِيهَآ أَزْوَٰجٌۭ مُّطَهَّرَةٌۭ ۖ وَهُمْ فِيهَا خَٰلِدُونَ";
lbl.font=[UIFont fontWithName:@"Scheherazade" size:33.0];
lbl.backgroundColor = [UIColor white];
lbl.lineBreakMode = NSLineBreakByWordWrapping;
[self.view addSubview:lbl];
lbl.numberOfLines = 0;
lbl.textAlignment = NSTextAlignmentCenter;

A: Find your problem actually font size was not channing with your lbl.font=[UIFont fontWithName:@"Scheherazade" size:33.0]; try to adjust your font size with this code
lbl.font= [UIFont systemFontOfSize:10];
I have updated my code and now i am able to see complete text
UILabel *lbl  = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, 280, 320)];
lbl.text = @"شِّرِ ٱلَّذِينَ ءَامَنُوا۟ وَعَمِلُوا۟ ٱلصَّٰلِحَٰتِ أَنَّ لَهُمْ جَنَّٰتٍۢ تَجْرِى مِن تَحْتِهَا ٱلْأَنْهَٰرُ ۖ كُلَّمَا رُزِقُوا۟ مِنْهَا مِن ثَمَرَةٍۢ رِّزْقًۭا ۙ قَالُوا۟ هَٰذَا ٱلَّذِى رُزِقْنَا مِن قَبْلُ ۖ وَأُتُوا۟ بِهِۦ مُتَشَٰبِهًۭا ۖ وَلَهُمْ فِيهَآ أَزْوَٰجٌۭ مُّطَهَّرَةٌۭ ۖ وَهُمْ فِيهَا خَٰلِدُونَ";
lbl.font=[UIFont fontWithName:@"Scheherazade" size:33.0];
lbl.backgroundColor = [UIColor whiteColor];
//lbl.lineBreakMode = NSLineBreakByCharWrapping;
[self.view addSubview:lbl];
lbl.numberOfLines = 0;
lbl.textAlignment = NSTextAlignmentCenter;


text:
Q: Serverless command "project" not found I want to create a large project (not a simple template) with serverless framework.
The template should be created by running the command line :
serverless project create

but i receive the error
Serverless command "project" not found

Here the docs of this command line:
https://serverless.readme.io/docs/configuring-aws
https://serverless.readme.io/docs/project-create

Do you have any idea about this issue ??
My serverless version is 1.31.0

A: To create a new service, use the following command:
# Create a new Serverless Service/Project
$ serverless create --template aws-nodejs --path my-service
# Change into the newly created directory
$ cd my-service

Your docs are for Serverless 0.5.
You'll find the correct docs at: https://serverless.com/framework/docs/
You can also have a list of available commands with:
$ serverless --help

And a list of available templates with:
$ serverless create --help

If your project has a lot of resources, you will need to split it in multiple services or use nested stacks. You will find some solutions here.


text:
Q: When Can the Dark Side Be Sensed? This could also be phrased as, "Why can Luke feel the place strong with the dark side and not one Jedi suspected Palpatine?" But I don't want to restrict it to just those two situations.
In The Phantom Menace, Yoda says, "Hard to see, the dark side is."  While they don't think the Sith could have returned without their sensing it, Jedi regularly interact with Palpatine and never suspect him of being a Sith Dark Lord.  So there's good reason to believe the dark side is hard to sense, even for a Jedi Grand Master, like Yoda.
On the Death Star, Obi-Wan knows he his facing his destiny, but there's no indication he expects it to be Vader, yet Vader knows Obi-Wan is on the Death Star.
But on Dagobah, Luke senses the place that's infused with the dark side of the force and he's a rather inexperienced Jedi in training.
Is there something special about that spot on Dagobah?  (I've already read the question and answer here about the dark place on Dagobah, but there's still no clear answer what caused it or why Luke could sense the dark side there, even with so little training.
Is it just that one spot that's easy to sense?  Or are there conditions that make the dark side easy to sense?

A: Palpatine was actively trying to hide, and I'm sure that the Sith have mastered techniques to hide themselves from the Jedi, otherwise they wouldn't last very long.  So a Sith actively hiding is probably quite difficult to sense.
The cave on Dagobah, along with other dark spots was caused in the first place by hatred so strong and powerful that it left a stain on the universe itself.  The dark Jedi who caused it may have at one point been hiding but once they leave such a stain, it's just not possible to hide.
As for Obi-Wan, I'm pretty sure he did know it was Vader on the Death Star.


text:
Q: easiest way to map ids during database refactoring i have a number of tables with a column called OrderId.  I have just done a refactoring and i want to get rid of the Order table and i have a new table called Transaction.  I want all tables that have an OrderId column to now have a TransactionId column
This is complete.   I now need to populate the transactionId column.  I have a mapping today between orderId and transactionId  so i wanted to see the quickest way i can go populate that new transactionId  column  (should i do this through code, through a SQL query, etc ??)
So i have the transationId column in the Order Table so i can do a join.
I want a query that says something like this (pseudo SQL)
update childTable CT
set transactionId = MapFromOrderId(CT.OrderId)

any suggestions?

A: I would do it in SQL code:
UPDATE MT
SET
    transaction_id = MAP.transaction_id
FROM
    My_Table MT
INNER JOIN My_Map MAP ON
    MAP.order_id = MT.order_id

Then check to make sure that every row was mapped:
SELECT
    *
FROM
    My_Table
WHERE
    transaction_id IS NULL

A: The process is usually:

*

*Make sure the database is backed up

*Addtransctionid to each child table.
Populate based on a join to the
mapping table (you did store the
mappings between orderid and
transactionid in a table?)

*Make sure you have no blank values.

*Then you create the FK for
transactions, drop the fk to the
Order table and then drop the orderid
column.

*Then move to the next table and
repeat.

*Test to make sure everything worked
properly

Definitely I'd do this in a script so it will be easy to port to prod after dev and QA testing.
On prod you need to do this while the database is in single user mode to prevent new orders from being added as the process transitions.


text:
Q: PayPal METHOD = DoDirectPayment #10759 error I am using Paypal transaction by DoDirectPayment method, I have verified my API credentials about 100 times; it's not wrong.
 Array (
        [TIMESTAMP] => 0000-00-00T00:00:00Z
        [CORRELATIONID] => 0000000000
        [ACK] => Failure
        [VERSION] => 56.0
        [BUILD] => 000000
        [L_ERRORCODE0] => 10759
        [L_SHORTMESSAGE0] => Transaction cannot be processed.
        [L_LONGMESSAGE0] => Please use a different payment card.
        [L_SEVERITYCODE0] => Error
        [AMT] => 0.50
        [CURRENCYCODE] => USD
)

Above is response what I am getting from paypal.
I am tried all cards from here: https://www.paypalobjects.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm
My Code:
$request  = 'METHOD=DoDirectPayment';
$request .= '&VERSION=56.0';
$request .= '&USER='.$paypal_user;
$request .= '&PWD='.$paypal_pass;
$request .= '&SIGNATURE='.$paypal_sign;
$request .= '&CUSTREF=' . $post_id;
$request .= '&PAYMENTACTION=Authorization';
$request .= '&AMT='.$amount;
$request .= '&EXPDATE=' . $expmonth . $expyear;
$request .= '&CVV2=' . $ccv;
$request .= '&ACCT=' . $card_number;
$request .= '&CURRENCYCODE=USD';
$request .= '&IPADDRESS=' . urlencode($_SERVER['REMOTE_ADDR']);
$request .= '&CREDITCARDTYPE=' . $cardtype; // VISA AND ALL

$curl = curl_init($apiurl);
curl_setopt($curl, CURLOPT_PORT, 443);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FORBID_REUSE, 1);
curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);

// Request to paypal
$response = curl_exec($curl);

Please let me know what I am missing here.

A: The cards provided at that URL have been used so much in the sandbox that they simply don't work anymore.  With PayFlow they do, but not with DoDirectPayment.
Instead, generate fresh numbers here when you need them.  Any number generated there will work with any security code and valid expiration date.

A: You may try create new dummy card info in step 4 within below page and try your test again.
https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1413


text:
Q: counting the unique items in a numpy array: why is scipy.stats.itemfreq so slow? I'm trying to count the unique values in a numpy array.
import numpy as np
from collections import defaultdict
import scipy.stats
import time

x = np.tile([1,2,3,4,5,6,7,8,9,10],20000)
for i in [44,22,300,403,777,1009,800]:
    x[i] = 11

def getCounts(x):
    counts = defaultdict(int)
    for item in x:
        counts[item] += 1
    return counts

flist = [getCounts, scipy.stats.itemfreq]

for f in flist:
    print f
    t1 = time.time()
    y = f(x)
    t2 = time.time()
    print y
    print '%.5f sec' % (t2-t1)

I couldn't find a builtin function at first to do this, so I wrote getCounts(); then I found scipy.stats.itemfreq so thought I would use that instead. But it's slow! Here's what I get on my PC. Why is it so slow compared to such a simple handwritten function?
<function getCounts at 0x0000000013C78438>
defaultdict(<type 'int'>, {1: 19998, 2: 20000, 3: 19999, 4: 19999, 5: 19999, 6: 20000, 7: 20000, 8: 19999, 9: 20000, 10: 19999, 11: 7})
0.04700 sec
<function itemfreq at 0x0000000013C5D208>
[[  1.00000000e+00   1.99980000e+04]
 [  2.00000000e+00   2.00000000e+04]
 [  3.00000000e+00   1.99990000e+04]
 [  4.00000000e+00   1.99990000e+04]
 [  5.00000000e+00   1.99990000e+04]
 [  6.00000000e+00   2.00000000e+04]
 [  7.00000000e+00   2.00000000e+04]
 [  8.00000000e+00   1.99990000e+04]
 [  9.00000000e+00   2.00000000e+04]
 [  1.00000000e+01   1.99990000e+04]
 [  1.10000000e+01   7.00000000e+00]]
2.04100 sec

A: First, time.time is the wrong function to use when timing, as it measures wall-clock time, not cpu time (see this question). Ideally you would use the timeit module, but time.clock is also better.
Also, it seems that you might be using an outdated version of scipy. I'm using Python 3.4 and scipy 0.14.0 and these are my timings:
x = np.tile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 20000)
for i in [44, 22, 300, 403, 777, 1009, 800]:
    x[i] = 11

%timeit getCounts(x)
# 10 loops, best of 3: 55.6 ms per loop

%timeit scipy.stats.itemfreq(x)
# 10 loops, best of 3: 20.8 ms per loop

%timeit collections.Counter(x)
# 10 loops, best of 3: 39.9 ms per loop

%timeit np.unique(x, return_counts=True)
# 100 loops, best of 3: 4.13 ms per loop

A: If you can use numpy 1.9, you can use numpy.unique with the argument return_counts=True.  I.e.
unique_items, counts = np.unique(x, return_counts=True)

In fact, itemfreq was updated to use np.unique, but scipy currently supports numpy versions back to 1.5, so it doesn't use the return_counts argument.
Here's the complete implementation of itemfreq in scipy 0.14:
def itemfreq(a):
    items, inv = np.unique(a, return_inverse=True)
    freq = np.bincount(inv)
    return np.array([items, freq]).T

A: For the lazy:
import pandas as pd
pd.Series( my_list_or_array ).nunique()

A: Thanks for the responses. I can't use numpy 1.9 yet or scipy 0.14 because of some module conflicts in my application but looks like the new scipy.stats.itemfreq is much faster:
import numpy as np
from collections import defaultdict, Counter
import scipy.stats
import time
import timeit

x = np.tile([1,2,3,4,5,6,7,8,9,10],20000)
for i in [44,22,300,403,777,1009,800]:
    x[i] = 11

def getCounts(x):
    counts = defaultdict(int)
    for item in x:
        counts[item] += 1
    return counts

def itemfreq_scipy14(x):
    '''this is how itemfreq works in 0.14:
    https://github.com/scipy/scipy/commit/7e04d6630f229693cca3522b62aa16226f174053
    '''
    items, inv = np.unique(x, return_inverse=True)
    freq = np.bincount(inv)
    return np.array([items, freq]).T

flist = [getCounts, scipy.stats.itemfreq, np.bincount, itemfreq_scipy14, Counter]

for f in flist:
    print f
    print timeit.timeit(lambda: f(x),number=3)

which yields on my PC:
<function getCounts at 0x0000000013F8EB38>
0.148138969181
<function itemfreq at 0x0000000013C5D208>
6.15385023664
<built-in function bincount>
0.00313706656675
<function itemfreq_scipy14 at 0x0000000013F8EDD8>
0.0757223407165
<class 'collections.Counter'>
0.255281199559


text:
Q: @media rule adds extra space to my page I added @media screen and (max-width: 1000px) rule to my code with modifications it would make. I wanted to make boxes stack up on width: 1000px; and I did succeed to do that, however, now when the boxes stack up, there is an extra space to the right of my webpage.
It appears that my boxes somehow conflict with one of the lines of the header style. Tried removing margins and did not pay off. I want that space removed that those boxes add.
Also, it is possible that the header does not have to do anything here and only the boxes are stretching out the website.

body {
  margin: 0;
}

.header {
  width: 100%;
  height: 100vh;
  background-color: #262626;
  display: table-cell;
  vertical-align: middle;
}

.header h1 {
  line-height: 50%;
  color: white;
  text-align: center;
  font-size: 5em;
}

.content {
  margin-top: 10%;
}

.subcontent div a {
  user-select: none;
  font-size: 30px;
  display: table-cell;
  vertical-align: middle;
  text-decoration: none;
  text-align: center;
  color: black;
  font-weight: normal;
  border: 2px solid #3B3B3B;
  font-family: "ALK Rounded Mtav Med", sans-serif;
  transition-duration: 0.3s;
}

.subcontent {
  display: flex;
  justify-content: center;
}

.subcontent div {
  display: table;
  margin: 15px;
  height: 500px;
  width: 100%;
  transition-duration: 0.15s;
}

@media screen and (max-width: 1000px) {
  .subcontent {
    display: block;
  }
  .subcontent div {
    height: 300px;
    margin-top: 15px;
    margin-bottom: 15px;
  }
}

ვისწავლოთ

იაპონური

        ანბანი

        გრამატიკა

        ლექსიკონი

        დიალოგები

A: Don't change display:flex to display:block. Instead you can simply change flex-diretion to column and make width:auto to avoid the overflow due to the margin added to the width:100%.

body {
  margin: 0;
}

.header {
  width: 100%;
  height: 100vh;
  background-color: #262626;
  display: table-cell;
  vertical-align: middle;
}

.header h1 {
  line-height: 50%;
  color: white;
  text-align: center;
  font-size: 5em;
}

.content {
  margin-top: 10%;
}

.subcontent div a {
  user-select: none;
  font-size: 30px;
  display: table-cell;
  vertical-align: middle;
  text-decoration: none;
  text-align: center;
  color: black;
  font-weight: normal;
  border: 2px solid #3B3B3B;
  font-family: "ALK Rounded Mtav Med", sans-serif;
  transition-duration: 0.3s;
}

.subcontent {
  display: flex;
  justify-content: center;
}

.subcontent div {
  display: table;
  margin: 15px;
  height: 500px;
  width: 100%;
  transition-duration: 0.15s;
}

@media screen and (max-width: 1000px) {
.subcontent {
  flex-direction:column;
}
  .subcontent div {
    height: 300px;
    width:auto;
    margin-top: 15px;
    margin-bottom: 15px;
  }
}

ვისწავლოთ

იაპონური

        ანბანი

        გრამატიკა

        ლექსიკონი

        დიალოგები

A: It's because of the margin: 15px on the .subcontent which makes a margin of 15px all around the .subcontent

body {
  margin: 0;
}

.header {
  width: 100%;
  height: 100vh;
  background-color: #262626;
  display: table-cell;
  vertical-align: middle;
}

.header h1 {
  line-height: 50%;
  color: white;
  text-align: center;
  font-size: 5em;
}

.content {
  margin-top: 10%;
}

.subcontent div a {
  user-select: none;
  font-size: 30px;
  display: table-cell;
  vertical-align: middle;
  text-decoration: none;
  text-align: center;
  color: black;
  font-weight: normal;
  border: 2px solid #3B3B3B;
  font-family: "ALK Rounded Mtav Med", sans-serif;
  transition-duration: 0.3s;
}

.subcontent {
  display: flex;
  justify-content: center;
}

.subcontent div {
  display: table;
  /* margin: 15px; This is the villain */
  height: 500px;
  width: 100%;
  transition-duration: 0.15s;
}

@media screen and (max-width: 1000px) {
  .subcontent {
    display: block;
  }
  .subcontent div {
    height: 300px;
    margin-top: 15px;
    margin-bottom: 15px;
  }
}

ვისწავლოთ

იაპონური

        ანბანი

        გრამატიკა

        ლექსიკონი

        დიალოგები

Fiddle here


text:
Q: Make a table's field in MongoDB text searchable Prerequisites:
Database is created already with the collections posts and it's Schema is as follows:
module.exports = function(mongoose){
var Schema = mongoose.Schema;

var postSchema = new Schema({
   postID:          String,
   title:           String,
   description:     String
});

mongoose.model('post', postSchema, 'posts');
postSchema.index({title: 'text'});

};

Node's router to handle via an API:
apiRouter.get('/api/searchPosts', function(req, res, next){
    postModel.find(
        { $text : { $search : req.query.text } },
        { score : { $meta: "textScore" } }
    )
    .sort({ score : { $meta : 'textScore' } })
    .exec(function(err, posts) {
        if(posts){
            res.json({
                posts       :   posts
            });
        } else {
            res.send('Post does not exist');
        }
    });
});

What I am trying to achieve:
I want to make a field in my posts table called title text searchable.
My stack:
MongoDB, NodeJS (with Mongoose), Angular
My approach:
As mentioned in the Prerequisites, I have added the line:
postSchema.index({title: 'text'});

Furthermore, I have run the below command in the terminal once the collections has been created:
db.posts.createIndex({"title":"text"})

The problem:
When I access this from the URL, it works initially but after a few weeks, it stops working (I get 'Post does not exist' without making any changes!). To get it working again, I have to delete the collections and make a fresh one and run the command:
db.posts.createIndex({"title":"text"})

It then starts working for a few weeks and so on.
What I am doing wrong? I am not seeing a trend about what happens in these few weeks. I have been stuck on this issue for a few weeks so if someone can help, it will be highly appreciated.
Thanks,
Shayan

A: In the end, the solution was as below:
var postSchema = new Schema({
  postID:          String,
  title:           { type: String, text: true },
  description:     String
});

This did the trick so far.
I will check this again and see if it breaks like it did every few weeks. Will update the post if it does.
Thanks Andrei Neagu for the logging the 'err' suggestion. Sometimes, the obvious ones just get missed


text:
Q: Query, which returns data from last week / month ORACLE SQL The query should return the last week of month. Today is 17/03/2020,
should return last week of the day 09/03/2020(monday) to day 15/03/2020 (sunday)...
so next week the same thing on day 23/03/2020(monday) return last week from day (16/03/2020) to (22/03/2020)
And return first day of last month to Last day of last month
MY DB Is Oracle

A: You can do this with next_day():
select
    next_day(sysdate - 14, 'monday') start_of_last_week,
    next_day(sysdate - 7, 'sunday') end_of_last_week
from dual

Demo on DB Fiddlde:

START_OF_LAST_WEEK | END_OF_LAST_WEEK
:----------------- | :---------------
09-MAR-20          | 15-MAR-20

If you want the start and end of last month, then:
select
    add_months(trunc(sysdate, 'mm'), -1) start_of_last_month,
    trunc(sysdate, 'mm') - 1 end_of_last_month
from dual

A: NEXT_DAY is dependent on the language your database is set to. To do it independently of any language (and without relying on any strings) you can TRUNCate the date to the start of the ISO 8601 week (using the IW format model) which will always be midnight Monday of that week:
SELECT TRUNC( sysdate, 'IW' ) - INTERVAL '7' DAY AS start_of_last_week,
       TRUNC( sysdate, 'IW' ) - INTERVAL '1' DAY AS sunday_of_last_week,
       TRUNC( sysdate, 'IW' )                    AS start_of_this_week
FROM   DUAL;

A: As a slight enhancement to @GMB's week query, you can avoid the NLS dependency by getting the day names in the current session's date language by getting those from any arbitrary fixed date that happens to be on the required day; e.g.:
alter session set nls_date_language = 'ENGLISH';

select
    to_char(date '2018-01-01', 'day') as monday,
    to_char(date '2017-12-31', 'day') as monday,
    next_day(sysdate - 14, to_char(date '2018-01-01', 'day')) start_of_last_week,
    next_day(sysdate - 7, to_char(date '2017-12-31', 'day')) end_of_last_week
from dual;

MONDAY    MONDAY    START_OF_L END_OF_LAS
--------- --------- ---------- ----------
monday    sunday    2020-03-09 2020-03-15

alter session set nls_date_language = 'FRENCH';

select
    to_char(date '2018-01-01', 'day') as monday,
    to_char(date '2017-12-31', 'day') as monday,
    next_day(sysdate - 14, to_char(date '2018-01-01', 'day')) start_of_last_week,
    next_day(sysdate - 7, to_char(date '2017-12-31', 'day')) end_of_last_week
from dual;

MONDAY   MONDAY   START_OF_L END_OF_LAS
-------- -------- ---------- ----------
lundi    dimanche 2020-03-09 2020-03-15

This avoids the possibility of getting an ORA-01846 "not a valid day of the week" error.
db<>fiddle


text:
Q: Error: The argument type 'List>' can't be assigned to the parameter type 'List>?' [enter image description here](https://i.stack.imgur.com/Oz8T2.png)I want to access list from the currincies but fail

A: Change :
List<DropDownMenuItem>

with:
List<DropDownMenuItem<String>>

in the function type.


text:
Q: Multiple inputs for .change function I've got a table in which I want to remove a tablerow each time a checkbox is triggered in the row. I've got it working for one row (only if I specifically enter the row's ID). Is there some way to have a dynamic input for the javascript function? How do I do this?
HTML (embedded ruby)
<tr class="showContainer <%= "hideTableRow#{comment.id}" %>">
  <%= check_box_tag "approved#{comment.id}", comment.id, comment.approved, data: { toggle: "hideTableRow#{comment.id}" }, class: 'comment-approve' %>
    <%= comment.username %>
    <%= comment.email %>
    <%= comment.body %>

This translates into (two entries).

  <input type="checkbox" name="approved1" id="approved1" value="1" data-toggle="hideTableRow1">
    foobar username1
    foobar email1
    foobar body1

  <input type="checkbox" name="approved3" id="approved3" value="3" data-toggle="hideTableRow3">
    foobar username3
    foobar email3
    foobar body3

My CSS:
.showContainer {
    display:block;
}

My JS:
$("#approved1").change(function () {
    $('.' + $(this).data('toggle')).toggle();
});

Obviously my JS now only applies to the first tablerow. How do I make it so that it affects both individually?
Excuse me if this is a total noob question. Learning JS is next-up, haha.
Thank you for your help!

A: You want to select the containing row, correct? Try this:
$('.approved-checkbox').change(function(e){
    $(e.target).closest('.showContainer').toggle();
});

Then give the checkboxes the class of 'approved-checkbox' or whatever name you want to use.
.closest() documentation


text:
Q: Heroku Dyno keeps crashing with error code:H10 My project uses the spring-mvc framework. I keep running into this problem where whenever i deploy the app on heroku, it crashes. The first time i deployed it (it being my own project and not the sample one provided by the tutorials given on the heroku website), it worked perfectly.
The recent major changes i made was adding security and a few controllers.
P.s. the whole app works perfectly when run on localhost.
This is the log when i deploy and run on heroku:
H:\Documents-(H-drive)\FAST\Semester-8\ICC-Project\Spring-Workspace

\SpringHotelManagementSystem>heroku logs
2018-03-12T07:18:34.762170+00:00 app[web.1]:    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
2018-03-12T07:18:34.762171+00:00 app[web.1]:    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
2018-03-12T07:18:34.762173+00:00 app[web.1]:    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4994)
2018-03-12T07:18:34.762175+00:00 app[web.1]:    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5492)
2018-03-12T07:18:34.762177+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
2018-03-12T07:18:34.762179+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
2018-03-12T07:18:34.762187+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
2018-03-12T07:18:34.762189+00:00 app[web.1]:    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2018-03-12T07:18:34.762191+00:00 app[web.1]:    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
2018-03-12T07:18:34.762193+00:00 app[web.1]:    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
2018-03-12T07:18:34.762195+00:00 app[web.1]:    at java.lang.Thread.run(Thread.java:748)
2018-03-12T07:18:34.762197+00:00 app[web.1]: Caused by: java.lang.IncompatibleClassChangeError: class org.springframework.core.type.classreading.ClassMetadataReadingVisitor has interface org.springframework.asm.ClassVisitor as super class
2018-03-12T07:18:34.762201+00:00 app[web.1]:    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
2018-03-12T07:18:34.762199+00:00 app[web.1]:    at java.lang.ClassLoader.defineClass1(Native Method)
2018-03-12T07:18:34.762202+00:00 app[web.1]:    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
2018-03-12T07:18:34.762204+00:00 app[web.1]:    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2957)
2018-03-12T07:18:34.762206+00:00 app[web.1]:    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1210)
2018-03-12T07:18:34.762212+00:00 app[web.1]:    at java.lang.ClassLoader.defineClass1(Native Method)
2018-03-12T07:18:34.762210+00:00 app[web.1]:    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
2018-03-12T07:18:34.762226+00:00 app[web.1]:    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
2018-03-12T07:18:34.762208+00:00 app[web.1]:    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1690)
2018-03-12T07:18:34.762228+00:00 app[web.1]:    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
2018-03-12T07:18:34.762230+00:00 app[web.1]:    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2957)
2018-03-12T07:18:34.762232+00:00 app[web.1]:    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1210)
2018-03-12T07:18:34.762234+00:00 app[web.1]:    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1690)
2018-03-12T07:18:34.762235+00:00 app[web.1]:    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
2018-03-12T07:18:34.762237+00:00 app[web.1]:    at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:63)
2018-03-12T07:18:34.762239+00:00 app[web.1]:    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)
2018-03-12T07:18:34.762241+00:00 app[web.1]:    at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102)
2018-03-12T07:18:34.762243+00:00 app[web.1]:    at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:237)
2018-03-12T07:18:34.762245+00:00 app[web.1]:    ... 32 more
2018-03-12T07:18:34.762247+00:00 app[web.1]:
2018-03-12T07:18:34.766868+00:00 app[web.1]: Mar 12, 2018 7:18:34 AM org.apache.catalina.core.StandardContext startInternal
2018-03-12T07:18:34.766871+00:00 app[web.1]: SEVERE: Error listenerStart
2018-03-12T07:18:34.815509+00:00 app[web.1]: Mar 12, 2018 7:18:34 AM org.apache.catalina.core.StandardContext startInternal
2018-03-12T07:18:34.815513+00:00 app[web.1]: SEVERE: Context [] startup failed due to previous errors
2018-03-12T07:18:34.848500+00:00 app[web.1]: SEVERE: Context [] failed in [org.apache.catalina.core.StandardContext] lifecycle. Allowing Tomcat to shutdown.
2018-03-12T07:18:34.851967+00:00 app[web.1]: Mar 12, 2018 7:18:34 AM org.apache.catalina.core.ApplicationContext log
2018-03-12T07:18:34.851970+00:00 app[web.1]: INFO: Closing Spring root WebApplicationContext
2018-03-12T07:18:34.852147+00:00 app[web.1]: INFO : org.springframework.web.context.support.XmlWebApplicationContext - Closing Root WebApplicationContext: startup date [Mon Mar 12 07:18:33 UTC 2018]; root of context hierarchy
2018-03-12T07:18:34.859280+00:00 app[web.1]: WARN : org.springframework.web.context.support.XmlWebApplicationContext - Exception thrown from ApplicationListener handling ContextClosedEvent
2018-03-12T07:18:34.859288+00:00 app[web.1]: java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: Root WebApplicationContext: startup date [Mon Mar 12 07:18:33 UTC 2018]; root of context hierarchy
2018-03-12T07:18:34.859291+00:00 app[web.1]:    at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:337)
2018-03-12T07:18:34.859293+00:00 app[web.1]:    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:324)
2018-03-12T07:18:34.859294+00:00 app[web.1]:    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1025)
2018-03-12T07:18:34.859297+00:00 app[web.1]:    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:988)
2018-03-12T07:18:34.859298+00:00 app[web.1]:    at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:586)
2018-03-12T07:18:34.859300+00:00 app[web.1]:    at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:143)
2018-03-12T07:18:34.859302+00:00 app[web.1]:    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:5035)
2018-03-12T07:18:34.859304+00:00 app[web.1]:    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5687)
2018-03-12T07:18:34.859305+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
2018-03-12T07:18:34.859307+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
2018-03-12T07:18:34.859309+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
2018-03-12T07:18:34.859311+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
2018-03-12T07:18:34.859313+00:00 app[web.1]:    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2018-03-12T07:18:34.859315+00:00 app[web.1]:    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
2018-03-12T07:18:34.859316+00:00 app[web.1]:    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
2018-03-12T07:18:34.859319+00:00 app[web.1]:    at java.lang.Thread.run(Thread.java:748)
2018-03-12T07:18:34.862763+00:00 app[web.1]: WARN : org.springframework.web.context.support.XmlWebApplicationContext - Exception thrown from LifecycleProcessor on context close
2018-03-12T07:18:34.862765+00:00 app[web.1]: java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: Root WebApplicationContext: startup date [Mon Mar 12 07:18:33 UTC 2018]; root of context hierarchy
2018-03-12T07:18:34.862767+00:00 app[web.1]:    at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:350)
2018-03-12T07:18:34.862769+00:00 app[web.1]:    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1033)
2018-03-12T07:18:34.862771+00:00 app[web.1]:    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:988)
2018-03-12T07:18:34.862773+00:00 app[web.1]:    at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:586)
2018-03-12T07:18:34.862775+00:00 app[web.1]:    at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:143)
2018-03-12T07:18:34.862776+00:00 app[web.1]:    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:5035)
2018-03-12T07:18:34.862778+00:00 app[web.1]:    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5687)
2018-03-12T07:18:34.862780+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
2018-03-12T07:18:34.862782+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
2018-03-12T07:18:34.862783+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
2018-03-12T07:18:34.862785+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
2018-03-12T07:18:34.862787+00:00 app[web.1]:    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2018-03-12T07:18:34.862789+00:00 app[web.1]:    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
2018-03-12T07:18:34.862791+00:00 app[web.1]:    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
2018-03-12T07:18:34.862792+00:00 app[web.1]:    at java.lang.Thread.run(Thread.java:748)
2018-03-12T07:18:34.872554+00:00 app[web.1]: Mar 12, 2018 7:18:34 AM org.apache.catalina.core.StandardContext listenerStop
2018-03-12T07:18:34.872558+00:00 app[web.1]: SEVERE: Exception sending context destroyed event to listener instance of class org.springframework.web.context.ContextLoaderListener
2018-03-12T07:18:34.872566+00:00 app[web.1]: java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext
2018-03-12T07:18:34.872571+00:00 app[web.1]:    at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1066)
2018-03-12T07:18:34.872572+00:00 app[web.1]:    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1040)
2018-03-12T07:18:34.872569+00:00 app[web.1]:    at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:172)
2018-03-12T07:18:34.872574+00:00 app[web.1]:    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:988)
2018-03-12T07:18:34.872576+00:00 app[web.1]:    at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:586)
2018-03-12T07:18:34.872577+00:00 app[web.1]:    at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:143)
2018-03-12T07:18:34.872579+00:00 app[web.1]:    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:5035)
2018-03-12T07:18:34.872581+00:00 app[web.1]:    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5687)
2018-03-12T07:18:34.872583+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
2018-03-12T07:18:34.872585+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
2018-03-12T07:18:34.872586+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
2018-03-12T07:18:34.872588+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
2018-03-12T07:18:34.872590+00:00 app[web.1]:    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2018-03-12T07:18:34.872592+00:00 app[web.1]:    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
2018-03-12T07:18:34.872594+00:00 app[web.1]:    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
2018-03-12T07:18:34.872596+00:00 app[web.1]:    at java.lang.Thread.run(Thread.java:748)
2018-03-12T07:18:34.872598+00:00 app[web.1]:
2018-03-12T07:18:34.958364+00:00 app[web.1]: Mar 12, 2018 7:18:34 AM org.apache.coyote.AbstractProtocol start
2018-03-12T07:18:34.958368+00:00 app[web.1]: INFO: Starting ProtocolHandler ["http-nio-34226"]
2018-03-12T07:18:35.009594+00:00 app[web.1]: INFO: Pausing ProtocolHandler ["http-nio-34226"]
2018-03-12T07:18:35.009587+00:00 app[web.1]: Mar 12, 2018 7:18:35 AM org.apache.coyote.AbstractProtocol pause
2018-03-12T07:18:36.206708+00:00 heroku[web.1]: Process exited with status 0
2018-03-12T07:18:36.233993+00:00 heroku[web.1]: State changed from up to crashed

this is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.icc</groupId>
    <artifactId>springhms</artifactId>
    <name>SpringHotelManagementSystem</name>
    <packaging>war</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>
    <properties>
        <java-version>1.6</java-version>
        <org.springframework-version>3.1.1.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
    </properties>
    <dependencies>
        <!-- AWS SDK -->
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.11.289</version>
            <scope>compile</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>3.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>3.2.3.RELEASE</version>
        </dependency>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                 </exclusion>
                 <exclusion>
                    <groupId>spring-asm</groupId>
                    <artifactId>spring-asm</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                 <exclusion>
                    <groupId>spring-asm</groupId>
                    <artifactId>spring-asm</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>

        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>

        <!-- Logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>

        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>

        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.3</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals><goal>copy</goal></goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>com.github.jsimone</groupId>
                                <artifactId>webapp-runner</artifactId>
                                <version>7.0.57.2</version>
                                <destFileName>webapp-runner.jar</destFileName>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        </plugins>
    </build>
</project>

This is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml,/WEB-INF/spring-security.xml</param-value>

    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

Here is my spring-secruity.xml:
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http auto-config="true">
        <intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
        <intercept-url pattern="/client/**" access="ROLE_CLIENT" />

        <form-login
            login-page='/login.jsp'

            authentication-failure-url="/login.jsp" />
    </http>

    <authentication-manager>
      <authentication-provider>
        <user-service>
        <user name="admin1" password="123123" authorities="ROLE_ADMIN" />
        </user-service>
      </authentication-provider>
    </authentication-manager>

</beans:beans>

If there is anything else needed please let me know.
Any suggestion will be helpful. Thanks


text:
Q: Get only parent class data entity framework I have a few classes with child objects. When I retrieve and convert the data to JSON - for example to a class DeviceType - it returns the data from the related child entities as well. How can I avoid getting the data of the child entities without setting Ignore attribute or ProxyCreationEnabled? In some cases I need child class data as well.
See the code below: when I select data for DeviceTypes it returns Devices too. Now I'm using Select to get only the fields which I need but as the application grows it will be difficult to handle. Since I'm using dynamic type I can return it only as object.
public partial class DeviceType
{

    public DeviceType()
    {
        this.Devices = new HashSet<Devices >();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }
    public string Code { get; set; }

    public virtual ICollection<Device> Devices { get; set; }
}

public override ICollection<DeviceType> Get()
{
    return DbContext.Set<DeviceType>().ToList().Select(x => new DeviceType
    {
       Id = x.Id,
       Name =  x.Name
    }).ToList();
}

A: It is not EF that behaves like this, it is your JSON serializer (likely Newtonsoft.Json). The child data are actually not there, they are lazily loaded. The fact that this happens is actually a serious problem (not with Newtonsoft.Json but with how you consume the data). The Json serializer, unless instructed otherwise, will simply reflect over your class, find all its properties (including collections), traverse them and serialize everything it finds into JSON. So, even if the object you are working with actually contains the collection as a lazy collection which is loaded when first accessed, the JSON serializer does see it and will include it.
The reasoning of why it is a problem is detailed here, please read it.
The way to solve the problem, in a few words, detailed in the link above: don't send your DB entities. Besides being a possible source of Select N+1 problems it is also an enormous security vulnerability. Use viewmodels instead and project your data into them:
public IEnumerable<ResultViewModel> GetData()
{
    return dbItemsAsQueryable.Select(item => new ResultViewModel
    {
        Id = item.Id,
        Name = item.Name,
        // other properties
    }).ToList();

}

By utilizing the backing store as an IQueryable you not only avoid Select N+1's (since the query will be translated to the appropriate Joins) but you also solve the security problem simply because what you do no select will not be there. In other words, you only expose data that you actually want to expose.


text:
Q: Collecting AngularJS and Ionic crashes The question is really easy.
Is there a web service that provide us a structure to collect all client crashes?
Our clients are developed using AngularJS and Ionic and we would like to unify the way to collect these logs.

A: I use Bugsnag for this in my Ionic apps.
Note: I'm not an affiliate or anything, just like the service.
Note2: It's free for open source and non-profit organizations.


text:
Q: What does the notation $M^{[2]}$ mean with regards to matrices? I am busy studying transitive closures of relations.
The Matrix of the relation, $M_R$ is
$$M_R = \begin{pmatrix} 1&0&1\\ 0&1&0 \\ 1&1&0 \end{pmatrix}$$
As you might know the transitive closure is given by:
$$M_R^* = M_R\vee M_R^{[2]}\vee M_R^{[3]}  $$
How can I find $M_R^{[2]}$ and $M_R^{[3]}$? It is not the same as $M_R \times M_R$ and $M_R \times M_R \times M_R$ right?

A: We find $M^{[n]}$ in the same way we would find $M^n$, only we replace addition with $\vee$ and multiplication with $\wedge$.  So, for example: we have
$$
M_R = \pmatrix{
1&0&\color{blue}1\\
\color{red} 0&
\color{red} 1&
\color{purple}0\\
1&1&\color{blue}0
}
$$
So, the entry of $M_R^{[2]}$ in the $\color{red}2$nd row and $\color{blue}3$rd column is given by
$$
(\color{red}0 \wedge \color{blue}1) \vee
(\color{red}1 \wedge \color{blue}0) \vee
(\color{red}0 \wedge \color{blue}0) = 0
$$
Overall, we compute
$$
M_R^{[2]} =
\pmatrix{
1&1&1\\
0&1&0\\
1&1&1
}
$$


text:
Q: Do I keep the money at the end of GTA V? I now have the choice to kill Trevor or Michael or do Deathwish. But the thing I wanna know is, do I still get the money from 'The Big Score' heist if I choose Deathwish?

A: I'd recommend you saving the game before the mission and replay it with the different endings. That being said yes you'll get at least 20 million dollars either way:

 In any case you get a lot of money.
 If you choose to kill either Michel or Trevor, you'll spend the end mission killing them, after that Lester will give you a call (I only killed Trevor but am assuming its the same for Michel too, but I guess his family gets the money not Frank) telling you he can't reach one or the other (depending on who you killed) and he'll transfer you (Franklin) the killed character's cut too, so you'll get 40 million dollars. If you choose Death-wish, everyone lives, everyone gets 20 Million and you kill some other dudes instead.

One thing to note though:

 If you choose to kill one or the other, they are obviously dead after the mission, and are unplayable, you simply can't switch to them.

So yeah, that's that.

A: When you kill Trevor he gives Franklin and Michael more money, but if you kill Michael, Lester gives it to his family, so the best options are to, "kill Trevor" or "Deathwish" for keeping the most money money.


text:
Q: Pass data via a pipe to a C program I want to send data through a pipe to a simple c program:
#include <stdio.h>
int main(int argc, char const *argv[])
{
char message[100000];
scanf("%s", message);
printf("%s", message);
return 0;
}

For instance, I want to print to the terminal all the data from /etc/passwd. To do so, I type:
cat /etc/passwd | ./my_c_program

But it is not working, it just prints "##".

A: One of the easiest way is to use getline(). The man page describes the function as below:

ssize_t getline(char **lineptr, size_t *n, FILE *stream);
getline()  reads  an  entire line from stream, storing the address of the buffer containing the text into *lineptr.  The buffer is null-terminated and includes the newline character, if one was found.

By the way, keep in mind this paragraph:

If *lineptr is set to NULL and *n is set 0 before the call, then getline() will allocate a buffer for storing the line.  This buffer should  be  freed  by the user program even if getline() failed.

Below a working sample.
#include <stdio.h>

int main(int argc, char* argv)
{
  char* l = NULL;
  size_t n;
  while (getline(&l,&n, stdin) != -1 )
    {
      printf("%s",l);
    }
  free(l); // don't forget to release the allocated memory
           // mmh, yes, here it's not useful since the program
           // ends.
}

This answer is inspired by this SO reply.