text:
Q: Filtering the required data from Firebase based on the button selection I have two activities, one(MainActivity) where there is an option of selecting the Category of event you want to see, and the second activity(EventView) shows you those particular events based on your selection. The category options are:
Arch
Art
Finance
Science
In the next activity, I want the data from Firebase to come in the form of a recycler view based on the category I select, however all my data from Firebase is being called. I added a query next to my databaseReference, using orderByChild, to get my required data.
MainActivity.java
package com.example.admin.trialforevents;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button b1, b2, b3, b4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        b1 = (Button) findViewById(R.id.archBttn);
        b2 = (Button) findViewById(R.id.artBttn);
        b3 = (Button) findViewById(R.id.scienceBttn);
        b4 = (Button) findViewById(R.id.financeBttn);

        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
        b3.setOnClickListener(this);
        b4.setOnClickListener(this);
    }

    public void onClick(View view){
        Toast.makeText(this, "Button Selected !", Toast.LENGTH_SHORT).show();
        Intent i = new Intent(getApplicationContext(), EventView.class);

    switch(view.getId()){
        case R.id.archBttn:
            String arch = "Architecture";
            i.putExtra("Category", arch);
            break;

        case R.id.artBttn:
            String art = "Art";
            i.putExtra("Category", art);
            break;

        case R.id.scienceBttn:
            String science = "Science";
            i.putExtra("Category", science);
            break;

        case R.id.financeBttn:
            String fin = "Finance";
            i.putExtra("Category", fin);
            break;
    }
        startActivity(i);
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.admin.trialforevents.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/archBttn"
        android:text="Arch"
        android:layout_marginTop="41dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:text="Art "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/archBttn"
        android:layout_alignRight="@+id/archBttn"
        android:layout_alignEnd="@+id/archBttn"
        android:layout_marginTop="33dp"
        android:id="@+id/artBttn" />

    <Button
        android:text="Finance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/financeBttn"
        android:layout_below="@+id/artBttn"
        android:layout_alignLeft="@+id/artBttn"
        android:layout_alignStart="@+id/artBttn"
        android:layout_marginTop="32dp" />

    <Button
        android:text="Science"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/financeBttn"
        android:layout_alignRight="@+id/financeBttn"
        android:layout_alignEnd="@+id/financeBttn"
        android:layout_marginTop="33dp"
        android:id="@+id/scienceBttn" />
</RelativeLayout>

EventView.java
package com.example.admin.trialforevents;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;

public class EventView extends AppCompatActivity{

    DatabaseReference databaseReference;

    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_view);

        databaseReference = FirebaseDatabase.getInstance().getReference().child("ApprovedEvents");

        recyclerView = (RecyclerView) findViewById(R.id.request_EventList);

        //Avoid unnecessary layout passes by setting setHasFixedSize to true
        recyclerView.setHasFixedSize(true);

        //Select the type of layout manager you would use for your recyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

    }

    @Override
    protected void onStart() {
        final String event_cat  = getIntent().getStringExtra("Category");
        super.onStart();
        FirebaseRecyclerAdapter<Event, RequestViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Event, RequestViewHolder>(
                Event.class,
                R.layout.event_list_row,
                RequestViewHolder.class,
                databaseReference.orderByChild(event_cat)
        ) {
            @Override
            protected void populateViewHolder(RequestViewHolder viewHolder, Event model, int position) {
                    viewHolder.setTitle(model.getTitle());
                    viewHolder.setDesc(model.getDesc());
                    viewHolder.setCategory(model.getCategory());
                    viewHolder.setLocation(model.getLocation());
                    viewHolder.setPrice(model.getPrice());
                    viewHolder.setImageUrl(getApplicationContext(), model.getImageUrl());
                viewHolder.imageButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(EventView.this, "Image Selected", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };
        recyclerView.setAdapter(firebaseRecyclerAdapter);
    }

    public static class RequestViewHolder extends RecyclerView.ViewHolder {
        View mView;
        ImageView imageButton;

        public RequestViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
            imageButton = (ImageView) mView.findViewById(R.id.request_image);
        }

        public void setTitle(String title) {
            TextView a_title = (TextView) mView.findViewById(R.id.request_title);
            a_title.setText(title);
        }

        public void setDesc(String desc) {
            TextView a_desc = (TextView) mView.findViewById(R.id.request_desc);
            a_desc.setText(desc);
        }

        public void setLocation(String location) {
            TextView a_desc = (TextView) mView.findViewById(R.id.request_location);
            a_desc.setText(location);
        }

        public void setCategory(String category) {
            TextView a_category = (TextView) mView.findViewById(R.id.request_category);
                a_category.setText(category);
        }

        public void setPrice(String price) {
            TextView a_price = (TextView) mView.findViewById(R.id.request_price);
            a_price.setText(price);
        }

        public void setImageUrl(Context ctx, String imageUrl) {
            ImageView a_image = (ImageView) mView.findViewById(R.id.request_image);
            Picasso.with(ctx).load(imageUrl).into(a_image);
        }
    }
}

activity_event_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.admin.trialforevents.EventView">
    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/request_EventList"
        android:clickable="true"/>

</RelativeLayout>

Event.java
package com.example.admin.trialforevents;

public class Event {

    private String title, desc, location, category, price, imageUrl;

    public Event(String title, String imageUrl, String price, String category, String location, String desc) {
        this.title = title;
        this.imageUrl = imageUrl;
        this.price = price;
        this.category = category;
        this.location = location;
        this.desc = desc;
    }
    public Event(){

    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getPrice() {
        return price;
    }

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

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

}

event_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/request_category"
            android:textStyle="bold"
            android:textSize="15dp"
            android:padding="5dp"
            android:layout_gravity="left"
            android:text="Category will come here"/>

        <TextView
            android:layout_width="191dp"
            android:layout_height="wrap_content"
            android:id="@+id/request_location"
            android:textSize="15dp"
            android:gravity="right"
            android:layout_gravity="right"
            android:text="Location will come here"
            android:padding="5dp"
            android:textStyle="bold"/>
    </LinearLayout>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Price will come here"
        android:id="@+id/request_price"
        android:paddingBottom="5dp"
        android:paddingLeft="5dp"/>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="275dp"
        android:id="@+id/request_image"
        android:src="@drawable/abc_btn_check_material"
        android:adjustViewBounds="true"
        android:clickable="true"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/request_title"
        android:text="Title will come here "
        android:padding="10dp"
        android:textStyle="bold"
        android:textSize="15dp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/request_desc"
        android:text="Desc will come here "
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp" />

</LinearLayout>

A: You almost got it!
Everything is fine, except your Switch: after each Case, you should provide a Break.
The way it is written now will always cause the last case to be called, which is "Finance" in your case.
Did this for you:
switch(view.getId()){
    case R.id.archBttn:
        String arch = "Architecture";
        i.putExtra("Category", arch);
        break;

    case R.id.artBttn:
        String art = "Art";
        i.putExtra("Category", art);
        break;

    case R.id.scienceBttn:
        String science = "Science";
        i.putExtra("Category", science);
        break;

    case R.id.financeBttn:
        String fin = "Finance";
        i.putExtra("Category", fin);
        break;
}

Side note: your code is beautifully written :)

A: In the FireBaseRecyclerAdapter while mentioning datareference as an argument, use a query like:
databaseReference.orderByChild("category").equalTo(event_cat)

This will call only the category of data that is required.


text:
Q: Xcode 11 - Simulator won't respond Ever since I updated to Xcode 11, the simulator freezes intermittently. Specially when the keyboard is brought to focus. I don't think it has anything to do with memory or any hardware specs of my Mac since it does not crashes, just doesn't respond to any events.
The only solution so far is to rebuild again and again the app until the touch on the textfield magically responds again.
Has anyone faced the same problem? Any ideias on what might be causing it?
Thank you!

A: According to this post in Apple's developer forum it's a bug in the simulator. A workaround is to disable to Pasteboard sync in the simulator. Uncheck the option in Edit -> Automatically Sync Pasteboard

redpajama_set_name: RedPajamaStackExchange


text:
Q: urllib.error.HTTPError: HTTP Error 400: Bad Request in Python function I am making a program which searches for recipes based on certain input (being ingredients so far). The program works when I search for only a few ingredients, but a few more return an urllib error. I looked at other questions but they were for urllib 2 and their solutions didn't fix my issue.
Link where it works (searching for a few ingredients) - http://allrecipes.com/search/results/?ingIncl=Chicken&ingExcl=beef&sort=re
Link where it doesn't (searching for more) - http://allrecipes.com/search/results/?ingIncl=chicken,cheese,egg&ingExcl=lettuce&sort=re
*My code below
from bs4 import BeautifulSoup
import urllib
import urllib.request

html = "http://allrecipes.com/search/results/?ingIncl='chicken', 'cheese', 'egg'&ingExcl='lettuce'&sort=re"
number = 5

def get_recipes(html, number):######## this doesnt work if there are a few ingredients

    html = urllib.request.urlopen(html)

    soup = BeautifulSoup(html, "html.parser")

    num_results = soup.find('span',{'class': 'subtext'}).get_text()
    num_results = str(number) + ' out of ' + num_results #number will have to be changed if less recipes were found than number

    i = 0
    recipe_dict = {}

    for card in soup.find_all('article', {'class':'grid-col--fixed-tiles'}): #gets 2 more than required
        try:
            info = card.find('a', {'data-internal-referrer-link':'hub recipe'})
            link = info.get('href')
            name = info.get_text()
            recipe_dict[name] = link
            if i > (number - 2): #-2 is temp fix
                break
            else:
                i += 1
        except:
            pass
    print(recipe_dict)
    return recipe_dict

get_recipes(html, number)

Error:
Traceback (most recent call last):
  File "C:\Users\bakat\AppData\Local\Programs\Python\Python35-32\Diet Buddy\DB_find_recipes.py", line 39, in <module>
    get_recipes(html, number)
  File "C:\Users\bakat\AppData\Local\Programs\Python\Python35-32\Diet Buddy\DB_find_recipes.py", line 13, in get_recipes
    html = urllib.request.urlopen(html)
  File "C:\Users\bakat\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 163, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\bakat\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 472, in open
    response = meth(req, response)
  File "C:\Users\bakat\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 582, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Users\bakat\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 510, in error
    return self._call_chain(*args)
  File "C:\Users\bakat\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 444, in _call_chain
    result = func(*args)
  File "C:\Users\bakat\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 590, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request

A: Seems to be a simple typo.  Compare:
html = "http://allrecipes.com/search/results/?ingIncl='chicken', 'cheese', 'egg'&ingExcl='lettuce'&sort=re"

