text:
Q: Horizontal stacked bar plot and add labels to each section I am trying to replicate the following image in matplotlib and it seems barh is my only option. Though it appears that you can't stack barh graphs so I don't know what to do

If you know of a better python library to draw this kind of thing, please let me know.
This is all I could come up with as a start:
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

people = ('A','B','C','D','E','F','G','H')
y_pos = np.arange(len(people))
bottomdata = 3 + 10 * np.random.rand(len(people))
topdata = 3 + 10 * np.random.rand(len(people))
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)
ax.barh(y_pos, bottomdata,color='r',align='center')
ax.barh(y_pos, topdata,color='g',align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel('Distance')

plt.show()

I would then have to add labels individually using ax.text which would be tedious. Ideally I would like to just specify the width of the part to be inserted then it updates the center of that section with a string of my choosing. The labels on the outside (e.g. 3800) I can add myself later, it is mainly the labeling over the bar section itself and creating this stacked method in a nice way I'm having problems with. Can you even specify a 'distance' i.e. span of color in any way?

A: Edit 2: for more heterogeneous data. (I've left the above method since I find it more usual to work with the same number of records per series)
Answering the two parts of the question:
a) barh returns a container of handles to all the patches that it drew. You can use the coordinates of the patches to aid the text positions.
b) Following these two answers to the question that I noted before (see Horizontal stacked bar chart in Matplotlib), you can stack bar graphs horizontally by setting the 'left' input.
and additionally c) handling data that is less uniform in shape.
Below is one way you could handle data that is less uniform in shape is simply to process each segment independently.
import numpy as np
import matplotlib.pyplot as plt

# some labels for each row
people = ('A','B','C','D','E','F','G','H')
r = len(people)

# how many data points overall (average of 3 per person)
n = r * 3

# which person does each segment belong to?
rows = np.random.randint(0, r, (n,))
# how wide is the segment?
widths = np.random.randint(3,12, n,)
# what label to put on the segment (xrange in py2.7, range for py3)
labels = range(n)
colors ='rgbwmc'

patch_handles = []

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)

left = np.zeros(r,)
row_counts = np.zeros(r,)

for (r, w, l) in zip(rows, widths, labels):
    print r, w, l
    patch_handles.append(ax.barh(r, w, align='center', left=left[r],
        color=colors[int(row_counts[r]) % len(colors)]))
    left[r] += w
    row_counts[r] += 1
    # we know there is only one patch but could enumerate if expanded
    patch = patch_handles[-1][0]
    bl = patch.get_xy()
    x = 0.5*patch.get_width() + bl[0]
    y = 0.5*patch.get_height() + bl[1]
    ax.text(x, y, "%d%%" % (l), ha='center',va='center')

y_pos = np.arange(8)
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel('Distance')

plt.show()

Which produces a graph like this , with a different number of segments present in each series.
Note that this is not particularly efficient since each segment used an individual call to ax.barh.  There may be more efficient methods (e.g. by padding a matrix with zero-width segments or nan values) but this likely to be problem-specific and is a distinct question.

Edit: updated to answer both parts of the question.
import numpy as np
import matplotlib.pyplot as plt

people = ('A','B','C','D','E','F','G','H')
segments = 4

# generate some multi-dimensional data & arbitrary labels
data = 3 + 10* np.random.rand(segments, len(people))
percentages = (np.random.randint(5,20, (len(people), segments)))
y_pos = np.arange(len(people))

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)

colors ='rgbwmc'
patch_handles = []
left = np.zeros(len(people)) # left alignment of data starts at zero
for i, d in enumerate(data):
    patch_handles.append(ax.barh(y_pos, d,
      color=colors[i%len(colors)], align='center',
      left=left))
    # accumulate the left-hand offsets
    left += d

# go through all of the bar segments and annotate
for j in range(len(patch_handles)):
    for i, patch in enumerate(patch_handles[j].get_children()):
        bl = patch.get_xy()
        x = 0.5*patch.get_width() + bl[0]
        y = 0.5*patch.get_height() + bl[1]
        ax.text(x,y, "%d%%" % (percentages[i,j]), ha='center')

ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel('Distance')

plt.show()

You can achieve a result along these lines (note: the percentages I used have nothing to do with the bar widths, as the relationship in the example seems unclear):

See Horizontal stacked bar chart in Matplotlib for some ideas on stacking horizontal bar plots.

A: Imports and Test DataFrame

*

*Tested in python 3.10, pandas 1.4.2, matplotlib 3.5.1, seaborn 0.11.2

*For vertical stacked bars see Stacked Bar Chart with Centered Labels
import pandas as pd
import numpy as np

# create sample data as shown in the OP
np.random.seed(365)
people = ('A','B','C','D','E','F','G','H')
bottomdata = 3 + 10 * np.random.rand(len(people))
topdata = 3 + 10 * np.random.rand(len(people))

# create the dataframe
df = pd.DataFrame({'Female': bottomdata, 'Male': topdata}, index=people)

# display(df)
   Female   Male
A   12.41   7.42
B    9.42   4.10
C    9.85   7.38
D    8.89  10.53
E    8.44   5.92
F    6.68  11.86
G   10.67  12.97
H    6.05   7.87

Updated with matplotlib v3.4.2

*

*Use matplotlib.pyplot.bar_label

*See How to add value labels on a bar chart for additional details and examples with .bar_label.

*labels = [f'{v.get_width():.2f}%' if v.get_width() > 0 else '' for v in c ] for python < 3.8, without the assignment expression (:=).

Plotted using pandas.DataFrame.plot with kind='barh'
ax = df.plot(kind='barh', stacked=True, figsize=(8, 6))

for c in ax.containers:

    # customize the label to account for cases when there might not be a bar section
    labels = [f'{w:.2f}%' if (w := v.get_width()) > 0 else '' for v in c ]

    # set the bar label
    ax.bar_label(c, labels=labels, label_type='center')

    # uncomment and use the next line if there are no nan or 0 length sections; just use fmt to add a % (the previous two lines of code are not needed, in this case)
#     ax.bar_label(c, fmt='%.2f%%', label_type='center')

# move the legend
ax.legend(bbox_to_anchor=(1.025, 1), loc='upper left', borderaxespad=0.)

# add labels
ax.set_ylabel("People", fontsize=18)
ax.set_xlabel("Percent", fontsize=18)
plt.show()

Using seaborn

*

*sns.barplot does not have an option for stacked bar plots, however, sns.histplot and sns.displot can be used to create horizontal stacked bars.

*seaborn typically requires the dataframe to be in a long, instead of wide, format, so use pandas.DataFrame.melt to reshape the dataframe.

Reshape dataframe
# convert the dataframe to a long form
df = df.reset_index()
df = df.rename(columns={'index': 'People'})
dfm = df.melt(id_vars='People', var_name='Gender', value_name='Percent')

# display(dfm)
   People  Gender    Percent
0       A  Female  12.414557
1       B  Female   9.416027
2       C  Female   9.846105
3       D  Female   8.885621
4       E  Female   8.438872
5       F  Female   6.680709
6       G  Female  10.666258
7       H  Female   6.050124
8       A    Male   7.420860
9       B    Male   4.104433
10      C    Male   7.383738
11      D    Male  10.526158
12      E    Male   5.916262
13      F    Male  11.857227
14      G    Male  12.966913
15      H    Male   7.865684

sns.histplot: axes-level plot
fig, axe = plt.subplots(figsize=(8, 6))
sns.histplot(data=dfm, y='People', hue='Gender', discrete=True, weights='Percent', multiple='stack', ax=axe)

# iterate through each set of containers
for c in axe.containers:
    # add bar annotations
    axe.bar_label(c, fmt='%.2f%%', label_type='center')

axe.set_xlabel('Percent')
plt.show()

sns.displot: figure-level plot
g = sns.displot(data=dfm, y='People', hue='Gender', discrete=True, weights='Percent', multiple='stack', height=6)

# iterate through each facet / supbplot
for axe in g.axes.flat:
    # iteate through each set of containers
    for c in axe.containers:
        # add the bar annotations
        axe.bar_label(c, fmt='%.2f%%', label_type='center')
    axe.set_xlabel('Percent')

plt.show()

Original Answer - before matplotlib v3.4.2

*

*The easiest way to plot a horizontal or vertical stacked bar, is to load the data into a pandas.DataFrame

*

*This will plot, and annotate correctly, even when all categories ('People'), don't have all segments (e.g. some value is 0 or NaN)

*Once the data is in the dataframe:

*

*It's easier to manipulate and analyze

*It can be plotted with the matplotlib engine, using:

*

*pandas.DataFrame.plot.barh

*

*label_text = f'{width}' for annotations

*pandas.DataFrame.plot.bar

*

*label_text = f'{height}' for annotations

*SO: Vertical Stacked Bar Chart with Centered Labels

*These methods return a matplotlib.axes.Axes or a numpy.ndarray of them.

*Using the .patches method unpacks a list of matplotlib.patches.Rectangle objects, one for each of the sections of the stacked bar.

*

*Each .Rectangle has methods for extracting the various values that define the rectangle.

*Each .Rectangle is in order from left the right, and bottom to top, so all the .Rectangle objects, for each level, appear in order, when iterating through .patches.

*The labels are made using an f-string, label_text = f'{width:.2f}%', so any additional text can be added as needed.

Plot and Annotate

*

*Plotting the bar, is 1 line, the remainder is annotating the rectangles

# plot the dataframe with 1 line
ax = df.plot.barh(stacked=True, figsize=(8, 6))

# .patches is everything inside of the chart
for rect in ax.patches:
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the data value and can be used as the label
    label_text = f'{width:.2f}%'  # f'{width:.2f}' to format decimal values

    # ax.text(x, y, text)
    label_x = x + width / 2
    label_y = y + height / 2

    # only plot labels greater than given width
    if width > 0:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)

# move the legend
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)

# add labels
ax.set_ylabel("People", fontsize=18)
ax.set_xlabel("Percent", fontsize=18)
plt.show()

Example with Missing Segment
# set one of the dataframe values to 0
df.iloc[4, 1] = 0

*

*Note the annotations are all in the correct location from df.

