text:
Q: Controllable React Bootstrap Carousel component not working Here is the code in the component I am getting the error at the bottom.
This is where I got the controllable Carousel code from: https://react-bootstrap.github.io/components/carousel/
Anyone know why I am getting this error? I cannot se how the handleSelect method is wrong...
import React, { Component } from 'react';
import Carousel from 'react-bootstrap/Carousel'

class CarouselComponent extends Component {

    setIndex = (selectedIndex) => {
    this.setState({index: selectedIndex})
    }

    setDirection = (direction) => {
        this.setState({direction: direction})
    }

    handleSelect = (selectedIndex, e) => {
        this.setIndex(selectedIndex);
        this.setDirection(e.direction);
    }

    constructor(props) {
        super(props);
        this.state = {
            index: 0,
            setIndex: 0,
            direction: null,
            setDirection: null
        };
    }

    render() {
        const { index, direction } = this.state;
        return (

                <Carousel activeIndex={index} direction={direction} onSelect={this.handleSelect}>
                    <Carousel.Item>

                        <Carousel.Caption>

First slide label

Nulla vitae elit libero, a pharetra augue mollis interdum.

                        </Carousel.Caption>
                    </Carousel.Item>
                    <Carousel.Item>

                        <Carousel.Caption>

Second slide label

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

                        </Carousel.Caption>
                    </Carousel.Item>
                    <Carousel.Item>

                        <Carousel.Caption>

Third slide label

                                Praesent commodo cursus magna, vel scelerisque nisl consectetur.

                        </Carousel.Caption>
                    </Carousel.Item>
                </Carousel>

        );
    }

}

export default CarouselComponent;

Here is the error I am getting.
./src/components/CarouselComponent.jsx
  Line 7:  Parsing error: Unexpected token

   5 | class CarouselComponent extends Component {
   6 |
>  7 |    function handleSelect(selectedIndex, e) {
     |             ^
   8 |     setIndex(selectedIndex);
   9 |     setDirection(e.direction);
  10 | }

A: Syntax error. Have a look at the below snippet.

import React, { Component } from 'react';
import Carousel from 'react-bootstrap/Carousel'

class CarouselComponent extends Component {

    setIndex = () => {
    //Implement method
    }

     setDirection = () =>  {
        //Implement method
     }

   handleSelect = (selectedIndex, e) => {
    this.setIndex(selectedIndex);
    this.setDirection(e.direction);
    }

constructor(props) {
    super(props);
    this.state = {
        index: 0,
        setIndex: 0,
        direction: null,
        setDirection: null
    };
}

render() {
    const {index, direction} =  this.state;
    return (

    <Carousel interval={false} activeIndex={index} direction={direction} onSelect={this.handleSelect}>
                <Carousel.Item>

                    <Carousel.Caption>

First slide label

Nulla vitae elit libero, a pharetra augue mollis interdum.

                    </Carousel.Caption>
                </Carousel.Item>
                <Carousel.Item>

                    <Carousel.Caption>

Second slide label

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

                    </Carousel.Caption>
                </Carousel.Item>
                <Carousel.Item>

                    <Carousel.Caption>

Third slide label

                            Praesent commodo cursus magna, vel scelerisque nisl consectetur.

                    </Carousel.Caption>
                </Carousel.Item>
            </Carousel>

    );
}

}

export default CarouselComponent;


text:
Q: Is there a way to remove Jupyter "Run Cell" buttons in Visual Studio Code? I want to remove the Jupyter "Run Cell|Run All Cells" buttons that appear if the syntax #%% is present in Visual Studio Code.

Is there a setting that controls that?

A: If you turn off the data science features (the Python Interactive window) under Settings>Python>Data Science>Enabled then you won't see those code lenses any more. However that will also hide the rest of the data science features along with the lenses. Were you looking to turn off all data science features in the python extension or just the lenses?

A: Update for others coming to this question:
With recent update you can choose what's displayed Run cell |...".
If you're looking to remove clutter delete everything and save like below:

I would recommend leaving at least python.datascience.runcell as it seems to disable shift+enter shortcut

A: You can toggle off Python>Data Science: Enable Cell Code Lens settings.

A: Save the code snippet below as : remove_inline_comment.py
Assuming your filename as : sample_file.py,
RUN : python remove_inline_comment.py sample_file.py
[ NOTE : Make sure both of these files are in same folder ]
import argparse
import os
import sys
import re

def process(filename):
    """Removes empty lines and lines that contain only whitespace, and
    lines with comments"""

    with open(filename) as in_file, open(filename, "r+") as out_file:
        for line in in_file:
            if re.match("# In\[[0-9\\d+\]]", line):
                out_file.write("\n")
            else:
                out_file.writelines(line)

if __name__ == "__main__":

    my_parser = argparse.ArgumentParser(
        description="Removing the In#\[[0-9\d+\]] in notebook to script conversion"
    )

    my_parser.add_argument(
        "script_path",
        metavar="path",
        type=str,
        help="path to script that requires a conversion",
    )

    args = my_parser.parse_args()
    script_path = args.script_path

    file_format = script_path.split(".")[1]
    if file_format != "py":
        print("File is not a py file")
        sys.exit()

    try:
        print(f"processing : {script_path}")
        process(script_path)
    except FileNotFoundError:
        print("Please provide path correctly")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot using SQLDataProvider if SET @VARIABLE from query I have a lot of query in my Mysql Database. Thte query is like this adn working fine.
 SET @cleaning = 'cleaning';
        SET @one_bar = 'one bar';
        SET @test_periodic = 'test_periodic';
        SET @repairs = 'repair';

        SELECT ir.id, ir.no_surat, @cleaning as tagihan,tc.`level`, tc.cleaning as nominal FROM ydepotras_estimator.repair_estimate re
        LEFT JOIN ydepotras_estimator.inspection_report ir
        ON re.inspection_id = ir.id
        INNER JOIN ydepotras_finance.tagihan_cleaning tc
        ON re.id = tc.repair_estimate_id

        UNION ALL

        SELECT ir.id, ir.no_surat,  @one_bar as tagihan, tob.`level`, tob.one_bar as nominal
            FROM ydepotras_estimator.repair_estimate re
        LEFT JOIN ydepotras_estimator.inspection_report ir
        ON re.inspection_id = ir.id
        INNER JOIN ydepotras_finance.tagihan_one_bar tob
        ON re.id = tob.repair_estimate_id
        UNION ALL

        SELECT ir.id, ir.no_surat,  @test_periodic as tagihan,
                ttp.`level`, IFNULL(ttp.years2,ttp.years5)  as nominal
            FROM ydepotras_estimator.repair_estimate re
        LEFT JOIN ydepotras_estimator.inspection_report ir
        ON re.inspection_id = ir.id
        INNER JOIN ydepotras_finance.tagihan_test_periodic ttp
        ON re.id = ttp.repair_estimate_id
        GROUP by ttp.id
        UNION ALL
        SELECT ir.id, ir.no_surat,  @repairs as tagihan,
                tr.`level`, tr.`repair` as nominal
            FROM ydepotras_estimator.repair_estimate re
        LEFT JOIN ydepotras_estimator.inspection_report ir
        ON re.inspection_id = ir.id
        INNER JOIN ydepotras_finance.tagihan_repair tr
        ON re.id = tr.repair_estimate_id
        ORDER BY no_surat

Now Yii2 is turn on.
This query will be turn into $dataProvider  and then, it's so much complicated if using  ActiveRecord.
I prefer to use SQLDataProvider like this :
$query = 'The query from above'

 $dataProvider  = new SqlDataProvider([
        'sql' => $query,
        'totalCount' => 100,
    ]);

 return $dataProvider->getModels();

But it gives me :
Database Exception – yii\db\Exception
  SQLSTATE[HY000]: General error

A: Do the fact you don'assign dinamically value to yours mysql var  you could use directly the values instead of var
    SELECT ir.id, ir.no_surat, 'cleaning' as tagihan,tc.`level`, tc.cleaning as nominal FROM ydepotras_estimator.repair_estimate re
    LEFT JOIN ydepotras_estimator.inspection_report ir
    ON re.inspection_id = ir.id
    INNER JOIN ydepotras_finance.tagihan_cleaning tc
    ON re.id = tc.repair_estimate_id

Or use  binding param
  $params = [':cleaning' => 'cleaning];
  $sql= Yii::$app->db->createCommand("
          SELECT ir.id, ir.no_surat, :cleaning as tagihan,tc.`level`, tc.cleaning as nominal FROM ydepotras_estimator.repair_estimate re
          LEFT JOIN ydepotras_estimator.inspection_report ir
          ON re.inspection_id = ir.id
          INNER JOIN ydepotras_finance.tagihan_cleaning tc
          ON re.id = tc.repair_estimate_id )
             ->bindValues($params);


text:
Q: Setting a character uneditable in a JFormattedTextField Is there a way, if so how, to set a single character within a FormattedJTextField as uneditable? I am trying to format a JTextField for currency and have read quite a few articles such as this, though it doesn't seem to clarify what I am trying to achieve.
What I am trying to create is a JTextField which will always have the "£" sign within it and will allow the user to enter there chosen price. As a result of this, I thought maybe a way to accomplish this was to the the "£" as uneditable whereas the rest of the JTextField can be edited.
An example:
categoryB = new JLabel("Category B: ",JLabel.CENTER);
centerP.add(categoryB);
categoryBText = new JTextField("");
centerP.add(categoryBText);
contentP.add(centerP);
setPriceFrame.setVisible(true);

When the GUI is opened, I want categoryBTextto always start with a "£" and is not removable from the JTextField.
Is there a better way to approach this?
Solution:
try {
   MaskFormatter catA£ = new MaskFormatter("£###.##");
   catA£.setPlaceholderCharacter(' ');
   categoryAText = new JFormattedTextField(catA£);
   centerP.add(categoryAText);
} catch (Exception ex) {
}


text:
Q: Plotting several spheres on the same graph I am writing code to plot spheres. I am generating random points using a separate function and I would like to add these as spheres to the same graph. For the moment, separate graphs are created for each sphere. The code is shown below. Disk here is a list of the form [x, y, z]. Also, is it possible to make the length of the x, y, and z axes equal? Many thanks.
def plot_disks2(disk, radius, c, ax=None):
    fig = plt.figure(figsize=(12,12), dpi=300)
    ax = fig.add_subplot(111, projection='3d')

    u = np.linspace(0, 2 * np.pi, 100)
    v = np.linspace(0, np.pi, 100)

    x = radius * np.outer(np.cos(u), np.sin(v))
    y = radius * np.outer(np.sin(u), np.sin(v))
    z = radius * np.outer(np.ones(np.size(u)), np.cos(v))

    ax.plot_surface(x+disk[0], y+disk[1], z+disk[2],  rstride=4, cstride=4, color=c, linewidth=0, alpha=0.5)

A: In brief, is recommendable that you use a function to generate data and other one for plotting, as follows:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

def disks2(disk, radius):
    u = np.linspace(0, 2 * np.pi, 100)
    v = np.linspace(0, np.pi, 100)
    x = radius * np.outer(np.cos(u), np.sin(v))
    y = radius * np.outer(np.sin(u), np.sin(v))
    z = radius * np.outer(np.ones(np.size(u)), np.cos(v))
    return x+disk[0],y+disk[1],z+disk[2]

def plotting_spheres(data, colors):
    fig = plt.figure(figsize=(12,12), dpi=300)
    ax = fig.add_subplot(111, projection='3d')
    for k,sph in enumerate(data):
        x, y, z = sph[0], sph[1], sph[2]
        ax.plot_surface(x, y, z,  rstride=4, cstride=4,
                        color=colors[k], linewidth=0, alpha=0.5)
    ax.set_aspect("equal")
    plt.show()

N = 5 # spheres
points = np.random.randint(1,10,(N,3))
rs = np.random.random((N,1))
colors = ("r","g","b","y","m")

data = [disks2(points[k,:], rs[k]) for k in range(N)]
plotting_spheres(data, colors)

For axes aspect can you use the set_aspect method.


text:
Q: Only copy newer files with CopyWebpackPlugin I'm copying lots of files using the CopyWebpackPlugin, and I want them to be copied only if the files at the destination are older. The same as was common in grunt / gulp.
new CopyWebpackPlugin({
  patterns: [
    { from: "./node_modules/jquery/dist/jquery.min.js", to: "./libs/" },
  ],
}),

But the output always shows:

asset libs/jquery.min.js 87.4 KiB [compared for emit] [from: node_modules/jquery/dist/jquery.min.js] [copied]

which implies that it copies it each time.
How do I make it copy only if the destination is missing or the source is newer?


text:
Q: What are the differences in importing css using these three techniques? Is There any difference to import to an Angular project a CSS lib (eg bootstrap) considering the options below:
Angular.json (npm)
"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "styles.scss"
]

Angular.json (CSS file locally)
"styles": [
  "assets/lib/bootstrap/dist/css/bootstrap.min.css",
  "styles.scss"
]

styles.scss (CSS file locally)
@import "assets/lib/bootstrap/css/bootstrap.min.css";

A: I suggest the first solution, because:

*

*All three will end up in main CSS bundle

*But 2. and 3. will also have original bootstrap inside assets. Even though it's used in bundle, it won't be removed from assets - which are a part of a build as it is.

Also, if you update Bootstrap it's way easier doing so by NPM.


text:
Q: I can't find my husband or my follower I married Marcelo and I told him to move to Breezehome. I keep going there but he's not there. I've gone to the temple of Mara and to the Bee and Bard in Riften. I don't know where he is.  Where's my husband?
Also I can't find Cicero I spared him and lied to Astrid so he'd be my follower but I don't know where he is.


text:
Q: Eloquent: get changed columns I need to log updated columns using Eloquent getChanges, It works just fine when use it in the same code context right after ex: updateOrCreate, but when call it from the "provider" it returns empty array, example of boot in service provider:
   public function boot()
    {
        User::updating(function ($user) {
            dd($user->getChanges()); //empty array
        });
    }

A: I get the problem I should use User::updated instead, ex:
public function boot()
{
    User::updated(function ($user) {
        dd($user->getChanges());
    });
}


text:
Q: Java how to call paint in actionperform am try to call paint in action perform but it not work
btnNewButton_5.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            class MyCanvas extends JComponent {

                public void paint(Graphics g) {
                    g.drawLine(10,20,50,60);
                }
            }

            JFrame window = new JFrame();
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            window.setBounds(30, 30, 300, 300);
            window.getContentPane().add(new MyCanvas());
            window.setVisible(true);

        }
    });