And
html = "http://allrecipes.com/search/results/?ingIncl=chicken,cheese,egg&ingExcl=lettuce&sort=re"


text:
Q: How do I access another MySQL Database from another IP Address with PHP? Ok, If you can answer this question, you deserve the nobel peace prize. Anyways, here's the situation.
I'm using Slicehost dot net, and I have 2 slices (two different IPs). One slice is my mail server and the other is my normal website. I'm running Ubuntu (8.04 or 8.10, something like that, it shouldn't matter). What I'm trying to do is access the MySQL database on the Mail server from the other slice. I'm trying to do that with PHP. I really appreciate any help.

A: mysql_connect()
$resource = mysql_connect('other-server-address.com', 'username', 'password');

The first parameter is the mysql server address.

Server Param
The MySQL server. It can also include
  a port number. e.g. "hostname:port" or
  a path to a local socket e.g.
  ":/path/to/socket" for the localhost.
If the PHP directive
  mysql.default_host is undefined
  (default), then the default value is
  'localhost:3306'. In SQL safe mode,
  this parameter is ignored and value
  'localhost:3306' is always used.

Unless I'm misunderstanding... this setup is pretty common. Any trouble you're having might be related to the following:

*

*Firewall settings

*Grant access to the mysql user to connect from the other host

*my.ini settings not allowing outside connections
Some other related SO questions:

*

*Connecting to MySQL from other machines

*How do I enable external access to MySQL Server?

*php access to remote database

*How to make mysql accept connections externally

*Remote mysql connection

A: Assuming your mail server is at IP 192.168.1.20 and web server is 192.168.1.30
First of all you need to allow the web server to access the mysql database on your Mail server .
On 192.168.1.20 you run the mysql command and grant access on the database needed to your web server
mysql>  grant all on mydb.* to 'someuser'@'192.168.1.30' identified by 'secretpass;

Your PHP code connects to that database with something like:
$conn = mysql_connect('192.168.1.20', 'someuser', 'secretpass');

A: mysql_connect() returns a link identifier if the connection is successful. Also you have to do is keep the references to both links.
When you want to use which ever link, simply include the link as an argument.
$link1 = mysql_connect($host1, $username1, $password1);
$link2 = mysql_connect($host2, $username2, $password2);
$r = mysql_query(QUERY, $link1);

Simple as that.


text:
Q: Calculating a surface integral using change of coordinates. I need to use
 $u=x+y,\ v=x^2+y^2$
to find $I=\int_D x+y\ dxdy$ where $D=\{ (x,y)\ :\ x^2+y^2=1, y\geq 0\}$.
I think the region for the $u-v$ plane is the rectangle $\{(u,v)\ :\ -1\leq u\leq \frac{1}{\sqrt{2}},0\leq v\leq 1\}$ but i'm having trouble finding the jacobian.
When finding the jacobian I used that $\frac{\partial y,x}{\partial u,v} =1/\frac{\partial u,v}{\partial x,y} $ and found that it's $\frac{1}{2\sqrt{2v-u^2}}$ though I'm having trouble computing the integral still when i put into the change of coordinate formula. And for the region I used a sketch.

A: Defining
$$ f :(x,y) \to (x+y,x^2+y^2)$$
$$ \nabla f(x,y)=\begin{pmatrix}
1 & 1\\
2x & 2y
\end{pmatrix}$$
$$J_f(x,y)=(1-2y)-(1-2x)=2(x-y) $$
So $f$ is a bijection from $D$ to $D'=[-1,\sqrt2]\times\{1\}- \{ x(u,v)=y (u,v)\}$
So once you have the expression of
$$  x(u,v) \\
y(u,v) $$
Put in $J_f$,invert it and then :
Your integral is :
$$ I=\int_{D'}(x(u,v)+y(u,v))|J_f^{-1}(u,v)|dudv $$


text:
Q: Linear independence of functions from positive definite kernel Let $S$ be a finite set and $M_p(S)\subset \mathbb{R}^{|S|}$ the set of probabilities on $S$.
Define the positive-definite kernel:
$$k:M_p(S)\times M_p(S)\rightarrow \mathbb{R},\,\qquad(\nu,\mu)\mapsto k(\nu,\mu):=\left(\sum_{s\in S}\nu(s)\mu(t)\right)^2=(\nu^T\mu)^2,$$
wherein the final equality $\nu\,,\mu$ are considered vectors in $\mathbb{R}^{|S|}$.
This positive-definite kernel induces maps $M_p(S)\rightarrow \mathbb{R}$, one for each $\nu\in M_p(S)$:
$$K_\nu:M_p(S)\rightarrow \mathbb{R},\,\qquad \mu\mapsto k(\nu,\mu).$$

Are these maps linearly independent?

Without the square,
$$K_\nu=\sum_{s\in S}\nu(s)K_{\delta^s},$$
and there is linear dependence, but I am looking for linear independence.

Some thoughts. Consider a finite set $\{\nu_1,\nu_2,\dots,\nu_m\}\subset M_p(S)$ and complex numbers $(\alpha_i)_{i=1}^m$ such that:
$$\sum_{i=1}^m\alpha_iK_{\nu_i}=0.$$
For each $s\in S$, we have:
\begin{align*}
  \sum_{i=1}^m\alpha_i K_{\nu_i}(\delta^s)  =0
  \Rightarrow \sum_{i=1}^m \alpha_i \nu_i(s)^2  =0
\end{align*}
Consider, for a pair $s_a,s_b\in S$:
\begin{align*}
  \sum_{i=1}^m\alpha_i K_{\nu_i}\left(\frac12\delta^{s_a}+\frac12 \delta^{s_b}\right)  =0
  \Rightarrow \sum_{i=1}^m \alpha_i\nu_i(s_a)\nu_i(s_b) & =0.
 \end{align*}
Summing over $s_a\in S$:
$$\sum_{i=1}^m\alpha_i \nu_i(s_b)=0.$$
Considering where $u_S$ is the uniform distrition
$$\sum_{i=1}^m\alpha_i K_{\nu_i}\left(u_S\right)\Rightarrow \sum_{i=1}^m \alpha_i=0.$$

As per the comments, it is sufficient to show that for any finite subset $\{\nu_1,\dots,\nu_m\}\subset M_p(S)$, that the Gram matrix $G\in M_m(\mathbb{R})$:
$$G_{ij}=\langle\nu_i,\nu_j\rangle^2=(\nu_i^T\nu_j)^2$$
is (strictly) positive definite.

The bounty winner's answer gives for $\nu_1=(1,0)$, $\nu_2=(0,1)$, $\nu_3=(1/2,1/2)$, and $\nu=(1/3,2/3)$:
$$K_\nu=-\frac19 K_{\nu_1}+\frac{2}{9}K_{\nu_2}+\frac49 K_{\nu_3}.$$

A: To show that the Gram matrix is positive definite, it is enough to note that it is the Hadamard product of the Gram matrix corresponding to the usual inner product with itself (which is itself positive definite) and then to use the Schur product theorem .
Edit:
If you begin with $v_i$ which are not linearly independent, there is no reason why the Gram matrix corresponding to $K$ should be non-singular as it is the Gram matrix of $e_i\otimes e_i$. For instance,  take $e_1=(1,0),e_2=(0,1)$ and the set $\{e_1,e_2,\frac{1}{2}e_1+\frac{1}{2}e_2,\frac{1}{3}e_1+\frac{2}{3}e_2\}$. The Gram matrix for the inner product is
$$G=\begin{pmatrix}1&0&\frac{1}{2}&\frac{1}{3}\\
0&1&\frac{1}{2}&\frac{2}{3}\\
\frac{1}{2}&\frac{1}{2}&\frac{1}{2}&\frac{1}{2}\\
\frac{1}{3}&\frac{2}{3}&\frac{1}{2}&\frac{5}{9}
\end{pmatrix}$$
so that $G\circ G$, the Gram matrix for our kernel is
$$\begin{pmatrix}1&0&\frac{1}{4}&\frac{1}{9}\\
0&1&\frac{1}{4}&\frac{4}{9}\\
\frac{1}{4}&\frac{1}{4}&\frac{1}{4}&\frac{1}{4}\\
\frac{1}{9}&\frac{4}{9}&\frac{1}{4}&\frac{25}{81}
\end{pmatrix}$$
which has determinant $0$.


text:
Q: WPF get inserted inline from applypropertyvalue I have a RichTextBox (CurRichTextControl) and I change the TextDecoration of selected text:
TextRange range = new TextRange(CurRichTextControl.Selection.Start, CurRichTextControl.Selection.End);
TextDecorationCollection tdc;
tdc = TextDecorations.OverLine;
range.ApplyPropertyValue(Inline.TextDecorationsProperty, tdc);

WPF ist going to create a new Inline by that.
Lets say the Paragraph containing the range consists of only 1 Inline (or Run) prior to applying the TextDecoration.
Then it is going to result in 3 Inline elements after that.
How can I get the new Inline with the OverLine? ApplyPropertyValue does not return any value or object. Do I have to search the Paragraph manually?
Thank you!


text:
Q: modalDialog inside a loop in shinyapp How can I use a modalDialog inside a loop? I've looked at some forums but none of them were satisfactory or didn't fit my problem.
Below is a minimal reproducible code that simulates my problem. The solution presented in RShiny: How to have sequential Modals in for loop didn't work as the actionbutton I put in the text argument of the shinyalert function was not recognized in the observeEvent.
library(shiny)

dialog_filtro <- function(ID,LabelID,messagee){
  modalDialog(
          title = "Menssagem importante",
          messagee,
          footer = tagList(
                           actionButton(ID[1],LabelID[1]),
                           actionButton(ID[2],LabelID[2])
                           )
           )
}

ui <- fluidPage(
           uiOutput('res')
)

server <- function(input, output, session) {

      RESFIL <- reactiveValues(dest = NULL)
      lista <- list(a=2,a=3)
      grupdest <- rep(list(NA),length(lista))
      RESFIL$dest <- grupdest

      for(i in 1:length(lista)){

          if(lista[[i]] > 0){

             showModal(dialog_filtro(ID = c(paste0('yes',i),paste0('no',i)),
                     LabelID = c('Yes','No'),
                     messagee = paste0('This is the loop ',i)
                     ))

             observeEvent(input[[paste0('yes',i)]], {
                 RESFIL$dest[[i]] <- i+10
                 removeModal()
             })

             observeEvent(input[[paste0('no',i)]], {
                 RESFIL$dest[[i]] <- i+100
                 removeModal()
             })

             }else{
                 RESFIL$dest[[i]]  <- i+1000
                 removeModal()
             }
          }

        output$res <- renderPrint({ RESFIL$dest })
  }

shinyApp(ui = ui, server = server)

A: Here is a way with shinyalert. That's strange, if you put a button in a Shiny alert, then clicking the button automatically closes the alert. That's why I use actionLink instead of actionButton. The app does not react as usual when clicking one button/link, so I use the onclick attribute which runs Shiny.setInputValue. As you can see I'm using local in the loop, otherwise that does not work as expected. But I think (I didn't test) that instead of using for+local, you can use an ordinary lapply.
library(shiny)
library(shinyalert)

dialog_filtro <- function(i, input, session, RESFIL, ID, LabelID, messagee) {
  al <- shinyalert(
    title = "Menssagem importante",
    text = tagList(
      tags$p(messagee),
      actionLink(
        ID[1], LabelID[1], class = "btn btn-primary",
        onclick = sprintf(
          'Shiny.setInputValue("%s", true, {priority: "event"});',
          ID[1]
        )
      ),
      actionLink(
        ID[2], LabelID[2], class = "btn btn-primary",
        onclick = sprintf(
          'Shiny.setInputValue("%s", true, {priority: "event"});',
          ID[2]
        )
      ),
    ),
    html = TRUE,
    session = session
  )
  observeEvent(input[[ID[1]]], {
    RESFIL$dest[[i]] <- i + 10
    closeAlert(id = al)
  }, domain = session)
  observeEvent(input[[ID[2]]], {
    RESFIL$dest[[i]] <- i + 100
    closeAlert(id = al)
  }, domain = session)
}

ui <- fluidPage(
  verbatimTextOutput("res")
)

server <- function(input, output, session) {

  RESFIL <- reactiveValues(dest = NULL)
  lista <- list(a = 2, a = 3)
  grupdest <- rep(list(0), length(lista))
  RESFIL$dest <- grupdest

  for (i0 in 1:length(lista)) {
    local({

      i <- i0

      if (lista[[i]] > 0) {

        dialog_filtro(
          i,
          input,
          session,
          RESFIL,
          ID = c(paste0("yes", i), paste0("no", i)),
          LabelID = c("Yes", "No"),
          messagee = paste0("This is the loop ", i)
        )

      } else {
        RESFIL$dest[[i]] <- i + 1000
        # removeModal() not clear what you want to do here: remove which modal?
      }

    })
  }

  output$res <- renderPrint({
    RESFIL$dest
  })
}

shinyApp(ui = ui, server = server)


text:
Q: How we can clear the cookie for Internet Explorer for Selenium automation We are currently automating using IE browser using Selenium webdriver. in order to run our test cases we need to clear the cookie from Registry and run test case to start from page 1. Can you help me out to  how we can do?

A: I hope question is not related to registry. There are two ways which doesn't need to work with registry key to clear cookies are:

*

*set capability ie.ensureCleanSession to true
iexplorer.additional.capabilities={'ie.ensureCleanSession':true}

*Through code delete all coockies

 driver.manage().deleteAllCookies();

Right place to put #2 is in driver listener onInitialize method.
public void onInitialize(QAFExtendedWebDriver driver){
 driver.manage().deleteAllCookies();
}


text:
Q: Prevent Expressjs from creating a session when requests contain an authorization header? I have an API that can be called either using a browser where requests are transactional and have a session OR directly, eg. using curl, where requests are atomic. Browser requests must first authenticate and then use an express session (connect.sid) for subsequent authorization, direct API calls use a header: Authorization: "SOMETOKEN" which has to be sent for every request.
The problem I have is, because I'm using the same web server to serve both atomic and transactional traffic, every API call is needlessly being given a session by Express. Every response includes a Set-Cookie and all these sessions are filling up my session store. Therefore: how can I prevent Express from entering a new sess key in the memory store (Redis) when a request contains an Authorization header?
Note. I get that a more classic approach would be to have a separate API server and a separate WEB server but why not run both on one machine? To me, the difference is that the API serves data and the WEB serves views but beyond that they are both part of the same application. I just happen to also allow users to access their data directly and don't force them to use my interface.
Express Config
module.exports = function(app, exp, sessionStore, cookieParser, passport, flash) {

    app.configure(function(){
        // Templates
        app.set('views', ERNEST.root + '/server/views');
        app.set('view engine', 'jade');
        app.set('view options', { doctype : 'html', pretty : true });

        // Allow large files to be uploaded (default limit is 100mb)
        app.use(exp.limit('1000mb'));

        // Faux putting and deleting
        app.use(exp.methodOverride());

        // Static content
        app.use(exp.static(ERNEST.root + '/server'));
        app.use(exp.static(ERNEST.root + '/public'));

        // Handle favicon
        app.use(exp.favicon());

        // For uploads
        app.use(exp.bodyParser({keepExtensions: true}));

        // Configure cookie parsing
        if ( cookieParser ) app.use(cookieParser);
        else app.use(exp.cookieParser());

        // Where to store the session
        var session_options = { 'secret': "and she put them on the mantlepiece" };
        if ( sessionStore ) session_options.store = sessionStore;
        app.use(exp.session( session_options ));

        // Rememberance
        app.use( function (req, res, next) {
            if ( req.method == 'POST' && req.url == '/authenticate' ) {
                if ( req.body.rememberme === 'on' ) {
                    req.session.cookie.maxAge = 2592000000; // 30*24*60*60*1000 Rememeber 'me' for 30 days
                } else {
                    req.session.cookie.expires = false;
                }
            }
            next();
        });

        // PassportJS
        if ( passport ){
            app.use(flash());
            app.use(passport.initialize());
            app.use(passport.session());
        }
    });

};

An example route
app.get('/status/past_week', MID.ensureAuthenticated, MID.markStart, function(req, res) {
    WEB.getStatus('week', function(err, statuses){
        if ( err ) res.send(500, err);
        else res.send(200, statuses);
    });
});

Authorization Middleware
MID.ensureAuthenticated = function(req, res, next) {
  if ( req.isAuthenticated() ) return next();
  else {
        isAuthorised(req, function(err, authorised){
            if ( err ) return res.redirect('/');
            else if ( authorised ) return next();
            else return res.redirect('/');
        });
    }

    function isAuthorised(req, callback){
        var authHeader = req.headers.authorization;
        if ( authHeader ) {
            // Has header, verify it
            var unencoded = new Buffer(authHeader, 'base64').toString();
            var formatted = unencoded.toString().trim();
            ACCOUNT.verifyAuth(formatted, callback); // verifyAuth callbacks next() when successful
        } else callback(null, false); // No Authorised header
    }
};

A: Try this:
var sessionMiddleware = exp.session( session_options );

app.use(function(req, res, next) {
  if (req.headers.authorization) {
    return next();
  }
  return sessionMiddleware(req, res, next);
});

A: Looks like you need to write your own session middleware.  Here's an example.  If you can create a separate subdomain, say, www.example.com for browser sessions and app.example.com for accessing it directly, then you should be able to use the linked method almost exactly, and just don't start the session for app.example.com requests.  That may be the most direct method whereby the call indicates the method it intends to authenticate by, and any diversion from that is an error.
Otherwise, you'll have to detect the authentication token in the middleware and not start the session when you find it.

A: An alternative approach to reducing the amount of sessions stored in your session storage is to set a default maxAge to something low. Then, when you actually need sessions stored longer, like after a user logins, you can set req.session.cookie.expires = null;. Also don't forget to set the session expiration to something low when the user logs out.
Here's an example:
// set default to something low
app.use(session({
  resave: true,
  saveUninitialized: true,
  cookie: {
    maxAge: 5 * 60 * 1000 // 5 minutes
  },
  secret: secrets.sessionSecret,
  store: new MongoStore({
    url: yourUrl,
    auto_reconnect: true
  })
}));

// on successful login,
// set expiration to null or something longer than default
var time = 14 * 24 * 3600000; //2 weeks
req.session.cookie.maxAge = time;
req.session.cookie.expires = new Date(Date.now() + time);
req.session.touch();

// on logout, reset expiration to something low
var time = 5 * 60 * 1000; // 5 minutes
req.session.cookie.maxAge = time; //2 weeks
req.session.cookie.expires = new Date(Date.now() + time);
req.session.touch();

This is particularly useful when remote monitoring your app because if the monitoring is frequent enough, the sessions will fill up fast.

A: You can always just catch the response headers event and remove the 'set-cookie' header:
app.use(function(req, res, next) {
  res.on('header', function () {
    if (req.headers.authorization) {
      delete res._headers['set-cookie'];
    }
  });
  next();
});

You can technically put this anywhere in your middleware chain.


text:
Q: Segurança com AccountManager Estou utilizando o seguinte método para recolher o email do usuário para servir de autenticação(somente o email) no meu app:
AccountManager.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);