A: For this case, the above answers work perfectly. The issue I had, and didn't find a plug-and-play solution online, was that I often have to plot stacked bars in multi-subplot figures, with many values, which tend to have very non-homogenous amplitudes.
(Note: I work usually with pandas dataframes, and matplotlib. I couldn't make the bar_label() method of matplotlib to work all the times.)
So, I just give a kind of ad-hoc, but easily generalizable solution. In this example, I was working with single-row dataframes (for power-exchange monitoring purposes per hour), so, my dataframe (df) had just one row.
(I provide an example figure to show how this can be useful in very densely-packed plots)
[enter image description here][1]
[1]: https://i.stack.imgur.com/9akd8.png
'''
This implementation produces a stacked, horizontal bar plot.
df --> pandas dataframe. Columns are used as the iterator, and only the firs value of each column is used.
waterfall--> bool: if True, apart from the stack-direction, also a perpendicular offset is added.
cyclic_offset_x --> list (of any length) or None: loop through these values to use as x-offset pixels.
cyclic_offset_y --> list (of any length) or None: loop through these values to use as y-offset pixels.
ax --> matplotlib Axes, or None: if None, creates a new axis and figure.
'''
    def magic_stacked_bar(df, waterfall=False, cyclic_offset_x=None, cyclic_offset_y=None, ax=None):

        if isinstance(cyclic_offset_x, type(None)):
            cyclic_offset_x = [0, 0]
        if isinstance(cyclic_offset_y, type(None)):
            cyclic_offset_y = [0, 0]

        ax0 = ax
        if isinstance(ax, type(None)):
            fig, ax = plt.subplots()
            fig.set_size_inches(19, 10)

        cycler = 0;
        prev = 0 # summation variable to make it stacked
        for c in df.columns:
            if waterfall:
                y = c ; label = "" # bidirectional stack
            else:
                y = 0; label = c # unidirectional stack
            ax.barh(y=y, width=df[c].values[0], height=1, left=prev, label = label)
            prev += df[c].values[0] # add to sum-stack

            offset_x = cyclic_offset_x[divmod(cycler, len(cyclic_offset_x))[1]]
            offset_y = cyclic_offset_y[divmod(cycler, len(cyclic_offset_y))[1]]

            ax.annotate(text="{}".format(int(df[c].values[0])), xy=(prev - df[c].values / 2, y),
                        xytext=(offset_x, offset_y), textcoords='offset pixels',
                        ha='center', va='top', fontsize=8,
                        arrowprops=dict(facecolor='black', shrink=0.01, width=0.3, headwidth=0.3),
                        bbox=dict(boxstyle='round', facecolor='grey', alpha=0.5))

            cycler += 1

        if not waterfall:
            ax.legend() # if waterfall, the index annotates the columns. If
                        # waterfall ==False, the legend annotates the columns
        if isinstance(ax0, type(None)):
            ax.set_title("Voi la")
            ax.set_xlabel("UltraWatts")
            plt.show()
        else:
            return ax

''' (Sometimes, it is more tedious and requires some custom functions to make the labels look alright.
'''
A, B = 80,80
n_units = df.shape[1]
cyclic_offset_x = -A*np.cos(2*np.pi / (2*n_units)  *np.arange(n_units))
cyclic_offset_y = B*np.sin(2*np.pi / (2*n_units) * np.arange(n_units)) + B/2


text:
Q: Adding classes to categories in a list of archives in Wordpress I am not very familiar with PHP but I am learning. I am using Wordpress and am wanting to create a filterable page of 'news updates', which are a list of post archives from the 'last 15 posts'.
I have 4 categories:

*

*New Benefit

*Useful

*Urgent & Important

*For You

When I create a post assigned to this particular category I want the list item to be given the class of the category.
The result I want my page to be

With the following CSS:
.category-useful:before {
        float: right;
    position: inherit;
    color: white;
    font-family: "Font Awesome 5 Pro";
    font-weight: 900;
    content: "\f129";
    zoom: 3;
    padding: 5px 10px 5px 20px;
}

.category-urgent_important, .category-urgent_important h2 {
    color: white;
    background-color: red;
}

.category-urgent_important:before {
        float: right;
    position: inherit;
    color: white;
    font-family: "Font Awesome 5 Pro";
    font-weight: 900;
    content: "\f071";
    zoom: 3;
    padding: 5px 5px 5px 20px;
}

.category-for_you, .category-for_you h2 {
    color: white;
    background-color: green;
}

.category-for_you:before {
    float: right;
    position: inherit;
    color: white;
    font-family: "Font Awesome 5 Pro";
    font-weight: 900;
    content: "\f02d";
    zoom: 3;
    padding: 5px 5px 5px 20px;
}

.category-uncategorised {
display: none;
}

Here is my current markup:
  function category_ac(){
    $categories = get_the_category();
    foreach ( $categories as $category ) {
        echo esc_html( $category->cat_name );
    }
  }

  $how_many_last_posts = intval(get_post_meta($post->ID, 'archived-posts-no', true));
  if($how_many_last_posts > 200 || $how_many_last_posts < 2) $how_many_last_posts = 15;

  $my_query = new WP_Query('post_type=post&nopaging=1');
  if($my_query->have_posts()) {
    echo '
Last '.$how_many_last_posts.' Posts
 ';
    echo '

';
    $counter = 1;
    while($my_query->have_posts() && $counter <= $how_many_last_posts) {
      $my_query->the_post();
      ?>
      <li class="<?php echo 'category-'.category_ac() ?>"><a href="<?php the_permalink() ?>" rel="category tag" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title();?>

      <?php
      $counter++;
    }
    echo '

';
    wp_reset_postdata();
  }

The trouble is, it works, but like this:

Test 5

Test 4

Test 3

Test 2

Test 1

How can I manipulate the output of 'category_ac();' and remove white space and capitalisation all while sticking 'category-' in the front?
I found this thread:
Strip php variable, replace white spaces with dashes
Though that implies that the 'category_ac()' would need to be a variable to be changed.
I couldn't seem to apply my own variable like:
$test = category_ac();

...As that didn't do anything so I imagine I'm doing it wrong.

A: If you leave category- out of php brackets and just echo the function will work.
Then you can try to use the category slug instead of name probably this will solve you the name issue
Here is the code with my changes $category->slug and <li class="category-<?php echo category_ac() ?>">
Let me know if it's working for you
  function category_ac(){
    $categories = get_the_category();
    foreach ( $categories as $category ) {
        echo esc_html( $category->slug );
    }
  }

  $how_many_last_posts = intval(get_post_meta($post->ID, 'archived-posts-no', true));
  if($how_many_last_posts > 200 || $how_many_last_posts < 2) $how_many_last_posts = 15;

  $my_query = new WP_Query('post_type=post&nopaging=1');
  if($my_query->have_posts()) {
    echo '
Last '.$how_many_last_posts.' Posts
 ';
    echo '

';
    $counter = 1;
    while($my_query->have_posts() && $counter <= $how_many_last_posts) {
      $my_query->the_post();
      ?>
      <li class="category-<?php echo category_ac() ?>"><a href="<?php the_permalink() ?>" rel="category tag" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title();?>

      <?php
      $counter++;
    }
    echo '

';
    wp_reset_postdata();
  }

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJS not passing ID to UI-View What I'm trying to do is create a ui-view for each request in requests.
When the app state = request.detail I'd like to render the "detail" into a UI-view with the id set as the request.id. I cannot figure out how to pass the request.id through angular and name the ui-view which the state renders in dynamically.
For Example if the request.id = 1 I'd like the ui-view to be ui-view="1";
if the request.id=23 , i'd like it's ui-view to be ui-view="23".
Request.js
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
 $stateProvider
    .state('home', { url: '',  views: { 'main': { templateUrl: 'static_pages/home.html'}}})
    .state('requests', { url: '/requests',  views: {'main': { templateUrl: 'requests.html', controller: 'RequestsCtrl'}}})
    .state('requests.detail',  { url: '/:id', views: {':id': { templateUrl: function($stateParams) {return `/requests/${$stateParams.id}`;}, controller: 'RequestController'}}})
    .state('requests.detail.pdf', { url: '.pdf', views: { 'requestpdf': {  templateUrl: function($stateParams) {return `/requests/${$stateParams.id}.pdf`;}, controller: 'RequestController'}}})
    .state('requests.detail.edit',  { url: '/edit', views: {'main2': { templateUrl: function($stateParams) {return `/requests/${$stateParams.id}/edit`;}, controller: 'RequestController'}}})
    .state('users', { url: '/users', templateUrl: 'users.html', controller: 'UsersCtrl'})
    .state('/users/:id', { url: 'users_show.html', controller: 'UsersCtrl' });

    $locationProvider.html5Mode({ enabled: true, requireBase: false });

});

app.controller("RequestsCtrl", ['$scope', '$state', '$stateParams', 'Request', '$location',  function($scope, $stateParams, $state, Request, $location ) {

    $scope.requests = Request.query();
    $scope.request = Request.query();

    $scope.deleteRequest = function (request) {
        Request.delete({id: request.id})
        console.log("deleted" + request.id);
    }

}]);

app.controller("RequestController", ['Request', '$scope', '$stateParams', RequestController]);

function RequestController( $scope, $stateParams, Request ) {
        $scope.currentRequestId = $stateParams.request.id;
};

Index.html

       *NEW*
      Request #{{request.id}}

      {{request.name}}
      {{request.email}}
      {{request.city}}, {{request.state}}, {{request.region}}

        View
         Delete


text:
Q: Invisible ImageView not responding to clicks - How to fix? I am having some issues creating an invisible ImageView with an onTouch/onClick listener in my Android app.
The issue is that when the ImageView is set to invisable the clicks do not register (the listener is not triggered).
I have tried to force the width and height of the view to be a specific number, thinking that in wrap mode an invisible view might take up no space. I have also tried to set clickable to true and the same for focusable.
None of these made a differece.
When visible it works fine.
I want an invisible ImageView that will react to clicks/touches.
How can I fix this?
This is some code from a dummy app that recreates the issue:
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.david.imageviewclicktest.MainActivity">

    <ImageView
        android:id="@+id/test"
        android:layout_height="100dp"
        android:layout_width="500dp"
        android:src="@drawable/listeners"
        android:visibility="invisible"
        android:clickable="true"
        android:focusable="true"></ImageView>

</android.support.constraint.ConstraintLayout>

Code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        ImageView test = (ImageView)findViewById(R.id.test);
        test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "clicked",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

A: Instead of making it invisible make the alpha channel 0.0f, i.e. make it transparent.
android:alpha="0"

Or by code
imageView.setAlpha(0.0f);


text:
Q: The symbol % becomes %25 when passing it through a Nodejs route with the following code I bring a report that is hosted on JasperReports Server (This works), the problem is when passing values that have % since it returns %25 in the route and generates an error, any way to solve this problem?
const express = require('express');
const axios = require("axios");
const app = express();
var bodyParser = require("body-parser");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}))

app.get('/prueba', function(req,res){
    res.sendFile(__dirname+"/prueba.html");
});

app.post('/form-submit', async function(req,res){
    try {
        const url = "http://localhost:8080/jasperserver/rest_v2/reports/reports/Re013.pdf"
        const params = {
            AMB_OCULTO: req.body.AMB_OCULTO,
            AMB : req.body.AMB,
            INS : '%',
            ORD_INI: req.body.ORD_INI,
            ORD_FIN: req.body.ORD_FIN
        }
        const file = await axios.get(url, {
            params: params,
            responseType: "stream",
            auth:{
                username: "jasperadmin",
                password: "jasperadmin"
            }
        })
        res.writeHead(200,{"Content-Type":"application/pdf"})
        file.data.pipe(res)
    } catch (error) {
        res.sendFile(__dirname+"/prueba.html");
        console.log(error)
    }
});