problem is it show only frame but rectangle doesn't draw
how can i edit this code help me

A: First you should implement the paint() method on your class and then it is recall as simple function call use repaint() method on ActionListener.


text:
Q: while(true) in javascript - how does it work I've written this code for a Binary Search Tree. For the most part I understand how it works when it comes to inserting nodes. What I don't quite get is the while(true) part.
I'm used to comparing some sort of value when using while loops.
For this code, how does it work?
Is it because I'm setting current and the while loop goes back and checks if that matches the value passed? is that how the while loop works with true?

class Node {
  constructor(val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

class BinarySearchTree {
  constructor() {
    this.root = null;
  }
}

BinarySearchTree.prototype.insert = function(value) {
  const newNode = new Node(value);

  if (this.root === null) {
    this.root = newNode;
  }

  let current = this.root;

  while(true) {
    if (value === current.val) return;

    if (value < current.val) {
      if (current.left === null) {
        current.left = newNode;
      }

      current = current.left;
    } else {
      if (current.right === null) {
        current.right = newNode;
      }

      current = current.right;
    }
  }
}

let tree = new BinarySearchTree();
tree.insert(10)
tree.insert(5)
tree.insert(13)
tree.insert(11)
tree.insert(2)
tree.insert(16)
tree.insert(7)

console.log(tree);

A: The insert function will iterate, if there are nodes, until it finds a place to put the new node -- either current.right or current.left. After that it will set the current node to either left or right. This means in the next iteration it will check if current.value === value and if true the while(true) infinite loop will be exited which is done by the "return" you could also use "break" instead.
Read this (Does return stop a loop?) to understand how the "return;" works.
Edit: To clear it up, "return" and "break" have different functions but in your case both have the same effect.

A:
For this code, how does it work? there's nothing in the code other than it returning when the same number is inserted. how does it break out of the loop?

It returns.
A return will exit the current function.
That overrides a loop inside the function.


text:
Q: copy a character array from a pointer variable VOID change(CHAR *TP, CHAR *FR, BOOL Vw)
{
CHAR *User, *NU, *CU = NULL, *Ref = NULL;
int Loop = 0;
<Some lines of code>

   if(Loop == 0)
      memcpy(Ref, FR, strlen(FR)+1);

   CU = NU;
   Loop++;
}
   if(CU)
   free(CU);

}// end of function

Ok so as you can see... the FR is a pointer to a character array.. and each time it sends the memory location..
and I  have to copy it to Ref..
But all these are pointer variables..
What I need to do is.. I need to make a character array Lets say
AZ and it will contain,
AZ = the character array FR points to + "/abcd" +
then i will do a memcpy of AZ to Ref...
My problem is the FR variable is a pointer and I cant understand how to put that into a character array and then add characters to the final array..

A: Make sure that Ref has enough memory allocated to hold the strings that you want to concatenate.
Then you can use the strcpy() function to copy the first string to Ref, and strcat() to concatenate additional strings. For example:
strcpy(Ref, AZ);
strcat(Ref, "/abcd");
strcat(Ref, more_stuff);


text:
Q: Is $\operatorname{Hom}(E,M)$ simple as an $\operatorname{End}(M)$-module if $E$ is simple? Let $R$ be a ring, let $M$ be an $R$-module and let $R' := \operatorname{End}_R(M)$.
Let $E$ be a simple $R$-module with $\operatorname{Hom}_R(E,M) \neq 0$.

Question:
  Is $\operatorname{Hom}_R(E,M)$ simple as an $R'$-module?

Background:
While trying to understand (a version of) the double centralizer theorem I learned that the $E$-isotypical component of $M$ can be described as $M_E \cong \operatorname{Hom}_R(E,M) \otimes_{\operatorname{End}_R(E)} E$ as an $(R' \otimes_{\mathbb{Z}} R)$-module.
Because $M_E$ is simple as an $(R' \otimes_{\mathbb{Z}} R)$-module I am wondering about the $R'$-simplicity of the tensor factor $\operatorname{Hom}_R(E,M)$.
I think the statement holds if $M$ is semisimple:
We can then assume that $M = M_E \cong E^{\oplus I}$ for some index set $I$ (because every $R$-endomorphism of $M_E$ extends to an $R$-endomorphism of $M$).
For the skew field $D := \operatorname{End}_R(E)$ we then have that $R' \cong \operatorname{M}_I(D)$ (the algebra of column-finite $(I \times I)$-matrices) and $\operatorname{Hom}_R(E,M) \cong D^{\oplus I}$, with $\operatorname{M}_I(D)$ acting transitively on $D^{\oplus I} \smallsetminus \{0\}$.
I assume that the statement does not hold for general $M$, but I haven't found a counterexample.
Any help is welcome.

A: Let $k$ be a field, let $R=k[x,y]$, and let $I$ be the maximal ideal $(x,y)\subset R$.  Let $M=R/I^2$, and let $E=R/I$.  Then $R'$ is just the quotient ring $R/I^2$ and $\operatorname{Hom}_R(E,M)$ is naturally identified with $I/I^2$.  This is not a simple $R'$-module, since $x$ and $y$ act trivially on it so that submodules are the same thing as $k$-subspaces, and $\dim_k I/I^2=2$ ($x$ and $y$ are a basis).
(The key point is that the submodule $N$ of $M$ spanned by copies of $E$ is a direct sum of copies of $E$, but not every $\operatorname{End}_R(E)$-endomorphism of it extends to an endomorphism of $M$.  In this case, $N\cong E^2$ and $\operatorname{End}_R(E)\cong k$, but $R'$ only contains the diagonal action of $k$ on $E^2$, not the full $M_2(k)$ action, since in $M$ the two copies of $E$ in $N$ are actually both multiples of a single generator over $R$.)


text:
Q: как методом __str__ задать количество отображаемых символов объекта? Мне необходимо в данном классе, при выводе на страницу, оставить только первые 15 символов текста. Вот что я написал на данный момент, но этот метод не работает:
PRE_TEXT_LEN: int = 15

class Post(models.Model):
    """Класс постов с сообщениями."""
    text = models.TextField(verbose_name='Текст')
    pub_date = models.DateTimeField(
        auto_now_add=True,
        verbose_name='Дата публикации'
    )
    group = models.ForeignKey(
        Group,
        blank=True,
        null=True,
        on_delete=models.CASCADE,
        related_name='posts',
        verbose_name='Группа'
    )
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='posts',
        verbose_name='Автор'
    )

    def __str__(self) -> str:
        return f'{ self.text[:PRE_TEXT_LEN] }'

необходимо использовать метод __str__. Если кто знает как правильно можно это сделать?
def index(request):
    """Главная страница."""
    header = 'Это главная страница проекта Yatube'
    title = 'Последние обновления на сайте'
    posts = Post.objects.order_by('-pub_date')[:ORDER_OBJECTS]
    context = {
        'posts': posts,
        'title': title,
        'header': header,
    }
    return render(request, 'posts/index.html', context)

index.html
{% extends 'base.html' %}
{% block content %}

{{ header }}

    {% for post in posts %}

          Автор: {{ post.author.get_full_name }}

          Дата публикации: {{ post.pub_date|date:"d E Y" }}

        {{ post.text }}

    {% if post.group %}
      все записи группы
    {% endif %}
      {% if not forloop.last %}
{% endif %}
    {% endfor %}

{% endblock %}


text:
Q: strategy / payoff matrix I am trying to create a strategy matrix in LaTeX such as

Any suggestion would be greatly appreciated. I would like there to be two values in each cell, aligned as in this diagram.

A: Here is a solution using tabular (a tikz solution follows).
\begin{tabular}{ccccc}
&&\multicolumn{2}{c}{Payoff Matrix}\\
&&\multicolumn{2}{c}{Firm B}\\
&&Low Price&High Price\\
\cline{3-4}
\raisebox{-0.25cm}{\rotatebox{90}{A}}&\multicolumn{1}{p{1cm}}{Low Price}&
\multicolumn{1}{|p{1.5cm}}{\hfill $10$\newline $10$\hfill}&
\multicolumn{1}{|p{1.5cm}|}{\hfill $5$\newline $25$\hfill}\\
\cline{3-4}
\raisebox{-0.25cm}{\rotatebox{90}{Firm}}&\multicolumn{1}{p{1cm}}{Low Price}&
\multicolumn{1}{|p{1.5cm}}{\hfill $5$\newline $25$\hfill}&
\multicolumn{1}{|p{1.5cm}|}{\hfill $20$\newline $20$\hfill}\\\cline{3-4}
\end{tabular}

Here is the result

Here is a tikz solution: (note: I fixed an alignment problem in the code, but I did not update the picture)
\documentclass{minimal}

\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{matrix}
\usetikzlibrary{positioning}

\begin{document}

\begin{tikzpicture}

\matrix[matrix of math nodes,every odd row/.style={align=right},every even row/.style={align=left},every node/.style={text width=1.5cm},row sep=0.2cm,column sep=0.2cm] (m) {
10&5\\
10&25\\
5&20\\
25&20\\
};
\draw (m.north east) rectangle (m.south west);
\draw (m.north) -- (m.south);
\draw (m.east) -- (m.west);

\coordinate (a) at ($(m.north west)!0.25!(m.north east)$);
\coordinate (b) at ($(m.north west)!0.75!(m.north east)$);
\node[above=5pt of a,anchor=base] {Low Price};
\node[above=5pt of b,anchor=base] {High Price};

\coordinate (c) at ($(m.north west)!0.25!(m.south west)$);
\coordinate (d) at ($(m.north west)!0.75!(m.south west)$);
\node[left=2pt of c,text width=1cm]  {Low Price};
\node[left=2pt of d,text width=1cm]  {High Price};

\node[above=18pt of m.north] (firm b) {Firm B};
\node[left=1.6cm of m.west,rotate=90,align=center,anchor=center] {Firm A};

\node[above=5pt of firm b]  {Payoff Matrix};
\end{tikzpicture}

\end{document}

The result is


text:
Q: How know space disk left WITHOUT root I'd like to know if there is a way to get free space disk of a unix (debian) system without root (sudo) and if possible in only one command ?

A: Depends on what "free space" are you trying to get.
df provides information about free space for mounted filesystems and it doesn't require root:
$ df -h
Filesystem                           Size  Used Avail Use% Mounted on
devtmpfs                             717M     0  717M   0% /dev
tmpfs                                737M     0  737M   0% /dev/shm
tmpfs                                295M  1,3M  294M   1% /run
/dev/mapper/fedora-root               17G   11G  5,4G  67% /
tmpfs                                737M  9,5M  727M   2% /tmp
/dev/sda1                            976M  285M  625M  32% /boot

If you want to know how much free/unallocated space is on each disk (space not occupied by partitions), you need to use tools like parted or fdisk and you need root privileges for that. lsblk can help, but it doesn't print free space:
$ lsblk /dev/sdb
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sdb      8:16   0    1G  0 disk
├─sdb1   8:17   0  100M  0 part
├─sdb2   8:18   0  512B  0 part
└─sdb3   8:19   0  100M  0 part

But you can assume from its output that sdb here has approximately 800 MiB of free space for a new partition.
You can get better picture with UDisks, which also has information about partition layout, GNOME Disks uses this data to display free space on disks:

UDisks doesn't have a simple way to display this. You'd need to use its DBus API and calculate the free space yourself.


text:
Q: Need An Explanation of Steps to Rotate AV Camera So I am having an issue with rotations. I have an AV Camera set up to display in a view controller. Now I know there are a lot of components that went into this, that is why I am simply saying AV Camera. My problem is, that when I rotate the device, the preview layer is not rotating with the device as well. This is aside having any buttons or recording actions of any kind, simply just the preview of what is to be captured.
I have looked all around here and the internet, but I cannot find anything that can just simply explain to me the steps involved in doing rotating this preview correctly with the device when it is rotated. All of the information that I find is bits and pieces and really hard to try to understand how those code snippets can be modified to my logic.
It would be really nice if I could get a step by step logical basis on where I need to go with rotating this preview layer correctly with my device. Any help is greatly appreciated.
Thanks

A: I have figured it out! I just needed to apply the standard transformation rotation matrix that we all learned in linear algebra!. This function rotates the videoPreviewLayer with the device rotation after registering for the notification of device rotation in viewWillAppear.
Although the rotation is not smooth for this. You can see the edges of the layer as it is rotating with the device. I have tried dispatching it to its own queue, but it doesn't make much of a difference.
My solution to this is going to be locking the preview layer to one orientation, UIDeviceOrientation.Portrait, and then apply deviceOrientationDidChange() on the buttons I will have in the view. I suspect I will have to apply it to the video/picture data when I press capture too, in order for the user to be able to ultimately view it in the way they took the video/picture. (please, correct me if I am wrong)
/**************************************************************************
    DEVICE ORIENTATION DID CHANGE
    **************************************************************************/
    func deviceOrientationDidChange() {

        println("DEVICE ORIENTATION DID CHANGE CALLED")
        let orientation: UIDeviceOrientation = UIDevice.currentDevice().orientation

        //------ IGNORE THESE ORIENTATIONS ------
        if orientation == UIDeviceOrientation.FaceUp || orientation == UIDeviceOrientation.FaceDown || orientation == UIDeviceOrientation.Unknown || orientation == UIDeviceOrientation.PortraitUpsideDown || self.currentOrientation == orientation {
            println("device orientation is \(orientation) --- returning...")
            return
        }

        self.currentOrientation = orientation

        //------ APPLY A ROTATION USING THE STANDARD ROTATION TRANSFORMATION MATRIX in R3 ------
        /*

             x     y      z
           ---           ---
        x | cosø  -sinø   0 |
        y | sinø  cosø    0 |
        z | 0     0       1 |
           ---           ---

        BUT IMPLEMENTED BY APPLE AS

            x       y       z
           ---            ---
        x | cosø    sinø    0 |
        y | -sinø   consø   0 |
        z | 0       0       1 |
            ---            ---
        */

        //----- PERFORM VIDEO PREVIEW LAYER ROTATION BEFORE CAMERA CONTROLLER ROTATION ------

        switch orientation {

        case UIDeviceOrientation.Portrait:
            println("Device Orientation Portrait")
            if self.usingFrontCamera == true {
            }
            else {
                self.playBackTransformation = CGAffineTransformMakeRotation(self.degrees0)
                self.videoPreviewLayer?.setAffineTransform(self.playBackTransformation!)
                self.videoPreviewLayer!.frame = self.view.bounds
            }
            break
        case UIDeviceOrientation.LandscapeLeft:
            println("Device Orientation LandScapeLeft")
            if self.usingFrontCamera == true {
            }
            else {
                self.playBackTransformation = CGAffineTransformMakeRotation(CGFloat(-self.degrees90))
                self.videoPreviewLayer?.setAffineTransform(self.playBackTransformation!)
                self.videoPreviewLayer!.frame = self.view.bounds
            }
            break
        case UIDeviceOrientation.LandscapeRight:
            println("Device Orientation LandscapeRight")
            if self.usingFrontCamera == true {
            }
            else {
                self.playBackTransformation = CGAffineTransformMakeRotation(self.degrees90)
                self.videoPreviewLayer?.setAffineTransform(self.playBackTransformation!)
                self.videoPreviewLayer!.frame = self.view.bounds
            }
            break
        default:
            break
        }
    }


text:
Q: Angular 2 - Why imported module routing order is different to fix-coded? Let's say i'have this in my app.module.ts
@NgModule({
   imports: [
     BrowserModule,
     HttpModule,
     RouterModule.forRoot([
        {path: 'home', component: HomeComponent},
        {path: '', redirectTo: 'home', pathMatch: 'full'},
        {path: '**', component: NotFoundComponent},
     ]),
     UserModule
     ...
})

this leads in my opinion to this routing order:

{path: 'User', component: UserComponent},
  {path: 'home', component: HomeComponent},
  {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: '**', component: NotFoundComponent}

Note that User is now before the others.
Now i am exporting the part RouterModule.ForRoot to another module called AppRoutingModule.
@NgModule({
   imports: [
     BrowserModule,
     HttpModule,
     AppRoutingModule, // newly created routing module
     UserModule
     ...
})

this leads now to this in my opinion:

{path: 'home', component: HomeComponent},
  {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: '**', component: NotFoundComponent},
  {path: 'User', component: UserComponent}

Note that User is now after the others.
So i have to put the AppRoutingModule below the UserModule. Why is it implemented like this?

A: Here are two links from the official documentation that will help you understand how imports are made, and how to know the current order route :

*

*https://angular.io/guide/router#inspect-config
App.Module.ts
const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'hero/:id',      component: HeroDetailComponent },
  {
    path: 'heroes',
    component: HeroListComponent,
    data: { title: 'Heroes List' }
  },
  { path: '',
    redirectTo: '/heroes',
    pathMatch: 'full'
  },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )
    // other imports here
  ],
  ...
})
export class AppModule { }