Minha dúvida é se isso é facilmente burlável e se tem como diminuir esse risco.


text:
Q: matching elements from one set to another using given metric First, I'd like to say I'm not looking for code, I'm looking for an algorithm.
Motivation:
I'm writing top-level testing of a complex real-time software system. It runs all software components (~20 processes, ~100 threads), sets up fake data sources (rtsp video sources) and feeds prepared data (video files) to the system, records system responses (events) and then stops the system after all prepared test data was sent.
As the test data is always the same, I expect tested system to provide correct responses (events) at correct times (from the start of the test).
I then compare generated responses (events) to expected events (manually prepared), which I expect to be all there, possibly with some small time variances which I would limit with some given time-tolerance, let's say 5 seconds.
Let's say the tested system is supposed to detect animals in 1500 seconds long video and I watched it and written down 5 animals and time when they appeared in video:
at   10s - a sparrow
at   20s - a cat
at   50s - a rabbit
at  100s - an owl
at 1000s - a bear

Based on that, I would then write expected_events set:
expected_events = [
    Event(10, 'sparrow'),
    Event(20, 'cat'),
    Event(50, 'rabbit'),
    Event(100, 'owl')
    Event(1000, 'bear')
]

And I want to be able to tell how well the real detected events (which will be affected by processor load, disk usage, network usage atd, as this is multiprocess system on real computer) match these expected_eevents.
Let's say the tested system returned:
detected_events = [
    Event(10.1, 'sparrow'),
    Event(19.5, 'cat'),
    Event(50.2, 'rabbit'),
    Event(99.3, 'owl')
    Event(1000.2, 'bear')
]