text:
Q: Uncertainty in measurements: if $x$ has uncertainty $\pm\epsilon$, what is the uncertainty in $\sin x$? I have two questions regarding uncertainties in measurements.
First, if I have some measured value for $x$ with an uncertainty $\pm e$, what would be the uncertainty in $\sin x$, $\pm\sin e$?
Then, if I have a range of values from 30 to 46, can I include an uncertainty value of $\pm 2$? Even if it's not wrong from a mathematical point of view, would it be unsuitable in a physics laboratory report?

A: First: You don't necessarily get an uncertainty of $\sin(x)\pm\sin(e)$. Remember that the sine function is periodic. So if you have that $x = 0$ and $e = 2\pi$. Then you would not get an uncertainty of $\sin(0) \pm \sin(2\pi) = 0 \pm 0$. In such a case you would get $0\pm 1$ since on the interval $[-2\pi, 2\pi]$ sine takes all values. Now for another example: If you get a value of $x =0.7$ and $e = 0.1$ then indeed you get $\sin(x)\pm \sin(e)$ because $sin$ is strictly increasing on the interval $[0.6, 0.8]$.
Second: I don't think I quite understand, and you might want to ask about some of this on the physics.SE site, but if you are trying to measure something, and you get values ranging from $30$ to $46$, then I guess you might give the average of $38$ with an uncertainty of $\pm 8$. Now, from what I understand, giving uncertainties of measurements in physics is about more than just giving the range of values that you got. You also have to account for uncertainties in the instruments.
Edit: If you have $\sin(x)$ and you measure $x$ in degrees, then $\sin$ is increasing on the interval $[30,46]$. So if the uncertainty is $\pm 2$ on $x$ (from the instrument or what ever), then the uncertainty on $\sin(x)$ is $\pm \sin(2)$.


text:
Q: chessboard: How to add or inherit styles? Is it possible to add styles?
I add for example a style 's1' on a style 's2':
\storechessboardstyle{s1}{
movenr={1},
markmove=\xskakget{movefrom}-\xskakget{moveto},
}

\storechessboardstyle{s2}{
style=s1,% <----------------   no effect!
movenr={2},
markmove=\xskakget{movefrom}-\xskakget{moveto},
}

But this does not work.
What do I have to do?

\documentclass[margin=5mm, varwidth]{standalone}
\usepackage{xskak, pgfplots}
\usepackage{chessboard}
\setchessboard{showmover=false, margin=false}
\setchessboard{pgfstyle=straightmove, color=red}

\begin{document}
\section{Works}
\newchessgame[setwhite={Ba8}]
\hidemoves{1. Be4 ... 2. Bh7 ... 3. Bg8 ... 4. Ba2 ...}

\storechessboardstyle{s}{
movenr={1},
markmove=\xskakget{movefrom}-\xskakget{moveto},
movenr={2},
markmove=\xskakget{movefrom}-\xskakget{moveto},
}
\chessboard[tinyboard, style=s]
%======================================

\section{Works not}
\newchessgame[setwhite={Ba8}
]
\hidemoves{1. Be4 ... 2. Bh7 ... 3. Bg8 ... 4. Ba2 ...}

\storechessboardstyle{s1}{
movenr={1},
markmove=\xskakget{movefrom}-\xskakget{moveto},
}

\storechessboardstyle{s2}{
style=s1,% <----------------   no effect!
movenr={2},
markmove=\xskakget{movefrom}-\xskakget{moveto},
}

\subsection{Style s1  - ok}
%\setchessboard{style=s1}
\chessboard[tinyboard,   style=s1]

\subsection{Style s2 - not ok (should include s1)}
%\setchessboard{style=s2}
\chessboard[tinyboard, style=s2]
\end{document}


text:
Q: Get all elements in selection/highlight using window.getSelection I can get a single element, or common ancestor element, but I can't figure out how to get all elements that are being highlighted.
Here's a demo of getting the common ancestor.

console.clear();
document.querySelector('div').addEventListener('mouseup', () => {
  const selection = window.getSelection();
  const elem = selection.getRangeAt(0).commonAncestorContainer.parentNode;
  console.log(elem);
});

Rich Text Editing Development

I'm really annoyed with trying to figure out this answer.

Since rangeCount is always only 1, and the objects I see from selection and other children don't have an array or nodeList of selected items (that I noticed), I don't know what to do.
So how do I know which elements are being selected/highlighted?

A: Though you'll get a copy of the descendant elements instead of references to the real ones, you can use the cloneContents() method of a Range, in addition to the common ancestor parent node (even supported in IE11 if using ES5 syntax):

document.addEventListener('mouseup', () => {

  console.clear();

  const selection = window.getSelection();
  if (!selection.rangeCount) return;

  const range = selection.getRangeAt(0);

  console.log('Selected elements:');
  range.cloneContents().querySelectorAll('*').forEach(e => console.log(e));

  console.log('Selected text/elements parent:');
  console.log(range.commonAncestorContainer.parentNode);

});

Rich Text Editing Development

I'm really annoyed with trying to figure out this answer.


text:
Q: get the expanded row id in postData jqgrid I'm strugling to get the expanded row id in a jqgrid postData, I want something like:
postData: {
  objectID: expandedRowId
}

how can i get the expandedRowId to send it to server with my parameters. I've seen something like:
postData : {
   ...
   nodeid:rc.id,
   n_left:rc.lft,
   n_right:rc.rgt,
   n_level:rc.level,
   ...
}

but what is "rc"??
plzz help

A: Sorry, but it's unclear what you want. I have to guess what you mean. Is expandedRowId a variable which you defined in your code and which you change somewhere? In the case you can define objectID property of postData as function:
postData: {
    objectID: function () { return expandedRowId; }
}

see the answer for more details.


text:
Q: How to send automated email every 24 hours using data stored in array - Android studio I am creating a ClockIn Android app using java for employees and I would like the owner/manager to receive a daily email for when employees have clocked in and out. I am using an array to store this 'data' and plan on deleting all 'data' from the array when the email is sent. Any help would be appreciated, thank you very much.

A: As @sudeshregmi wrote, do it on the server side. Sending email in java does not require many libraries, javax.mail should be enough in Your case. Though, If You would like to send millions of emails I recommend looking into some cloud based solutions like aws.amazon.com/ses :)
For task scheduling You can use QUARTZ - https://github.com/quartz-scheduler/quartz/blob/master/docs/quick-start-guide.adoc


text:
Q: barplot percentage in R I have a data frame with 3 columns (percentage of life-satisafction, agegroup and year). I want to visualize my data in the following way: percenatge of life-satisfaction for each age group once for the year 2014 and for 2020. My data for the percentage of life-satisfaction consists already of percentage values for each group and year.
How do I visualize this?
Example in Screenshot

data example


text:
Q: Do Wizards pay Muggle taxes? There are quite a lot of Wizarding families who, I assume, live in places inaccessible/invisible to Muggles. However, there are examples of families who live among the Muggles, so their neighbors know about their existence, they just think they are a bit eccentric. However, if they openly live in a house on a Muggle street, it means that their address is registered, their house is known to the Muggle government, and they have to pay property taxes. They would probably also require some kind of Muggle ID documents.