The order of the routes in the configuration matters and this is by
  design. The router uses a first-match wins strategy when matching
  routes, so more specific routes should be placed above less specific
  routes. In the configuration above, routes with a static path are
  listed first, followed by an empty path route, that matches the
  default route. The wildcard route comes last because it matches every
  URL and should be selected only if no other routes are matched first.

App.Module.ts
// Diagnostic only: inspect router configuration
constructor(router: Router) {
  console.log('Routes: ', JSON.stringify(router.config, undefined, 2));
}

*

*https://angular.io/guide/router#module-import-order-matters


text:
Q: Fallo en el diseño de formulario html Estoy haciendo un formulario con el uso de las etiquetas , quiero que me quede así finalmente:
Todo estará con el estilo en el css, pero no consigo que me haga caso. Este es el index.html:
    <!DOCTYPE html>

        <title>Formulario</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <link rel="stylesheet" type="text/css" href="estilo.css">

            <form method="POST" id="formulario" name="formulario" role="form">

<input type="text" name="nombre" placeholder="Nombre">

                        <input type="checkbox" name="check1" value="check1"> Uno

                        <input type="checkbox" name="check2" value="check2"> Dos

                        <input type="checkbox" name="check3" value="check3"> Tres

Proyecto
                        <select class="custom-select">
                            <option>Opción 1</option>
                            <option>Opción 2</option>
                        </select>

                    Mensaje:

                     <textarea name="contenido" id="contenido" class="form-control" rows="4"                    cols="50" placeholder="Escribe tu mensaje aquí" style="background-color: white;"></textarea>

            </form>

                <button id="myBtn" class="button" input type="submit" value="Enviar">Enviar</button>

            ×

 Tus datos han sido guardados correctamente.

            ×

 Tus datos han sido guardados correctamente.

