text:
Q: How can I use redis with Django? I've heard of redis-cache but how exactly does it work? Is it used as a layer between django and my rdbms, by caching the rdbms queries somehow?
Or is it supposed to be used directly as the database? Which I doubt, since that github page doesn't cover any login details, no setup.. just tells you to set some config property.

A: This Python module for Redis has a clear usage example in the readme: http://github.com/andymccurdy/redis-py
Redis is designed to be a RAM cache. It supports basic GET and SET of keys plus the storing of collections such as dictionaries. You can cache RDBMS queries by storing their output in Redis. The goal would be to speed up your Django site. Don't start using Redis or any other cache until you need the speed - don't prematurely optimize.

A: Just because Redis stores things in-memory does not mean that it is meant to be a cache. I have seen people using it as a persistent store for data.
That it can be used as a cache is a hint that it is useful as a high-performance storage. If your Redis system goes down though you might loose data that was not been written back onto the disk again. There are some ways to mitigate such dangers, e.g. a hot-standby replica.
If your data is 'mission-critical', like if you run a bank or a shop, Redis might not be the best pick for you. But if you write a high-traffic game with persistent live data or some social-interaction stuff and manage the probability of data-loss to be quite acceptable, then Redis might be worth a look.
Anyway, the point remains, yes, Redis can be used as a database.

A: You can also use Redis as a queue for distributed tasks in your Django app. You can use it as a message broker for Celery or Python RQ.

A: Redis as a Primary database
Yes you can use Redis key-value store as a primary database.
Redis not only store key-value pairs it also support different data structures like

*

*List

*Set

*Sorted set

*Hashes

*Bitmaps

*Hyperloglogs

Redis Data types Official doc
Redis is in memory key-value store so you must aware of it if Redis server failure occurred your data will be lost.
Redis can also persist data check official doc.
Redis Persistence Official doc

Redis as a Cache
Yes Redis reside between in Django and RDBMS.
How it works

given a URL, try finding that page in the cache if the page is in the cache: return the cached page else: generate the page save the generated page in the cache (for next time) return the generated page

Django's cache framework Official Doc

How can use Redis with Django
We can use redis python client redis-py for Django application.
Redis python client redis-py Github
We can use Django-redis for django cache backend.
Django-redis build on redis-py and added extra features related to django application.
Django-redis doc Github
Other libraries also exists.

Redis use cases and data types
Some use cases

*

*Session cache

*Real time analytics

*Web caching

*Leaderboards

Top Redis Use Cases by Core Data structure types

Big Tech companies using Redis
 Twitter GitHub Weibo Pinterest Snapchat Craigslist Digg StackOverflow Flickr

A: Redis is basically an 'in memory' KV store with loads of bells and whistles. It is extremely flexible. You can use it as a temporary store, like a cache, or a permanent store, like a database (with caveats as mentioned in other answers).
When combined with Django the best/most common use case for Redis is probably to cache 'responses' and sessions.
There's a backend here https://github.com/sebleier/django-redis-cache/ and excellent documentation in the Django docs here: https://docs.djangoproject.com/en/1.3/topics/cache/ .
I've recently started using https://github.com/erussell/django-redis-status to monitor my cache - works a charm. (Configure maxmemory on redis or the results aren't so very useful).


text:
Q: LTRIM does not remove leading space in SQL I load data from a text file and it seems that it does not contain leading space, however when I SELECT from a table, I see the leading space but cannot remove it with a LTRIM function:
SELECT ltrim(DATA) FROM MYTABLE WHERE LineNumber = 4

I'm getting the following:

T000000000004

with a single leading space before T
When I do select convert(varbinary,data) from mytable, that's what I get:
0x0A54303030303030303030303034

In the file it looks ok: T000000000004 - no leading space and it starts from the first character in the file. However, in the table it's inserted with a leading space.
How can I fix it?

A: As HABO mentioned, your value doesn't start with a space, it doesn't actually have any white space in it at all, it has a leading Line Feed (character 10, or 0X0A).
To remove these, and any carriage returns you might have too, you can use REPLACE:
REPLACE(REPLACE(data,CHAR(10),'')),CHAR(13),'')

(L/R)TRIM only remove leading/trailing white space. Nothing else.
If there could be a range of leading characters, and you want to remove all of them up to say the first alphanumerical character, you can use PATINDEX and STUFF:
SELECT STUFF(V.[data],1,PATINDEX('%[A-z1-9]%',V.[data])-1,'')
FROM (VALUES(CHAR(10) + CHAR(13) + '  -T000000129B'))V([data])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linear isometry and its trace (We're in $\mathbb{R}^3$)
What can we say about type of linear isometry $F : \mathbb{R}^3 \to \mathbb{R}^3$ if trace of $\mathrm{m} (F)$ is $-2$ or $\frac{1}{\sqrt{2}}$ or $\sqrt{2}$? Which one of these three cases says anything about type of linear isometry (is it rotation, symmetry or something else), and which one doesn't tell anything?
So far I just figured out, that any 3x3 matrix has at least one real eigenvalue $|\lambda| = 1$ and of course $\mathrm{tr} (\mathrm{m} (F)) = \mathrm{tr} (PJP^{-1}) = \mathrm{tr} (J)$, where $J$ is either $\begin{pmatrix} \lambda & 0 & 0 \\ 0 & \mu & 0 \\ 0 & 0 & \eta \end{pmatrix}$ or $\begin{pmatrix} \lambda & 0 & 0 \\ 0 & \mu & 1 \\ 0 & 0 & \mu \end{pmatrix}$ or $\begin{pmatrix} \lambda & 1 & 0 \\ 0 & \lambda & 1 \\ 0 & 0 & \lambda \end{pmatrix}$. Thus in case of trace $-2$ is either

*

*$3\lambda = -2$

*or $\lambda + 2\mu = -2$

*or $\lambda + \mu + \eta = -2$
First case we rule out, cause only eigenvalue has to be $1$ or $-1$, so that can't hold. Second case turns into

*

*$\lambda = 1$ and $\mu = -\frac{1}{2}$ or $\lambda = -1$ and $\mu = -\frac{3}{2}$

*$\lambda = 0$ and $\mu = -1$ or $\lambda = -4$ and $\mu = 1$
And last case is just $\lambda + \mu = -1$ or $\lambda + \mu = -3$
I don't know what can I do with that information, how to determine type of linear isometry using that. Any hints would be much appriciated.

A: There are basically two kinds of linear isometry of $\mathbb R^3$: rotations (including the identity transformation which is a rotation by angle $0$) and improper rotations (including reflection across a plane which is an improper rotation by angle $0$, and reflection through the origin which is an improper rotation by angle $\pi$).  A rotation of $\mathbb R^3$ by angle $\theta$ has eigenvalues $1$, $e^{i\theta}$ and $e^{-i\theta}$, so its trace is $1 + 2 \cos(\theta) \in [-1,3]$.  An improper rotation by angle $\theta$ has eigenvalues $-1$, $e^{i\theta}$ and $e^{-i\theta}$ so its trace is $-1 + 2 \cos(\theta) \in [-3,1]$.  So if the trace is $-2$ it can only be
an improper rotation with $\cos(\theta) = -1/2$, if the trace is $\sqrt{2}$ it can only be a rotation with $\cos(\theta) = (\sqrt{2}-1)/2$, and if the trace is $1/\sqrt{2}$ it could be either.

A: It is not necessary at all to use Jordan form.
You only need two results :
1) The eigenvalues of an isometry have a unit modulus.
2) In $\mathbb{R^3}$, the characteristic equation of the corresponding matrix has degree 3, thus with

*

*either 3 real values, which must then be either $1$ (order of multiplicity n) and/or $-1$ (order of multiplicity $(3-n)$), thus with trace

$$n1+(3-n)(-1) \ = \ 2n-3 ;$$
Otherwise said, in this case, the trace can take only 4 values
$$\{-3,-1,1,3\},$$
none of them corresponding to the desired traces :
$$t_1=-2, t_2=\dfrac{1}{\sqrt{2}}, t_3=\sqrt{2}. \tag{1}$$

*

*or one real value ($+1$ or $-1$) and two complex conjugate ones $e^{\pm i \theta}$ giving a trace equal either to $1+2 \cos \theta$ (by using Euler formula $e^{i \theta}=\cos \theta+i \sin \theta$), covering the range $(-1,3)$, or $-1+2 \cos \theta$  covering the range $(-3,1)$ thus giving solutions for all the values given in (1).

Let us consider the case of $t_1=-2$ : one sees that the eigenvalues are necessarily $\{-1, e^{i \theta}, e^{-i \theta}\}$ (with $\theta=2\pi/3$), the corresponding matrix being :
$$\begin{pmatrix}-1&0&0\\0&\cos(\theta)&-\sin(\theta)\\0&\sin(\theta)&\cos(\theta) \end{pmatrix}=\begin{pmatrix}-1&0&0\\0&1&0\\0&0&1 \end{pmatrix}\begin{pmatrix}1&0&0\\0&\cos(\theta)&-\sin(\theta)\\0&\sin(\theta)&\cos(\theta) \end{pmatrix}$$
which can be characterized as a rotation in plane $yOz$ followed by the orthogonal symmetry with respect to this plane (in either order, in fact).
I leave you the two other cases.
Remark dealing with the subrange $(-1,1) \subset (-3,3)$ : if the trace is in this reduced range, one can express it in two different ways $1+2 \cos \theta_1$, or $-1+2 \cos \theta_2$.


text:
Q: javascript var statement per scope Looks like a lot of var per  scope is a waste of bytes and bad code habits. I dont know how to fix my code. how should I edit the lines below as per good JS practices?
<script type="text/javascript">
// <![CDATA[
    var jump_page = '{LA_JUMP_PAGE}:';
    var on_page = '{ON_PAGE}';
    var per_page = '{PER_PAGE}';
    var base_url = '{A_BASE_URL}';
    var style_cookie = 'style';
    var style_cookie_settings = '{A_COOKIE_SETTINGS}';
    var onload_functions = new Array();
    var onunload_functions = new Array();

    /**
    * Find a member
    */
    function find_username(url)
    {
        popup(url, 760, 570, '_usersearch');
        return false;
    }

    /**
    * New function for handling multiple calls to window.onload and window.unload by pentapenguin
    */
    window.onload = function()
    {
        for (var i = 0; i < onload_functions.length; i++)
        {
            eval(onload_functions[i]);
        }
    };

    window.onunload = function()
    {
        for (var i = 0; i < onunload_functions.length; i++)
        {
            eval(onunload_functions[i]);
        }
    };

// ]]>
</script>

A: I always recommend scoping variables to only the scope that needs them. It's a common error source to use global variables since you can have conflicts.
I will some times wrap my code in JavaScript closures to avoid adding variables to the global scope since variables in global scope never become eligible for garbage collection.

A: If you're looking to avoid polluting the global window scope then you can wrap the whole thing up like this:
(function() {
  "use strict";
  var onunload_functions = [];

  window.onunload = function()
  {
    for (var i = 0; i < onunload_functions.length; i++)
    {
      eval(onunload_functions[i]);
    }
  };

}());

