text:
Q: Angular2 ReferenceError: System is not defined when using webpack I get an error similar to:
Angular2 + webpack Uncaught ReferenceError: System is not defined
...or
Angular 2 with webpack - Uncaught ReferenceError: System is not defined
I am using latest npm package.json settings from:
http://angular.io/docs/ts/latest/guide/npm-packages.html
I did not find any solutions for this issue. I am using ASP.NET local IIS server. Project starts on Visual Studio Commutity 2015.
webpack.common.js:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
var ProvidePlugin = require('webpack/lib/ProvidePlugin');

module.exports = {
    devtool: 'cheap-module-source-map',
    cache: true,
    debug: true,

    entry: {
        'polyfills': './polyfills.ts',
        'vendor': './vendor.ts',
        'main': './main.ts',
    },

    plugins: [
        new webpack.optimize.OccurenceOrderPlugin(true),
        new webpack.optimize.CommonsChunkPlugin({
            name: ['main', 'vendor', 'polyfills'],
            minChunks: Infinity
        }),
        new ProvidePlugin({
            jQuery: 'jquery',
            $: 'jquery',
            jquery: 'jquery'
        })
    ],

    module: {
        loaders: [
            { test: /\.ts$/, loaders: ['awesome-typescript-loader', 'angular2-template-loader'] },
            { test: /\.css$/, loaders: ['to-string-loader', 'css-loader'] },
            { test: /\.less$/, loader: 'raw-loader!less-loader' },
            { test: /\.html$/, loader: 'raw-loader' },
            { test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/, loader: 'file?name=assets/[name].[hash].[ext]' }
        ]
    },

    output: {
        publicPath: '/',
        filename: '[name].js',
        sourceMapFilename: '[name].map',
        chunkFilename: '[id].js'
    },

    htmlLoader: {
        minimize: false
    },

    devServer: {
        contentBase: '.',
        host: 'localhost',
        potr: 44305
    },

    resolve: {
        extensions: ['', '.ts', '.js', '.css', '.less']
    },

    node: {
        global: 1,
        crypto: 'empty',
        module: 0,
        Buffer: 0,
        clearImmediate: 0,
        setImmediate: 0
    }
};

webpack.config.js:
var webpack = require('webpack');
var path = require('path');
var webpackMerge = require('webpack-merge');
var commonConfig = require('./webpack.common.js');

// Webpack Config
var webpackConfig = {

    output: {
        filename: '[name].js'
    }

};

module.exports = webpackMerge(commonConfig, webpackConfig);
tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "rootDir": ".",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },
  "exclude": [
    "node_modules"
  ],
  "awesomeTypescriptLoaderOptions": {
    "useWebpackText": true
  },
  "compileOnSave": true,
  "buildOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}

vendors.ts:
import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import '@angular/core';
import '@angular/common';
import '@angular/http';
import '@angular/router';

import 'rxjs/Rx';

import 'jquery/dist/jquery';
import 'bootstrap/dist/js/bootstrap';
import 'angular2-notifications/components.js';
import 'moment';
import 'eonasdan-bootstrap-datetimepicker/src/js/bootstrap-datetimepicker.js';

polyfills.ts:
import 'core-js/es6';
import 'core-js/es7/reflect';

require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');