Como se puede observar, el formulario obtiene los datos, los manda a un php aparte y los mete en la bd. También tiene un modal, que no me funciona del todo, y los estilos de las etiquetas no me hacen ni caso. Aquí el css:
    .form{
    position:relative;
    width:500px;
    height:600px;
    padding-left: 20px;
    padding-top: 30px;
    padding-bottom: 10%;
    background-color:#EC2F2F;
    border-radius: 20px;
    margin:auto;
    margin-top: 90px;
}

body{
    margin: 30px;
}
input[type=text],[type=email]{
    width:470px;
    height:35px;
    font: 14px normal normal uppercase arial;
}

input[type=checkbox]{
    display: inline-block;
    position: relative;
    padding-left: 35px!important;
    margin-bottom: 15px;
    cursor: pointer;
    font-size: 22px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
textarea{
    width: 100%;
    height: 100%;
    font: 14px normal normal uppercase arial;
    resize: none;
    padding-top: 5px;
}

input[type=submit]{
    position:relative;
    width:150px;
    height:40px;
    border-radius:20px;
    margin-left: 150px;
    border:0px;
    background-color:#FFFFFF;
    font: 14px black normal normal uppercase arial;
}

input {
    width: 13px;
    height: 13px;
    padding: 0;
    margin:0;
    vertical-align: bottom;
    position: relative;
    top: -1px;
    *overflow: hidden;
}

/* Create a custom checkbox */
.checkmark {
    position: absolute;
    top: 0;
    left: 0;
    height: 20px;
    width: 20px;
    background-color: #eee;
}

/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
    content: "";
    position: absolute;
    display: none;
}

/* Show the checkmark when checked */
.container input:checked ~ .checkmark:after {
    display: inline-block;
}

/* Style the checkmark/indicator */
.container .checkmark:after {
    left: 9px;
    top: 5px;
    width: 5px;
    height: 10px;
    border: solid white;
    border-width: 0 3px 3px 0;
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}

/*CASILLA SELECCIONAR*/

/*the container must be positioned relative:*/
.custom-select {
  position: relative;
  font-family: Arial;
}

.custom-select select {
  display: none; /*hide original SELECT element:*/
}

.select-selected {
  background-color: #C81A1A;
}

/*style the arrow inside the select element:*/
.select-selected:after {
  position: absolute;
  content: "";
  top: 14px;
  right: 10px;
  width: 0;
  height: 0;
  border: 6px solid transparent;
  border-color: #fff transparent transparent transparent;
}

/*point the arrow upwards when the select box is open (active):*/
.select-selected.select-arrow-active:after {
  border-color: transparent transparent #fff transparent;
  top: 7px;
}

/*style the items (options), including the selected item:*/
.select-items div,.select-selected {
  color: #ffffff;
  padding: 8px 16px;
  border: 1px solid transparent;
  border-color: transparent transparent rgba(0, 0, 0, 0.1) transparent;
  cursor: pointer;
  user-select: none;
}

/*style items (options):*/
.select-items {
  position: absolute;
  background-color: #C81A1A;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 99;
}

/*hide the items when the select box is closed:*/
.select-hide {
  display: none;
}

.select-items div:hover, .same-as-selected {
  background-color: rgba(0, 0, 0, 0.1);
}

/*BOTÓN ENVIAR*/

.button{
    padding: 5px 15px;
    font-size: 20px;
    text-align: center;
    margin-left: 350px;
    cursor: pointer;
    outline: none;
    color: #000;
    background-color: #FFF;
    border: none;
    border-radius: 15px;
    box-shadow: 0 9px #999;
}

.button:active {
    background-color: #3e8e41;
    box-shadow: 0 5px #666;
    transform: translateY(4px);
}

.logytel{
    float: right;
    margin-top: -15px;
    margin-bottom: 10px;
    margin-right: 8%;
    width:200px;
    height:81px;
}

/*MODAL*/

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

/* The Close Button */
.close {
    color: #ff0000;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

No sé qué es lo que falla, si son las clases mal colocadas, el css, o el index. Si pueden ayudarme a dar con ello, lo agradecería muchísimo. Muchas gracias.

A: Para empezar, tienes tantos problemas que mi recomendación es que empieces de nuevo ya que se ve que has cogido una plantilla o algo ya pre hecho y has tratado de adaptarlo en vano.
Tienes una mezcla de cosas ahí metidas que he intentado hacer algo pero está ya bastante infumable, ya que si tocas algo rompes otra cosa.
Mis recomendaciones son:

*

*Comprende el funcionamiento de Bootstrap, ya que estas declarandolo en el html pero se ve que sin sentido. El elemento col es en si una clase css que divide en columnas tu html.

*Abuso del píxeles, para mi opinión, si deseas que te quede igual en cualquier pantalla, usa unidades relativas.

*Usa las clases css para retocar y adaptar a tu formulario y no para forzarlo a tener una forma determinada, usando la potencia de bootstrap, ya que probablemente vuelvas a la misma situación si tratas de repetirlo.

Te dejo un pequeño ejemplo sobre cómo puedes empezar

/* Uso css para detalles*/
.imagen {
    background-color: red;
    padding: 2%;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<form>

  Coloco a la derecha este texto

    Ejemplo
    <input type="tex" class="form-control" id="ejemplo" placeholder="Nombre Ejemplo">

      <input type="checkbox"> 1

      <input type="checkbox"> 4

      <input type="checkbox"> 2

      <input type="checkbox"> 5

      <input type="checkbox"> 3

      <input type="checkbox"> 6

  <textarea class="form-control" rows="3" placeholder="Uso bootstrap para adaptar"></textarea>

  <button type="submit" class="btn btn-default">Submit</button>

</form>

A: *

*Para empezar te falta un cierre de etiqueta en el textarea.

*Revisa los div ya que tienes mal dividida la pantalla para lo que quieres
hacer y no se te va a organizar bien el textarea ni el botón.

*En la imagen que propones el texarea ocupa todo el ancho de la pantalla y
lo tienes puesto para que ocupe un tercio ya que tienes el espacio
dividido en 3.

*Te recomiendo que al div del cuerpo le metas un margin: 10-30px para que se separe
de los bordes de la pantalla.

*La lista de opciones tal y como la tienes solo te hace falta alinearlo al centro y
si quieres que el texarea te quede debajo centrado haz que ocupe todo el ancho o
ponlo en el div del centro y que ocupe el ancho del div.

De momento te recomiendo estos cambios, si después de esto tienes mas problemas comentalo.


text:
Q: MonoTouch.Dialog: Arabic Elements Is there a way to have the text in a StyledStringElement be RTL so that Arabic and Farsi and Hebrew can render correctly?
I create an StyledStringElement:
var eBahai = new StyledStringElement ("بهائی");

When rendered it is left aligned, not right aligned.

A: StyledStringElement elm = new StyledStringElement("your caption");
elm.Alignment = UITextAlignment.Right;

if I understood you right, that's should work for you


text:
Q: Restful DDS execution I download restful-dds-1.0-src.tgz file from http://code.google.com/p/restful-dds/downloads/list website. I am using linux environment. From the ReadMe.txt file i execute the chatter application (CHATROOM TEST) up to scripts/startRESTfulDDS.sh and also view the html file from http://ipaddress:8182/static/ajaxTest.html. After that "run the Chatter application in the Tutorial directory by running scripts/Chatter.{sh,bat}." In here my problem arise. I am not able to see scripts folder and chatter.sh file inside the Tutorial folder. Please, help me what i did wrong.
I am using  opensplice DDS v5.5
GWT2.4.0,
JDK 1.6,
Restlet v2.0.14,
Gson v2.2.2

A:
I am not able to see scripts folder and
  chatter.sh file inside the Tutorial folder

The Tutorial folder that is created is an exact copy of the OpenSpliceDDS tutorial, found in $OSPL_HOME/examples/dcps/standalone/Java/Tutorial. There seems to be a mismatch between the description in the resful-dds README and this tutorial because indeed, there is no chatter.sh. However, there is a README.txt inside the Tutorial directory which explains how to run Chatter:
Chatter [userid] [username]
  userid:   an integer number that uniquely identifies the sender of a message
            (Transmit a message with userid = -1 to terminate the MessageBoard.)
  username: the user-name other chatters will see when they receive one of your
            chat messages.

The executables classes are located in the chatroom package, but should be
started from the current directory in the following way:
...
java -classpath $OSPL_HOME/jar/dcpssaj.jar:bld chatroom.Chatter 1 Bill

Following this procedure, you should be able to run Chatter. Of course, you should first run ospl start to initialize the infrastructure.
By the way, it is not required that you run the java version of the tutorial -- any supported language should do. The OpenSpliceDDS installation itself should give you more information about running Chatter for different languages. The restful DDS webservice will pick up any data found on the DDS bus and expose it via HTTP, no matter what language the originating process was written in.


text:
Q: How can I display a list in reverse with 3 colon-separators? how can get the 3rd line to do the same as the second line?
list = [1,2,3,4,5,6,7,8,9,10]
print(list[::-1])
print(list[-1:0:-1])

this is the result i got:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[10, 9, 8, 7, 6, 5, 4, 3, 2]

A: You should omit 0 here:
print(list[-1:0:-1])

and write it as
print(list[-1::-1])

or place None:
print(list[-1:None:-1])

The reason is: when you omit the stop value (or substitute None) in a "3 colon-seperators", this will happen:

If i or j are omitted or None, they become "end" values (which end depends on the sign of k).

where j here corresponds to the stop value (and i is the start i.e. [i:j:k])

A: Use None:
>>> list[-1:None:-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

or
>>> list[None:None:-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

You could use -len(list)-1, but None is simpler and doesn't require any computation.
BTW list is a bad variable name since it shadows the builtin list.

A: You can use following ways of list slicing to achieve required result.
list = [1,2,3,4,5,6,7,8,9,10]

#Use Blank:
print(list[::-1])
print(list[-1::-1])
#output
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

#Use None:
print(list[:None:-1])
print(list[None:None:-1])
#output
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

#Use Boolean:
print(list[-True::-True])
#output
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

#Use Boolean:
print(list[~False::-1])
#output
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

#Use of Length function:
print(list[:-(len(list)+1):-1])
#output
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]


text:
Q: Differentiate items loading to list vs scroll event Xamarin forms listview This is my code that can successfully detect scroll up or down:
 MyListView.ItemAppearing += async (object sender, ItemVisibilityEventArgs e) =>
        {
            var currentIdx = CurrentList.IndexOf((MyClass)e.Item);

            if (currentIdx > _lastItemAppearedIdx)
                ShowChopped();
            else
                ShowFull();

            _lastItemAppearedIdx = CurrentList.IndexOf((MyClass)e.Item);
        };

What is working is the following: Items get added to the list, then once i start scrolling it works fine where ShowChoppedand ShowFull are methods with animations that just makes a simple animation to either half the size of an object or make it full. This works fine, but if i however click a new category that changes the content in the list, ItemAppearing gets triggered of course and ShowChoppedand ShowFull are called even though i only want it called during a scrollevent.
How would i be able to differentiate a scroll to a item collection change? I have only tried this on iOS.
Updated code:
public class ListView_iOS : ListViewRenderer
{
    private IDisposable _offsetObserver;
    private double _prevYOffset;
    private IListView _myListView;

    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.ListView> e)
    {
        base.OnElementChanged(e);

        if (e.NewElement is IListView)
            _offsetObserver = Control.AddObserver("contentOffset",
                         Foundation.NSKeyValueObservingOptions.New, HandleAction);
    }

    private static bool CloseTo(double x, double y)
    {
        return Math.Abs(x - y) < 0.1;
    }

    private void HandleAction(Foundation.NSObservedChange obj)
    {
        var effectiveY = Math.Max(Control.ContentOffset.Y, 0);
        if (!CloseTo(effectiveY, _prevYOffset) && Element is IListView)
        {
            var myList = Element as IListView;
            myList.IsScrolling = true;
        }
    }
}

A: You can differentiate items loading from list scrolling by
1  adding the code if (EmployeeView.IsScrolling) within ItemAppearing method.
2  adding the code EmployeeView.IsScrolling = false; within any function you write to change the appearing of items without scrolling action, for example, when you add items or change category.
And the  EmployeeView.IsScrolling value is set from listview renderer.
So the code is like:
NativeListView.cs
public class NativeListView : ListView
    {
        public static readonly BindableProperty
            IsScrollingProperty =
                BindableProperty.Create(nameof(IsScrolling),
                typeof(bool), typeof(NativeListView), false);

        public bool IsScrolling
        {
            get { return (bool)GetValue(IsScrollingProperty); }
            set { SetValue(IsScrollingProperty, value); }
        }
    }

NativeAndroidListViewRenderer.cs
[assembly: ExportRenderer(typeof(NativeListView), typeof(NativeAndroidListViewRenderer))]
namespace App2.Droid
{
    public class NativeAndroidListViewRenderer : ListViewRenderer
    {
        public NativeAndroidListViewRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.ListView> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement is NativeListView)
                Control.Scroll += Control_Scroll;
        }
        private void Control_Scroll(object sender, AbsListView.ScrollEventArgs e)
        {
            var myList = Element as NativeListView;
            myList.IsScrolling = true;
        }

    }
}