Which I would evaluate as correct, 100% match with expected events, all events are present and time differences are below time-tolerance:
matches = [
    {'name': 'sparrow', 'detected': 10.1,   'expected': 10,   'time-diff': 0.1},
    {'name': 'cat',     'detected': 19.5,   'expected': 20,   'time-diff': 0.5},
    {'name': 'rabbit',  'detected': 50.2,   'expected': 50,   'time-diff': 0.2},
    {'name': 'owl',     'detected': 99.3,   'expected': 100,  'time-diff': 0.7},
    {'name': 'bear',    'detected': 1000.2, 'expected': 1000, 'time-diff': 0.2},
]

If the tested system returned:
detected_events = [
    Event(10.1, 'sparrow'),
    Event(50.2, 'rabbit'),
    Event(99.3, 'owl')
    Event(1010.5, 'bear')
]

which I would expect could result in matches like this:
raw_matches = [
    {'name': 'sparrow', 'detected': 10.1,   'expected': 10,   'time-diff': 0.1},
    {'name': 'cat',     'detected': None,   'expected': 20,   'time-diff': None},
    {'name': 'rabbit',  'detected': 50.2,   'expected': 50,   'time-diff': 0.2},
    {'name': 'owl',     'detected': 99.3,   'expected': 100,  'time-diff': 0.7},
    {'name': 'bear',    'detected': 1010.5, 'expected': 1000, 'time-diff': 10.52},
]

pruned_matches = [
    {'name': 'sparrow', 'detected': 10.1,   'expected': 10,   'time-diff': 0.1},
    {'name': 'rabbit',  'detected': 50.2,   'expected': 50,   'time-diff': 0.2},
    {'name': 'owl',     'detected': 99.3,   'expected': 100,  'time-diff': 0.7},
]

I would see this as fail, because:

*

*it didn't detected a cat

*bear was detected 10.5 seconds too late

*therefore only 3 out of 5 was really matched and result should be 60% match

So I what I need is a method for evaluating detected_events against expected_events to be able to evaluate how good the tested system works.
Simplyfication
Because matching event types is essential to the problem and can be done as matching for every event type separately, I'll do following simplyfications:

*

*all events are the same - i.e. only the time of the event is important and therefore event will be represented only by the timestamp

*timestamp will be int to make it easier to read

What do I consider to be a "good" match:
As many of you pointed out in comments, I actually don't have metric for evaluating final matching beyond dismissing matches with time difference > time-tolerance.
This makes it a bit harder, but I think it's intuitive - I know what should happen at which time, and I compare that to actual events and I'll try to match them as good as is possible to make sure:

*

*as many expected events are matched as possible

*each detected_event matching expected_event must happen at the same time with given time tolerance.

So this I would consider "correct" matches (with 5 second time tolerance):
                                  matches = [
expected_events = [10, 20]  =>        {'expected': 10,    'detected': 10},
detected_events = [10, 20]            {'expected': 20,    'detected': 20},
                                  ]

                                  matches = [
expected_events = [10, 20]  =>        {'expected': 10,    'detected': 15},
detected_events = [15, 25]            {'expected': 20,    'detected': 25},
                                  ]

                                  matches = [
expected_events = [10, 20]  =>        {'expected': 10,    'detected':  5},
detected_events = [ 5, 15]            {'expected': 20,    'detected': 15},
                                  ]

                                  matches = [
expected_events = [10, 11]  =>        {'expected': 10,    'detected': 11},
detected_events = [11, 12]            {'expected': 11,    'detected': 12},
                                  ]

                                  matches = [
expected_events = [10, 20]  =>        {'expected': 10,    'detected': 10},
detected_events = [10, 26]        ]

expected_events = [10, 20]  =>    matches = []
detected_events = [ 4, 26]

                                  matches = [
expected_events = [10, 20, 30] =>     {'expected': 20,    'detected': 17},
detected_events = [17, 24]        ]

This I would consider "bad" matches (i.e. this is not how I want it to work):
                                  matches = [
expected_events = [10, 20]  =>        {'expected': 20,    'detected': 15},
detected_events = [15, 25]        ]
# matched only 1 events even though it's possible to match 2

                                  matches = [
expected_events = [10, 11]  =>        {'expected': 11,    'detected': 11},
detected_events = [11, 12]        ]
# matched only 1 events even though it's possible to match 2

                                  matches = [
expected_events = [10, 20]  =>        {'expected': 10,    'detected': 4},
detected_events = [ 4, 26]            {'expected': 20,    'detected': 26},
                                  ]
# should not match anything, time differences > 5sec

Pseudocode / What I tried:
Code should look something like this:
expected_events = [10, 20, 50, 100, 1000] # times in second
detected_events = [11, 18, 51,      1001]

def metric(ev1, ev2):
    return abs(ev1 - ev2)

matches = match_events(expected_events, detected_events, metric, tolerance=5)

*

*Simple, naive approach - start from best match
I tried extremely simple approach:

*

*product of (expected_events, detected_events)

*compute time difference

*filter matches with time difference greater than given tolerance

*sort matches by time difference

*start matching from first matches and discard "conflicts" (i.e. latter matches using same elements)

This works for simple cases, but I run into a problem when events are "shifted":
 expected_events = [10, 11]
 detected_events = [11, 12]

Now I get:
 [
     {'expected': 11,    'detected': 11},
 ]

While I want to have:
 [
     {'expected': 10,    'detected': 11},
     {'expected': 11,    'detected': 12},
 ]

*Brute force - permutations
Then I tried brute force:

*

*product of (expected_events, detected_events)

*compute time difference

*filter matches with time difference greater than given tolerance

*create all possible permutations of given matches

*for each permutation, start matching from first matches and discard "conflicts" (i.e. latter matches using same elements)

*compute lengths of all those matchings

*keep only those with maximal length

*select matching with min(sort by sum of all time differences)

This works, but as you may have expected, it's too slow for anything longer than few elements. (I hoped to make it work using lazy evaluation, but couldn't make it work).
Question:
What would be a correct algorithm for such matching?
It seems to me this may be already solved problem - but I don't know what to search for.

It is a solved problem - assignment problem - https://en.wikipedia.org/wiki/Assignment_problem - thanks to Yossi Levi!

A: I will follow your asking, and provide a non-programming approach, but only logical (semi-mathematical) approach as I see it.
Algorithm steps:

*

*lets define the threshold as T

*pad the smaller list with don't care values (None for example) - just to make sure the dimension agreed

*create similarity matrix by take absolute value of decreasing each element of one list to element in other list, let's define the matrix as S.

clarification: S[i,j] refer to the difference between i'th element from list A to j'th element in list B

*

*create binary matrix B in which every element that satisfy the threshold critirea is 1, otherwise it 0 (MATLAB-> B=S<L)

for example:
       0 0 0

B =    0 1 1

       1 0 0

saying X dimension represent list A and Y represent list B then:
B[2] === A[2]
B[2] === A[3]
B[3] === A[1] (=== means that two elements satisfy the criteria of similarity)

Now - the question becomes more mathematical, in order to find the best match, you can use one of the following suggestions:
brute force (less elegant approach in my opinion):

*

*choose element which is 1 (among non marked rows and columns)

*mark his entire column and row as marked

*keep choose another 1 until there aren't legal places and sum it up to score

*iteratively do it for all options and choose the one with the highest score
more elegant approach:

*

*iterate over all permutations of columns (for B matrix)

*if Trace or opposite-diagonal equals to len(A) then finish (found matching for all elements)

*choose the permutation with highest TRACE (or the opposite diagonal)
number of permutations in worst case are of-course N! (which N is the dimension of B)

Best approach:
While searching over the net on how to find the maximum Trace of matrix when only columns swapping allowed I ran into this (pay attention please to Example and Matrix interpretation sections).
moreover, I found implementation of it in PyPI package.
As the documentation says - the algorithm is trying to find the minimum Trace over all possible permutations of matrix - so just invole with -B as argument instead.
overall example (with more elegant approach as last step):
A = [1,5,7]
B = [6,6,2]

T = 2

S =
5 5 1
1 1 3
1 1 5

B =
0 0 1
1 1 0
1 1 0

permutations of columns:

1-
0 0 1
1 1 0
1 1 0

Trace = 1
other-diagonal = 3

Done -- > no need for more permutations because len(other-diagonal) == 3
A[1] =1 === B[3] =2
A[2] =5 === B[2] =6
A[3] =7 === B[1] =6

feel free to ask, or give any insights that you might have

