text:
Q: props.history.push() doesn't redirect props.history.push("/") doesn't redirect.
I did search for solution for this problem and can't find where is the problem and that drives me crazy.
index.js
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import './index.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { createBrowserHistory } from 'history';
import configureStore from './store/configureStore';
import App from './App';
//import registerServiceWorker from './registerServiceWorker';

// Create browser history to use in the Redux store
const baseUrl = document.getElementsByTagName('base')[0].getAttribute('href');
const history = createBrowserHistory({ basename: baseUrl });

// Get the application-wide store instance, prepopulating with state from the server where available.
const initialState = window.initialReduxState;
const store = configureStore(history, initialState);

//Render app on  "root"
 in index.html
ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
        <App />
    </ConnectedRouter>
  </Provider>,
    document.getElementById('root'));

//registerServiceWorker();

app.js
import React from 'react';
import { Route, Switch } from 'react-router';
import Home from './components/Home';
import Login from './components/Login/Login';
import Counter from './components/Counter';
import FetchData from './components/FetchData';
import { PrivateRoute } from './components/PrivateRoutes/PrivateRoute';

const App = (props) => {

    return (
        <Switch>
            <Route path="/login" component={Login}/>
            <PrivateRoute path="/" component={Home} />
            <Route path='/counter' component={Counter} />
            <Route path='/fetchdata/:startDateIndex?' component={FetchData} />
        </Switch>
        );
}

export default App;

Login.js
import React, { useState } from 'react';
import { withRouter, Redirect, history } from 'react-router-dom'
import { Form, Label, FormGroup, FormControl, Button } from 'react-bootstrap';
import Home from '../Home';

//Login user
function LoginUser(username, password, callback) {
    console.log("Atemt to login..." + " " + username);

    fetch('api/SampleData/Login', {
        method: "POST",
        body: JSON.stringify({
            email: username,
            password: password,
        })
    }).then(response => response.json())
        .then(json =>callback(json))
}

 function Login(props) {

    var logged = false;

    var data = { username: '', password: '', };

    function getUsername(event) {
        data.username = event.target.value;
        console.log(data);
    }

    function getPassword(event) {
        data.password = event.target.value;
        console.log(data);
    }

    function requestCallback(res) {
        if (res[0] === "connected") {

            props.history.push('/');
            console.log(props.history);
        }
    }

    if (logged === true) {

        return (<Redirect to="/" component={Home} />);
    }
     return (

             <Form >
                <FormGroup controlId="formBasicEmail">
                    Email address
                    <FormControl type="email" placeholder="Enter email" onChange={getUsername} />
                </FormGroup>
                <FormGroup controlId="formBasicPassword">
                    Password
                     <FormControl type="password" placeholder="Password" onChange={getPassword} />
                </FormGroup>

                 <Button variant="primary" onClick={() => LoginUser(data.username, data.password, requestCallback)} style={{ margin: '0 auto', display: 'block', width: '100px' }}>
                    Login
                 </Button>
            </Form>

    );
}

export default withRouter(Login);

As you can see Login component is wrapped with withRouter(Login).  console.log(props)  in Login.js file shows that history is passed to props.

A: The problem is that in your PrivateRoute you have a constant variable called userLogged which is initiated with the value false. If the variable is true, the defined component is rendered. If it is false, you redirect ot /login.
The value of userLogged is always false, so you always redirect to /login. I recommend you handle your logged-in state either in your parent component App or through the usage of a store from redux.

A: Use 'history' npm package
1)App.js
import React, { Component } from "react";
import { Route, Router } from "react-router-dom";
import { createBrowserHistory } from "history";

import Dashboard from "./components/dashboard.js ";
import Login from "./components/login.js";
import Profile from "./components/profile.js";
import PrivateRoute from "./privateRoute.js";

export const history = createBrowserHistory();
//refer 'history' for wanted component like profile.js

class App extends Component {
  render() {
    return (
      <Router history={history}>

          <PrivateRoute
            path="/"
            component={Dashboard}
            exact
          />
          <Route path="/login" component={Login} exact />
          <PrivateRoute path="/profile" component={Profile} />

      </Router>
    );
  }
}
export default App;

a)Once you login store some data in local Storage with key "user".
b)Based on this "user" object in localStorage routing will happen in prBivateRoute.js
c)If you want to log out clear localStorage it will navigate into loginPage
2)privateRoute.js
import React from "react";
import { Route, Redirect } from "react-router-dom";

const PrivateRoute = ({ component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props => {
        if (localStorage.getItem("user")!= "") {
          return <Component />;
        }else {
           return <Redirect to={{ pathname: "/login" }} />;
        }
      }}
    />
  );
};

3)profile.js
import React, { Component } from "react";
import { history } from "./App.js";

class Profile extends Component {
  goBack = () => {
    history.push("/");
  };

  render() {
    <button onClick={() => this.goBack()}> back to dashboard </button>;
  }
}

export default Profile;


text:
Q: Subspace of vector space. I have task sound like:
Examine that $ W $ is a subspace of the vector space $M_{3x3} $
$W=({A:A^t=-A}) $
To check it from definition I have to check two conditions.
1) $ \vec u + \vec v \in W $
2) $ \alpha \cdot \vec u \in W $
1)
$B, C $ are matrix 3x3 and $\in W $
$B^t+C^t =(B+C)^t = -A $ and i don't know what i can do next. Could anyone tell me how i can do this task?

A: First Condition:
Two matrices in the subspace are $B$ and $C$.  These satisfy:
$$B^t = -B$$
$$C^t = -C$$
You must show that the sum of the two matrices is also in the subspace:
$$B^t + C^t = -B - C$$
$$(B + C)^t = -(B+C)$$
Which is in the subspace.
Don't compare the matrices to $A$; $A$ is an arbitrary matrix in the subspace used to explain the definition of the subspace.
EDIT:
Second condition:
Let $B$ be in the subspace (that is, $B^t = -B$), and $a$ be an arbitrary scalar.
$$(a \cdot B)^t = a\cdot B^t$$
Because $B^t = -B$:
$$(a \cdot B)^t = a \cdot (-B)$$
$$(a \cdot B)^t = -(aB)$$
Thus $a \cdot B$ is in the subspace.

redpajama_set_name: RedPajamaStackExchange


text:
Q: extracting weighs of relalanced portfolio I am running a portfolio optimization on a series of stocks and I am trying to extract the weights of the rebalanced portfolio.
The problem I am having: instead of getting the weights of the rebalanced portfolio, I am getting 3 dates. The code for the project is down below.
library(ROI)
install.packages("DEoptim")
library(ggplot2)
install.packages("quantmod")
library(quantmod)
library(quantmod)
install.packages("PerfomanceAnalytics")
library(PerformanceAnalytics)
library(PortfolioAnalytics)
library(random)
install.packages("random")
library(random)
library(DEoptim)
install.packages("fPortfolio")
library(fPortfolio)
install.packages("foreach")
install.packages("doParallel")
library(PortfolioAnalytics)

#vector of stocks in my portfolio  of
tickers <- c("FB", "AAPL", "AMZN", "GM", "GOOGL", "SQ", "NVDA","RYAM", "AMAT", "IMMR","SOI","PETS")
#bind porfolio prices
portfolioPrices <- NULL
for(ticker in tickers) {
  portfolioPrices <- cbind(portfolioPrices,
                           getSymbols.yahoo(ticker, from='2003-01-03', periodicity = 'daily', auto.assign=FALSE)[,4])
}
#portfolio returns
portfolioReturns <- na.omit(ROC(portfolioPrices))
print(portfolioReturns)
portf <- portfolio.spec(colnames(portfolioReturns))
portf <- add.constraint(portf, type="weight_sum", min_sum=.99, max_sum=1,01)
portf <- add.constraint(portf, type="box", min=.02, max=.60)
portf<-add.constraint(portf,type="transation_cost", ptc=.001)
portf <- add.objective(portf, type="return", name="mean")
portf <- add.objective(portf, type="risk", name="StdDev",target=.005)

rp<-random_portfolios(portf, 10000, "sample")
#optimize portfolio using the "DEoptim solver"
optPort <- optimize.portfolio(portfolioReturns, portf, optimize_method = "DEoptim", trace=TRUE)

#chart weights of optimized portfolio

chart.Weights(optPort)
summary(optPort)

chart.RiskReward(optPort, risk.col = "StDev", return.col = "mean", chart.assets = TRUE)

rp<-random_portfolios(portf, 10000, "sample")
#rebalance portfolo
opt_rebal <- optimize.portfolio.rebalancing(portfolioReturns,
                                            portf,
                                            optimize_method="ROI",
                                            rp=rp,
                                            rebalance_on="years",
                                            training_period=60,

                                            rolling_window=60)

extractWeights(optPort)
chart.Weights(optPort)
#extract weights of rebalanced portfolio
extractWeights(opt_rebal))

How can I fix this?
Your help will be greatly appreciated.
Thank you.

A: First of all, your code is very messy!
Therefore, while giving you the solution, I also cleaned it.
Here are bullet points that cover all aspects of your question:

*

*Support plugins
Since you are using not only DEoptim solver but also ROI, you need to download the recommended support plugins for ROI:
 install.packages(c("fGarch",
                        "Rglpk",
                        "ROI.plugin.glpk",
                        "ROI.plugin.quadprog",
                        "ROI.plugin.symphony",
                        "pso",
                        "GenSA",
                        "corpcor",
                        "testthat",
                        "nloptr",
                        "MASS",
                        "robustbase")
                      )

*Use of libraries
You should load libraries once and in the correct order since some libraries can mask some functions from each other. Here is the recommended order:
    library(ROI)
    library(ggplot2)
    library(quantmod)
    library(PerformanceAnalytics)
    library(random)
    library(DEoptim)
    library(fPortfolio)
    library(PortfolioAnalytics)
    library(dplyr)

*Use of pipe operator
Notice that there is an additional dplyr library loaded which is needed for piping (%>%), i.e. making your code more efficient and readable!:
#vector of stocks in my portfolio  of
tickers <- c("FB", "AAPL", "AMZN", "GM", "GOOGL", "SQ", "NVDA","RYAM", "AMAT", "IMMR","SOI","PETS")