A: Well, if they're living among the muggles, in a house that is plainly visible and accounted for, then it would make sense that they would have to pay property taxes. Also they would probably be a target of investigation by HRMC or something like that, as they would have no official income, yet they would still somehow have money to lead comfortable life.
But more importantly, this leads to a bigger question: Should wizards pay income taxes? And if so to which government? Consider a business owner in Diagon Alley. He's definitely a UK resident, but he's not really a part of UK economy, nor he gains much benefit from services offered by UK government, for the taxes he would pay. On the other hand there is the Ministry of Magic, that also needs money to operate (if nothing else, it has to pay it's employees). I would guess that wizards pay taxes to MoM, which would make sense. Ministry could then take care of the muggle taxes, using a portion of taxes collected from the wizards.
Good solution would be to register all wizards who live among muggles as employees of one fictitious company. The Minister of Magic could then agree with the muggle Prime Minister on the portion of taxes wizarding population owes to the muggle government (considering how much they benefit from the public infrastructure), and pay it through the fictitious income of the fictitious company. "Muggle known" wizards would be covered as tax payers; and as there is probably not a whole lot of them, the fraction of wizard taxes used to cover them would not be large (there is more "secret" wizards, that still have to pay wizard taxes).

A: Judging by the fact that said Muggle-meshing Wizard families aren't allowed to mind-control Muggles willy-nilly due to International Statute of Secrecy; AND would be carted off to jail if they avoided their taxes the same way Daywalking Vampires do; it stands to reason that the wizards who are known to Muggle world pay taxes because we never hear of Wizarding families going to jail.
Also, out of universe, JKR is very pro-taxation and anti-rich. So if anyone cheated on their taxes, it'd be the Evil Rich Malfoys and co... and we all know that Malfoys wouldn't be caught dead living in a Muggle world.

A: My guess is that they just wave a magic wand over a blank sheet of paper and mail it to the IRS.  Or the British equivalent.  It worked for Dumbledore in Book 6.

A: The Ministry of Magic probably pays a fixed or almost fixed sum in taxes to Republic of Ireland and UK government using a fake company stationed in the two countries. Probably one or two guys at Ministry of Magic who has taken muggle studies makes this happen. The sum would be small enough not to raise any suspicion (only about 5 k wizards at most on the British islands) and if it does the Ministry of Magic guys can use the confounds charm.
The Ministry of Magic then adds a reasonably sum to the income taxes the wizards pay to make up for the money the MoM pays on the wizards behalf. Wizards who live in muggle houses or own muggle stocks and bonds probably pays taxes on them just like a muggle.
There are no wizards who are prominent in the muggle world so wizards paying no income tax would not raise much suspicion since the only wizards known to muggle authorities are the very few who pay taxes on capital like real estate and stocks and bonds. If there is any suspicion they can just use the confundus charm or obliviate.

A: Non-muggles may well have paid muggle taxes, but then this might've been refunded to them, depending on their usage of muggle public services. After all the muggle government was both aware of, and had formal relations with the ministry of magic didn't they?
So what someone would've paid in pounds, they'd have got as tax refunds in sickles and galleons.

A: I could see a couple options, depending on the interaction with the person or family in questions. We know that Wizards tend to squeeze their urban centers in between existing centers (platform 9 3/4, the The Blacks' residence in Order of the Phoenix in a town home in between other homes), so those may or may not "exist" on the books of Muggle census and real estate information. Are we looking at a Perception Filter/Someone-Elses-Problem field, where it actually exists but no one cares? Or are they literally creating space where there was not some? That is a question that is never really answered, other then the larger-on-inside aspects of Hermione's bag or the pup tent that shows up every so often in book 4 onward.
The only other option we see is in the Lovegoods, Weasleys & Malfoys, that have family estates of various sizes in what seems to be the middle of nowhere. They could be listed and owned privated estates, where the owners simply pay property taxes, or they could simply be in public land and fall into the Perception Filter category.
Assumably those that have some interaction with the Muggle world would pay taxes. But with the European wizards consisting a veil of secrecy and illusion for everyone other than the Prime Minister, we won't know unless there's supplemental information (as opposed to American Wizards, which are in the Yellow Pages under "Wizard")


text:
Q: How to set android:drawable to left and top? I just wanted to set icon to the top and left corner of my TextView.
This is my code and the output respectively:
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Content"
    android:drawableLeft="@drawable/icon" />

Output:

but I want to set my icon to the top and left like this one :

A: For this purpose you have to take the seperate imageView like this and in textview field you have to add one line code that  android:layout_toRightOf="@+id/imageView":
For better understanding see following code:
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:background="@mipmap/ic_launcher"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
      android:layout_toRightOf="@+id/imageView"
        android:text="this si fodfjkhsdhaffjsdfasdfjhsdfhjsdhfjhsdfhsdhfhdsjfhsdjhfjhdsfhsdhfjhsdjhfjsdhfjhsdjfhjsdhfjhsdjfhjdshfsdjhfjsdhfsdkjhfjsdhfjhsdjfhjsdhjfhsdjhfjsdhfjhjsdhfjsdhjfhsdjf"
        />

</RelativeLayout>

A: You can use setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)
(For better Understand refer this link:)
https://developer.android.com/reference/android/widget/TextView.html#attr_android:drawableTop

A: Use below code;
<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/Content"
   android:drawableTop="@drawable/def"
   android:drawableLeft="@drawable/icon" />

A: try this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/tv1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="hello world"
    android:layout_toEndOf="@+id/imageView" />

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_error" />

</RelativeLayout>

A: You can align a compound-Drawable to the top (or bottom) by creating a custom Drawable that wraps your Drawable.
Usage
GravityCompoundDrawable gravityDrawable = new GravityCompoundDrawable(innerDrawable);
// NOTE: next 2 lines are important!
innerDrawable.setBounds(0, 0, innerDrawable.getIntrinsicWidth(), innerDrawable.getIntrinsicHeight());
gravityDrawable.setBounds(0, 0, innerDrawable.getIntrinsicWidth(), innerDrawable.getIntrinsicHeight());
textView.setCompoundDrawables(gravityDrawable, null, null, null);

Custom GravityCompoundDrawable class:
public class GravityCompoundDrawable extends Drawable {

// inner Drawable
private final Drawable mDrawable;

public GravityCompoundDrawable(Drawable drawable) {
    mDrawable = drawable;
}

@Override
public int getIntrinsicWidth() {
    return mDrawable.getIntrinsicWidth();
}

@Override
public int getIntrinsicHeight() {
    return mDrawable.getIntrinsicHeight();
}

@Override
public void draw(Canvas canvas) {
    int halfCanvas= canvas.getHeight() / 2;
    int halfDrawable = mDrawable.getIntrinsicHeight() / 2;
    // align to top
    canvas.save();
    canvas.translate(0, -halfCanvas + halfDrawable);
    mDrawable.draw(canvas);
    canvas.restore();
 }
}

A: This code will help you and see the attached image.
  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/llMain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.10"
            android:orientation="vertical">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@mipmap/ic_launcher" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@mipmap/ic_launcher" />

        </LinearLayout>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.90"
            android:text="It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using" />
    </LinearLayout>
</LinearLayout>

https://i.stack.imgur.com/hLUGT.png

A: None of the solutions from SO worked form me. In the end I did it like this:
class MyTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null
) : AppCompatTextView(context, style) {
    private val leftDrawable = ContextCompat.getDrawable(context, R.drawable.checkmark)

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        setBulletPoint(compoundDrawables[0], canvas)
    }

    private fun setBulletPoint(drawableLeft: Drawable?, canvas: Canvas?) {
        if (!TextUtils.isEmpty(text)) {
            leftDrawable?.let { drlft ->
                if (lineCount == 1) {
                    setCompoundDrawablesWithIntrinsicBounds(drlft, null, null, null)
                } else {
                    val buttonWidth = drlft.intrinsicWidth
                    val buttonHeight = drlft.intrinsicHeight
                    val topSpace = abs(buttonHeight - lineHeight) / 2

                    drlft.setBounds(0, topSpace, buttonWidth, topSpace + buttonHeight)
                    canvas?.apply {
                        save()
                        drlft.draw(canvas)
                        restore()
                    }
                }
            }
        }
    }
}

A: If you want to resolve it using compound drawable, you should create a custom textview and use it.
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

class TopAlignCompoundDrawableTextView: AppCompatTextView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    )

    override fun dispatchDraw(canvas: Canvas?) {
        super.dispatchDraw(canvas)
        val centerTextView = height / 2

        val drawableLeft = compoundDrawables[0]
        drawableLeft?.let {
            val topDrawable = it.intrinsicHeight/2 - centerTextView
            it.setBounds(
                0,
                topDrawable,
                it.intrinsicWidth,
                it.intrinsicHeight + topDrawable
            )
        }

        val drawableRight = compoundDrawables[2]
        drawableRight?.let {
            val topDrawable = it.intrinsicHeight/2 - centerTextView
            it.setBounds(
                0,
                topDrawable,
                it.intrinsicWidth,
                it.intrinsicHeight + topDrawable
            )
        }
    }
}


text:
Q: Swift - remove all delivered notifications on all devices I've made a simple app, which is receiving push notifications from a service called OneSignal. This service just pushes notifications to devices without any user tracking, etc. so the user receives the notification on all devices, the app is installed.
I was wondering if it's possible to clear all notifications in the notification center on all devices in swift, without any server side modifications, like sending a badge=0 push to all other devices? My goal is, that when the user taps the notification / opens the App on his iPhone, the notifications are cleared on his iPad or other iCloud-linked device too.
This works unfortunately just locally and not on all devices of the same Apple ID:
application.applicationIconBadgeNumber = 0
UNUserNotificationCenter.current().removeAllDeliveredNotifications()


text:
Q: Are Weyl sequences polynomially bounded? Look at the Hilbert space $l^2( \mathbb{Z}) $ and let $A$ be a translation invariant band operator. I.e. if $\{ e_n \}_{n \in \mathbb Z} $ is the standard basis for $l^2( \mathbb{Z}) $ then it holds that
\begin{align*}
\langle e_n, A e_m \rangle  = 0
\end{align*}
for $\vert n-m \vert \geq K$ for some $K$. And translation invariance gives
\begin{align*}
\langle e_n, A e_m \rangle  = \langle e_{n+k}, A e_{m+k} \rangle
\end{align*}
for all $k \in \mathbb{Z}$.
The eigenvalue equation reads
\begin{align*}
A \psi = \lambda \psi
\end{align*}
for some function $\psi \in l^2 ( \mathbb{Z}) $.
Since $A$ is a band matrix we could extend this equation for functions $\phi: \mathbb{Z} \to \mathbb{C}$ which we do not require to be square-summable and ask for solutions to this equation.
Is it now true that $\lambda \in \sigma(A)$ if and only if there exists such a solution $\psi$ which is bounded by a polynomial?
Maybe one needs to assume translation invariance.
Example: For the discrete Laplacian
\begin{align*}
\langle e_n, A e_m \rangle  = -2 \delta_{n,m} + \delta_{n+1,m} + \delta_{n,m+1}
\end{align*}
we get solutions of the form $\psi(x) =e^{ipx}$ which are not square integrable, but are still solutions of the finite difference equation.
Notice that one can truncate these to construct af Weyl-sequence and it seems that this could prove at least one direction of the question.
The issue is discussed in chapter 7.1 https://arxiv.org/pdf/0709.3707.pdf here for Hamiltonians $A$, but I am particularly interested in the non-normal case.
EDIT: (Partially progress using translation invariance)
By translation invariance the eigenvalue equation can be written as
\begin{align*}
\sum_{i = - K}^K a_i \psi_{i+n} = \lambda \psi_n
\end{align*}
which is just linear recursion. So one can find the solutions using the characteristic equation and then they are either constant or exponentially increasing/decreasing. How can we show that the exponentially increasing solutions do not correspond to elements in the spectrum of $A$?
Edit2: In this case we can prove the result using Fourier Transformation, but what if the operator is not translation invariant, but translation invariant plus a compact pertubation?


text:
Q: Using C# to find nodes within .csproj files I'm having trouble trying to select a particular node from a .csproj file I've read in as a XDocument.
XDocument xmldoc = XDocument.Load("The full path of the .csproj file");

This loads the .csproj file into a XDocument without issue. I've tried Descendants, Elements, etc etc to try to get TheNodeIWant and its value, but cannot figure out why I keep getting no results.
<?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
        <PropertyGroup>
            <TheNodeIWant>The String I Want </TheNodeIWant>
        </PropertyGroup>
        <PropertyGroup>
        .......
        </PropertyGroup>
    </Project>

How can I select TheNodeIWant and retrieve its value?

A: see https://stackoverflow.com/a/4171468/1301310
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(@"c:\test.txt");

XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable);
ns.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003");
XmlNode node = xmldoc.SelectSingleNode("//msbld:TheNodeIWant", ns);

if (node != null)
{
    MessageBox.Show(node.InnerText);
}

A: You can use the MSBuild Project class to better use csproj from code.

A: I suggest to use Xpath to navigate inside your csproj file.


text:
Q: Making a bluetooth connection on windows using C++ (getting error 10060) I'm trying to get 2 laptops with bluetooth to connect.
This is the code I'm using for making a server:
WSADATA wsd;
WSAStartup (MAKEWORD(1,0), &wsd);

SOCKET server_socket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);

SOCKADDR_BTH sa;
memset(&sa, 0, sizeof(sa));
sa.addressFamily = AF_BTH;
sa.port = 0 & 0xFF;

if(0 != bind(server_socket, (SOCKADDR *)&sa, sizeof(sa)))
{
    std::cout << "BIND ERROR: " << WSAGetLastError () << std::endl;
    closesocket(server_socket);
    return false;
}

if(0 != listen (server_socket, 5))
{
    std::cout << "LISTEN ERROR: " << WSAGetLastError () << std::endl;
    closesocket(server_socket);
    return false;
}

SOCKADDR_BTH sa2;
int size = sizeof(sa2);
SOCKET s2 = accept(server_socket, (SOCKADDR*)&sa2, &size);
if(s2 == INVALID_SOCKET)
{
    std::cout << "ACCEPT ERROR: " << WSAGetLastError () << std::endl;
    return false;
}
else
{
    std::cout << "Connected? " << WSAGetLastError () << std::endl;
}

and the following as a client:
WSADATA wsd;
WSAStartup (MAKEWORD(1,0), &wsd);

SOCKET client_socket = socket (AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);