A: I just found out there is pretty good implementation of "Hungarian algorithm" (assignment problem) in scipy python package:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html
Example (for expected, detected, metric see the question's example code):
from scipy.optimize import linear_sum_assignment

...

def match_events(expected, detected, metric, tolerance=5):
    # some arbitrary large value used to prevent impossible matches
    dont_match = 1000 * tolerance

    def modified_metric(e, d):
        dt = metric(e, d)
        return dt if dt <= tolerance else dont_match

    cost_matrix = [
        [
            modified_metric(exp, det)
            for det in detected
        ]
        for exp in expected
    ]
    row_idx, col_idx = linear_sum_assignment(cost_matrix)
    for e_idx, d_idx in zip(row_idx, col_idx):
        dt = cost_matrix[e_idx][d_idx]
        if dt <= time_tolerance:
            yield (expected[e_idx], detected[d_idx], dt)

It's not very elegant, because I had to somehow limit matches to tolerance, but Hungarian algorithm works only on matrix of all possible combinations, so I use dont_match value to mark those cases.


text:
Q: How do I get my ExpressJS/NodeJs backend to work with HTTPS? I'm currently working on deploying a fullstack webapp to DigitalOcean, where I have 2 docker images - One for the frontend to statically serve files, and an ExpressJS backend that handles any logic for API calls. I have recently added CloudFlare to my website, which has enabled HTTPS, and while that is progress, now my backend is no longer responsive from the domain when doing HTTPS, if i access it by going to my droplet's ip(unsecure, HTTP) I can see that my api requests are working, but on the main HTTPS site, the entire backend is unresponsive.
I am currently mapping my frontend to port 80 outside of the docker container (from port 3000 inside) and 3001:3001 for my backend. I've heard that I should maybe use nginx, but I'm unsure how that works with my 2 docker images, and I've tried to use https.createServer(options, app) to try to get it to listen for the HTTPS requests, but to no avail.
Here is my current backend now:
const express = require("express");
const webserver = express();
const cors = require("cors");
const mysql = require("mysql");

// Connection pool here

webserver.use(cors());
webserver.use(express.json());

const PORT = 3001;

//api routes here

webserver.listen(PORT, () => {
  console.log(`[Express] Server running on ${PORT}`);
});

Any step in the right direction would be much appreciated, I've been researching how to fix this for ~10 hours with no luck.
Edit: I believe the solution is not to change the Express server to allow HTTPS, but somehow have Nginx do a reverse proxy and convert it to HTTP before it even hits the Express server, but I am unsure of how this is done.

A: Instead of app.listen() or with your variable naming webserver.listen(), you have to manually create the server instance using https.createServer() and pass it the security credentials for your https server:
const https = require('https');
const express = require("express");
const app = express();

const server = https.createServer({
      key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
}, app);

server.listen(443);

Relevant https doc here and Express doc here.


text:
Q: Trying to create an automated docker build I am trying to learn docker and create an automated build. I forked a git repo with a dockerfile. I then added this repo to my docker hub account as described here:
When I tried to pull it, I get:
$ docker pull sukottokun/docker-drupal-env
Using default tag: latest
Pulling repository docker.io/sukottokun/docker-drupal-env
Tag latest not found in repository docker.io/sukottokun/docker-drupal-env

Ok, so there is no "latest" tag, fine. After figuring out this is different than a git tag (I think, I tried and failed to clone after pushing a git tag), I am now trying to add that. Since I can't pull it, how can I add a tag?


text:
Q: Launch ipad application from attachment in email I am sending a zip file containing images and text file as an email attachment in ipad. Now my required functionality is that I want to launch my app when user taps on attachment for downloading and save the zip file in documents folder of app. How can I accomplish this task?

A: You cannot launch your iPhone/iPad Application by clicking on the attachment link in email. However, you can open your app by setting custom URL for your app.
For more information on setting custom URL for your app, you can check the question below, May be this way you can achieve your target :
How to register a custom app opening URL scheme with Xcode 4?


text:
Q: create-react-app is not using my eslint configuration file I am using create-react-app to start a new react project, and I want to use my own eslint configuration file, extending from the react-app one.
It seems like my .eslintrc file is not used at all, even though I placed it in the root folder. In my output terminal I can see the file is loaded from the node_modules folder:

.../node_modules/eslint/lib/api.js

Am I missing something, or should I save the file somewhere else?
Thanks.

A: True, those files are not used by create-react-app.
It is still possible to disable ESLint rules using comments in the JavaScript files:
// eslint-disable-next-line react/style-prop-object
For more information see: http://eslint.org/docs/user-guide/configuring.html#configuring-rules

A: According to the documentation, now it is available by setting the EXTEND_ESLINT env variable. But the feature is experimental right now.
See the Experimental: Extending the ESLint config section.


text:
Q: How can I keep my Kivy ToggleButton state when scrolling using a RecycleView? If I create a list of ToggleButtons and put them in a RecycleView, Toggling one ToggleButton causes out of view ToggleButtons to change state by scrolling in and out of view.  Have I implemented my RecycleView incorrectly?
My RecycleView works as expected if I use Buttons instead of ToggleButtons.
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.recycleview import RecycleView
from kivy.properties import StringProperty,NumericProperty
Builder.load_string("""
<MyLayout>:
    orientation: 'vertical'
    spacing: 10
    RV:
<RV>:
    viewclass: 'RecycleViewRow'
    RecycleBoxLayout:
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'

<RecycleViewRow>:
    orientation: 'horizontal'
    ToggleButton:
        text: root.text
""")

class MyLayout(BoxLayout):
    pass

class RecycleViewRow(BoxLayout):
    text = StringProperty()

class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'text': "Button " + str(x+1)} for x in range(30)]

class MainscreenApp(App):
    def build(self):
        return MyLayout()

if __name__=="__main__":
    MainscreenApp().run()

A: Here is a modification of your code that does the self.data update:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.recycleview import RecycleView
from kivy.properties import StringProperty

Builder.load_string("""
<MyLayout>:
    orientation: 'vertical'
    spacing: 10
    RV:
        id: rv
<RV>:
    viewclass: 'RecycleViewRow'
    RecycleBoxLayout:
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'

<RecycleViewRow>:
    orientation: 'horizontal'
    ToggleButton:
        id: tb
        text: root.text
        state: root.state
        on_release: app.root.ids.rv.adjust_data(root)
""")

class MyLayout(BoxLayout):
    pass

class RecycleViewRow(BoxLayout):
    text = StringProperty()
    state = StringProperty('normal')

class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'text': "Button " + str(x+1), 'state': "normal"} for x in range(30)]

    def adjust_data(self, rvRow):
        for d in self.data:
            if d['text'] == rvRow.text:
                d['state'] = rvRow.ids.tb.state
                rvRow.state = rvRow.ids.tb.state
                break

class MainscreenApp(App):
    def build(self):
        return MyLayout()

if __name__=="__main__":
    MainscreenApp().run()


text:
Q: ResponseEntityExceptionHandler error with new Spring Boot version Although I could use ResponseEntityExceptionHandler with the previous Spring Boot versions as shown on this example, I get the following error for the handleExceptionInternal method when I implement the same exception handler in my new app (Spring Boot version 3.0.2):

Method does not override method from its superclass

So, I can fix the problem by not extending ResponseEntityExceptionHandler, but I am not sure if there is a better way to fix this problem.
Any idea for this problem?

A: The signature of the method is different so now you get that error. Check signature here.
Basically what you need to change is: HttpStatus --> HttpStatusCode
Here is an example of overriding this method:
 @Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex,
    Object body,
    HttpHeaders headers,
    HttpStatusCode statusCode,
    WebRequest request){

    //your code here....

}


text:
Q: Missing required gems when execute cron created by whenever gem in production environment I've ruby on rails application running in production, this apps have STOCK model and it should be updated every 1 minute.
For updating this model i create simple rake task db:populate:stocks, when it contain only two operation :

*

*truncate the STOCK model

*fill STOCK model with latest data fetch from webservice

this rake task should be execute every 1 minute, for this purpose i use whenever gem. Here my schedule.rb :
env :PATH, ENV['PATH']
set :job_template, nil
set :output, {:standard => '/home/admin/shared/log/cron.log', :error => '/home/admin/shared/log/cron-error.log'}

job_type :rake, "cd :path && rake :task RAILS_ENV=:environment --trace :output"

every 1.minute do
  rake "db:populate:stocks"
end

In production i'm using rvm running ruby 1.9.2-p180, rails 3.1.0 and capistrano, here my capistrano task for update cron tab :
after "deploy:update_code" do
 run "cd #{release_path} && whenever --clear-crontab RAILS_ENV=production"
 run "cd #{release_path} && whenever --update-crontab RAILS_ENV=production"
end

And my schedule.rb create cron task like :
# Begin Whenever generated tasks for: RAILS_ENV=production
PATH=/home/admin/.rvm//gems/ruby-1.9.2-p180@admin/bin:/home/admin/.rvm//gems/ruby-1.9.2-p180@global/bin:/home/admin/.rvm//rubies/ruby-1.9.2-p180/bin:/home/admin/.rvm//bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

* * * * * cd /home/admin/releases/20120904103658 && RAILS_ENV=production rake db:populate:stocks --trace >> /home/admin/shared/log/cron.log 2>> /home/admin/shared/log/cron-error.log

THE PROBLEM is the cron task failed to execute the rake task, from cron-error.log :
/home/admin/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems.rb:314:in `bin_path': can't find gem rake ([">= 0"]) with executable rake (Gem::GemNotFoundException)
from /home/admin/.rvm//gems/ruby-1.9.2-p180@admin/bin/rake:19:in `<main>'

What i'm missing here, why the cron job failed to load my env ? Is there any problem with my  schedule.rb ?

A: Make sure your RVM defaults to the correct ruby version where the gems are.
Then try to use bundle exec rake ...
by doing so it will explicitly invoke whatever the gems in the bundle (assuming you are using RVM)

A: I have similar problem and I fix with
rvm cron setup

in server. This add rvm env variables (PATH, GEM_HOME,GEM_PATH...) to my cronjob.
I have to delete the set command
env :PATH, ENV['PATH']

A: modifying PATH is not enough, check rvm help cron - there are few options that will help manage rvm in crontab.


text:
Q: difference if I put the DateAdd function between the SELECT and FROM and FROM and WHERE I created a query that must will get be controlled by a datetimepicker, what I am aiming to do is that I will get the next 7 days of the designated date set by the datetimepicker
I tried it in my query but it seems to have no difference at all or my query codes were just wrong
     select count(PatientID) as id, Patient.FirstName, Patient.LastName,
      Patient.MiddleName, " +"Patient.Nickname, Patient.Age,
       Patient.Birthday, Patient.Sex, Patient.Occupation,
       Patient.CompleteAddress, Patient.MobilePhone, Patient.Phone, " +
       "Patient.PersonTCI, Patient.PContact, Patient.DateofC

       from Patient

        Where DATEADD ('d' , 7 , datetimepicker1 ) and Active = '1' " + "

        Group by Patient.FirstName,
        Patient.LastName, Patient.MiddleName,
        Patient.Nickname, Patient.Age, Patient.Birthday, Patient.Sex,
        Patient.Occupation, Patient.CompleteAddress, " +
        "Patient.MobilePhone, Patient.Phone, Patient.PersonTCI,
          Patient.PContact, Patient.DateofC"

A:     select count(PatientID) as id, Patient.FirstName, Patient.LastName,
          Patient.MiddleName, " +"Patient.Nickname, Patient.Age,
           Patient.Birthday, Patient.Sex, Patient.Occupation,
           Patient.CompleteAddress, Patient.MobilePhone, Patient.Phone, " +
           "Patient.PersonTCI, Patient.PContact, Patient.DateofC
       from Patient

        Where Patient.DateofC>=Patient.DateofC and Patient.DateofC<= datetimepicker1.value.AddDay(7)     and Active = '1' " + "

        Group by Patient.FirstName,
        Patient.LastName, Patient.MiddleName,
        Patient.Nickname, Patient.Age, Patient.Birthday, Patient.Sex,
        Patient.Occupation, Patient.CompleteAddress, " +
        "Patient.MobilePhone, Patient.Phone, Patient.PersonTCI,
          Patient.PContact, Patient.DateofC"

A: In where clause the condition for date comparison is missing.
How about this.
var dateFrompicker = datetimepicker1.AddDay(7);
select count(PatientID) as id, Patient.FirstName, Patient.LastName,
      Patient.MiddleName, " +"Patient.Nickname, Patient.Age,
       Patient.Birthday, Patient.Sex, Patient.Occupation,
       Patient.CompleteAddress, Patient.MobilePhone, Patient.Phone, " +
       "Patient.PersonTCI, Patient.PContact, Patient.DateofC

       from Patient

        Where dateFrompicker >  Patient.DateofC   and Active = '1' " + "

        Group by Patient.FirstName,
        Patient.LastName, Patient.MiddleName,
        Patient.Nickname, Patient.Age, Patient.Birthday, Patient.Sex,
        Patient.Occupation, Patient.CompleteAddress, " +
        "Patient.MobilePhone, Patient.Phone, Patient.PersonTCI,
          Patient.PContact, Patient.DateofC"