NativeiOSListViewRenderer.cs
    private IDisposable _offsetObserver;
    private double _prevYOffset;
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.ListView> e)
    {
        base.OnElementChanged(e);

        if (e.NewElement is NativeListView)
            _offsetObserver = Control.AddObserver("contentOffset",
                         Foundation.NSKeyValueObservingOptions.New, HandleAction);
    }

    private void HandleAction(Foundation.NSObservedChange obj)
    {
        var effectiveY = Math.Max(Control.ContentOffset.Y, 0);
        if (!CloseTo(effectiveY, _prevYOffset) && Element is NativeListView)
        {
            var myList = Element as NativeListView;

            myList.IsScrolling = true;
            _prevYOffset = effectiveY;
        }
    }
    private static bool CloseTo(double x, double y)
    {
        return Math.Abs(x - y) < 0.1;
    }
    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        if (disposing && _offsetObserver != null)
        {
            _offsetObserver.Dispose();
            _offsetObserver = null;
        }
    }

MainPage.xaml.cs
namespace App2
{
    public partial class MainPage : ContentPage
    {
        ObservableCollection<String> employeeList = new ObservableCollection<String>();
        int count = 0;

        public MainPage()
        {
            InitializeComponent();
            AddButtion.Clicked += AddButtion_Clicked;
            DelButtion.Clicked += DelButtion_Clicked;
            EmployeeView.ItemsSource = employeeList;

            EmployeeView.ItemAppearing += async (object sender, ItemVisibilityEventArgs e) =>
            {
                if (EmployeeView.IsScrolling) {
                    await DisplayAlert("ItemAppearing", e.Item + " row is appearing", "OK");
                    Console.WriteLine("ItemAppearing!!!!!!!!!!");
                }
            };

        }

        private void AddButtion_Clicked(object sender, EventArgs e)
        {
            employeeList.Add("Mr. Mono"+ count++);

            EmployeeView.IsScrolling = false;
        }

        private void DelButtion_Clicked(object sender, EventArgs e)
        {
            if (employeeList.Count > 0) {
                employeeList.RemoveAt(0);
            }
            EmployeeView.IsScrolling = false;

        }
    }
}


text:
Q: Class not found in PHP - Scope Resolution I got 2 PHP files:
courier.php
    <?php
namespace Shipping;

class Courier
{
    public $name;
    public $home_country;

    public function __construct($name) {
        $this->name = $name;
        return true;
    }

    public function ship($parcel) {
        // sends the parcel to  its destination
        return true;
    }

    public static function getCouriersByCountry($country) {
        // get a list of couriers with their home_country = $country

        // create a Courier object for each result

        // return an array of the results
        return $courier_list;

    }

}
?>

filephp.php
<?php
//namespace Fred;

require 'courier.php';
//function __autoload($classname) {
//    include //strtolower($classname).'.php';
//}

$mono = new Shipping\Courier('Monospace Delivery');

//var_dump($mono);

// accessing a property
echo "Courier Name: " . $mono->name;

// calling a method
$mono->ship($parcel);

$spanish_couriers = Courier::getCouriersByCountry('Spain');

echo $spanish_couriers;
?>

But when I execute filephp.php I get this error:

Fatal error: Class 'Courier' not found in D:\masterphp\test.php on line 19

line 19 is this:
$spanish_couriers = Courier::getCouriersByCountry('Spain');

What is wrong with my scope resolution?

A: You are missing the Shipping namespace, it should be \Shipping\Courier::...


text:
Q: Spring Boot 2 - method annotated with @async is not called asynchronous maybe someone can help me.
Within my SpringBoot 2 Application I want to call a service asynchronous. I know, there are lot of posts which cover this issue and I read many of them attentive but unfortunately I'm stuck.
The affected service is initialized within a configuration class (annotated with @Configuration and @EnableAsync).
The service implements an Interface and the interesting interface method I'm talking about is  annotated with @Async. But as I've read in another post this shouldn't be a problem.
The bean initialization with the configuration class:
@Configuration
@EnableAsync
public class GlobalConfiguration {

   @Bean
    public DocumentMimetypeDetectionService getPermittedMimetypes() throws IOException {
        DocumentMimetypeDetectionServiceImpl detectionService = new DocumentMimetypeDetectionServiceImpl();
        detectionService.setPermittedDocumentMimetypes(permittedDocumentMimetypes().getObjectType()
                .cast(permittedDocumentMimetypes().getObject()));
        return detectionService;
    }

   @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(4);
        executor.setQueueCapacity(1500);
        executor.setThreadNamePrefix("ServiceAsync-");
        executor.initialize();
        return executor;
    }

}

The interface of DocumentMimetypeDetectionService:
public interface DocumentMimetypeDetectionService {

    @Async
    CompletableFuture<String> discoverDocumentMimetype(final InputStream aIs)
            throws DocumentMimetypeDetectionServiceException, IOException;
}

I created a test to inspect if the service is calling asynchronous.
Additional to that I include a

Thread.sleep(1000)
log.debug("current thread {}", Thread.currentThread().getId());