SOCKADDR_BTH sa;
memset (&sa, 0, sizeof(sa));
sa.addressFamily = AF_BTH;
sa.btAddr = (BTH_ADDR)d.getDeviceAddress();
sa.port = 0;
sa.serviceClassId = *d.getLpServiceClassId();

if(client_socket == INVALID_SOCKET)
{
    std::cout << "SOCKET ERROR: " << WSAGetLastError () << std::endl;
    return false;
}
if (0 != connect (client_socket, (SOCKADDR *)&sa, sizeof(sa)))
{
    std::cout << "CONNECT ERROR: " << WSAGetLastError () << std::endl;
    return false;
}
else
{
    //std::cout << "CONNECT ERROR: " << WSAGetLastError () << std::endl;
    //Perform error handling.s
    send(client_socket, "ABC",3,0);
    closesocket (client_socket);
    return true;
}

Where "b" is the bluetooth device I give as argument the bluetoothdevice class has the following fields:
LPSOCKADDR local_address;
LPSOCKADDR device_address;
LPGUID lp_service_class_id;

This SHOULD work. But when I try to connect to the server, the server gets nothing and the client gives me error 10060.
This error means:
WSAETIMEDOUT 10060

The I/O timed out at the Bluetooth radio level (PAGE_TIMEOUT).

Is there anyone out here who has worked with the bluetooth stack on windows and knows where this error comes from?

A: Have you registered your service with Bluetooth SDP? If no, I guess, you will not be able to connect using current approach in your client code. From MSDN:
The bind function does not automatically advertise the server application using the Bluetooth SDP; applications must call the WSASetService function to be found by remote  Bluetooth applications.
Also take a look to bluetooth documentation for bind and connect funcs:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa362901%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/aa362901%28v=vs.85%29.aspx
Another approach, as I understand, is that you can try to specify port explicitly at both server and client side. But it will be enough only for playground applications.
You can refer to http://msdn.microsoft.com/en-us/library/windows/desktop/aa363058%28v=vs.85%29.aspx for more information on bluetooth usage.


text:
Q: Want to seperate integers and floats from column with diferent strings in it I am trying to extract only integers and floats from column of string
i have tried
data['new'] = data['text'].str.extract(r'^\d+\.\d+$')

A: If need extract only values with numeric:
data = pd.DataFrame({'text':['20','45.45','ss4','7.4ds','dr']})
data['new'] = data['text'].str.extract(r'^(\d+\.\d+|\d+)$')
print (data)
    text    new
0     20     20
1  45.45  45.45
2    ss4    NaN
3  7.4ds    NaN
4     dr    NaN

Then convert to floats:
data['new'] = data['text'].str.extract(r'^(\d+\.\d+|\d+)$').astype(float)
print (data)
    text    new
0     20  20.00
1  45.45  45.45
2    ss4    NaN
3  7.4ds    NaN
4     dr    NaN

Or use to_numeric function:
data['new'] = pd.to_numeric(data['text'], errors='coerce')
print (data)
    text    new
0     20  20.00
1  45.45  45.45
2    ss4    NaN
3  7.4ds    NaN
4     dr    NaN

A: You need to add capture groups in your regex.
I assumed the simplest case since you didnt provide any example of your data:
>> df
               text
0     green123apple
1  yellow45.6banana

So here's the new regex: "(\d+(?:\.\d+)?)"
If we split the regex down we get:
The ?: part means that you don't want to capture this inner group, you don't care about getting the decimal part in a separate group. You just want the whole number.
Output:
>> df["new"] = df["text"].str.extract("(\d+(?:\.\d+)?)")
>> df
               text   new
0     green123apple   123
1  yellow45.6banana  45.6


text:
Q: How do I find an object whose properties foo or bar equal a query value? I searched google and looked at the docs, but I found no example of this.
I have this object with embedded children:
{
  teacher: "Balthazar",
  students: [
    { name: 'Wilfred', sibling: 'Cordelia' },
    { name: 'Mortimer', sibling: 'Arthur' },
    { name: 'Cordelia', sibling: 'Wilfred' },
    { name: 'Arthur' sibling: 'Mortimer' },
  ]
}

I want to find Balthazar's students whose name or sibling is in ['Wilfred', 'Cordelia', 'foo']. I got it to work this way:
criteria_a = balthazar.students.in(name: ['Wilfred', 'Cordelia'])
criteria_b = balthazar.students.in(sibling: ['Wilfred', 'Cordelia'])
criteria_a << criteria_b

But is there a cleaner way to chain criteria? I tried chaining, but it doesn't work. It produces an AND intersection, not an OR.
balthazar.students.
  .in(name: ['Wilfred', 'Corderial'])
  .in(sibling: ['Wilfred', 'Corderial'])

So, in plain speak, this query is name is in array **AND** sibling is in array. But I want name is in array __OR__ sibling is in array.

A: You can use any_of
balthazar.students.any_of({name: ['Wilfred', 'Cordelia']}, {sibling: ['Wilfred', 'Cordelia']})


text:
Q: Is it possible to "catch" magic methods in Python? Inspired by this question, I thought it'd be interesting to throw together a "MutableNum" class for fun that, in as many cases as possible, acted just like a standard numeric type, but it would be mutable, so something like the following would work:
def double(x): x *= 2

x = MutableNum(9)
print(x)             # 9
double(x)
print(x)             # 18

I got to the following:
class MutableNum():
    val = None
    def __init__(self, v): self.val = v
    # Comparison Methods
    def __eq__(self, x):    return self.val == x
    def __ne__(self, x):    return self.val != x
    def __lt__(self, x):    return self.val <  x
    def __gt__(self, x):    return self.val >  x
    def __le__(self, x):    return self.val <= x
    def __ge__(self, x):    return self.val >= x
    # Arithmetic
    def __mul__(self, x):   return self.__class__(self.val * x)
    def __rmul__(self, x):  return self.__class__(self.val * x)
    # Casts
    def __int__(self):      return self.val
    # Represenation
    def __str__(self):      return "%d" % (self.val)
    def __repr__(self):     return "%s(%d)" % (self.__class__.__name__, self.val)

Which works (so far, as far as I can tell), but I found myself wanting to "catch" the magic methods, since many of them would follow very similar structure.
For example, I'd like to catch __mul__, __add__, __sub__, etc in something like:
def catch(self, method, x): return MutableNum(self.val.method(x))

So for __add__, catch() would return
return MutableNum(self.val.__add__(x))

