text:
Q: Netbeans no muestra los primeros caracteres de la tabla ASCII. Java
☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔☻↔▲▼ !""#$%&''())*+,-./01234568

Cuando imprimo los primeros caracteres en Netbeans hasta ! me sale una caja vacía, intente cambiar en propiedades del proyecto el encoding de UTF-8 a ISO-8859-1 y nada, no hay manera.
¿alguien tiene alguna solución?

A: No es un tema de Netbeans o de Java. Puedes comprobar en la Wikipedia que:

El código ASCII reserva los primeros 32 códigos (numerados del 0 al 31
  en decimal) para caracteres de control: códigos no pensados
  originalmente para representar información imprimible, sino para
  controlar dispositivos (como impresoras) que usaban ASCII. Por
  ejemplo, el carácter 10 representa la función "nueva línea" (line
  feed), que hace que una impresora avance el papel, y el carácter 27
  representa la tecla "escape" que a menudo se encuentra en la esquina
  superior izquierda de los teclados comunes.

Y el 32 sí te lo muestra, lo que pasa es que es el espacio.
El 33 es el primero visible (considerando el espacio como "no visible") y es el signo de exclamación !
En realidad, como se puede comprobar con las caracteres de tu pregunta, si tienes la fuente (tipo de letra) compatible, sí se muestran esos caracteres, pero en una consola o terminal del sistema no se suelen mostrar:
Pero incluso para mostrarlo aquí, el navegador usa otros códigos: el corazón es el código 9829 (2665 en hexadecimal):

console.log("\u2665\u2666\u2667\u2664");


text:
Q: Dell Inspiron 5520 fan always working I was trying to find a solution for my problem, but without any success. Namely, I decided to move to Ubuntu system (from windows 8) and I installed latest one for my laptop (12.04 LTS).
I installed graphic card, wireless update, everything. However I'm afraid that my card is not installed property because in detail there is written 'Graphic driver: unknown' even if I installed it.
My fan is always working and I don't know how to stop it or prevent. On windows 8 everything works without problems, fan stops etc. What could be my problem?

A: Most of times it could be about your graphic card gets warm and because your graphic card is integrated into your cpu the system thinks that cpu gets warm
install mesa-utils and mesa-utils-extras and reboot  , for installing use the following command-
sudo apt-get install mesa-utils mesa-utils-extra

it will work for Intel Graphic Cards
If you are having NVIDIA graphic card then use bumblebee because mesa and NVIDIA will conflict with each other for sure.. to install bumblebee use-
sudo add-apt-repository ppa:bumblebee/testing

then for 12.04 and 13.04 use-
sudo apt-get install bumblebee bumblebee-nvidia virtualgl linux-headers-generic

otherwise  for 13.10 use-
sudo apt-get install bumblebee bumblebee-nvidia primus linux-headers-generic

If that doesnt work, try to

*

*Cleaning your laptop- As might be its because of just that, stopping fan from running  properly.

*Update bios - After updating it can perform good operations like increasing compatibility .That solved my issue.

*Update Kernel
hope the very first suggestion will resolve your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which compiler did macport use? I'm working on a c++ project which just implemented some of the shared pointer features from boost and/or TR1. Since the upgrade, my code no longer compiles with gcc 4.2.1 (provided by Xcode), I'm installing gcc 4.5.x which is suppose to provide the aforementioned features. I need to recompile mpich2 (and then my code) with the new compiler and I want to be sure macport is using the right one.
sudo port install gcc45
gcc_select mp-gcc45

should have gotten the job done, but I'd like port to tell me which compiler it is using.
Can anyone help me with this?
Thanks in advance,
Nick

A: MacPorts - Using the Right Compiler


text:
Q: Map API batch stocks object to stocks array | React I'm using axios with react to query the alpha vantage api. I have the api part working. What I am trying to figure out is how to map to data I am pulling to make it accessible to generate a list of items from the data. I want to use map create an array called stocks that would then have an object for each item with the symbol, price, volume, timestamp that I could use. How do I correctly do this?
Here's my map function:
axios.get(axios.get(url)
.then(res => {
  console.log(res.data['Stock Quotes']);
  const stocks = res.data['Stock Quotes'].map((stock) => [{symbol: stock.symbol, price: stock.price}])
})
.catch(error => console.log(error))
)

This is what is returning from the console.log(res.data['Stock Quotes']);
(3) [{…}, {…}, {…}]
0:{1. symbol: "MSFT", 2. price: "93.8100", 3. volume: "26478373", 4. timestamp: "2018-03-07 16:00:00"}
1:{1. symbol: "FB", 2. price: "183.7000", 3. volume: "19004961", 4. timestamp: "2018-03-07 16:56:26"}
2:{1. symbol: "AAPL", 2. price: "175.0200", 3. volume: "30982083", 4. timestamp: "2018-03-07 16:36:24"}
length:3

This is what is returning from the console.log(stocks);
(3) [Array(1), Array(1), Array(1)]
0:Array(1)
0:{symbol: undefined, price: undefined}
length:1
__proto__:Array(0)
0:Array(1)
1:{symbol: undefined, price: undefined}
length:1

This is the full code I'm using
import React, { Component } from 'react';
import axios from 'axios';
import SearchBar from './components/search_bar';
import './App.css';

class App extends Component {
  constructor() {
    super();

this.state = {
  stocks: [],
  term: null,
  value: ''
};

this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
}

handleChange(e) {
this.setState({
  value: e.target.value
});
}

handleClick(e) {
  if(e) e.preventDefault();

  this.setState({
    value: '',
    term: this.state.value,
    stocks: this.state.stocks
  });

let term = this.state.value;
const key = 'F41ON15LGCFM4PR7';
const url = `https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=${term}&apikey=${key}`;

axios.get(axios.get(url)
.then(res => {
  console.log(res.data['Stock Quotes']);
  const stocks = res.data['Stock Quotes'].map((stock) => [{symbol: stock.symbol, price: stock.price}])
})
.catch(error => console.log(error))
)

}

render () {
const value = this.state.value;
return (

Stock Search

    <SearchBar value={ value }
               onChange={ this.handleChange }
               onClick={ this.handleClick }/>

);
}
}
export default App;

A: Looks like the whole key for each "Stock Quote's" "symbol" is actually "1. symbol", not just "symbol" (and for price it's "2. price").
Why this would be the case I have no idea, but the following should work:
const stocks = res.data['Stock Quotes'].map((stock) => [{symbol: stock['1. symbol'], price: stock['2. price']}])


text:
Q: New to Android programming, have a few questions about format and style for an app I am new to Android programming and my first app has to do with a Wikia page.  The current way that I have it set up right now my app will pull a list of the categories and put them in a listview for the user to click.  Once the user clicks it redirects them to the mobile page for the category/item that they chose.
I was wondering is this good practice for an app to redirect to the mobile site, or should I find a way to pull the info from the site into my app?  Is either way better than the other?  Please give me as many opinions as you have good or bad, I want to know so I can make this the best that I can.

A: Theee is no need to redirect the user to the browser or a webView since you can parse the data with the WikiMedia API
You can also checkout the official Wikipedia Android App from Github, but it's not an native Android app(It's build with phonegap)


text:
Q: Isomorphism between $E$ and $E^*$ Show that there does not exist a  isomorphism $\phi:E\rightarrow E^*$ that it takes every basis of $E$ to its dual basis. ($E$ is a vector space over field K and $\text{dim}E=n$ .)
My attempt: There exist some basis $(e_1,\cdots,e_n)$ that $(\phi(e_1),\cdots,\phi(e_n))$ is its dual basis since there exist the isomorphism. Now I probably have to make a basis that under $\phi$ is not its dual basis.

A: You should seem $(e_1+e_2,\cdots,e_n)$ and $(\phi(e_1+e_2),\cdots,\phi(e_n))$ .
since $\phi(e_1+e_2)\in E^{**}$ then $1=\phi(e_1+e_2)(e_1+e_2)=\phi(e_1)(e_1+e_2)+\phi(e_2)(e_1+e_2)=\cdots=1+1$. this is
 a contradiction.


text:
Q: not able to access statefulset headless service from kubernetes I have created a headless statefull service in kubernates. and cassandra db is running fine.
PS C:\> .\kubectl.exe get svc
NAME         CLUSTER-IP   EXTERNAL-IP   PORT(S)    AGE
cassandra    None         <none>        9042/TCP   50m
kubernetes   10.0.0.1     <none>        443/TCP    6d