text:
Q: Generate list of numbers in specific format I need to generate a list of numbers in a specific format. The format is
mylist = [00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15]
#Numbers between 0-9 are preceded by a zero.

I know how to generate a normal list of numbers using range
>>> for i in range(0,16):
...     print i

So, is there any built-in way in python to generate a list of numbers in the specified format.

A: Python string formatting allows you to specify a precision:

Precision (optional), given as a '.' (dot) followed by the precision.

In this case, you can use it with a value of 2 to get what you want:
>>> ["%.2d" % i for i in range(16)]
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12',
 '13', '14', '15']

You could also use the zfill function:
>>> str(3).zfill(2)
'03'

or the string format function:
>>> "{0:02d}".format(3)
'03'

A: One liner in Python 3.x
[f'{i:>02}' for i in range(1, 16)]

Output:
['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15']

A: in oracle write this query to generate 01 02 03 series
select lpad(rownum+1, decode(length(rownum),1,2, length(rownum)),0) from employees


text:
Q: undefined my variables in react class component My variables are undefined, none of them, why not? What did I define incorrectly?
Do I need to change the whole method or can I fix some things based on what I wrote?
I put here only the relevant component
Thanks!
Addroom.js
import React, { Component } from 'react'

export default class Addroom extends Component {

    constructor(props) {

        super(props)
        this.state = {

            category,
            setCategory,
            roomTypes:[kitchen, bathroom, bedroom],
            yourRoom
        }}

        getSelectedRoomInCategory = () => {
            return roomTypes.filter(
              (yourRoom) => yourRoom.category === category
            );
          };

    render() {
        return (

Select Room Type!

                <select onChange={(e) => setCategory(e.target.value)}>
                <option value={kitchen}>{kitchen}</option>
                <option value={bathroom}>{bathroom}</option>
                <option value={bedroom}>{bedroom}</option>
                </select>

        )
    }
}

A: Looks like:

*

*you're missing some imports there (kitchen, bathroom, bedroom);

*unnecessarily overriding the constructor to set initial state;

*incorrectly referencing setCategory (either deconstruct this.state or reference it fully as: this.state.setCategory);

*not setting state.setCategory to any valid values (should this even belong in state or should it be passed down from props? if so, don't copy to state);

*not setting state.category to any valid value (as above)

*possibly missing a value binding on the select;

A: Ciao, there are some errors in your code. Lets try to rewrite component like this:
import React, { Component } from 'react'

export default class Addroom extends Component {

constructor(props) {

    super(props)
    this.state = {
        roomTypes:["kitchen", "bathroom", "bedroom"],
        roomSelected: ''
    }}

 setCategory = (roomSel) => {
     this.setState({roomSelected : roomSel});
 };

render() {
    return (

Select Room Type!

            <select onChange={(e) => setCategory(e.target.value)}>
               this.state.roomTypes.map(type => {
                  <option value={type}>{type}</option>
               })

            </select>

    )
}
}

And now you have the room selected in this.state.roomSelected.

A: Now its works perfect, all the relevant variables are imported and identified.
I used a slightly different method, using the one written below with a little bit of changes.
I made a connection between the written function and the call of the function in return and correctly defined the variables in state so now all the relevant variables are imported and identified and everything works. thank you all!

import React, { Component } from 'react'

export default class Addroom extends Component {

    constructor(props) {

        super(props)
        this.state = {

            roomTypes:["kitchen", "bathroom", "bedroom"],
            roomSelected: '',
            roomSel:''

        }}

    setCategory = (roomSel) => {
        this.setState({roomSelected : roomSel});
    };

    render() {
        return (

Select Room Type

            <select onChange={(e) => this.setCategory(e.target.value)}>
               {this.state.roomTypes.map((type) =>
                  <option value={type}>{type}</option>
               )}

            </select>

        )
    }

}


text:
Q: find: '/e': No such file or directory I all of the sudden started getting this message at startup in my command line.

find: '/e': No such file or directory

I have no idea what '/e' is and what's causing this to happen. Does anyone know what this is? If not, is there a way to get more information on this message I'm getting? I'm new to Zsh, Cygwin, and Oh My Zsh so I don't really know what to do, or what's causing it.
I would really appreciate anyone's help. This is driving me crazy. I seem to still be able to do everything, but I get this every time I start 'babun'.
Oh by the way, I'm using babun, which is a convenient way of getting Cygwin, Zsh, Oh My Zsh, Git, etc. Here's the link of that. I doubt babun itself has anything to do with this though.
http://babun.github.io/

A: I finally figured it out! So '/e' is my flash drive that I had disconnected. All I had to do was delete the 'e' file in the cygwin directory and it was resolved. There are also files named 'c' and 'd' for other drives.


text:
Q: Responsive margins and padding I would like to make certain elements of my page have more fluid transitions as they size down. If you look here:
http://abezieleniec.com/SIDWeb/
You can see that when you size down to tablet and phone size the first blue bar snaps to different positions to meet with the main logo. This was obviously done with media queries but I'm wondering if there is a way to make it more fluid with percentages? I'm assuming this would require some JS...
Any ideas are welcome!
Thanks

A: It's not too hard a process as it happens! It's something I had to use for the website here: http://flourishworld.co.uk/
The key is to use :before with "margin-top: xx%":
.element:before  {
  margin-top: 50%;
  position: relative;
  content: "";
  display: block;
}

From looking at your site...it may be easier to just present some altered code. First I changed your markup (this may not work for you)

Using the code idea above:
#home:before {
  margin-top: 55%;
  position: relative;
  content: "";
  display: block;
}

But for this to work you need some amended CSS code for other elements...
.jumbotrontop {
  font-size: 21px;
  height: 100%;
  line-height: 2.1428571435;
  color: inherit;
  width: 100%;
  background-size: cover;
  z-index: 1;
}

.biglogo {
  width: 80%;
  display: block;
  margin-left: 10%;
  margin-right: 10%;
  margin-top: 10%;
  margin-bottom: 130px;
  opacity: 1;
  position: absolute;
  z-index: 100;
  top: 0;
  position: relative;
  display: table;
}

.jumbotrontop img {
  width: 100%;
  height: auto;
  margin: auto;
  max-width: 740px;
  display: block;
}

#home:after {
  background-color: #eeeeee;
  background-image: url(../images/background1.jpg);
  display: block;
  position: fixed;
  top: 0;
  left: 0;
  content: "";
  bottom: 0;
  right: 0;
  z-index: 1;
  background-size: cover;
}

What this does is it takes your top element and takes it's height away, it's contents are positioned absolutely so it doesn't take up space. The :before element then adds a responsive height that will shrink as the width of the page shrinks. In doing so we had to change the logo markup around so that it stayed in a central location and continued to shrink as the window did.
Hope this helps! No JS, all CSS.


text:
Q: Vacation/Holiday Request Our company has just got Office 365 and SharePoint online.  I would like to create an online Vacation/Holiday Request form but don't know where start.
I haven't used SharePoint before so can this be created using the online version? or do I need any extra tools?
I would like the user to be able to, put their details in to a form (Name, Start Date, End Date, No. of Days).
The details and or a notification is sent to the users line manager for approval.
If approved the holiday is then put on to a calendar.
I would be grateful if you could point me in the right direction.
Thanks in advance,
Dave

A: For this I would use a custom list, it works like a table in a database.
You can create the structure you want and after this create a form with InfoPath for input the data.
With a workflow you can add this data automatically to a calendar, or do whatever you want with this raw data. You can follow this tutorial for creating custom lists:

*

*SharePoint lists IV: Create a custom list
And for add this data to a calendar you can check this question here: How to update calendar item created by an other list?

A: I would use a calendar for this. A calendar is a type of list you can add out of the box. Fields like start date etc. Are already present and you can add extra columns to make it a real vacation form.
For the automatic email you can create a workflow via SharePoint Designer that sends the mail when a new item is created in The list.
Or you can attach The out of the box approval workflow.

A: We have a created Vacation request in online same as above business case. The steps we followed as follows

*

*Created a SharePoint list to store request information.

*We built a custom form to apply additional details like getting manager and other and some additional calculation for a type of leave.

*Created the SPD workflow on item added. It will send a notification to a manager and wait until status changes. If status approved, sends a notification and add a record to the calendar or sends a rejected notification.

I will help you further if you stuck somewhere need additional clarification.
Thanks,
Venkat Konjeti

A: There are dozens of ways to do this in SharePoint so you are going to continually get different answers from everyone you ask. I would encourage you to build some lists on the site to learn how they work to capture information. There are all sorts of columns you can add to lists to customize it to meet your needs. If you are going to build any workflows you will need to download SharePoint designer 2013 to build them to send if you have custom logic that needs to send emails and update items etc.
My advise is to keep things as simple as possible. There is a built in approval setting found in any given list that lines up with an approval permission level but it may or may-not work for your situation. Do some tests to see if it works for you, if not go about it another way such as making columns that filter views based on status etc.
Info on the built in approval: https://support.office.com/en-us/article/Require-approval-of-items-in-a-site-list-or-library-CD0761C4-8C3F-4EA2-9435-13C28AA23D08
Info on lists: https://support.office.com/en-us/article/Data-and-lists-in-SharePoint-647a1fba-e144-4755-85e8-1f3cc0eaf2a8


text:
Q: Custom validation Error Messages I am working with dataannotations and I have applied a range validator but the error message in the validator is not working. It is defaulted to "The Code1 field is required" ..
View Page::

  @Html.DropDownListFor(m => m.Code1, Model.Codes, "Select", new { })
                      @Html.ValidationMessageFor(mbox => mbox.Code1)

model
  [Range(1, 250, ErrorMessage = "code field is required")]
        public int Code1 { get; set; }

I do not know why my defined error message is not showing up.
I have also tried in changing the message in view page:
View Page::

  @Html.DropDownListFor(m => m.Code1, Model.Codes1, "Select","Code is required", new { })

Now, the message defined here is working but it is giving me a weird behaviour.
It shows the above given message in black and white and just changes to red when the
Validation fires and when I change a value in dropdown it again becomes black and white.
enter code here

A: Use the required validator instead of the range validator for compulsory entry.
    [Required(ErrorMessage = "Code1 is required")]
    [Range(1, 250, ErrorMessage = "Value must be between 1 and 250")]
    public int Code1 { get; set; }