Is something like this possible?  Or should I just implement all of the magic methods like I have already done?
EDIT:  I've experimented a little with trying to catch magic methods with __getattr__(self,key), but I'm getting mixed results.
Thanks in advance.
Edit 2
With everyone's help, here's what I came up with:
class MutableNum(object):
    __val__ = None
    def __init__(self, v): self.__val__ = v
    # Comparison Methods
    def __eq__(self, x):        return self.__val__ == x
    def __ne__(self, x):        return self.__val__ != x
    def __lt__(self, x):        return self.__val__ <  x
    def __gt__(self, x):        return self.__val__ >  x
    def __le__(self, x):        return self.__val__ <= x
    def __ge__(self, x):        return self.__val__ >= x
    def __cmp__(self, x):       return 0 if self.__val__ == x else 1 if self.__val__ > 0 else -1
    # Unary Ops
    def __pos__(self):          return self.__class__(+self.__val__)
    def __neg__(self):          return self.__class__(-self.__val__)
    def __abs__(self):          return self.__class__(abs(self.__val__))
    # Bitwise Unary Ops
    def __invert__(self):       return self.__class__(~self.__val__)
    # Arithmetic Binary Ops
    def __add__(self, x):       return self.__class__(self.__val__ + x)
    def __sub__(self, x):       return self.__class__(self.__val__ - x)
    def __mul__(self, x):       return self.__class__(self.__val__ * x)
    def __div__(self, x):       return self.__class__(self.__val__ / x)
    def __mod__(self, x):       return self.__class__(self.__val__ % x)
    def __pow__(self, x):       return self.__class__(self.__val__ ** x)
    def __floordiv__(self, x):  return self.__class__(self.__val__ // x)
    def __divmod__(self, x):    return self.__class__(divmod(self.__val__, x))
    def __truediv__(self, x):   return self.__class__(self.__val__.__truediv__(x))
    # Reflected Arithmetic Binary Ops
    def __radd__(self, x):      return self.__class__(x + self.__val__)
    def __rsub__(self, x):      return self.__class__(x - self.__val__)
    def __rmul__(self, x):      return self.__class__(x * self.__val__)
    def __rdiv__(self, x):      return self.__class__(x / self.__val__)
    def __rmod__(self, x):      return self.__class__(x % self.__val__)
    def __rpow__(self, x):      return self.__class__(x ** self.__val__)
    def __rfloordiv__(self, x): return self.__class__(x // self.__val__)
    def __rdivmod__(self, x):   return self.__class__(divmod(x, self.__val__))
    def __rtruediv__(self, x):  return self.__class__(x.__truediv__(self.__val__))
    # Bitwise Binary Ops
    def __and__(self, x):       return self.__class__(self.__val__ & x)
    def __or__(self, x):        return self.__class__(self.__val__ | x)
    def __xor__(self, x):       return self.__class__(self.__val__ ^ x)
    def __lshift__(self, x):    return self.__class__(self.__val__ << x)
    def __rshift__(self, x):    return self.__class__(self.__val__ >> x)
    # Reflected Bitwise Binary Ops
    def __rand__(self, x):      return self.__class__(x & self.__val__)
    def __ror__(self, x):       return self.__class__(x | self.__val__)
    def __rxor__(self, x):      return self.__class__(x ^ self.__val__)
    def __rlshift__(self, x):   return self.__class__(x << self.__val__)
    def __rrshift__(self, x):   return self.__class__(x >> self.__val__)
    # Compound Assignment
    def __iadd__(self, x):      self.__val__ += x; return self
    def __isub__(self, x):      self.__val__ -= x; return self
    def __imul__(self, x):      self.__val__ *= x; return self
    def __idiv__(self, x):      self.__val__ /= x; return self
    def __imod__(self, x):      self.__val__ %= x; return self
    def __ipow__(self, x):      self.__val__ **= x; return self
    # Casts
    def __nonzero__(self):      return self.__val__ != 0
    def __int__(self):          return self.__val__.__int__()               # XXX
    def __float__(self):        return self.__val__.__float__()             # XXX
    def __long__(self):         return self.__val__.__long__()              # XXX
    # Conversions
    def __oct__(self):          return self.__val__.__oct__()               # XXX
    def __hex__(self):          return self.__val__.__hex__()               # XXX
    def __str__(self):          return self.__val__.__str__()               # XXX
    # Random Ops
    def __index__(self):        return self.__val__.__index__()             # XXX
    def __trunc__(self):        return self.__val__.__trunc__()             # XXX
    def __coerce__(self, x):    return self.__val__.__coerce__(x)
    # Represenation
    def __repr__(self):         return "%s(%d)" % (self.__class__.__name__, self.__val__)
    # Define innertype, a function that returns the type of the inner value self.__val__
    def innertype(self):        return type(self.__val__)
    # Define set, a function that you can use to set the value of the instance
    def set(self, x):
        if   isinstance(x, (int, long, float)): self.__val__ = x
        elif isinstance(x, self.__class__): self.__val__ = x.__val__
        else: raise TypeError("expected a numeric type")
    # Pass anything else along to self.__val__
    def __getattr__(self, attr):
        print("getattr: " + attr)
        return getattr(self.__val__, attr)

I put the entire class, with usage header and rough test suite here.
mgilson's suggestion of using @total_ordering will simplify this a bit.
As long as you follow the usage guidelines (e.g. using x *= 2 instead of x = x * 2), it seems that you'll be fine.
Although, simply wrapping the argument in a list and then modifying x[0] seems much easier -- still was a fun project.

A: The easiest thing to do is going to be to implement them all by hand.  If this was something you were going to add to lots of classes then you might look at metaclasses (can be brain melting) or class decorators (much easier to deal with), but you should do it once by hand so you know what's going on.
The reason __getattr__ only works sometimes is that it is only called if the name it is looking for cannot be found on the class or any of its base classes.  So if __xyz__ can be found on object, __getattr__ will not be called.

A: Most magic methods are looked up on the type rather than an instance. You can neither overwrite them in an instance nor catch them with __getattr__. In order to hook into a double under function you have to implement it.
Example:
obj < 1

doesn't call
obj.__lt__(1)

Instead the call goes through the type. It's almost equal to (except it skips getattr on the meta class, too).
type(obj).__lt__(obj, 1)

The lookup is documented http://docs.python.org/3/reference/datamodel.html#special-method-lookup


text:
Q: Por que no pasa mi variable a la vista blade? Por que no pasa la variable usuario a la vista del componente?
este es mi componente:
<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\User;

class PerfilComponent extends Component
{
    public $id, $nombre, $correo, $password;

    public function mount(){
      $id = Auth::id();
    }

    public function render()
    {
        $usuario = User::where('id','=',$id)->get();
        return view('livewire.Perfiles.perfil-component',compact('usuario'));
    }

}

Coloque esto en el route/web
Route::view('/perfil', 'livewire/Perfiles/perfil-component');

y esta es la vista de mi componente:
@extends('layouts.app')
@section('content')
<div>
  @foreach($usuario as $usu)
    {{$usu->name}}
  @endforeach
</div>
@endsection

cuando me voy a localhot:8000/perfil me aparece el siguiente error:
ErrorException
Undefined variable: usuario (View: /../resources/views/livewire/Perfiles/perfil-component.blade.php)
he revisado proyectos anteriores con livewire y no me pasaba esto. qué podrá ser?

A: Al hacer esto Route::view() la ruta se va directamente a la vista, sin pasar por el componente y método render() por eso no encuentra la variable $usuario.
Si quieres que funcione tal y como está ahora, en tu route/web, debes adjuntar también la variable usuario, algo así: Route::view(...,['usuario' => 'data'])
Intenta poniendo la ruta de la siguiente manera: Route::livewire() o Route::get(..., PerfilComponent::class).


text:
Q: Meta and Metafor R Package - I am currently conducting a metaanlysis in R using the package "metafor". Doing my research I came across a different package for metaanalyses in R, namely "meta". I like the forest plot created by the latter package better (designwise) but unfortunatley some of the data is not the same as in the plot I created with metafor.
Specifically, the data is different only for I^2 and the pooled estimate.
meta_1 <- rma(yi=yi, vi=vi, measure="SMD", method="ML", slab=Citation, data=dat)
forest(meta_1)

meta_2 <- metagen(yi,vi^.5,data = dat,studlab = paste(Citation), comb.fixed = FALSE,
                 comb.random = TRUE, hakn = TRUE, method.tau = "ML", sm = "SMD")
forest(meta_2)

Does anyone know why those differences emerge?

A: So I was able to get the prediction interval to match across functions but not the I^2 values (even though the difference is off by only 2%). There might be some statistical correction one package is doing compared to the other or it has to do with the RE/FE type of modeling approach.
Anyway I hope this code helps point you in the right direction. To get the CIs to match you also have to use the parameter method.tau.ci in metagen().
library(meta)
library(metafor)
study<- c(1:10)
yi<- c( -0.48965031,0.64970214, 0.11201680,0.07945655,-0.70874645 -0.54922759,0.66768916 , -0.45523574 )
vi <- c(0.10299697,0.14036855,0.05137812, 0.03255550, 0.34913525, 0.34971466, 0.07539957, 0.08428983)
dat <- cbind(study, yi, vi)
dat <- as.data.frame(dat)

meta_1 <- rma(yi=dat$yi, vi=dat$vi, measure="SMD", method="REML", slab=paste(study), data=dat)
forest(meta_1)

meta_2 <- meta::metagen(TE =dat$yi,seTE = dat$vi^.5, method.tau = 'REML',
                        method.tau.ci = 'BJ', comb.random = TRUE, comb.fixed = TRUE,
                        sm = 'SMD')

forest(meta_2)


text:
Q: Random redirects on single URL Hi guys is this possible via .htaccess?
This URL: example.com/main should randomly redirects to one of these two links:

1) example-one.com/test1
2) example-two.com/test2

I've tried this article but no luck:
.htaccess redirect to random URL

A: To base the "randomness" on the seconds portion of the current time and redirect to URL#1 on even seconds and URL#2 on odd seconds (when requesting /main) then you can do something like the following (before the existing WordPress directives):
RewriteCond %{TIME_SEC} (0|2|4|6|8)$
RewriteRule ^main$ https://example-one.com/test1 [R,L]
RewriteRule ^main$ https://example-two.com/test2 [R,L]

Importantly, this is a 302 (temporary) redirect. (A 301 would ordinarily be cached by the browser, so the same user/browser would see the same response on repeated requests - which could be desirable in some scenarios.)
NB: This isn't strictly "random" as it's tied directly to time, but might appear random to the casual user.
To implement "real" random you would need access to the server config to configure a rnd RewriteMap, which can then be called from .htaccess. But this cannot be configured in .htaccess alone.