This closure will prevent random var variables being added to window / global scope.


text:
Q: How to pass arguments in bulk to another step in a Github Action? I want to pass the value set by core.setOutput to different steps at once. So I passed the outputs of the step hello-action to another step:
//index.js
const core = require("@actions/core");
core.setOutput("res1","res1");
core.setOutput("res2","res2");
core.setOutput("res3","res3");

jobs:
  build:
    runs-on: ubuntu-latest
    name: Hello
    steps:
      - name: Checkout
        uses: actions/checkout@master
      - name: run hello action
        id: hello-action
        run: node index.js
      - name: run hello2 action
        id: hello2-action
        run: node index2.js
        with:
          outputs: ${{ steps.hello-action.outputs }}

point is this.
outputs: ${{ steps.hello-action.outputs }}

The type of the above value is an object, but I couldn't access the key inside the object.
//index2.js
const core = require("@actions/core");
const outputs = core.getInput("outputs");
console.log("hello2 outputs:", outputs); //result is [object Object]
console.log("hello2 outputs:", outputs.res1); //result is undefined

Is there a way to pass arguments in bulk?

A: Objects cannot be transferred to output from action, only strings.
Therefore, when passing an object from a custom action toString() method will be called on it. As a result, you get your [object Object] already at the moment of performing this action here:
- name: run hello action
  id: hello-action
  run: node index.js

To transfer data structures from a custom action, cast object to JSON string using JSON.stringify() method.
first action
//index1.js
const obj = {
    field1: "value1",
    field2: "value2",
}
core.setOutput("outputs", JSON.stringify(obj));

And in your second step, parse the JSON string
second action
//index2.js
const core = require("@actions/core");
const outputs = JSON.parse(core.getInput("outputs"));

This should help you.


text:
Q: How to call a component inside a custom component in React? I want to change the body dynamically, how can i do this?

import React from 'react'
// import { Link } from 'react-router-dom'
export default function ProjectTemplate(props) {
    const Css= {
        "--background":`${props.isValue ? props.mode : 'red'}`
    }
    return (
        <>

{props.name}

        </>
    )
}

this is a custom component
import React from 'react'
import ProjectTemplate from '../Projects/ProjectTemplate/ProjectTemplate'

export default function Blog(props) {
  return (
    <>
      <ProjectTemplate name='Blog' mode={props.mode} isValue={props.isValue} >
        hhhh

      </ProjectTemplate>
    </>
  )
}

this is the another component where i want to add the body of previous component dynamically, then the hhh is not display in browser
output in browser:

{props.name}

                                hhh

but hhh is not visible in browser, how can i do for this output

A: You should read this docs, all you need here is children props

A: The word hhh will not be displayed because you are calling the custom component in the project template with no props name which you want to display. In your code if you render the component the Blog name will displayed only.
use this in the project template and pass the props to the childrenanme

  {props.childrenanme}

A: To Answer your Question: Yes we can use component inside nested component in react.

In JSX expressions that contain both an opening tag and a closing tag,
the content between those tags is passed as a special prop React Documentation.

And to use these special props you have to use {props.children}.
In your example, you have passed the content b/w opening and closing tag of a custom component but forgot to use it.
In projectTemplate component use the children that you have passed while invoking the component, like this:

  {props.childrenanme}


text:
Q: how to retrieve images from server using spring boot and reactjs I am using spring boot as backend and reactjs as frontend. I stored images and videos on server. then retrieve it to front end. when using localhost it works properly. but after i deployed this application on ubuntu server i can't preview images.(but image save process success). In ubuntu my spring boot jar file is located at /root/main/test. But uploaded images saved outside root folder(/upload/image.jpg). so i can't retrive this as full url. such as mydomain.com/upload/image.jpg isn't working. how can i get this image using react js

A: You can configure spring boot to serve static content:
spring.resources.static-locations=file:/upload

or with code:
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
      .addResourceHandler("/upload/**")
      .addResourceLocations("file:/upload/");
 }
...


text:
Q: Primefaces File Upload Location Error I am trying to upload an image file to a local folder and getting File Not Found Error. The location pointing out in error message for the upload file is not right. Actually the file location is showing on the error is a combination of my source and destination location. I am trying to upload file to "C:/Users/sam//File/Upload/" from my desktop. Here is the error code,
Error message
java.io.FileNotFoundException: C:\Users\sam\File\Upload\C:\Users\sam\Desktop\test.jpg (The filename, directory name, or volume label syntax is incorrect)

My class file
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import org.apache.commons.io.IOUtils;
import org.primefaces.event.FileUploadEvent;

@ManagedBean
public class FileUploadView {
private String fileUploadFolder = "C:/Users/sam/File/Upload/";

public void handleFileUpload(FileUploadEvent event) {
    FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, message);