text:
Q: one signal additional data in ionic 2/3 I'm trying to work with one signal plugin in my ionic 2 app
I've installed Onesignal and it was working fine,but i don't know how to work with handleNotificationOpened function
there is no document at all (nothing was found)
this is my code:
this.oneSignal.handleNotificationReceived().subscribe((msg) => {
       // o something when notification is received
      });

but I have no idea how to use msg for getting data.
any help? link?
tank you

A: Here is how i redirect user to related page when app launch from notification.
app.component.ts
this.oneSignal.handleNotificationOpened().subscribe((data) => {
      let payload = data; // getting id and action in additionalData.
      this.redirectToPage(payload);
 });

redirectToPage(data) {
    let type
    try {
      type = data.notification.payload.additionalData.type;
    } catch (e) {
      console.warn(e);
    }
    switch (type) {
      case 'Followers': {
        this.navController.push(UserProfilePage, { userId: data.notification.payload.additionalData.uid });
        break;
      } case 'comment': {
        this.navController.push(CommentsPage, { id: data.notification.payload.additionalData.pid })
        break;
      }
    }
  }

A: A better solution would be to reset the current nav stack and recreate it. Why?
Lets see this scenario:
TodosPage (rootPage) -> TodoPage (push) -> CommentsPage (push)
If you go directly to CommentsPage the "go back" button won't work as expected (its gone or redirect you to... who knows where :D).
So this is my proposal:
this.oneSignal.handleNotificationOpened().subscribe((data) => {
    // Service to create new navigation stack
    this.navigationService.createNav(data);
  });

navigation.service.ts
    import {Injectable} from '@angular/core';
    import {App} from 'ionic-angular';
    import {TodosPage} from '../pages/todos/todos';
    import {TodoPage} from '../pages/todo/todo';
    import {CommentsPage} from '../pages/comments/comments';

    @Injectable()
    export class NavigationService {

      pagesToPush: Array<any>;

      constructor(public app: App) {
      }

      // Function to create nav stack
      createNav(data: any) {

        this.pagesToPush = [];

        // Customize for different push notifications
        // Setting up navigation for new comments on TodoPage
        if (data.notification.payload.additionalData.type === 'NEW_TODO_COMMENT') {
          this.pagesToPush.push({
            page: TodoPage,
            params: {
             todoId: data.notification.payload.additionalData.todoId
            }
          });
          this.pagesToPush.push({
            page: CommentsPage,
            params: {
              todoId: data.notification.payload.additionalData.todoId,
            }
          });
        }

        // We need to reset current stack
        this.app.getRootNav().setRoot(TodosPage).then(() => {
          // Inserts an array of components into the nav stack at the specified index
          this.app.getRootNav().insertPages(this.app.getRootNav().length(), this.pagesToPush);
        });
      }

    }

I hope it helps :)


text:
Q: file system for fast mmap access for read only files over LAN I have some large files(several dozen GBs) which are accessed via mmap,
I would like to place them on a single server shared by a few (~4) clients which will mount the folder and mmap them. With the server having enough RAM to hold everything in memory but the clients not necessarly capeable of keeping everything in buffer cache.
Files never change. Network is 10Gbit Etherenet.
What will give me best performance. Obviously I can do NFS or such, but I fear that is not optimized for my use case where I want fast access. Preferably outperforming local hard drives for random access.
I would much prefer not changing client code, so mmap is a must for whatever FS used.


text:
Q: Compare values allowing for a specific margin of error Are there any written functions in R that allow for a margin of error when comparing numbers or vectors? x==y would evaluate to TRUE if the two values were within a specified tolerable error margin.
Example if the target value is 77 and my allowable margin of error was 5%, asking the question does x==77? would evaluate to TRUE if x is within a 5% margin of error around 77, i.e. any values of x between 73.15 and 80.85 would evaluate to TRUE.
I can right a function to do the "==" comparison but couldn't come up with a solution that builds an "acceptance" range around each of the target values so that if my allowable margin of error was 5%, any of the dta elements that falls within +/- 5% of tgt values would evaluate to TRUE.
tgt <- c(45,77,92)
dta <- c(33,41,44,60,68,71,77,78,87,95)
sapply(tgt, function(i) i==dta)

This compares each of tgt to each of dta. The only comparison that returns TRUE is when 77 is compared to 77. I would have to build a range around each of tgt elements then compare each of dta elements to that range returning true whenever any of dta elements falls inside any of the ranges created. As I started building the ranges I got so confused.  The result I am looking for would evaluate to true when 44 is compared to 45 as it's short by less than 5%, similarly 78 is close enough to 77 to evaluate to true as well as 95 to 92.

A: neighbour <- function(x, y, tol=0.1){
  sapply(x, function(.x) {.tol <- tol * pmax(.x, y) ; abs(.x - y) <= .tol})
}

tgt <- c(45,77,92)
dta <- c(33,41,44,60,68,71,77,78,87,95)

neighbour(x=tgt, y=dta)


text:
Q: Android dynamically create String Array from XML string resources, without XML string array Ok, so this question is a bit weird, and kinda rubs me the wrong to even ask, but since I probably don't have a choice I want to see what you guys think. I'm still a novice at Java and Android.
The case is as follows: We are trying to automate the building of our strings.xml for localisation. A parser has been made to convert a csv-file to xml. For regular strings it's not a real problem, that works fine. But the parser that was built, doesn't take string arrays into account and there is little chance that someone will modify it.
Is there an "easy" way to work with the strings and create an string array programmatically based on parts the name attributes?
If not, then I would have to hard code the arrays and that leaves the creator (client) of the language files unable to add items to something that should be a dynamic list.
I know modifying the strings.xml manually might be an option, but because our management wants to automate stuff like that, it's not much of a choice I have.
Probably I will hard code the stuff and say they can't dynamically fill the lists, but still (also for my personal education) I wanna know what you guys think.
Thanks for your opinions or solutions. :)
Cheers!

A: You can use (& really really really should anyways) references in string arrays. Assuming this is your generated res/values/strings.xml in Swedish:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="string1">Hej, detta är på svenska</string>
    <string name="string2">Denna strängen också</string>
</resources>

You can put your string-array in, for instance, res/values/arrays.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="somearrayname">
        <item>@string/string1</item>
        <item>@string/string1</item>
    </string-array>
</resources>

A: So you will get strings.xml as below
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="string1">1st string</string>
    <string name="string2">2nd string</string>
                 ........
    <string name="stringN">Nth string</string>
</resources>

I suggest a simple modification to strings.xml, which is add a string with name count at top of all strings with value equal to total number of strings and add another string with name prefix below the count, then it looks like as below.
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="count">4</string>
    <string name="prefix">string</string>
    <string name="string1">1st string</string>
    <string name="string2">2nd string</string>
    <string name="string3">3rd string</string>
    <string name="string4">4th string</string>
</resources>

So now, in your java file you can access them like below
int count = Integer.parseInt(getString(R.string.count));
        String prefix = getString(R.string.prefix);
        String[] strings = new String[count];
        for (int i = 0; i < count; i++) {
            strings[i] = getString(getResources().getIdentifier(prefix+(i+1), "string", getPackageName()));
        }

I hope it may help you.


text:
Q: Manually building a tile server I use this instruction http://switch2osm.org/serving-tiles/manually-building-a-tile-server-12-04/
I have the problem on the step "Starting your tileserver"
sudo mkdir /var/run/renderd
sudo chown username /var/run/renderd
renderd -f -c /usr/local/etc/renderd.conf

The problem:
renderd[4620]: An error occurred while loading the map layer 'default': Could not create datasource. No plugin found for type 'shape' (searched in: /usr/lib/mapnik/input) (encountered during parsing of layer 'world' in map '/home/oleg/src/mapnik-style/osm.xml')
renderd[4620]: An error occurred while loading the map layer 'default': Could not create datasource. No plugin found for type 'shape' (searched in: /usr/lib/mapnik/input) (encountered during parsing of layer 'world' in map '/home/oleg/src/mapnik-style/osm.xml')
renderd[4620]: An error occurred while loading the map layer 'default': Could not create datasource. No plugin found for type 'shape' (searched in: /usr/lib/mapnik/input) (encountered during parsing of layer 'world' in map '/home/oleg/src/mapnik-style/osm.xml')
renderd[4620]: An error occurred while loading the map layer 'default': Could not create datasource. No plugin found for type 'shape' (searched in: /usr/lib/mapnik/input) (encountered during parsing of layer 'world' in map '/home/oleg/src/mapnik-style/osm.xml')
renderd[4620]: DEBUG: Got incoming connection, fd 8, number 1
renderd[4620]: DEBUG: Got command RenderPrio fd(8) xml(default), z(0), x(0), y(0)
renderd[4620]: Received request for map layer 'default' which failed to load
renderd[4620]: DEBUG: Connection 0, fd 8 closed, now 0 left
renderd[4620]: DEBUG: Got incoming connection, fd 8, number 1
renderd[4620]: DEBUG: Got command RenderPrio fd(8) xml(default), z(0), x(0), y(0)
renderd[4620]: Received request for map layer 'default' which failed to load
renderd[4620]: DEBUG: Connection 0, fd 8 closed, now 0 left
renderd[4620]: DEBUG: Got incoming connection, fd 8, number 1
renderd[4620]: DEBUG: Got command RenderPrio fd(8) xml(default), z(0), x(0), y(0)
renderd[4620]: Received request for map layer 'default' which failed to load
renderd[4620]: DEBUG: Connection 0, fd 8 closed, now 0 left

Update 1: One of the problem was the file "renderd.conf". here is file without error.
[renderd]
socketname=/var/run/renderd/renderd.sock
num_threads=2
tile_dir=/var/lib/mod_tile
stats_file=/var/run/renderd/renderd.stats

[mapnik]
plugins_dir=/usr/local/lib/mapnik/input
font_dir=/usr/share/fonts/truetype/ttf-dejavu
font_dir_recurse=1

[default]
URI=/osm_tiles/
TILEDIR=/var/lib/mod_tile
XML=/home/map/src/mapnik-style/osm.xml
HOST=localhost
TILESIZE=256
CORS=*

But I have another errors:
renderd[8967]: An error occurred while loading the map layer 'default': Shape Plugin: shapefile '/usr/local/share/world)boundaries/shoreline_300.shp' does not exist (encountered during parsing of layer 'world' in map '/home/oleg/src/mapnik-style/osm.xml')
renderd[8967]: An error occurred while loading the map layer 'default': Shape Plugin: shapefile '/usr/local/share/world)boundaries/shoreline_300.shp' does not exist (encountered during parsing of layer 'world' in map '/home/oleg/src/mapnik-style/osm.xml')