in the Service-Implementation Class (method discoverDocumentMimetype)  to test the async behavior.
My test class is annotated with @RunWith(SpringRunner.class) and @SpringBootTest.
And now the call of the service method:
   private void checkFiles(List<FileInfo> files)
            throws ExecutionException, InterruptedException, MasterindexValidationException {

        List<Mt> mtList = new ArrayList<>();
        files.forEach(f -> {
            try {
                Mt mt = new Mt(mimetypeDetectionService.discoverDocumentMimetype(f.getFileContainer().getContent()), f.getFileId());
                mtList.add(mt);

            } catch (DocumentMimetypeDetectionServiceException | InterruptedException | ExecutionException | IOException e) {
                throw new RuntimeException(String.format("error in verifying mimetype of file %s - detail: %s", f.getFileId(), e.getMessage()));
            }
        });

What I observed:
The call of

Mt mt = new Mt(mimetypeDetectionService.discoverDocumentMimetype(f.getFileContainer().getContent()), f.getFileId());

doesn't result in a asynchronous behavoir. Means, the document detection service allways stuck in the thread sleep and the Thread.Id ist always the same (log output).
What I'm doing wrong?
Any help are appreciate.
Many thanks in advance.
Regards, Bodo


text:
Q: Sign in with Apple. Get user phone number In my application users can log in or register with phone number, verified via SMS-code.  A phone number is a non-optional field, like a primary key. Some day I added log in with social network which provides user's phone number. Now Apple asks me to add Sign in with Apple. But I can not find how to retrieve user's phone after getting ASAuthorizationAppleIDCredential. It it possible? Or I have to ask Apple not to add Sign in with Apple button?

A: Personal data should not be used as primary keys for an authentication system. The user should be able to change his email, phone number, name, address... without breaking your whole database. You should definitely assign to your users a random UUID at registration time, and then use it as a primary key.
You are right about the fact you have to add SignIn With Apple if you implement any 3rd party social login, but those will not always provide you a phone number (it is not mandatory for Facebook, Google, Linkedin...). Apple goes further and may also hide the real email address by providing an alias. For data privacy concerns, Apple will reject an application that requires the user to provide its email and phone number without a strong business justification. If you think you are legitimate to require it, you can implement a profile completion right after the login, that will check if all the required data are already known, and prevent the user from going further into the application before he fills the missing data.
However in this case, you should explain to the user (to avoid drop off) and to the Apple reviewer (to avoid rejection) why those data are mandatory to use your app.


text:
Q: I want to save a pointer to a function in a Global variable So i thought this would be straight forward but i keep getting compile errors, which probably means i am doing something stupid.
So i am using C and i want to save a pointer to a function in a global variable.
As a test case i have three files. Test.c, Test.h and FunctionPtr.c
Test.h goes like this
void (*MyCallBack)(void);

int SetFunc( void (*CallBackArg)(void));
void CallFunc();

Test.c Goes like this
#include <stdio.h>
#include <stdlib.h>
#include "test.h"
void SetFunc( void (*CallBackArg)(void)){

    printf("Set CallBack\n");
    MyCallBack=CallBackArg;
}

void CallFunc(){
    printf("In Call Func\n");
    MyCallBack();
}

and FunctionTest.c goes like this
#include <stdio.h>
#include <stdlib.h>
#include "test.h"

void MyFunc(){
    printf("Work!\n");
}
int main()
{
    SetFunc(MyFunc);
    CallFunc();

}

When i compile using  gcc FunctionTest.c  test.c test.h -o FunctionTest
I get the following error...
test.c:4: error: conflicting types for 'SetFunc'
test.h:4: note: previous declaration of 'SetFunc' was here
I cant figure out what i am doing wrong? Perhaps i am not declaring the Global Pointer right?

A: int SetFunc( void (*CallBackArg)(void));

void SetFunc( void (*CallBackArg)(void))

The return types are different, that's your problem. You have to declare it the same way in the header as in the .c file.

A: Test.c has it returning void
void SetFunc( void (*CallBackArg)(void)){

Test.h has it returning int
 int SetFunc( void (*CallBackArg)(void));

Presumably you meant void, as it doesn't return anything


text:
Q: IDLE and unicode chars (2.5.4) Why does IDLE handle one symbol correctly but not another?
>>> e = '€'
>>> print unichr(ord(e))
     # looks like a very thin rectangle on my system.
>>> p = '£'
>>> print unichr(ord(p))
£
>>> ord(e)
128
>>> ord(p)
163

I tried adding various # coding lines, but that didn't help.
EDIT: browser should be UTF-8, else this will look rather strange
EDIT 2: On my system, the euro char is displayed correctly on line 1, but not in the print line.  The pound char is displayed correctly both places.

A: The answer depends what encoding the IDLE REPL is using. You should be more explicit about what's actually unicode text, and what's a byte sequence. Meditate on this example:
# -*- coding: utf-8 -*-
c = u'€'
print type(c)
for b in c.encode('utf-8'):
    print ord(b)

c = '€'
print type(c)
for b in c:
    print ord(b)

EDIT:
As for IDLE, it's kind of borken, and needs to be patched to work correctly.
IDLE 1.2.2
>>> c = u'€'
>>> ord(c)
128
>>> c.encode('utf-8')
'\xc2\x80'
>>> c
u'\x80'
>>> print c
[the box thingy]

>>> c = u'\u20ac'
>>> ord(c)
8364
>>> c.encode('utf-8')
'\xe2\x82\xac'
>>> c
u'\u20ac'
>>> print c
€

In the first session, by the time the € is interpreted, it has already been mis-encoded, and is unrecoverable.

A: The problem is probably that your font doesn't have the proper glyphs.  In addition to getting the encoding right, you have to have the proper font when presenting the text in the IDLE ui.  Try using a different font to see if it helps (Arial Unicode has a very large glyph complement, for example).
The euro symbol is much newer than the pounds sterling symbol, so your font may not have a euro glyph.


text:
Q: Arithmetic mean of a register in vhdl For a project I am currently working on, I am trying to take some inputs, store them in a register then find the arithmetic mean of the register. All of my inputs are 24-bits long. My registers are 4-inputs long therefore I simply remove the last 3-digits of the least-significant bits while dividing them by 4 in order to calculate the arithmetic mean, then simply add them.
mean is my register(95 downto 0) (4 x 24 = 96), and mean_medium is type unsigned.
When I code the following line
signal mean_medium : unsigned (23 downto 0) := (others => '0');
mean_medium <= unsigned(medium (95 downto 75)) +
               unsigned(medium (71 downto 51)) +
               unsigned(medium (47 downto 27)) +
               unsigned(medium (23 downto 3)) ;

I took the following warning:

Width mismatch. mean_medium has a width of 24 bits but assigned expression is 21-bit wide.

Do you have any suggestions to fix this?

A: I am making the assumption that you are using the numeric_std package.
In the numeric_std package, the + operator requires that the width of the sum be the same width as the widest of the operands. You operands are 21 bits wide, your sum is 24 bits wide. So, you need to make your operands 24 bits wide, too. You can do this using the resize function in numeric_std. In fact, this should be sufficient:
mean_medium <= resize(unsigned(medium (95 downto 75)),24) +
               unsigned(medium (71 downto 51)) +
               unsigned(medium (47 downto 27)) +
               unsigned(medium (23 downto 3)) ;

but you could also do this if you think it tidier:
mean_medium <= resize(unsigned(medium (95 downto 75)),24) +
               resize(unsigned(medium (71 downto 51)),24) +
               resize(unsigned(medium (47 downto 27)),24) +
               resize(unsigned(medium (23 downto 3)) ,24) ;

Or some variation on this is even better:
mean_medium <= resize(unsigned(medium (95 downto 75)),mean_medium'length) +
               unsigned(medium (71 downto 51)) +
               unsigned(medium (47 downto 27)) +
               unsigned(medium (23 downto 3)) ;

A: two side of a equation should have same size, you can use resize function or you can use a 24-bit temporary signal and do like this:
signal temp : std_logic_vector(23 downto 0);
temp(23 downto 21) <= "000";
temp(20 downto 0) <= medium (95 downto 75);
mean_medium <= temp + ....

A: An error already is that you divide by four by shifting 3 bits. You only need to shift 2 bits.
But for correct/precise arithmetic you should not pre-shift the operants of that expression, as you lose precision due to trunctation. First add all the 4 full 24-bit values to one 26-bit output. Then shift-and-round the output. Example
signal mean_medium : unsigned (23 downto 0); -- redundant := (others => '0');
signal mean_temp : unsigned(25 downto 0);

mean_temp <=
    resize(unsigned(medium (95 downto 72)), mean_Temp'length) +
    resize(unsigned(medium (71 downto 48)), mean_Temp'length) +
    resize(unsigned(medium (47 downto 24)), mean_Temp'length) +
    resize(unsigned(medium (23 downto 0)), mean_Temp'length) +
    2; -- round factor

mean_medium <= shift_right(mean_temp, 2); --divide by 4

p.s. you could also combine this in one line, removing the necessity of mean_temp.


text:
Q: django-dropbox - cannot serialize I wanted to try django-dropbox to upload images directly to dropbox.
This is the model
from django_dropbox.storage import DropboxStorage

STORAGE = DropboxStorage()

class Drop(models.Model):

    photo = models.ImageField(upload_to='photos', storage=STORAGE,null=True, blank=True)
    resume = models.FileField(upload_to='resumes', storage=STORAGE,null=True, blank=True)

But when i try to migrate i get this error:
Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemigrations.py", line 124, in handle
    self.write_migration_files(changes)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemigrations.py", line 152, in write_migration_files
    migration_string = writer.as_string()
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 131, in as_string
    operation_string, operation_imports = OperationWriter(operation).serialize()
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 82, in serialize
    arg_string, arg_imports = MigrationWriter.serialize(item)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 263, in serialize
    item_string, item_imports = cls.serialize(item)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 333, in serialize
    return cls.serialize_deconstructed(path, args, kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 239, in serialize_deconstructed
    arg_string, arg_imports = cls.serialize(arg)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 409, in serialize
    "topics/migrations/#migration-serializing" % value
ValueError: Cannot serialize: <django_dropbox.storage.DropboxStorage object at 0xa01db4c>


text:
Q: Finding unique data grids in sql I want to find unique data sets using sql (think groups of rows that form unique data sets, find and eliminate duplicates). Grouping is to be done on parent_id, key_id, key_value_id. But uniqueness needs to be determined by considering data both horizontally and vertically. The data size runs into terra bytes.
As an example, I have following data in a table -
parent_id   key_id  key_value_id    id     value
601         null       null         601     S
601         null       null         602     5

601         null       null         601     S
601         null       null         602     5
601         null       null         610     TYPE B

16501       16502       3           16501   -
16501       16502       3           16508   ?

601         null       null         601     S
601         null       null         602     5

16501       16502       3           16501   -
16501       16502       3           16508   3

The expected result is as below -
parent_id   key_id  key_value_id    id     value
601         null       null         601     S
601         null       null         602     5

601         null       null         601     S
601         null       null         602     5
601         null       null         610     TYPE B

16501       16502       3           16501   -
16501       16502       3           16508   ?

16501       16502       3           16501   -
16501       16502       3           16508   3

This data set/grid was repeated and hence removed.
601         null       null         601     S
601         null       null         602     5

This is to be considered as separate data set due to an extra row in the set -
601         null       null         601     S
601         null       null         602     5
601         null       null         610     TYPE B

One option is to use cursors but the size of data is huge and this may not be a performant solution. I am wondering if there is a simpler way to do this.
Any help/ pointers will be appreciated.

A: SQL is set based, but generally order in not important. How about using the MINUS operator to compare the 2 queries above. If you want something more complex than this you'll need to give more details of your queries, requirements and the database engine you are using.
PS MINUS is used in Oracle, I think SQLServer uses EXCEPT


text:
Q: How to merge 2 column into 1 column TO output in SQL I have this sql query:
$sql = "SELECT d.doctor_name, a.patient_name, s.date, s.time FROM appointments AS a LEFT JOIN doctors AS d ON d.id = a.doctor_id LEFT JOIN slots AS s ON  s.id = a.slot_id WHERE s.date > '2019-10-01' ORDER BY d.doctor_name DESC ";

$result = $mysqli->query($sql);

echo '<pre>';
while ( $row = $result->fetch_assoc() ) {
    print_r($row);
}
echo '</pre>';

and it's output is:
Array
(
    [doctor_name] => Khaled
    [patient_name] => Nawaz
    [date] => 2019-10-11
    [time] => 02:01
)
Array
(
    [doctor_name] => Khaled
    [patient_name] => Anik
    [date] => 2019-10-07
    [time] => 02:31
)
Array
(
    [doctor_name] => Khaled
    [patient_name] => Manik
    [date] => 2019-10-02
    [time] => 03:31
)

Can I merge the date and time column as slot_date_time?
So output will be e.g:
Array
(
    [doctor_name] => Khaled
    [patient_name] => Manik
    [slot_date_time] => 2019-10-02 03:31
)

A: Try this query
SELECT d.doctor_name, a.patient_name, CONCAT(s.date, ',', s.time) AS slot_date_time
FROM appointments AS a LEFT JOIN doctors AS d
ON d.id = a.doctor_id LEFT JOIN slots AS s
ON  s.id = a.slot_id
WHERE s.date > '2019-10-01'
ORDER BY d.doctor_name DESC

Use CONCAT for merge two column as one column


text:
Q: Workaround to .ts files in video merging? I've got these sentences of code that I use for video processing, the first one adds a watermark, the second creates a .ts file of the watermarked video and then adds an intro and outro to it but I found that it quickly fills disk space because of the .ts files being used, is there a way to achieve the same results without them? Either by deleting them right after using them or by using a different process altogether.
for %%I in ("C:\Users\Administrator\Desktop\work\*.mp4") do ffmpeg.exe
    -y -i "%%I" -i white.png -filter_complex "[0:v]scale=iw:ih[v0];[1:v][v0]scale2ref=iw/6:ih/18[logo][0v];[0v][logo]overlay=W-w-3:H-h-1[v]"
    -map "[v]" -map 0:a -codec:v libx264 -preset ultrafast -crf 23 -codec:a copy "C:\Users\Administrator\Desktop\Complete-videos\%%~nI.mp4"

for %%I in ("C:\Users\Administrator\Desktop\Complete-videos\*.mp4") do ffmpeg -y
    -i %%I -c copy -vbsf h264_mp4toannexb -f mpegts -s 1280*720 %%I.ts && ffmpeg -y -i "concat:out1.ts|%%I.ts|out1.ts" -c:v libx264 -strict experimental -bsf:a aac_adtstoasc -ar 48000 -r 20 "C:\Users\Administrator\Desktop\Complete-videos\%%~nI.mp4
pause

A: [totally untried suggestion since I have no idea what the ffmpeg line is doing]
I suggest you try this on a small file subset on a device with a restricted space like a ramdrive or a usb drive. USB drive may take a while. Coffee is good.
for %%I in ("C:\Users\Administrator\Desktop\work\*.mp4") do (
 ffmpeg.exe -y -i "%%I" -i white.png -filter_complex "[0:v]scale=iw:ih[v0];[1:v][v0]scale2ref=iw/6:ih/18[logo][0v];[0v][logo]overlay=W-w-3:H-h-1[v]"
    -map "[v]" -map 0:a -codec:v libx264 -preset ultrafast -crf 23 -codec:a copy "C:\Users\Administrator\Desktop\Complete-videos\%%~nI.mp4"

 for %%Q in ("C:\Users\Administrator\Desktop\Complete-videos\%%~nI.mp4") do ffmpeg -y
    -i %%Q -c copy -vbsf h264_mp4toannexb -f mpegts -s 1280*720 %%Q.ts && ffmpeg -y -i "concat:out1.ts|%%I.ts|out1.ts" -c:v libx264 -strict experimental -bsf:a aac_adtstoasc -ar 48000 -r 20 "C:\Users\Administrator\Desktop\Complete-videos\%%~nQ.mp4

 del *.ts
)
pause

This way, the first loop using %%I selects the file to be processed and apparently puts the processed file in another directory then immediately performs the second process on that file, controlled by %%Q using the name in %%~nI to select the single file created by the previous process.
Consequently, instead of processing 10 files each with its own .ts set, one is processed at a time and only one .ts set is created. I don't know whether the second process deletes the .ts files, but I've added a del to get rid of them on each cycle. I've also no idea whether the first process creates the .ts files, but I've made that assumption.
As the educationalists said about "new maths" - it's the idea that's important.

A: This does it in one command, with no intermediate files.
for %%I in ("C:\Users\Administrator\Desktop\work\*.mp4") do ffmpeg.exe
-y -i "%%I" -i white.png -i out1.ts -filter_complex "[1:v][0:v]scale2ref=iw/6:ih/18[logo][0v];[0v][logo]overlay=W-w-3:H-h-1,scale=hd720,setsar=1[vl];[2:v][2:a][vl][0:a][2:v][2:a]concat=n=3:v=1:a=1[v][a]"
-map "[v]" -map "[a]" -r 20 -c:v libx264 -ar 48000 "C:\Users\Administrator\Desktop\Complete-videos\%%~nI.mp4"

pause

Notes: Depending on where out1.ts is, you may have to specify its full path during input. In the first command, in your 2nd step, the size option has no effect as you're copying streams. If resize is needed, insert scale=hd720 after the concat filter in my command. Add -strict experimental if your ffmpeg is older than Dec 2015 and you don't want to upgrade.


text:
Q: Tx_Extbase_Domain_Repository_FrontendUserRepository->findAll() not working in typo3 4.5.30? I am trying to run a simple query off of the Tx_Extbase_Domain_Repository_FrontendUserRepository. I cannot get anything to work except findByUid(), not even findAll().
In my controller I have this code which seems to work:
/**
* @var Tx_Extbase_Domain_Repository_FrontendUserRepository
*/
protected $userRepository;

/**
* Inject the user repository
* @param Tx_Extbase_Domain_Repository_FrontendUserRepository $userRepository
* @return void */
public function injectFrontendUserRepository(Tx_Extbase_Domain_Repository_FrontendUserRepository $userRepository) {
$this->userRepository = $userRepository;
}

/**
* action create
*
* @param Tx_BpsCoupons_Domain_Model_Coupon $newCoupon
* @return void
*/
public function createAction(Tx_BpsCoupons_Domain_Model_Coupon $newCoupon) {
...... some code .....
$user = $this->userRepository->findByUid(($GLOBALS['TSFE']->fe_user->user[uid]));
$newCoupon->setCreator($user);
...... some code .....
}

but in another function I want to look up a user not by uid but by a fe_users column called vipnumber (an int column) so I tried
/**
* check to see if there is already a user with this vip number in the database
* @param string $vip
* @return bool
*/
public function isVipValid($vip) {
echo "
" . __FUNCTION__ . __LINE__ . "
";
echo "
".$vip."
";

//$ret = $this->userRepository->findByUid(15); //this works!! but
$query = $this->userRepository->createQuery();
$query->matching($query->equals('vip',$vip) );
$ret = $query->execute(); //no luck
.................

and neither does this
$ret = $this->userRepository->findAll();

How can one work but not the others? In my setup I already put
config.tx_extbase.persistence.classes.Tx_Extbase_Domain_Model_FrontendUser.mapping.recordType >
which seems to be necessary for the fiondByUid to work, is i t preventing the other from working?
I am using typo3 v 4.5.30 with extbase 1.3
Thanks

A: If $this->userRepository->findByUid(15); works, there is no reason why $this->userRepository->findAll(); should not. However $this->userRepository->findAll(); returns not a single Object but a collection of all objects, so you have to iterate over them.
If you add a column to the fe_users, you have to add it to TCA and to your extbase model (you need a getter and a setter), too! After that you can call findByProperty($property) in your repository. In your case that would be
$user = $this->userRepository->findByVipnumber($vip);

This will return all UserObjects that have $vip set as their Vipnumber. If you just want to check if that $vip is already in use, you can call
$user = $this->userRepository->countByVipnumber($vip);

instead. Which obviously returns the number of Users that have this $vip;
You never use $query = $this->createQuery(); outside your Repository.
To add the property to the fronenduser Model you create your own model Classes/Domain/Model/FronendUser.php:
class Tx_MyExt_Domain_Model_FrontendUser extends Tx_Extbase_Domain_Model_FrontendUser {
  /**
   * @var string/integer
   */
  protected $vipnumber;
}

Add a getter and a setter. Now you create your own FrontendUserRepository and extend the extbase one like you did with the model. You use this repository in your Controller. Now you're almost there: Tell Extbase via typoscript, that your model is using the fe_users table and everything should work:
config.tx_extbase {
    persistence{
        Tx_MyExt_Domain_Model_FrontendUser{
            mapping {
                tableName = fe_users
            }
        }
    }
}

To disable storagePids in your repository in general, you can use this code inside your repository:
/**
 * sets query settings repository-wide
 *
 * @return void
 */
public function initializeObject() {
    $querySettings = $this->objectManager->create('Tx_Extbase_Persistence_Typo3QuerySettings');
    $querySettings->setRespectStoragePage(FALSE);
    $this->setDefaultQuerySettings($querySettings);
}

After this, your Querys will work for all PIDs.

A: I didn't have the opportunity to work with frontend users yet, so I don't know if the following applies in this case:
In a custom table I stumbled uppon the fact, that extbase repositories automatically have a look at the pids stored in each entry and check it against a set storage pid (possibly also the current pid if not set). Searching for a uid usually means you have a specific dataset in mind so automatic checks for other values could logically be ignored which would support your experiences. I'd try to set the storage pid for your extension to the place the frontend users are stored in ts-setup:
plugin.[replace_with_extkey].persistence.storagePid = [replace_with_pid]


text:
Q: Behaviour of volatile keyword c++ What effect does volatile have on pointers?
I got some unexpected behavior while using it
int main() {

volatile uint32_t *ptr=((uint32_t *)(0x00000000+0x00100100));
cout<<ptr<<endl;

uint32_t *ptr1=((uint32_t *)(0x00000000+0x00100100));
cout<<ptr1<<endl;

return 0;
}

"ptr" returns value 1, while
"ptr1" return value 0x100100.
What causes this difference?


text:
Q: Format PrimeFaces Slider InputText I have a PrimeFaces slider with an associated inputText. Everything is working fine, except I can´t find a way of formatting the inputText value. I want the inputText to show and get values in currency format.
What I've tried so far:

*

*Changing the p:inputText with a pe:inputNumber component: causes an exception because the value can't be set (slider simply doesn´t work with inputNumber);

*Setting the p:slider target to a h:inputHidden component with the same value than p:inputText (with a f:convertNumber attached to): works when changing values through slider, but when using inputText to change the value slider doesn´t update (throws an UpdateModelException behind the scenes);

Update: it was found later that the second option exception is thrown because f:convertNumber expects a number type bean property, not an integer one. Both solutions shown below work around this issue.
Is there a simple way of doing this without using jQuery?
Thanks!
Filipe

A: Below I posted minimal requirements to obtain a custom inputText but you lost live update on it.
SliderView.java
private int number1 = 0;
private String number2 = String.valueOf(number1);

public int getNumber1() {
return number1;
}

public void setNumber1(int number1) {
this.number1 = number1;
}

public String getNumber2() {
return number2;
}

public void setNumber2(String number2) {
this.number2 = number2;
}

public void converToInt() {
log.debug(number2);
//TODO should be improved
this.number1 = Integer.parseInt(number2);
}

public void onSlideEnd(SlideEndEvent event) {
log.debug("current number: " + event.getValue());
this.number1 = event.getValue();
this.number2 = String.valueOf(event.getValue());

}

slider.xhtml
<h:form id="bcr_form_2" styleClass="form">
    <h:panelGrid columns="1" style="margin-bottom: 10px">
        <p:inputMask id="output" value="#{sliderView.number2}">
            <p:ajax event="keyup" listener="#{sliderView.converToInt}" update="@form:txt @form:slider" />
            <f:converter converterId="CurrencyConverter" />
            <pe:keyFilter regEx="/[0-9_]/i" />
        </p:inputMask>
        <h:inputHidden id="txt" value="#{sliderView.number1}" />
        <p:slider id="slider" for="txt" style="width: 200px">
            <p:ajax event="slideEnd" listener="#{sliderView.onSlideEnd}" update="@form:output" />
        </p:slider>
    </h:panelGrid>
</h:form>

CurrencyConverter.java
@FacesConverter("CurrencyConverter")
public class CurrencyConverter implements Converter {
  @Override
  public Object getAsObject(FacesContext context, UIComponent component, String value) {
    return value.replace('€', ' ').trim();
  }

  @Override
  public String getAsString(FacesContext context, UIComponent component, Object value) {
    return value.toString() + "€";
  }
}

Glad to be helpful.

A: So there are 2 ways of solving this problem:

*

*Creating a custom converter (drafted by @giaffa86 in his solution);

*Enabling Number getters and setters to the int property and using them with inputText (what's simpler, IMO).

The code below shows how to implement the second option.
TestView.java
@ManagedBean(name="testView")
@ViewScoped
public class TestView {

    private int realValue = 500;

    public int getValueAsInt() {
        return this.realValue;
    }

    public Number getValueAsNumber() {
        return (Number)realValue;
    }

    public void setValueAsInt(int value) {
        this.realValue = value;
    }

    public void setValueAsNumber(Number value) {
        this.realValue = value.intValue();
    }

    public void onSlideEnd(SlideEndEvent event) {
        this.realValue = event.getValue();
    }
}

view.xhtml
    <p:inputText id="input" value="#{testView.valueAsNumber}">
        <p:ajax update="slider" />
        <f:convertNumber currencySymbol="$" type="currency"
            integerOnly="true" />
    </p:inputText>

    <h:inputHidden id="hidden" value="#{testView.valueAsInt}" />
    <p:slider id="slider" for="hidden" minValue="0" maxValue="1000" step="10">
        <p:ajax event="slideEnd" listener="#{testView.onSlideEnd}" update="input" />
    </p:slider>

This solution, as the first option, also loses live update, but that's no problem in my scenario.


text:
Q: 500 Internal Server Error while using curl i am using the below code in my word press site. and i am trying change some of the functionality by calling the wcf web service in my php code. below is the code i am using which is giving me error
$Url = "http://localhost:8080/Service1.svc/checkUseronHealnt";
$json = "[{\"MOBILE_NO\":\"8745009403,8745009411\"}]"
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $Url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($json));
$curl_response = curl_exec($curl);
if (curl_error($curl)) {
    echo 'error:' . curl_error($curl);
} else {
    echo"Response - " . $curl_response;
}

A: $json = "[{\"MOBILE_NO\":\"8745009403,8745009411\"}]"
; is missing after this
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($json));
json_encode is not needed here.
And  unless there is { somewhere above the code you provided, last } is also not needed.

A: $json = "[{\"MOBILE_NO\":\"8745009403,8745009411\"}]" - Semicolon is missing after statement
Remove extra curly bracket {} from the code.
Your good code is below
$Url ="http://localhost:8080/Service1.svc/checkUseronHealnt";
$json = "[{\"MOBILE_NO\":\"8745009403,8745009411\"}]";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $Url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($json));
$curl_response = curl_exec($curl);
if(curl_error($curl)) {
  echo 'error:' . curl_error($curl);
}
else {
  echo"Response - ".$curl_response;
}


text:
Q: C++ nested classes - inner/outer relationship I read some posts about Nested Classes in our community and outside and I'm pretty confused.
As far as I understand, in C++, Nested Classes aren't not any different from separate/independent classes.
While I was trying to understand the conecpt better I wrote a simple code and I found out that an inner class can access an outer class without being given friendship from the outer class.
For example:
class Outer {
private : // default access modifier
    int x;
    static int sx;
public:
    class Inner {
    public:
        void changeOuterDataMemberValues(int value) {
            sx = value; // changes the private static data member of Outer.

            Outer out;
            out.x = value; // changes the private data member via object (not via class!)
        }
        void printMyOuterDataMember()  {
            cout << sx; // prints the private data member of Outer.
        }
    };
};

class Lonesome {
    void tryingToChangeDataMemberValue(int value) {
        Outer::sx = value; // cannot change the private static data member of Outer.
    }
};

int Outer::sx;

You can see that the Inner class which is nested in the Outer class has access to its(the Outer class) data members whilst the Lonesome as independent class cannot access the Outer class data member.
I apologize if this is a duplicate or stupid question, but I just want to confirm with you guys that there is a difference between a Nested Class and independent class (two different classes which don't have inner / outer relationship).
Thank you all,
Syndicator =]

A: From section 11.7 of the standard:

1 - A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class [...]

So a nested ("inner") class is effectively a friend of the enclosing class.

A: There is a difference between C++03 and C++11 in this regards. So the answer varies depending on which compiler you are using.
If you are using a C++03 compliant compiler then:
Nested class cannot access all members of the enclosing class.
If you are using C++11 compliant compiler then:
Nested class can access all members of the enclosing class. Nested class is treated as just another member of the class.
C++03 Standard 11.8 Nested classes:
§1

The members of a nested class have no special access to members of an enclosing class, nor to classes or functions that have granted friendship to an enclosing class; the usual access rules shall be obeyed.

C++11 Standard 11.7 Nested Classes:

A nested class is a member and as such has the same access rights as any other member.

A: You had answered your question by yourself:

You can see that the Inner class which is nested in the Outer class has access to its(the Outer class) data members whilst the Lonesome as independent class cannot access the Outer class data member.

Pay attention to contrarily to Java in C++ you can not acces to non-static members of Outer class.
It's an often practice to give a reference to Outer class to Inner class.
class Outer {
    private : // default access modifier
    int x;
    static int sx;
public:
    class Inner {
    public:
        Inner( Outer & o ) : m_outer( o ) {}
        void changeOuterDataMemberValues(int value) {
            sx = value; // changes the private static data member of Outer.

            //Outer out;
            //out.x = value; // changes the private data member via object (not via class!)
            m_outer.x = value; // <---------
        }
        void printMyOuterDataMember()  {
            cout << sx; // prints the private data member of Outer.
            cout << m_outer.x;
        }
    private:
        Outer & m_outer;
    };
};


text:
Q: HTML DIV's stack one below the other when resizing the browser window Have not worked much on UI front. I have a main div , and 2 nested div's. The 2 div's appear one besides the other, but when I resize the window the div's stack one below the other. My requirement is, Though I resize the window the divs should be place one besides the other and browser window should have a scroll bar horizontally to scroll right if i want to see the contents.
I did try various approaches but could not succeed.

body {
  background-color: white;
}

#mainContainer {
  overflow: hidden
}

#firstBox {
  background-color: gray;
  margin: 10px;
  padding: 10px;
  overflow-x: auto;
  width: 45%;
  height: 30%;
  float: left;
  display: inline-block;
}

#secondBox {
  background-color: gray;
  margin: 10px;
  padding: 10px;
  overflow: auto;
  width: 45%;
  height: 30%;
  float: left;
  display: inline-block;
  position: fixed;
}

    Lorem ipsum dolor sit amet, nullam eros posuere quam, non ipsum ornare vehicula. In integer, ac tempus aenean lorem nec amet ac, non blandit class, eget odio eu, mollis mauris massa. In augue erat convallis, morbi lectus lobortis tempor in lorem. Dis
    et morbi consectetuer non, tempor pretium. Leo dolor erat orci, lobortis adipisicing scelerisque integer diam lorem, tempus non, dolor libero vivamus velit. Viverra ipsum quam id in arcu, ligula tortor laoreet fermentum sit ipsum. Erat dapibus nulla
    justo vitae, feugiat nullam felis sollicitudin, dolor wisi mauris, tristique tempus nunc tristique. Velit non, duis auctor a. Ipsum pede maecenas vestibulum id ornare, ac facilisi wisi maecenas sem ultrices, non pede cupiditate mollis lorem condimentum,
    suscipit integer etiam mauris amet. Magna rutrum cras, tincidunt lacus ut, lectus donec

    Lorem ipsum dolor sit amet, nullam eros posuere quam, non ipsum ornare vehicula. In integer, ac tempus aenean lorem nec amet ac, non blandit class, eget odio eu, mollis mauris massa. In augue erat convallis, morbi lectus lobortis tempor in lorem. Dis
    et morbi consectetuer non, tempor pretium. Leo dolor erat orci, lobortis adipisicing scelerisque integer diam lorem, tempus non, dolor libero vivamus velit. Viverra ipsum quam id in arcu, ligula tortor laoreet fermentum sit ipsum. Erat dapibus nulla
    justo vitae, feugiat nullam felis sollicitudin, dolor wisi mauris, tristique tempus nunc tristique. Velit non, duis auctor a. Ipsum pede maecenas vestibulum id ornare, ac facilisi wisi maecenas sem ultrices, non pede cupiditate mollis lorem condimentum,
    suscipit integer etiam mauris amet. Magna rutrum cras, tincidunt lacus ut, lectus donec,

A: The above code is already working fine and it isn't stacking one below the other I guess, can you tell me when did it stack one below the other.

A: Just try this add width to container & child elements.

#mainContainer
{
    width:1490px;
    height:auto;
    overflow-x: auto;
}
#firstBox {
    background-color: gray;
    margin: 10px;
    padding: 10px;
    width: 700px;
    height: auto;
    float: left;

}

#secondBox {
    background-color: gray;
    margin: 10px;
    padding: 10px;
    width: 700px;
    height: auto;
    left:750px;
    float: left;

}

            Lorem ipsum dolor sit amet, nullam eros posuere quam, non ipsum
            ornare vehicula. In integer, ac tempus aenean lorem nec amet ac, non
            blandit class, eget odio eu, mollis mauris massa. In augue erat
            convallis, morbi lectus lobortis tempor in lorem. Dis et morbi
            consectetuer non, tempor pretium. Leo dolor erat orci, lobortis
            adipisicing scelerisque integer diam lorem, tempus non, dolor libero
            vivamus velit. Viverra ipsum quam id in arcu, ligula tortor laoreet
            fermentum sit ipsum. Erat dapibus nulla justo vitae, feugiat nullam
            felis sollicitudin, dolor wisi mauris, tristique tempus nunc
            tristique. Velit non, duis auctor a. Ipsum pede maecenas vestibulum
            id ornare, ac facilisi wisi maecenas sem ultrices, non pede
            cupiditate mollis lorem condimentum, suscipit integer etiam mauris
            amet. Magna rutrum cras, tincidunt lacus ut, lectus donec

            Lorem ipsum dolor sit amet, nullam eros posuere quam, non ipsum
            ornare vehicula. In integer, ac tempus aenean lorem nec amet ac, non
            blandit class, eget odio eu, mollis mauris massa. In augue erat
            convallis, morbi lectus lobortis tempor in lorem. Dis et morbi
            consectetuer non, tempor pretium. Leo dolor erat orci, lobortis
            adipisicing scelerisque integer diam lorem, tempus non, dolor libero
            vivamus velit. Viverra ipsum quam id in arcu, ligula tortor laoreet
            fermentum sit ipsum. Erat dapibus nulla justo vitae, feugiat nullam
            felis sollicitudin, dolor wisi mauris, tristique tempus nunc
            tristique. Velit non, duis auctor a. Ipsum pede maecenas vestibulum
            id ornare, ac facilisi wisi maecenas sem ultrices, non pede
            cupiditate mollis lorem condimentum, suscipit integer etiam mauris
            amet. Magna rutrum cras, tincidunt lacus ut, lectus donec,


text:
Q: DB2: FAILED: CDIPR2123I: Ensure that the database xmeta is empty I am installing InfoSphere V1171 on Linux RHEL 7.
When I am trying to install InfoSphere but in the validation step I get the error:
FAILED: CDIPR2123I: Ensure that the database xmeta is empty

I have tried to drop the table using the below command and recreate the DB but the error reappears:
db2 drop database xmeta

How can I clear the DB?


text:
Q: Put Information form Content Script into popout.html- Chrome Extensions I wrote a content script for a chrome extension that parses information from a website and displays them to the user. I can see this information if I console log it so I know the script is getting the information I want, but I don't know how to send that back to the popout I made.
So for example I have a line that pulls the header from a website the user is on
titlearea = document.getElementById("titlelarge").innerText;

However when I try to set the the title element in my popout.html file to titlearea nothing happens. Obviously the information isn't getting there. How do I transfer all the data I collect?
-Thanks

A: in you content script, send the data you want to show to popout page with sendMessage API
then you can show the data:)