    try {
        File targetFolder = new File(fileUploadFolder);
        InputStream input = event.getFile().getInputstream();
        OutputStream output = new FileOutputStream(new File(targetFolder,
                event.getFile().getFileName()));
        try {
            IOUtils.copy(input, output);
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(output);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}
and my html
    <p:fileUpload fileUploadListener="#{fileUploadView.handleFileUpload}"
        mode="advanced" dragDropSupport="false" update="messages"
        sizeLimit="100000000" fileLimit="1"
        allowTypes="/(\.|\/)(gif|jpe?g|png|xlsx|jpg)$/" />

I also tried example from BalusC, still getting same error, ui with primefaces5.1.

A: As hinted by the clearly wrong file path in the exception,

java.io.FileNotFoundException: C:\Users\sam\File\Upload\C:\Users\sam\Desktop\test.jpg (The filename, directory name, or volume label syntax is incorrect)

the problem is the combination of this piece of code
OutputStream output = new FileOutputStream(new File(targetFolder,
    event.getFile().getFileName()));

and the fact that MSIE browser was being used. This browser has the security bug that it sends the entire client side disk file system path along with the file name instead of only the file name.
You basically need to get rid of that client side disk file system path from the file name.
String fileName = event.getFile().getFileName();
fileName = fileName.substring(fileName.lastIndexOf('\\') + 1); // MSIE fix.
OutputStream output = new FileOutputStream(new File(targetFolder, fileName));
// ...

You've however a bigger problem here. You seem to not have considered the possibility that multiple different users can upload a file having exactly the same filename. If you'd like to make your code more robust as to that, then head to How to save uploaded file in JSF.


text:
Q: Pegar informações digitadas em um iframe Tenho uma página HTML que tem um elemento iframe.
Esse iframe possui um cadastro. Eu preciso salvar as informações que são digitadas dentro do iframe (outro domínio).
Em minhas pesquisas, verifiquei a possibilidade de utilizar Window.postMessage(), porém não encontrei uma forma de usar conforme minha necessidade.


text:
Q: Got error on installing pyfastext on Mac: command 'cc' failed with exit status 1 I just got an error on installing pyfasttext.
cogent@MBP: pip install --user pyfasttext

And then I got these:

Collecting pyfasttext
        Downloading https://files.pythonhosted.org/packages/f5/ef/90606442481d1e4ab10eba8c2b2c449ceaa70c60e9b8d5898bb7504e3634/pyfasttext-0.4.6.tar.gz (244kB)
          100% |████████████████████████████████| 245kB 224kB/s
      Requirement already satisfied: future in /Users/cogent/Library/Python/2.7/lib/python/site-packages (from pyfasttext) (0.18.1)
      Requirement already satisfied: cysignals in /Users/cogent/Library/Python/2.7/lib/python/site-packages (from pyfasttext) (1.10.2)
      Requirement already satisfied: numpy in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from pyfasttext) (1.8.0rc1)
      Requirement already satisfied: Cython>=0.28 in /Library/Python/2.7/site-packages (from cysignals->pyfasttext) (0.29.13)
      Installing collected packages: pyfasttext
        Running setup.py install for pyfasttext ... error
          Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;file='/private/var/folders/gm/kpbf6gyx1dx_167zbp2gmdym0000gn/T/pip-install-wuuXwu/pyfasttext/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /private/var/folders/gm/kpbf6gyx1dx_167zbp2gmdym0000gn/T/pip-record-Qtcina/install-record.txt --single-version-externally-managed --compile --user --prefix=:
          running install
          running build
          running build_ext
          building 'pyfasttext' extension
          creating build
          creating build/temp.macosx-10.14-intel-2.7
          creating build/temp.macosx-10.14-intel-2.7/src
          creating build/temp.macosx-10.14-intel-2.7/src/fastText
          creating build/temp.macosx-10.14-intel-2.7/src/fastText/src
          cc -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -iquote . -include src/custom_exit.h -arch i386 -arch x86_64 -pipe -Isrc -I/Users/cogent/Library/Python/2.7/lib/python/site-packages/cysignals -I. -Isrc/variant/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include -c src/pyfasttext.cpp -o build/temp.macosx-10.14-intel-2.7/src/pyfasttext.o -Wno-sign-compare -std=c++0x
          In file included from src/pyfasttext.cpp:53:
          In file included from /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/Python.h:85:
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/unicodeobject.h:534:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register PyObject obj,     / Object */
              ^~~~~~~~~
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/unicodeobject.h:553:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register PyObject obj      / Object */
              ^~~~~~~~~
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/unicodeobject.h:575:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register const wchar_t w,  / wchar_t buffer */
              ^~~~~~~~~
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/unicodeobject.h:593:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register wchar_t w,        / wchar_t buffer */
              ^~~~~~~~~
          In file included from src/pyfasttext.cpp:53:
          In file included from /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/Python.h:94:
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/stringobject.h:173:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register PyObject obj,     / string or Unicode object */
              ^~~~~~~~~
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/stringobject.h:174:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register char **s,          /* pointer to buffer variable */
              ^~~~~~~~~
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/stringobject.h:175:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register Py_ssize_t len    / pointer to length variable or NULL
              ^~~~~~~~~
          In file included from src/pyfasttext.cpp:676:
          In file included from /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include/numpy/arrayobject.h:4:
          In file included from /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include/numpy/ndarrayobject.h:17:
          In file included from /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include/numpy/ndarraytypes.h:1760:
          /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: "Using deprecated NumPy API, disable it by "          "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-W#warnings]
          #warning "Using deprecated NumPy API, disable it by " \
           ^
          8 warnings generated.
          In file included from src/pyfasttext.cpp:53:
          In file included from /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/Python.h:85:
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/unicodeobject.h:534:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register PyObject obj,     / Object */
              ^~~~~~~~~
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/unicodeobject.h:553:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register PyObject obj      / Object */
              ^~~~~~~~~
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/unicodeobject.h:575:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register const wchar_t w,  / wchar_t buffer */
              ^~~~~~~~~
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/unicodeobject.h:593:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register wchar_t w,        / wchar_t buffer */
              ^~~~~~~~~
          In file included from src/pyfasttext.cpp:53:
          In file included from /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/Python.h:94:
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/stringobject.h:173:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register PyObject obj,     / string or Unicode object */
              ^~~~~~~~~
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/stringobject.h:174:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register char **s,          /* pointer to buffer variable */
              ^~~~~~~~~
          /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/stringobject.h:175:5: warning: 'register' storage class specifier is deprecated and incompatible with C++17 [-Wdeprecated-register]
              register Py_ssize_t len    / pointer to length variable or NULL
              ^~~~~~~~~
          In file included from src/pyfasttext.cpp:676:
          In file included from /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include/numpy/arrayobject.h:4:
          In file included from /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include/numpy/ndarrayobject.h:17:
          In file included from /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include/numpy/ndarraytypes.h:1760:
          /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: "Using deprecated NumPy API, disable it by "          "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-W#warnings]
          #warning "Using deprecated NumPy API, disable it by " \
           ^
          8 warnings generated.
          cc -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -iquote . -include src/custom_exit.h -arch i386 -arch x86_64 -pipe -Isrc -I/Users/cogent/Library/Python/2.7/lib/python/site-packages/cysignals -I. -Isrc/variant/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include -c src/fasttext_access.cpp -o build/temp.macosx-10.14-intel-2.7/src/fasttext_access.o -Wno-sign-compare -std=c++0x
          src/fasttext_access.cpp:43:1: error: non-type template argument is not a pointer to member constant
          ALLOW_METHOD_ACCESS(FastText, bool, checkModel, std::istream&);
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          src/private_access.h:55:38: note: expanded from macro 'ALLOW_METHOD_ACCESS'
            template struct rob
                                               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          src/fasttext_access.cpp:54:1: error: non-type template argument is not a pointer to member constant
          ALLOW_CONST_METHOD_ACCESS(Dictionary, int32_t, find, const std::string&);
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          src/private_access.h:59:38: note: expanded from macro 'ALLOW_CONST_METHOD_ACCESS'
            template struct rob
                                               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          src/fasttext_access.cpp:55:1: error: non-type template argument is not a pointer to member constant
          ALLOW_CONST_METHOD_ACCESS(Dictionary, void, pushHash, std::vector&, int32_t);
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          src/private_access.h:59:38: note: expanded from macro 'ALLOW_CONST_METHOD_ACCESS'
            template struct rob
                                               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          src/fasttext_access.cpp:56:1: error: non-type template argument is not a pointer to member constant
          ALLOW_METHOD_ACCESS(Dictionary, void, initTableDiscard, );
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          src/private_access.h:55:38: note: expanded from macro 'ALLOW_METHOD_ACCESS'
            template struct rob
                                               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          src/fasttext_access.cpp:57:1: error: non-type template argument is not a pointer to member constant
          ALLOW_METHOD_ACCESS(Dictionary, void, initNgrams, );
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          src/private_access.h:55:38: note: expanded from macro 'ALLOW_METHOD_ACCESS'
            template struct rob
                                               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          5 errors generated.
          error: command 'cc' failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/gm/kpbf6gyx1dx_167zbp2gmdym0000gn/T/pip-install-wuuXwu/pyfasttext/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/gm/kpbf6gyx1dx_167zbp2gmdym0000gn/T/pip-record-Qtcina/install-record.txt --single-version-externally-managed --compile --user --prefix=" failed with error code 1 in /private/var/folders/gm/kpbf6gyx1dx_167zbp2gmdym0000gn/T/pip-install-wuuXwu/pyfasttext/

Why I got these message? Any idea? Thanks for much!

A: Accourding to this answer, PyFastText is no longer maintained.
You can instead use:
pip install fastText


text:
Q: Laravel 5.4 $request->get trims whitespace in input Laravel is trimming whitespace at the beginning of the string.
Example:
"     this is a test"
Is returning
This is a test
I use Laravels $request->get('name')
When i use $_POST in the laravel application it is working fine.
Does somebody know how i can achive this with $request->get()

A: In laravel 5.4, Taylor added the TrimStrings middleware to default middleware group. So you can remove the \App\Http\Middleware\TrimStrings::class from the Http\Kernel.php.


text:
Q: How to get MySql database queries log I need a list of queries executed against my database on some shared server... is it possible to get that list without having admin rights?
any sort of profiling will help


text:
Q: Cygwin - STunnel doesn't respond anymore I long used Cygwin 64bit and cygwin's package All/Net/stunnel: Universal TLS wrapper on my Windows 10 machine very happily.
Suddenly however, STunnel doesn't respond anymore. I know it's very vague, so I'll provide some info below. I have installed version 5.31-1, but also tried with 5.28-1 to no avail.
$ # from the man page for stunnel,
$ # -version should output version and compile time.
$ # But nothing comes out.
$
$ stunnel -version
$ stunnel -help
$ type stunnel
stunnel is hashed (/usr/bin/stunnel)
$ which stunnel
/usr/bin/stunnel
$

The lack of output is driving me crazy, not sure why nothing comes out. I completely uninstalled cygwin - following the website guidelines -  then reinstalled cygwin and stunnel.
I suspect a missing library, but cygwin takes care of all dependancies, unless it's not and I really miss an important library. I have installed perl and openssh but still no luck.
$ cygcheck ../../bin/stunnel.exe
C:\cygwin64\bin\stunnel.exe
  C:\cygwin64\bin\cygssp-0.dll
    C:\cygwin64\bin\cygwin1.dll
      C:\WINDOWS\system32\KERNEL32.dll
        C:\WINDOWS\system32\ntdll.dll
        C:\WINDOWS\system32\KERNELBASE.dll
          C:\WINDOWS\system32\api-ms-win-eventing-provider-l1-1-0.dll
        C:\WINDOWS\system32\api-ms-win-core-synch-l1-2-0.dll
        C:\WINDOWS\system32\api-ms-win-core-timezone-l1-1-0.dll
        C:\WINDOWS\system32\api-ms-win-core-xstate-l2-1-0.dll
  C:\cygwin64\bin\cygcrypto-1.0.0.dll
    C:\cygwin64\bin\cygz.dll
  C:\cygwin64\bin\cygssl-1.0.0.dll
  C:\cygwin64\bin\cygwrap-0.dll

$ ldd ../../bin/stunnel.exe
    ntdll.dll => /cygdrive/c/WINDOWS/SYSTEM32/ntdll.dll (0x7ffbd65b0000)
    KERNEL32.DLL => /cygdrive/c/WINDOWS/system32/KERNEL32.DLL (0x7ffbd5890000)
    KERNELBASE.dll => /cygdrive/c/WINDOWS/system32/KERNELBASE.dll (0x7ffbd2f90000)
    TmUmEvt64.dll => /cygdrive/c/WINDOWS/system32/tmumh/20019/AddOn/6.80.0.1007/TmUmEvt64.dll (0x7ffbd0350000)
    PSAPI.DLL => /cygdrive/c/WINDOWS/system32/PSAPI.DLL (0x7ffbd39a0000)
    SHLWAPI.dll => /cygdrive/c/WINDOWS/system32/SHLWAPI.dll (0x7ffbd3d10000)
    msvcrt.dll => /cygdrive/c/WINDOWS/system32/msvcrt.dll (0x7ffbd5a50000)
    combase.dll => /cygdrive/c/WINDOWS/system32/combase.dll (0x7ffbd6200000)
    RPCRT4.dll => /cygdrive/c/WINDOWS/system32/RPCRT4.dll (0x7ffbd6490000)
    bcryptPrimitives.dll => /cygdrive/c/WINDOWS/system32/bcryptPrimitives.dll (0x7ffbd2e70000)
    GDI32.dll => /cygdrive/c/WINDOWS/system32/GDI32.dll (0x7ffbd3a20000)
    USER32.dll => /cygdrive/c/WINDOWS/system32/USER32.dll (0x7ffbd3db0000)
    ADVAPI32.dll => /cygdrive/c/WINDOWS/system32/ADVAPI32.dll (0x7ffbd3f10000)
    sechost.dll => /cygdrive/c/WINDOWS/system32/sechost.dll (0x7ffbd5520000)
    IMM32.DLL => /cygdrive/c/WINDOWS/system32/IMM32.DLL (0x7ffbd3d70000)
    tmmon64.dll => /cygdrive/c/WINDOWS/system32/tmumh/20019/TmMon/1.6.0.1163/tmmon64.dll (0x6fa30000)

How should I go about troubleshooting this problem? I tried on a colleague's pc and he has the same problem.

A: As cygcheck says that all dll's are in place, you can use
two ways to highlight a mismatch in library
You can use
http://www.dependencywalker.com/
or run
strace -o tunnel.strace stunnel


text:
Q: Setup CloudWatch Alarms for EC2 instances in Autoscaling Group(CF) I have an AWS::AutoScaling::AutoScalingGroup configuration that runs two instances of EC2. My question is - is it possible to attach CloudWatch alarms for both instances? For example I want to observe StatusCheckFailed_Instance metric for each EC2 in a group?
Usually you can attach alarms through the EC2 Instance ID but how to know each EC2 Instance ID in AutoScalingGroup to attach alerts? or here should be another way to attach alerts? I really can't find something useful and workable over internet.

A: Option 1)

*

*Create your own script that's triggered on launch/terminate events

*the scripts will each be set to trigger a lambda that would read in the instance ID and create/delete an alarm

Option 2)

*

*If you're not trying to use the auto-recover option (which you shouldn't need in an ASG, since the ASG will just replace the instances), then you can make 1 aggregate alarm for the ASG

*Create the alarm based on the StatusCheckFailed_Instance metric with the ASGName=<> Dimension

*Set it to trigger if the MAX statistic value is > 1 (since that means at least 1 instance is failing, each instance will push its own datapoints to ASG versions of EC2 metrics)

*Since you only have 2 instances, you can just manually check both if it ever triggers.  But for larger ASGs using the SEARCH() math expression on the CloudWatch metrics console (or a dashboard) would be a good way to look through all the ASG instances and view their metrics to see which one is failing


text:
Q: C#: How to use the char overload for string.Replace() to replace with nothing? I have the following extension method (which is invalid and does not compile ATM):
    public static string Strip( this string str, char[] charsToStrip )
    {
        foreach( char c in charsToStrip )
        {
            str.Replace( c, "" );
        }

        return str;
    }

The str.Replace() call needs to invoke the 'char' overload of Replace(), however using this overload I'm not sure what to pass into the 2nd parameter to tell it to replace with "nothing".
The goal of this function is to iterate each character in the charsToStrip variable and remove all instances of that character in the source string, str.
Also if my function is reinventing the wheel, let me know. I'm using .NET 3.5
Thanks in advance.

A: Try:
str = str.Replace(c.ToString(), String.Empty);

Note that instances of string are immutable. As such, you need to assign the result of String.Replace otherwise the result is lost.

A: There is no empty char, so use a string overload:
str = str.Replace( c.ToString(), "");


text:
Q: What is the best platform-neutral font for résumés? Which font is the best to make a résumé look equally good on all operating systems?

A: The Microsoft Core Fonts like Arial, Verdana, Tahoma and Times New Roman are usually available on most platforms, but there's no guarantee that any font is available on any platform. The best thing to do is use a document format that preserves font information such as PDF, which is an open-spec file format with at least primitive viewers available on the most widely used platforms.