PS C:\> .\kubectl.exe get pods
NAME          READY     STATUS    RESTARTS   AGE
cassandra-0   1/1       Running   0          49m
cassandra-1   1/1       Running   0          48m
cassandra-2   1/1       Running   0          48m

I am running all this on minikube. From my laptop i am trying to connect to 192.168.99.100:9402 using a java program. But it is not able to connect.

A: Looks like your service not defined with NodePort. can you change service type to NodePort and test it.
when we define svc to NodePort we should get two port number for the service.


text:
Q: How do i add a query string to $GET function I have $GET function that by default send out a request to get 30 items back
$transactions = $MK->getTransactions($_GET)

It will go to the header as following
transactions?&page=1&per_page=30

And from the API provider module i found this line
 if (!empty($params['per_page'])) {
            $request_params['per_page'] = (int) $params['per_page'];
        }

SO my question is how to add the param to the $_GET
Right now when it goes out just as $transactions = $MK->getTransactions($_GET)
the request itself will go out as /transactions?&page=1&per_page=30
But i need to change the per_page value to smth else.

A: So you have smth like:
$transactions = $MK->getTransactions($_GET)

Whiich leads you to the following path:
/transactions?&page=1&per_page=30

But you want to change the value of one parameter in $_GET?
First, from you example, if you'd print $_GET, you would see:
Array
(
    [page] => 1
    [per_page] => 30
)

So do smth like:
$parameters = $_GET;
$parameters["per_page"] = 123;

And than:
$transactions = $MK->getTransactions($parameters);

which will result in changed number per page.


text:
Q: General formula for roots for cubic equation I have the following cubic equation with  $ \beta \in [0,1]$ and  $ \delta\in [0,1]$ are 2 parameters. Is it possible to use software to get the explicit expression of the solution.
\begin{equation*}
U^{3}\left( -\left( \frac{\delta^{2}}{2} + \beta\right)+\delta-\frac{1}{2} \right)+U^{2}\left(\frac{3}{2}-\delta-\left( \frac{\delta^{2}}{2} + \beta\right)\right)+U\left(\left( \frac{\delta^{2}}{2}+\beta -2 \delta\right)\right)+\left( \frac{\delta^{2}}{2} + \beta\right)=0
\end{equation*}
I want to solve this equation usin Maple or Mathematica, but I was not able to do it.

A: You can find formula for cubic equation in Wikipedia: https://en.wikipedia.org/wiki/Cubic_equation
I will shortly describe the process how to solve such equation. This can be done in steps to minimize the use of long complicated expressions.
Step 1: write $aU^3 + bU^2 + cU + d = 0$.
Step 2: reduce to the case $T^3 + pT + q = 0$ (as explained in Wikipedia, divide the equation by $a \ne 0$ and then subsitute $U = T - \frac{b}{3a}$).
Step 3: use Cardano's formula. Taking the real cubic roots you get
$$ T_{\mathbb{R}}=u+v=\sqrt[3]{-{q\over 2}+ \sqrt{{q^{2}\over 4}+{p^{3}\over 27}}} +\sqrt[3]{-{q\over 2}- \sqrt{{q^{2}\over 4}+{p^{3}\over 27}}} $$
Step 4: to find the rest of the roots divide $T^3 + pT + q$ by $T-T_{mathbb{R}}$ and then solve the quadratic that you get.
In all the steps you intermediate parameters-variables, e.g.
$$ A = -\left( \frac{\delta^2}{2} + \beta \right) + \delta - \frac{1}{2} $$
etc.

A: Look in this Wikipedia page for a general formula for cubic roots.


text:
Q: Draw a ray with tkz-euclide I know that \tkzDrawLine(A,B) tkz-euclide draws a line between points A and B. However, I need to draw a ray that starts at A and goes through B. How can I do this?

A: Strictly speaking, I think, a ray is semi-infinite, and so impossible to draw. As an approximation, you can extend your line segment to a third point, and draw the 'truncated ray' thus:
\documentclass{article}
\usepackage{tkz-euclide}
\usetkzobj{all}
\begin{document}
\noindent
\begin{tikzpicture}
\tkzInit[ymin=0,ymax=5,xmin=0,xmax=8]
\tkzClip
\tkzDefPoint(1,1){A}
\tkzDefPoint(3,2){B}
\tkzDefPointBy[homothety=center A ratio 1.5](B) \tkzGetPoint{C}
\tkzDrawSegments(A,C)
\tkzDrawPoints(A,B)
\tkzLabelPoints(A,B)
\end{tikzpicture}\\
\end{document}

A: Simple manner, without tkzeuclide only using [pos = x] to set the position of the point on a path

\begin{document}

\begin{tikzpicture}

\node[draw,circle,label={A}] (A) at (0,0){};
\node[draw,circle,label={B}] (B) at (2,-3){};
\node[draw,circle,label={C}] (C) at (3,1){};

\draw (A) -- (C)  coordinate[pos=1.8](ff2) -- (ff2);
\path (A) -- (B) coordinate[pos=-0.5](dd) coordinate[pos=1.8](ff);
\draw (dd) -- (ff);
\end{tikzpicture}

\end{document}


text:
Q: How to check if a cookie is expired How do I check if a cookie I get through a GET request is expired or not?
I tried:
cookie, err := c.Request.Cookie("session")
if err == nil && time.Now().Before(cookie.Expires) {
    log.Printf("COOKIE IS STILL GOOD. YUM!\n")
    return
}

But when I debug I see the expiration date is incorrect:
2019/05/15 01:23:46 0001-01-01 00:00:00 +0000 UTC

The date is today, rather than 2051 like I set it to be, and nothing else makes sense. What is happening?

A: Because clients send names and values only in a Cookie header, the Name and Value fields are the only fields set in this context. The Expires field has the time.Time zero value as the log output indicates.
The application must do something outside of the cookie protocol to determine if the cookie is still valid.


text:
Q: Difference between requested and allocated memory - Spark on Kubernetes I am running a Spark Job in Kubernetes cluster using spark-submit command as below,
bin/spark-submit \
    --master k8s://https://api-server-host:443 \
    --deploy-mode cluster \
    --name spark-job-name \
    --conf spark.kubernetes.namespace=spark \
    --conf spark.kubernetes.container.image=docker-repo/pyspark:55 \
    --conf spark.kubernetes.authenticate.driver.serviceAccountName=spark-submit \
    --conf spark.kubernetes.pyspark.pythonVersion=3 \
    --conf spark.executor.memory=4G \
    --files local:///mnt/conf.json \
    local:///mnt/ingest.py

and when I check the request and limit for the executor pod, it shows below. There is almost 1700 MB extra got allocated for the pod.
Limits:
  memory:  5734Mi
Requests:
  cpu:     4
  memory:  5734Mi

Why is that?

A: In addition to @CptDolphin 's answer, be aware that Spark always allocates spark.executor.memoryOverhead extra memory (max of 10% of spark.executor.memory or 384MB, unless explicitly configured), and may allocate additional spark.executor.pyspark.memory if you defined that in your configuration.

A: What you define the pod (as individual system) can use is one thing, what you define spark or java or any other app runing inside that system (pod) can use, is another thing; think of it as normal computer with limits, and then your application with its own limits.


text:
Q: Showing top nav links only to users that have access I am working with SharePoint online. From a navigation perspective, I am leveraging Managed Metadata navigation to show links to certain sites which obviously is visible to everyone at the moment.
One of the challenges I have is, these links should be visible to only the users that they have access to them (not everyone). If a user doesn't have access to one of the links in top nav then he/she should not be seeing that link in the top nav. Is this possible to implement in SPO and if so then what would be the best way to achieve?
I am open to using other type of navigation as well.
Any help is appreciated, thanks in advance.