text:
Q: mdadm Boot Error, incrementally starting raid array Ubuntu SErver 14.04 i build a small Server with Ubuntu 14.04 for Samba,
I has one SSD Drive (the ubuntu installation is on it)
and 2 3TB SATA Disk,
the sata disk are combined to a Raid 1 with mdadm.
Now sometimes (no everytime, i think it's maybe related to a dirty shutdown)
the system hangs at the boot process:
incrementally starting raid arrays
mdadm: Create user root not found
mdadm: create group disk not found
incrementally started raid arrays

these 4 lines keep repeating.
It's really strange cause the boot volume (the ssd) isn't configured as raid and this should not affect it?
Important edit: if i press ctrl + alt + del , the server reboots and starts up normaly,
if i look at the raid dev mdadm --detail /dev/md0
after the boot, everything looks good.
I'm not a linux pro and didn't find anything on the internet related to these errors, so now i'M a littel stuck, maybe somebody has a clue what the problem could be or some advanced troubleshooting advises (log files etc)?
thanks for reading
regards
Stefan

A: Had this as well. In my environment: 2x SAS HDDs configured as raid10.
The problem was that mpt2sas.ko was not loaded, and thus mdadm couldn't see any disk. This in turn was caused by a packaging error:  when apt was removing unneeded wlan packages like crda, it also auto-removed the linux-image-extra-$VERSION package, which actually owns mpt2sas.ko.
To ensure, that the module gets loaded before the raid modules, I also did a
echo mpt2sas >>/etc/initramfs-tools/modules

A: On my machine (Ubuntu trusty) this was caused by having a newer (xenial 4.4.0 -series) kernel installed under /boot and being used by default.
I solved this issue by booting an older kernel version and then running:
update-initramfs -u
update-grub

A: finally "fixed" the error.
Short Version: The Transcend SSD (TS128GSSD25S-M) in combination with the  ASRock B85M Pro4 Mainboard caused the Error.
After Cloneing the System with clonezilla to a Samsung 840 Evo i booted now 30 times without problems.
in deep Problem report:
But why is mdadm showing up with totaly unrelated raid Array Problems? :
Well while creating the Raid Array (or maybe by default? i dont know exactly) mdadm put's a raid initialization script into the initramfs.
This scrip check if the rootfs is mounted, if the rootfs (on my SSD) isn't mounted it jumps to function mountroot_fail
message "Incrementally starting RAID arrays..."
if mdadm --incremental --run --scan; then
message "Incrementally started RAID arrays."
return 0

This leads to the confusing output. After Removing those scripts from initramfs i bumped into the real Problem:
Gave up wiating for root device. Common problems:

*

*Boot args (cat /proc/cmdline)

*

*check rootdelay= (did the system wait long enough?)

*check root= (did the system wait for the right device?)

*missing modules (cat /proc/modules; ls /dev)
ALERT! /dev/disk/by-uuid/01234567-89ab-cdef-0123-456789abcdef does not exist. Dropping to a shell!
BusyBox v1.13.3 (Ubuntu 1:1.13.3-1ubuntu11) built-in shell (ash)
Enter 'help' for a list of built-in commands.
(initramfs)

As the error isn't persistent i thought to give a different SSD a try, and BAM working.

A: For me the solution were missing "dm-mod", "dm-snapshot" and "dm-mirror" entries in /etc/initramfs-tools/modules. I took me quite some time to fight this issue as the error messages were talking about "mdadm" and raid - so how should one guess that lvm is the issue.
My setup:
sda -> sda1 (0xfd linux raid autodetect, 500MB), sda2 (0xfd linux raid autodetect, 250G)
same for sdb

*

*sda1 + sdb1 --> /dev/md0 (mdadm) "/boot"

*sda2 + sdb2 --> /dev/md1 (mdadm) --> lvm volume for "swap" and "/"
I didn't put "/boot" into the LVM to avoid hazzle with grub/lvm in the first place. But it looks like I just have fallen into another tarpit of grub/lvm/raid :(
I guess the issue was that grub properly mounted the initramfs and then it couldn't mount / (because of missing lvm modules) it tried to initialize some raid devices.
The incrementally starting raid arrays is somewhat misleading as it can be any missing module which inhibits / from getting mounted. Also see above post about missing mpt2sas module.
Additionally I tought the dm_ modules were not necessary as they are for dmraid - which is wrong: They are also necessary for LVM. In my situation I did a switch from dmraid back to the good ol' mdadm because dmraid (fakeraid) caused problems (A directory just disappeared).
And last but not least I wondered that I can add dm-mod, dm-snapshot anddm-mirrorto/etc/modulesand/etc/initramfs-tools/modulesaltough there are not really and.ko` files by that name. Must be some kind of module aliases.

A: The case for me was that I was using a 3.x kernel and upgraded to 4.4.x.  Booting the 3.x kernel fixed it and I've since removed the 4.4, there is definitely something incompatible or a problem with the initramfs that comes with it.


text:
Q: get_called_class hack not working with eval-code I am using a ge_called_class hack for allowing late static binding in php version 5.2 (found here).
I have the following in my code:
# db_record.php
$ac = "ForumThread";
$objects = $ac::find("all");

This will not work in php 5.2 for some reason, so I have done this:
# db_record.php
$ac = "ForumThread";
eval("\$objects = {$ac}::find('all');");

This on the other hand will not work with the get_called_class function. I get an error that the file function can't read the evaled section of code.

A: If you're using eval, your solution is wrong.
Why won't your non-eval version work?  What is going wrong?  What is the full and complete error message?
The user-suppled version of get_called_class performs a backtrace and tries to open the caller's file to determine the class name.  The reason the eval fails is because the eval backtrace doesn't supply a filename.
(Edit: Also, that get_called_class hack is very much a hack.  Is there a reason you can't use 5.3?)
Have you tried using call_user_func?  call_user_func(array($ac, 'find'), 'all') should call the static method find for the class name contained in $ac with the paramater 'all'.  See also the callback pseudo-type, and the "Type 2" example in specific


text:
Q: Cannot start minikube I can't start minikube. Everything seems to be ok, but
When I open VirtualBox, and then click on 'minikube', it shows this...

I see the first picture, and minikube is not configured even after 5 minutes. So, how can I get minikube configured?

A: Error could be based on the environment settings too. So please provide additional information about it.
Nevertheless, check the minikube logs for more information.
minikube start --logtostderr --show-libmachine-logs
Hope this helps you figure out the issue.
I faced a similar situation with minikube. But then realized that my network blocked certain images from being pulled. My error looked something like this.
unable to pull sandbox image "gcr.io/google_containers/pause-amd64:3.0"
So in this case, I used a VPN connection and it resolved my issue.


text:
Q: Unbind Radeon > hand over to VFIO-PCI i have two Radeon GPUs (AMD R9 290 and AMD HD7870) i want to unbind the R9 290 from the radeon driver and hand over it to QEMUs VFIO-PCI driver. I'm using these commands:
echo 0000:06:00.0 > /sys/bus/pci/drivers/radeon/unbind
echo 1002 67b1 > /sys/bus/pci/drivers/vfio-pci/new_id
echo 0000:06:00.1 > /sys/bus/pci/drivers/snd_hda_intel/unbind
echo 1002 aac8 > /sys/bus/pci/drivers/vfio-pci/new_id

but my system freez after 5 seconds. I dont want bind the GPU to pci-stub because want to use two screens before i starting the VM. Like in this video: https://www.youtube.com/watch?v=17qxEpn4EGs
Can someone help me?
Best Regards

A: I am currently using this, it requires a lightdm restart though. Execute it from a different tty console, not within the lightdm session itself.
(CTRL+ALT+F# for a console, F7 is normally the xsession)
#!/bin/bash

read -n3 -rsp "Restart lightdm to unbind the GPU? [yes] " res
test "$res" != 'yes' && exit 1
echo

sudo service lightdm stop
sudo echo "1002 683d" > /sys/bus/pci/drivers/vfio-pci/new_id
sudo echo "1002 aab0" > /sys/bus/pci/drivers/vfio-pci/new_id
sudo echo "0000:01:00.0" > /sys/bus/pci/devices/0000:01:00.0/driver/unbind
sudo echo "0000:01:00.1" > /sys/bus/pci/devices/0000:01:00.1/driver/unbind
sudo echo "0000:01:00.0" > /sys/bus/pci/drivers/vfio-pci/bind
sudo echo "0000:01:00.1" > /sys/bus/pci/drivers/vfio-pci/bind
sudo echo "1002 683d" > /sys/bus/pci/drivers/vfio-pci/remove_id
sudo echo "1002 aab0" > /sys/bus/pci/drivers/vfio-pci/remove_id
sudo service lightdm start

echo "Rebind Audio"
sudo modprobe pci_stub
sudo echo "8086 8ca0" > /sys/bus/pci/drivers/pci-stub/new_id
sudo echo "0000:00:1b.0" > /sys/bus/pci/drivers/snd_hda_intel/unbind
sudo echo "0000:00:1b.0" > /sys/bus/pci/drivers/pci-stub/bind
sudo echo "8086 8ca0" > /sys/bus/pci/drivers/pci-stub/remove_id

# Check if VM drive is mounted
if ! grep -qs '/media/ljosalfur/VM' /proc/mounts; then
echo "Attempting to mount VM drive. I don't know how though."
#sudo mkdir /media/ljosalfur/VM
#sudo mount /dev/disk/by-id/0BD253F0-EF7F-6F40-BDD8-FABF85161762 /media/ljosalfur/VM
fi

sudo kvm -monitor stdio -vnc :0 \
-m 6G -mem-path /dev/hugepages \
-drive if=pflash,format=raw,file=./OVMF.fd -rtc base=localtime \
-cpu host -smp 6,sockets=1,cores=6,threads=1 \
-device vfio-pci,host=01:00.0,multifunction=on,x-vga=on \
-device vfio-pci,host=01:00.1 \
-device pci-assign,host=00:1b.0 \
-drive file=/media/ljosalfur/VM/vm7.img,format=raw,cache=writethrough \
-smb /media/ljosalfur \
-usb -usbdevice host:046d:c24a -show-cursor \
-usb -usbdevice host:1b1c:1b08

echo
echo "Re-Rebind Audio"
sudo echo "0000:00:1b.0" > /sys/bus/pci/drivers/pci-stub/unbind
sudo echo "0000:00:1b.0" > /sys/bus/pci/drivers/snd_hda_intel/bind

echo "Unbind GPU from vfio-pci"
sudo echo "0000:01:00.0" > /sys/bus/pci/drivers/vfio-pci/unbind
sudo echo "0000:01:00.1" > /sys/bus/pci/drivers/vfio-pci/unbind

read -n3 -rsp "Restart lightdm to rebind the GPU? [yes] " ress
test "$ress" != 'yes' && (exit 1)
echo
sudo echo "0000:01:00.0" > /sys/bus/pci/drivers/radeon/bind

I am looking for a workaround as restarting lightdm is not favourable, I think I will open a new question with different tags for this.

A: I wouldn't suggest you to do it like shown in the video. I bound it my graphics card to pci-stub driver in grub kernel parameters and plugged a second mouse and a second HDMI cable in my computer and switch the source on my monitor.
So here is my start script.
qemu-system-x86_64 -enable-kvm -m 10240 -cpu host,kvm=off \
-smp 4,sockets=1,cores=4,threads=1 \
-bios /home/qemu/.qemu/bios/ovmf.bin \
-soundhw hda \`
-usb -usbdevice host:046d:c53b \
-rtc base=localtime \
-hda /home/qemu/.qemu/boot/Windows8_1pro.img \
-hdb /home/qemu/.qemu/hdd/HDD1.img \
-device vfio-pci,host=01:00.0 -device vfio-pci,host=01:00.1 \
-vga none \`


text:
Q: tkinter PhotoImage doesn't exist? from tkinter import *

root = Tk()

photo = PhotoImage(file='blueface.png')
label = Label(root, image=photo)
label.pack()

root.mainloop()

The image face.png is in the same directory as this .py script, but when I run it, I get the following error:
 line 5, in <module>
    photo = PhotoImage(file='blueface.png')
 line 3539, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
 line 3495, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "face.png": no such file or directory

A: It doesn't matter very much that the image is in the same folder as the script, when you call the file like that without a path python assumes it's in the same folder that you were working on when you started the script. For example, if both the script and the image are in temp folder, and you started your script like this:
python temp/script.py

The interpreter doesn't realize that blueface.png is also in temp and looks for it in the folder that you were in, in this case the parent of temp
What you should do, is either use absolute paths, or use the __file__ to get the full script address first. For example:
photo = PhotoImage(file='/absolute/path/to/image/blueface.png')

Or using the current script's location to build the image's path:
import os
base_folder = os.path.dirname(__file__)
image_path = os.path.join(base_folder, 'blueface.png')
photo = PhotoImage(file=image_path)

A: Older versions of tkinter can not handle .png's that well. Try making the file a .gif. Or use the PhotoImage from PIL:
import tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()

photo = ImageTk.PhotoImage(Image.open('blueface.png'))
label = tk.Label(root, image=photo)
label.pack()

root.mainloop()


text: Q: Multiple trait entities in wit.ai I have created two entities in Wit. One is "sentiment" and one is "category". I've fed them both with labeled data through the HTTP API. Sentiment analysis was working great up until I have added the "category" entity. Now Wit only recognizes categories, it does not look for sentiments. Is it possible to extract two trait entities from a message?


text:
Q: Welch t-test when to declare equality I'm testing if one algorithm is faster than another. I can carry on increasing the sample and use the Welch t-test to see if one of them is faster to confidence level. My problem is when to stop and declare them equal. Is there a way to do this with a Welch t-test? I guess I may need to say they are equal if they are within a certain time tolerance (say 0.1%) for the given confidence interval?
Many Thanks

A: This is an interesting problem, and one that has broad relevance. The answer revolves around the notion that this is not at its core a statistical question.
Given a large enough sample, any trivial difference in the speed of your algorithms can be found to be statistically significant at any desired level of statistical significance. (Note that this is only the case when there is a real difference in the speeds. See my answer here:Why does frequentist hypothesis testing become biased towards rejecting the null hypothesis with sufficiently large samples?)
However, as your question implies, at some level a small enough difference is effectively no practical difference. Thus the trick is to decide on a threshold for 'not large enough to care about' rather than to fob off the responsibility for decision onto a statistical routine.
I suggest that you decide on either a fractional difference or maybe an absolute time difference for your threshold. Then make sure that your sample is large enough that the upper end of a confidence interval for the difference between the mean speeds does not cross that threshold. (What level should your confidence interval be? That depends on the consequences of the decision might be, so note that you do not have to use a 95% interval.)


text:
Q: How would I render html tags inserted via compile in AngularJS? I am creating a UI that would allow a user to create preview html content.
For the purposes of this question, lets say I have the following array of objects:
modules = [
    {
        id: 0,
        type: 'title',
        content: 'This is the title',
        subtitle: 'This is the subtitle'
    },
    {
        id: 1,
        type: 'intro',
        content: 'This is the intro copy. This is the intro copy!'
    },
    {
        id: 2,
        type: 'title',
        content: 'This is the title'
    }
];

I have created a directive that loops through the objects to choose a template based on the type and uses $compile to render the different modules.
app.directive('module', function( $compile ){

    // Define templates as strings
    var titleTemplate = '
' +
                            '{{ module.content }}' +
                        '
' +
                        '
{{ module.subtitle }}
';

    var introTemplate = '
' +
                            '{{ module.content }}' +
                        '
' +
                        '
{{ module.secondContent }}
';

    // Select the current template by value passed in through scope.module.type

    var getTemplate = function(moduleType) {

        var template = '';

        switch(moduleType) {
            case 'title':
                template = titleTemplate;
                break;
            case 'intro':
                template = introTemplate;
                break;
            case 'ribbon':
                template = ribbonTemplate;
        }

        return template;

    };

    // Pass the scope through to the template for access in the module

    var linker = function( scope, element, attrs ) {
        element.html( getTemplate( scope.module.type ) ).show();
        $compile( element.contents() )( scope );
        console.log(attrs);
    };

    return {
        restrict: 'E',
        link: linker,
        replace: true,
        scope: {
            module : '='
        }
    }
});

and finally, in the html I have
<module module="module" ng-repeat="module in modules"></module>

The issue that I have run into is that when I have an html element in the content, such as the intro copy in modules[1].content, the element is rendered as a string, instead of bolding the text like intended.

A: To interpret HTML from a var in angular you need to use the ng-bind-html directive. It will interpret the HTML instead of just showing it as a string.
Exemple :
$scope.myhtmlvar = "I'm bold</b";

This looks good but will actually not work. Why ? For a good reason : interpreting HTML is not safe. Just imagine interpreting the whole html, the user can add as much javascript as he want and can completely inject his own behaviours and hack your application. To avoid this problem you will need to add the ngSanitize angular library into your project.
https://ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-sanitize.js

And register it into your app
var app = angular.module('testApp', ['ngSanitize']);

From now your ng-bind-html will automatically sanitize the html you're giving him. The two lines ahead should now work.
Here is a working plunker as exemple
Hope it helped.


text:
Q: how to use akka's scheduler in play 2.0 application? I want to use akka's scheduler in my play 2.0(using java) framework application to send email reminders on a particular date and time.I am new to play 2.0. Please tell me the procedure to use the akka scheduler in play 2.0 framework if anyone knows (in detailed) ?
Thanks in advance.

A: I'm new as well, and have another question related to Akka in Scala. But while reading i found that this might be helpful to you: http://www.playframework.org/documentation/2.0/JavaAkka and perhaps this as well: https://github.com/playframework/Play20/wiki/JavaAsync

A: Module Class
import com.google.inject.AbstractModule
import play.api.libs.concurrent.AkkaGuiceSupport

class JobModule extends AbstractModule with AkkaGuiceSupport {
  def configure() = {
    bindActor[JobBucket]("job-bucket-actor")
    bind(classOf[Scheduler]).asEagerSingleton()
  }
}

Scheduler Class
import javax.inject._
import akka.actor._
import scala.concurrent.ExecutionContext
import scala.concurrent.duration._

class Scheduler @Inject()(val system: ActorSystem, @Named("job-bucket-actor") val jobBucketActor: ActorRef)(implicit ec: ExecutionContext) {
  system.scheduler.schedule(0.microseconds, 1.day, jobBucketActor, "cleanBucket")
}

JobBucket (You can create multiple jobs in this class and call them by passing different messages to the receive method.)
import javax.inject._
import akka.actor.Actor
import org.apache.commons.io.FileUtils
import play.api.Logger

// You can inject any service class or other class if it's required
@Singleton
class JobBucket extends Actor {
  def receive = {
    //You can place n number of cases.
    case "cleanBucket" => clean()
  }

  def clean(): Unit = {
    //Do whatever you want to do over here.
    Logger.info("This task has been scheduled...!!!")
  }
}

You'll also need to add a line in apllication.config file:
play.modules.enabled += "com.abc.xyz.JobModule"


text:
Q: I get data from firebase database and save to ArrayList, but when i run progrem it is null     String currentUserID = Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid();
    dataRef = FirebaseDatabase.getInstance().getReference();

    //lấy dữ liệu chats của người dùng về
    dataRef.child("Chats").child(currentUserID).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot: dataSnapshot.getChildren()){
                for (DataSnapshot snapshot1 : snapshot.getChildren()){
                    Chats chat = snapshot1.getValue(Chats.class);  //I got chat here
                    Chat.add(chat);                                // and I save it into ArrayList
                }
            }
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

    //Lấy ra các ID của nhưng người đã nhắn tin để đoạn dưới lấy tên -_-
  ArrayList<String> listIdUserChat = new ArrayList<>();
    for(Chats chat: Chat){                                          //But here ArrayList Chat is null
       String ID = chat.getFrom();
      if(!ID.equals(currentUserID)){
           if(!listIdUserChat.contains(ID)) {
                listIdUserChat.add(ID);
            }
       }
    }

.............
When i debug

Why is it like that and how do I fix it?
  Sorry because my English not good and I'm an amateur. Thanks all.


text:
Q: SAPUI5 to Java HttpServletRequest.getUserPrincipal() returns null I'm trying to authenticate users in my java backend. I'm trying to connect to my backend with SAPUI5. I added two roles in the SCP Portal and I want to access them in Java. I'm using HttpServletRequest.getUserPrincipal() to get the user, but it keeps returning null. Any ideas on how to solve this? Did I forget something in SAPUI5?
package be.amista.filters;

import java.io.IOException;
import java.security.Principal;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sap.security.um.service.UserManagementAccessor;
import com.sap.security.um.user.User;
import com.sap.security.um.user.UserProvider;

@WebFilter("/*")
public class UserFilter implements Filter {
 private static final Logger logger = LoggerFactory.getLogger(UserFilter.class);
 private static Set<String> userRoles;

 public void destroy() {
 }

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
   HttpServletRequest httpServletRequest = (HttpServletRequest) request;

  if (httpServletRequest.getUserPrincipal() != null) {
   try {
       // UserProvider provides access to the user storage
       UserProvider users = UserManagementAccessor.getUserProvider();

       // Read the currently logged in user from the user storage
       User user = users.getUser(httpServletRequest.getUserPrincipal().getName());
       userRoles = user.getRoles();
     } catch (Exception e) {
       // Handle errors
      logger.error(e.getMessage());
     }
  }
  // pass the request along the filter chain
  chain.doFilter(request, response);
 }

 public void init(FilterConfig fConfig) throws ServletException {
 }

 public static Set<String> getUserRoles() {
  return userRoles;
 }
}

A: I found a solution myself. I added this piece of code to the web.xml and it worked.
<resource-ref>
    <res-ref-name>user/Provider</res-ref-name>
    <res-type>com.sap.security.um.user.UserProvider</res-type>
</resource-ref>
<resource-ref>
    <res-ref-name>connectivityConfiguration</res-ref-name>
    <res-type>com.sap.core.connectivity.api.configuration.ConnectivityConfiguration</res-type>
</resource-ref>
<login-config>
    <auth-method>FORM</auth-method>
</login-config>
<security-constraint>
    <web-resource-collection>
        <web-resource-name>Protected Area</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>Everyone</role-name>
    </auth-constraint>
</security-constraint>
<security-role>
    <description>All SAP Cloud Platform users</description>
    <role-name>Everyone</role-name>
</security-role>


text:
Q: Desconecta frequentemente Laravel App Criei um CMS sobre a plataforma do Laravel 5.2, criado todo o sistema de usuário (login, register, reset pass, logout), porém o usuário desconecta frequentemente, já desabilitei o Middleware VerifyCsrfToken porém nada acontece.
Isso acontece do nada, ao atualizar alguma página, já alterei o lefttime para 1200000 e de nada adiantou, ele é redirecionado para a Rota de login.
O que vocês acham que pode ser?


text:
Q: How to embed iframe without breaking floated layout? I'm embedding a YT video (iframe) within my floated layout and it's breaking the float. The right div complete disappears from view.
Its a simple layout:

|content| left | middle | right | /content |
FIDDLE
HTML

CSS
#container {
width: 100%;
background-color: gray;
height: 200px;
}
#left {
width: 25%;
height: 190px;
background-color: green;
float: left;
}
#middle {
height: 190px;
width: 50%;
background-color: purple;
float: left;
}
#right {
width: 25%;
height: 190px;
background-color: orange;
float: left;
}
#content {
width: 80%;
height: 200px;
margin: auto;
}

A: You haven't closed the iframe correctly with the required
http://jsfiddle.net/David_Knowles/vkhse/

A: You have a few problems with your markup:

*

*The  is not closed correctly.

*The #container div is not closed (but it might be that you did not copy the last line).

*The type attribute for  does not exist.

*The frameborder attribute is deprecated: use CSS.

If you need to embed a YT video, then simply click on Share, then Embedded HTML under a video.

A: For anyone who's still having problems even with the closing tag, try sticking something in between the tags, eg:
(Worked for me.)


text:
Q: SQL Escape '#' Symbol I have a SQL query that inserts data to the database.
Below is my sample data:

*

*OrderID: 1

*Email: #TestDistribution
However, when I am trying to insert the OrderID and Email values to the table but the '#' cannot be read by SQL Server.
So that, how would I escape it?
I have an idea of apostrophe's can be escaped using CHAR(29) and what would be the equivalent for #?
Below is my query:
INSERT INTO orders(orderid,email) VALUES(1,'#TestDistribution')

Below is the table structure:
orders

*

*orderid: int

*email: nchar(150)
There is no error raised by the server, but upon checking the orders table, the data was not inserted.

A: Works fine for me on SQL Server 2008 using:
Create/Insert:
CREATE TABLE yourtable
    ([OrderID] int, [Email] nvarchar(99))
;

INSERT INTO yourtable
    ([OrderID], [Email])
VALUES
    (1, '#TestDistribution')
;

Select:
SELECT * FROM yourtable

Output:
OrderID Email
1       #TestDistribution

A: you'vve got two ' a the end
try
 INSERT INTO orders(orderid,email) VALUES(1,'#TestDistribution')

A: Make sure that your column type should be varchar
create table orders(orderid int(30),email varchar(30));
insert into orders value(1,'#TestDistribution');
select * from orders;

A: Thank you for posting your answers here. The issue has been resolved already. I found out that there were some settings in my server which restricts special characters.
Apologies.
Thank you everyone!


text:
Q: Need advice? What to choose Servlets or Spring MVC? I have an application in mind which I want to develop. I am targeting the application for a big user base, consider it as a social app. But I am not
sure whether to write it with Servlets or Spring MVC.
I have a good grip on Servlets, it would be easy for me to develop, but when it comes to Spring I am still novice.
I am not clear what difference would it make if the app is developed on Servlets rather than Spring MVC.
Scalability or some factors like that?
Any advice would be appreciated. Thanks

A: Its always good to go for Spring framework as it provides:

*

*Dependency Injection support

*Spring MVC: easy to customize

*Data access support

*Spring Security

*AOP support etc..

Clearly, Spring provides more functionality than servlets. But if your app is very simple enough, you can go for Servlets.

A: It might take you some time to learn Spring but..., once you do, it will provide powerful tools to code.