A: If you want to be completely platform neutral then you should format it in plain text and wrap it at 80 columns. Otherwise, even if you end up using Times New Roman which is available on nearly every platform but put it in a Word document, you'll be restricted.

A: Why not convert the resume to a PDF so that it looks the same across the different OS's?

A: Sadly and boringly Times New Roman for printed / pdf documents.
Or are you asking about a font for web delivery? It's hard to tell with the lack of any real information in your question.


text:
Q: How to show that $m(E_1 \cap E_2)+m(E_1 \cup E_2)=m(E_1)+m(E_2)$? Let $E_1$ and $E_2$ measurable sets.
Show that $m(E_1 \cap E_2)+m(E_1 \cup E_2)=m(E_1)+m(E_2)$
if $E_1$ is measurable, for any set A, $m^*(A)=m^*(A\cap E_1)+m^*(A \cap E_1^c)$
how can I start?
(sorry my jvs isnt working I cant add correct tag)

A: $$E_{1}\cup E_{2}=\left(E_{1}\backslash E_{2}\right)\cup\left(E_{2}\backslash E_{1}\right)\cup\left(E_{1}\cap E_{2}\right)$$
Consequently: $$m\left(E_{1}\cup E_{2}\right)+m\left(E_{1}\cap E_{2}\right)=m\left(E_{1}\backslash E_{2}\right)+m\left(E_{2}\backslash E_{1}\right)+2m\left(E_{1}\cap E_{2}\right)$$
$$E_{1}=\left(E_{1}\backslash E_{2}\right)\cup\left(E_{1}\cap E_{2}\right)\text{ and } E_{2}=\left(E_{2}\backslash E_{1}\right)\cup\left(E_{1}\cap E_{2}\right)$$
Consequently: $$m\left(E_{1}\right)+m\left(E_{2}\right)=m\left(E_{1}\backslash E_{2}\right)+m\left(E_{2}\backslash E_{1}\right)+2m\left(E_{1}\cap E_{2}\right)$$
So the RHS of the equations is the same. This allows the conclusion: $$m\left(E_{1}\cup E_{2}\right)+m\left(E_{1}\cap E_{2}\right)=m\left(E_{1}\right)+m\left(E_{2}\right)$$

A: Integrate with respect to the measure $m$ the pointwise identity $$\mathbf 1_{E_1\cup E_2}+\mathbf 1_{E_1\cap E_2}=\mathbf 1_{E_1}+\mathbf 1_{E_2}.$$

A: (Assumption: $m$ denotes measure, $m^*$ denotes outer measure.)
You can decompose
$$
E_1\cup E_2=(E_1\backslash E_2)\cup(E_2\backslash E_1)\cup(E_1\cap E_2)\tag{*}
$$
then use the additive property (3 times).

To be more explicit:
\begin{gather*}
E_1=(E_1\backslash E_2)\cup(E_1\cap E_2)\implies m(E_1)=m(E_1\backslash E_2)+m(E_1\cap E_2),\\
E_2=(E_2\backslash E_1)\cup(E_1\cap E_2)\implies m(E_2)=m(E_2\backslash E_1)+m(E_1\cap E_2).
\end{gather*}
So
$$
m(E_1)+m(E_2)=m(E_1\cap E_2)+[m(E_1\backslash E_2)+m(E_2\backslash E_1)+m(E_1\cap E_2)].
$$
Now use the decomposition given in (*).


text:
Q: How to create custom PyQt accept/reject dialogue? I'm struggling to figure out how to create custom accept/reject dialogue. I have WarningMessage() class that I want to be able to work in two modes:

*

*Just inform user that something is wrong (only Ok button to close the dialogue).

*Get the decision from user: either to continue or to cancel (two buttons). This decision should be an output from the class: choise = WarningMessage(u'continue?', choice = True)
The first mode works fine, but I fail to make the second one work.
from PyQt4 import QtGui
from PyQt4.QtCore import *

class WarningMessage(QtGui.QMessageBox):
  '''
  Creates a message for the case when something is wrong
  '''
  def __init__(self, message, choice=False):
    super(WarningMessage, self).__init__()
    self.choice = choice
    if not isinstance(message, basestring):
      message = str(message)
    self.initUI(message)

  def initUI(self, message):
    if not self.choice:
      self.warning(self, u'warning!',
          message, QtGui.QMessageBox.Ok)
      return None
    else:
      self.m_button_box = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel, Qt.Horizontal, self)
      QtGui.QVBoxLayout(self).addWidget(self.m_button_box)
      self.m_button_box.accepted.connect(lambda: self.accept(True))
      self.m_button_box.rejected.connect(lambda: self.accept(False))
      self.warning(self, u'Warning!', message, self.m_button_box)

  def accept(self, yes=True):
    if yes:
      return True
    else:
      return False

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    choice = WarningMessage(u'Continue?', choice = True)
    print choice
    sys.exit(app.exec_())

This throws the error:
TypeError: arguments did not match any overloaded call:
  QMessageBox.warning(QWidget, QString, QString, QMessageBox.StandardButtons buttons=QMessageBox.Ok, QMessageBox.StandardButton defaultButton=QMessageBox.NoButton): argument 4 has unexpected type 'QDialogButtonBox'
  QMessageBox.warning(QWidget, QString, QString, int, int, int button2=0): argument 4 has unexpected type 'QDialogButtonBox'
  QMessageBox.warning(QWidget, QString, QString, QString, QString button1Text=QString(), QString button2Text=QString(), int defaultButtonNumber=0, int escapeButtonNumber=-1): argument 4 has unexpected type 'QDialogButtonBox'