#bind porfolio prices
portfolioPrices <- NULL
for(ticker in tickers) {
  portfolioPrices <- cbind(portfolioPrices,
                           getSymbols.yahoo(ticker, from='2003-01-03', periodicity = 'daily', auto.assign=FALSE)[,4])
}
#portfolio returns
portfolioReturns <- na.omit(ROC(portfolioPrices))
print(portfolioReturns)

portf <- portfolio.spec(colnames(portfolioReturns)) %>%
  add.constraint(type="weight_sum", min_sum=1, max_sum=1) %>%
  add.constraint(type="box", min=.02, max=.60) %>%
  add.constraint(type="transation_cost", ptc=.001) %>%
  add.objective(type="return", name="mean") %>%
  add.objective(type="risk", name="StdDev",target=.005)

*Removing redundancies
Not sure why you cannot use the previous random portfolio rp which was input to optPort as an input to opt_rebal.
rp<-random_portfolios(portf, 10000, "sample")

#optimize portfolio using the "DEoptim solver"
optPort <- optimize.portfolio(portfolioReturns, portf, optimize_method = "DEoptim", trace=TRUE,
                              rp=rp)

#chart weights of optimized portfolio
chart.Weights(optPort)
summary(optPort)

# chart.RiskReward(optPort, risk.col = "StDev", return.col = "mean", chart.assets = TRUE)

#not sure why you cannot use the previous random portfolio!!
rp<-random_portfolios(portf, 10000, "sample")

*Understanding the use of Risk-Reward plot
There is an error in this function call which I assume is due to the dual objective in your portf as it might prevent you from getting the efficient frontier. Not sure about that; this is not essential but a task for you to explore :-)
# chart.RiskReward(optPort, risk.col = "StDev", return.col = "mean", chart.assets = TRUE)

*Understanding ROI
ROI differs from other back-ends and therefore needs a separate portfolio specification portfolio.spec and portfolio optimisation optimize.portfolio or optimize.portfolio.rebalancing.
Here is one way of implementing it (pay attention to portfolio specification which has no add.objective inside):
portf2 <- portfolio.spec(colnames(portfolioReturns)) %>%
  add.constraint(type="weight_sum", min_sum=1, max_sum=1) %>%
  add.constraint(type="box", min=.02, max=.60) %>%
  add.constraint(type="transation_cost", ptc=.001)

#this optimises based on Sharpe Ratio
optPort2 <- optimize.portfolio(portfolioReturns, portf2, optimize_method = "ROI", trace=TRUE,
                               maxSR=TRUE)

#rebalance portfolo
opt_rebal <- optimize.portfolio.rebalancing(portfolioReturns,
                                            portf2,
                                            optimize_method="ROI",
                                            rp=rp,
                                            rebalance_on="years",
                                            training_period=60,
                                            rolling_window=60)

extractWeights(optPort)
chart.Weights(optPort)

#extract weights of rebalanced portfolio
extractWeights(opt_rebal)

Output:
> extractWeights(opt_rebal)
           FB.Close AAPL.Close AMZN.Close GM.Close GOOGL.Close SQ.Close NVDA.Close RYAM.Close AMAT.Close
2017-12-29      0.6        0.2       0.02     0.02        0.02     0.02       0.02       0.02       0.02
2018-12-31      0.6        0.2       0.02     0.02        0.02     0.02       0.02       0.02       0.02
2019-09-20      0.6        0.2       0.02     0.02        0.02     0.02       0.02       0.02       0.02
           IMMR.Close SOI.Close PETS.Close
2017-12-29       0.02      0.02       0.02
2018-12-31       0.02      0.02       0.02
2019-09-20       0.02      0.02       0.02

You can read the documentation about optimize.portfolio to see what limited type of convex optimization problems it can solve.


text:
Q: 'Element' is an invalid XmlNodeType error when parsing XML file I'm very new to XML parsing and don't really know what I'm doing. I'm trying to parse a file in XML, but have encountered this error:
System.Xml.XmlException: ''Element' is an invalid XmlNodeType.'

Here's the code below:
    Dim settings As XmlReaderSettings = New XmlReaderSettings
    settings.DtdProcessing = DtdProcessing.Parse
    Dim xmlR = XmlReader.Create(jmdictpath, settings)

    Do While xmlR.Read()
        If Not xmlR.IsEmptyElement And xmlR.NodeType = XmlNodeType.Element Then
            MsgBox(xmlR.ReadElementContentAsString)
        End If
    Loop

The error runs on the line MsgBox(xmlR.ReadElementContentAsString). I've tested that the element is not empty, so that shouldn't be a problem.
Then I checked the xmlReader object in QuickWatch, and it looks like what the object is currently trying to read is a whitespace or line return character:

Is there some standard method to handle all cases like this when parsing XML so that whitespace characters don't get picked up as XML tags and confuse the reader?


text:
Q: XSLT sorting by 2 parametres and choosing by the 1st unique and the 2nd highest I had an xls book saved as xml. There I have 1st rows with header and other rows with data.
In xml it looks:
<Row ss:AutoFitHeight="0">
    <Cell><Data ss:Type="String">Header 1 - id</Data><NamedCell
      ss:Name="_FilterDatabase"/></Cell>
    <Cell><Data ss:Type="String">Header 2 - Version</Data><NamedCell ss:Name="_FilterDatabase"/></Cell>
    <Cell><Data ss:Type="String">Header 3 - some data...</Data><NamedCell
      ss:Name="_FilterDatabase"/></Cell>
</Row>
<Row ss:AutoFitHeight="0">
    <Cell><Data ss:Type="String">id001</Data><NamedCell
      ss:Name="_FilterDatabase"/></Cell>
    <Cell><Data ss:Type="Number">1</Data><NamedCell ss:Name="_FilterDatabase"/></Cell>
    <Cell><Data ss:Type="String">blabla</Data><NamedCell
      ss:Name="_FilterDatabase"/></Cell>
</Row>
<Row ss:AutoFitHeight="0">
    <Cell><Data ss:Type="String">id001</Data><NamedCell
      ss:Name="_FilterDatabase"/></Cell>
    <Cell><Data ss:Type="Number">2</Data><NamedCell ss:Name="_FilterDatabase"/></Cell>
    <Cell><Data ss:Type="String">blabla</Data><NamedCell
      ss:Name="_FilterDatabase"/></Cell>
</Row>
<Row ss:AutoFitHeight="0">
    <Cell><Data ss:Type="String">id002</Data><NamedCell
      ss:Name="_FilterDatabase"/></Cell>
    <Cell><Data ss:Type="Number">1</Data><NamedCell ss:Name="_FilterDatabase"/></Cell>
    <Cell><Data ss:Type="String">blabla</Data><NamedCell
      ss:Name="_FilterDatabase"/></Cell>
</Row>

So I have two main fields - Header 1 and Header 2, first contains id (Not unique!!!) the second - version or edition.
How is it looks in Excel:
Number  Version
A001    1
A001    6
A002    2
A002    3
A003    1

I need to process all unique id's with the maximum version!
Here I would like to get
A001    6
A002    3
A003    1

My xslt code is:
 <xsl:template match="orig:Table" name ="Table">
    <xsl:variable name="Id" select ="'Number'"/>
    <xsl:element name="Declarations">
      <xsl:for-each select="orig:Row">
        <xsl:sort select="orig:Cell[1]/orig:Data" data-type="text" order="ascending"/>
        <xsl:sort select="orig:Cell[2]/orig:Data" data-type="number" order="descending"/>
        <xsl:if test="$Id!=orig:Cell[1]/orig:Data">
          <xsl:call-template name="Row"> <!--Here in template "Row" all further processing will be done-->
        </xsl:if>

      </xsl:for-each>
    </xsl:element>
  </xsl:template>

At first I'm sorting them to get the list like:
Number  Version
A001    6
A001    1
A002    3
A002    2
A003    1

Then I want to save every 1st header value and compare it to itself in the next row - if the value is the same, that means that it is the same record with older version and we skip it. But if value changes - this mean that we have a new record with maximum version and we should take it.
Eg:
"Number" != A001    6 => we take this
A001 = A001 1 => skip
A001 != A002     3 => we take this
and so on

It would be easy to do if I could use inside "IF" construction like
variable name="Id" := orig:Cell[1]/orig:Data

But it is impossible here!
Please Help!

A: This is basically a grouping problem - you are trying to group rows by their first cell value, then produce one output row per group from the latest version within that group.  The standard approach in XSLT 1.0 is called Muenchian grouping and involves defining a key that groups related nodes and a then using trick with generate-id to pull out just the first node in each group:
 <xsl:key name="rowById" match="orig:Row" use="orig:Cell[1]/orig:Data" />

 <xsl:template match="orig:Table" name ="Table">
    <xsl:variable name="Id" select ="'Number'"/>
    <xsl:element name="Declarations">
      <!-- Muenchian grouping - one "iteration" per unique idNNN value -->
      <xsl:for-each select="orig:Row[
           generate-id() = generate-id(key('rowById', orig:Cell[1]/orig:Data)[1])]">
        <!-- sort groups by ID -->
        <xsl:sort select="orig:Cell[1]/orig:Data" data-type="text" order="ascending"/>

        <!-- for-each over the members of this group -->
        <xsl:for-each select="key('rowById', orig:Cell[1]/orig:Data)">
          <!-- find the maximum version value within this group -->
          <xsl:sort select="orig:Cell[2]/orig:Data" data-type="number" order="descending"/>
          <xsl:if test="position() = 1">
            <xsl:call-template name="Row"> <!--Here in template "Row" all further processing will be done-->
          </xsl:if>
        </xsl:for-each>
      </xsl:for-each>
    </xsl:element>
  </xsl:template>


text:
Q: Angular i18n $localize - template literal with expressions I am having so much trouble getting this syntax to translate - Angular 13.0.02 .
My two resources are:
https://angular.io/api/localize/init/$localize
https://lokalise.com/blog/angular-i18n/

As per the Angular docs:
 Naming placeholders
 If the template literal string contains expressions, then the expressions will be automatically associated with placeholder names for you.