Update: The question is solved

A: The problem was almost certainly that you had a stray bracket:
renderd[8967]: An error occurred while loading the map layer 'default': Shape Plugin: shapefile '/usr/local/share/world)boundaries/shoreline_300.shp' does not exist (encountered during parsing of layer 'world' in map '/home/oleg/src/mapnik-style/osm.xml')

Note: world ) boundaries
Can you close this question off?


text:
Q: WordPress Gutenberg Block State Issue I've written a basic format block that collects text and an optional link value to create a new inline footnote. This is represented by an img element in the block's rendered output:

I'm running into an issue where multiple footnote format blocks within a single paragraph end up sharing state. Whichever footnote is selected first seems to set a state that is then shared by all other footnotes within the same paragraph block. For instance, in the following example, both footnotes will have a text of "Foo bar baz" if the first footnote is selected first, and "" (empty string) if the second footnote is selected first:

Trust fund jean shorts viral, deep v beard craft beer lomo yr gastropub brooklyn kale chips wayfarers dreamcatcher bushwick. Next level 8-bit cornhole salvia cliche health goth bicycle rights stumptown fanny pack williamsburg. Thundercats brooklyn swag drinking vinegar tacos dreamcatcher. Cloud bread activated charcoal godard vegan knausgaard, portland twee. YOLO ennui air plant truffaut.

Hoping someone has some insight into this issue.
    registerFormatType,
    toggleFormat,
    insertObject,
  } = wp.richText;
  const {
    RichTextToolbarButton,
    RichTextShortcut,
  } = window.wp.editor;
  const {
    TextControl,
    TextareaControl,
    Popover,
    Button,
  } = wp.components;
  const { Component, Fragment } = wp.element;
  const { __ } = wp.i18n;

  function getRange() {
    const selection = window.getSelection();
    return selection.rangeCount ? selection.getRangeAt( 0 ) : null;
  }
  const stopKeyPropagation = ( event ) => event.stopPropagation();

  const formatHandle = 'lucida/footnote-format';

  class FootnoteEditor extends Component {
    constructor() {
      super(...arguments);
      this.state = {
      };
    }

    static getDerivedStateFromProps( props, state ) {
        const {
            activeObjectAttributes,
        } = props;

        // if ( activeObjectAttributes.footnoteText === state.prevFootnoteText ) {
        //  return null;
        // }
      //
        // if ( ! activeObjectAttributes.footnoteText ) {
        //  return {
        //      footnoteText: undefined,
        //      prevFootnoteText: activeObjectAttributes.footnoteText,
        //  };
        // }

      const newState = {
            footnoteText: activeObjectAttributes.footnoteText,
            // prevFootnoteText: activeObjectAttributes.footnoteText,
            footnoteLink: activeObjectAttributes.footnoteLink,
            // prevFootnoteLink: activeObjectAttributes.footnoteLink,
        };
        return newState;
    }

    onKeyDown( event ) {
        if (
            [ LEFT, DOWN, RIGHT, UP, BACKSPACE, ENTER ].indexOf(
                event.keyCode
            ) > -1
        ) {
            // Stop the key event from propagating up to ObserveTyping.startTypingInTextField.
            event.stopPropagation();
        }
    }

    onChange(newValues) {
        this.setState( { ...newValues } );
    }
    render() {
      const {
        onChange,
        value,
        // isActive,
            isObjectActive,
            activeObjectAttributes,
      } = this.props;
      const {
        footnoteText,
        footnoteLink,
      } = this.state;

      // console.log(`state:`, this.state)

      return (
        <Fragment>
          <RichTextToolbarButton
            icon='book-alt'
            title='Footnote'
            onClick={() => {
              // console.log(`inserting element 2`);
              onChange(
                insertObject(
                  value,
                  {
                                type: formatHandle,
                                attributes: {
                                    'data-widget': `footnote`,
                      src: '/wp-content/themes/mbm-custom-theme/bookmark.svg',
                                },
                            }
                )
              );
            }}
            isActive={isObjectActive}
          />
          { isObjectActive && (
                    <Popover
                        position="bottom center"
                        focusOnMount={ false }
                        anchorRef={ getRange() }
                    >
              <form
                onKeyPress={ stopKeyPropagation }

                // onKeyDown={ this.onKeyDown }

                onSubmit={ ( event ) => {
                  event.preventDefault();

                  const newReplacements = value.replacements.slice();

                  const newAttributes = {
                    ...activeObjectAttributes,
                    src: '/wp-content/themes/mbm-custom-theme/bookmark.svg',
                    'data-widget': `footnote`,
                    'data-footnote-text': footnoteText,
                    'data-footnote-link': footnoteLink,
                  };

                  // console.log(`newAttributes:`, newAttributes)

                  newReplacements[ value.start ] = {
                    type: formatHandle,
                    attributes: newAttributes,
                  };

                  onChange( {
                    ...value,
                    replacements: newReplacements,
                  } );
                } }
              >

                  <TextareaControl
                    label={ __( 'Footnote description' ) }
                    value={ footnoteText }
                    onChange={(value) => this.onChange({footnoteText: value}) }
                  />
                  <TextControl
                    label={ __( 'Source link (optional)' ) }
                    value={ footnoteLink }
                    onChange={(value) => this.onChange({footnoteLink: value}) }
                    style={{marginBottom: '0', }}
                  />
                  <Button
                    isPrimary
                    isSmall
                    icon='yes'
                    label={ __( 'Apply' ) }
                    type="submit"
                  >
                    { __( 'Apply' ) }
                  </Button>

              </form>
                    </Popover>
                ) }
        </Fragment>
      )
    }
  }

  registerFormatType(
    formatHandle,
    {
      title: 'Footnote',
      object: true,
      tagName: 'img',
      className: 'footnote-placeholder',
        attributes: {
            footnoteText: 'data-footnote-text',
            footnoteLink: 'data-footnote-link',
        },
      edit: FootnoteEditor,
    }
  );```


text:
Q: Regex Pattern to Remove Custom Markers I am trying to figure out a regex that would strip a set of custom markers from a character string. For example, if I have the string,
s = "{\n \"graph\": \"#! graph1 !#\",\n\"element\": \"#!
    document.getElementById('x_axis1') !#\",\n\"orientation\": \"bottom\" \n}"

I want the output to be
"{\n \"graph\":  graph1 ,\n\"element\":  document.getElementById('x_axis1')
 ,\n\"orientation\": \"bottom\" \n}"

I tried the following code
gsub('\"#!([^!].*)!#\"', "\\1", s)

But it only removes the first set of markers. I would really appreciate if anyone can point me to a regex that would strip all the custom markers.

A: Try this:
gsub("#!(.*?)!#", "\\1", s)

As long as you don't accept nested "blocks" of #!...!# (e.g., #! hello #! world !# goodbye !# as one occurrence) and you don't need to detect "unmatched" blocks, that should do everything you need.
If you do need nested matching, you'll need to build a proper parser instead of using regular expressions. (This isn't hard; it's merely worth noting that you can't use regular expressions to detect arbitrarily nested blocks.)

A: It's your regex. The .* in [^!].* is matching everything from graph.1 !#.... onwards (including the newlines).
Try (changed [^!].* to [^!]*):
gsub('\"#!([^!]*)!#\"', "\\1", s)
#> cat(gsub('\"#!([^!]*)!#\"', "\\1", s))
#{
#   "graph":  graph.1 ,
#   "element":  document.getElementById('x_axis1') ,
#   "orientation": "bottom"
#}>

A: You could use two gsubs:
gsub('!#"', "", gsub('"#!', "", s))


text:
Q: Java JAR unable to load class on Class-Path? I have a jar file that uses a class within a second jar file. However, when I run the first jar file, I get an exception that the class can not be found. I can't find any documentation on how to troubleshoot the issue.
I have two .jar files, MyApp.jar and sqljdbc42.jar. Both of these .jar files are in the same directory.
MyApp.jar has the following code in the main:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

The manifest for MyApp.jar has the following:
Manifest-Version: 1.0
Main-Class: com.mycompany.myapp.MyApp
Class-Path: sqljdbc42.jar
<blank line>

The class com.microsoft.sqlserver.jdbc.SQLServerDriver is in the jar sqljdbc42.jar.
When MyApp.jar is executed, the following exception occurs:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
  at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
  at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
  at java.lang.Class.forName0(Native Method)
  at java.lang.Class.forName(Class.java:264)

Using Java 8, built in IntelliJ, verified the manifest contents by opening the jar in 7Zip.
Any advice on how I can get this (seemingly simple, basic piece of Java JAR concept) working would be greatly appreciated.

A: There are three ways to solve your issue:
1) You can generate your jar using IDE "Eclipse Neon".

*

*create folder in your project "lib" and put sqljdbc42.jar into it;

*add sqljdbc42.jar to the classPath: Properties -> Java Build Path -> Libraries -> Add JARs... (select your jar from "lib");

*Right click on your project -> Export... -> Runnable JAR file -> Launch configuration (choose you main class) and check Library handing: Extract required libraries into generated JAR.
Eclipse will repack all reference libraries automatically without any security issues and ClassNotFound exceptions.
2) We should convert project into Maven project. And then use special plugins for generating JARs and creating dependencies of custom libs.
3) We can even generate it using Intellij Idea. But we should create Artifact of application with configuration where all signed libraries will be outside of your generated jar.
I think that the first variant is the easiest. Check it. If it does not help I will describe other methods with more details.


text:
Q: Can I get access to the series legend text from the tooltip expression? When setting a tooltip expression for the chart series, is it possible to access the same series' legend text? What would be the syntax? I just want to aviod having to type the same literal in two places. I.e. instead of
=Fields!Metric.Value +  ", Literal : " + FormatNumber(Fields!Data.Value, 2)

I would like to use whatever syntax for the Series/Legend Text:
=Fields!Metric.Value + Series.LegendText + FormatNumber(Fields!Data.Value, 2)


text:
Q: Visual studio developer edition I am learning MVC myself. I downloaded visual studio community edition 2013 but it is expired after 30 days.
Can anyone suggest me any Visual studio developer edition without trial period.
Kindly suggest me any websites/url to learn MVC quickly.

A: Now you can download Visual Studio 2015 Community, and it's free for individuals. Check this page for more information and download.
I recommend you the official page. You can follow the tutorials and have a good learning about ASP.NET and MVC.
I also recommend Pluralsight for video tutorials. It's paid but you can get a 10 days trial.
Hope it can help you!