A: You can Use Structural Navigation and set your permission whatever you want.
Step1.Activate SharePoint Server Publishing Feature on your site collection level. (these features take little time.
Step 2. You can set audience targetting specific menus depending on your permissions.
as well as you can set your menus/links to open in a new window like that.

A: If you use Managed Metadata navigation, these links should be visible to the users who have permission on the term set and terms. If a user doesn't have access to one of the links but he has permission on the term set and terms, he can see the links.
You can Use Structural Navigation, activate "Limited-access user permission lockdown mode" site collection feature, these links should be visible to only the users that they have access to them (not everyone). Or you can set target audience on these links to limit which users can see those links.


text:
Q: Memory usage when creating and downloading zip archive as HttpContent I have a web api GET method that returns a zip file for downloading. Here's the code that creates the zip archive:
var resultStream = new MemoryStream();
using (var zipArchive = new ZipArchive(resultStream, ZipArchiveMode.Create, leaveOpen: true))
{
    foreach (var file in files)
    {
        zipArchive.CreateEntryFromFile(file.Path, file.Name, CompressionLevel.Optimal);
    }
}

And here's how the response gets populated:
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(resultStream.ToArray());
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "export_" + DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss") + ".zip";
response.Content.Headers.ContentDisposition.CreationDate = DateTime.Now;
response.Content.Headers.ContentDisposition.Size = resultStream.Length;
response.Content.Headers.ContentLength = resultStream.Length;

The code above works just fine, the problem is it consumes a lot of memory on the server, depending of course on the file sizes. I've tried changing the result to StreamContent, however this didn't work as the response only returned headers and eventually timed out.
So here are my questions:

*

*Is there a way to avoid loading all files in memory and instead send the zip file as it gets created?

*Is using StreamContent better to use in this scenario and if yes, what do I need to change to make it work?

*How is buffering affecting memory consumption in each case? I've tried disabling buffering by implementing a custom IHostBufferPolicySelector as suggested in this article, but it doesn't appear to have any effect.

*The api action currently can be called by navigating a link, using HttpClient or by AJAX request, so any solution has to support all scenarios.

A: Adapted from the Kudu project, a method that uses PushStreamContent in combination with a specific DelegatingStream wrapper to stream a zip archive:
public static class ZipStreamContent
{
    public static PushStreamContent Create(string fileName, Action<ZipArchive> onZip)
    {
        var content = new PushStreamContent((outputStream, httpContent, transportContext) =>
        {
            using (var zip = new ZipArchive(new StreamWrapper(outputStream), ZipArchiveMode.Create, leaveOpen: false))
            {
                onZip(zip);
            }
        });
        content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
        content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        content.Headers.ContentDisposition.FileName = fileName;
        return content;
    }

    // this wraps the read-only HttpResponseStream to support ZipArchive Position getter.
    public class StreamWrapper : DelegatingStream
    {
        private long _position = 0;

        public StreamWrapper(Stream stream)
            : base(stream)
        {
        }

        public override long Position
        {
            get { return _position; }
            set { throw new NotSupportedException(); }
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            _position += count;
            base.Write(buffer, offset, count);
        }

        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            _position += count;
            return base.BeginWrite(buffer, offset, count, callback, state);
        }
    }
}

Which for your case you could use like:
var response = new HttpResponseMessage(HttpStatusCode.OK);
var response.Content = ZipStreamContent.Create(
    "export_" + DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss") + ".zip",
    zipArchive => {
        foreach (var file in files)
        {
            zipArchive.CreateEntryFromFile(file.Path, file.Name, CompressionLevel.Optimal);
        }
    });


text:
Q: (hairSimulation/CFX) selecting multiple curves with its own duplicate and blendShape at the same time In maya I am simulating hair and I want to lock the curves that are jittering. I duplicated those curves to make blend shapes, but there are too many to blend shape them individually. Is there a way to script to solve this? I think the way is to slice to get the name/number of the curves and blendShape all of them with a loop. But since I'm new to scripting I need help.

A: You can get follicles with this command :
fols = cmds.ls(type='follicle')

After that, find the curves simulated :
crvs = cmds.ls(fols, dag=True, type='nurbsCurve')

Loop through those curves and use :
dup = cmds.duplicate(c)[0] # where c is the iterator of the for loop on crvs

then :
bs = cmds.blendShape(dup, c)

You have few flags on every command but it should help you like name, weight and few more.
I don't have maya for few weeks so I hope it will help you
EDIT :
Not that follicle curves are set as intermediate, for blendshaping, you might need to temporarly set them :
cmds.setAttr(c+'.io', 0)
bs = cmds.blendShape(dup, c)
cmds.setAttr(c+'.io', 1)


text:
Q: Integration, computation of integral in $[0,1]$. I am student in first year in economics. I don't have enough knowledge on integration.
I want to compute this integral:
\begin{equation*}
\int_{0}^{1} (\ln(p))(\ln(1-p)) dp
\end{equation*}
It will be great if you can detail the proof.

A: By the substitution $p = e^{-u}$,
\begin{align*}
\int_{0}^{1} \log p \log(1-p) \, dp
&= - \int_{0}^{\infty} u e^{-u} \log(1-e^{-u}) \, du.
\end{align*}
Then by the Taylor expansion of the logarithm,
\begin{align*}
\int_{0}^{1} \log p \log(1-p) \, dp
&= \int_{0}^{\infty} u e^{-u} \left\{ \sum_{n=1}^{\infty} \frac{e^{-nu}}{n} \right\} \, du \\
&= \sum_{n=1}^{\infty} \frac{1}{n} \int_{0}^{\infty} u e^{-(n+1)u} \, du \\
&= \sum_{n=1}^{\infty} \frac{1}{n(n+1)^{2}} \\
&= \sum_{n=1}^{\infty} \left( \frac{1}{n} - \frac{1}{n+1} - \frac{1}{(n+1)^{2}} \right) \\
&= 2 - \zeta(2)
 = 2-\frac{\pi^{2}}{6} \\
&\approx 0.355065933151773563527584833354\cdots.
\end{align*}
Or we can just make use of the beta function
$$ \beta(z, w) = \frac{\Gamma(z)\Gamma(w)}{\Gamma(z+w)} = \int_{0}^{1} x^{z-1}(1-x)^{w-1} \, dx $$
to obtain
\begin{align*}
\int_{0}^{1} \log p \log(1-p) \, dp
&= \frac{\partial^{2} \beta}{\partial z \partial w}(1, 1) \\
&= \beta(1, 1) \left\{ \left( \psi^{(0)}(1)-\psi ^{(0)}(2) \right)^{2} - \psi^{(1)}(2) \right\} \\
&= 1 \cdot \{ (-1)^{2} - (\zeta(2) - 1) \} \\
&= 2 - \zeta(2).
\end{align*}


text:
Q: Is there a similar server side IDE for Python (like Spyder) similar to running R-studio server? I am currently running r-studio via my server at work which is amazing having all the cores at my disposal when running really intensive algos... not to mention I can code anywhere via a web browser.  My question is, is there something similar for say Spyder and developing in Python?  I code 50/50, R/Python and would love to set up a similar workflow.  Thoughts?

A: If you are using Rstudio-server, unfortunately similar tool like that is not available. The closest to rstudio is Ipython notebook: http://ipython.org/ipython-doc/stable/interactive/notebook.html


text:
Q: Regular expressions in R to get the date What could be the better solution to get the date only, it is a tag of a webpage.
I hope someone could help me.
The patterns is this value in many pages "publishedAtDate":"2020-02-07"
I would like to have the next outcome:
2020-02-07
I am using this code:
art_publishdate<-regexpr("publishedAtDate\":\"[0-9]{4}-[0-9]{2}-[0-9]{2}\"", thepage)

but the result include many backslashes.
[1] "publishedAtDate\":\"2020-02-07\""

Thank you

A: Two ways to capture the output.
Using gsub we remove everything till a colon (:) is encountered.
string <- '"publishedAtDate":"2020-02-07"'
gsub('.*:|"', '', string)
#[1] "2020-02-07"

Or using sub we can extract date pattern.
sub('.*?(\\d+-\\d+-\\d+).*', '\\1', string)
#[1] "2020-02-07"

A: You could try to just pick out the numbers and format them as.Date.
as.Date(gsub("\\D", "\\1", '"publishedAtDate":"2020-02-07\"'), format="%Y%m%d")
# [1] "2020-02-07"

A: Another solution using str_extract from the stringr package:
str_extract(string, "[0-9]{4}-[0-9]{2}-[0-9]{2}")
[1] "2020-02-07"

Alternatively, the date can be extracted thus:
str_extract(string, "[0-9-]+")
[1] "2020-02-07"