A: Use QtGui.QMessageBox.question like explained here.
class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Message box')
        self.show()

    def closeEvent(self, event):

        reply = QtGui.QMessageBox.question(self, 'Message',
            "Are you sure to quit?", QtGui.QMessageBox.Yes |
            QtGui.QMessageBox.No, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

you can easily change the closeEvent function from this example and call it by e.g. a button.

A: Thanks to @a.smiet I was able to modify my class the way I need and now I', able to get users choice this way: choice = WarningMessage(u'Continue?', choice = True).user_choice
from PyQt4 import QtGui
from PyQt4.QtCore import *

class WarningMessage(QtGui.QMessageBox):
  '''
  Creates a message for the case when something is wrong
  '''
  def __init__(self, message, choice=False):
    super(WarningMessage, self).__init__()
    self.choice = choice
    if not isinstance(message, basestring):
      self.message = str(message)
    else:
      self.message = message
    self.user_choice = None
    self.initUI()

  def initUI(self):
    if not self.choice:
      self.warning(self, u'Warning!',
          self.message, QtGui.QMessageBox.Ok)
      return None
    else:
      reply = QtGui.QMessageBox.question(self, u'Warning!',
            self.message, QtGui.QMessageBox.Yes |
            QtGui.QMessageBox.No)

      if reply == QtGui.QMessageBox.Yes:
        self.user_choice = True
      else:
        self.user_choice = False

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    choice = WarningMessage(u'Continue?', choice = True).user_choice
    print choice
    sys.exit(app.exec_())


text:
Q: @font-face works locally and not working while using url This code works fine on my single HTML page, both the HTML file and the font are in the same folder.
@font-face {
    font-family: myFont;
    src: url(DroidKufi-Regular.ttf);
}

Now i'm trying to add the font in the website and use the link in the code.
src: url("http://hnauae.com/myFonts/DroidKufi-Regular.ttf");

This one isn't working, can anyone explain me why?

A: Import url make page loading slower than normal loading.
use your resources local
and use relative path like below:
@font-face {
    font-family: 'Roboto';
    src: url('fonts/roboto/Roboto-Thin-webfont.eot');
    src: url('fonts/roboto/Roboto-Thin-webfont.eot?#iefix') format('embedded-opentype'),
         url('fonts/roboto/Roboto-Thin-webfont.woff') format('woff'),
         url('fonts/roboto/Roboto-Thin-webfont.ttf') format('truetype'),
         url('fonts/roboto/Roboto-Thin-webfont.svg#robotothin') format('svg');
    font-weight: 100;
    font-style: normal;
    /*other custom  styles*/
}

A: Even if you try to add in website use relative path

A: Maybe try to use a relative path rather than a relative path.

Note that it will depend on your file structure.

Change
src: url("http://hnauae.com/myFonts/DroidKufi-Regular.ttf");

To
src: url("../myFonts/DroidKufi-Regular.ttf");


text:
Q: IDLE on Mac keeps crashing when using specific keys is anybody experiencing the same issue?
I regularly rush in and start typing shortcuts on my Mac. And sometimes when trying to use the Ctrl + P (previous) or Ctrl + N (next) to re-run commands, I accidentally the (in spanish ISO keyboard) ` key. This results in IDLE crashing instantly.
I've also found that using mexican ´ accent key creates the same crash.
Any idea on how to prevent this?
Thanks!

A: Thanks to @Blckknght I found the answer.
You should install the TCL Version 8.5.15
At first I tried with 8.6 because it was the first "COME AND CLICK ME" button on the website, but then I learned that the correct version is the one below marked as 8.5.15.0


text:
Q: Emails are not getting sent from SalesForce Sandbox . Have already configured Deliverability to 'All Mails' Emails are not getting sent from SalesForce Sandbox. Have already configured Deliverability to 'All Mails'. Checked email logs and found below details.
   Mail Event – P - Permanent Failure
   Delivery Stage - reading BANNER
   554 SFDCSMTPin.xxxxxx.com - 554 Error code (The transaction failed)

Any idea what can be the reason behind it.


text:
Q: Is Red Hat's JBoss EAP a fork of the JBoss AS code you get from JBOSS.org? Does anyone know if Red Hat has forked the code you download from JBOSS.org?  I'm guessing that the answer is "yes", but I'd like to confirm it.  I can't pin it down at the Red Hat site, and jboss.org giving me an HTTP 502 right now for some reason.
I know that Red Hat owns JBoss.  Does that mean that the code they sell in JBoss Developer Studio for $99 a pop is identical to what I can download from JBOSS.org without paying a fee?  Or have they forked the for-fee version in some way?

A: All the source code for Red Hat/JBoss products is available in opensource (in svn/cvs etc.), but the sold version is what is called the productized version.
What does productized mean ? It means as Michael says, it has additional tests/QA, it has the certified bits, it has matching doc's, etc. It also means that some features in the community version are disabled, removed or have a slightly different configuration default and slightly different packaging.
Examples of differences:
i.e. JBoss EAP comes bundled with Seam, JBoss AS does not.
The productized Seam 1.2 works on JBoss AS 4.3, Seam from .org did not
JBoss EAP has a 'production' profile which is tuned for production (i.e. hotdeploy disabled and other best practices which our support recommend), JBoss AS does not have that.
JBoss EAP gets supported and guaranteed cumulative patches for many years, JBoss AS from .org does not.
All of the above is about having a productized version that is supportable for a long period of time and hence much more about having a stable version than about having the latest-greatest cutting edge version of the latest development.
If you are looking for the bleeding edge then JBoss.org is for you.
To answer you question for Michael, "If I download the code from JBoss.org i'm sure to be using the same stuff that someone who buys it from Red Hat, correct?" - Then the answer to that is: It depends on the project.
Some projects are exactly the same, where as others have more visible differences BUT all features in the productized version is available in the .org version, but there might be some features that exist in .org that has been removed/disabled (see above).
So what to do? If you are looking for bleeding edge, use JBoss.org - if you are looking for making sure you are developing on the exact same set of binaries which JBoss/Red Hat can provide development and product support on for the next many years, then the $99 product from Red Hat you refer to (I assume you meant JBoss Developer Studio Portfolio) is your best option.
btw. the official answer to what the difference is between the community and enterprise (productized) versions is shown at http://www.jboss.com/products/community-enterprise/
For full disclosure: I'm the lead of JBoss Tools and JBoss Developer Studio.

A: No its not a fork as in different code - its build from the .org versions and put through various tests/QA environments, certified if necessary etc...
Its analagous to what goes on with Fedora and Red Hat Enterprise Linux (I think the idea is to have a similar model) - so if you look into that model it might help explain it better then I can.


text:
Q: Django form ignoring 'required' value I created a date range form to use in my Django views.  In some of the views I use it in the date range is required, but not in others so I need the form to accept a required key word. I'm having trouble getting my form to recognize required=False.
The Django form:
class DateRangeForm(forms.Form):
  def __init__(self, *args, **kwargs):
    initial_start_date = kwargs.pop('initial_start_date')
    initial_end_date = kwargs.pop('initial_end_date')
    required_val = kwargs.pop('required')
    input_formats = kwargs.pop('input_formats')

    super(DateRangeForm,self).__init__(*args,**kwargs)
    self.fields['start_date'].initial = initial_start_date
    self.fields['start_date'].required = required_val
    self.fields['start_date'].input_formats = input_formats
    self.fields['end_date'].initial = initial_end_date
    self.fields['end_date'].required = required_val
    self.fields['end_date'].input_formats = input_formats

  start_date = forms.DateTimeField(widget=forms.DateInput(attrs={'class':"form-control text-center"}))
  end_date = forms.DateTimeField(widget=forms.DateInput(attrs={'class':"form-control text-center"}))

It's used in my Django view like this:
def Nominal_Request(request):

  initial_end = Utils.addToDatetime(datetime.today().strftime("%Y/%m/%d"),weeks=6)

  form_dict = {}
  arg_dict = {}
  message = message = {'last_url':'Nominal_Request'}

  if request.method == 'POST':
    daterange_form = DateRangeForm(request.POST,required=False,initial_start_date=None,initial_end_date=initial_end,input_formats=dateFormats)

    if 'Range' in request.POST:

        if daterange_form.is_valid():
            #process the dates here....
            WS = daterange_form.cleaned_data['start_date']
            WE = daterange_form.cleaned_data['end_date']
            #date processing continues....

        args = {'Start':WS,'End':WE}
    return Request_Results(request,args)

  else:
    daterange_form = DateRangeForm(required=False,initial_start_date=None,initial_end_date=initial_end,input_formats=dateFormats)

    form_dict.update({'daterange_form':daterange_form})

  return render(request,'InterfaceApp/Request_Nominal.html',form_dict)

It displays fine, but Django still thinks that both of the date range fields are required and won't let me submit the form with one or both of the fields empty.

Why is it not picking up on my required arg?


text:
Q: How to get the value of a function outside the loop "while" in C#?     bool Estprenom = false;
    while (!Estprenom)
   {
     string prenom = Console.ReadLine();
     if (prenom == "x" || prenom == "y")
     {
        Estprenom = true;
        Console.WriteLine("..." + prenom + "...");
     }
     else
     {
        Estprenom = false;
        Console.WriteLine("Error " + prenom + " is not your name !\n");
     }
   }

This is my code, and i'd like to know how to use the value " prenom " outside the loop " While ". In this example, the value is set by the user via a " Console.ReadLine ", but I can't use it outside the loop. If I put it before the loop :
  bool Estprenom = false;
  string prenom = Console.ReadLine();

The loop will never stop if the name written is wrong.
How can I get the value of the string " prenom " outside the loop so I can write :
   while (!Estprenom)
    {
    (...)
    }
   Console.WriteLine("..." + prenom );

Thank you for your help !

A: Simply declare the variable outside of the loop and then assign it inside the loop:
string prenom;
while (!Estprenom)
{
    ...
    prenom = Console.ReadLine();
    ...
}
Console.WriteLine("..." + prenom );

A: Just pull the prenom value out of the loop scope.
bool Estprenom = false;
string prenom;
while (!Estprenom)
{
    prenom = Console.ReadLine();
    if (prenom == "x" || prenom == "y")
    {
        Estprenom = true;
        Console.WriteLine("..." + prenom + "...");
    }
    elsestring
    {
        Estprenom = false;
        Console.WriteLine("Error " + prenom + " is not your name !\n");
    }
}
Console.WriteLine(prenom);

A: Thank you for your answers.
Well, I did use your code, but .. It doesn't seem to work. I still got an error.
     bool Estprenom = false;
        string prenom;
        while (!Estprenom)
        {
            prenom = Console.ReadLine();
            if (prenom == "x" || prenom == "y")
            {
                Estprenom = true;
                Console.WriteLine("..." + prenom + "...");
            }
            else
            {
                Estprenom = false;
                Console.WriteLine("Error " + prenom + " is not your name !\n");
            }
        }
        Console.WriteLine(prenom);

It's still saying that the "prenom" value in "Console.WriteLine(prenom) is not assigned. I don't understand why...


text:
Q: Image won't appear on my tkinter text widget I have been trying to get an image into my tkinter child window and when I run this code I receive no errors but I only get a series of numbers in the child window. Here is a piece of the code I have:
from tkinter import *
top = Tk('Outfit Randomizer')

#gender entry
L1 = Label(top, text = 'What is your gender? Type 1 for male and 2 for female')
L1.grid(row = 0, column = 0)
g = StringVar()
E1 = Entry(top, bd = 5, textvariable = g)
E1.grid(row = 0, column = 1)

#submit function
def submit():
    g.get()
    gender = g.get()
    if gender == '1':
        root = Toplevel()
        T = Text(root, height = 30, width = 90)
        T.pack()
        mhbs = random.choice([ms1, ms2])
        if mhbs == ms1:
            photo = PhotoImage(file = "m.GIF")
            label = Label(image = photo)
            label.image = photo
            label.pack()
        if mhbs == ms2:
            photo = PhotoImage(file = "m.GIF")
            label = Label(image = photo)
            label.image = photo
            label.pack()
        T.insert(END, T)

#submit button
MyButton1 = Button(top, text = 'Submit', width = 10, command = submit)
MyButton1.grid(row = 3, column = 1)

top.mainloop()

ms1 and ms2 are defined in a different part of my code where I create a male shirts class but I felt that was unnecessary for this question. Please let me know what I can do to get my image to transfer to the new window!

A: You have at least two problems.
First, you should never create more than one instance of Tk or call mainloop more than once. If you need another window, create an instance of Toplevel, and don't call mainloop a second time.
Two, Your image is getting garbage-collected because you are using a local variable to store the image. For more information see http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm
You are also putting the label in the root window rather than the instance of the Toplevel that you are creating, because you are neglecting to give the Label a parent.
Finally, I have no idea what you think T.insert(END, T) is supposed to do. It appears you're attempting to insert a widget into itself. a) this makes no sense, b) if you want to insert a widget into a text widget you must use the window_create method, and c) if your actual intention is to insert an image into a text widget then you don't need the Label and you can use image_create instead.


text:
Q: Loading Statistics`Library` I need to use a number of functions from theStatistics`Library` namespace. Since that is a bit of a mouthful I would like to import it, but I get errors:
In[42]:= Needs["Statistics`Library`"]

During evaluation of In[42]:= Get::noopen: Cannot open Statistics`Library`. >>

During evaluation of In[42]:= Needs::nocont: Context Statistics`Library` was not created when Needs was evaluated. >>

Out[42]= $Failed

In[43]:= << Statistics`Library`

During evaluation of In[43]:= Get::noopen: Cannot open Statistics`Library`. >>

Out[43]= $Failed

I can use individual functions from the namespace
In[44]:= Statistics`Library`DistributionDimensionality[

NormalDistribution[]]
Out[44]= 1

so the problem is not in the name.
What is the problem then? What is the correct way to do the import?

A: Statistics`Library` does not correspond directly to a package path, so it cannot be loaded with Get or Needs. Rather, this contents of this context come from
FileNameJoin[{
 $InstallationDirectory, "SystemFiles", "Kernel", "SystemResources", $OperatingSystem,
 "Statistics", "Library.mx"
}]

which is loaded automatically at startup. Loading this file populates the context, but does not add anything to the context path.
It is straightforward to change the context path, however:
AppendTo[$ContextPath, "Statistics`Library`"]

Now:
DistributionDimensionality@NormalDistribution[] (* -> 1 *)


text:
Q: 'Advisors' field with variable number of names for beamer title page I'd like to create a new command \advisors{Advisor1}{Advisor2}...{AdvisorN} (or any variation like \advisors{Advisor1,Advisor2,...,AdvisorN}) to be used to print inside the title of a beamer presentation a list like this
    \centering
    \textbf{Advisors:}\\
    Advisor1\\
    Advisor2\\
    ...\\
    AdvisorN

Here is the custom beamer template I am using for the title page
\setbeamertemplate{title page}{
    \vbox{}
    \vfill
    \begin{centering}
        {\usebeamercolor[fg]{titlegraphic}\inserttitlegraphic\par}\vskip1em
        {\rmfamily\textsc{- Doctoral Disseration -}\par}\vskip1em
        \begin{beamercolorbox}[sep=8pt,center,rounded=true,shadow=true]{title}
            \usebeamerfont{title}\inserttitle\par%
            \ifx\insertsubtitle\@empty%
            \else%
                \vskip0.25em%
                {\usebeamerfont{subtitle}\usebeamercolor[fg]{subtitle}\insertsubtitle\par}%
            \fi%
        \end{beamercolorbox}%
        \vskip1em\par
        \begin{beamercolorbox}[sep=7pt,center]{author}
            \usebeamerfont{author}
            \textbf{PhD candidate:}\\
            \insertauthor
        \end{beamercolorbox}
        %%% HERE SHOULD BE PRINTED THE LIST OF ADVISORS %%%
        \begin{beamercolorbox}[sep=8pt,center]{date}
            \usebeamerfont{date}\insertdate
        \end{beamercolorbox}
    \end{centering}
    \vfill
}

Can you help me?

A: The easiest way is to define the two macros
\newcommand*{\@advisors}{}
\newcommand*{\advisors}[1]{\def\@advisors{#1}}

and to add somewhere in the title page the lines
\ifx\@advisors\@empty\else
\par\medskip\textbf{Advisors:}\par\def\and{\par}\@advisors
\fi

A full MWE, where I add the advisors in the same beamercolorbox containing the author.
\documentclass{beamer}

\makeatletter

\newcommand*{\@advisors}{}
\newcommand*{\advisors}[1]{\def\@advisors{#1}}

\setbeamertemplate{title page}{
    \vbox{}
    \vfill
    \begin{centering}
        {\usebeamercolor[fg]{titlegraphic}\inserttitlegraphic\par}\vskip1em
        {\rmfamily\textsc{- Doctoral Disseration -}\par}\vskip1em
        \begin{beamercolorbox}[sep=8pt,center,rounded=true,shadow=true]{title}
            \usebeamerfont{title}\inserttitle\par%
            \ifx\insertsubtitle\@empty%
            \else%
                \vskip0.25em%
                {\usebeamerfont{subtitle}\usebeamercolor[fg]{subtitle}\insertsubtitle\par}%
            \fi%
        \end{beamercolorbox}%
        \vskip1em\par
        \begin{beamercolorbox}[sep=7pt,center]{author}
            \usebeamerfont{author}
            \textbf{PhD candidate:}\par
            \insertauthor
            \ifx\@advisors\@empty\else                                  % ADDED
            \par\medskip\textbf{Advisors:}\par\def\and{\par}\@advisors  % ADDED
            \fi                                                         % ADDED
        \end{beamercolorbox}
        \begin{beamercolorbox}[sep=8pt,center]{date}
            \usebeamerfont{date}\insertdate
        \end{beamercolorbox}
    \end{centering}
    \vfill
}
\makeatother

\author{Me Myself}
\title{My Work}
\advisors{First Advisor\and Second Advisor}

\begin{document}

\begin{frame}

\maketitle

\end{frame}

\end{document}

The real output of your code will of course depend on the rest of your template.


text:
Q: Getting usercontext supplied is invalid error i have setup build server on virtual machine in Azure, lets say buildserver is called vm-build. I am trying to copy file from build server to another vm called vm-client in same subnet and i get error
Copying failed for resource : vm-client.cloudapp.net
Failed to connect to the path \\vm-client.cloudapp.net with the user \\domain\username for copying.
The user context supplied is invalid.

I am using windows machine file copy functionality from tfs to copy between 2 vm's.
What i have tried
Tried to ping vm-client from vm-build with ip address and it returns response. SO in build script i also tried to use ip address instead of dns name but it still gives same error.
For your information
when i ping vm with ip address then i get response but when i ping vm with dns name then i get request timeout. I dont think its still issue here.

A: First, please double confirm you have follow the requirement of arguments in Windows Machine File Copy task.
According to the error The user context supplied is invalid.  Make sure your user account has admin permission in vm-client

Admin Login
The username of either a domain or a local administrative account on
  the target host(s).

*

*Formats such as domain\username, username, and machine-name\username    are supported.

*UPN formats such as username@domain.com and built-in system accounts    such as NT Authority\System are not supported.

\\domain\username seems not to be a qualify format.
Besides since there are two Azure VMs,  suggest you to use Azure File Copy task which may do trick.  This task  copy files to Microsoft Azure storage blobs or virtual machines (VMs).


text:
Q: Accessing fields of children classes within an array I am testing inheritance within Java, I have an abstract class with two fields and three extended classes with their own fields. In another class I instantiate and add objects of the class in an array, but I am not sure of how I can access the fields of the subclasses, the array is of the main abstract class:
here is the complete code of the abstract class and one of the extended classes:
public abstract class MusicRecord {
    private String type;
    private int length;

    public MusicRecord(String type, int length){
    this.type = type;
    this.length = length;
    }

    public String getType(){
    return type;
    }
    public int getLength(){
    return length;
    }

    public void setType(String type){
    this.type = type;
    }

    public void setLength(int length){
        this.length = length;
    }

    }

public class CD extends MusicRecord {
    private int price;
    private String title;

    public CD(String type, int lenght, String title, int price){
        super(type, lenght);
        this.price = price;
        this.title = title;
    }

    public String getTitle(){
        return title;
    }
    public int getPrice(){
        return price;
    }
    public String getType(){
        return "MusicRecord: " + super.getType();
    }
    public int getLenght(){
        return super.getLength();
    }

    public void setPrice(int price){
        this.price = price;
    }
    public void setTitle(String title){
        this.title = title;
    }
}

import java.util.Arrays;
public class Store {

    public static void main(String args[]){
    CD cd1 = new CD("Jaz", 34, "Music 44", 19);
    SD sd1 = new SD("R&B", 45, "Lova is never Lost!!", 21);
    BlueRay br1 = new BlueRay("Hell on Earth", 25, "HipHop", 40);

    MusicRecord[] mr = {cd1, sd1, br1,
        new CD("House", 40, "22 Is the Age", 22),
        new SD("Garage", 60, "Boom Boom Boommm", 14),
        new BlueRay("is it time to love", 18, "R&B", 35)};

    for(MusicRecord r : mr){
        System.out.println("Type: " + r.getType() + "\nLength: " + r.getLength());
    }
}

how do I get the fields from the subclass/es?

A:
ow I can access the fields of the subclasses, the array is of the main abstract class:

The java type system is covariant. (Except in generics, where variance is selectable, and by default, invariant). For the rest of this answer, you need to be aware that:

*

*java.lang.Integer extends java.lang.Number

*java.lang.Double extends java.lang.Number

*java.lang.Number extends java.lang.Object

Covariance means that you can take an expression whose type is Integer, and use it where a Number is required: Any subtype is fine when a supertype is required. (Invariance means that only an expression of specifically type Number will do, and contravariance is the reverse: If Integer is required, either Number or Object is also fine).
Thus:
Number[] x = new Number[2];
x[0] = new Integer(5);
x[1] = new Double(10.0);

is all fine.
That also means, if you flip it around, that if an expression is of type Number, then it may well be some subtype of Number. Given that Number is abstract, this is in, fact, a guarantee! No instances of Number itself can exist, only instances of subclasses of it.
You can use instanceof and casting and pattern matching to work with this:
NB: This uses new java features introduced in java15!
Object[] x = new Object[2];
x[0] = "hello";

if (x[0] instanceof String y) {
    y.toLowerCase();
}

Here we first check if x[0] is a String (it might be. It could also be an Integer, or a FileInputStream, or a com.sun.internal.impl.HttpRequestImpl$1 - covariance means that the actual type of things can be, and usually is, some internal detail that isn't guaranteed and can change between java versions and implementations). If it is a string, then for all code that can only be reached if it was (here that'd be the insides of that if block), y as a variable exists, and contains a reference to the exact same object, but this time typed as a string, and thus you can freely invoke string methods on it, such as .toLowerCase().
If you're not on JDK15 yet, the 'old' way is:
if (x[0] instanceof String) {
    String y = (String) x[0];
    y.toLowerCase();
}

This is called the cast operator, and it is merely a type assertion: If x[0] is indeed a String, then this code does nothing. It's as if you wrote (String y = x[0];, except that won't compile, but the effect is the same: y is now pointing at the same thing x[0] points at, the cast merely tells the compiler you know this is asserting type, and adds a runtime test).
If on the other hand x[0] is not pointing at some instance of j.l.String, that line will throw a ClassCastException.
Thus you could do something like:
int totalPrice = 0;
for (MusicRecord mr : records) {
    if (mr instanceof CD cd) totalPrice += cd.price;
}

NB: The right way to write that in java is Cd, not CD. By convention, of course - the java spec lets you write whatever you want. But if you want your code to interact well with libraries and be readable to other java coders, it's a good idea to follow the established conventions, and these state that you titlecase all the things, even acronyms that are, in ordinary writing, rendered in all-caps. DvdPlayer, not DVDPlayer. Cd, not CD. While you're at it, direct field access is not okay by convention - make getters instead. Should be cd.getPrice().

A: Thanks to Lino,rzwitserloot and Federico klez Culloca, I was able to solve the issue with the following addition.
for(MusicRecord r : mr){
      if(r instanceof CD){
        System.out.println("Type: " + r.getType() + "\nLength: " + r.getLength() + "\nTitle: " + ((CD)r).getTitle() + "\nPrice: " + ((CD)r).getPrice() + "\n ***************");
      } else if (r instanceof SD){
        System.out.println("Type: " + r.getType() + "\nLength: " + r.getLength() + "\nTitle: " + ((SD)r).getTitle() + "\nPrice: " + ((SD)r).getPrice() + "\n ***************");
      } else {
        System.out.println("Type: " + r.getType() + "\nLength: " + r.getLength() + "\nTitle: " + ((BlueRay)r).getTitle() + "\nPrice: " + ((BlueRay)r).getPrice() + "\n ***************");
      }


text:
Q: Communication between rest services hosted on different tomcat servers I have a scenario where i am hosting different java Rest Services on different Tomcat instances (different machines). These projects running on the tomcats do not have any UI. For simplicity's sake, lets assume that the user will directly enter some URL in the browser (or curl) to avail these services. Now I need this service to be able to talk to (call functions) the services available in the other tomcat instance.
For eg. If TomcatInstance1 gets the call, and all this does is act as a 'router' to the different services, i want it to be able to place the Rest call for the other 'service' available on, say, TomcatInstance2. Is this possible?. If so, how to achieve that? (Tried searching for similar questions on SO, couldnt find any). Are there any online reference for the same?
PS: Hosting the services in the same Tomcat Instance is against the requirement that I'm having.

A: That is completely possible. You can use (for example) Jersey-client (http://jersey.java.net/) to make the queries to the other RESTful web services in the other Tomcat instances. Only need to define the correct URIs of the end points and query them according the the API exposed and call it (like you were a client from a browser, or curl).
See here a nice example of using Jersey-client to do that: http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/

A: I would suggest Spring Restful api ( http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch18s02.html , http://www.mkyong.com/spring-mvc/spring-3-rest-hello-world-example/ ).
As @emgsilva mentioned the only thing you need to do is to point correct uris between each other.
The beauty of spring restful api is it is simple to use and you don't deal with any serialization - deserialization.


text:
Q: Objective-c - Passing in variables to a variable-length method I've got an array with items, and I want to pass these in to a variable-length method. How do you do that?
I.e., I've got this (for example):
NSArray *array = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];

[[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:nil cancelButtonTitle:[array objectAtIndex:0] otherButtonTitles:[array objectAtIndex:1], [array objectAtIndex:2], nil];

But imagine that array could have a variable length of items, so you cant hardcode it like this.

A: - (id) initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles ...
{
    va_list args;
    va_start(args, otherButtonTitles);
    for (NSString *arg = otherButtonTitles; arg != nil; arg = va_arg(args, NSString*))
    {
        //do something with nsstring
    }
    va_end(args);
}

You could also just make an argument in your functions that accepts an array (easy solution)
Anyway the ... notation is for a variable amount of arguments at the end of a function.

A: The documentation for the otherButtonTitles parameter in -[UIAlertView initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:] states that:

Using this argument is equivalent to invoking addButtonWithTitle: with this title to add more buttons.

Have you tried this:
NSArray *array = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil];
for (NSString *s in array) {
    [view addButtonWithTitle:s];
}


text:
Q: concentration bounds on weighted multinomial sum Consider i.i.d random vectors $Y_{1},..,Y_{n}$ and they are chosen uniformly at random from $\{e_{1},..,e_{L}\}$ where $e_{i}$ is a $L\times 1$ vector with $i$th component be 1 and the others be 0. Given weights $h=(h_1,h_2,..,h_n)\in R^n$ that satisfy $\sum h_k=0 $, we would like to study the tail probability bounds of $$S^2(h)\triangleq\|\sum_{k=1}^n h_kY_k\|^2_2   $$

*

*some simple calculations give $ES^2(h)=\|h\|_2^2+\sum_{k\neq k'}h_kh_{k'}\frac1L=(1-\frac1L)\|h\|_2^2$.  Note that for distinct $k_1,k_2,k_3$, $Y_{k_1}^TY_{k_2}$ and $Y_{k_1}^TY_{k_3}$ are uncorrelated, thus $$Var(S^2(h))=4Var(\sum_{k< k'} h_kh_{k'}Y_k^TY_{k'})   $$
$$=4\sum_{k< k'} h_k^2h_{k'}^2Var(Y_k^TY_{k'})\ $$ $$= 4\sum_{k< k'} h_k^2h_{k'}^2\frac1L(1-\frac1L) \leq\frac{2\|h\|_2^4}{L}(1-\frac1L)$$Then Chebyshev inequality yields $\forall t>0$ $$P(\frac{S^2(h)-ES^2(h)}{ES^2(h)}>t)\leq \frac{Var(S^2(h))}{t^2(ES^2(h))^2}\leq \frac2{t^2(L-1)}$$

*Direct apply a Bernstein inequality for suprema of empirical process (Thm 8.42 in the book 'Mathematical Introduction to Compressed Sensing')
Theorem 8.42 Let $\cal{F}$ be a countable set of functions $F:R^L\rightarrow R$. Let $Y_1,..,Y_n$ be independent random vectors in $R^L$ such that $E(F(Y_k))=0$ and $F(Y_k)\leq K$ almost surely for all $k\in {1,2,.,,n}$ and for all $F\in \cal{F}$ for some constant K>0. Introduce $$Z=\sup_{F\in \cal{F}}\sum_{k=1}^nF(Y_k)$$ Let $\sigma^2_k>0$ such that $E(F(Y_k)^2)\leq \sigma^2_k$ for all $k\in {1,2,.,,n}$ and for all $F\in \cal{F}$. Then for all $t>0$, $$P(Z>EZ+t)\leq \exp{(-\frac{t^2/2}{\sigma^2 + 2KEZ +tK/3})}$$ where $\sigma^2=\sum_k \sigma^2_k$.
Back to our problem, we apply this theorem to $\tilde{Y}_k:=h_k(Y_k-EY_k)$, $F_x(\tilde{Y}_k):=<x,\tilde{Y}_k>$ and $\cal{F}$ $ = \{ F_x, x\in Q^L,\|x\|_2=1 , <1,x>=0 \}$. Then $Z$ in the theorem above is exactly our $S(h)$. Further, we can choose $K=(1-\frac1L)|h|_{\infty}$ and $\sigma^2_k=\frac{h^2_K}{L}$ Then we have $$P(S(h)\geq ES(h)+t)\leq \exp(-\frac{t^2/2}{\|h\|^2_2/L+|h|_{\infty}(2ES(h)+t/3)})$$

Actually, we are interested in  the tail bound $P(S(h)\geq 1)$ when the weights satisfy $\|h\|^2_2 \asymp \frac{L}{n}$, $|h|_{\infty} \asymp \frac{L}{n}$ and $\frac{L}{n}=o(1)$ From the Bernstein inequality for suprema of emprical process, we have $$P(S(h)\geq 1)\leq \exp(-c_{1}\frac{n}{L})$$ where $c_1$ is some positive universal constant. This bound is not good when $\frac{L}{n}$ goes to zero very slowly. It may be even worse than the bound given by Chebyshev inequality : $$P(S(h)\geq 1)\leq c_2\frac{L}{n^2}$$where $c_2$ is some positive universal constant.  We are aiming at finding some improved exponential tail bound. Specifically, can we get $$P(S(h)\geq 1)\leq C\exp(-cn)$$ for some universal positive constants $C,c$ under the assumption or some stronger assumptions? (This bound improve both the two known bounds and is true if we think those $Y_i's$ are i.i.d multivariate normal with the same convariance matrix with that of the original random vector).

From another angle, we would like find some analogue to the inequality  $$P(\|\sum_{k=1}^n h_kX_k\|_2\geq \|h\|_2u)\leq \exp(-\frac{L}{2}(u^2-\log(u^2)-1))$$ for all $u>1$ and $h_1,..,h_n$, where $X_1,..,X_n$ are i.i.d uniformly distributed on the unit sphere $S^{n-1}=\{x\in R^L, \|x\|=1\}$. This inequality can be found here Thm 4.2 in this paper. The prove of this inequality relies on an extension of the Kintchine inequality to sum of independent random vectors that are rotationally invariant. See here extension of Kintchine inequality .

Any thoughts, comments, references are welcomed! Thanks!


text:
Q: Load and display an image: why is it rotated 90°? When doing:
library(png)
img = readPNG("a.png")

the image is loaded into a matrix and then by doing:
image(img, axes = FALSE, col = grey(seq(0, 1, length = 256)))

it is displayed. However it is displayed 90° rotated like this:

Why? and how to display it normally?
I tried to transpose the matrix img = t(img), but then it is flipped 180° vertically.

A: There may be a better way, but this works - transpose and then flip the columns:
image(t(img)[,ncol(img):1],axes=FALSE,useRaster=TRUE)

The reason for this flipping is the difference between image contexts and tabular contexts: from ?image,

Notice that 'image' interprets the 'z' matrix as a table of
       'f(x[i], y[j])' values, so that the x axis corresponds to row
       number and the y axis to column number, with column 1 at the
       bottom, i.e. a 90 degree counter-clockwise rotation of the
       conventional printed layout of a matrix.


text:
Q: Batch move file with using regex to new folder I'm not dev, I'm just looking for get code.
my folder:
default-0.png
default-0@2x.png
default-1.png
default-1@2x.png
default-2.png
default-2@2x.png
default-3.png
default-3@2x.png
default-4.png
default-4@2x.png
default-5.png
default-5@2x.png
default-6.png
default-6@2x.png
default-7.png
default-7@2x.png
default-8.png
default-8@2x.png
default-9.png
default-9@2x.png
...

I want move files with filename "@2..." only and any file extension to "new folder".
default-0@2x.png
default-1@2x.png
default-2@2x.png
default-3@2x.png
default-4@2x.png
default-5@2x.png
default-6@2x.png
default-7@2x.png
default-8@2x.png
default-9@2x.png
...

I trying use regex: (^.+@2.+.$) see check regex101 for full match text.
I tried my code and doesn't work:
@echo off
setlocal enabledelayedexpansion
for /f %%f in ('dir /b | findstr /r "(^.+@2.+.$)") do (
    md "new folder"
    move "%%~f" "moved folder"
)
Echo done
pause

anyone help me, what am i wrong?
UPDATED: thanks for @develc (answered) and @Mofi (edited)
This worked, perfect number of my files matched regex.
md "new folder"
move "*@2x*" "new folder"

ANOTHER METHOD:
This worked but 0.1% can't move cause can't detect to filename has comment like example@2x - if comment.png. thanks for answered by @Hackoo
@echo off
MD "new folder">nul 2>&1
setlocal enabledelayedexpansion
for /f %%f in ('dir /b *@2*') do (
    move "%%~f" "new folder"
)
Echo done
pause

A: There can be used something like this:
md "new folder"
move "*@2x*" "new folder"

In batch files, *a means everything that ends with a; b* means everything that starts with b; a*b means everything that starts with a and ends with b; a?b means everything that starts with a, has one character between a and b and ends with b. So * is a wildcard for everything and ? is a wildcard for every character.
See: MS-DOS and Windows Wildcard Characters
 on Microsoft's documentation site.

A: You can try something like that :
 @echo off
 MD "new folder">nul 2>&1
 setlocal enabledelayedexpansion
 for /f %%f in ('dir /b *@2*') do (
     move "%%~f" "new folder"
 )
 Echo done
 pause

A: There can be used also:
%SystemRoot%\System32\robocopy.exe . "new folder" *@2x.* /MOV /NDL /NFL /NJH /NJS >nul

The entire directory tree to the specified destination folder – in this case the subdirectory new folder in current directory – is automatically created by ROBOCOPY on not existing before moving all files in current directory matched by the wildcard pattern *@2x.*.
Run in a command prompt window robocopy /? for help on this command.
See also:

*

*SS64.com - A-Z index of Windows CMD commands

*Microsoft documentation for the Windows commands

*Microsoft documentation about Naming Files, Paths, and Namespaces

*Microsoft documentation about Using command redirection operators

A: You could also use this (based on @develc's answer)
@echo off
echo Setting up . . .
set "file=%temp%\d-file%random%.txt"
echo "d" > "%file%"
echo Starting the copy process . . .
xcopy /D /V "*@2*" "new folder" 1>nul < "%file%"

if errorlevel 0 (
    echo Copying files completed successfully.
    echo Starting to delete old files . . .
    del /Q "*@2*" || (echo Deleting files failed. && echo on && exit /b 1)
    echo Deleting files completed successfully.
    @echo on
    @exit /b 0
)

echo Copying files failed.
@echo on
@exit /b 2

A: Normally your regex syntax seem to be correct. But when you check "findstr" documentation the plus (+) character is not in accepted list :)
Findstr doc: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/findstr
You can try this:
@echo off
setlocal enabledelayedexpansion
MD "new folder">nul 2>&1
for /f %%f in ('dir /b ^ | findstr /r "(^.*@2.*$)"') do (
    move "%%~f" "new folder"
)
Echo done
pause


text:
Q: Learning roadmap request: compiling a "Mathematics Stack Exchange Undergraduate Bibliography" [Book recommendation] questions are quite popular on this website, which is, at least for me, one of the best places to get useful and insightful suggestions because it gathers a great number of experts in different areas of mathematics.
In my opinion, it would be very beneficial for the organization of the site (and for the many undergraduate students searching for guidance when facing a new course or looking for a good learning roadmap -- like myself) to make one thread that collects a big "Mathematics Stack Exchange Undergraduate Mathematics Bibliography" divided by categories just like the nice one proposed here, but surely more comprehensive (given the much larger number of contributors).
This thread should collect sparse material already available on the website but hard to find among the numerous questions and also new inputs. Ideally each entry should be briefly commented with matter-of-fact remarks.

A: Please, add your contributions to this answer (which I made community wiki). In case you wish to add some personal comments about your entries, add a tag like [Your_Username].

Foundations
 Daniel J. Velleman, How
    to Prove It: A Structured Approach
Problem solving

*

*G. Polya, How to Solve It: A New Aspect of Mathematical Method
Recreational
Algebra

*

*Roger Godement  , Algebra     (Translation of Cours d' Algebre)

*Lang - Algebra

*Jacobson - Basic Algebra I, Basic Algebra II

*Rotman - Introduction to the Theory of Groups

*Dummit and Foote - Algebra

*Hungerford - Abstract Algebra

*Serre - Linear Representations of Finite Groups

*Fulton, Harris - Representation Theory - A First Course

*Humphreys - Introduction to Lie Algebras and Representation Theory

*Atiyah, MacDonald - Introduction to Commutative Algebra

*Eisenbud - Commutative Algebra: with a View Toward Algebraic Geometry

*Weibel - An Introduction to Homological Algebra

Linear algebra

*

*Sheldon Axler, Linear Algebra Done Right.

*
*Sergei Treil, *Linear Algebra Done Wrong*

*

*Roman - Advanced Linear Algebra

Geometry

*

*Mumford - The Red Book of Varieties and Schemes

Point-set topology
Differential geometry

*
*John Lee, *Introduction to Smooth Manifolds
*

Number theory

*
* Andre Weil, *Basic Number Theory*

*

*Ireland and Rosen - A Classical Introduction to Moder Number Theory

*Edmund Landau - Introduction to Number Theory

*Burton - Elementary Number Theory

Combinatorics and discrete mathematics

*

*Graham, Knuth, Patashnik, Concrete Mathematics.
Probability and Statistics
Real analysis

*
*Gerald B. Folland, *Real Analysis: Modern Techniques and Their Applications*

*

*Shilov and  Gurevich: Integral, Measure and Derivative.

Multivariable calculus

*

*Spivak, Calculus On Manifolds.
Complex analysis

*

*Tristan Needham, Visual Complex Analysis.

*Remmert - Introduction to the Theory of Functions.

*Remmert - Classical Topics in Function Theory

Differential equations
Functional analysis

*
*Walter Rudin, *Functional Analysis*

*Erwin Kreyszig, *Introductory Functional Analysis with Applications*

*Reinhold Meise & Dietmar Vogt: Introduction to Functional Analysis
Mathematical and theoretical physics

*

*Arnold - Mathematical Methods of Classical Mechanics


text:
Q: How to optimize .NET EF Core bulk insert? I'm building an app for ordering food at school. This requires the end user to add accounts for the different types (head secretariat, teacher, pupil,..).
I made a reliable interface to do so but it takes 111 seconds to add 1000 pupils because of all the queries it needs to go through for one insert.
this is the code for insert:
public async Task<List<FullPupil>> AddPupilAccountsBySchoolId(List<FullPupil> pupils, string schoolId, string password, string hashedPassword, Types type) {
        foreach (FullPupil pupil in pupils) {
            Accounts checkAccount = await _context.Accounts.FirstOrDefaultAsync(a => a.Email == pupil.Email);

            if (checkAccount == null) {
                Accounts newAccount = new Accounts() {
                    Email = pupil.Email,
                    FirstTime = true,
                    FirstTimePassword = password,
                    Password = hashedPassword,
                    Name = pupil.Name,
                    SurName = pupil.SurName,
                    EmailSend = false,
                };

                await _context.Accounts.AddAsync(newAccount);
                checkAccount = newAccount;
            }

            AccountsTypes checkAccountsTypes = await _context.AccountsTypes.FirstOrDefaultAsync(a => a.AccountId == checkAccount.AccountId && a.TypeId == type.TypeId);

            if (checkAccountsTypes == null) {
                AccountsTypes accountsTypes = new AccountsTypes() {
                    AccountId = checkAccount.AccountId,
                    TypeId = type.TypeId,
                };

                await _context.AccountsTypes.AddAsync(accountsTypes);
            }

            Pupils checkPupil = await _context.Pupils.FirstOrDefaultAsync(a => a.AccountId == checkAccount.AccountId);

            if (checkPupil == null) {
                Pupils newPupil = new Pupils() {
                    AccountId = checkAccount.AccountId,
                    ClassId = Guid.Parse(pupil.Class[0].Id),
                    CodeId = Guid.Parse(pupil.Code[0].Id),
                    ModifiedDate = DateTime.Now,
                };

                await _context.Pupils.AddAsync(newPupil);
            } else {
                checkPupil.ModifiedDate = DateTime.Now;
            }

            pupil.AccountId = checkAccount.AccountId;
        }

        await _context.SaveChangesAsync();
        return pupils;
    }

(I am aware that all accounts will have the same password, this is just for testing purpose)
This is the database structure this uses:

(a classId in Pupils is linked to a unique class of a school)
One account can have multiple functions or be the same function on multiple schools so for example: a teacher can be teacher on multiple schools and at the same time a parent on a different school. (AccountsTypes is a many-to-many relationship between Accounts and Types)
Because of this, the insert needs to check if the account already exists and if it doesn't, add it, otherwise do nothing and go on and check if it is already a pupil in this school and if it isn't, add it, otherwise do nothing and so on.
I thought of a solution by just adding everything and if it already exists, just update it without first checking but I couldn't find anything about how to do that.
So how can I optimize this so it doesn't take so long and doesn't have to check if it already exists and maybe insert it in one addAsync so it adds it in all the related tables?
This also needs to be really reliable so it doesn't fail.

A: EF itself is not designed for Bulk Operations, everything should go through ChangeTracker.
I would suggest to use linq2db.EntityFrameworkCore (note that I'm one of the creators).
Library has temporary tables support and it's onw LINQ translator, which makes linq2db very powerful for ETL tasks.
public async Task<List<FullPupil>> AddPupilAccountsBySchoolId(List<FullPupil> pupils, string schoolId, string password, string hashedPassword, Types type)
{
    using var db = _context.CreateLinqToDBConnection();

    // Preprocess data for temporary table
    var pupilsProjection = pupils.Select(pupil => new
    {
        pupil.Email,
        pupil.Name,
        pupil.SurName,
        ClassId = Guid.Parse(pupil.Class[0].Id),
        CodeId = Guid.Parse(pupil.Code[0].Id),
    });

    // here we create temporary table and execute BulkCopy for inserting items into database
    using var tempPupil = await db.CreateTempTableAsync(pupilsProjection, tableName: "TempPupils");

    var missingAccounts =
        from t in tempPupil
        join a in _context.Accounts on t.Email equals a.Email into gj
        from a in gj.DefaultIfEmpty()
        where a == null
        select t;

    // Inserting missed accounts
    await missingAccounts.InsertAsync(_context.Accounts.ToLinqToDBTable(), pupil =>
        new Accounts
        {
            Email = pupil.Email,
            FirstTime = true,
            FirstTimePassword = password,
            Password = hashedPassword,
            Name = pupil.Name,
            SurName = pupil.SurName,
            EmailSend = false,
        }
    );

    // Helper query for Acount <-> Pupil association
    var pupilWithAccount =
        from t in tempPupil
        join a in _context.Accounts on t.Email equals t.Email
        select new
        {
            Pupil = t,
            Account = a
        };

    var missingAccountTypes =
        from pa in in pupilWithAccount
        join at in _context.AccountsTypes on new { pa.Account.AccountId, pa.Account.TypeId } equals { at.AccountId, type.TypeId } into gj
        from at in gj.DefaultIfEmpty()
        where at == null
        select pa.Account;

    // Inserting missing Account Types
    await missingAccountTypes.InsertAsync(_context.AccountsTypes.ToLinqToDBTable(),
        a => new AccountsTypes()
        {
            AccountId = a.AccountId,
            TypeId = type.TypeId,
        }
    );

    var missingPupils =
        from pa in pupilWithAccount
        join p in _context.Pupils on pa.AccountId equals p.AccountId into gj
        from p in gj.DefaultIfEmpty()
        where p == null
        select pa;

    // Insering missing pupils
    await missingPupils.InsertAsync(_context.Pupils.ToLinqToDBTable(),
        pa => new Pupil
        {
            AccountId = pa.Account.AccountId,
            ClassId = pa.Pupil.ClassId,
            CodeId = pa.Pupil.CodeId,
            ModifiedDate = Sql.CurrentTimestamp,
        }
    );

    // retrieve current account Id
    var newIds = await pupilWithAccount
        .Select(pa => new { paAccount.Account.AccountId, paAccount.Account.Email })
        .ToDictionaryAsyncLinqToDB(x => x.Email, x => x.AccountId);

    foreach (var pupil in pupils)
    {
        if (newIds.TryGetValue(pupil.Email, out var accountId))
            pupil.AccountId = accountId;
    }

    return pupils;
}

Please note that I have written this sample from memory and there can be typos.


text:
Q: how to access to a sub-set of a dictionary through a sub-set of a key? For efficiency reason, I am representing a textual huge dictionary as a Python dictionary with a key in form of a tuple (first letter, number of letter). We can visualize it as a matrix. Let us have an example built from a list:
l=["baby", "bird","as","at", "friend","always"]
d = {}
for mot in l:
  if (len(mot), mot[0]) in d:
      d[len(mot),mot[0]].append(mot)
  else:
      d[len(mot),mot[0]] = [mot]

print("d : ", d)

The result is:
d :  {(6, 'a'): ['always'], (6, 'f'): ['friend'], (2, 'a'): ['as', 'at'], (4, 'b'): ['baby', 'bird']}

The question is how to print/access to a line or a row in a single command.
For example: all the words starting with a, or all the words of length 6.

A: use filter builtin, it takes two argument, function and iterable:
filter(lambda x, y: x[0] == 6, d.items())

A: With a single command, one option could be:
lines = [d[k] for k in d if k[1] == 'a']

similarly for the other case.
But, this totally beats the point of using a dictionary, now you've just scanned over all the keys to find elements that partially share the key.
It would be more efficient, time-wise, to relate each length with a dictionary of letters and do a double key-lookup; this obviously increases the memory requirements of the structure but that's the trade-off you need to pay.


text:
Q: React router not working I have a simple react-router setup. Please see my code here -
https://github.com/rocky-jaiswal/lehrer-node/tree/master/frontend
It is the most basic setup for react-router, however in the browser I cannot get it working -
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route } from 'react-router';
import IndexContainer from './components/index-container';
import AboutContainer from './components/about-container';
import PagesContainer from './components/pages-container';

(function main() {
  ReactDOM.render((
    <Router>
      <Route path="/" component={IndexContainer}>
        <Route path="about" component={AboutContainer} />
        <Route path="pages" component={PagesContainer} />
      </Route>
    </Router>),
    document.getElementById('app')
  );
})();

The trouble also is there is no error reported on the console. Even I change the URL the IndexComponent is always mounted. Also if I type http://localhost:3333/#/about it changes to http://localhost:3333/#/about?_k=bac2pt somehow and stays on the IndexComponent.
Could there be something wrong with my simple webpack config or versions of react / react-router?
Thanks,
Rocky

A: IndexContainer is your parent component, try adding { this.props.children } in your render() so AboutContainer and PagesContainer will show.