For example:

  $localize `Hi ${name}! There are ${items.length} items.`;

  will generate a message-source of Hi {$PH}! There are {$PH_1} items.`

And providing meaning, descrip, and ID:
$localize`:meaning|description@@id:source message text`;

$localize`:meaning|:source message text`;
$localize`:description:source message text`;
$localize`:@@id:source message text`;

This example from lokalise.com works:
const company = "Google";
const created_by = $localize`Created by ${company}`;

in my XLIF translation file:
   <trans-unit id="3990133897753911565" datatype="html">
     <source>Created by <x id="PH"/></source>
     <target>Creado por... <x id="PH"/></target>
   </trans-unit>

This DOESN'T WQRK:
Yet when I try to reproduce the same syntax with another i18 term - it DOESN'T WORK. It only pulls the English phrase, not the Spanish one.
 const company = "Google";
 const createdByCompany = $localize`Created by this person ${company}`;

<trans-unit id="spanishTest123" datatype="html">
    <source>Created by this person <x id="PH"/></source>
    <target>Creado por esta persona <x id="PH"/></target>
</trans-unit>

FYI: for the example that does work, if I REMOVE id="3990133897753911565", then it does NOT pull that translation. So clearly this id makes it happen - yet in my 2nd example I cannot get it to work.
*** UPDATE ***
Using the Angular extract tool produces the XLF file in the required xml format (it parses all i18n tags in your html temples, and the $localize calls in your component code). Run in your app's root dir as follows  ng extract-i18n --output-path src/locale - then check the messages.xlf file in the locale folder.

A: So as per the docs, the "pre-pending it with a colon" syntax did work - https://angular.io/api/localize/init/$localize
const msg = $localize`:Password Reset Modal|Min num of chars@@passwordNumChars:Must be at least ${setting.SettingValue}:minLen: characters long.`;

Notice how I updated the trans-unit "id" attrib in the xlf - i.e. my custom ID is "passwordNumChars".

<trans-unit id="passwordNumChars" datatype="html">
    <source>Must be at least <x id="minLen" equiv-text="setting.SettingValue"/> characters long.</source>
    <target>Debe contener al menos <x id="minLen" equiv-text="setting.SettingValue"/> caracteres.</target>
    <note priority="1" from="meaning">password edit modal</note>
</trans-unit>

One final note: if you have the $localize function setup in your ts code - but you can't figure out the xlf format - you can use ng extract-i18n --output-path src/locale from a cmd line to generate the appropriate xlf file.
Then just copy/paste the section you need into your locale file; also perhaps into whatever translation software you're using as the source of truth (i.e. poedit.com to store all i18n terms).


text:
Q: Ruby on Rails 4.x, nested models, best practise Asking for best practice to list nested attributes in show action when you need to paste them in various places..
I have two models: Product & ProductDetail, ProductDetails belongs to Product, Product has_many ProductDetails. Within forms and nested renders it works like a charm, no issues (especially after RailsCast 196/197 by Ryan (thanks boet!)
Now, I need to issue view for my product. Basically it is just a product in commerce.
So in my controllers I have regular things like
@product = Product.find ...
@product_details = @product.product_details.build

When in show action view
=@product.title
=@product.price
=@product.sku
    -@product_details.each do |d|
=d.attribute1
=d.attribute2

... some other view details here..

    -@product_details.each do |d|
=d.attribute3
=d.attribute3

As you can see I put loops into view several time as I need show them in various places.
I wonder to know what is best practice (may be arrays make sense for here), please suggest.
I'am planning to extend page functionality by using radio buttons and jQuery events for changing (i.e. price) and values of certain field, which at the end changes price and order detail.
Would be great to get some good reading / example of rails + js combination specifically for nested models and its attributes.. the other thing is that I am planning to build number of nested models around main product and show them / update / edit etc based on client behavior. Is there any best practice on number of nested models per model ?

A: I'm sure you probably found this eventually - but just to touch up on this one ...
Yes, you want arrays passing to partials using the 'render' command to keep it 'DRY'.  This allows you to reuse the fields in all sections you want with minimal hassle, per the Ruby Way...check the tutorial on partials/layout for views too(Link).  I've never read the advanced pattern book - and things might have changed in the last year.  I know a bunch of people randomly suggest using Cocoon with simpleForm, sometimes HAML comes up too to replace ruby's *.erb partial rendering.
You're missing the second part he did ... very helpful to me was the additional update did #403: Dynamic Form.  Specifically he calls for rending by the type of checkbox which gives you a loading checkbox type ... it's dynamic partials loading...which is the answer on how to best repeat for each of these in a loop.
app / views / products / _form.html.erb
  <%= f.fields_for :properties, OpenStruct.new(@product.properties) do |builder| %>
    <% @product.product_type.fields.each do |field| %>
      <%= render "products/fields/#{field.field_type}", field: field, f: builder %>
    <% end %>
  <% end %>


text:
Q: FakeHttpServer quebra ao atualizar para o Jetty 9 Eu estou migrando uma aplicação que usava o Jetty 7.4.5.v20110725 para o Jetty 9.3.0.M2, usando o Maven. Eu já atualizei o javax.servlet-api para a versão 3.1.0.
Mas, eu estou utilizando o FakeHttpServer versão 0.3.0 para testes, e no momento não existe uma versão mais nova. Ele usa a classe org.eclipse.jetty.server.nio.SelectChannelConnector que costumava existir até o Jetty 8.x, mas não existe mais no Jetty 9.
Neste momento, o meu projeto quebra em tempo de execução com um NoClassDefFoundError por causa da classe removida do Jetty que o FakeHttpServer tenta usar, me impedindo de completar o upgrade do Jetty. Como posso consertar isso?
Nota: isto também foi postado no StackOverflow em inglês: https://stackoverflow.com/q/30309677/540552

A: Tal como respondido em inglês pelo Joakim Erdfelt no Stack Overflow em inglês, a única saída é atualizar o FakeHttpServer. Seja convencendo os autores originais a fazê-lo, ou seja fazendo isso eu mesmo.
Fonte: https://stackoverflow.com/a/30311559/540552


text:
Q: Conditional logic for coding questions? If the user typed in 'N' for no, how would you avoid the extra cost of $50 and skip asking for the height and width to calculate the surface area, and carry on with the rest of the code? Bare in mind that I haven't written the questions after the code; if the user typed 'Y' for Yes, then the $50 will be added and the program will ask for the width and height of each wall in the room.
total_surface_area = 0
number = int(input("Number of rooms to paint")
print("\n***ROOM DETAILS***")
for room in range(number):
    room_name = input("\n\nPlease enter the name of the room:")
    wall_number = int(input("Number of walls in the room:"))
    wallpaper = input("\nWould you like to remove the paint? (Y for Yes/N for No). If yes, $50 will be charged per room:")

A: You were probably a bit too vague for us to determine what the most elegant solution to your problem is, but I suspect you were looking for the continue and break statements. You can find an explanation here.
This might illustrate how you can use both statements:
total_surface_area = 0
# You were missing a parenthesis in the following line.
number = int(input("Number of rooms to paint"))
print("\n***ROOM DETAILS***")
for room in range(number):
    print('=== details of room number '+str(room)+' ===')
    room_name = input("\n\nPlease enter the name of the room:")
    wall_number = int(input("Number of walls in the room:"))

    print("\nWould you like to remove the paint? (Y for Yes/N for No). If yes, $50 will be charged per room:")
    while True:
        buffer = input()
        if buffer == 'Y':
            wallpaper = True
            break
        elif buffer == 'N':
            wallpaper = False
            break
        else:
            print('please anser "Y" or "N"')

    if wallpaper:
        print('I will now ask many more questions.......')
        # continue asking questions ...
    else:
        # move to the next room
        continue

A: This is probably what you are looking for:
from distutils.util import strtobool
total_surface_area = 0
extra_cost = 0
number = int(input("Number of rooms to paint")
print("\n***ROOM DETAILS***")
for room in range(number):
    room_name = input("\n\nPlease enter the name of the room:")
    wall_number = int(input("Number of walls in the room:"))
    wallpaper = input("\nWould you like to remove the paint? (Y for Yes/N for No). If yes, $50 will be charged per room:")
    if strtobool(wallpaper):
        extra_cost += 50
        dimensions = []
        for wall in range(wall_number):
            dimensions.append(input("Please input wall dimensions..."))

    ...


text:
Q: Checkbox list - dynamic list C#/XAML I have 3 tables
User:
  id
  name

Preference:
  id:
  title:

UserPreferences:
  user_id
  preference_id

How to create a view model for hold data and create a form like this?
New User

Name
|------------|
|textbox     |
|------------|

Your Preferences
[ ] Preference1
[ ] Preference2
[ ] Preference3
..
[ ] PreferenceN

A: I believe, it should look something like this:
metacode with C#
// You can realize INotificationChanged here too if you need
sealed class Preference
{
  public Preference(string name, bool isSelected)
  {
    Name = name;
    IsSelected = isSelected;
  }

  public string Name { get; private set; }
  public bool IsSelected { get; set; }
}

sealed class User : INotificationChanged
{
  private ObservaleCollection<Preference> viewPreferences;

  public event PropertyChangedEventHandler PropertyChanged;

  public User(PreferenceCollection preferences)
  {
    PreferenceTitle = preferences.Title;
    // put info to collection
  }

  public ObservaleCollection<Preference> Preferences
  {
    get { return preferences; }
  }

  // You can remove set if you don't want to set it directly
  public UserId { get; set; }
  public UserName { get; set; }
  public PreferenceTitle { get; private set; }

  // Use it to update data in view
  protected void OnPropertyChanged(string name)
  {
      PropertyChangedEventHandler handler = PropertyChanged;
      if (handler != null)
      {
          handler(this, new PropertyChangedEventArgs(name));
      }
  }
}

it is just a mockup of a model. Of course, you need to add validation, save data logic and to bind properties to xaml form


text:
Q: Node.js falsely claims port is in use I'm trying to run node.js http server and fail as node.js thinks the port is in use. However, checking the port list with netstat shows that the port is free. Trying any other port also results in the same error:
var activePort = +process.argv[2];
var serverEndpoint = http.createServer(function(req, res) {
});
serverEndpoint.listen(activePort);

{ [Error: listen EADDRINUSE :::30009]
  code: 'EADDRINUSE',
  errno: 'EADDRINUSE',
  syscall: 'listen',
  address: '::',
  port: 30009 }

I am however running multiple same processes (just with a different port number) using forever - I'm thinking this may have some relation to the error.

A: Apparently, the ports were really in use. My system was heavily in use so most of my ephemeral port range was being actively used. I was also trying to create node.js ports in my ephemeral port range. Because of that Node.js would randomly fail, but netstat would not show the port being in use anymore after just a few seconds.
I adjusted my ephemeral port range (sysctl net.ipv4.ip_local_port_range) and Node no longer complains about ports being in use.


text:
Q: Custom Dropdown menu not working with links I'm trying to make a custom menu using a tutorial I found.
The problem I'm running into is not the implementation, but something that stops me from clicking through links. When, I have the menu "opened" and when I click on a say link, it just closes the menu and for a quick second I see it highlight the whole box instead of the link.
Here are a few screenshots. You can hover over the links (they turn purple when hovered), but when you click on an individual link it tends to just click out of the whole menu instead of sending you to the said page. But when, I hover over it I can see that it is showing the link in the bottom left hand corner of my browser. I just can't seem to figure out what is happening with the click out instead of the url sending you to the page.
http://cl.ly/image/0S2F2c3h3g1o
(hover screen shot)
http://f.cl.ly/items/3P1h27323B203E2J0N41/clickout.png
(clickout)
When I try to click on any link, I just get this blue box, and it closes the menu instead of sending you to the linked page.
This is the HTML that I have hooked up

ABOUT

WORK

NOTES

This is the Javascript.

        function DropDown(el) {
            this.dd = el;
            this.opts = this.dd.find('ul.dropdown > li');
            this.val = '';
            this.index = -1;
            this.initEvents();
        }
        DropDown.prototype = {
            initEvents : function() {
                var obj = this;

                obj.dd.on('click', function(event){
                    $(this).toggleClass('active');
                    return false;
                });

                obj.opts.on('click',function(){
                    var opt = $(this);
                    obj.val = opt.text();
                    obj.index = opt.index();
                });
            },
            getValue : function() {
                return this.val;
            },
            getIndex : function() {
                return this.index;
            }
        }

        $(function() {

            var dd = new DropDown( $('#mobmenu') );

            $(document).click(function() {
                // all dropdowns
                $('.dropdown-menu').removeClass('active');
            });

        });

    </script>

And the CSS.
#mobile-menu {
    width: 320px;
}
.dropdown-menu {
    background: #050607 url(images/menu_closed.png) no-repeat center top;
    border: none;
    color: #FFF;
    cursor: pointer;
    height: 50px;
    font-weight: bold;
    margin-top: 17px;
    outline: none;
    position: fixed;
    -webkit-appearance: none;
    width: 320px;
    z-index: 9999;
}
.dropdown-menu::after {
    content: "";
    width: 0;
    height: 0;
    position: absolute;
    right: 16px;
    top: 50%;
    margin-top: -6px;
}
/* ACTIVE STATE */
.dropdown-menu .dropdown {
    background: #050607;
    height: 1000px;
    list-style: none;
    overflow: hidden;
    pointer-events: none;
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    opacity: 0.0;
}
.dropdown-menu .dropdown  li {
    position: relative;
    top: 10px;
    z-index: 99;
}
.dropdown-menu .dropdown li a {
    border-top: 1px solid #1f1f1f;
    color: #FFF;
    display: block;
    font-family: 'Open Sans', sans-serif;
    font-size: 30px;
    font-weight: 200;
    letter-spacing: 8px;
    pointer-events: visible;
    padding: 15px 25px 15px 25px;
    text-align: center;
    text-decoration: none;
    z-index: 9999999999999999999999;
}
.dropdown-menu .dropdown li:nth-child(5)  {
    font-size: 15px;
    font-weight: 100;
    letter-spacing: 2px;
    text-align: center;
}
.dropdown-menu .dropdown li:hover a { background: #050607; color: #605e90; }
.dropdown-menu.active .dropdown {
    -moz-animation: fadein .3s linear;
    -webkit-animation: fadein .3s linear;
    -ms-animation: fadein .3s linear;
    animation: fadein .3s linear;
    pointer-events: auto;
    opacity: 1.0;
    z-index: 999999 !important;
}
.dropdown-menu.active:active {
    pointer-events: auto;
}
.dropdown-menu.active::after {
    border-color: #000;
    margin-top: -3px;
}
.dropdown-menu.active {
    background: #050607 url(images/menu_open.png) no-repeat center top;
    outline: none;
}

Thanks! :3

A: After the obj.opts click event handler fires, the obj.dd click event handler will also fire. To prevent this, call the stopPropagation function of the event object passed to the handler.
See here for a working example: http://jsfiddle.net/hwTUZ/1/


text:
Q: iPad Apps with nice transitions/animations I hope I'm right here, if not please point me to another location to ask my question ;-)
I need to assemble a small showcase (research for a project at work) of Apps for the iPad that have nice view-to-view transitions / animations of objects. I already looked around on Google, and some Blogs and found some stuff, but I'm still missing the "Killer App" that has awesome transitions.
Anyone in the know of Apps that have what I'm looking for?
This is what I already have:

*

*A concept that features a nice navigation (http://momo.brauchtman.net/2011/09/16/ipad-app-concept-based-on-a-fluid-layout/)

*Jamie Oliver Recipes

*Flipboard

*Pulse News

*Volkswagen Das. (DE)

Rules

*

*One app per answer.

*Use this format for the first and second lines of your answer:
## [app name](link to website)
[App Store](link to appstore) (price in usd)

*Include a short description.

*Check for duplicates before adding new answers.

Any addition to this list is appreciated. If you just have a video that shows a concept, I'm also fine with that, must not be a released App.

A: Try Jamie Olivers remarkably well designed 20 Minute Meals app:
Also, in the first iPad year, Flipboard was awarded best app, and it has some very nice transitions.

A: Check out:

*

*Apple Trailers (recommended)

*Bloomberg TV

*Wired Magazine: Free interactive demo articles can be downloaded within the app if you are not a subscriber.

*Weather HD

*Design Scene

*The Fantastic Flying Books of Mr. Morris Lessmore:
More interaction than navigation but worth mentioning because of the transitions.

*Appstream

A: If you're looking for some really smooth animations in games, I'd highly recommend checking out Gesundheit! by Konami Digital. Some really good animations for characters in the game. Hope this helped! :)


text:
Q: Reference collapsing under C++03 I need to create a predicate from bound member function, so I wrapped it in a boost::function<bool(SomeObject const &)>. That seems to be fine and everything, but I also needed to negate it in one case. However
boost::function<bool(SomeObject const &)> pred;
std::not1(pred);

does not compile under MSVC++ 9.0 (Visual Studio 2008), complaining that reference to reference is invalid:
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\functional(213) : warning C4181: qualifier applied to reference type; ignored
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\functional(213) : error C2529: '_Left' : reference to reference is illegal

The problem is that boost::function defines the argument_type as SomeObject const & and the std::unary_negate<_Fn1> instantiated by std::not1 internally tries to use const typename _Fn1::argument_type& and compiler rejects it because T::argument_type is already a reference. I am certain that that should compile under C++11, but this is old compiler that is C++03 only. So I'd like to know who's fault it is:

*

*the compiler's, because it should collapse the reference (apparently not),

*the standard library's, because it should be prepared to handle functors taking references (apparently not, because the specification defines unary_negate with const typename Predicate::argument_type& x argument),

*boost's, because argument_type shouldn't be reference even when the actual argument is or

*mine, because boost::function shouldn't be used with reference arguments?

A: The fault is certainly not Boost's; boost::function is basically just std::function, with all the same semantics. And boost::functions with reference parameters work fine, too. You just can't use them with std::not1 or the rest of the <functional> stuff.
C++11's reference-collapsing makes std::not1 work the way you would think it ought to. The way std::not1 was specified in C++03 couldn't possibly work without reference-collapsing — except in implementations where the implementors did a little bit of creative interpretation rather than slavishly following the letter of the Standard.
It's possible to make std::not1 work in C++03 by adding a specialization of std::unary_negate for predicates with reference argument_types, but neither libc++ nor libstdc++ has done so.
But you know who has? Boost! If you just change your code to use boost::not1 everywhere you currently use std::not1, everything will work fine. Basically, think of the boost namespace as if it were a C++11-compliant version of std; anything that works in C++11's std namespace probably works in C++03's boost namespace.

Caveat, hopefully off-topic: The Clang compiler on my Macbook (Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)) silently collapses references even in -std=c++03 mode, so that
typedef const int& ref;
typedef const ref& ref2;

produces no error. When you test your C++03 code, make sure you're not using a compiler with this misfeature.


text:
Q: Calculate the first homology group of $P^2\#T$, that is $H_1(P^2\#T)$ I've already found that the fundamental group of the connected sum $P^2\#T$, by the labelling scheme $aabcb^{-1}c^{-1}$, to be $F_3/<aabcb^{-1}c^{-1}>$. How would I find the first homology group? The first homology group is defined to be:
$
H_1(X) = \pi_1(X,x_0)/[\pi_1(X,x_0),\pi_1(X,x_0)]
$.
I believe I have to use the following theorem:
Let $F$ be a group; let $N$ be a normal subgroup of $F$; let $q$: $F \to F/N$ be the projection. The projection homomorphism $P: F \to F/[F,F]$ induces an isomorphism $\phi: q(F)/[q(F),q(F)] \to p(F)/p(N)$. But I can't seem to figure out a nicer representation for the first homology group with this theorem.

A: As Lee Mosher has pointed out in the comments, the correct representation for the fundamental group should be $F_3/\langle aabcb^{-1}c^{-1} =1\rangle$, or in other words, $\langle a, b, c|aabcb^{-1}c^{-1} = 1\rangle$.
$H_1$ is precisely abelianization of this group, and the abelianization just attaches the relators $[a, b] = [b, c] = [a, c] = 1$ to the presentation, i.e.,  $\langle aabcb^{-1}c^{-1} = [a, b] = [b, c] = [a, c] = 1\rangle$. As $[b, c] = 1$, $aabcb^{-1}c^{-1}$ reduces to $aa$. Thus, your group is $\langle a, b, c | a^2 = [a, b] = [b, c] = [a, c] = 1\rangle$ which is isomorphic to $\Bbb Z/2\Bbb Z \oplus \Bbb Z^2$
Hence, $H_1(P^2 \# T) \cong \Bbb Z^2 \oplus \Bbb Z/2\Bbb Z$.


text:
Q: Class member is not initialized in derived class using TypeScript I'm trying to define some fields of derived class in declarative way, like this (consider this is minimal code example):
abstract class Car {
  model: string;

  constructor() {
    // some initializing
    console.log(`Car model: ${this.model}`);
  }
}

class Dodge extends Car {
  model = 'Dodge';

  constructor() {
    super();
  }
}

const dodge = new Dodge();

The problem is that model seems to be not initialized yet when I try to access it from constructor, so I get:
Car model: undefined
How to do it in a correct way?


text:
Q: I am unable to ask questions, and I can't see why I am banned? I know very well that if a user posts a significant number of low quality questions or questions that do not fit the standards then they will be blocked from asking questions.
And the block is not fixed about how much time it will take to be able to ask a new question. Also it is not removed after making a request for removal.
I could not find a reason for my ban because:

*

*I have asked my last question on June 18 - It has been close to a month from then.

*The question which I asked did not get a downvote - though it also not received any greater response

*Don't know exactly whether the answer section is considered for banning a user for asking question but in the answering section as well I have not received any downvotes for an answer; also, none have been deleted.
It is quite surprising to have been banned like this. Is there any reason to be banned like this ?

A: Deleted questions also count towards the criteria for a question ban (keep in mind I do not know the exact algorithm, I've only seen instances where a user claims he is Q-banned and correlated that to the state of their questions).
In your case, you have two deleted questions which would still count, even though they can never be upvoted (because they're deleted):

*

*javascript works fine with IE but not with firefox and Chrome

*I want to show my websites visitor the flag of there country when they login
(titles pasted from the questions)
For some of your other questions, they have downvotes, and this counts towards what would induce a question ban.
My advice to you is to follow the advice listed here, and work to improve your deleted questions and get them undeleted.

A: OK, based on the comments and other meta answers, I see only two possible solutions in this case:

*

*You were either banned by mistake (which I personally doubt - nothing against you)

*or as the above suggestions from comments - you (or someone else on your network) have been posting extremely poor questions (possibly deleted now).

I cannot find any other reasonable cause for your account to be banned.
What I would like to see is some sort of history print out related to your IP address.
What I recommend you to do (in case you're not guilty) is to follow the recommendations in  Meta Stack Overflow question What can I do when getting "Sorry, we are no longer accepting questions/answers from this account"?.


text:
Q: Using ASP.Net Identity in MVC 4 I've been reading about the new auth stuff in the upcoming versions of ASP.net: http://blogs.msdn.com/b/webdev/archive/2013/06/27/introducing-asp-net-identity-membership-system-for-asp-net-applications.aspx
I'm creating a new ASP.net MVC 4 project in visual studio 2012 and I'd like to use the new auth bits if I can. Is this possible?
I'm reading code and trying to wrap my head around this new API. But in the meantime, what steps are involved to get going?

A: It should be doable, first you basically want to install the 3 packages:
Microsoft.AspNet.Identity.Core
Microsoft.AspNet.Identity.EntityFramework
Microsoft.AspNet.Identity.Owin

You would then need to pull in the associated Owin packages as well:
Owin
Microsoft.Owin
Microsoft.Owin.Security
Microsoft.Owin.Security.Cookies
Microsoft.Owin.Host.SystemWeb

And you would then need to hookup Owin with something like this:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(WebApplication19.Startup))]
namespace WebApplication19
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
                // Enable the application to use a cookie to store information for the signed in user
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    LoginPath = new PathString("/Account/Login")
                });
                // Use a cookie to temporarily store information about a user logging in with a third party login provider
                app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        }
    }
}

You will also have to remove/turn off all of the old membership/forms auth in your app, and switch to using the new identity APIs.


text:
Q: Error when comparing two DateTime objects in Ruby on Rails I'm comparing two DateTime objects (at least I think I am, they look slightly different in the console output below).
p DateTime.now
p current_user.created_at #schema.rb states that this is a datetime field
difference = DateTime.now - current_user.created_at
p difference

Console output
Mon, 04 Oct 2010 22:56:32 +1000
Sat, 14 Aug 2010 20:51:08 EST +10:00

Error (on the difference = DateTime.now - current_user.created_at line)
expected numeric or date

What am I doing wrong? Thanks for reading.

A: Try Time.zone.now (http://railsapi.com/doc/rails-v3.0.0/classes/ActiveSupport/TimeWithZone.html).


text:
Q: Installing boot-repair 64 bit on my computer I recently installed ubuntu in my computer, once it installed it was unable to boot windows saying that it was crashing due to the modifications the computer recently went through, then i heard about boot-repair which i also installed on my computer but now its telling me that I need the 64 bit version which I already downloaded and wrote it on a CD, but when i try to run the program both through the cd and just the downloaded file it never opens or starts running, any comments?
Thank you for your time.

A: Have you tried using a live cd and installing the boot-repair again?
Or if its not working you can download the iso image file of the boot-repair here and burn it to a disk or use UnetBootIn to make it bootable using a usb drive.


text:
Q: Elements briefly disappear and reappear on Chrome 77 I have a tabbed UL that briefly disappears on Chrome 77 when li > a is clicked. When it reappears it appears behind the element below it (almost like it literally disappeared from the DOM and then the element below it moved in it's place or something)
Here are some notes:

*

*If you reload the page the problem doesn't generally occur

*It only happens if you navigate to the page from somewhere else

*If you inspect any element and uncheck any css property on the page the problem immediately corrects itself

I'm using suitecommerce which I don't have full control over the source code. And if you know anything about Suitecommerce I can't really rely on their developers to fix anything in a timely manner.
To reproduce the problem:
Here's an example page:
https://www.1800cpap.com/airfit-p30i-nasal-pillow-cpap-mask-by-resmed
Once you land on the page, scroll down to the tabbed section and click any tab. If you don't see the problem you might have to navigate away from the page and back to it OR you can navigate to any product page. Once you see the problem inspect any element, uncheck any css property and the problem will be fixed instantly. It only happens on Chrome 77.
I'm happy to provide code but I'm honestly not sure where to even start. The platform is built using backbone.js
Any thoughts would be welcomed.

A: The issue comes from your tabs list that has height 0. Why? => read here
This code should fix it:
ul.product-details-information-content-tabs {
    float: left;
    width: 100%;
    margin: 0;
}


text:
Q: apache node js socket.io error connection refused There is a php-file on apache:
<script src="/../node_modules/socket.io/client-dist/socket.io.js"></script>

let socket = io.connect( 'http://localhost:3000' );

socket.on('update', function updateData(sounds) {
    console.log(sounds);
});

and node js in same directory
let http = require('http');
let express = require('express');
let path = require('path');
let socketIO = require('socket.io');
let app = express();
let server = http.Server(app);
let io = socketIO(server);

app.set('port', 3000);

server.listen(3000, function() {
   console.log('listening on *:3000');
});

io.on('connection', function(socket) {
   console.log('A user connected');

   socket.on('disconnect', function() {
      console.log('A user disconnected');
   });

});

browser throws an error: GET http://192.168.100.31/socket.io/?EIO=4&transport=polling&t=NxOsf3z 404 (Not Found)
if replace let socket = io.connect( 'http://localhost:3000' )
on
let socket = io.connect( 'http://192.168.100.31:3000' );
browser will give another error: Access to XMLHttpRequest at 'http://192.168.100.31:3000/socket.io/?EIO=4&transport=polling&t=NxOt0X0' from origin 'http://192.168.100.31' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

A: Just had to replace
let socket = io.connect( 'http://localhost:3000' );

with
let socket = io.connect( 'http://192.168.100.31:3000/' );


text:
Q: How does expansion of the macro parameters work in c++ I just noticed an interesting thing about the expansion of the macro parameters in C++.
I defined 4 macros; 2 of them turn given parameter into string and another 2 try to separate 2 arguments. I passed them argument with macro which expands into , and got the following results:
#define Quote(x) #x
#define String(x) Quote(x)
#define SeparateImpl(first, second) first + second
#define Separate(pair) SeparateImpl(pair)
#define comma ,

int main(){
Quote(1 comma 2);  // -> "1 comma 2"
String(1 comma 2); // -> "1 , 2"
SeparateImpl(1 comma 2); // -> 1 , 2 + *empty arg*
Separate(1 comma 2);     // -> 1 , 2 + *empty arg*
return 0;
}

So, as we see macro String turned into "1 , 2", that means macro comma had been unpacked first. However, macro Separate turned into 1 , 2 + **empty arg**, that means macro comma hadn't been unpacked first and I wonder why? I tried this in VS2019.

A: #define Quote(x) #x
#define String(x) Quote(x)
#define SeparateImpl(first, second) first + second
#define Separate(pair) SeparateImpl(pair)
#define comma ,

Macro invocation proceeds as follows:

*

*Argument substitution (a.s), where if a parameter is mentioned in the replacement list and said parameter does not participate in a paste or stringification, it is fully expanded and said mentions of the parameter in the replacement list are substituted with the result.

*Stringification

*Pastes

*Rescan and further replacement (r.a.f.r.), where the resulting replacement list is rescanned, during which the macro's name is marked as invalid for expansion ("painted blue").

Here's how each case should expand:
Quote(1 comma 2)

a.s. no action (only mention of parameter is stringification).  Stringification applies.  Result: "1 comma 2".
String(1 comma 2)

a.s. applies; yielding Quote(1 , 2).  During r.a.f.r., Quote identified as a macro, but the argument count doesn't match.  This is invalid.  But see below.
SeparateImpl(1 comma 2)

Invalid macro call.  The macro is being invoked with one argument, but it should have 2.  Note that comma being defined as a macro is irrelevant; at the level of macro invocation you're just looking at the tokens.
Separate(1 comma 2)

a.s. applies; yielding SeparateImpl(1 , 2).  During r.a.f.r., SeparateImpl is invoked... that invocation's a.s. applies, yielding 1 + 2.
I tried this in VS2019.
I could tell from a glance it was VS something before 2020, where the walls tells me they're finally going to work on preprocessor compliance.  VS in particular seems to have this strange state in which tokens with commas in them nevertheless are treated as single arguments (it's as if argument identification occurs before expansion but continues to apply or something); so in this case, 1 , 2 would be that strange thing in your String(1 comma 2) call; i.e., Quote is being called with 1 , 2 but in that case it's actually one argument.


text:
Q: Can I have multiple "categories" on one connection? I'll be designing a SPA with Angular 6 and .netcore 2 as a backend API. I'm going to need a socket implementation for live data streaming and charting purposes.
I have a page that requires 3 different data types "live streamed" and my question is - can I do this with one websocket connection? As far as I know, I think that there is a way to create some kind of a queue in the connection or something like a substream, so I can have something like the following:
socket = new WebSocket(url);
socket.on('dataOne', () => { // proccess here }
socket.on('dataTwo', () => { // proccess here }
socket.on('dataThree', () => { // proccess here }

I'm wondering if this is possible and if it is, can you advise me on a lib that I can use for the Client and the API?
I've researched libs like SignalR for C# and Substream, but I'm not completely sure. All kinds of advises and explanations are appreciated!

A: There are existing SignalR clients for both JavaScript and C#. You should use those. Other than that, I'm not honestly sure what you're talking about. You don't need separate hubs, if that's what you mean. Ultimately, SignalR is really pretty simplistic: you simply send a message and the client binds to that message type and does something when it receives it. The reverse process is largely the same: the client simply "invokes" some method defined on your hub, which then does something.
As such, you can bind to pretty much anything client-side, and the server just needs to send that particular message to cause something to happen. For example:
let connection = new signalR.HubConnectionBuilder()
    .withUrl("/myhub")
    .build();
connection.on("dataOne", data => { ... });
connection.on("dataTwo", data => { ... });
connection.on("dataThree", data => { ... });
connection.start().catch(err => console.error(err.toString()));

Then, server-side:
 await _hub.Clients.All.SendAsync("dataOne", data);

A: you should keep the connection to one only and use multiple proxies for your categories.
something like this
var contosoChatHubProxy = connection.createHubProxy('ContosoChatHub');
contosoChatHubProxy.on('addContosoChatMessageToPage', function(userName, message) {
    console.log(userName + ' ' + message);
});

var categoryOneHubProxy = connection.createHubProxy('categoryOne');
var categoryTwoHubProxy = connection.createHubProxy('categoryTwo');

for detail refer


text:
Q: LinkedIn API 403 - "Access to posting shares denied" I'm developing a PHP function to automatically share new articles on Linkedin's user feed, on my company's framework. Authentication works, so tokens are working (I can get my first and last name from LinkedIn at the time of sharing), but I keep getting a 403 error "Access to posting shares denied" in the POST result when sharing an article.
In my app's parameters "r_basicprofile" and "w_share" are checked. But I re-add these scope parameters when I create the authorization URL (I'm using linkedin-php by splashmedia to connect). I'm also connected as an user with both admin and developer privileges on my LinkedIn app. But I still cannot share an article on my own feed.
Here is the part of my code that fails. I'm in AJAX so if I console.log the generated URL, it is valid but returns the 403 error message in JSON format.
/* Create API request to share an article */

//Building up the URL
$url = 'https://api.linkedin.com/v1/people/~/shares?&oauth2_access_token='.$_SESSION['linkedInCreds']['access_token'].'&format=json&message='.rawurlencode($_REQUEST['message']).'&visibility[code]='.$_REQUEST['visibility']['code'];
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($url)
        )
    );

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context); /***** FAILS: Returns JSON with 403 error code from LinkedIn. *****/

/* Check if $result is true or false and echoes the result. End of AJAX. */

I'm currently stuck with this issue. Apparently this feature wasn't removed by LinkedIn but I can't make it work, could anyone help ?
Thanks in advance.


text:
Q: Rails. Error uploading images on heroku via cloundinary and carrierwave I want to upload product images in my online shop via cloudinary and carrierwave.
I followed the instructions on the cloudinary official web site and i was able to upload images in development environment. But after I pushed it on heroku, I tried to create new product with product picture, but i got error "If you are the application owner check the logs for more information."
I couldn't find specific error(s) in heroku logs:

2015-01-09T17:40:00.955232+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/bundler/gems/activeadmin-7414104d41e5/lib/active_admin/resource_controller/data_access.rb:138:in `build_new_resource'
2015-01-09T17:40:00.955231+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0.rc3/lib/active_record/inheritance.rb:61:in `new'
2015-01-09T17:40:00.949065+00:00 app[web.1]:   AdminUser Load (1.7ms)  SELECT  "admin_users".* FROM "admin_users" WHERE "admin_users"."id" = $1  ORDER BY "admin_users"."id" ASC LIMIT 1  [["id", 1]]
2015-01-09T17:40:00.955222+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_controller/metal/strong_parameters.rb:188:in `each_pair'
2015-01-09T17:40:00.955234+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/bundler/gems/activeadmin-7414104d41e5/lib/active_admin/resource_controller/data_access.rb:121:in `build_resource'
2015-01-09T17:40:00.955247+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_controller/metal/implicit_render.rb:4:in `send_action'
2015-01-09T17:40:00.955185+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/carrierwave-0.10.0/lib/carrierwave/orm/activerecord.rb:38:in `image='
2015-01-09T17:40:00.955249+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/abstract_controller/base.rb:198:in `process_action'
2015-01-09T17:40:00.955225+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0.rc3/lib/active_record/core.rb:557:in `init_attributes'
2015-01-09T17:40:00.955264+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/abstract_controller/callbacks.rb:20:in `block in process_action'
2015-01-09T17:40:00.955274+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2
.0.rc3/lib/active_support/callbacks.rb:169:in `call'
2015-01-09T17:40:00.955266+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:117:in `call'
2015-01-09T17:40:00.955268+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:117:in `call'
2015-01-09T17:40:00.955187+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0.rc3/lib/active_record/attribute_assignment.rb:54:in `public_send'
2015-01-09T17:40:00.955271+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:169:in `call'
2015-01-09T17:40:00.955286+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:169:in `call'
2015-01-09T17:40:00.955301+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:92:in `call'
2015-01-09T17:40:00.955278+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:234:in `call'
2015-01-09T17:40:00.955227+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0.rc3/lib/active_record/core.rb:280:in `initialize'
2015-01-09T17:40:00.955306+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:81:in `run_callbacks'
2015-01-09T17:40:00.955321+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0.rc3/lib/active_record/railties/controller_runtime.rb:18:in `process_action'
2015-01-09T17:40:00.955320+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
2015-01-09T17:40:00.955236+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/bundler/gems/inherited_resources-9e4c7576b48e/lib/inherited_resources/actions.rb:31:in `create'
2015-01-09T17:40:00.955251+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_controller/metal/rendering.rb:10:in `process_action'
2015-01-09T17:40:00.955334+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/routing/route_set.rb:42:in `serve'
2015-01-09T17:40:00.955336+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/journey/router.rb:43:in `block in serve'
2015-01-09T17:40:00.955318+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_controller/metal/instrumentation.rb:30:in `process_action'
2015-01-09T17:40:00.955283+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:234:in `call'
2015-01-09T17:40:00.955229+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0.rc3/lib/active_record/inheritance.rb:61:in `new'
2015-01-09T17:40:00.955292+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:169:in `call'
2015-01-09T17:40:00.955289+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:169:in `call'
2015-01-09T17:40:00.955276+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:169:in `block in halting'
2015-01-09T17:40:00.955273+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:169:in `block in halting'
2015-01-09T17:40:00.955324+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionview-4.2.0.rc3/lib/action_view/rendering.rb:30:in `process'
2015-01-09T17:40:00.955303+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:92:in `_run_callbacks'
2015-01-09T17:40:00.955288+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:169:in `block in halting'
2015-01-09T17:40:00.955308+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/abstract_controller/callbacks.rb:19:in `process_action'
2015-01-09T17:40:00.955310+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_controller/metal/rescue.rb:29:in `process_action'
2015-01-09T17:40:00.955353+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.6.0.beta2/lib/rack/conditionalget.rb:38:in `call'
2015-01-09T17:40:00.955358+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/middleware/flash.rb:260:in `call'
2015-01-09T17:40:00.955331+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/routing/route_set.rb:73:in `call'
2015-01-09T17:40:00.955342+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/journey/router.rb:30:in `each'
2015-01-09T17:40:00.955269+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:169:in `block in halting'
2015-01-09T17:40:00.955300+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:169:in `block in halting'
2015-01-09T17:40:00.955313+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/notifications.rb:164:in `block in instrument'
2015-01-09T17:40:00.955346+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/warden-1.2.3/lib/warden/manager.rb:35:in `block in call'
2015-01-09T17:40:00.955323+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/abstract_controller/base.rb:137:in `process'
2015-01-09T17:40:00.955355+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.6.0.beta2/lib/rack/head.rb:13:in `call'
2015-01-09T17:40:00.955281+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:234:in `block in halting'
2015-01-09T17:40:00.955332+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/routing/route_set.rb:73:in `dispatch'
2015-01-09T17:40:00.955356+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/middleware/params_parser.rb:27:in `call'
2015-01-09T17:40:00.955378+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:734:in `_run_call_callbacks'
2015-01-09T17:40:00.955343+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/journey/router.rb:30:in `serve'
2015-01-09T17:40:00.955315+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
2015-01-09T17:40:00.955284+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:234:in `block in halting'
2015-01-09T17:40:00.955326+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_controller/metal.rb:195:in `dispatch'
2015-01-09T17:40:00.955374+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:88:in `call'
2015-01-09T17:40:00.955381+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/middleware/callbacks.rb:27:in `call'
2015-01-09T17:40:00.955379+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:81:in `run_callbacks'
2015-01-09T17:40:00.955316+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/notifications.rb:164:in `instrument'
2015-01-09T17:40:00.955385+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
2015-01-09T17:40:00.955291+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:169:in `block in halting'
2015-01-09T17:40:00.955359+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.6.0.beta2/lib/rack/session/abstract/id.rb:225:in `context'
2015-01-09T17:40:00.955329+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_controller/metal.rb:236:in `block in action'
2015-01-09T17:40:00.955348+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/warden-1.2.3/lib/warden/manager.rb:34:in `catch'
2015-01-09T17:40:00.955364+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/middleware/cookies.rb:560:in `call'
2015-01-09T17:40:00.955390+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/tagged_logging.rb:68:in `block in tagged'
2015-01-09T17:40:00.955350+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/warden-1.2.3/lib/warden/manager.rb:34:in `call'
2015-01-09T17:40:00.955411+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.6.0.beta2/lib/rack/methodoverride.rb:22:in `call'
2015-01-09T17:40:00.955409+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/middleware/request_id.rb:21:in `call'
2015-01-09T17:40:00.955305+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:734:in `_run_process_action_callbacks'
2015-01-09T17:40:00.955352+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.6.0.beta2/lib/rack/etag.rb:24:in `call'
2015-01-09T17:40:00.955365+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0.rc3/lib/active_record/query_cache.rb:36:in `call'
2015-01-09T17:40:00.955376+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/callbacks.rb:88:in `_run_callbacks'
2015-01-09T17:40:00.955388+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/railties-4.2.0.rc3/lib/rails/rack/logger.rb:20:in `block in call'
2015-01-09T17:40:00.955431+00:00 app[web.1]:   vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'
2015-01-09T17:40:00.955394+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/railties-4.2.0.rc3/lib/rails/rack/logger.rb:20:in `call'
2015-01-09T17:40:00.955418+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.6.0.beta2/lib/rack/sendfile.rb:113:in `call'
2015-01-09T17:40:00.955387+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/railties-4.2.0.rc3/lib/rails/rack/logger.rb:38:in `call_app'
2015-01-09T17:40:00.955413+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.6.0.beta2/lib/rack/runtime.rb:18:in `call'
2015-01-09T17:40:00.955373+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
2015-01-09T17:40:00.955362+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.6.0.beta2/lib/rack/session/abstract/id.rb:220:in `call'
2015-01-09T17:40:00.955393+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/tagged_logging.rb:68:in `tagged'
2015-01-09T17:40:00.955416+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/middleware/static.rb:113:in `call'
2015-01-09T17:40:00.955423+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.6.0.beta2/lib/rack/lock.rb:17:in `call'
2015-01-09T17:40:00.955311+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
2015-01-09T17:40:00.955414+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
2015-01-09T17:40:00.955428+00:00 app[web.1]:   vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
2015-01-09T17:40:00.955421+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/railties-4.2.0.rc3/lib/rails/application.rb:164:in `call'
2015-01-09T17:40:00.955433+00:00 app[web.1]:
2015-01-09T17:40:00.955419+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/railties-4.2.0.rc3/lib/rails/engine.rb:518:in `call'
2015-01-09T17:40:00.955391+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.0.rc3/lib/active_support/tagged_logging.rb:26:in `tagged'
2015-01-09T17:40:00.955425+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.6.0.beta2/lib/rack/content_length.rb:15:in `call'
2015-01-09T17:40:00.955382+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
2015-01-09T17:40:00.955327+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
2015-01-09T17:40:00.955426+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.6.0.beta2/lib/rack/handler/webrick.rb:89:in `service'
2015-01-09T17:40:00.955434+00:00 app[web.1]:
2015-01-09T17:40:00.955430+00:00 app[web.1]:   vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
2015-01-09T17:40:00.955345+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/routing/route_set.rb:802:in `call'
2015-01-09T17:40:00.955371+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0.rc3/lib/active_record/connection_adapters/abstract/connection_pool.rb:647:in `call'
2015-01-09T17:40:00.955384+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.0.rc3/lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'

Form:
form(:html => { :multipart => true }) do |f|
  f.inputs 'New product' do
    ...
    f.file_field :image, label: 'Image'
    f.submit
  end
end

Uploader:
class ImageUploader < CarrierWave::Uploader::Base

  include Cloudinary::CarrierWave

end

Model:
class Product < ActiveRecord::Base

  ...

  mount_uploader :image, ImageUploader

  ...

end

Controller:
def create
  @product = Product.new(product_params)
  respond_to do |format|
    if @product.save
      format.html { redirect_to @product }
    else
      format.html { render :new, notice: 'Errors.' }
    end
  end
end

def product_params
  params.require(:product).permit(:title, :short_description, :description, :image, :price)
end

I have Rails 4.2.0


text:
Q: Infinite universe and the impossibility of monochromatic light and infinite plane waves I recently asked a question relating to this excerpt from the textbook Optics, fifth edition, by Hecht:

Mathematically, the plane wave extends out to infinity in all its directions, and, of course, physically that cannot be. A real "plane wave" is a finite thing that, no matter how big, only resembles a mathematical plane. Since lenses and mirrors and laser beams are all finite, that "resemblance" is usually good enough.

Specifically, I asked why this was not possible.
Thinking about this further, it seemed to me that this situation is similar to that of the impossibility of monochromatic light, no? And I had actually asked a question precisely about this in the past.
Furthermore, in my now deleted comment to the answer by user "Semoi", I said that, given that the empirical evidence suggests that the universe has zero spatial curvature and is therefore infinite (assuming it has a trivial topology), I do not see why Semoi's argument relating to infinite space is valid. In fact, would this evidence not suggest that plane waves can indeed extend out to infinity?
But if the universe is indeed infinite, then does this not also mean that monochromatic light is possible and exists in the universe?
Now, as the user "anna v" said in her answer, when we observe the universe, we do not see any evidence of monochromatic light, right? So, presuming that we have technology that should be able to detect such things, it seems to me that this suggests that monochromatic light and infinite plane waves do not exist and/or are impossibilities, right?
But then, by the same reasoning, shouldn't monochromatic light and infinite plane waves exist, or at least be possible, in an infinite universe? So does this in turn suggest that, despite the empirical evidence, that the universe is not infinite?
As you can see, the more I thought about this, the more, what seems like, contradictions I encountered, and the more questions arose. I would greatly appreciate it if people would please take the time to give me an answer to these questions that makes sense and puts my mind at ease once and for all.


text:
Q: convert an XML jQuery Object to String I have an uploaded xml file that I'm perusing using jQuery via var $ts = $.parseXML(filecontents)
I have attempted to convert back to the original source when locating objects within the XML Document by utilising:
$('<div>').append($ts.find('Object').clone()).html();

In chrome, this works absolutely fine and I get the output as it looks in the original document. In firefox, it reorders the attributes of elements alphabetically.
Since I'm hashing this output, I need it to be the same as the input. Is this possible to enforce at all, or am I better with a different method of walking through this xml document?

A: Use the XMLSerializer API instead:
var foo = $ts.find("Object").get(0);
var serializer = new XMLSerializer();
var original = serializer.serializeToString(foo);


text:
Q: Can't stop propagation of event in Jquery I'm a bit confused. I have list of what are names with a checkbox next to them. The list is constructed dynamically in after doing a post to the backend.
Problem is whenever I click on the checkbox it immediately gets unchecked. The reason I know this is that if an alert is inserted in the event, the checkbox is actually checked, until the alert is dismissed.
This is my code:
$("#NamesList").on("click", "input[type='checkbox']", function (e) {
    CheckboxClicked();
    return false;
})
.on("click", "li", function (e) {
    e.preventDefault();
    e.stopPropagation();

    switch (e.target.nodeName) {
         case "A":
             GetPerson(e.target.href)
             break;
         case "LI":
              GetPerson($("a", e.target).attr("href"))
              break;
         default: return false;
     }

     return false;
});

Thing is, I have link in the listitem that I need to be able to follow. If the part for navigating to the link is taken out, the checkbox functionality works fine.
This is what a typical list of names look like:

         <input class="checkbox" type="checkbox" />
         John Smith

Any ideas?

A: $("#NamesList").on("click", "input[type='checkbox']", function (e) {
    CheckboxClicked();
    e.stopPropagation();
})

replaced return false; with e.stopPropagation();. return false is equivalent to e.preventDefault(); e.stopPropagation(); However, you don't want to prevent the default :)
Working fiddle: http://jsfiddle.net/wpx6A/

A: try
e.stopImmediatePropagation()

this will make sure the event is not propagated.


text:
Q: в Android Studio не отображается часть Дизайна
В текстовой части есть код, но при добавлении Button или Text не происходит ничего - не добавляются ни кнопки, ни текстовая часть. При эмуляции чаще всего текстовая часть появляется.

A: Поменяй тему, тогда всё должно появиться.
Сделать это можно, нажав на кнопку с надписью AppTheme чуть выше дизайна


text:
Q: How to hide these 2 element in css / less? In Magento2 I want to hide the price-notice and the qty-holder from the bundle product page. I want to edit the _custom.less page but not sure what to write in it. Any help would help. Thanks!

A: You need to search for those classes in the repository/source code, and then use the same nesting in your _custom.less file. The path to get to that class needs to match what it is currently. You can also see this in the browser by inspecting those elements. The classes themselves will need either visibility: hidden; or display: none; depending on what your trying to achieve exactly. You can also test this in the browser inspector before putting in your file. When done, deploy your static content php bin/magento setup:static-content:deploy and if cache is enabled, clear it php bin/magento cache:flush.


text:
Q: Flash on OS X Lion Flash is not supported in OS X Lion i.e. Safari, how can I browse webpages with flash content and actually view the flash content?

A: Adobe Flash Player is supported in Lion (Chrome works by using its own copy of the plug-in that you can disable) and Safari uses the Plug-in installed in your personal libraries folder:
~/Library/Internet Plug-Ins/

or in the system-wide libraries:
/Library/Internet Plug-Ins/

Lion, however, doesn't ship with Flash player installed by default (I'm not 100% sure because I haven't had Flash in a long time), but that doesn't stop you from installing it.
Head over to Adobe's FlashPlayer download page and select 10.4-10.6 as your operating system:

So as you can see there is not a 10.7 version yet, so there are some issues. At first it was said that Lion disabled the Hardware acceleration of Flash; Adobe later retracted that when they found out it was their own bug.

The final release of Mac OS X Lion (10.7) provides the same support
  for Flash hardware video acceleration as Mac OS X Snow Leopard (10.6).
  The previous "Known Issue" described in a tech note suggesting that
  video hardware acceleration was disabled in Lion was incorrect and
  based on tests with a pre-release version of Mac OS X Lion that
  related to only one particular Mac GPU configuration.

source: Adobe's Blog
If you are brave enough, you could try the BETA version (used by developers) that is theoretically the version that will be released for Lion.
Those Betas are available Here.

A: Were did you heard that Flash is not supported in Lion?
Flash is very well supported, I have it running in Safari and Chrome and it works fine.


text:
Q: Split dataframe into two based on numeric and integer type in R I want to split a dataframe into df1 and df2 based on data type numeric and integer.
The df1 and df2 will respectively contain "bmi", "age", "cal", "pro" and "male", "urban".
sapply(df, class)

Out:
      bmi       age       cal       pro      male
"numeric" "numeric" "numeric" "numeric" "integer"
    urban
"integer"

str(df)

Out:
'data.frame':   4825 obs. of  6 variables:
 $ bmi  : num  24.7 25.3 22.8 21.7 24.2 ...
 $ age  : num  37.5 36.5 37 36.9 40 ...
 $ cal  : num  6.31 1.84 3.87 2.67 1.59 ...
 $ pro  : num  13.57 13.43 9.57 12.51 11.65 ...
 $ male : int  1 0 1 0 1 0 0 1 1 0 ...
 $ urban: int  1 1 1 1 1 1 1 1 1 1 ...

How can I do that in R? Thank you.
I try with unlist(lapply(df, is.numeric)), but it doesn't distingue numeric and integer.
Update:
With the code below I get a dataframe but it's not a subset of df, another problem is interger columns included:
numeric <- which(sapply(df,is.numeric))
df1 <- as.data.frame(numeric)
print(df1)

Out:

A: The following code works, many thanks to @A5C1D2H2I1M1N2O1R2T1 and @Ronak Shah.
out <- split.default(df, sapply(df, class))
names(out) <- paste0('df', seq_along(out))
names(out)
list2env(out, .GlobalEnv)


text:
Q: Custom photo album category for ALAssetsLibrary is not working in ipad? I have an image and i want to save that image into custom photo album.
My code is working fine for Iphone but it is not workin for iPad.
self.library = [[ALAssetsLibrary alloc] init];

[self.library saveImage:imageShow.image toAlbum:@"APP NAME" withCompletionBlock:^(NSError *error) {
    if (error!=nil) {
        NSLog(@"Big error: %@", [error description]);
    }
}];

just help me please
Thanx for help..


text:
Q: Why are my .txt files printed when I double-click them? My Text files (.txt) are not opening. Instead, they are printing as the default command when I double-click on any file.
I realized that the print command is default now and open is not the default command.
How do i change it back?

A: Open up a folder and then go to the menu:

Tools > Folder Options > File Types

Go down to the TXT extension and then click the Advanced button for the Edit File Type dialog:

If you are missing the open action

To create a new open action, take the following steps:

*

*Click New. A New Action dialog will pop up

*For Action, enter open

*For Application used to perform action, enter
"C:\WINDOWS\system32\NOTEPAD.EXE %1"

*Click OK

(Adjust the program file path as necessary if you prefer opening with another text editor.)

In the Edit File Type dialog:

*

*Select open under the Actions list

*Click Set Default

*Click OK

*Close out the Folder Options

This should now set back the default action of double-clicking on a .txt to open instead of printing.

A: You cloud try to right-click on it in a Windows explorer and check if the popup menu entry "right click on it" is there.
If it is, you should then be able to select a program, use Notepad and select "always use this".

Otherwise, there are some ways to restore default association in Windows XP


text:
Q: Sending 0x00 using I2C I am using the Wire class to have two Arduino Unos communicate using I2C.  It seems that the Wire class ends transmission on a value of 0.  So if I send bytes 0x01, 0x02, 0x00, and 0x04, the master receives: 0x01, 0x02, 0xFF, 0xFF.
It seems odd that a communication network designed for processor communication cannot send a 0x00.  All the examples for I2C that I have seen use ASCII only.  Inter-processor communication restricted to ASCII does not seem to make any sense.  Am I missing something with I2C or is this just an implementation limitation of the Arduino Wire class?
Master
void loop() {
  Wire.requestFrom(2, 4);

  while(Wire.available()) {
    byte b = (byte) Wire.read();
    Serial.println(b);
  }

  delay(1000);
}

Slave
void requestEvent() {
  char bytes[4] = {0x01,0x02,0x00,0x04};
  Wire.write(bytes);
}

The results are: 1 2 255 255.
When that 0x00 was 0x03 I got the expected: 1 2 3 4.

A: You are passing an array of chars to Wire.write()... This makes Wire treat the argument as a null-terminated string, and therefore the NULL byte terminates the transmission.  If you want to send bytes, call the write() function once for each byte, passing it byte types.
Alternatively, you can call the write(const uint8_t *, size_t); version: you pass it a pointer to / array of bytes, but you also have to give it a size of your data array.

A: Do you have Wire.begin() and Wire.beginTransmission() (with correct address) happening before calling Wire.write()?


text:
Q: NodeJS - how to control execution flow of promises? I am asking this to try and understand nodeJS.. I'm trying to use the following code to execute CMD opreations one by one, but due to the event loop (i assume) it gets executed in random variations. This is my code:
const exec = require('child_process').exec;

//os_func's execCommand is incharge of executing cli strings using a promise
function os_func() {
    this.execCommand = function (cmd) {
        return new Promise((resolve, reject)=> {
           exec(cmd, (error, stdout, stderr) => {
             if (error) {
                reject(error);
                return;
            }
            resolve(stdout)
           });
       })
   }
}

//start
var os = new os_func();

os.execCommand('pwd').then(res=> {
    console.log("os1 >>>", res); //sometimes first, sometimes second
}).catch(err=> {
    console.log("os >>>", err);
})

os.execCommand('pwd').then(res=> {
    console.log("os2 >>>", res); //sometimes first, sometimes second!
}).catch(err=> {
    console.log("os >>>", err);
})

How can I control the execution-flow, while not affecting performance?

A: First off, the JS way to make (err, ...args)-based callbacks asynchronous is to use util.promisify that was built just for this purpose. Example:
const {exec} = require('child_process');
const {promisify} = require('util');
const exec_async = promisify(exec);
exec_async('pwd').then(({stdout, stderr}) => console.log(stdout))
// you can use exec_async instead of os.execCommand

Then, you have to understand that promises are asynchronous. To make it simple, between the invocation and the resolving of a promise, things can happen. Asynchronicity is one of the building blocks of JS - I won't go into details on it, but if you have troubles understanding this concept I'd recommend starting by MDN's guide on asynchronous programming in JS.
Basically in your code, this can happen:
time
|
| os.execCommand('echo hello from 1')
| .then(res=> console.log('os1 >>> ', res))
| os.execCommand('echo hello from 2')
| .then(res=> console.log('os2 >>> ', res))
V
Output:
os1 >>> hello from 1
os2 >>> hello from 2

But also this:
time
|
| os.execCommand('echo hello from 1')
| os.execCommand('echo hello from 2')
| .then(res=> console.log('os2 >>> ', res))
| .then(res=> console.log('os1 >>> ', res))
V
Output:
os2 >>> hello from 2
os1 >>> hello from 1

And also a few other spooky combinations. If you want to make sure that one command executes before another one, you should instead chain your promises using then:
exec_async('echo hello from 1')
.then(console.log)
.then(
  exec_async('echo hello from 2')
  .then(console.log)
)

Nested then can affect readability, as such you may opt for the async/await syntax:
const hello1 = await exec_async('echo hello1');
const hello2 = await exec_async('echo hello2');


text:
Q: How to generate a Audio sound Output on Nexys ddr 4 FPGA I want try to using Nexys 4 to generate car sound. Do i need to store the sound in ROM? what is the step to create a sound. I am using the verilog. Thanks

A: The Nexys 4 board does not contain an audio codec but it contains a simple lowpass (or bandpass) filter creating a sound output from a PWM signal.
Your programming challenge is to create a PWM signal whose duty cycle represents the current level of the sound output signal.
I would think about the following pseudo-code (here C-like, not Verilog like):
signed int levelAccu = 0;

on_Every_Clock_Edge()
{
    int level = getCurrentSoundLevel();
    levelAccu += level;
    if(levelAccu > 0)
    {
        setOutputPin(HIGH);
        levelAccu -= MAX_LEVEL;
    }
    else
    {
        setOutputPin(LOW);
        levelAccu -= MIN_LEVEL;
    }
}

While:
getSoundLevel() represents the current desired "level" of the sound output. (The value of the current sample if you use sampled sound.)
MAX_LEVEL and MIN_LEVEL are the maximum and minimum values of the "level". Example: If you want to play sound which is stored as 8-bit signed values you have MAX_LEVEL=127 and MIN_LEVEL=-128.
The register levelAccu should have 1 or 2 bits more than the level.
Note that the clock edges must be much faster than the sample rate of the audio.

Do I need to store the sound in ROM?

Depends on which kind of sound you want to create.
If you want to play recorded sound samples you'll have to store them in some memory (RAM, ROM...).
If you want to generate sound programmatically (such as sine waves) you don't have to store them.
By the way
Your question is not Verilog specific but it is more related to FPGAs in common and to the circuits close to the FPGA.
For this reason "electronics.stackexchange.com" should really be the better place for such questions.


text:
Q: fancybox: remove href's from status bar When I hover over thumbnails, the ref to the img is continuously displayed in the lower left corner. See here. This is distracting and I want to hide it. I think it is due to the "href's" in the gallery definitions.

A: Just replace the anchor's href attribute by the special fancybox data-fancybox-href attribute like :
open fancybox

It's assumed you have properly initialized fancybox in your custom script
$(".fancybox").fancybox();

See JSFIDDLE
Note: this is for fancybox v2.x


text:
Q: Content above RecyclerView with parallax effect in Android As described in 1, I want to implement a Layout where half the screen is some Content, f.e. a LinearLayout including a pie chart.
The other half of the screen should be a RecyclerView including a CardView which I already implemented.
When scrolling up there should be a Parallax Effect hiding the Contentup to the AppBar.
I tried to use LinearLayouts (where one includes the Content and one includes the Recyclerview) with a weightSum but it did not work properly.
How can I implement this properly?
Design that I want to implement in my App

A: I agree with the other answer here. Take a look at the docs.
But for a quick fix,
First, import the android Design Library
implementation 'com.android.support:design:28.0.0'

You must already be having the CardView and RecyclerView libraries
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'

Then implement this code
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main3Activity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing"
            android:layout_width="match_parent"
            android:layout_height="350dp"
            android:fitsSystemWindows="true"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="#0e0d0e"
            app:expandedTitleTextAppearance="@android:color/transparent">

            <!--these views are only to illustrate the imp. tags -->
            <!--that you need to implement in your views-->
            <!--in the "Component" area-->

            <!--start example-->

            <ImageView
                android:id="@+id/iv"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:contentDescription="@null"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                app:title="Title"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_collapseMode="parallax"/>

            <!--end example-->

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/nestedScrollView"
        android:clipToPadding="false"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="1200dp">

            <!--implement the RecyclerView here-->

            <android.support.v7.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scrollbars="vertical">

            </android.support.v7.widget.RecyclerView>

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>