Chrome console:
core.umd.js:3468Error: Uncaught (in promise): ReferenceError: System is not defined
    at resolvePromise (https://localhost:44305/polyfills.js:7687:32)
    at https://localhost:44305/polyfills.js:7664:14
    at ZoneDelegate.invoke (https://localhost:44305/polyfills.js:7461:29)
    at Object.onInvoke (https://localhost:44305/vendor.js:6786:42)
    at ZoneDelegate.invoke (https://localhost:44305/polyfills.js:7460:35)
    at Zone.run (https://localhost:44305/polyfills.js:7354:44)
    at https://localhost:44305/polyfills.js:7720:58
    at ZoneDelegate.invokeTask (https://localhost:44305/polyfills.js:7494:38)
    at Object.onInvokeTask (https://localhost:44305/vendor.js:6777:42)
    at ZoneDelegate.invokeTask (https://localhost:44305/polyfills.js:7493:43)

A: Like you, I followed the Angular 2 guide I expected my application to build and run successfully with Webpack instead of SystemJS. Yeah, right! For me, it turned out to be caused by lazy loaded modules.
If you specify 'loadChildren' in any of your route definitions, Angular 2 defaults to using the SystemJS module loader to retrieve the module. Unless you provide another loader (see https://angular.io/docs/ts/latest/guide/router.html#!#asynchronous-routing)
Solution: Install a lazy loader for Webpack

*

*Install npm package 'angular2-router-loader' as a dev. dependency

*Add 'angular2-router-loader' to the TypeScript loaders in webpack config

*You may have to specify paths in 'loadChildren' with a leading './' (opposed to absolute or 'implicitly relative')

*Build, run and jump with joy when it finally works

Source: https://medium.com/@daviddentoom/angular-2-lazy-loading-with-webpack-d25fe71c29c1#.lmd8lnkos


text:
Q: Cannot call the first element of a JSON object I'm trying to access the first object from data[]. Then, grab the keys using Object.keys() but it gives me this error:

"TypeError: Cannot convert undefined or null to object".

I need the output to be an array of the keys.
import React, { Component } from 'react';

class CodecChart extends Component {

  constructor(props) {
    super(props);
    this.state = {
      post: [],
      isLoaded: false,

    }
  }

  componentDidMount() {
    const url = 'https://jsonplaceholder.typicode.com/users';
    fetch(url)
      .then(result => result.json())
      .then(post => {this.setState({ post: post })
      })
  }

  render() {
    const data = this.state.post;

// cannot reach the first object of data[]
    var keys = Object.keys(data[0]);

    return (

//output should be an array of the keys

{keys}

    )
  }
}

export default CodecChart;

A: The first time you try to access data[0], it's still empty:
this.state = {
  post: [],
  isLoaded: false,
}

and const data = this.state.post; means that data[0] is undefined.
it's only after the component is mounted, and the state is set correctly that data[0] is defined (or not, depending on what the API returns).

A: I found a way for it to work by adding another "then" so it can set the "keys" state right after the "posts" state was set. But I wonder if there is another way to make it more elegant. Thank you for trying to help.
constructor(props) {
    super(props);
    this.state = {
      posts: [],
      isLoaded: false,
      keys: []
    }
  }

  componentDidMount() {
    const url = 'https://jsonplaceholder.typicode.com/users';
    fetch(url)
      .then(result => result.json())
      .then(posts => {
        this.setState({ posts: posts })
      })
      .then(_ => { this.setState({ keys: Object.keys(this.state.posts[0]) }) })
  }

  render() {
    const keys = this.state.keys;

    return (

{keys}

    )
  }

redpajama_set_name: RedPajamaStackExchange


text:
Q: javax.persistence.version causes the Id of an entity to remain null in the transaction I have two entities with typical primary foreign key relationship. id in EntityA is has foreign key relationship in EntityB. I am trying to persist entity A and entity B in same transaction.
Entity A
-------------------------------
@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;

@Version
private Integer version;

Entity B
--------------------------------
@ManyToOne
@JsonBackReference
@JoinColumn(name = "id_fk")
private EntityA entityA;

@Version
private Integer version;

I am using javax.persistence.version annotation to perform the optimistic locking on version column. I have two statements
   1. entityARepository.save(entityA)
   2. EntityB entityB = generateEntityB(entityA)
   3. entityBRepository.save(entityB)

The statement number 3 fails with exception that entity A id is null and entityB can not be saved with id null of entity A. I tried to use entityManager.flush() after statement 1 but the id of entity A is not getting generated when line 3 is encountered.
How to change the code so that Id of entity A gets generated and persisted so that when entityB tries to get that primary key of entity A it is not null?

A: If anyone is having the same issue the save operation of CrudRepository of Spring Data may return entirely different instance of entity so you will have to do following.
   1. entityA = entityARepository.save(entityA)
   2. EntityB entityB = generateEntityB(entityA)
   3. entityBRepository.save(entityB)


text:
Q: when i am doing ng g compoment newone its not getting updated in app.module.ts
i am creating a new component and it mentions that it is added the new component to the module.ts but when i check my module.ts it does display the new component

 $ ng generate component newone
      create src/app/newone/newone.component.html (25 bytes)
      create src/app/newone/newone.component.spec.ts (628 bytes)
      create src/app/newone/newone.component.ts (269 bytes)
      create src/app/newone/newone.component.css (0 bytes)
      update src/app/app.module.ts (602 bytes)

this is my app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http';

    import { AppComponent } from './app.component';

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

A: try ou this steps in terminal . This might be issue in version of angular cli
npm uninstall -g angular-cli @angular/cli
npm uninstall angular-cli @angular/cli -–save-dev
npm cache clean
npm install -g @angular/cli@latest
npm install --save-dev @angular/cli@latest
let's update all the local again packages to the latest ones with this funny utility:
npm install -g npm-check-updates
ncu -u -a --packageFile package.json
rm -rf node_modules
npm install


text:
Q: AttributeError for analyzing multiple sheets in python pandas I included sheet_name=None to analyze every sheet but then I have a problem with reading columns.
import pandas

df = pd.read_excel('file.xlsx', sheet_name=None, index_col=[0])

df.columns = df.columns.str.split('_', expand=True)

I got this error message
    df.columns = df.columns.str.split('_', expand=True)
AttributeError: 'dict' object has no attribute 'columns'

It is working perfectly on one sheet, why won't work for multiple sheets?

A: According to Pandas doc

sheet_namestr, int, list, or None, default 0
Strings are used for sheet names. Integers are used in zero-indexed sheet positions. Lists of strings/integers are used to request multiple sheets. Specify None to get all sheets.

This means when sheet_nameis specified as None, Pandas load all your sheets as separate DataFrames and store them in a dict with sheet names as keys and the corresponding DataFrame as values.
To achieve a similar effect, you may want:
df_dict = pd.read_excel('file.xlsx', sheet_name=None, index_col=[0])
for name, df in df_dict.items():
    df.columns = df.columns.str.split('_', expand=True)

A: When you specify sheet_name as None then that returns dict, that is why you are getting that 'dict' object has no attribute 'columns' but if you want to get the DataFrame then you can try this :
for key in df:
     df[key].columns = df[key].columns.str.split('_', expand=True)
     print(df[key].head())

But if you know the exact name of sheet that you want then do this :
df["<>"].column=df["<>"].columns.str.split('_', expand=True)

For more information about all these visit here

sheet_name : str, int, list, or None, default 0
Strings are used for sheet names. Integers are used in zero-indexed sheet positions. Lists of strings/integers are used to request multiple sheets. Specify None to get all sheets.
Available cases:
Defaults to 0: 1st sheet as a DataFrame
1: 2nd sheet as a DataFrame
"Sheet1": Load sheet with name "Sheet1"
[0, 1, "Sheet5"]: Load first, second and sheet named "Sheet5" as a dict of DataFrame
None: All sheets.

A: Solution:
dfs = pd.read_excel('file.xlsx', sheet_name=None, index_col=[0])

with pd.ExcelWriter('output_file.xlsx') as writer:
    for name, df in dfs.items():
        print(name)
        df.columns = df.columns.str.split('_', expand=True)


text:
Q: How do I insert into boost::unordered_set >? The following code fails to compile, but if I remove the commented line, it compiles and runs correctly. I was only intending to use boost because C++ doesn't provide a hash function for std::unordered_set<int> by default.
#include <iostream>
#include <boost/unordered_set.hpp>

int main() {
    boost::unordered_set<boost::unordered_set<int> > fam;
    boost::unordered_set<int> s;
    s.insert(5);
    s.insert(6);
    s.insert(7);
    std::cout << s.size() << std::endl;
    fam.insert(s); // this is the line causing the problem

    return 0;
}

Edit 1:
I want to be more clear than I was in the OP. First I know that the idea of the boost::unordered_set<> is that it is implemented with a hash table, rather than a BST. I know that anything that is to be a template type to the boost::unordered_set<> needs to have a hash function and equality function provided. I also know that by default the std::unordered_set<> does not have a hash function defined which is why the following code does not compile:
#include <iostream>
#include <unordered_set>

int main() {
    std::unordered_set<std::unordered_set<int> > fam;
    return 0;
}

However, I thought that boost provides hash functions for all their containers which is why I believed the following code does compile:
#include <iostream>
#include <boost/unordered_set.hpp>

int main() {
    boost::unordered_set<boost::unordered_set<int> > fam;
    return 0;
}

So now, I'm not sure why boost code just above compiles, but the code in the OP does not. Was I wrong that boost provides a hash function for all their containers? I would really like to avoid having to define a new hash function, especially when my actual intended use is to have a much more complicated data structure: boost::unordered_map<std::pair<boost::unordered_map<int, int>, boost::unordered_map<int, int> >, int>. It seems like this should be a solved problem that I shouldn't have to define myself, since IIRC python can handle sets of sets no problem.

A: An unordered_set (or _map) uses hashing, and requires a hash operator to be defined for its elements.  There is no hash operator defined for boost::unordered_set<int>, therefore it cannot put such a type of element into your set.
You may write your own hash function for this.  For example, this is a typical generic hash approach, though you may want to customize it for your particular data.  If you drop this code into your example, it should work:
namespace boost {
  std::size_t hash_value(boost::unordered_set<int> const& arg) {
    std::size_t hashCode = 1;
    for (int e : arg)
      hashCode = 31 * hashCode + hash<int>{}(e);
    return hashCode;
  }
}


text:
Q: Firebase Storage IO Exception I've been trying to download a PDF file from Firebase Storage and storing it in local storage, not external.
Exception occurring:

com.google.firebase.storage.StorageException: An unknown error occurred, please check the HTTP result code and inner exception for server response.

Code for downloading the file and storing it:
        FirebaseStorage storage = FirebaseStorage.getInstance();
        StorageReference storageRef = storage.getReferenceFromUrl(fileDetails.getFileUrl());

        File rootPath = new File(Environment.getDataDirectory(), "notesApp");
        if (!rootPath.exists()) {
            rootPath.mkdirs();
        }

        final File myFile = new File(rootPath,fileDetails.getFileName()+".pdf");

        storageRef.getFile(myFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                // Local temp file has been created
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Handle any errors
                Log.e("Download Failed: ",exception.toString());
            }
        });

Logcat for exception:
    java.io.IOException: No such file or directory
        at java.io.UnixFileSystem.createFileExclusively0(Native Method)
        at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:281)
        at java.io.File.createNewFile(File.java:1008)
        at com.google.firebase.storage.FileDownloadTask.processResponse(com.google.firebase:firebase-storage@@19.0.1:136)
        at com.google.firebase.storage.FileDownloadTask.run(com.google.firebase:firebase-storage@@19.0.1:227)
        at com.google.firebase.storage.StorageTask.lambda$getRunnable$7(com.google.firebase:firebase-storage@@19.0.1:1072)
        at com.google.firebase.storage.StorageTask$$Lambda$12.run(Unknown Source:2)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
2019-09-18 20:38:01.109 32195-32312/com.example.android.notes E/StorageException: StorageException has occurred.
    An unknown error occurred, please check the HTTP result code and inner exception for server response.
     Code: -13000 HttpResult: 200
2019-09-18 20:38:01.156 32195-32312/com.example.android.notes E/StorageException: No such file or directory
    java.io.IOException: No such file or directory
        at java.io.UnixFileSystem.createFileExclusively0(Native Method)
        at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:281)
        at java.io.File.createNewFile(File.java:1008)
        at com.google.firebase.storage.FileDownloadTask.processResponse(com.google.firebase:firebase-storage@@19.0.1:136)
        at com.google.firebase.storage.FileDownloadTask.run(com.google.firebase:firebase-storage@@19.0.1:227)
        at com.google.firebase.storage.StorageTask.lambda$getRunnable$7(com.google.firebase:firebase-storage@@19.0.1:1072)
        at com.google.firebase.storage.StorageTask$$Lambda$12.run(Unknown Source:2)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
2019-09-18 20:38:01.163 32195-32312/com.example.android.notes E/StorageException: StorageException has occurred.
    An unknown error occurred, please check the HTTP result code and inner exception for server response.
     Code: -13000 HttpResult: 200
2019-09-18 20:38:01.242 32195-32312/com.example.android.notes E/StorageException: No such file or directory
    java.io.IOException: No such file or directory
        at java.io.UnixFileSystem.createFileExclusively0(Native Method)
        at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:281)
        at java.io.File.createNewFile(File.java:1008)
        at com.google.firebase.storage.FileDownloadTask.processResponse(com.google.firebase:firebase-storage@@19.0.1:136)
        at com.google.firebase.storage.FileDownloadTask.run(com.google.firebase:firebase-storage@@19.0.1:227)
        at com.google.firebase.storage.StorageTask.lambda$getRunnable$7(com.google.firebase:firebase-storage@@19.0.1:1072)
        at com.google.firebase.storage.StorageTask$$Lambda$12.run(Unknown Source:2)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
2019-09-18 20:38:40.889 32195-32195/com.example.android.notes E/Download Failed:: com.google.firebase.storage.StorageException: An unknown error occurred, please check the HTTP result code and inner exception for server response.

Edit:
Replaced  File rootPath = new File(Environment.getDataDirectory(), "notesApp");
with
 File rootPath = new File(getBaseContext().getFilesDir(), "notesApp");
Now only error that shows is:
error getting token java.util.concurrent.ExecutionException: com.google.firebase.internal.api.FirebaseNoSignedInUserException: Please sign in before trying to get a token.


text:
Q: Prevent floated image from clearing  in ie6 I am making a WYSIWYG webpage editor: http://brokenmyriad.com/editor2.php, however I have come across a problem when trying to add image functionality.
Note: the image is not inside a contenteditable element, but is just a normal floated image.
The problem can be recreated by clicking into either the paragraph or the heading and the clicking the insert image button on the toolar (the far right button). (on the above linked page).
In standards based browsers it works as expected, and the heading and the paragraph  are both to the right of the image, however in ie6 the paragraph is under the floated image like in this picture: http://tinypic.com/view.php?pic=2mfcfo8&s=3
My simplified code structure is as follows:

Click here to edit!

Click here to edit!

What I want is for the
 element to be alongside the floated image, and under the
 element as it is in standards based browsers.
Any help would be greatly appreciated!

A: Why is the paragraph in a separate div? Wouldn't the following work:

Click here to edit!

Click here to edit!

If you must have the divs, then the second one needs to be nested

Click here to edit!

Click here to edit!

A: Your second div should be floated left:

Click here to edit!

Click here to edit!

A: It turned out that the  elements had width:100% on them, which was causing the error.


text:
Q: getting error from my local html project - cannot read property 'concat' of undefined I am making a local html file that I will use later to make article/reader mode for any website.
I am doing that by fetching the website html, converting it to dome document and run it in Readability.js

$(document).ready(function() {
  $("form").submit(function(event) {

    var parser = new DOMParser();
    var doc = parser.parseFromString($("#url").val(), 'text/html');
    window.console.log(doc)
    var article = window.Readability(doc).parse();
    window.console.log(article)

    event.preventDefault()
  });
});
<!DOCTYPE html>

  <meta charset='utf-8'>
  <title>test </title>
  <meta name='viewport' content='width=device-width, initial-scale=1'>

    <form action="">
      html: <input id="url" type="text" name="urlField" value="">

      <input type="Submit" value="Submit">
    </form>

But I am getting

cannot read property 'concat' of undefined

A: Please try with the following code:
Major change is var article = new Readability(doc).parse();
<!DOCTYPE html>

    <meta charset='utf-8'>
    <title>test </title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>

    <form action="">
    html: <input id="url" type="text" name="urlField" value="https://www.google.com/">

    <input type="button" value="Submit" id="btn-submit" >
  </form>


text:
Q: Android ADB-over-WiFi still disconnects when USB cable is cycled (?!?) I am working on a USB-based project so I'm using ADB over WiFi TCP/IP. Works perfectly, and frankly this ability to debug over a wireless connection is one of the coolest development tricks I've used in years. Really, really cool.
I'm working on the various Intents associated with USB connects and disconnects. I've found that anytime the USB cable's physical status changes - whether it's plugged in or unplugged - the ADB wireless connection is lost. I can reestablish it and resume debugging via DDMS, but by then a whole lot of CPU time has gone by. This makes debugging USB connection events basically impossible.
I cannot understand why ADB would still take action on USB events when it is connected via TCP/IP (over WiFi, no less). Is there an ADB configuration detail I'm missing? How do you tell ADB to ignore USB since it's not running over USB anyway?
Thanks!

A: I had the same issue and i think managed to solve it by "Revoke USB debugging authorizations"
I then connected over usb and allowed my PC
Then restarted adb in tcpip mode and connected to my device.
It stayed connected when I disconnected the USB cable.
Hope this helps.


text:
Q: AIC values for auto.arima I have a problem with identifying why auto.arima suggest specific coefficients. I have time series with multiple seasonalities and I am trying to forecast future values using STL+ARIMA. I have been following Hyndman's book (https://otexts.org/fpp2/complexseasonality.html). However, in all examples I've come across I see auto.arima function being used instead of specifying Arima parameters.
I've basically used mstl() function to get the remainders from Loess and then tried to estimate ARIMA parameters for these remainders. I am not sure if what I am doing is correct. I just wanted to check what auto.arima was suggesting.
auto.arima was suggesting (0,1,2) parameters:AIC= 6759.638  SSE= 4774186  p-VALUE= 0.616866 . However, majority of other models had smaller AIC values, like arima(8,0,7):AIC= 6691.219  SSE= 3820932  p-VALUE= 0.9947854. or arima(3,1,7):AIC= 6709.794  SSE= 4177168  p-VALUE= 0.9993566 .
I don't understand if what I am doing is correct and why this happens. I have checked residuals as well (Residuals from STL +  ARIMA(0,1,2)
Q* = 39.068, df = 18, p-value = 0.00279 Model df: 2.   Total lags used: 20). ( Residuals from STL +  ARIMA(3,1,7 Q* = 5.5735, df = 10, p-value = 0.8497 Model df: 10.Total lags used: 20)Any suggestions how to approach this situation ? code is below
data.hourly.msts=msts(ts.data,seasonal.periods =
c(24,168),start=c(1,1))
fixed.nValid=48
fixed.nTrain=length(ts.data)-fixed.nValid

datatrain.msts=window(data.hourly.msts,start=c(1,1),end=c(1,fixed.nTrain))
a <-  mstl(datatrain.msts)

b<-a[,5]

for(p in 1:10){
for(q in 1:10){
for(d in 1:2){
  if(p+d+q<=20){
    model<-arima(x=b, order = c((p-1),(d-1),(q-1)),optim.control = list(maxit = 2500),method="ML")
    pval<-Box.test(model$residuals, lag=log(length(model$residuals)))
    sse<-sum(model$residuals^2)
cat(p-1,d-1,q-1, 'AIC=', model$aic, ' SSE=',sse,' p-VALUE=', pval$p.value,'\n')
   }
  }
 }
}

data.hourly.stlm=stlm(data.hourly.msts,s.window="periodic",
modelfunction=Arima,order=c(8,0,7))
data.hourly.stlm.pred=forecast(data.hourly.stlm,h=48)

A: There are two default parameters to auto.arima() that are relevant here.

*

*First, auto.arima() by default limits the orders of AR and MA coefficients, as well as the amount of differencing. Here are the relevant parameters with their default values: max.p=5, max.q=5, max.d=2. There are very good reasons for this default behavior: Why does default auto.arima stop at (5,2,5)? and Order of ARMA models.

*Second, even if you were to specify higher maximum orders, auto.arima() might not find the AIC-minimal model, because it does by default not search all possible models, but proceeds in a greedy stepwise fashion (stepwise=TRUE).
You can of course both increase the maximum orders and set stepwise=FALSE. Be prepared for a long model selection and fitting process, especially if you have a long time series. (Or multiple series.)
In any case, as per above, there are good reasons not to spend too much time on higher ARIMA orders. The authors of the forecast package know what they are doing, and higher orders may well yield lower AICs, but they will typically not lead to smaller out-of-sample forecast errors. Have you assessed your more complicated models on holdout samples? I would strongly recommend you do so.


text:
Q: How to detokenize Protein Embedding Method I'm using ProtTransBertBFDEmbedder embedding to covert my sequence into embedding format.
It returns me an array (length: 1024). My purpose is how can I find the original sequence again by using this 1024-length array. So how can I detokenize/reverse it?
!pip3 install -U bio_embeddings[all] > /dev/null

from bio_embeddings.embed import ProtTransBertBFDEmbedder

embedder_bertbfd = ProtTransBertBFDEmbedder()

embedding = embedder_bertbfd.embed("YSPNNIQHFHEEHLVHFVL")
reduce_per_protein = embedder_bertbfd.reduce_per_protein(embedding)

print(reduce_per_protein)

print(reduce_per_protein.shape)

Output (1024,)

How can I get this original sequence (YSPNNIQHFHEEHLVHFVL) again by using reduce_per_protein
You can use this Original Colab to try

A: You can use BasicAnnotationExtractor() from bio_embeddings.extract module to achieve the desired result as follows:
from bio_embeddings.extract import BasicAnnotationExtractor

print(BasicAnnotationExtractor(reduced_embedding))

Also, you must notice that you need to define your custom model architecture. If not you may run into some issues with its execution.


text:
Q: need help with xampp virtual host I am using XAMPP, Apache 2.2.17. I have added virtual host but my virtual host and localhost both point to the same location. Here is my code in httpd-vhosts.conf
<VirtualHost www.domain.tld:80>
ServerName www.domain.tld
ServerAlias domain.tld *.domain.tld
DocumentRoot "C:/xampp/htdocs/workspace/testsite"
</VirtualHost>

<VirtualHost *:80>
   DocumentRoot "C:/xampp/htdocs/xampp"
   ServerAlias localhost
   ServerName localhost
</VirtualHost>

With the above code, I get testsite with www.domain.tld so that is good. But If i type localhost, it will go to testsite  as well. If I move  ahead of test site then localhost goes to localhost good and www.domain.tld goes to localhost too. I tried different setting for localhost as like
<VirtualHost *>
<VirtualHost localhost:80>

and removing *.domain.tld from domain.tld but nothing works. Am I missing something obvious?

A: My own answer: The following code fixed the problem
<VirtualHost *:80> <--- * fixed the problem, apache 2.2 doc does say it must match www.domain.tld, which caused problem for other Virtual hosts
ServerName www.domain.tld
ServerAlias domain.tld
DocumentRoot "C:/xampp/htdocs/workspace/patriot2"
</VirtualHost>

<VirtualHost *:80>
   DocumentRoot "C:/xampp/htdocs/xampp"
   ServerAlias localhost
   ServerName localhost
</VirtualHost>

A: please change your ServerName from virtualhost to a local IP address such as 127.0.0.2.
ServerName domain.tld is an example of using "domain.com" where .tld is replaced by .com for your domain.


text:
Q: Syncing sprite animation and physics in Godot In a 2D scene in Godot, I have a factory belt transporting items. The items are physics objects (with linear damping = 1 so they do not accelerate too much), the belts have an Area2D with a gravity force that transports the items. The belts have a sprite animation showing the belt moving.
I can sync the sprite animation reasonably well to the speed the items reach on the belts by adjusting the AnimatedSprite's speed scale. Any divergence looks odd visually of course, as the items will either be moving faster or slower than the belt.
I am worried that differences in FPS across devices may cause the visual correctness to break.
Should I just stop worrying? Is there a better way to implement belts moving items? I am aware that I can implement the item movement myself instead of relying on the physics engine - but this won't solve the problem of syncing with the belt animation.


text:
Q: Amazon EMR - Spark Web UI for Thrift server queries I have an EMR cluster for running Spark code using Zeppelin and occasionally I run SQL queries using the JDBC interface provided by Spark thrift server. The queries are running fine and I am able to see the results but I am not able to see the Spark UI for the queries executed using Spark thrift server.
When I use Zeppelin, I can see the application in YARN resource manager and Spark History server. But the queries I run using the thrift server don't show up anywhere. It is understandable that they don't show up in YARN resource manager but it is surprising to not see them in Spark HistoryServer as well. Where can I see the details of the SQL queries executed using Spark thrift server in EMR?


text:
Q: Center 3 Column Grid Inside 100% Width Div I have a 3 column grid, which is sitting inside a 100% container div. But as of now it is just being pulled all the way to the left side of the page. I want the three columns to be div to be centered inside the container. Here is a screenshot of the design that I'm trying to code:  To fix the margin issue between each grid box, I used the technique found here (Scroll down to the last section "Roll your own...")
HTML:

CSS:
.featured-properties {
  width: 100%;
}

  .properties {
    margin: -79px;
    overflow: hidden;
    clear: both;
    width: 1047px;
  }

    .property {
      float: left;
      margin-left: 79px;
    }

A: No need explanation, see the CSS below and demo (responsive!).
DEMO: http://jsfiddle.net/0m5p2818/
.properties {
    text-align: center;
    max-width: 720px; /* (200+(20x2))x3 */
    font-size: 0; /* fix for white space bug */
    margin-left: auto;
    margin-right: auto;
}

.property {
    display: inline-block;
    margin: 20px;
    font-size: 16px;
}

A: I'm not really sure if I understood your question, but I think CSS 3 Flexbox can help you to achieve what I think you need.
Take a look at it here and see if it works for you: https://css-tricks.com/snippets/css/a-guide-to-flexbox/


text:
Q: Как добавить изображение в Xamarin? В общем... Нужно добавить изображение в Xamarin.Forms через XAML. Но есть проблема. Я уже указал несколько путей и всё тщетно. Зато в Xamarin.Forms Previewer все видно, и все показывается.
<Image Source="Resource/drawable/icon.png"
        VerticalOptions="CenterAndExpand"
        HorizontalOptions="Center"
        />

Собственно вопрос: по какому пути обращаться?

A: Вам не нужно указывать полный путь до файла.
По умолчанию, система уже смотрит туда.
Нужно указать просто:
Source="{icon.png}"


text:
Q: Java Content Assist / Refactoring with External Build tools We currently build our Android (Java) projects using the built-in Eclipse build tools. Then we have a separate ANT build script for automated building, unit testing, etc.
I would like to switch to using the ANT script inside Eclipse as well. What I can't figure out is how Eclipse content assist and refactoring tools will interact with such an arrangement.
Can I continue to use the Eclipse refactoring / content assist tools, while never using the Eclipse build button? We don't currently use the "Automatic Building" mode for Eclipse, so I don't care about that.
On a related note, will a tool like ANT be able to build just as little as Eclipse does?
Or does Eclipse do something a lot more intelligent that modification-date checking to limit how much it builds?

A: You can absolutely do it. With Ant it's easy - just do Window->Show View->Ant and then drag your build.xml to it. After that you can just double-click on the target which will kick the Ant build. Of course you can still use Eclipse for anything else


text:
Q: stderr changes behavior of python's Popen when closing the script I was using this script on python2 to launch an application and then immediately exit the python script without waiting for the child process to end. This was my code:
kwargs = {}
if platform.system() == 'Windows':
    # from msdn [1]
    CREATE_NEW_PROCESS_GROUP = 0x00000200  # note: could get it from subprocess
    DETACHED_PROCESS = 0x00000008          # 0x8 | 0x200 == 0x208
    kwargs.update(creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
    kwargs.update(stderr=subprocess.PIPE)
elif sys.version_info < (3, 2):  # assume posix
    kwargs.update(preexec_fn=os.setsid)
else:  # Python 3.2+ and Unix
    kwargs.update(start_new_session=True)

subprocess.Popen([APP], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,**kwargs)

It works OK on python 2.7, but it doesn't start the expected 'APP' on python 3.7 without changes.
In order to make it work in python3, I found two independent workarounds:

*

*Change stderr to this: stderr=subprocess.DEVNULL
or

*Add a time.sleep(0.1) call after the Popen (before closing the script).

I assume this is not actually related to python, but to some event that needs to happen after the process gets opened before the python script can safely exit?
Any hints? I'd really like to know why it happens. Right now I simply added the sleep call.
Thank you


text:
Q: How do I find the number of ordered group possible as in a sublist from a super list in python? Suppose I have a smaller list A = [1,2,3] and larger list B = [1,2,3,1,1,2,2,3,2,3].
B has no other elements except A's but elements order is not maintained.
I want to find how many times A appears in B preserving A's order. For this example A appears 3 times in B. I could solve this for two elements, like [1,2] comes 2 times in [1,1,2,2,1,1]. In other words, I want to find how many ordered group such A is possible from the larger list as B.

A: From what I understood, you want to count how many times all the elements of A are repeated in order in B, even if there are other elements inbetween.
If that's the case, you can use:
A = [1,2,3]

B = [1,1,1,1,1,1,1,1,1,2,3,1,1,2,2,3,2,3,3,3,3,3,3,3,3]

counters = [0 for _ in A] # initialize a list with the same number of values of A, but all at 0

for x in B: # for each element in B
    for n in range(len(A)): # for all the indexes in A
        if x == A[n]: # if the element in B is present in A
            if n == 0 or (counters[n] < counters[n-1]):
            # if n == 0, is the first element of A: we know it's a start of a possible match
            # if the previous number in index is higher of the current number, means that we are looking for the match to continue
                counters[n] += 1 # add 1 to the current number
                break

print counters[-1] # the last number of the counters represent the times that you reached the end of a match

A: An efficient approach is to build a dict of queues of indices for each item in B, then cycle through items in A to look for the next item in the dict whose index is greater than the index of the last found item by keeping dequeueing until such an index is found or break the loop if any queue is exhausted, with each completed cycle incrementing the count by 1:
from collections import deque
index = {}
for i, n in enumerate(B):
    index.setdefault(n, deque()).append(i)
count = 0
while True:
    last = -1
    try:
        for n in A:
            while True:
                i = index[n].popleft()
                if i > last:
                    last = i
                    break
    except (IndexError, KeyError):
        break
    count += 1

count becomes:
3


text:
Q: Concrete5 MySQL query issue I'm getting following SQL error at Concrete5 CMS, just to give you the background we've recently updated MySQL from 5.6 yo 5.7 and this has started to happen.
I've already tried repairing database but it didn't work
mysqlt error: [3065: Expression #1 of ORDER BY clause is not in SELECT list, references column 'scotnew_c5.u.uDateAdded' which is not in SELECT list; this is incompatible with DISTINCT] in EXECUTE("SELECT DISTINCT u.uID, u.uName FROM Users u left join UserSearchIndexAttributes on (UserSearchIndexAttributes.uID = u.uID) where 1=1 order by uDateAdded desc limit 0,10 ")


text:
Q: Resize the width and height of shape (not scaling) in paperjs How can I implement the resizing of width and height of a shape in paper js. just like this : Resizing Objects in Fabric.js ? I am currently basing on this link : Transform bounding box in Paper.js .

A: I have implemented it in Romanesco but it is a bit complicated (I still have to clean the code).
Maybe you would go faster by doing it yourself.
Anyway you can have a look in the source code, in SelectionRectangle.coffee, SelectTool.coffe and Item.coffee.


text:
Q: Delphi & Vista Dragging Forms Glitch I wondered if you have a work around for the problems with docking forms in Vista, such as the close button being partially obscured, and the gray border when being dragged rendering extremely slow, making a appearing / disappearing appearance?
Delphi 2007 & Vista (64 bit)

A: I believe you have two different bugs here.
The obscured button thing is new to me.  Don't think I've seen that one.
The second bug (resizing) is a known one, ie it was fixed in D2009, but there is a solution.
I found it in a JEDI VCL bug fix report and when I it applied to my code it worked great.
JEDI Issue Tracker Report
The fix can be non trivial for users of the native Delphi VCL docking system.  If you're using a third-party docking system such as JvDock from the JEDI VCL it already has it supported.  I implemented it in one of my major applications but I'm using a mixture of native VCL docking and third-party components.
I wanted to post you the solution I have but I got looking into my code and it spans a bunch of units and parts of the main code tree.
There is no simple answer except maybe you want to look at the JEDI docking system.
There is also another known bug with DockingTabs under vista, in that the obscured areas of a "docked" window when they slide closed doesn't repaint properly.  Slide out works fine, slide in (hide) doesn't there is a solution to this one as well, but it requires modifying VCL source to make it work.
Sorry,
Ryan

A: Update: I've looked into the JVCL implementation of the docking, and I think it will work quite nicely, as it doesn't have either of the problems. Thanks again for your help.


text:
Q: Upgrading Azure Tiers Ok Ive been trying to find a definitive answer for this but it keeps getting me more confused trying to differentiate between people talking about VMs and Website plans, and different tier names being introduced, and the whole "Website Hosting Plan" where all your sites are now tied together in the plan.
Pretty much all I want to know is if I started an Azure account and made three free websites. Then I go to the Scale tab and upgrade it to Shared, it will say "all the websites in your plan will be affected" and change all three sites to Shared. Does this apply the ~$9.90 Shared price to each of the three sites (~$30) or does that ~$9.90 cover all the sites in the that shared hosting plan (I believe 100 is the max).

A: In Shared mode, you pay for each Web Site.  In Standard mode, you pay for the VM that can host unlimited Web Sites (limit was 500 before).
So if you do the math, starting at 8 Web sites, it makes sense to go to Standard. It's even cheaper with the new Basic tier.


text:
Q: Force helper 'action' to use HTTPS {{ action('controller@post') }} is not returning the https. Forms are unable to submit because of this.
Moved to a new server and now having issues with https not be recognized.
{{ action('controller@post') }}

A: The action helper uses the UrlGenerator underneath.
There are multiple solutions to this problem.
1.
You can force Laravel to always use https by running
URL::forceScheme('https');

In your AppServiceProvider.
2.
Set your APP_URL in your .env to have https:// at the front. eg.
APP_ULR=https://example.org

3.
Add scheme => 'https' to your group config in you route.
Route::group([scheme => 'https']), function(Router $route) {
    $route->get('secured_route')
}

4.
Use the secure_url() helper. It will always generate a https url.


text:
Q: Xgboost: How to convert prediction probabilities to multiclass labels original names? I am using the xgboost multiclass classifier as outlined in the example below. For each row in the X_test dataframe the model outputs a list with the list elements being the probability corresponding to each category 'a','b','c' or 'd' e.g. [0.44767836 0.2043365  0.15775423 0.19023092].
How can I tell which element in the list corresponds to which class / cateogry (a,b,c or d)? My goal is to create 4 extra columns on the dataframe a,b,c,d with the matching probability as the row value in each column.
import numpy as np
import pandas as pd
import xgboost as xgb
import random
from sklearn import preprocessing
from sklearn.model_selection import train_test_split

#Create Example Data
np.random.seed(312)
data = np.random.random((10000, 3))
y = [random.choice('abcd') for _ in range(data.shape[0])]

features = ["x1", "x2", "x3"]
df = pd.DataFrame(data=data, columns=features)
df['y']=y

#Encode target variable
labelencoder = preprocessing.LabelEncoder()
df['y_target'] = labelencoder.fit_transform(df['y'])

#Train Test Split
X_train, X_test, y_train, y_test = train_test_split(df[features], df['y_target'], test_size=0.2, random_state=42, stratify=y)

#Train Model
dtrain = xgb.DMatrix(X_train, label=y_train)
dtest = xgb.DMatrix(X_test, label=y_test)

param = {        'objective':'multi:softprob',
                 'random_state': 20,
                 'tree_method': 'gpu_hist',
                 'num_class':4
                }

xgb_model = xgb.train(param, dtrain, 100)

predictions=xgb_model.predict(dtest)

print(predictions)

A: Predictions follow the same order as your column labels 0, 1, 2, 3. To get original target names use the classes_ attribute from LabelEncoder.
import pandas as pd

pd.DataFrame(predictions, columns=labelencoder.classes_)
>>>
           a           b           c           d
0       0.133130    0.214460    0.569207    0.083203
1       0.232991    0.275813    0.237639    0.253557
2       0.163103    0.248531    0.114013    0.474352
3       0.296990    0.202413    0.157542    0.343054
4       0.199861    0.460732    0.228247    0.111159
...
1995    0.021859    0.460219    0.235214    0.282708
1996    0.145394    0.182243    0.225992    0.446370
1997    0.128586    0.318980    0.237229    0.315205
1998    0.250899    0.257968    0.274477    0.216657
1999    0.252377    0.236990    0.221835    0.288798


text:
Q: parsing `/etc/passwd` file to find users with Interactive shells I want to parse /etc/passwd file to find out if the user can run interactive shell.
I know the 7th field in each line of /etc/passwd file tells the path of shell. But How do you say that, defined shell is interactive?
I am parsing this files in python, I can implement the logic, I just don't know the how to find out how to identify Interactive shell.
PS. I want to find it out using python.

A: I think you have a basic misconception: talking of a shell that you cannot run interactively but that you can run non-interactively is much like talking of a car that you can't drive but that you can use to listen to the radio.
The main purpose of a shell is running interactively, the fact that it can run non-interactively is the optional, not the other way around.
Closer to the concept of a shell that you cannot run interactively but that you can run non-interactively is an interpreted language which can't be interpreted interactively (though one real example is not occuring to me right now: the most common interpreted languages all can run interactive sessions: Perl, Python, PHP, ...)
That been said if you want to find out whether a user is allowed to login through a shell, you can use this command:
shell=$(getent passwd user | cut -d ':' -f 7); [ "$shell" = "/usr/sbin/nologin" -o "$shell" = "/bin/false" ] && printf 'User is not allowed to login\n' || printf '%s\n' "$shell"

(replace user in the getent passwd user command with the user's username)
In Python you could do:
#!/usr/bin/python
user = "user"
with open("/etc/passwd") as file:
    for line in file:
        if line.split(":")[0] == user:
            if line.rstrip("\n").split(":")[6] in ["/usr/sbin/nologin", "/bin/false"]:
                print("User is not allowed to login")
            else:
                print(line.rstrip("\n").split(":")[6])

(replace user in the user = "user" statement with the user's username)
Or, as suggested by muru, better using the pwd module:
#!/usr/bin/python
from pwd import getpwnam

user = "user"
shell = getpwnam(user)[6]
if shell in ["/usr/sbin/nologin", "/bin/false"]:
    print("User is not allowed to login")
else:
    print(shell)

(replace user in the user = "user" statement with the user's username)
In all of the examples above if the seventh field of the user's /etc/passwd entry is either /usr/sbin/nologin or /usr/bin/false a message saying that the user is not allowed to login is printed; otherwise the user's login shell is printed.
But keep in mind that not being able to login through a shell doesn't mean the user is not allowed to login at all, and that there might be bogus shells other than /usr/sbin/nologin or /bin/false used to forbid the user's login. You should watch out for those too.

A: Loop through file splitting each line into fields and check if 6th field doesn't contain "no-login" for all the lines where UID is greater than 1000
>>> with open("/etc/passwd") as file:
...     for line in file:
...        if  int(line.split(":")[2])  > 1000  and not str(line.split(":")[6]).__contains__("nologin"):
...            print line
...
testuser:x:1001:1001:,,,:/home/testuser:/bin/bash

tester:x:1002:1002:TESTER,,,:/home/tester:/bin/bash

newUser:x:1003:1003::/home/newUser:

testUser:x:1004:1004::/home/testUser:

testuser2:x:1005:1005:asdf,asdf,asdf,asdf,asdf:/home/testuser2:/bin/bash

Usernames who have shell set can login with that shell, for instance xieerqi has /bin/mksh, while testUser has /bin/bash. Other users don't have shell set, which will default to /bin/bash


text:
Q: How start ubuntu from a bootable USB stick I made a bootable USB stick and I made sure to follow the guide lines. As far as I can tell nothing went wrong when creating the USB stick but somehow I can't find out how to boot ubuntu from the stick. I tried restarting my laptop as guide lines suggest but it only starts Windows again. Any ideas what I'm doing wrong?

A: It looks like something not set correctly in BIOS. So first go to the BIOS (look which Fxx key is the "BIOS-entry" key on your model of computer) and look around. There may be Allow USB boot option somewhere. If there is -> enable it. Than search for Boot order menu. You should set the "boot from USB" before "boot from HD". Make sure that you have the bootable USB pluged in before entering to BIOS. My machine for example, didn't give me "boot from USB" option if there was no bootable USB plugged in. If you see somewhere Fast boot option (or similar) -> disable it. You can also set the BIOS to Legacy mode.
Hope you get it working!

A: Usually, if you press F2 or F8 or F10 when your PC is booting will open the boot menu. Pay attention to the info showed on screen to notice what key will do that.

A: Make sure the partition is active.

*

*Boot to Windows.

*Open Disk Management
In Win7 or Vista: Click Start > in the Search box, type diskmgmt.msc     and then click the diskmgmt.msc higher up.
In Win XP: Click Start > click Run > type diskmgmt.msc and click OK

*Select Disk Management.

*Right-click on the Primary partition you want to mark as Active and

*select Mark Partition as Active.

Press respective keys during boot and select boot from USB. This option varies from bios to bios.
If the following doesn't work then try using other tools to create live USB.
Personally I prefer Linux Live USB creator. It works very fine.
http://www.linuxliveusb.com

A: Boot up into windows, find the power menu (restart and shutdown menu) and hold shift and press restart. When a menu comes up select USB device and select your USB.


text:
Q: VHDL - Quartus II modsim I'm starting to write a VGA controller for a DE0 board. I have a model which compiles and loads onto the DE0 board. Also it displays the test message. The problem I am having is I cannot simulate my controller using Quartus II modsim. When I run the simulation I cannot start the VGA file. The little plus icon is missing from the file. A picture and the models file I am using are below:

vga model
LIBRARY IEEE;
USE IEEE.std_logic_1164.ALL;
USE IEEE.numeric_std.ALL;

ENTITY VGA is
PORT (clk                       :   IN   std_logic; -- demo had 2 bit vector
        rst                     :   IN   std_logic:='1';
        vga_hs, vga_vs          :   OUT std_logic;
        vga_r, vga_g, vga_b :   OUT std_logic_vector(3 DOWNTO 0));
END ENTITY VGA;

ARCHITECTURE A1 OF VGA IS
SIGNAL clk25    :   std_logic; -- clk25 signal
BEGIN
SYNC1    :  ENTITY work.sync(A1)
            PORT MAP (clk25, vga_hs, vga_vs, vga_r, vga_g, vga_b);
CLK_25 :    ENTITY work.CLK25(behav)
            PORT MAP (clk, rst, clk25);
END ARCHITECTURE A1;

Sync model
LIBRARY IEEE;
USE IEEE.std_logic_1164.ALL;
USE IEEE.numeric_std.ALL;

ENTITY SYNC IS
GENERIC (
h_res               :   integer:= 640 ;     -- horizontal screen resolution
h_fp                :  integer:= 16 ;   -- horizontal front porch
h_bp                :   integer:= 48 ;     -- horizontal back porch
h_sync          :   integer:= 96 ;  -- horizontal sync pulse duration
h_sync_pol      :   std_logic:='0';     -- horizontal sync pulse state
v_res               :   integer:= 480 ; -- vertical screen resolution
v_fp                :   integer:= 10 ;     -- vertical front porch
v_bp                :   integer:= 33 ;      -- vertical back porch
v_sync          :  integer:= 2;    -- vertical sync pulse duration
v_sync_pol      :   std_logic:='0'    -- vertical sync pulse state
);
PORT(
clk                             :   IN      std_logic;
h_sync_pulse, v_sync_pulse  :   OUT     std_logic;
r, g, b                         :   OUT std_logic_vector(3 DOWNTO 0)
);
END ENTITY SYNC;

ARCHITECTURE A1 OF SYNC IS
 CONSTANT h_size  : integer := (h_res + h_fp + h_bp + h_sync); -- total horizontal vector
 CONSTANT v_size  : integer := (v_res + v_fp + v_bp + v_sync); -- total vertical vector
 SIGNAL h_pos       : integer RANGE 0 TO h_size := 0; -- total horizontal vector
 SIGNAL v_pos      : integer RANGE 0 TO h_size := 0; -- total vertical vector
BEGIN
TIMING :PROCESS(clk, h_pos, v_pos) IS
BEGIN
    IF rising_edge(clk) THEN
        IF (h_pos <= 480 or v_pos <= 285)  THEN -- middle of the screen is pic res/2 + (FP + sync + BP)
            r <= (OTHERS => '1');
            g <= (OTHERS => '1');
            b <= (OTHERS => '1');
        ELSE
            r <= (OTHERS => '0');
            g <= (OTHERS => '0');
            b <= (OTHERS => '0');

        END IF;
                    IF (h_pos <= 480 or v_pos <= 285)  THEN -- middle of the screen is pic res/2 + (FP + sync + BP)
            r <= (OTHERS => '1');
            g <= (OTHERS => '1');
            b <= (OTHERS => '1');
        ELSE
            r <= (OTHERS => '0');
            g <= (OTHERS => '0');
            b <= (OTHERS => '0');
        END IF;
        IF (h_pos < h_size) THEN
                h_pos <= h_pos + 1;
            ELSE
                h_pos <= 0;
            IF (v_pos < v_size) THEN
                    v_pos <= v_pos + 1;
                ELSE
                    v_pos <= 0; --< edit was v_pos <= v_pos
            END IF;
        END IF;

        IF (h_pos > h_fp and h_pos < h_fp + h_sync ) THEN -- H_POS between end of FP and the end of H_SYNC
            h_sync_pulse <= h_sync_pol;                       -- H_SYNC needs to stay high during display
        ELSE
            h_sync_pulse <= '1';
        END IF;

        IF (v_pos > v_fp and v_pos < v_fp + v_sync ) THEN    --V_POS between end of FP and the end of V_SYNC
            v_sync_pulse <= v_sync_pol;                          -- V_SYNC needs to stay high during display
        ELSE
            v_sync_pulse <= '1';
        END IF;

        IF ((h_pos > 0 and h_pos < h_fp + h_bp + h_sync) or (v_pos > 0 and v_pos < v_fp + v_bp + v_sync )) THEN --During all of SYNC i.e FP + SYNC + BP colour signals stay low
            r <= (OTHERS => '0');
            g <= (OTHERS => '0');
            b <= (OTHERS => '0');
        END IF;
    END IF;
END PROCESS TIMING;
END ARCHITECTURE A1;

The design units after compilation do not show the architectures for either the vga.vhd or the sync.vhd files


text:
Q: how to ignore builtin xslt rules I have this xml:
<?xml version="1.0" encoding="UTF-8"?>
<lib>
    <books xmlns="http://www.books.com/SRK">
        <name>English</name>
    </books>
    <cats>
        <cat>cat1</cat>
        <cat>cat2</cat>
    </cats>
</lib>

and this xslt:
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="//cats/*">
        <xsl:element name="{local-name()}">
            <xsl:apply-templates select="node()"/>
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>

the expected out is to not have english in output but first it  write english and then what I need.
I mean currently output is :
English<cat>cat1</cat>
<cat>cat2</cat>

but I don't want it contain English.

A: You can apply your template only to cats section. like this:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes"/>
    <xsl:template match="node()|@*">
           <xsl:apply-templates select="//cats"/>
    </xsl:template>
    <xsl:template match="cats">
        <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>


text:
Q: Reemplazar una parte de la cadena sin magia Tengo el siguiente código:

text = 'check this regex<placeholder>, it will do what you want';
result = text.replace('<placeholder>', ' `^sql$`');

console.log(result);

Como pueden ver, el resultado es
check this regex `^sqlcheck this regex, it will do what you want

Cuando esperaría que sea
check this regex `^sql$`, it will do what you want

Por qué pasa esto? y... cómo puedo arreglarlo?

A: La función replace tiene un comportamiento interesante respecto al segundo parámetro: (las negritas son mías).

The replacement string can include the following special replacement
  patterns:
Pattern   Inserts

*

*$$  Inserts a "$".

*$&  Inserts the matched substring.

*$`    Inserts the portion of the string that precedes the matched substring.

*$'  Inserts the portion of the string that follows the matched substring.

*$n  Where n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a
  RegExp object. Note that this is 1-indexed.

Traducción aproximada:
El string de reemplazo puede incluir los siguientes patrones de reemplazo:

*

*$$ inserta un "$".

*$& Inserta el substring que coincide con la búsqueda.

*$` Inserta la porción del string que precede al substring que coincide con la búsqueda.

*$' Inserta la porción del string que sigue al substring que coincide con la búsqueda.

*$n Donde n es un número entero positivo y menor a 100, inserta la n-ésima sub-coincidencia entre paréntesis (grupo de captura), asumiendo que el patrón (primer parámetro) es una expresión regular.

Es decir, en este caso se añade ^sql y tras esto se añade todo el string que precede al match. Se puede solucionar duplicando el carácter $:

const text = 'check this regex<placeholder>, it will do what you want';
const result = text.replace('<placeholder>', ' `^sql$$`');
//                                                  ^^
console.log(result);


text:
Q: How to support all the different resolutions of android products All the different resolutions of the different Android products are driving me nuts.
My first android app that I wrote was designed so it supported the three commonly used resolutions: 240x320 (LDPI), 320x480 (MDPI) and 480x800 (HDPI). The 480x854 didn't do any harm to the layout because it has the same width as 480x800.
I've also bought the following devices to test my android apps on:
Samsung Galaxy Europe (LDPI)
HTC Desire Z (HDPI)
Luckily my girlfriend has a HTC Wildfire S (MDPI) so I've got most resolutions covered.
But today, my brother downloaded my app on his new HTC Sensation which has yet another resolution 540x960 (HDPI?). Which didn't show my app as it should and probably the most tablets won't show it correctly either.
What I've did with my first app was read out the density and then set the parameters:
public void set_ui_parameters() {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    if(metrics.densityDpi == DisplayMetrics.DENSITY_HIGH){
        textSize   = 35;
        timeWidth  = 80;
        dayWidth   = 110;
        moneyWidth = 50;
    } else if(metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM){
        textSize   = 35;
        timeWidth  = 53;
        dayWidth   = 73;
        moneyWidth = 33;
    } else if(metrics.densityDpi == DisplayMetrics.DENSITY_LOW){
        textSize   = 28;
        timeWidth  = 40;
        dayWidth   = 55;
        moneyWidth = 25;
    }
}

Besides the parameters I've also created drawables for LDPI, MDPI and HDPI. This works fine for the resolutions described above, but this depends on the screen resolution i.c.w. screen size and fails for, for example the HTC sensatoin with 540x960.
I know that not all the resolutions are used that often, but I would like to support as many as possible. Stats of Screen Sizes and Densities
I've read Supporting Multiple Screens multiple times but didn't found a clear answer to this "problem".
So should I read out the resolution and set the parameters according to the resolutions instead of density? Is this a smart thing to do or how do you cope with this?
Thanks a lot for your information!

A: You don't have to do that to support different densities. What you do is create different resources folders:
res/values-ldpi/dimens.xml
res/values-mdpi/dimens.xml
res/values-hdpi/dimens.xml

Then Android will decide which file to use. You can have something like:
<!-- in values-ldpi/dimens.xml -->
<dimen name="textSize">25dip</dimen>

and..
<!-- in values-mdpi/dimens.xml -->
<dimen name="textSize">20dip</dimen>

etc. And you shouldn't care about resolution... there are a lot of different resolutions sizes so it would be a hell to take decisions based on that.
Also, if you use dp instead of pixels, you hardly ever will have to create different dimensions files for each density. Of course, sometimes you have to, but it depends on the app.

A: Only thing you have to do is, that you set android:minSdkVersion to 7 or higher in your manifest file. Is is possible that some views will appear slightly different but app is
applicable and on whole screen.

A: Now, i'm just guessing here since the rest of the implementation isn't shown, but I'm assuming you are using those derived measurements as px
Take a look at dp.   That essentially does all those things you did, automatically, for any device.  (Device Independent Pixel)

A: Don't worry about the slight difference in resolution: 540x960 is only slightly bigger than 480x800. The extra vertical space is easy: it gives you more room for your lists. For horizontal space, as long as you're handling your layouts correctly you'll simply have extra padding (30pix ea) on the sides.
Unfortunately, full-width images (480 wide) are a slightly bigger problem. If you want pixel perfect images, you'll want to use scaleType="center" so the image centers but not scales. If you want full width, you can use scaleType="fitCenter" to make it fill. It will be a bit fuzzy... but so many thing on Android are ;-)

A: I ran into this problem as well, except my app is a game where there is one SurfaceView canvas that I draw background images and sprites to (similar to LunarLander example).
The way you handle it here is to extend your background image to the largest size you are willing to support (540x960) but you keep all the important things (like buttons, text, information, etc) within a smaller rectangle of 480x800.  You can extend the image itself, or just add borders.  The key is that nothing important is there.
People with 480x800 phones will see your normal app.  People with 540x960 phones will see a little extra border.


text:
Q: Handlebars.Net Each loop c# I have a JArray that contains an array of objects. I am using handlebars.net to bind the data in the template.
In getReportDetails variable, I am getting an array of objects in the below format
[
{
"index": 1,
"Name": "Adam",
},
{
"index": 2,
"Name": "Sdam",
}
];

var template = Handlebars.Compile(source);
_logger.Info(getReportDetails);
var getdata = template(getReportDetails);

   {{#each getReportDetails}}

    {{Name}}

In getdata variable data is not binding.  What am I doing wrong?

A: Your array is root of your data object, so you should use #each this:

    {{#each this}}

Working example:
    var list = new List<X>() { new X() { Id=1 }, new X() { Id = 2} };
    var template = Handlebars.Compile("{{#each this}} xxx {{Id}} {{/each}}");


text:
Q: How to set a timeout to terminate nginx workers? I would like to set a duration for Nginx to terminate the workers after the timeout. I am looking for a feature like "Ping Maximum Response Time" in IIS. I am using uWSGI, Nginx, and Pylons Framework.

IIS - Ping Maximum Response Time (seconds): Maximum time (in seconds)
that a worker process is given to respond to a health monitoring ping.
If the worker process does not respond, it is terminated.

I found some Nginx directives, but I am not sure which one(s) must be used.

*

*uwsgi_read_timeout

*uwsgi_send_timeout

*proxy_read_timeout

*proxy_send_timeout

*worker_shutdown_timeout

A: I found the solution.
As Nginx is used as a reverse proxy, I added these three directives.
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 600; # (in seconds) <- must be changed to what we need.


text:
Q: How to get left table values only (left join) I have two tables:

*

*bloodrequest (id,name,Rphone,bloodtype) as:

*reacheduser (id,Rphonw,Dphone) as:

I want to read all data in bloodrequest if bloodrequest.id is not equal to reachedusers.id where reachedusers.Dphone!="618159985"
I have tried left join , subquery  but unfortunately nothing work
hear is some code i tried:
SELECT bloodrequest.id, bloodrequest.magac, bloodrequest.bloodType
FROM bloodrequest
LEFT JOIN reachedusers on bloodrequest.id != reachedusers.id
WHERE reachedusers.Dphone != "618159985"

i want to check if request id in table bloodrequest  is in reached table where Dphone ="618159985"
if the id is exist but but dphone is not 618159985 i want to read otherwise not

A: You can use NOT IN (subquery) to find the rows you want, as in:
SELECT
  id, magac, bloodType
FROM bloodrequest
WHERE id NOT IN (
  SELECT id
  FROM reachedusers
  WHERE Dphone = "618159985"
)


text:
Q: Assign type from key of a Interface I have a interface:
interface IReceipt {
  payment: IPayment;
  details: string;
}

I have one component which takes payment as parameter:
const renderPayment = (props: {paymentInfo}) => {}

I need to define the type of paymentInfo as Payment. How can I use the IReceipt interface to assign type to paymentInfo
Something like {paymentInfo: IReceipt.payment}

A: You can simply use:
paymentInfo: IReceipt['payment']

So you can simply write:
interface IReceipt {
    payment: IPayment;
    details: string;
}
const renderPayment = (props: {paymentInfo: IReceipt['payment']}) => {}


text:
Q: Adding an event within a WebComponent I want to create a Web Component. I use a ShadowDom and after generating a list I want to add a click Event to each element of the list. But I wonder how to access the list.
Neither the document nor the template shows me the items after a querySelect.
My question:
How can I access the generated list within the webcomponent?

const news =
  {
    uk: [{
      id: 1,
      title: "News 1 UK",
      body: "lorem ipsum"
    },
    {
      id: 2,
      title: "News 2 UK",
      body: "lorem ipsum"
    },
    {
      id: 3,
      title: "News 3 UK",
      body: "lorem ipsum"
    },
    {
      id: 4,
      title: "News 4 UK",
      body: "lorem ipsum"
    },
  ],
  de: [
    {
      id: 1,
      title: "News 1 DE",
      body: "lorem ipsum"
    },
    {
      id: 2,
      title: "News 2 DE",
      body: "lorem ipsum"
    },
    {
      id: 3,
      title: "News 3 DE",
      body: "lorem ipsum"
    },
    {
      id: 4,
      title: "News 4 DE",
      body: "lorem ipsum"
    },
  ]
  };

class MyNews {

  #limit = 10;
  #region = 'uk';
  news = [];

  constructor(conf = {}) {
    this.#limit = conf.limit ?? this.#limit;
    this.#region = conf.region ?? this.#region;
    this.news = news[this.#region]
  }

  showNews() {
    const items = this.news.slice(0,this.#limit);
    return items.map((n,i) => {
      return `<p>${i+1}. ${n.title}</p>`;
    }).join('');
  }

  getNewsData() {
    return this.news;
  }
}

class NewsTicker extends HTMLElement {

  constructor() {
    super();
    this.name = 'World News';
    this.limit = 10;
    this.region = "uk"
  }

  static get observedAttributes() {
    return ['name', 'url', 'limit', 'region'];
  }

  attributeChangedCallback(property, oldValue, newValue) {

    if (oldValue === newValue) return;
    this[ property ] = newValue;

  }

  async connectedCallback() {
    const options = {
      url: this.url,
      limit: this.limit,
      region: this.region
    };
    const myNews = new MyNews(options);

    const
      shadow = this.attachShadow({ mode: 'closed' }),
      template = document.getElementById('news-template').content.cloneNode(1),
      contextTitle = `Context ${ this.name } !`;

    template.querySelector('.news-context-title').textContent = contextTitle;
    template.querySelector('.news-list').innerHTML = myNews.showNews();
    shadow.append( template );

    const list = document.querySelector('.news-list');
    console.log("try to get list inner the template tag:", list)
  }

}

customElements.define( 'news-ticker', NewsTicker );
<news-ticker
     name="News DE"
     region="de"
     limit="2">
</news-ticker>
<template id="news-template">

</template>

A: You dont have access to the template over document. The template tag is a shadow DOM. You can make avaible for access the shadow DOM if you change the mode parameter to true: this.attachShadow({ mode: 'open' }). Then you can use this.shadowRoot.querySel.... Otherwise you can access directly over your shadow object (shadow = this.attachShadow({ mode: 'closed' })) with shadow.querySelector().

const news =
  {
    uk: [{
      id: 1,
      title: "News 1 UK",
      body: "lorem ipsum"
    },
    {
      id: 2,
      title: "News 2 UK",
      body: "lorem ipsum"
    },
    {
      id: 3,
      title: "News 3 UK",
      body: "lorem ipsum"
    },
    {
      id: 4,
      title: "News 4 UK",
      body: "lorem ipsum"
    },
  ],
  de: [
    {
      id: 1,
      title: "News 1 DE",
      body: "lorem ipsum"
    },
    {
      id: 2,
      title: "News 2 DE",
      body: "lorem ipsum"
    },
    {
      id: 3,
      title: "News 3 DE",
      body: "lorem ipsum"
    },
    {
      id: 4,
      title: "News 4 DE",
      body: "lorem ipsum"
    },
  ]
  };

class MyNews {

  #limit = 10;
  #region = 'uk';
  news = [];

  constructor(conf = {}) {
    this.#limit = conf.limit ?? this.#limit;
    this.#region = conf.region ?? this.#region;
    this.news = news[this.#region]
  }

  showNews() {
    const items = this.news.slice(0,this.#limit);
    return items.map((n,i) => {
      return `<p>${i+1}. ${n.title}</p>`;
    }).join('');
  }

  getNewsData() {
    return this.news;
  }
}

class NewsTicker extends HTMLElement {

  constructor() {
    super();
    this.name = 'World News';
    this.limit = 10;
    this.region = "uk"
  }

  static get observedAttributes() {
    return ['name', 'url', 'limit', 'region'];
  }

  attributeChangedCallback(property, oldValue, newValue) {

    if (oldValue === newValue) return;
    this[ property ] = newValue;

  }

  async connectedCallback() {
    const options = {
      url: this.url,
      limit: this.limit,
      region: this.region
    };
    const myNews = new MyNews(options);

    const
      shadow = this.attachShadow({ mode: 'open' }), // change mode to open then you have access over the shadowRoot
      template = document.getElementById('news-template').content.cloneNode(1),
      contextTitle = `Context ${ this.name } !`;

    template.querySelector('.news-context-title').textContent = contextTitle;
    template.querySelector('.news-list').innerHTML = myNews.showNews();
    shadow.append( template );

    const list = document.querySelector('.news-list');
    const list_1 = shadow.querySelector('.news-list');
    const list_2 = this.shadowRoot.querySelector('.news-list');

    console.log("document.querySelector('.news-list') :", list_1)
    console.log("shadow.querySelector('.news-list') :", list_2);
    console.log("this.shadowRoot.querySelector('.news-list') :", list_3);

  }

}

customElements.define( 'news-ticker', NewsTicker );
<news-ticker
     name="News DE"
     region="de"
     limit="2">
</news-ticker>
<template id="news-template">

</template>


text:
Q: Perform foreach on values returned inside array I'm not sure if I have worded this question correctly, but basically I have the following array result from WordPress I am trying to deal with:
Array
(
    [0] => WP_User Object
        (
            [data] => stdClass Object
                (
                    [ID] => 3
                    [user_login] => Jean Gomes
                    [user_pass] => $P$BvW6LK9/blGKLuSj.9spNPW3.v104..
                    [user_nicename] => jean-gomes
                    [user_email] => jean.gomes@dpa.dev
                    [user_url] =>
                    [user_registered] => 2014-08-28 10:56:39
                    [user_activation_key] =>
                    [user_status] => 0
                    [display_name] => Jean Gomes
                )

            [ID] => 3
            [caps] => Array
                (
                    [author] => 1
                )

            [cap_key] => dpa2335327_capabilities
            [roles] => Array
                (
                    [0] => author
                )

            [allcaps] => Array
                (
                    [upload_files] => 1
                    [edit_posts] => 1
                    [edit_published_posts] => 1
                    [publish_posts] => 1
                    [read] => 1
                    [level_2] => 1
                    [level_1] => 1
                    [level_0] => 1
                    [delete_posts] => 1
                    [delete_published_posts] => 1
                    [wpseo_bulk_edit] => 1
                    [author] => 1
                )

            [filter] =>
        )

    [1] => WP_User Object
        (
            [data] => stdClass Object
                (
                    [ID] => 4
                    [user_login] => Tammy Day
                    [user_pass] => $P$BejydpFxKDp60WruV71u0/JnJm9o.E.
                    [user_nicename] => tammy-day
                    [user_email] => tammy.day@dpa.dev
                    [user_url] =>
                    [user_registered] => 2014-08-28 10:57:23
                    [user_activation_key] =>
                    [user_status] => 0
                    [display_name] => Tammy Day
                )

            [ID] => 4
            [caps] => Array
                (
                    [author] => 1
                )

etc
I would like to perform a foreach using these results, for the ID.
E.g.
foreach ( $authors as $author_id ) {

But I don't know how to access the ID. I tried:
foreach ( $authors->ID as $author_id ) {

But obviously this can't work, as there is a number before that, is there an equivalent of:
foreach ( $authors['X']->ID as $author_id ) {

that I could use?
Sorry I know this is probably a silly question, but I'm quite stuck. I know I probably have to do a foreach within a foreach but I can't work out the syntax at all.

A: You cant try this instead of foreach :
$i=0;
while ($i<count($authors)){
$author_id = $authors[$i]['data']['id'];
//Do whatever you want here.
$i=$i+1;
}

A: As the dump states, the array elements are instances of WP_User. You can use the following loop to fetch the IDs:
foreach ($authors as $User) {
    $author_id = $User->ID;
    // Act
}

For a reference of the WP_User class, see http://codex.wordpress.org/Class_Reference/WP_User

A:
foreach (array_expression as $value)

On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

Read this documentation page for more details about foreach loop:
In your situation $value will pointer to the instance of WP_User Object. To access to the user's id just read object's property ID
foreach ( $authors as $author ) {
    $author_id = $author->ID;
}


text:
Q: How to change the background color of pop up header? I am getting issue in background color on popup  header.I  am trying to change the background color of pop up header using below code but its not working. The header background color for the popup not taking the below css. Please help me.
HTML
    Open Modal

                            X

css
    .pop-header
    {
         width: 100%;
         background-color: #000;
         height: 50px;
         padding: 20px;
    }

    .modalDialog {
        position: fixed;
        font-family: Arial, Helvetica, sans-serif;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background: rgba(0,0,0,0.8);
        z-index: 99999;
        opacity:0;
        -webkit-transition: opacity 400ms ease-in;
        -moz-transition: opacity 400ms ease-in;
        transition: opacity 400ms ease-in;
        pointer-events: none;
    }

    .modalDialog:target {
        opacity:1;
        pointer-events: auto;
    }

    .modalDialog > div {
        width: 600px;
        position: relative;
        margin: 2% auto;
        padding: 5px 20px 13px 20px;
        border-radius: 5px;
        background: #fff;
        height: 100%;
    }

    .close
    {
        float: right;
    }

A: Change color background in .modalDialog > div css.
.modalDialog > div {
        width: 600px;
        position: relative;
        margin: 2% auto;
        padding: 5px 20px 13px 20px;
        border-radius: 5px;
        background: red; //Here
        height: 100%;
    }

Fiddle
Edit:
If you want to change color of only header part then you should put one div parent to .pop-header

  X

And css:
.pop-header
    {
       width: 100%;
       background-color: red;
       height: 50px;
    }

Updated Fiddle
Check as per your image
New Fiddle

A: you can try this one:
 .pop-header
    {
         width: 100%;
         background-color: #000!important;
         height: 50px;
         padding: 20px;

    }

    .modalDialog {
        position: fixed;
        font-family: Arial, Helvetica, sans-serif;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background: rgba(0,0,0,0.8);
        z-index: 99999;
        opacity:0;
        -webkit-transition: opacity 400ms ease-in;
        -moz-transition: opacity 400ms ease-in;
        transition: opacity 400ms ease-in;
        pointer-events: none;
    }

    .modalDialog:target {
        opacity:1;
        pointer-events: auto;
    }

    .modalDialog > div {
        width: 600px;
        position: relative;
        margin: 2% auto;
        padding: 5px 20px 13px 20px;
        border-radius: 5px;
        background: #fff;
        height: 100%;
    }

    .close
    {
        float: right;
        color:white;
    }

DEMO HERE
Or
.pop-header
    {
         width: 100%;
         background-color: #000!important;
         height: 50px;
         padding: 20px;

    }

.pop-header p
{
  color:white;
  background-color:blue;
  float:left;
  margin:0px;

  width:100%;
  top:0px;
  position:relative;
  display:inline-block;
  padding:8px;
}

    .modalDialog {
        position: fixed;
        font-family: Arial, Helvetica, sans-serif;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background: rgba(0,0,0,0.8);
        z-index: 99999;
        opacity:0;
        -webkit-transition: opacity 400ms ease-in;
        -moz-transition: opacity 400ms ease-in;
        transition: opacity 400ms ease-in;
        pointer-events: none;
    }

    .modalDialog:target {
        opacity:1;
        pointer-events: auto;
    }

    .modalDialog > div {
        width: 600px;
        position: relative;
        margin: 2% auto;
        padding: 5px 20px 13px 20px;
        border-radius: 5px;
        background: #fff;
        height: 100%;

    }

    .close
    {
        float: right;
        color:white;
        position:absolute;
        top:13px;
         right:10px;
    }

DEMO HERE

A: replace your .pop-header class with below :
.pop-header
    {
         width: 100%;
         background-color: #000!important;
         height: 50px!important;
         padding: 20px;
    }

Hope this helps you.

A: The popup header rule is ignored, using !important will make sure nothing can override it you could just put this rule at the end of the style sheet.
.pop-header
    {
         width: 100%;
         background-color: #000 !important;
         height: 50px;
         padding: 20px;
    }


text:
Q: Kubernetes use the same volumeMount in initContainer and Container I am trying to get a volume mounted as a non-root user in one of my containers.  I'm trying an approach from this SO post using an initContainer to set the correct user, but when I try to start the configuration I get an "unbound immediate PersistentVolumneClaims" error.  I suspect it's because the volume is mounted in both my initContainer and container, but I'm not sure why that would be the issue: I can see the initContainer taking the claim, but I would have thought when it exited that it would release it, letting the normal container take the claim.  Any ideas or alternatives to getting the directory mounted as a non-root user?  I did try using securityContext/fsGroup, but that seemed to have no effect.  The /var/rdf4j directory below is the one that is being mounted as root.
Configuration:
apiVersion: v1
kind: PersistentVolume
metadata:
  name: triplestore-data-storage-dir
  labels:
    type: local
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteMany
  storageClassName: local-storage
  volumeMode: Filesystem
  persistentVolumeReclaimPolicy: Delete
  hostPath:
    path: /run/desktop/mnt/host/d/workdir/k8s-data/triplestore
    type: DirectoryOrCreate
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: triplestore-data-storage
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1Gi
  storageClassName: local-storage
  volumeName: "triplestore-data-storage-dir"
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: triplestore
  labels:
    app: demo
    role: triplestore
spec:
  selector:
    matchLabels:
      app: demo
      role: triplestore
  replicas: 1
  template:
    metadata:
      labels:
        app: demo
        role: triplestore
    spec:
      containers:
        - name: triplestore
          image: eclipse/rdf4j-workbench:amd64-3.5.0
          imagePullPolicy: Always
          ports:
            - name: http
              protocol: TCP
              containerPort: 8080
          resources:
            requests:
              cpu: 100m
              memory: 200Mi
          volumeMounts:
            - name: storage
              mountPath: /var/rdf4j
      initContainers:
        - name: take-data-dir-ownership
          image: eclipse/rdf4j-workbench:amd64-3.5.0
          command:
            - chown
            - -R
            - 100:65533
            - /var/rdf4j
          volumeMounts:
            - name: storage
              mountPath: /var/rdf4j
      volumes:
        - name: storage
          persistentVolumeClaim:
            claimName: "triplestore-data-storage"

kubectl get pvc
NAME                       STATUS   VOLUME                         CAPACITY   ACCESS MODES   STORAGECLASS    AGE
triplestore-data-storage   Bound    triplestore-data-storage-dir   10Gi       RWX            local-storage   13s

kubectl get pv
NAME                           CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                              STORAGECLASS    REASON   AGE
triplestore-data-storage-dir   10Gi       RWX            Delete           Bound    default/triplestore-data-storage   local-storage            17s

kubectl get events
LAST SEEN   TYPE      REASON              OBJECT                             MESSAGE
21s         Warning   FailedScheduling    pod/triplestore-6d6876f49-2s84c    0/1 nodes are available: 1 pod has unbound immediate PersistentVolumeClaims.
19s         Normal    Scheduled           pod/triplestore-6d6876f49-2s84c    Successfully assigned default/triplestore-6d6876f49-2s84c to docker-desktop
3s          Normal    Pulled              pod/triplestore-6d6876f49-2s84c    Container image "eclipse/rdf4j-workbench:amd64-3.5.0" already present on machine
3s          Normal    Created             pod/triplestore-6d6876f49-2s84c    Created container take-data-dir-ownership
3s          Normal    Started             pod/triplestore-6d6876f49-2s84c    Started container take-data-dir-ownership
2s          Warning   BackOff             pod/triplestore-6d6876f49-2s84c    Back-off restarting failed container
46m         Normal    Pulled              pod/triplestore-6d6876f49-9n5kt    Container image "eclipse/rdf4j-workbench:amd64-3.5.0" already present on machine
79s         Warning   BackOff             pod/triplestore-6d6876f49-9n5kt    Back-off restarting failed container
21s         Normal    SuccessfulCreate    replicaset/triplestore-6d6876f49   Created pod: triplestore-6d6876f49-2s84c
21s         Normal    ScalingReplicaSet   deployment/triplestore             Scaled up replica set triplestore-6d6876f49 to 1

kubectl describe pods/triplestore-6d6876f49-tw8r8
Name:         triplestore-6d6876f49-tw8r8
Namespace:    default
Priority:     0
Node:         docker-desktop/192.168.65.4
Start Time:   Mon, 17 Jan 2022 10:17:20 -0500
Labels:       app=demo
              pod-template-hash=6d6876f49
              role=triplestore
Annotations:  <none>
Status:       Pending
IP:           10.1.2.133
IPs:
  IP:           10.1.2.133
Controlled By:  ReplicaSet/triplestore-6d6876f49
Init Containers:
  take-data-dir-ownership:
    Container ID:  docker://89e7b1e3ae76c30180ee5083624e1bf5f30b55fd95bf1c24422fabe41ae74408
    Image:         eclipse/rdf4j-workbench:amd64-3.5.0
    Image ID:      docker-pullable://registry.com/publicrepos/docker_cache/eclipse/rdf4j-workbench@sha256:14621ad610b0d0269dedd9939ea535348cc6c147f9bd47ba2039488b456118ed
    Port:          <none>
    Host Port:     <none>
    Command:
      chown
      -R
      100:65533
      /var/rdf4j
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    1
      Started:      Mon, 17 Jan 2022 10:22:59 -0500
      Finished:     Mon, 17 Jan 2022 10:22:59 -0500
    Ready:          False
    Restart Count:  6
    Environment:    <none>
    Mounts:
      /var/rdf4j from storage (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-s8wdv (ro)
Containers:
  triplestore:
    Container ID:
    Image:          eclipse/rdf4j-workbench:amd64-3.5.0
    Image ID:
    Port:           8080/TCP
    Host Port:      0/TCP
    State:          Waiting
      Reason:       PodInitializing
    Ready:          False
    Restart Count:  0
    Requests:
      cpu:        100m
      memory:     200Mi
    Environment:  <none>
    Mounts:
      /var/rdf4j from storage (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-s8wdv (ro)
Conditions:
  Type              Status
  Initialized       False
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  storage:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  triplestore-data-storage
    ReadOnly:   false
  kube-api-access-s8wdv:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   Burstable
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type     Reason            Age                    From               Message
  ----     ------            ----                   ----               -------
  Warning  FailedScheduling  6m24s                  default-scheduler  0/1 nodes are available: 1 pod has unbound immediate PersistentVolumeClaims.
  Normal   Scheduled         6m13s                  default-scheduler  Successfully assigned default/triplestore-6d6876f49-tw8r8 to docker-desktop
  Normal   Pulled            4m42s (x5 over 6m12s)  kubelet            Container image "eclipse/rdf4j-workbench:amd64-3.5.0" already present on machine
  Normal   Created           4m42s (x5 over 6m12s)  kubelet            Created container take-data-dir-ownership
  Normal   Started           4m42s (x5 over 6m12s)  kubelet            Started container take-data-dir-ownership
  Warning  BackOff           70s (x26 over 6m10s)   kubelet            Back-off restarting failed container

Solution
As it turns out the problem was that the initContainer wasn't running as root, it was running as the default user of the container, and so didn't have the permissions to run the chown command.  In the linked SO comment, this was the first comment to the answer, with the response being that the initContainer ran as root - this has apparently changed in newer versions of kubernetes.  There is a solution though, you can set the securityContext on the container to run as root, giving it permission to run the chown command, and that successfully allows the volume to be mounted as a non-root user.  Here's the final configuration of the initContainer.
initContainers:
  - name: take-data-dir-ownership
    image: eclipse/rdf4j-workbench:amd64-3.5.0
    securityContext:
      runAsUser: 0
    command:
      - chown
      - -R
      - 100:65533
      - /var/rdf4j
    volumeMounts:
      - name: storage
        mountPath: /var/rdf4j

A: 1 pod has unbound immediate PersistentVolumeClaims. - this error means the pod cannot bound to the PVC on the node where it has been scheduled to run on. This can happen when the PVC bounded to a PV that refers to a location that is not valid on the node that the pod is scheduled to run on. It will be helpful if you can post the complete output of kubectl get nodes -o wide, kubectl describe pvc triplestore-data-storage, kubectl describe pv triplestore-data-storage-dir to the question.
The mean time, PVC/PV is optional when using hostPath, can you try the following spec and see if the pod can come online:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: triplestore
  labels:
    app: demo
    role: triplestore
spec:
  selector:
    matchLabels:
      app: demo
      role: triplestore
  replicas: 1
  template:
    metadata:
      labels:
        app: demo
        role: triplestore
    spec:
      containers:
      - name: triplestore
        image: eclipse/rdf4j-workbench:amd64-3.5.0
        imagePullPolicy: IfNotPresent
        ports:
        - name: http
          protocol: TCP
          containerPort: 8080
        resources:
          requests:
            cpu: 100m
            memory: 200Mi
        volumeMounts:
        - name: storage
          mountPath: /var/rdf4j
      initContainers:
      - name: take-data-dir-ownership
        image: eclipse/rdf4j-workbench:amd64-3.5.0
        imagePullPolicy: IfNotPresent
        securityContext:
          runAsUser: 0
        command:
          - chown
          - -R
          - 100:65533
          - /var/rdf4j
        volumeMounts:
          - name: storage
            mountPath: /var/rdf4j
      volumes:
        - name: storage
          hostPath:
            path: /run/desktop/mnt/host/d/workdir/k8s-data/triplestore
            type: DirectoryOrCreate


text:
Q: Dapper SplitOn Repeating Classes I fear I may be misunderstanding multi-mapping in Dapper.
Given the following:
public class Job
{
    public int JobId { get; set; }
    public Site FromSite { get; set; }
    public Site ToSite { get; set; }
}

public class Site
{

    public int SiteId { get; set; }
    public string CompanyName { get; set; }
    public Address Address { get; set; }
}
public class Address
{
    public string Address1 { get; set; }
    public string Postcode { get; set; }
}

Each Job will have 2 instances of Site, each of which will have an instance of an Address
This is flattened and I'm attempting to map this as below:
    string sql = @"
                    select
                        JOBIdNumber JobId,

                        fr.SUPKey SiteId,
                        fr.SUPCompanyName CompanyName,

                        fr.SUPAddress1 Address1,
                        fr.SUPPostCode Postcode,

                        t.SUPKey SiteId,
                        t.SUPCompanyName CompanyName,

                        t.SUPAddress1 Address1,
                        t.SUPPostCode PostCode

                    FROM tb_JobJob inner Join tb_SUPSupplier fr on JOBFromSiteId = fr.SupKey
                    inner join tb_SUPSupplier t on t.SUpkey = jobTositeId
                    where jobidnumber = @JobId
                ";

    var jb = cn.Query<Job, Site, Address, Site, Address, Job>(sql,
        (job, fromSite, fromSiteAddress, toSite, toSiteAddress) =>
    {
        job.FromSite = fromSite;
        job.FromSite.Address = fromSiteAddress;

        job.ToSite = toSite;
        job.ToSite.Address = toSiteAddress;

        return job;
    },
    splitOn: "SiteId,Address1",
    param: new { JobId = jobId });

Which results in:

When using the multi-mapping APIs ensure you set the splitOn param if
  you have keys other than Id

I'm not sure whether I am misunderstanding the process, and if so, how do I go about mapping this, it seems like it should be something others have come across.

A: You don't give dapper enough information to split the result columns into the respective objects.
    string sql = @"
                    select
                        1 as JobId,
                        2 as SiteId,
                        'Company 1' as CompanyName,
                        'Address 1' as Address1,
                        'Postcode 1' as Postcode,
                        3 as SiteId,
                        'Company 2' as CompanyName,
                        'Address 2' as Address1,
                        'Postcode 2' as PostCode
                ";

   var jb = connection.Query<Job, Site, Address, Site, Address, Job>(sql,
                    (job, fromSite, fromSiteAddress, toSite, toSiteAddress) =>
                    {
                        job.FromSite = fromSite;
                        job.FromSite.Address = fromSiteAddress;

                        job.ToSite = toSite;
                        job.ToSite.Address = toSiteAddress;

                        return job;
                    },
                    splitOn: "JobId,SiteId,Address1,SiteId,Address1");

Does the job.
splitOn means "put everything UP and including the split field into the respective object. Because you have multiple child classes, you need to define a split field for each of them.


text:
Q: Cache expensive JBuilder result from frequent resquest I've and endpoint that generates a Json response using JBuilder.
However, this Json is very slow to craft and since this request is made every few seconds and it don't need to be updated everytime, I decided to cache it.
It's a complicated-ish Json with nested attributes and it access some model associations.
How can I cache the json result and just render it to the user every x minutes?
file.json.jbuilder:
json.array!(@photos) do |photo|
  json.extract! photo, :id, :title, :description, :image_updated_at
  json.camera_roll_image_url URI.join(request.url, photo.image.url(:camera_roll)).to_s
  json.original_image_url URI.join(request.url, photo.image.url).to_s
  json.has_picture true

  json.girl do
    json.extract! photo.girl, :id, :name, :phone, :ddd, :country_code, :approved, :gender, :likes, :is_ad, :ad_type
    json.user_liked photo.girl.liked_by_user?(@user)
    if(photo.girl.is_ad == 1)
      json.ad_info do
        json.extract! photo.girl, :price, :description, :address, :ad_type
      end
    end
    json.is_featured photo.girl.is_featured?
    json.avatar URI.join(request.url, photo.girl.avatar.url(:thumb)).to_s
    json.age photo.girl.age
    json.country_num_code photo.girl.country_num_code
    json.type photo.girl.type
  end

  json.check_in do
    json.extract! photo.girl.check_ins.last, :latitude, :longitude
  end

  json.userLat @userLat
  json.userLong @userLong

  json.likes photo.likes
  json.user_liked photo.liked_by_user? @current_user
end

A: well, there are several caching mechanisms integrated into rails. you can read about them in the guides: http://guides.rubyonrails.org/caching_with_rails.html
in your specific case, there are several options, all of them have a high chance of success.
before caching anything, i would want to find out which part is most expensive and then cache that one and see if it is good enough.
if your clients are smart, you could also make use of etags, but all of this depends very much on your usecase (as always when it comes to caching).
side note, if you have something like nginx, you can use it as a reverse proxy https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/