Another alternative is using positive look-behind (which encodes the instruction "Match if you see on the left...") as well as a negated character class [^"], which excludes the quote mark but no other character:
str_extract(string, '(?<=:")[^"]*')
[1] "2020-02-07"


text:
Q: Error: operand of '*' must be a pointer I seem to be getting this error within my code and when I hover over the bit that says 'data' it says 'Error: operand of '*' must be a pointer'. Can anyone see possibly where the problem lies.
double* Matrix::get(int i, int j) const
    {
        return *data[i*N + j];
    }

A: Assuming data is an array member variable, what you need to say is:
return &data[i*N + j];

Also, as your function is const you should return a const pointer:
const double *Matrix::get(int i, int j) const
{
    return &data[i*N + j];
}

If you're not looking to have the caller modify the value in the array then change it to:
double Matrix::get(int i, int j) const
{
    return data[i*N + j];
}

A: If data is an array of double, then get rid of the * because you don't need to return the memory address:
double Matrix::get(int i, int j) const
{
    return data[i*N + j];
}


text:
Q: Connecting a Magellan RoadMate to a computer After reading this question...
Is it possible to connect a Magellan RoadMate (1200, to be specific) to a computer? I have an USB cable, but when I connect the device to my laptop, it isn't recognized by the OS (that is, neither Ubuntu's /var/log/syslog nor Windows' Device Manager show anything at all). The device is based on Windows CE Core 5.0 (or so it says on the back).

A: Perhaps a dumb question, but did it come with any drivers?
Though that doesn't necessarily solve your recognition problem...
Some people suggest that your cable is crap, bad wiring or something. Perhaps try another mini-USB cable?
I found something on a different device that had similar problems:

From Magellan:
Thank you for contacting Magellan.
  This email is in response to your
  query about the Explorist 210.
I understand that you are having
  difficulties in getting the unit
  detected on your computer.
Before you start doing these steps
  please check with the operating system
  in your PC. Because only WINDOWS XP,
  2000 would be compatible with
  Magellan. MACINTOSH would not be
  compatible with Magellan.

*

*Connect the USB cable to the Explorist unit in such a way that the
  USB cable is pointing downwards
  towards the battery case.

*Make sure that the unit is put up in the file transfer mode. After
  connecting the USB cable to the unit
  press menu and press enter in the file
  transfer mode.

*Make sure that you have connected the USB cable to the rear port and not
  to the front port of the PC. Then your
  unit would be detected as a new
  hardware under "Removable disk E:\ or
  G:\ or F:\"

*If you have any external devices like web cam or printer connected to
  the USB port please remove them.

*Also if you have any firewall or antivirus enabled in your PC please go
  ahead and disable them. Then restart
  your PC.

*Then remove the USB cable from your unit and power off the unit and then
  connect the USB cable and then power
  on the unit.
If the issue still persists, and If
  you could not install the CD then I
  would suggest you to please give a
  call to the technical support
  department number 1-800-707-9971 so
  that we would walk you through the
  trouble shooting steps to fix this
  issue.
If you have further queries, please
  get back to us.
You can also contact our Technical
  Support at 1-800-707-9971 for further
  assistance.
Regards, Steve  Magellan Email
  Support.

A: It is possible to connect Magellan GPS to laptop by following steps shown below;

*

*remove SD card from top slot (recording slot) to the slot on the left (reading slot) and then connect Magellan RoadMate GPS to laptop using USB cable.

*After that you have to open MiVue app on the laptop and click on Folder icon on the top left on the menu bar,

*Then in the Browse for Folders box, go to Removable Disk (G:).

*Select Normal or Parking Folder and click Open.

*The MiVue shows the video

*Click Play to play videos in that folder

*You can then save the video to laptop by selecting Save icon on top menu bar.

Sach

A: I was having the same issue.  Make sure you are using a compatible browser.  It won't connect using Google Chrome and make sure it's the actual browser from the internet and not app based.  Hope this helps.


text:
Q: curl hangs at no chunk, no close, no size. Assume close to signal end.With my http server I write a simple http server which now only can response 501.But when i test it. it shows

Trying 127.0.0.1...    * TCP_NODELAY set   * Connected to localhost
  (127.0.0.1) port 9999 (#0)

GET /bookstores/ HTTP/1.1
Host: localhost:9999
User-Agent: curl/7.58.0
Accept: /
HTTP/1.1 501 Not Implemented
no chunk, no close, no size. Assume close to signal end

my response code looks like that:
#include "handle_client.h"
#include <string.h>
const char *crlf = "\r\n";
const char *sp =" ";
const char *http_version = "HTTP/1.1";
const char *status_code_501 = "501";
char* response_501(){
    char *reason_phase = "Not Implemented";
    char *status_line = (char *)calloc(4096, sizeof(char));
    strcat(status_line, http_version);
    strcat(status_line, sp);
    strcat(status_line, status_code_501);
    strcat(status_line, sp);
    strcat(status_line, reason_phase);
    strcat(status_line, crlf);
    strcat(status_line, crlf);
    return status_line;
}

A: You need to either close the connection or supply a content-length header field (set to zero). See RFC 7230, Section 3.3.3.


text:
Q: Help in a simple homework exercise I need to create a method, in the following signature:
int x (int y);

That's the example of values that this it should return:
x(3) = 1
x(4) = 1
x(5) = 2
x(6) = 2
x(7) = 3
x(8) = 3
x(9) = 4
x(10) = 4
...

Any ideas how could I do it?
Thank you.
EDIT: That's what I've got so far:
    static int x(int y)
    {
        return (y / 2) - 1;
    }

but the problem is that:
x(3) = 0
x(4) = 1
x(5) = 1
x(6) = 2

A: Subtract 1 then integer divide by 2.

A: If you want to make a joke of those who asked you to do this (and if you know only values for 3 .. 10), you could also write the following method:
static int x(int y) {
  return (int)(10.0 * Math.Sin((double)y / 21.0));
}

It's probably not what they meant, but it should give the same results for arguments from 3 to 10 :-). And how did I find it? I know the graph of sin function, which is ascending in the beginning. Then I just tried to find out some 'magic constants' to find a configuration in which it returns the numbers you wanted...


text:
Q: Slow loss of connectivity to SQL Server 2005 Client has a dangerously open instance of SQL Server 2005.  VB.NET 1.1 connects to this from another server without problem.  Turning on Windows firewall with port 1433 open to subnets only seems like a quick stopgap solution.
DB seems fine, but begins to slow down over the course of an hour...  As though it is losing connections form it's pool.  Eventually no connections are possible from the app or other tools.
Does SQL Server require other ports to be open?
Linux guy here scratching his head.

A: Assuming you're running SQL Server with the defaults, then 1433 should be the only port you need open.
About the slowdown part - use my Perfmon monitoring tutorial to gather statistics about the SQL Server.  From there we can determine which part of the server is the bottleneck.  If you want, gather the stats as shown in the article for a few minutes while the server is fast, and then again while the server is slow.  There's no performance impact of gathering these statistics.  Then send the files to me at brento@brentozar.com and I should be able to tell pretty quickly where the bottleneck is.

A: Run sp_who2 to see who is connected and what they using.
JR

A: SQL Server provides a way to monitor open connections under "SQL Server Management Studio". I would check to make sure that connections are not getting opened up and left open from the application. Because unless the application explicitly closes the connection it could be possible for it to remain open until the Garbage Collector decides to finally clean up the object and release the connection back to the pool.
Another way to check and see if this is happening is to wait until the application can no longer get connected. Once in this state if restarting the application solves this problem then it is probably an issue with the application code.

A: When connections are no longer possible can you connect locally on the box?  If so then try connecting again using Management Studio but instead of using "Share Memory" use "TCP/IP".
If the latter fails then indeed I would investigate the firewall situation.  However I wouldn't be inclined to associate a firewall setting with "loss of connectivity over time".


text:
Q: Foreign Key Issues with Application User I am using entity framework core and code first to make some tables.
I want one table with two Foreign keys, with both being the application user.
I have it built and running, but every time I try to add to the table I get an error
SqlException: Violation of PRIMARY KEY constraint 'PK_ApplicationUser'. Cannot insert duplicate key in object 'dbo.ApplicationUser'. The duplicate key value is (ef20a79d-e819-499d-b006-c32f5cf85577).

This might just be a database design issue, but I feel like that I am doing this should work.
Here is the models:
    public class Test
    {
        public string TestId { get; set; }
        [ForeignKey("Giver")]
        public string GiverId { get; set; }
        public virtual ApplicationUser Giver { get; set; }
        [ForeignKey("Getter")]
        public string GetterId { get; set; }
        public virtual ApplicationUser Getter { get; set; }
    }

    // Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser
    {
        [InverseProperty("Giver")]
        public ICollection<CustomModels.Test> Giver { get; set; }
        [InverseProperty("Getter")]
        public ICollection<CustomModels.Test> Getter { get; set; }
    }

Here is the code to create the table:
migrationBuilder.CreateTable(
                name: "Tests",
                columns: table => new
                {
                    TestId = table.Column<string>(nullable: false),
                    GetterId = table.Column<string>(nullable: true),
                    GiverId = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Tests", x => x.TestId);
                    table.ForeignKey(
                        name: "FK_Tests_ApplicationUser_GetterId",
                        column: x => x.GetterId,
                        principalTable: "ApplicationUser",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_Tests_ApplicationUser_GiverId",
                        column: x => x.GiverId,
                        principalTable: "ApplicationUser",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateIndex(
                name: "IX_Tests_GetterId",
                table: "Tests",
                column: "GetterId");

            migrationBuilder.CreateIndex(
                name: "IX_Tests_GiverId",
                table: "Tests",
                column: "GiverId");

This is how I am adding to the DB:
Test test = (new Test
{
    Giver = await _userManager.GetUserAsync(User),
    Getter = await _userManager.Users.FirstOrDefaultAsync(u => u.Email == "s@gmail.com")
});
_context.Tests.Add(test);
await _context.SaveChangesAsync();

I would like to be able to track which user is giving information and which user is getting information.
We were using just the user email for tracking, but we would have to search for the email every time and I feel like this would be a better long-term solution.
I should be able to add as my "test" rows and repeat users, ie user1 can give to user2 and vise-versa, and that would be 2 different rows.

A: My guess is _userManager.GetUserAsync(User) isn't operating on the same DbContext as _context. So _context isn't aware of that ApplicationUser and will try to create it. The resolution to this would be to Attach the ApplicationUser before saving.


text:
Q: How to run Nginx and PHP on Mac OS X? I installed PHP 5.3.6 on Mac OS X 10.6 , but how can I run it with Nginx instead of Apache?
Previously I used MAMP with Apache but I would like to switch to nginx.
How can I install Nginx with PHP on Mac OS X?

A: The built in Apache2 with Mac OSX can run PHP by just uncommenting out this line in your httpd.conf file:
LoadModule php5_module libexec/apache2/libphp5.so
This won't work with Nginx
For Nginx you will have to compile it from source and configure your server files to use fastcgi.
You will also have to install php5-fpm or one of the old spawn-fcgi or php-cgi methods.  The PHP 5.3.6 you installed won't work with Nginx.
I would go with php-fpm and you can get installation instructions on the wiki..


text:
Q: Latvian characters into MySQL Database converting I have some problem. I have some data in my DB in Latvian (i.e Valentīna) and I need to display this on my page.
Other data are saved in cp1257 encoding and looks like AÎDA MACIJEVSKA - and it displays as Aīda Macijevska
So what I have tried...
1 - ucwords(mb_strtolower(iconv("windows-1257", "UTF-8//TRANSLIT", trim($row['pac_name'])), "UTF-8"));
2 - ucwords(mb_strtolower(iconv("windows-1257", "UTF-8", trim($row['pac_name'])), "UTF-8"));
3 - just show without any converting from DB `$row["pac_name"]`;

and all 3 points display same result - Valent?na
P.S Database has utf8_general_ci collation, also I gave header for utf-8 encoding - header('Content-Type: text/html; charset=utf-8');
So can anyone please help me with my problem?

A: Assuming you are truly using cp1257 and not utf8, then you need

*

*SET NAMES cp1257 (or some other way for the client to tell mysqld that the bytes are encoded using cp1257)

*CHARACTER SET cp1257 on each column (or perhaps defaulting from table definition).

But it sounds like you should go with utf8, not cp1257...
As I see it, Î does not exist in cp1257.  Reference: http://en.wikipedia.org/wiki/Windows-1257 .  Hence, the code you mentioned is free to screw it up, by either using ī or ?.
If you really need I-hat, go with utf8.  Note that the collation utf8_latvian_ci exists.  All the i's mentioned here do exist in utf8.
If you have further questions, please provide SELECT HEX(col)... for any text in question.  For example (with spaces added for clarity):
In utf8: AÎDA --> 41 C38E 44 41; Aīda --> 41 C4AB 64 61
In cp1257:  Aīda --> 41 EE 64 61


text:
Q: python selenium chrome webdriver giving me data; page I've been working with the following code, trying to introduce myself to selenium. When it runs, the chrome browser opens, but the page is blank, with no source code a far as I can tell, and 'data;' in the address bar. Any information on why this is happening would be greatly appreciated.
from selenium import webdriver

browser = webdriver.Chrome(service_args = ['--ignore-ssl-errors=true', '--ssl-protocol=TLSv1'])

url = 'https://www.google.com/'
browser.get(url)

I have also tried it without the service_args and tried it specifying the driver path and both, but get the same result each time

A: The most possibility is your browser not compatible with the webdriver.  Please confirm your browser version and webdriver version.
My chrome version is 60 and chromerdriver is chromedriver_2.30.exe
You can find compatible version from here

A: Update the chromedriver and Chrome Browser, sometime I also faced this issue.

A: I don't see any error as such in your code. Though the documentation for service_args is missing in the Selenium-Python API Docs as well as in the ChromeDriver Getting started Doc. But 0096850 clearly suggests service_args is implemented.
The service_args works well at my end. Hence I suspect there is a mismatch between Selenium version, chromedriver version and Chrome version we are using. First and foremost, we have to ensure that our Selenium version, chromedriver version and Chrome version are compatible. You can find the compatibility information on the Downloads page of ChromeDriver individually for each releases.
The Downloads page clearly mentions:

Latest Release: ChromeDriver 2.32 Supports Chrome v59-61

Additionally, you may be required to pass the argument executable_path to mention the absolute path of the chromedriver binary as follows:

Windows 8 based code:

from selenium import webdriver

browser = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe', service_args = ['--ignore-ssl-errors=true', '--ssl-protocol=TLSv1'])

url = 'https://www.google.com/'
browser.get(url)

A: I've met the same problem,but I solved it by updating my webdriver
Update your webdriver of chrome ,here is the link https://sites.google.com/a/chromium.org/chromedriver/downloads

A: If you're using Codeception, start the test with :
$I->amOnPage('/');

A: simply add this argument to selenium options (google how add options on solenium python to how to add options argument)
 options.add_argument("--remote-debugging-port=9225")


text:
Q: Turning simple Excel file into CartoDB map? I have Field 6 in my Excel sheet as a column of Zip Codes.
How do I get them to show up on the map using CartoDB?
My map continues to be blank.

A: As pointed out by @toms, you can find in the CartoDB documentation a step-by-step guide about how to geocode your data. Basically, click on the Edit buttom at the top of the Dataset View. Then, click on Georeference. Select "By postal code". And finally, select the field in which you have stored postal codes (Field 6) and choose the country your postal codes are located. Continue.


text:
Q: Why use transfinite induction? Why use transfinite induction to prove? I think the inclusion relation is trivial by transfinite recursion.

$\mathbf{11.B}$ The Borel Hierarchy
Assume now that $X$ is metrizable, so that every closed set is a $G_\delta$ set. Let $\omega_1$ be the first uncountable ordinal, and for $1 \leq \xi < \omega_1$ define by transfinite recursion the classes $\sum_\xi^0 (X)$, $\prod_\xi^0 (X)$ of subsets of $X$ as follows:
  \begin{align}
\sum_1^0 (X) &= \{U \subseteq X:U \text{ is open}\},  \\
\prod_\xi^0 (X) &= {} \sim \sum_\xi^0 (X),  \\
\sum_\xi^0 (X) &= \left\{ \bigcup_n A_n : A_n \in \prod_{\xi_n}^0 (X), \xi_n < \xi, n \in \mathbb{N}, \text{ if } \xi >1\right\}.
\end{align}
  In addition let $$\Delta_\xi^0 (X) = \sum_\xi^0 (X) \cap \prod_\xi^0 (X)$$ be the so-called ambiguous classes.
Traditionally, one denotes by $G(X)$ the class of open subsets of $X$, and by $F(X)$ the class of closed subsets of $X$. For any collection $\mathcal E$ of subsets of a set $X$, let
  \begin{align}
\mathcal E_\sigma &= \left\{ \bigcup_n A_n : A_n \in \mathcal E, n \in \mathbb N \right\},  \\
\mathcal E_\delta &= \left\{ \bigcap_n A_n : A_n \in \mathcal E, n \in \mathbb N \right\}.
\end{align}
  Then we have $\sum_1^0 (X) = G(X)$, $\prod_1^0 (X) = F(X)$, $\sum_2^0 (X) = (F(X))_\sigma = F_\sigma (X)$, $\prod_2^0 (X) = (G(X))_\delta = G_\delta (X)$, $\sum_3^0 (X) = (G_\delta(X))_\sigma = G_{\delta\sigma} (X)$,  $\prod_3^0 (X) = (F_\sigma(X))_\delta = F_{\sigma\delta} (X)$, etc. (Also, $\Delta_1^0 (X) = \{ A \subseteq X: A \text{ is clopen}\}$.) In general, an easy $\color{red}{\text{transfinite induction}}$ shows that
  $$\sum_\xi^0 (X) \cup \prod_\xi^0 (X) \subseteq \Delta_{\xi+1}^0 (X),$$

Thank you in advance.


text:
Q: How do I create an array with dynamic dimension sizes in C++? I'm looking to create an array (or vector?) to represent some files.
Basically, I'm going to have a variable number of input files. Each line of each file can be treated as a custom object (I'm calling them each a 'symbol'). There is a variable number of lines in each file.
So I'd like to have this kind of representation going on:
array[x][y]
where x will be referring to the file, and y the line in that file.
I'd seen a few topics on stackoverflow which suggested something along these lines
symbol **snapShots = new symbol*[usableFiles];
for(int i = 0; i < usableFiles; ++i) {
   snapShots[i] = new symbol[longestFile];
}

which is giving me an odd error message when building:
Undefined symbols for architecture x86_64:
   "symbol::symbol()", referenced from:
       _main in MarketDataGenerator.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
Info: Parallel threads used: 3

Any ideas how I'd go about this? Or would I just be better storing the information in file temporarily before reading back in for further processing?

A: Have you considered using std::vector<symbol> or std::vector<std::vector<symbol> >? What you linker is trying to tell you, is that you have declared a default constructor for your class symbol but not defined it (at least not in the files you are linking).


text:
Q: If $(1+x+x^2)^{25} =\sum^{50}_{r=0} a_r x^r$ then .... If $$(1+x+x^2)^{25} =\sum^{50}_{r=0} a_r x^r$$
then find :
$\sum^{16}_{r=0} a_{3r} =$
My approach :
let (1+x) =t  therefore,
$(1+x+x^2)^{25} =\sum^{50}_{r=0} a_r x^r$
=$(1+x+x^2)^{25} = (t+x^2)^{25}$
$= ^{25}C_0t^{25} +^{25}C_1 t^{24}x^2 +^{25}C_2 t^{23}x^4 +\cdots + x^{50}$
Also expanding the right hand side which is $\sum^{50}_{r=0} a_r x^r = a_0x^0 +a_1x+a_2x^2 +\cdots a_{50}x^{50}$
But unable to correlate this with the  given problem i.e how to find $\sum^{16}_{r=0} a_{3r}$ please guide further on this. thanks.

A: Hint: Evaluate at the two roots of the equation $1+x+x^2=0$ and at $x=1$, that is, at the three cube roots of unity, and add. The key fact is that if $\omega$ is one of the roots of $1+x+x^2=0$, then $\omega^2$ is the other, and $1^k+\omega^k+\omega^{2k}=0$ unless $k$ is divisible by $3$.

A: Here's an alternative approach.
In $(1+x+x^2)^n$ the coefficient $a_{n,k}$ of $x^k$ is the number of elements in the set $\{0,1,2\}^n$ whose terms sum to a multiple of $k$. (Why?) For $\ell\in\{0,1,2\}$ let
$$b_\ell(n)=\sum\{a_{n,k}:k\equiv\ell\!\!\!\pmod3\}\;;$$
equivalently, $b_\ell(n)$ is the number of elements in the set $\{0,1,2\}^n$ whose elements have a sum congruent to $\ell$ modulo $3$. It's not hard to see that
$$b_0(n)=b_1(n)=b_2(n)=b_0(n-1)+b_1(n-1)+b_2(n-1)$$
for $n\ge 1$: for any $\ell,m\in\{0,1,2\}$, each sequence in $\{0,1,2\}^{n-1}$ whose sum is congruent to $\ell$ modulo $3$ can be extended to exactly one sequence in $\{0,1,2\}^n$ whose sum is congruent to $m$ modulo $3$. Moreover, $b_0(0)=1$ and $b_1(0)=a_2(0)=0$, so by an easy induction
$$b_0(n)=b_1(n)=b_2(n)=3^{n-1}$$
for $n>0$.


text:
Q: How to install g++ compiler? I have tried the following:
sudo apt-get install build-essential
Reading package lists... Done
Building dependency tree
Reading state information... Done
build-essential is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

But when I compile the terminal shows the following:
g++ hello.cpp -o hello
The program 'g++' can be found in the following packages:
 * g++
 * pentium-builder
Try: sudo apt-get install <selected package>

What should I do?

A: The answer is in your question:

Try: sudo apt-get install <selected package>

In your case:
sudo apt-get install g++


text:
Q: How to populate a combobox using 3-tier architecture I am writing an application using 3-tier layer.
In presentation layer, I have a combobox that I need to populate with a simple SQL such as
SELECT distinct(Item) as items From ItemsTable order by items;

AFAIK, presentation layer shouldn't know about the name of the item column. Maybe the name will be changed in DB and I don't want to update the entire application, in the worst case only the DAL.
My question is how can I populate the combobox without having to write the name of the column (items)
ItemsComboBox.DisplayMember = "items";
ItemsComboBox.DataSource = _businessLayer.GetListOfItems();

Business Layer:
public DataTable GetListOfItems()
    {
        return DataAccess.Instance.Retrieve("TableName", "items");
    }

A: _businessLayer.GetListOfItems();

*

*Business layer should query Data Layer and not the DB.

*Only Data layer will be affected if DB changes.

It's better to create a business entity which won't change and use it
You can use some tool like AutoMapper  if you don't want to create them manually.
You can refer this in MSDN

A: You should define a class specifically for the transfer of data between the business layer and presentation layer. This is called a data transfer object. It will not hurt to reuse the same naming for the properties in DTO classes as the column names from your entities. Your business layer method would get the data from the database, populate the DTO and return it to the calling method in the presentation layer. The same object can be used to pass data back. If a column name then changes in the entity, you can amend the database access in the business layer without affecting the presentation layer. There are some great videos on application architecture by Bob Tabor on youtube. He explains it all very well.


text:
Q: Parsing JSON feed (WP feed) into React Native feed page I am not seeing any result in my simulator when I am parsing JSON feed (Wordpress JSON feed) into my React Native feed page, following is the code I am using;
----------AppBody.js----------
    import React, {Component} from 'react';
    import {Text, View, Image, StyleSheet, Dimensions} from 'react-native';
    import {Content, Container, Card, CardItem, Body} from 'native-base';

    import AppBodyData from './AppBodyData';

    export default class AppBody extends Component {

      constructor() {
        super()
        this.state={
          data:[]
        }
      }

      getData() {

        return fetch('https://www.rayaccountants.co.uk/feed/json')
              .then((response) => response.json())
              .then((responseJson) => {
                this.setState({data: responseJson.items});
              })
              .catch((error) => {
                console.error(error);
              });
      }

      componenetDidMount(){
        this.getData();
      }

      render() {
        return (
          <Container style={{
            marginTop: 100
            }}>
          <AppBodyData data={this.state.data}/>
          </Container>
        );
      }
    }

    module.export = AppBody;

----------AppBodyData.js----------
    import React, {Component} from 'react';
    import {Text, View, Image, StyleSheet, Dimensions} from 'react-native';
    import {Content, Container, Card, CardItem, Body} from 'native-base';

    export default class AppBodyData extends Component {
      render() {

        let articles = this.props.data.map(function(articlesData, index) {
          return (
            <Card>
              <CardItem>
                <Body>
                  <Text>
                    {articlesData.title}
                  </Text>
                </Body>
              </CardItem>
            </Card>
          )
        });

        return (
          <Container style={{
            marginTop: 60
          }}>
            <Container>
              {articles}
            </Container>
          </Container>
        );
      }
    }

    module.export = AppBodyData;

Following is what I am getting on my simulator, wonders what I might have overlooked?
iOS Simulator Screenshot

A: Change this this.setState({data: responseJson.items}) to this.setState({data: responseJson.items} ,() => console.log(this.state.data)) and you should be able to see whether you're getting the data correctly. If it does log then its just a styling issue and you might need to just add height/widths to see them rendered on the screen. Also you don't need to do module.export when you're doing export default already.


text:
Q: C++ modules and circular class reference To learn more about C++20 modules, I'm in the process of migrating a graphics application from header files to modules. At the moment I have a problem with a circular dependency between two classes. The two classes describe nodes and edges of a graph. The edge class has pointers to two nodes and the node class has a vector of pointers to adjacent edges. I know, there are other ways to describe a graph, but this archtitecture seems very natural to me, I have very fast access to neighboring elements and it works seamlessly in the old world of header files and #include. The key are forward references.
But in the new world of C++20 modules, forward references no longer work.
The topic of circular references has been discussed in many places, but I haven't yet found a solution that really convinces me.
A common statement is that circular references are an architectural problem and should be avoided. If necessary, the two classes should be packed into one module. That would clearly be a step backwards. I try to make modules small and elementary.
I could replace the pointers to nodes or edges with pointers to a common base class NetworkObject that actually already exists. But that would destroy valuable information and force me to use static_cast to artificially add the type information back.
My question is: Am I missing anything? Is there an easier way?

A: There are a few misconceptions I can see here. Not entirely false, but not entirely true either.

But in the new world of C++20 modules, forward references no longer work.

This is not completely true. You cannot use forward reference that would declare something as part of a different module, but you can certainly do that within the same module.
For example:
export module M;

export namespace n {
    struct B;

    struct A {
        B* b;
    };

    struct B {
        A* a;
    };
}

Then you can split it up in multiple module partitions:
export module M:a;

namespace n {
    struct B;
    export struct A {
        B* b;
    };
};

export module M:b;

namespace n {
    struct A;
    export struct B {
        A* b;
    };
};

export module M;
export import :a;
export import :b;

The gist of it is that types that depends on each other to be defined are coupled enough that they must reside in the same module.
Also, note that modules are not necessarily supposed to be as granular as headers. Dividing your modules too much could hurt compile time performances. For example, a whole library could be just one big module. The standard library chose this approach and export everything in the std modules and turns out it's faster than dividing the standard library in many smaller modules.
Smaller modules are not as good as many may think. Related things and classes should be packed in the same module, and if further splitting is needed for code organization within that module, partitions are an option.
The amount of modules and their name is part of your API. This means that if you have too much fine grained module, simply moving your code around will result in a breaking change. Module partitions are not part of your API and can be moved around freely.

A common statement is that circular references are an architectural problem and should be avoided. If necessary, the two classes should be packed into one module. That would clearly be a step backwards. I try to make modules small and elementary.

Those modules would not be small and elementary because of the cycle between them. ie you can't just use one module without also using the other. You will need to link against that other module if the implementation reside in another static library.

The two classes describe nodes and edges of a graph

We there be a program that would work with only the nodes module or only the edges module? Hardly. They should be part of the graph module. You could have a :edge and :node partitions, but it would not make sense using only one of those in a program or part of program.
If this is for compile times, then making bigger modules has been proven today that they are faster than smaller modules with current compiler technologies
The rationale for splitting modules into smaller modules is that there would be a use case for wanting to only import certain specific things. For example, std.freestanding would only contain the freestanding part of the standard library so programmers don't accidentally use parts they are not allowed to use.

Of course, another way to do that would be to drop all the modules safeguards and use Global Module Fragments (GMF). Using that allows modules to interface with the implicit global module. And yes, using that allows the benefit and the consequences that comes with global forward declaration. You will open the way for ODR violations to become possible again, and your entities won't be part of a named module anymore. It also allows a user to use your entities without importing the specific named module the declaration reside in, bypassing the API you expose to your users via your module names.
You can open Pandora's box using the extern "C++" directive:
export module A;

export namespace n {
    extern "C++" {
        struct B;
        struct A {
            B* b;
        };
    }
}

export module B;

export namespace n {
    extern "C++" {
        struct A;
        struct B {
            A* a;
        };
    }
}

Live example


text:
Q: 1980s Sci Fi Children's stories. Similar to Star Trek As a young child in the late 1980s or early 1990s, I remember reading at school a series of sci fi illustrated books. However, the books may have been older. The series was similar to Star Trek in appearance. I remember one story about a planet of ant like aliens. One of the characters may have been called something like 'Commander Peck'.
Can anyone help me identify these stories?
Thank you.


text:
Q: iphone - iOS Enterprise apps warning message Following is the pop up message when my clients first launch the Apps
Are you sure you want to open the application "Application Name" from Developer "iPhone distribution certificate name
However, I found that some of my client's device do not pop up this warning message even they first launch the apps. So my questions are

*

*By which condition the warning message will display when first launch the apps

*Is is possible to modify the warning message and how to do it

Thanks!

A: By which condition the warning message will display when first launch the apps
I think for the first time when one of your Enterprise apps is launched you see that Alert message.
Is is possible to modify the warning message and how to do it
No, that AlertView generated by the OS. Don't have control over it.


text:
Q: Notational(?) Question in Whiting's Paper "Mode Stability of the Kerr Black Hole" I am a math grad student attempting to read Bernard Whiting's paper "Mode Stability of the Kerr Black Hole." If you are in a university network, the paper should be easily found by a google search. At the beginning of the paper Whiting refers to the "master equation of Teukolsky" from the paper "Rotating Black Holes: Separable Wave Equations for Gravitational and Electromagnetic Perturbations." However, the equation Whiting writes down appears (to me) to be different than Teukolsky's. I assume I am missing something silly and was hoping that someone else has read this paper and can easily point out my mistake.
One needs to look at the paper for all the relevant definitions, but for ease of reference:
Whiting writes down
$\{\partial_r\Delta\partial_r - (1/\Delta)\{(r^2+a^2)\partial_t + a\partial_{\phi} - (r-M)s\}^2 - 4s(r+ia\cos\theta)\partial_t + $
$\partial_{\cos\theta}\sin^2\theta\partial_{\cos\theta} + (1/\sin^2\theta)\{a\sin^2\theta\partial_t + \partial_{\phi} + i\cos\theta\cdot s\}^2\}\psi = 0$
where $\Delta = r^2 - 2Mr + a^2$
while Teukolsky writes down
$\{(\frac{(r^2+a^2)^2}{\Delta} - a^2\sin^2\theta)\partial^2_t + \frac{4Mar}{\Delta}\partial^2_{t,\phi} + (\frac{a^2}{\Delta} - \frac{1}{\sin^2\theta})\partial^2_{\phi} - \Delta^{-s}\partial_r(\Delta^{s+1}\partial_r) - $
$\frac{1}{\sin\theta} \partial_{\theta}(\sin\theta\partial_{\theta}) - 2s(\frac{a(r-M)}{\Delta} + \frac{i\cos\theta}{\sin^2\theta})\partial_{\phi} - 2s(\frac{M(r^2-a^2)}{\Delta}-r-ia\cos\theta)\partial_t$
$ + (s^2\cot^2\theta - s)\}\psi = 0$
When I expanded out Whiting's equation out I did not get Teukolsky's equation. For example, it is clear that the $\partial_r$ terms are different. I also got that the constant terms (no derivative terms) did not agree.

A: Probably the definition of $\psi$ are slightly different? Judging by the fact that you get a different $\partial_r$ term and a different constant term, I am guess that Whiting's equation is Teukolsky's but commuted against $\Delta^l$ for some power $l$. (In other words, in Whiting's equation, replace $\psi \to \Delta^l\psi$ and divide the entire equation by $\Delta^l$, you should be able to find a $l$ (which depends on $s$, I think) that makes the two equation appear the same.)
(Observe that $\Delta^l$ commutes through the entire equation except for terms which have derivatives in $r$.)


text:
Q: Xamarin.Forms: SearchBar font size on windows phone I have a problem with styling the SearchBar for Windows phone. The font size is just unbearably huge and there is not property I can set directly. I've read a bit upon custom renederers (though I believe that's just overkill if I jsut wanted to set font size imho) but I really don't know how to even begin and it's the only thing now that's holding me back from being able to deploy to Windows Phone. I tried searching for it but uncle Google sadly let me down on this one. Any help is of course greatly appreciated.
Screenshot:

A: Unfortunately, the documentation says it has no property to change the font size. So you do not have another option that implementarte a custom render for that control.
It could be that your cell had changed the size of the system font to a larger size?
Documentation:
https://developer.xamarin.com/api/type/Xamarin.Forms.SearchBar/
Examples:
https://forums.xamarin.com/discussion/27424/simple-custom-renderer-of-searchbar-android

A: if you are using xaml then you can control style for different platforms like this:
<SearchBar x:Name="Search"
           Placeholder="Search"
           TextChanged="SearchBar_OnTextChanged"
           SearchButtonPressed="OnSearch" BackgroundColor="#19588F">
         <SearchBar.FontSize>
             <OnPlatform x:TypeArguments="x:Double"
                         WinPhone="10"
                         Android="22"
                         iOS="20" />
         </SearchBar.FontSize>
 </SearchBar>


text:
Q: Define HTML attribute name with razor syntax With MVC 5 and Razor 3 I'm trying to dynamically create an HTML Attribute Name with razor syntax, specifically a data-* attribute.
So this is about the name of the attribute and not the value.
Example for terminology:

Attribute Name: data-foo
Attribute Value: bar
This is what I'm trying with Razor syntax:

Neither examples are recognized by Razor and are rendered as is. So the html attribute name output is literally: data-search-@Model.Name.
Razor:

Output:

Am I out of luck here?

A: I think that the reason it doesn't work is, that @ is actually a valid character for an attribute in HTML5, and therefore Razor will not activate "code-mode" in this exact scenario. You could achieve what you are trying to do by building the attribute name completely in Razor code as follows:

However, this is not particularly pretty and although it functions properly, it can cause Visual Studio and ReSharper to complain about a missing attribute name. Instead I would probably make a helper function:
public class HtmlAttribute : IHtmlString
{
    public string Name { get; }
    public string Value { get; }

    public HtmlAttribute(string name, string value)
    {
        Name = name;
        Value = value;
    }

    public string ToHtmlString()
    {
        return $"{Name}=\"{Value}\"";
    }
}

public class static HtmlHelperExtensions
{
    public static HtmlAttribute Attribute(this HtmlHelper helper, string name, string value)
    {
        return new HtmlAttribute(name, value);
    }
}

Usage:

A: Here is a version for ASP.NET Core
public class HtmlAttribute : IHtmlContent
{
    public string Name { get; }
    public string Value { get; }

    public HtmlAttribute(string name, string value)
    {
        Name = name;
        Value = value;
    }

    public void WriteTo(TextWriter writer, HtmlEncoder encoder)
    {
        writer.Write($"{Name}=\"{Value}\"");
    }
}

public static class HtmlHelperExtensions
{
    public static HtmlAttribute Attribute(this IHtmlHelper helper, string name, string value)
    {
        return new HtmlAttribute(name, value);
    }
}


text:
Q: How to set vertical text from bottom to top in html? It is easy to set text from top to bottom and there are enough resources to do that.
The problem is with bottom to top vertical alignment.
See the image below-

A: You might want to try this.
.rotate {

/* Safari */
-webkit-transform: rotate(-90deg);

/* Firefox */
-moz-transform: rotate(-90deg);

/* IE */
-ms-transform: rotate(-90deg);

/* Opera */
-o-transform: rotate(-90deg);

/* Internet Explorer */
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);

}

A: This should work:

Vertical Text

A: div {
    top:90px;
    position:relative;
    width:50px;
    white-space:nowrap;
    -ms-transform:rotate(270deg);
    -moz-transform:rotate(270deg);
    -webkit-transform:rotate(270deg);
    -o-transform:rotate(270deg);
}

Worked well for me.


text:
Q: Android: TextInputEditText used for IP Good Morning everyone.
In my android app, I have a TextInputEditText (com.google.android.material.textfield.TextInputEditText) that I use for IP. I added the attributes:
                android:inputType="number|numberDecimal"
                android:digits="0123456789."

Usually everything works fine on smartphones, the user can write the ip and I have a TextWatcher that will validate the ip. If the ip is not valid, the 'OK' button is disabled. The user can only write numbers and points. The user can obviously write more points (an IP contains 3 points, like 127.0.0.1).
The only problem is on Android TV that things get a little weird. In particular, only the first point is visible. But the others are somehow 'memorized'.
To explain better, let's say the user use the D-Pad to write, and write '1.1.1.1' using the virtual keyboard, then he will see only '1.111'. But after clicking ok in order to close the keyboard, the IP is correctly displayed as '1.1.1.1'. So, more than a technical problem, is a bad user expierence.
Does someone have some suggestion how to improve the user expierence?
Is there some specific inputType for IPs?
Thanks everyone


text:
Q: JUL log messages and Apache log4j2 log4j-jul logging as org.apache.commons.logging.impl.Jdk14Logger I have an application using log4j2 with tomcat-jdbc. The tomcat-jdbc classes all log using java.util.logging (JUL), so I looked it up and saw I could route all JUL log calls to log4j2 with the following dependency and JVM parameter:
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-jul</artifactId>
        <version>${log4j.version}</version>
    </dependency>

And the JVM parameter -Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager.
Overall, my maven logging config is:
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <log4j.version>2.3</log4j.version>
    <oracle.ojdbc.version>11.2.0</oracle.ojdbc.version>
    <spring.framework.version>4.1.6.RELEASE</spring.framework.version>
</properties>
<dependencies>
    <!-- Logging using log4j 2.x -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-jul</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j-impl</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <!-- snipped non log4j related dependencies -->
<dependencies>

When I run the app, I get messages from tomcat-jdbc in my log4j2 logs now, but I can't tell where they are coming from because the LogManager from log4j-jul is overwriting that information:
2015/10/13 08:00:23.358 DEBUG 20512[main] org.apache.commons.logging.impl.Jdk14Logger log:99 - Executing prepared SQL query
2015/10/13 08:00:23.360 DEBUG 20512[main] org.apache.commons.logging.impl.Jdk14Logger log:99 - Executing prepared SQL statement [...]
2015/10/13 08:00:23.362 DEBUG 20512[main] org.apache.commons.logging.impl.Jdk14Logger log:99 - Fetching JDBC Connection from DataSource
2015/10/13 08:00:23.415 DEBUG 20512[main] org.apache.commons.logging.impl.Jdk14Logger log:99 - Returning JDBC Connection to DataSource
How can I get the information from the original message placed in the log?
I know Log4perl had a variable you could adjust if you were intercepting an event (via signal handler, etc): $Log::Log4perl::caller_depth++;, which would facilitate this. Not necessarily sure if this would be helpful though, since the code that re-routes the logging is done from a 3rd party library (org.apache.logging.log4j/log4j-jul)...
Thanks!


text:
Q: Simple modal JSON Jquery I will like to have have my content that is in a JSON file, populate my modal window  dynamically.
I want when everytime you click a corresponding the link or  maybe it can be a div with an ID on it....that specific content comes in the simple modal dialog window automatically .
JSON FILE
{
    "mycontent": [
        {
            "content": "content 1"
        }, {
            "entry": "content 2"
        }
        , {
            "entry": "content 3"
        }
    ]
}

Javascript
jQuery(function ($) {
    $.getJSON('/json.json', function(data){

    // Load dialog on page load
    //$('#basic-modal-content').modal();

    // Load dialog on click
    $('#basic-modal .basic').click(function (e) {
        $('#basic-modal-content').modal();

        return false;
    });
});

HTML
content 1
content 2
content 3

I'm using: http://www.ericmmartin.com/projects/simplemodal-demos/

A: look at this code:
$('#basic-modal .basic').click(function (e) {
    $.getJSON('/json.json', function(data){
        if( data != undefined && data.length > 0)
        {
            for( i=0; i < data.length; i++)
            {
                $('#DIV-ID').append( data.i.content... .... .. you code here... );
            }
            $('#basic-modal-content').modal();
        }
    });
    return false;
});