text:
Q: Should I use margin or padding when formatting a text? I am designing some CSS for my site. I need to format (add some proper spacing between headers and paragraphs) a section of uniform text with headers and paragraphs on a single background. This can be done using either margin or padding property. I do understand the difference between these two in CSS. Also, there are a plenty of questions on SO regarding usage of these CSS properties:

*

*Difference between margin and padding?

*When to use margin vs padding in CSS

*Margin or padding what is recommended?
However, no question shades the light on what property should be used for proper text formatting. Let's say I need to format the text like this:

Should I use margin or padding to control spacing between text elements (header and paragraphs)? What is recommended to use on
 and <h..> tags? What is the common practice?
Here is what I came up with for now:

/* tiny reset */
html { font-size: 10px; }
html, body { margin: 0; padding: 0; }
* { box-sizing: border-box; }

p {
  font-family: 'Roboto', sans-serif;
  font-size: 1.6rem;
  line-height: 2.5rem;
  margin: 0.6rem 0 2.0rem 0;
  padding: 0 2px 4px 2px;
  width: 100%; /* Opera needs this */
  text-rendering: optimizeLegibility;
}

h1, h2 {
  font-family: 'Roboto', sans-serif;
  font-weight: 700;
  text-align: center;
  text-transform: uppercase;
  padding: 0 2px 4px 2px;
  text-rendering: optimizeLegibility;
}
h1 {
  font-size: 4.0rem;
  line-height: 4.0rem;
  margin: 2.6rem 0 2.0rem 0;
}
h2 {
  font-size: 3.2rem;
  line-height: 3.2rem;
  margin: 2.4rem 0 2.0rem 0;
}

.wrap {
  margin: 20px;
  padding: 20px;
  -webkit-box-shadow: 0px 0px 12px 4px rgba(0,0,0,0.3);
  -moz-box-shadow: 0px 0px 12px 4px rgba(0,0,0,0.3);
  box-shadow: 0px 0px 12px 4px rgba(0,0,0,0.3);
}

The last declaration of a block doesn't need to be terminated by a semi-colon, though it is often considered good style to do it as it prevents forgetting to add it when extending the block with another declaration.

CSS statements

If style sheets could only apply a declaration to each element of a Web page, they would be pretty useless. The real goal is to apply different declarations to different parts of the document.

CSS allows this by associating conditions with declarations blocks. Each (valid) declaration block is preceded by a selector which is a condition selecting some elements of the page. The pair selector-declarations block is called a ruleset, or often simply a rule.

A: line-height is used to control the spacing between lines of a paragraph. Margin is used between elements containing only text, generally. This isn't much different than standard typography used in print.
So you set the line height for a heading and then control how much space you want underneath it with margin. Just as you would for any other component. The space between paragraphs is margin. However, the space between individual lines of a paragraph are controlled with line height.
All of this can also be used to set a vertical rhythm on a page. You should Google for that.
One good reference for this is The Elements of Typographic Style Applied to the Web

A: I don't think it's a black and white matter. Though I am a big fan of paddings. You should really use what you feel is best.
For me padding is for spacing what's inside and margin for spacing what's outside. Sometimes padding can cause problems with the box-model dimensions, other times it can conflict with a background-image. Margins in the other hand can break layouts and can collapse.
So you really need to understand how each property affects the box-model and flow and use whichever you are comfortable with. Also worth noting that margin accepts negative values while padding does not.
If you wanted to add space that does not affect the layout flow, you could resort to positioning.

A:
I narrowed the situation: I need to format a section of uniform text with headers and paragraphs on a single background.

For the space between the border of the container element and the text content, you'd probably want to use a padding on that container element. Of course you could use margins on the inner paragraph and headline elements as well – but that would be two different types of elements you'd have to format that way. So, setting a padding once on one element, or margins one multiple elements – which seems more efficient, and probably easier to maintain?
As for the spacing between the paragraphs and headlines themselves – here you might want to use margins, because margins can collapse.
Let's say you had
h2 { margin-top: 15px; margin-bottom: 30px; }
p  { margin-top: 10px; margin-bottom: 10px; }

(The h2 has a bigger font-size, so often it is desirable from a typographic perspective, that it should keep more distance to the preceding/following content as well, as say two paragraph elements directly following each other.)
Now with a headline followed by a paragraph in your HTML, with collapsing margins, that 30px bottom margin of the headline and the 10px top margin of the paragraph still result in 30px overall distance between those elements – whereas paddings with the same values would simple add up, and you'd get 40px distance between those two elements.


text:
Q: How to draw a Polyline using a Cartesian array? I need to draw a polyline using the mouse click.
All examples I've found only show the polyline positions using a Cesium.Cartesian3.fromDegreesArray:
var glowingLine = viewer.entities.add({
    name : 'Glowing blue line on the surface',
    polyline : {
        positions : Cesium.Cartesian3.fromDegreesArray([-75, 37,
                                                        -125, 37]),
        width : 10,
        material : new Cesium.PolylineGlowMaterialProperty({
            glowPower : 0.2,
            taperPower : 0.5,
            color : Cesium.Color.CORNFLOWERBLUE
        })
    }
});

But I need to use a cartesian comming from
var cartesian = viewer.camera.pickEllipsoid( movement.position, scene.globe.ellipsoid );

This is what I've done but with no success:
// Just to illustrate the mouse click consider movement.position different here.

var cartesian1 = viewer.camera.pickEllipsoid( movement.position, scene.globe.ellipsoid );
var cartesian2 = viewer.camera.pickEllipsoid( movement.position, scene.globe.ellipsoid );

    var entity = viewer.entities.add({
        polyline: {
            positions: [cartesian1, cartesian2],
            width : 5,
            material : new Cesium.PolylineOutlineMaterialProperty({
                color : Cesium.Color.ORANGE,
                outlineWidth : 2,
                outlineColor : Cesium.Color.BLACK
            })
        }
    });

This don't work. The error is:
An error occurred while rendering. Rendering has stopped.
RangeError: invalid array length
m.generateArc@http://localhost:36215/resources/Cesium/Workers/createPolylineGeometry.js:231:7308
m.generateCartesianArc@http://localhost:36215/resources/Cesium/Workers/createPolylineGeometry.js:231:8334
T.createGeometry@http://localhost:36215/resources/Cesium/Workers/createPolylineGeometry.js:231:12962
n@http://localhost:36215/resources/Cesium/Workers/createPolylineGeometry.js:231:14985
o@http://localhost:36215/resources/Cesium/Workers/createGeometry.js:231:22277
i@http://localhost:36215/resources/Cesium/Workers/createGeometry.js:231:21277
a/<@http://localhost:36215/resources/Cesium/Workers/createGeometry.js:231:21418

I have a 3D globe with terrain heights.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue Using Flex SDK in Flash Professional (for as3corelib) I recently found Mike Chambers' as3corelib when looking for ways to render the stage to a file. Works great in my ActionScript 3.0 project in Flash Professional (CS6 if it matters).
I decided to look at some of Mike's utility classes, notably the date related ones. However, his DateUtil class imports mx.formatters.DateBase, and when I attempt to use some of the methods, I'm getting lots (and lots) of "Access of undefined property DateBase."
I'm assuming that's because some reference to the Flex SDK is missing or wrong. I've added $(FlexSDK)/frameworks/libs/flex.swc to my project's Library path, but that's not helping.
I've used Flash for years, but this is my first truly code-centric project, and still learning through the school of hard knocks. No idea what's going wrong here. Ideas?

Example from as3corelib
package com.adobe.utils
{
    import mx.formatters.DateBase;

    /**
    *   Class that contains static utility methods for manipulating and working
    *   with Dates.
    */
    public class DateUtil
    {

        /**
        * Returns a date string formatted according to RFC822.
        */
        public static function toRFC822(d:Date):String
        {
            var date:Number = d.getUTCDate();
            var hours:Number = d.getUTCHours();
            var minutes:Number = d.getUTCMinutes();
            var seconds:Number = d.getUTCSeconds();
            var sb:String = new String();
            sb += DateBase.dayNamesShort[d.getUTCDay()];
            sb += ", ";

...

The line:
sb += DateBase.dayNamesShort[d.getUTCDay()];

...generates the mentioned error, as does any other DateBase reference in the class. Again, this code is directly from the latest as3corelib, located on GitHub:  https://github.com/mikechambers/as3corelib

A: Don't know whether you got this one licked or not, but I hit the same thing.  Love the library, hate the error messages.
I downloaded the Flex SDK from here:
Adobe Flex SDK Download
Then, I unzipped that into a temporary folder.
Then, since I didn't want the whole flex framework lurking about, I created a ./lib directory inside the directory where the .fla file lives.  I then moved these swcs from here (Inside the unzipped file structure):
mv ~/Downloads/flex_sdk_4.6/frameworks/libs/framework.swc ./lib
mv ~/Downloads/flex_sdk_4.6/frameworks/libs/core.swc ./lib
mv ~/Downloads/flex_sdk_4.6/frameworks/libs/mx/mx.swc ./lib

Not sure why all three were required, but it stopped the compiler complaining (and got the date conversions working).
You need to add them to the .fla's library list as well (under ActionScript Settings); but I'm betting you already knew that.
Perhaps useful, perhaps not.


text:
Q: remove tikzpicture border I am trying to load a picture as a whole pdf page, so I use below code to load the image as a node and use adjust box package to enlarge it to whole page:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{backgrounds}
\usepackage{graphicx}
\usepackage[a4paper,margin=0pt]{geometry}
\usepackage{adjustbox}

\begin{document}
%https://upload.wikimedia.org/wikipedia/commons/1/16/Mycena_interrupta.jpg
\def\imgfile{Mycena_interrupta.jpg}
\begin{adjustbox}{width=\paperwidth,height=\paperheight}
  \begin{tikzpicture}[background rectangle/.style={fill=red!40},show background rectangle]
    \node (N) { \includegraphics{\imgfile}};
  \end{tikzpicture}
\end{adjustbox}
\clearpage
\end{document}

But it seems tikzpicture has a border,just as the red!40 color indicated:

A: Following my comment, this is my solution:

\documentclass{article}
\usepackage{tikz}
\begin{document}
\pagestyle{empty}
\begin{tikzpicture}[remember picture,overlay]
\node at (current page.south west) [above right,inner sep=0,outer sep=0]
    {\includegraphics[width=\paperwidth,height=\paperheight]{Mycena_interrupta}};
\end{tikzpicture}
\end{document}


text:
Q: System Logs out when unused for some time instead of going into lock screen I have switched to XFCE4 some days back from Unity, but now i again switched to Unity. From that time onwards I am facing following problem.
My system logs out automatically when unused for some time, say 2 minutes (according to My Brightness And Lock Settings) and goes to Switch user screen instead of lock screen
How to tackle this problem ?


text:
Q: PDFBox 2.0.0 - decryption using password I'm trying to unlock a PDF using a password with PDFBox 2.0.0.
In 1.8.11 I was using the PDDocument.openProtection(DecryptionMaterial pm) method but it was removed in 2.0.0 from what I see.
The online documentation does not say how this can be achived in 2.0.0.
Question:
The PDF unlocking with password is still possible in PDFBox 2.0.0?

A: In 2.0, you just call PDDocument.load(file, password) or PDDocument.load(file) (if the password is empty). You don't have to call openProtection() anymore. The load() of 2.0 call is similar to the loadNonSeq() call of 1.8.

A: I used the latest version with the following code:
  PDDocument pd = PDDocument.load(ResourceUtils.getFile("[Your_File_Path]"), "[Your_Password]");
  pd.setAllSecurityToBeRemoved(true);
  pd.save("[New_FileName.pdf]");

pom.xml
<dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.22</version>
    </dependency>
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk15on</artifactId>
        <version>1.68</version>
    </dependency>
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcmail-jdk15on</artifactId>
        <version>1.68</version>
    </dependency>


text:
Q: Deleting certain rows in dataframe with groupby I have a dataframe of companies (represented by 'SCU_KEY') that are either customers or just prospects (shown as 'REVENUE_STATUS_FLAG'). Most SCU_KEYs have multiple entries and is updated regularly throughout time. I can't just delete rows that contain 0 in the dataframe, because it's important in my analysis to see moments when it goes from 1 to 0 or if 0 then returns to 1. My best assumption to solve it is through groupby, where if I group the SCU_KEY and the summation REVENUE_STATUS_FLAG is 0, that means that company (SCU_KEY) has only been a prospect and has not had an instance of adopting the product (open to hear alternative ways such as a lambda function for the df/groupby). The code is below and again the goal is to delete rows that contain 0 in the groupby (also containing the image of my returned code) and then make sure those SCU_KEYs are no longer accounted for in the df:

df_4.groupby('SCU_KEY')[['REVENUE_STATUS_FLAG']].sum()

A: Use transform and a boolean mask to filter your dataframe:
df_4[df_4.groupby('SCU_KEY')['REVENUE_STATUS_FLAG'].transform('sum').gt(0)]

Example:
>>> df_4
   SCU_KEY  REVENUE_STATUS_FLAG
0        1                    0  # drop
1        1                    0  # drop
2        1                    0  # drop
3        2                    0
4        2                    1
5        2                    0
6        3                    0
7        3                    0
8        3                    2

>>> df_4[df_4.groupby('SCU_KEY')['REVENUE_STATUS_FLAG'].transform('sum').gt(0)]
   SCU_KEY  REVENUE_STATUS_FLAG
3        2                    0
4        2                    1
5        2                    0
6        3                    0
7        3                    0
8        3                    2

A: You can also use:
df = pd.DataFrame(data={'scu_key':[1,1,1,2,2,2,3,3,3], 'revenue_status_flag':[0,0,0,1,0,1,1,0,1]})
df = df[df.groupby('scu_key')['revenue_status_flag'].transform(lambda x:  ~(x==0).all())]

Input:
   scu_key  revenue_status_flag
0        1                    0
1        1                    0
2        1                    0
3        2                    1
4        2                    0
5        2                    1
6        3                    1
7        3                    0
8        3                    1

Output:
   scu_key  revenue_status_flag
3        2                    1
4        2                    0
5        2                    1
6        3                    1
7        3                    0
8        3                    1


text:
Q: Base-from-Member Idiom in C++ The following code is from here:
#include <streambuf>  // for std::streambuf
#include <ostream>    // for std::ostream

class fdoutbuf
    : public std::streambuf
{
public:
    explicit fdoutbuf( int fd );
    //...
};

class fdostream
    : public std::ostream
{
protected:
    fdoutbuf buf;
public:
    explicit fdostream( int fd )
        : buf( fd ), std::ostream( &buf ) // This is not allowed.
                                          // buf can't be initialized before std::ostream.
        {}
    //...
};

I didn't really understand the comment. Why "buf can't be initialized before std::ostream"? Can I use some help understanding this?

A: The order of initialization is determined by the order of declaring your class members, and inherited classes come before all of that. Take a simple example that illustrate the basic problem without referring to inheritance :
class C
{
  int a, b;
public:
  C() : b(1), a(b) {} // a is initialized before b!
};

The code doesn't do what you think! a is initialized first, then b is initialized to one. So it depends on the order of the declaration not the order in the initialization list:
int a, b;

Now, the same idea applies to base classes which are initialized before the derived class members. To solve this problem, you create a class that you inherent which contains the member you want to initialize from a base class. Of course, that helper class must come before the one you are actually deriving from.

A: You have to call the base class constructor before you initialize your member variables, but you pass a pointer to buf (a member variable which is undefined at this point) to this constructor.


text:
Q: Indefiniteness of KKT system I know this is a trivial problem but am stuck with this thing.
$A \in \mathbb{R}^{m \times m}$ is a symmetric positive definite matrix and $C \in \mathbb{R}^{m \times p}$
How do I show that the matrix $$B = \begin{bmatrix} A & C \\ C^T & 0 \end{bmatrix}$$ is indefinite?
I can show that there exists a vector $v$ such that $v^TBv > 0$.
(This is trivial. For instance, $v = [x , 0]^T$ where $x \in \mathbb{R}^{1 \times m}$ and $0 \in \mathbb{R}^{1 \times p}$)
Now how do I find a vector such that $v^TBv < 0$.
I do not need the answer. A clue/hint is welcome.
You can assume that $p \leq m$ and the matrix $C$ is full rank that is to say that all the constraints are linearly independent.
Thanks

A: Hint for a less convoluted argument: Unless $C$ is zero (in which case the statement is false), there are vectors $x$ and $y$ such that $x^T C y$ is a nonzero $1\times 1$ matrix. Now consider $v=[x,ky]^T$ for large $k$ (positive or negative, depending on the sign of $x^T C y$).

A: Ok. So I figured it out. But I think my argument is really convoluted. I would appreciate if someone could come up with a simpler argument.
Without loss of generality, we can assume that the matrix $C$ is of full-rank $p$.
First let $B = \begin{bmatrix} A & C \\ C^T & 0 \end{bmatrix}$, where $A \in \mathbb{R}^{m \times m}$ and $C \in \mathbb{R}^{m \times p}$.
The first observation is that all the eigenvalues of this matrix have to be real. This is so since the matrix $B$ is symmetric. Also, the matrix $B$ has an eigenvalue decomposition.
Clearly, $\exists x$ such that $x^TBx > 0$. For instance, $x = [x_1 , 0]^T$ where $x_1 \in \mathbb{R}^{1 \times m}$ and $x_1 \neq 0$ and $0 \in \mathbb{R}^{1 \times p}$. Then $x^TBx =x_1^TAx_1 > 0$ since $A$ is positive definite.
Now, if we consider $x=[0,x_2]^T$ where $x_2 \in \mathbb{R}^{1 \times p}$ and $x_2 \neq 0$ and $0 \in \mathbb{R}^{1 \times m}$, then $x^TBx = 0$.
So $B$ is not positive definite. And since $B$ is symmetric, there is an eigenvalue decomposition for $B$. And hence $\exists \lambda$ such that $\lambda \leq 0$.
Now, we need to prove that $\exists \lambda$ such that $\lambda < 0$.
Now, we recognize that the matrix $B$ is full-rank.
This can be seen from the fact that the null space of the matrix $B$ is trivial.
Let $ z = \begin{bmatrix} x \\ y \end{bmatrix}$ such that $Bz = 0$.
Then we have $Ax + Cy = 0$ and $C^Tx = 0$. So we have $x = -A^{-1}Cy$ and hence we get $C^TA^{-1}Cy = 0$.
The matrix $C^TA^{-1}C$ is positive definite. This is because $C$ is full rank and is a skinny matrix. So whenever $x \neq 0$, $x^* = Cx \neq 0$ and hence $x^TC^TA^{-1}Cx = {x^*}^TA^{-1}x^* > 0$ (Since $A^{-1}$ is also positive definite).
Hence, $y=0$ is the only possible solution which implies $x=0$ and hence $z=0$ is the only vector in the null space.
So the matrix $B$ is of full-rank.
Hence, none of the eigenvalues are zero i.e. $\forall \lambda$, $\lambda \neq 0$.
Also, from previous argument, we have that $\exists \lambda$ such that $\lambda \leq 0$.
Hence, we can conclude that $\exists \lambda$ such that $\lambda < 0$. So if I choose the (or) a eigenvector $v$ corresponding to this $\lambda$, then I have $v^TBv = - \lambda ||v||_2^2 < 0$.
Hence, the matrix $B$ is Indefinite.

A: Consider $$z = \begin{bmatrix}x\\ y\end{bmatrix}^T$$ with $x \in R^m$ and $y \in R^p$
Then $$f(z) = z^TBz = x^TAx + 2x^TCy$$ which containts a bilinear term, which is linear as a function of $y$. Hence given an $x$, an appropriate $y$ can be chosen such that the $f(z) < 0$


text:
Q: Laravel default mail after applying ssl not working I am not receiving password reset mail after applying SSL on my site.Can anyone pls guide me.Only default laravel mails are not working other mails with Mailer class are working fine.
1..env Mail Setting on godday server
MAIL_DRIVER=smtp
MAIL_HOST=localhost
MAIL_PORT=25
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=
On reset password getting success msg but not receiving mail.I already tried too many solution from stakeoverflow.Pls guide me.Thanks in advance.


text:
Q: Memory leaks because of event handlers Currently, I have to fix an existing Silverlight application that's leaking a lot of memory. Using Redgate's ANT profiler I managed to detect possible problems. One of them is a static class that wraps around a web service, which contains two event handlers to support an asynchronous calculation.
And you've guessed it... A lot of objects assign an event to this handler but most don't release it again. As a result, those objects are linked to these static events and thus almost never released...
I need a simple fix to work around this problem. So, what possible options do I have to fix this memory leak without these changes having a lot of impact?
Making the event handlers non-static will result in a huge change, thus an undesired action...

A: Use the Weak Event pattern (don't know if it's possible with SL). This will allow a dirtier programming model with calling your static method.
A better alternative whould be to properly subscribe / unsubscribe events (agreeing with  tomasmcguinness), but this implies you can change the calling code and/or ask the consumers to better develop.
Another solution could to use async patterns. Maybe waiting for a Callback delegate in your method call, or even better, return a Task object.


text:
Q: Datatables load records per page in real time I have the plugin datatables 1.10 and I am trying to reduce the loading times, I currently have more than 1000 records that have to be shown in the table, and I have it configured to be paginated.
The problem is that when you load the page what you do is load all the records and once loaded it shows all the content and the page, I have since per page it shows 6 records.
What I want or would like is that when I load the page I only have to load the records of the current page, if I have to load the next page, then I would load the records of the page again.
I tried with "serverSide: true," but what it does is load them all without pagination.
This is my code actually:
var showcontent = baseurl+"transaction/showcontent";
var table = $('#datatablecontent').DataTable({
"responsive": true,
"processing": true,
    "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "Todos"]],
    "ajax": {
        "url": showcontent,
        "type": "POST"
},
"autoWidth": false,
'columnDefs': [
  { 'width': 10, 'targets': 1 },
  { 'width': 5, 'targets': 2 },
  { 'width': 5, 'targets': 3 },
  { 'width': 5, 'targets': 4 },
  { 'width': 55, 'targets': 5 },
  { 'width': 30, 'targets': 6 },
  { 'width': 20, 'targets': 7 },
  { 'width': 20, 'targets': 8 , 'visible': false},
  { 'width': 40, 'targets': 9 },
  { 'width': 20, 'targets': 10 , 'visible': false},
  { 'width': 20, 'targets': 11 , 'visible': false},
  { 'width': 20, 'targets': 12 , 'visible': false},
  { 'width': 20, 'targets': 13 },
  { 'width': 20, 'targets': 14 },
  { 'width': 10, 'targets': 15 },
  { 'width': 20, 'targets': 16 , 'visible': false},
  { 'width': 10, 'targets': 17 },
  { 'width': 10, 'targets': 18 },
  { 'width': 10, 'targets': 19 },
  { 'width': 10, 'targets': 20 , 'visible': false},
  { 'width': 10, 'targets': 21 , 'visible': false},
  { 'width': 50, 'targets': 22 },
  { 'targets': 0,'searchable':false,'orderable':false,}
  //{ 'targets': 1,'searchable':false,'orderable':false,}
],
"fixedColumns": true,
"iDisplayLength": 5,
"order": [[ 2, "desc" ]]
});

File php/codeigniter: transaction(controller)
public function showcontent(){
...
//Here before is the code from send data json
$output = array(
              "data" => $data,
  );
echo json_encode($output);
}

A: You need to use server-side script that will paginate results in addition to enabling server-side processing mode with serverSide: true.
With PHP you can use ssp.class.php that is available in /examples/server_side/scripts folder when you download DataTables library.
There is also a sample script server_processing.php in /examples/server_side/scripts folder that shows how to use it.


text:
Q: Further reading on the $p$-adic metric and related theory. In his book Introduction to Topology, Bert Mendelson asks to prove that
$$(\Bbb Z,d_p)$$
is a metric space, where $p$ is a fixed prime and
$$d_p(m,n)=\begin{cases} 0 \;,\text{ if }m=n \cr {p^{-t}}\;,\text{ if } m\neq n\end{cases}$$
where $t$ is the multiplicty with which $p$ divides $m-n$. Now, it is almost trivial to check the first three properties, namely, that
$$d(m,n) \geq 0$$
$$d(m,n) =0 \iff m=n$$
$$d(m,n)=d(n,m)$$
and the only laborious was to check the last property (the triangle inequality). I proceeded as follows:
Let $a,b,c$ be integers, and let
$$a-b=p^s \cdot k$$
$$b-c=p^r \cdot l$$
where $l,k$ aren't divisible by $p$.
Then $$a-c=(a-b)+(b-c)=p^s \cdot k+p^r \cdot l$$
Now we have three cases, $s>r$, $r>s$ and $r=s$. We have respectively:
$$a-c=(a-b)+(b-c)=p^r  \cdot(p^{s-r} \cdot k+  l)=p^r \cdot Q$$
$$a-c=(a-b)+(b-c)=p^{s} \cdot(   k+p^{r-s} \cdot l)=p^s \cdot R$$
$$a-c=(a-b)+(b-c)=p^s \cdot (k+l)=p^s \cdot T$$
In any case,
$$d\left( {a,c} \right) \leqslant d\left( {a,b} \right) + d\left( {b,c} \right)$$
since
$$\eqalign{
  & \frac{1}{{{p^r}}} \leqslant \frac{1}{{{p^s}}} + \frac{1}{{{p^r}}}  \cr
  & \frac{1}{{{p^s}}} \leqslant \frac{1}{{{p^s}}} + \frac{1}{{{p^r}}}  \cr
  & \frac{1}{{{p^s}}} \leqslant \frac{1}{{{p^s}}} + \frac{1}{{{p^s}}} \cr} $$
It might also be the case $k+l=p^u$ for some $u$ so that  the last inequality is
$$\frac{1}{{{p^{s + u}}}} \leqslant \frac{1}{{{p^s}}} + \frac{1}{{{p^s}}}$$
$(1)$ Am I missing something in the above? The author asks to prove that in fact, if $t=t_p(m,n)$ is the exponent of $p$, that
$$t\left( {a,c} \right) \geqslant \min \left\{ {t\left( {a,b} \right),t\left( {b,c} \right)} \right\}$$
That seems to follow from the above arguement, since if $s \neq r$ then
$$t\left( {a,c} \right) = t\left( {a,b} \right){\text{ or }}t\left( {a,c} \right) = t\left( {b,c} \right)$$
and if $s=r$ then
$$t\left( {a,c} \right) \geqslant t\left( {a,b} \right){\text{ or }}t\left( {a,c} \right) \geqslant t\left( {b,c} \right)$$
$(2)$ Is there any further reading you can suggest on $p$-adicity?

A: I am currently trying to learn about $p$-adic numbers and analysis too, so I too would be really interested to hear the opinions of people who know more than I do about this. I am currently using the following three texts, but don't intend to work through them fully; just enough to get something useful for a better understanding of how they can be used in number theory:

*

*Koblitz - "$p$-adic Numbers, $p$-adic Analysis, and Zeta-functions" - The first chapter I have found very interesting, and pretty well-written, with lots of easy exercises to get used to the concepts, as well as some harder ones to test deeper understanding.

*Robert - "A Course in $p$-adic Analysis" - covers much more material at a more advanced level than Koblitz, but isn't (quite) as off-putting as it seems at first, and it possible to pick out quite a few bits from the first two chapters which are illuminating.

*Borevich and Shafarevich - "Number Theory" - This one has some relatively understandable stuff on $p$-adic numbers in the first chapter which I have found really useful as it gives a different feel to the topic in a rather more old-fashioned approach.

A: What you have done seems correct. Also notice that from what you have done you get that
$$
d(a,c) \leq \max \{d(a,b), d(b,c) \},
$$
which is stronger than the triangle inequality.
For an introduction to $p$-adic numbers, I would suggest Fernando Gouvea's $p$-adic Numbers: An introduction. It should be easy for an undergraduate to understand the book, and I think it is a very nice introduction.
Edit: I should add that it's not easy for any undergraduate. One should've had a few courses which have a lot of proofs, and not just the standard calculus courses.

A: Your argument looks fine to me.

A very good online introduction to $p$-adics are these notes; it covers modular arithmetic leading up to Hensel's, basic analysis with the numbers, the very strange metric topology of $\Bbb Q_p$ (every point inside of a ball is a center, there are locally but not globally constant functions, etc.), and a bit of field theory and algebraic number theory.
I don't really have any recommendation for number-theoretically in-depth stuff. Also, I tend to stick to online documents because the web is where I spend all my time anyway.
In actuality, my favorite discussion is p-adic integration and the theory of groups, which involves category theory and abstract algebra (the $p$-adics are constructed as an inverse limit of topological rings, for example), as well as measure theory and group theory. This source perhaps takes more background to digest its contents satisfactorily, but it hits my buttons well.
Just for fun, I also suggest Pictures of Ultrametric Spaces. Related entertainment: (working with adeles) the character group of $\Bbb Q$ and (working with profinite integers) profinite Fibonacci numbers.


text:
Q: Block device - Initialize gendisk structure when not multiple of 512 bytes I'm currently learning kernel driver programmation using Linux Device Drivers - 3rd.
To define a block device, I have to declare a gendisk structure and to initialize it with relevant informations.
In chapter 16 its written:

sector_t capacity;
The capacity of this drive, in 512-byte sectors. The sector_t type can be 64 bits wide. Drivers should not set this field directly;
  instead, pass the number of sectors to set_capacity.

Usualy I set the capacity using a call like:
set_capacity(gendisk, sector_number*(hard_sector_size/KERNEL_SECTOR_SIZE));

Imagine that I have a device with a memory zone that is not a multiple of 512 bytes.
Let's take 2000 bytes so there is three 512 bytes zones plus a 464 bytes zone
[-512b-]      [-512b-]      [-512b-]      [-464b-]
0     511    512    1023   1024   1535   1536   1999

*

*What should I pass to set_capacity ?

Furthermore on some devices, memory is splitted into several areas. Imagine that I have a device containing multiple memory areas, each with different size and that I want to abstract this splitted memory into a single memory zone.
area1 => 32000 bytes
area2 => 512 bytes
area3 => 50 bytes
area4 => 45 bytes
area5 => 1024 bytes
In this case the hard sector size is not a constant within the device.

*

*How should I fill the gendisk structure ?

UPDATE after @KamilCuk answer:
To continue with this example let's take the full device memory (33631 bytes) which is 65 sectors of 512 bytes + 1 sector of 351 bytes.
So the solutions are to present it either as:

*

*33270 bytes memory zone ==> 65 sectors

or

*

*33631 bytes memory zone ==> 66 sectors with 161 bytes discarded at the end of last sector

Are those the best solutions or there is another way to handle this specific case ?

*

*Basically the question could be resumed to how to initialize a block device when it's not a multiple of KERNEL_SECTOR_SIZE?

A: *

*What should I pass to set_capacity ?
From lwm.net article:

The size value should be in 512-byte sectors, even if the hardware sector size used by your device is different.

Pass that you have 3 sectors, thus be compatible with kernel and ignore last sector.
Or pass that you have 4 sectors of 512, discard the bytes from 464 to 512 on the last sector on write and fill with zeros on read. Be sure, that all drivers that use your driver know, that the last sector is smaller and can act on it.

*

*How should I fill the gendisk structure ?
To be true, with your block driver implementation. You are implementing block driver not filesystem driver, files are on the upper level. A filesystem can implement multiple files saved between blocks or in the same block of underlying block device. (like btrfs can compress small files to one block)


text:
Q: Regex starting with a string I want to filter the following string with the regular expressions:
TEST^AB^^HOUSE-1234~STR2255

I wanna get only the string "HOUSE-1234" and I've to test the string always with the beginning "TEST^AB^^" and ending with the "~".
Can you please help me how the regex should look like?

A: You can use \^\^(.*?)\~ pattern which matches start with ^^ and ends with ~
string s = @"TEST^AB^^HOUSE-1234~STR2255";
Match match = Regex.Match(s, @"\^\^(.*?)\~", RegexOptions.IgnoreCase);

if (match.Success)
{
    string key = match.Groups[1].Value;
    Console.WriteLine(key);
}

Output will be;
HOUSE-1234

Here is a DEMO.

A: string input = "TEST^AB^^HOUSE-1234~STR2255";
var matches = Regex.Matches(input, @"TEST\^AB\^\^(.+?)~").Cast<Match>()
                .Select(m => m.Groups[1].Value)
                .ToList();

A: string pattern=@"\^\^(.*)\~";
Regex re=new Regex(pattern);

A: You should do this without regex:
    var str = "TEST^AB^^HOUSE-1234~STR2255";
    var result = (str.StartsWith("TEST^AB^^") && str.IndexOf('~') > -1)
                ? new string(str.Skip(9).TakeWhile(c=>c!='~').ToArray())
                : null;
    Console.WriteLine(result);

A: With the little information you've given us (and assuming that the TEST^AB isn't necessarily constant), this might work:
(?:\^\^).*(?:~)

See here
Or if TEST^AB is constant, you can throw it in too
(?:TEST\^AB\^\^).*(?:~)

The important part is to remember that you need to escape the ^

A: Don't even need the RegEx for something that well defined. If you want to simplify:
string[] splitString;
if (yourstring.StartsWith("TEST^AB^^"))
{
    yourstring = yourstring.Remove(0, 9);
    splitString = yourstring.Split('~');
    return splitString[0];
}
return null;

A: (TEST\^AB\^\^)((\w)+-(\w+))(\~.+)
There are three groups :
(TEST\^AB\^\^) : match yours TEST^AB^^
((\w)+\-(\w+)) : match yours HOUSE-123
(\~.+) : match the rest


text:
Q: Unable to install "Runner" on real device I'm using Flutter 3.0.4.
I run my app on my iPhone connected by USB, and I got this error:

The details button shows this:

I'm sure about that there is not duplicate bundle ID on apple developer or my phone.

A: *

*Press shift+command+k to clean build folder.

*Check your info.plist and AppFrameworkInfo.plist, bundle identifier should not be the same.


text:
Q: Db2 - Returning the top 5 of each category I want to be able to return 5 menuitem per menu.
Here are the tables

menus
-------
menuid int()
profileName varchar(35)

menuitems
-----------
itemid int()
name varchar(40)
menuid int()

I do see a solution for MySQL in this thread - mySQL Returning the top 5 of each category, looking for similar solution for DB2.
Any suggestion is great appreciated.

A: something like:
select ...
from (
    select ..., row_number() over ( partition by m.menuid
                                    order by ? ) as rn
    from menus m
    join menuitems mi
        m.menuid = mi.menuid
)
where rn <= 5;

Troels Arvin has a comparision of different DBMS at:
http://troels.arvin.dk/db/rdbms/

Amongst other things quota queries (such as the one you are asking) are discussed


text:
Q: Why is a function call without an argument in setState called before setState? As was pointed out to me in another question, if I have a function call without an argument in setState, randomQuoteIndex(), and the function uses a state set in that setState, it's called before setState.
  componentDidMount() {
        fetch('https://gist.githubusercontent.com/nataliecardot/0ca0878d2f0c4210e2ed87a5f6947ec7/raw/1802a693d02ea086817e46a42413c0df4c077e3b/quotes.json')
          .then(response => response.json())
          .then(quotes => this.setState({
              quotes,
              randomQuoteIndex: this.randomQuoteIndex(),
              isDoneFetching: true
            }));
  }

randomQuoteIndex() {
    return random(0, this.state.quotes.length - 1);
  }

This results in an error because the state of quotes isn't available at the time of randomQuoteIndex() call.
However, if I change randomQuoteIndex() to instead use a passed in quotes parameter, as below, it works.
componentDidMount() {
    fetch('https://gist.githubusercontent.com/nataliecardot/0ca0878d2f0c4210e2ed87a5f6947ec7/raw/1802a693d02ea086817e46a42413c0df4c077e3b/quotes.json')
      .then(response => response.json())
      .then(quotes => this.setState({
          quotes,
          randomQuoteIndex: this.randomQuoteIndex(quotes),
          isDoneFetching: true
        }));
  }

  randomQuoteIndex(quotes) {
    return random(0, quotes.length - 1);
  }

This is not what I expected; I had assumed that the state of quotes would be available at the time randomQuoteIndex() is called since it was called within setState. Why is randomQuoteIndex() called before setState even though it's inside it?

A: It is because setState is an async operation. You can still use your original function by  using setState as a callback
componentDidMount() {
        fetch('https://gist.githubusercontent.com/nataliecardot/0ca0878d2f0c4210e2ed87a5f6947ec7/raw/1802a693d02ea086817e46a42413c0df4c077e3b/quotes.json')
          .then(response => response.json())
          .then(quotes => this.setState({
              quotes,
              isDoneFetching: true
            }, () => {
             this.setState({
             randomQuoteIndex: this.randomQuoteIndex(),
        }); //this callback will be executed after your state is updated.
    }));

}

randomQuoteIndex() {
return random(0, this.state.quotes.length - 1);
}

So, essentially once a setState function is performed, the updated values will only reflect after the update lifecycle is finished, which means you can get the values either in componentDidUpdate method or by using the setState function as a callback.
I wouldn't recommend this solution but in this case, the function randomQuoteIndex() will get the updated state values without having any parameter passed.

A: Thats because at the time you passed the object to setState, you are executing inline call to this.randomQuoteIndex.
state.quotes did not exist yet in the state.
constructor() {
    this.state = { quotes: [] };

}

componentDidMount() {
    fetch('https://gist.githubusercontent.com/nataliecardot/0ca0878d2f0c4210e2ed87a5f6947ec7/raw/1802a693d02ea086817e46a42413c0df4c077e3b/quotes.json')
      .then(response => response.json())
      .then(quotes => {

          this.setState({
            quotes,
            randomQuoteIndex: this.randomQuoteIndex(),
            isDoneFetching: true
        })
      });

  }

  randomQuoteIndex() {
    return random(0, this.state.quotes.length - 1);
  }


text:
Q: localhost doesn't work I'm trying to solve out my problem since more than a week, but with no results until now.
When I try to open localhost/phpmyadmin, or any php file, I get on this message:

Internet Explorer cannot display the webpage ".

The same happens with Mozilla; no errors, but the page keeps loading without answer.
My configuration
Windows 7 32bit
Wampserver 2.2D ( all services are running ) green status,  server online

My hosts file
127.0.0.1 localhost
::1 localhost

IIS is stopped, but I don't think it's a problem with port 80.
I tried going directly to 127.0.0.1, it didn't work.
I will appreciate any advice.
Thanks

A: You may want to check your firewall authorizations...
I had same problem; I have since added wampserver as authorized program to my firewall and, as above, stopped IIS services in control panel/admistrative tools.

A: I had similar problem, a lot of research and analysis but nothing helped. Finally I came across UwAmp which works like a charm for me ever since then. Try it out:
http://www.uwamp.com/
It also supports multiple versions of PHP which you can switch by single click anytime you want.

A: Ok so if you have IIS on, stop it.
Go to cpanel and search administrative tools, component services, services (local), and scroll  to the w's to find and stop:
World wide web publishing service

and
Web deployment agent service (something like that)

Good luck.


text:
Q: Returning a vector for a given threshold in r I have written the code below - for a given threshold, it is supposed to add up the numbers until it gets below or equal to that threshold for e.g. (0, 1, 1, 1, 2, 4) - 0+1+1+1 = 3 and the provide the number of iterations, i.e. 4.  It seems to work, but not for a vector for e.g. [1:10] - what am I doing wrong?
sumf<-function(y){
    sum<-0
    for(i in 1:(length(y))){
        sum=sum+y[i]
    }
    print(sum)
}

sumf(x<n)

A: Perhaps try cumsum.
x <- c(0, 6, 3, 8, 5, 2, 4, 0, 2, 2)
data.frame(id = 1:length(x), x, sum = cumsum(x))

   id x sum
1   1 0   0
2   2 6   6
3   3 3   9
4   4 8  17
5   5 5  22
6   6 2  24
7   7 4  28
8   8 0  28
9   9 2  30
10 10 2  32


text:
Q: How to edit data in store through a component? REACT JS I have logged: false in my store and I need to change it to true on a button action in a component in react js. If you could tell me how to edit/update data in store or share a link?

A: How to create Store
const redux = require('redux');
const createStore = redux.createStore;

const initialState = {
    counter: 0
}

const rootReducer = (state = initialState, action) => {
  if(action.type === 'INC_COUNTER'){
    return {
      ...state,
      counter: state.counter + 1
    };
  }

  return state;
};

How to call Action
const mapDispatchToProps = dispatch => {
  return {
    onIncrementCounter: () => dispatch({type:'INC_COUNTER'})
  };
};

Calling it on click
<button clicked={this.props.onIncrementCounter} />

A: Here is a simple React Component which implements create,read,update,delete functionality:

[You can also view code implementation on codesanbox.io https://codesandbox.io/s/81r0n6l112
import React from "react";
import idGenerator from "react-id-generator";

export default class App extends React.Component {
  state = {
    employees: [],
    firstname: "",
    lastname: "",
    id: 0,
    create: true
  };
  componentDidMount() {
    //Intializing sample data
    const emps = [
      { firstname: "John", lastname: "Doe", id: 0 },
      { firstname: "Bruno", lastname: "Mars", id: 0 }
    ];
    this.setState({
      employees: emps.map(e => {
        return {
          firstname: e.firstname,
          lastname: e.lastname,
          id: idGenerator()
        };
      })
    });
  }

  handleChange = e => {
    const name = e.target.name;
    this.setState({ [name]: e.target.value });
  };

  handleCreateEmployee = () => {
    if (this.state.employees) {
      this.setState({
        employees: [
          ...this.state.employees,
          {
            firstname: this.state.firstname,
            lastname: this.state.lastname,
            id: idGenerator()
          }
        ]
      });
    } else {
      this.setState({
        employees: [
          {
            firstname: this.state.firstname,
            lastname: this.state.lastname,
            id: idGenerator()
          }
        ]
      });
    }
    this.setState({ firstname: "", lastname: "" });
  };

  handleEdit = e => {
    const employee = this.state.employees.find(function(emp) {
      if (emp.id === e.target.id) {
        return emp;
      }
    });
    this.setState({
      firstname: employee.firstname,
      lastname: employee.lastname,
      id: employee.id,
      create: false
    });
  };
  handleDelete = e => {
    this.setState({
      employees: this.state.employees.filter(function(emp) {
        if (emp.id !== e.target.id) return emp;
      })
    });
  };
  handleUpdateEmployee = () => {
    const employee = {
      firstname: this.state.firstname,
      lastname: this.state.lastname,
      id: this.state.id
    };
    const employeesupdated = this.state.employees.map(emp => {
      if (emp.id === this.state.id) {
        return employee;
      } else return emp;
    });

    this.setState((prevStae, props) => ({
      employees: employeesupdated,
      create: true,
      firstname: "",
      lastname: ""
    }));
  };

  render() {
    const create = this.state.create ? "Save" : "Update";
    const { employees } = this.state;
    const inputIsEmpty =
      this.state.firstname === "" || this.state.lastname === "" ? true : false;
    return (

        <input
          style={{ width: 120 }}
          type="text"
          placeholder="Enter Firstname"
          onChange={this.handleChange}
          name="firstname"
          value={this.state.firstname}
        />
        <input
          style={{ width: 120 }}
          type="text"
          placeholder="Enter Firstname"
          onChange={this.handleChange}
          name="lastname"
          value={this.state.lastname}
        />

        <button
          style={{ width: 150 }}
          disabled={inputIsEmpty}
          onClick={
            this.state.create
              ? this.handleCreateEmployee
              : this.handleUpdateEmployee
          }
        >
          {create}
        </button>

              First Name
              Last Name
              Edit
              Delete

            {employees.map((emp, i) => {
              return (

                  {emp.firstname}
                  {emp.lastname}

                    <button onClick={this.handleEdit} id={emp.id}>
                      Edit
                    </button>

                    <button onClick={this.handleDelete} id={emp.id}>
                      Delete
                    </button>

              );
            })}

    );
  }
}
[You can also view the code implementation here][1]

  [1]: https://codesandbox.io/s/81r0n6l112


text:
Q: Example of non-isomorphic vector bundles with the same element in $K$ Let $X$  be a paracompact and well behaved space. Topological K-Theory $K(X)$ of $X$ is group completing the monoid of isomorphism classes of vector bundles over $X$ with the Whitney sum.
Two vector bundles $E,E'\to X$ represent the same class $[E]=[E']$ in $K(X)$ if there is (after applying some theory) a trivial bundle $K$ such that $K\oplus E=K\oplus E'$.
What is an example of two non-isomorphic vector bundles $E$, $E'$ such that $[E]=[E']$?

A: The tangent vector bundle $\tau$ of $S^2$ gives such example: it's non-trivial (since there are no non-vanishing vector fields on $S^2$) but $\tau\oplus 1=3$ ($1$ is the normal bundle, which is trivial).


text:
Q: Initialization of member array objects avoiding move constructor I'm trying to create and initialize a class that contains a  member array of a non-trivial class, which contains some state and (around some corners) std::atomic_flag. As of C++11 one should be able to initialize member arrays.
The code (stripped down to minimum) looks like this:
class spinlock
{
    std::atomic_flag flag;
    bool try_lock() { return !flag.test_and_set(std::memory_order_acquire); }
public:
    spinlock() : flag(ATOMIC_FLAG_INIT){};
    void lock()     { while(!try_lock()) ; }
    void unlock()   { flag.clear(std::memory_order_release); }
};

class foo
{
    spinlock lock;
    unsigned int state;
public:
    foo(unsigned int in) : state(in) {}
};

class bar
{
    foo x[4] = {1,2,3,4}; // want each foo to have different state
public:
    //...
};

If I understand the compiler output correctly, this seems not to construct the member array, but to construct temporaries and invoke the move/copy constructor, which subsequently calls move constructors in sub-classes, and that one happens to be deleted in std::atomic_flag. The compiler output that I get (gcc 4.8.1) is:
[...] error: use of deleted function 'foo::foo(foo&&)'
note: 'foo::foo(foo&&)' is implicitly deleted because the default definition would be ill-formed
error: use of deleted function 'spinlock::spinlock(spinlock&&)'
note: 'spinlock::spinlock(spinlock&&)' is implicitly deleted because [...]
error: use of deleted function 'std::atomic_flag::atomic_flag(const std::atomic_flag&)'
In file included from [...]/i686-w64-mingw32/4.8.1/include/c++/atomic:41:0
[etc]

If I remove the array and instead just put a single foo member inside bar, I can properly initialize it using standard constructor initializers, or using the new in-declaration initialization, no problem whatsoever. Doing the same thing with a member array fails with the above error, no matter what I try.
I don't really mind that array elements are apparently constructed as temporaries and then moved rather than directly constructed, but the fact that it doesn't compile is obviously somewhat of a showstopper.
Is there a way I either force the compiler to construct (not move) the array elements, or a way I can work around this?

A: Here's a minimal example exposing the problem:
struct noncopyable
{
    noncopyable(int) {};
    noncopyable(noncopyable const&) = delete;
};

int main()
{
    noncopyable f0 = {1};
    noncopyable f1 = 1;
}

Although the two initializations of f0 and f1 have the same form (are both copy-initialization), f0 uses list-initialization which directly calls a constructor, whereas the initialization of f1 is essentially equivalent to foo f1 = foo(1); (create a temporary and copy it to f1).
This slight difference also manifests in the array case:
noncopyable f0[] = {{1}, {2}, {3}, {4}};
noncopyable f1[] = {1, 2, 3, 4};

Aggregate-initialization is defined as copy-initialization of the members [dcl.init.aggr]/2

Each member is copy-initialized from the corresponding initializer-clause.

Therefore, f1 essentially says f1[0] = 1, f1[1] = 2, .. (this notation shall describe the initializations of the array elements), which has the same problem as above. OTOH, f0[0] = {1} (as an initialization) uses list-initialization again, which directly calls the constructor and does not (semantically) create a temporary.

You could make your converting constructors explicit ;) this could avoid some confusion.
Edit: Won't work, copy-initialization from a braced-init-list may not use an explicit constructor. That is, for
struct expl
{
    explicit expl(int) {};
};

the initialization expl e = {1}; is ill-formed. For the same reason, expl e[] = {{1}}; is ill-formed. expl e {1}; is well-formed, still.

A: Gcc refuses to compile list-initialization of arrays of objects with virtual destructor up to version 10.2. In 10.3 that was fixed.
E.g. if noncopyable from @dyp answer had a virtual destructor, gcc fails to compile line:
noncopyable f0[] = {{1}, {2}, {3}, {4}};

arguing to deleted copy and move c-rs. But successfully compiles under 10.3 and higher.


text:
Q: Access to Vuex store state from a component using Nuxt
I'm trying to pass a list of button names into a menu component from the Vuex store following https://nuxtjs.org/guide/vuex-store
my /store/store.js:
export const state = () => ({
    'toolbarActions' : [ 'My project', 'Home', 'About', 'Contact' ]
})

My menu component:
<template>
  <v-toolbar color="indigo" dark>
    <v-toolbar-side-icon></v-toolbar-side-icon>
    <v-toolbar-title class="white--text">Title</v-toolbar-title>
    <v-spacer></v-spacer>
    <v-toolbar-items class="hidden-sm-and-down">
       <v-btn flat v-for="action in toolbarActions" :key="action">{{action}}</v-btn>
             <!-- <v-btn flat v-for="action in toolbarActions">{{action}}</v-btn> -->
      <!-- <v-btn flat>Link One</v-btn>
      <v-btn flat>Link Two</v-btn>
      <v-btn flat>Link Three</v-btn> -->
    </v-toolbar-items>
  </v-toolbar>
</template>

<script>

// import toolbarActions from '~/store/store.js'

export default {
computed: {
  toolbarActions() {
          return this.$store.state.toolbarActions

          // return [ 'My project', 'Home', 'About', 'Contact' ]
  }
  }
}
</script>

If I uncomment:
      // return [ 'My project', 'Home', 'About', 'Contact' ]

and comment:
          return this.$store.state.toolbarActions

The button names are passed into the component. but with
 return this.$store.state.toolbarActions

not commented, nothing is passed in.
How do I access the Vuex store here to pass in the button names?
EDIT: I've made the changes, I'm getting:
   ERROR  [Vue warn]: Error in render: "TypeError: Cannot read property
 'toolbarActions' of undefined"
  11:52:20

  found in

 ---> <Menu> at components/menu.vue
   <Default> at layouts/default.vue
     <Root>

 » store\_toolbar.js

A: I recommend to use a module named toolbar inside it put the following code :
  export const state = () => ({
     'toolbarActions' : [ 'My project', 'Home', 'About', 'Contact' ]
   })

the folder structure should be like :
.
.
> static
v store
  |_toolbar.js

and your computed property should be like :
computed: {
  toolbarActions() {
      return this.$store.state.toolbar.toolbarActions  //look i added the name of the toolbar module
                              // ^___________

  }
 }
}

A: Better option may be
import {mapGetters} from 'vuex';

and use like
computed:mapGetters({
    toolbarActions:'toolbar/toolbarActions'
})


text:
Q: Find the Cartesian representation of each curve represented by two parametric equations.
Given the two equations $x(t) = acos(4t)$ and $y(t) = bsin(4t)$, find
  $\frac{dy}{dx}$ and the Cartesian representation of the curve

I have already easily solved the first bit for $\frac{dy}{dx}$, the second part is a bit trickier. My first approach was to square both equations and write it in the $x^2 + y^2 = r^2$ form, but the constants are different so I thought that'd make $r^2$ a bit tricky to figure out.
Then I decided I'd substitute one into the other, so I did as shown:
$$x(t) = acos(4t) \implies cos^{-1}(\frac{x}{a}) = 4t$$
$$\because y(t) = bsin(4t) \implies y(t) = bsin(cos^{-1}(\frac{x}{a}))$$
I wanted to simplify it further, I thought I'd approach this the same way a sine cancels out an inverse sine if it's in its argument and the result simplifies to the inverse sine's argument
$$sin(sin^{-1}(x)) = x$$
but I didn't know how I'd do that with an inverse cosine being the argument of a sine.
Can this be simplified further? Is there an easier (more direct) way to find the Cartesian representation than just trying to guess?


text:
Q: leetcode add two numbers loop I am working on LeetCode problem 2. Add Two Numbers:

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

I am failing one of the test cases where l1 = [9,9,9,9,9,9,9] and l2 = [9,9,9,9]. I am outputting [8,9,9,9,9,1] and the correct output is [8,9,9,9,0,0,0,1]. My python code is posted below. I'm pretty sure my first while loop (l1 and l2) is working fine. I can't figure out what in the second loop (while l1) I need to change to get the correct output.
if l1 == [0] and l2 == [0]:
    return ListNode()
if l1 == [0]:
    return l2
if l2 == [0]:
    return l1

carry = False
sum_num = ListNode()
head = sum_num

while l1 and l2:
    temp = l1.val + l2.val
    if carry:
        temp += 1
        carry = False
    if temp >= 10:
        carry = True
        sum_num.val = temp % 10
    if temp < 10: #changed these from an if because not triggering correctly because double if
        sum_num.val = temp
    l1 = l1.next
    l2 = l2.next
    if not l1 or not l2:
        break
    sum_num.next = ListNode()
    sum_num = sum_num.next

while l1:
    temp2 = l1.val
    if carry:
        temp2 += 1
        carry = False
    if temp2 >= 10:
        carry = True
        sum_num.val = temp % 10
    if temp2 < 10:
        sum_num.val = temp
    l1 = l1.next
    if not l1:
        break
    sum_num.next = ListNode()
    sum_num = sum_num.next

while l2:
    temp3 = l2.data
    if carry:
        temp3 += 1
        carry = False
    if temp3 >= 10:
        carry = True
        sum_num.val = temp % 10
    if temp3 < 10:
        sum_num.val = temp
    l2 = l2.next
    if not l2:
        break
    sum_num.next = ListNode()
    sum_num = sum_num.next

if carry:
    sum_num.val = 1

return head

A: Two problems:

*

*You have references to temp instead of temp2 and temp3 in your second and third loop, which obviously will lead to wrong results.

*When all the loops have been done, and there is a carry, you overwrite the value of the last added node with a 1. This is wrong. You need a new node for storing the carry.
Some other remarks:

*

*I would find the code less confusing if you would only create a node when you already have the value for it ready. Then you can call ListNode(temp) or something -- passing the value it needs. This way you also can do away with the conditional break in your loops.

*You have three loops with code repetition. Avoid this repetition and let your first loop continue while either of the list references is not None. So change the while condition to an OR and let the body of the loop deal with the case where a list reference might be None.

*If you make carry an integer instead of a boolean, it is easier to work with: you can just add the carry and calculate its new value by dividing temp by 10.

*It is not really necessary to deal with the special cases where a list may be [0]. It is true that this may give some speed benefit for those particular cases, but I would leave them out.
Here is your code updated with the above remarks:
carry = 0  # Integer instead of boolean -- easier to work with here
sum_num = None  # Don't create a node yet
head = None

while l1 or l2:  # Changed condition to avoid code repetition in 2 more loops
    temp = carry  # Since carry is an int, we can just add this 0 or 1.
    if l1:  # Deal gracefully with a None
        temp += l1.val
        l1 = l1.next
    if l2:
        temp += l2.val
        l2 = l2.next
    carry = temp // 10  # Simple way to set the new carry
    new_node = ListNode(temp % 10)  # Create node now that you know the value
    if head:
        sum_num.next = new_node
    else:  # First time
        head = new_node
    sum_num = new_node

# No code repetition here. Just one more thing to do:
if carry:
    sum_num.next = ListNode(1)

return head


text:
Q: Upload not working with Jquery xhr & Ajax I have image upload function in my "form" which gets uploaded via ajax. So, until image is uploading, User continues to fill rest of form. and than click on submit button which is another ajax function to submit whole form.
Problem is I have below function for image upload :-
jQuery(window).load(function(){
            jQuery(':button').click(function(){
                var formData = new FormData(jQuery('form')[0]);
                jQuery.ajax({
                    url: 'upload.php',  //Server script to process data
                    type: 'POST',
                    xhr: function() {  // Custom XMLHttpRequest
                        var myXhr = jQuery.ajaxSettings.xhr();
                        if(myXhr.upload){ // Check if upload property exists
                            myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
                        }
                        return myXhr;
                    },
                    //Ajax events
                    beforeSend: function(e) { $('#progress').css('display', 'block'); },
                    success: function(e) {
                        if (e != "no" && e != 'dir') {
                            $('#img').attr("src", e);
                            $('#imglinktosent').val(e);
                        } else if (e == 'dir') {
                            alert('Oops! We could not find \image\ directory or may be permission is not correct');
                        } else {
                            alert('File was not Uploaded, Kindly Upload Image with Size less than 512KB');
                        }
                    } ,
                    error: function(e) { alert('error' + e.message); } ,
                    data: formData,
                    //Options to tell jQuery not to process data or worry about content-type.
                    cache: false,
                    contentType: false,
                    processData: false
                });
            });
            function progressHandlingFunction(e){
                if(e.lengthComputable){
                    $('progress').attr({value:e.loaded,max:e.total});
                }
            }
        });//]]>

It was hindering my complete form submission, therefore i changed it into Below function.
function uploadimage(){
            jQuery(':button').click(function(){
                var formData = jQuery('#myfile').val();
                jQuery.ajax({
                    url: 'upload.php',  //Server script to process data
                    type: 'POST',
                    xhr: function() {  // Custom XMLHttpRequest
                        var myXhr = jQuery.ajaxSettings.xhr();
                        if(myXhr.upload){ // Check if upload property exists
                            myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
                        }
                        return myXhr;
                    },
                    //Ajax events
                    beforeSend: function(e) { $('#progress').css('display', 'block'); },
                    success: function(e) {
                        if (e != "no" && e != 'dir') {
                            $('#img').attr("src", e);
                            $('#imglinktosent').val(e);
                        } else if (e == 'dir') {
                            alert('Oops! We could not find \image\ directory or may be permission is not correct');
                        } else {
                            alert('File was not Uploaded, Kindly Upload Image with Size less than 512KB');
                        }
                    } ,
                    error: function(e) { alert('error' + e.message); } ,
                    data: formData,
                    //Options to tell jQuery not to process data or worry about content-type.
                    cache: false,
                    contentType: false,
                    processData: false
                });
            });
            function progressHandlingFunction(e){
                if(e.lengthComputable){
                    $('progress').attr({value:e.loaded,max:e.total});
                }
            }
        }

So, that whenever user clicks on "upload image" button. Image will get uploaded by "uploadimage()" function set on "button" with event "onclick".
But PHP was giving error with "undefined index myfile" in upload.php
After searching for a while, i found, There was "request payload" and no formdata option in header.
After searching more in stackoverflow, i found i have to specify this too :
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");

as if you would have noticed at line 30, I am sending direct formData
data: formData,
//Options to tell jQuery not to process data or worry about content-type.

**
But I am unsure where should i specify
**
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");

in my uploadimage() function to work.

A: Ajax doesn't support binary file transfers by default. I think it is more easy to base-64 encode your image and just post the data string to the server. You can use a html5 canvas element to get a base-64 encoded string from your image canvas.toDataURL(); . Server side you'll need to decode this string with base64_decode($yourimagedatastring);


text: Q: Poisson GLM,Hessian matrix = the observed Hessian matrix Assume a simple Poisson model with 2 unknown parameters (the intercept and the slope) Show that the expectation of the Hessian matrix = the observed Hessian matrix or equivalently the observed Information matrix = expected Information matrix. The same is true for the logit model.


text:
Q: Qt JNI : Invalid indirect reference 0x61382e48 in decodeIndirectRef I am trying the Qt project that captures audio data from mic on android.
I refereed this article : Android AudioRecord example, and wrote it to Qt code.
int recorderSampleRate = 44100;
int recorderChannels = QAndroidJniObject::getStaticField<jint>("android/media/AudioFormat", "CHANNEL_IN_MONO");
int recorderAudioEncoding =  QAndroidJniObject::getStaticField<jint>("android/media/AudioFormat", "ENCODING_PCM_16BIT");
int sourceType = QAndroidJniObject::getStaticField<jint>("android/media/MediaRecorder$AudioSource", "MIC");

int bsize = QAndroidJniObject::callStaticMethod<int>("android/media/AudioRecord", "getMinBufferSize", "(III)I", recorderSampleRate, recorderChannels, recorderAudioEncoding);

mAudioRecorder = new QAndroidJniObject("android/media/AudioRecord", "(IIIII)V", sourceType, recorderSampleRate, recorderChannels, recorderAudioEncoding, BufferElements2Rec * BytesPerElement);

// starting capture.
mAudioRecorder->callMethod<void>("startRecording", "()V");

// ready buffer.
jint size = BufferElements2Rec * BytesPerElement;
jbyte buffers[size * 2];

qDebug() << "start capture";

while(true)
{
    {
        jint offset = 0;

        // read cached audio data from AudioRecord
        int result = mAudioRecorder->callMethod<jint>("read", "([BII)I", buffers, offset, size);

        qDebug() << "readed byte size " << result;
    }

    // wait a bit for new audio data.
    msleep(10);
}

But, at this line
int result = mAudioRecorder->callMethod("read", "([BII)I", buffers, offset, size);
the app crashed and outputted following log.
W/dalvikvm(24772): Invalid indirect reference 0x61382e48 in decodeIndirectRef
E/dalvikvm(24772): VM aborting
F/libc    (24772): Fatal signal 11 (SIGSEGV) at 0xdeadd00d (code=1), thread 24975 (ldAndroidCaptur)

I guessed this error was cause of bad JNI calling, but I couldn't find the reason.
Addition:
I found 0x61382e48 is a address of buffers array
EDIT : Android guide for AudioRecord is here.
Welcome any advices.


text:
Q: Defect not letting user delete their own account I'm a beginner using Typescript and React. On the UI of the application, there is a defect that does not allow a user to delete their own account when logged in. So like if I was logged in I could delete other accounts created, but not my own. To fix this, in the code shown, I think I need to add a function under "disabled" that checks if the user being selected to delete also belongs to the logged in user. If it does, the disabled should run true. Can someone please help with this and show how to do it?
const deleteAction = {
  children: (
    <TableMenuItem
      data-testid="delete-user-button"
      disabled={
        !hasAnyPermission(
          [
            KnownPermissions.IdentityUsersDeleteAllAccounts,
            KnownPermissions.IdentityUsersDeleteCurrentAccount,
          ],
          permissions
        )
      }
      onClick={() => handleDeleteUser(user)}
      iconId={'delete'}
      label={'Delete'}
    />
  ),
  dataTestId: 'delete-user-button',
  disabled: !hasAnyPermission(
    [
      KnownPermissions.IdentityUsersDeleteAllAccounts,
      KnownPermissions.IdentityUsersDeleteCurrentAccount,
    ],
    permissions
  ),
  iconId: 'delete',
  key: 'delete',
  onclick: () => handleDeleteUser(user),
  tooltip: 'Delete user',
};


text:
Q: Vaadin Sub-Window Does not close The subwindow that I create does not close. I've seen some people experienced the same issue and posted the same issue but still I cannot find a solution. I have checked this, and this ,and this,and that and could not find a solution.  Here' my code below for corresponding class for the window:
public class CommunicationConfigWindow extends Window
{
   private static CommunicationConfigWindow INSTANCE;
   private final Accordion catAccordion = new Accordion();
   private final VerticalLayout layout = new VerticalLayout();
   private final HorizontalLayout toolbar = new HorizontalLayout();
   private final Button applyButton = new Button( "Save&Close" );
   private final Button cancelButton = new Button( "Cancel" );

   private CommunicationConfigWindow( )
   {
      this.toolbar.setDefaultComponentAlignment( Alignment.MIDDLE_CENTER );
      this.applyButton.setSizeFull();

      this.cancelButton.addClickListener( e -> {
         UI.getCurrent().removeWindow( this );
         this.close();
      } );
      this.applyButton.addStyleName( ValoTheme.BUTTON_FRIENDLY );
      this.cancelButton.addStyleName( ValoTheme.BUTTON_DANGER );

      this.cancelButton.setSizeFull();
      this.toolbar.addComponents( this.cancelButton, this.applyButton );
      this.toolbar.setSizeFull();
      this.catAccordion.addTab( new GeneralCatLayer( CatVersionEnum.CAT21 ), "CAT 21" );
      this.catAccordion.addTab( new GeneralCatLayer( CatVersionEnum.CAT23 ), "CAT 23" );
      this.catAccordion.addTab( new GeneralCatLayer( CatVersionEnum.CAT247 ), "CAT 247" );
      this.layout.addComponents( this.catAccordion, this.toolbar );
      this.setContent( this.layout );

   }

   public static CommunicationConfigWindow getINSTANCE()
   {
      if ( CommunicationConfigWindow.INSTANCE == null )
      {
         CommunicationConfigWindow.INSTANCE = new CommunicationConfigWindow();
      }
      return CommunicationConfigWindow.INSTANCE;
   }

}

This is before I click on cancel.
This is after I click on cancel.
I do pop-up this window from a Display Settings Button. What happens is that:

*

*I click on a Display Settings Button and the window pops up.

*BEFORE I click on cancel, I click on Display Settings Button and it does not create a new window since its singleton.

*I click on cancel and click on Display Settings Button again, the old messed up one stays there and also creates a new window.

I basically want the window to be gone when I click on cancel or the close button but it simply does not.Why?
Thanks in advance.

A: May be problem with your singleton. Do you really need singleton window ?
If you want to add only one window on a button click. you can try with some validation like
 Window yourWindow = new Window();
        if (UI.getCurrent().getWindows().contains(yourWindow)) {
            getUI().addWindow(yourWindow);
        }

override equals in your window class

A: I have not changed anything, after 2 hours spending on this, it started working eventhough I did not change a thing and I have no idea why.


text:
Q: Results about continuous functions How can you show that if $f:\mathbb{R}\rightarrow \mathbb{R} $ and $g:\mathbb{R}\rightarrow \mathbb{R} $ are both functions continuous at the point $c\in \mathbb{R}$ then the product $f\cdot g $ is continuous at the point c.
I have $$|f(x)g(x)-f(x)g(c)+f(x)g(c)-f(c)g(c)|\leq |f(x)||g(x)-g(c)|+|g(c)||f(x)-f(c)| $$
But I'm having a hard time figuring out what I should make $|f(x)-f(c)|$ and $|g(x)-g(c)|$ less than (as a function of $\epsilon $) so that my final line shows that $|f(x)g(x)-f(c)g(c)|<\epsilon $.
[I've missed out some of the details that I would actually include to keep this as short as possible].

A: Let me give a hint. Of course we can make $|f(x)-f(c)|$ and $|g(x)-g(c)|$ as small as we want. No problem with $|g(c)|$ (which is constant). Because $f$ is continuous, it is bounded on a neighbourhod on $c$ which allows us to make the term on the right as small as we want.

A: You want to make each of the two terms smaller than $\epsilon/2$. That means, first of all, that $|f(x)-f(c)|$ must be made smaller than $\frac{\epsilon}{2|g(c)|}$, unless $g(c)=0$, in which case that term doesn't matter. The other term, you first need to make sure that $|f(x)|<|f(c)|+1$. Then you can make $|g(x)-g(c)|<\frac{\epsilon}{2(|f(c)|+1)}$. Now pick $\delta$ to be the most limiting of all these factors, and you're good.

A: Let $d>0$ such that $|x-c|<d\implies (\;|f(x)-f(c)|<1 \;\land \; |g(x)-g(c)|<1\;).$
Let $M=1+\max  (|f(c)|,|g(c)|).$ So $M>|g(c)|$ And  also $|x-c|<d\implies M>|f(x)|.$
For $\epsilon >0$ let $\delta \in (0,d)$ such that $|x-c|<\delta \implies (\;|f(x)-f(c)|<\epsilon /2M\; \land \;|g(x)-g(c)|<\epsilon /2M \;).$ Now we have $$|x-c|<\delta \implies |f(x)g(x)-f(c)g(c)|= $$ $$=|f(x)(g(x)-g(c))\;+\; g(c)(f(x)-f(c))|\leq $$ $$\leq |f(x)|\cdot |g(x)-g(c)|+|g(c)|\cdot |f(x)-f(c)|\leq $$ $$\leq M\cdot (|g(x)-g(c)|+|f(x)-f(c)|)<\epsilon.$$


text:
Q: How do I make my computer name visible on the local network and Windows? Sorry if I am asking this in the wrong place, but I am no *nix expert and I failed to find an answer to my question, although I found similar issues on XRDP and Samba tags.
When I use RDP on Windows computers on local network, I am able to do so without typing the IP address. I just write the computer name (e.g. John-Computer) and I am able to connect through Remote Desktop Connection. Now, I have setup an Ubuntu desktop with xrpd, but I am only able to connect to it using its IP address.
Is it possible to make my Computer Name visible to Windows computers to simplify connections and access to web services hosted on the Ubuntu machine? If not, what would you suggest for me?
Thanks in advance.


text:
Q: wrapping a scripted command line interface I want to call an external program from within python, but this external program tries to interact with the user by using an internal script (in the telemarketer sense) to ask questions and change questions based on answers given.  The creators of this program are also known for occasionally changing the text of some of these questions, or even worse, the order in which they are asked.
I'm thinking it wouldn't be too hard to write a python module that maps arguments to the wrapper as answers to questions asked by the external program.  I could then use difflib, for example, to do some fuzzy matching to try to make the mapping more robust in the event of an order or text change in the external program.
Before doing so I thought I would ask if something like this already exists, as I seem to have a tickling sensation of having seen something similar before, but can't recall the specifics.
Thanks!

A: Are you looking for something like pexpect?


text:
Q: See if an account exists in SFDC, otherwise create it? I have an integration from a flat file with a account-identifier. In SFDC, each acct record has a FK with that identifier. Is there a way to lookup to see if the record exists in SF, and if not, create it ?
How would I do it?

A: It should be possible at least as a two step process. First, perform a lookup to check all the accounts you will need and create all the missing entries. Then load the data with the second session.


text:
Q: Is there any way to convert JSON to model easier in C++? I have a JSON string that I need to map into a Model in C++. My current practice is define data type of the variable and get the value of JSON via key then assign to model one by one. Here is the code:
auto code = BaseModel::intValue(data, "code");

int BaseModel::intValue( const std::unordered_map<std::string, Value>& value, const std::string& key )
{
    return (value.find( key ) != value.end() && BaseModel::isBasicType(value.at(key))) ? value.at(key).asInt() : 0;
}

Is there any easy way to convert JSON to model? Maybe I just need define a header file with the model's data type, then it can help me convert JSON to model object.Instead of creating a model object, assign value to the model object from JSON one by one. I know there is a way in Objective-C:
// JSON:
{
    "uid":123456,
    "name":"Harry",
    "created":"1965-07-31T00:00:00+0000"
}

// Model:
@interface User : NSObject
@property UInt64 uid;
@property NSString *name;
@property NSDate *created;
@end
@implementation User
@end

// Convert json to model:
User *user = [User yy_modelWithJSON:json];

// Convert model to json:
NSDictionary *json = [user yy_modelToJSONObject];

A: I've had great success with the Nlohmann Json library, which allows you to define a single set of serialization and deserialization functions, and then freely convert from your chosen structure to json and back.


text:
Q: Calculating a break in the block can anyone please help me calculate the break between blocks that happened.
This is my class, and in my list I get Start and End time from the block:
private class Block
{
  public DateTime Start { get; set; }
  public DateTime End { get; set; }
}

this is how the time in the list looks like
 List<Block> blocks = new List<Block>();

[0] = End{12/30/1899 11:45:00 AM}
[0] = Start{12/30/1899 8:30:00 AM}
[1] = End{12/30/1899 5:00:00 PM}
[1] = Start{12/30/1899 1:15:00 PM}

now I want the arrival and departure times, which are the block times between Start and Stop, to calculate their sum.
public class Presence
{
  public DateTime arrival   { get; set; }
  public DateTime departure { get; set; }
}

List<Presence> presence = new List<Presence>();

time received in the presence list:
arrival                     departure
1899-12-30 08:03:00.000;    1899-12-30 09:21:00.000
1899-12-30 09:36:00.000;    1899-12-30 10:34:00.000
1899-12-30 10:45:00.000;    1899-12-30 12:05:00.000
1899-12-30 13:03:00.000;    1899-12-30 14:24:00.000
1899-12-30 14:34:00.000;    1899-12-30 16:14:00.000
1899-12-30 16:27:00.000;    1899-12-30 18:02:00.000

this is my attempt to calculate (arrival - depature) between blocks (start & stop), but not the correct result, how could i do it correctly?
  double sumOfBreakOfBlocks = presence.Where(x => blocks.Any(b =>( x.arrival > b.Start && x.arrival > b.End) && x.arrival > x.departure)
                                           && blocks.Any(b => (x.departure < b.End && x.departure > b.Start) && x.departure < x.arrival)).Sum
                                           (x => (x.arrival.TimeOfDay - x.departure.TimeOfDay).TotalHours);

So sumofbreakofblox should be: 49 Minutes, obtained as:
1899-12-30 09:36:00.000 - 1899-12-30 09:21:00.000; (15)
1899-12-30 10:45:00.000 - 1899-12-30 10:34:00.000; (11)
1899-12-30 14:34:00.000 - 1899-12-30 14:24:00.000; (10)
1899-12-30 16:27:00.000 - 1899-12-30 16:14:00.000; (13)

It is necessary for me to get the amount (departure - arrival) that was in the time between Start and End Block

A: As I missunderstood the question, here is an update:
using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var blocks = new List<Block>
            {
                new Block
                {
                    End = new DateTime(1899, 12, 30, 11, 45, 0), Start = new DateTime(1899, 12, 30, 8, 30, 0)
                },
                new Block
                {
                    End = new DateTime(1899, 12, 30, 17, 0, 0), Start = new DateTime(1899, 12, 30, 13, 15, 0)
                }
            };

            var presences = new List<Presence>
            {
                new Presence
                {
                    Arrival = new DateTime(1899, 12, 30, 8, 3, 0),
                    Departure = new DateTime(1899, 12, 30, 9, 21, 0)
                },
                new Presence
                {
                    Arrival = new DateTime(1899, 12, 30, 9, 36, 0),
                    Departure = new DateTime(1899, 12, 30, 10, 34, 0)
                },
                new Presence
                {
                    Arrival = new DateTime(1899, 12, 30, 10, 45, 0),
                    Departure = new DateTime(1899, 12, 30, 12, 5, 0)
                },
                new Presence
                {
                    Arrival = new DateTime(1899, 12, 30, 13, 3, 0),
                    Departure = new DateTime(1899, 12, 30, 14, 24, 0)
                },
                new Presence
                {
                    Arrival = new DateTime(1899, 12, 30, 14, 34, 0),
                    Departure = new DateTime(1899, 12, 30, 16, 14, 0)
                },
                new Presence
                {
                    Arrival = new DateTime(1899, 12, 30, 16, 27, 0),
                    Departure = new DateTime(1899, 12, 30, 18, 2, 0)
                }
            };

            // group presence by blocks
            var group = new Dictionary<Block, List<Presence>>();
            foreach (var block in blocks)
            {
                group.Add(block, new List<Presence>());

                foreach (var presence in presences)
                {
                    if(presence.Departure >= block.Start && presence.Arrival <= block.End)
                        group[block].Add(presence);
                }
            }

            // calculate time per block
            foreach (var pair in group)
            {
                var block = pair.Key;
                var ps = pair.Value;

                for (int i = 0; i < ps.Count; i++)
                {
                    if (i + 1 < ps.Count)
                    {
                        Console.WriteLine($"{ps[i+1].Arrival} - {ps[i].Departure} = {(ps[i+1].Arrival - ps[i].Departure).Minutes}");
                    }
                }
            }

            Console.WriteLine("Press any key to exit!");
            Console.ReadKey();
        }
    }

    public class Block
    {
        public DateTime Start { get; set; }
        public DateTime End { get; set; }
    }

    public class Presence
    {
        public DateTime Arrival   { get; set; }
        public DateTime Departure { get; set; }
    }
}

A: Save the previous Presence object, use two layers of loops,
you can solve this problem more concisely.
            Presence pre = null;
            int sum = 0;
            foreach(var cur in presences)
            {
                if(pre != null)
                {
                    foreach(var b in blocks)
                    {
                        if(pre.departure >= b.Start && b.End >=cur.arrival)
                        {
                            sum += (cur.arrival - pre.departure).Minutes;
                            break;
                        }
                    }
                }
                pre = cur;
            }

            Console.WriteLine(sum);//49


text:
Q: Why would using Caliburn Action inside a Blend KeyTrigger break my View? Caliburn Micro 2.0.2 and WPF 4 and .NET 4.5.
Using a very simple view and a very simple viewmodel to demonstrate, I notice that if I have a Caliburn Action inside a KeyTrigger, my View is not activated properly. When I say 'properly' I mean that if I look at it in Snoop, the whole UserControl is disabled. If I change it to a Window and open it as Window rather than an embedded control, Snoop cannot even find that Window and the control remains disabled.
Here is my ViewModel:
using System.Windows.Input;
using Caliburn.Micro;

namespace PlainSailTech.ViewModels.Admin
{
    public class SystemConfigurationViewModel : Screen
    {
        private bool canShowDevLinks;

        public bool CanShowDevLinks
        {
            get { return canShowDevLinks; }
            set
            {
                if (value.Equals(canShowDevLinks)) return;
                canShowDevLinks = value;
            }
        }

        public void ShowDevLinks(KeyEventArgs args)
        {
            if (args != null)
                args.Handled = true;
            CanShowDevLinks = !CanShowDevLinks;
        }
    }
}

Here is my XAML:
<Window x:Class="PlainSailTech.Bookkeeping.Ui.Views.Admin.SystemConfigurationView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:cal="http://www.caliburnproject.org"
         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
         xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
         mc:Ignorable="d"
         Title="Caliburn Action test"
         d:DesignHeight="300" d:DesignWidth="300">
<i:Interaction.Triggers>
    <ei:KeyTrigger Modifiers="Ctrl" Key="D" FiredOn="KeyUp" ActiveOnFocus="True">
        <cal:ActionMessage MethodName="ShowDevLinks">
            <cal:Parameter Value="$eventArgs" />
        </cal:ActionMessage>
    </ei:KeyTrigger>
</i:Interaction.Triggers>
<Grid>
    <Grid Width="Auto">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid Grid.Row="0" Background="#FFFBFBFB" Visibility="{Binding CanShowDevLinks, Converter={StaticResource BoolToVisible}}">
            <TextBlock Text="Dev links here" />
        </Grid>
        <Grid Grid.Row="1">
            <TextBox VerticalAlignment="Top" IsReadOnly="False" IsEnabled="True" Width="150" Height="30">
                <TextBox.Style>
                    <Style TargetType="TextBox">
                        <Setter Property="Background" Value="Blue"/>
                        <Setter Property="Foreground" Value="White"/>
                        <Setter Property="Text" Value="Enabled"/>
                        <Style.Triggers>
                            <Trigger Property="IsEnabled" Value="False">
                                <Setter Property="Background" Value="Red"/>
                                <Setter Property="Foreground" Value="Black"/>
                                <Setter Property="Text" Value="Disabled"/>
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </TextBox.Style>
            </TextBox>
        </Grid>
    </Grid>
</Grid>
</Window>

Notice that the TextBox is set to enabled but the whole control is being disabled. You can see this from this screen shot:

However, if I simply remove the Caliburn Action, everything is good again:
    <i:Interaction.Triggers>
    <ei:KeyTrigger Modifiers="Ctrl" Key="D" FiredOn="KeyUp" ActiveOnFocus="True">
    </ei:KeyTrigger>
</i:Interaction.Triggers>

A few possible clues. The problem goes away if:
If I replace the Caliburn Action with:
 <ei:ChangePropertyAction TargetObject="{Binding Mode=OneWay}" PropertyName="CanShowDevLinks" Value="True">

Or my ViewModel does not inherit from Screen or PropertyChangedBase.
If I override OnViewAttached and wire up a handler for EnableChanged, I can see the IsEnabled being set to false after the View is attached.
So it seems like an interaction between whatever is happening in the Screen/PropertyChangedBase base class and the wiring up of the Action.

A: Okay - the answer to this question is the person who asked it is an idiot. I have a guard property that has the name of the action's method. Because the KeyTrigger is below the UserControl, it is disabling the whole thing. Arghhh...
I knew that a guard property applied when you named a button, for example, but I didn't realise that it applied to any UI element that has an action attached to it. You live and learn, occasionally.


text:
Q: Boundary representation in ThreeJS I have been using ThreeJS for building my own web based CAD frontend. The API has amazing capabilities. My intent is to integrate the physics of the ThreeJS interface with a different product and sadly, the only supported common CAD format is STL.
One of the most important inputs in FEA is the boundaries. In my case, they would be the faces of a 3d model, which can be arbitrary shapes and not triangles. Apparently, ThreeJS considers a Face3 as a face.

For example:
a model converted from STL
This representation is also called as Boundary Representation.

Is there any way to get these faces in ThreeJS?

I tried the RayCaster but it did not work and my intent is to get a list of all the faces from the model beforehand.
Many Thanks


text:
Q: how to generate a set of continuous one in verilog I hope to generate a set of continuous one in verilog like
3 -> 'b111
4 -> 'b1111
5 -> 'b11111

I hope I can use {num{1'b1}}, but I found that the value must be constant.
Is there any way in verilog that I can generate the a set of continuous one value?

A: Using system verilog you can use the '1 syntax which automatically sizes correctly against the left hand side.
Also the above function 2^N - 1 in Dodon Victors answer is just -1 in signed notation. I have shown the usage of both below.
Some simulators may not work correctly with widths greater than 32, although I believe all modern simulators have fixed this issue.
Example below on EDAPlayground:
module dut;

  logic [65:0] test1;
  logic [65:0] test2;

  initial begin
    #1ps;
    test1 = '1;
    test2 = -1;

    #1ps;
    $displayb(test1);
    $displayb(test2);
  end
endmodule

Output:
# 111111111111111111111111111111111111111111111111111111111111111111
# 111111111111111111111111111111111111111111111111111111111111111111

A: N continuous 1 is just 2^N - 1, so you can use:
module test;
  initial begin
    $display("%b", ('b1 << 1) - 'b1);
    $display("%b", ('b1 << 2) - 'b1);
    $display("%b", ('b1 << 3) - 'b1);
    $display("%b", ('b1 << 4) - 'b1);
    $display("%b", ('b1 << 5) - 'b1);
  end
endmodule

and the output:
01
011
0111
01111
011111

You can use a function to generate like this:
function [31:0] gen1;
    input [5:0] n;
begin
    gen1 = ('b1 << n) - 1;
end
endfunction

then just call it using gen1(10).

A: How about this: ~('1 << n)
Test module:
module test;
  logic [7:0] a1=~('1 << 1) ;
  logic [7:0] a2=~('1 << 2) ;
  logic [7:0] a3=~('1 << 3) ;
  initial begin

    $display("%b", a1 );
    $display("%b", a2 );
    $display("%b", a3 );
  end
endmodule


text:
Q: How to make AddressSanitizer not stop after one error (and other issues) I'm running OS X, 10.8.5; I've installed llvm 3.4 via homebrew (clang version 3.4 (tags/RELEASE_34/final) ), and I'm building with -fsanitize=address.  I can get asan working with simple demo programs, but when building against our codebase, I have several problems (although I'd really just like an answer to #1):

*

*3rd party libraries are generating asan errors, and asan is terminating my app on the first occurrence.  I would think that there would be some kind of (runtime/compile-time) option to tell asan to keep going after finding an error.  Specifically, I see this:
bash-3.2$ ASAN_SYMBOLIZER_PATH=/usr/local/Cellar/llvm34/3.4/lib/llvm-3.4/bin/llvm-symbolizer ./unit_test
Start testing of PathTrieTest
Config: Using QTest library 4.8.2, Qt 4.8.2
PASS   : PathTrieTest::initTestCase()
PASS   : PathTrieTest::pathTrieNodeTest()
=================================================================
==76647==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x61600019e588 at pc 0x10891ddd3 bp 0x11312ba90 sp 0x11312ba58
WRITE of size 48830 at 0x61600019e588 thread T3
    #0 0x10891ddd2 in wrap_readdir_r (/usr/local/lib/llvm-3.4/lib/clang/3.4/lib/darwin/libclang_rt.asan_osx_dynamic.dylib+0x11dd2)
    #1 0x10ac23571 in QFileSystemIterator::advance(QFileSystemEntry&, QFileSystemMetaData&) (/Volumes/ToolChain/qt-4.8/lib/QtCore.framework/Versions/4/QtCore+0xef571)
    #2 0x10abd86d3 in QDirIteratorPrivate::advance() (/Volumes/ToolChain/qt-4.8/lib/QtCore.framework/Versions/4/QtCore+0xa46d3)
    #3 0x10abd7a7f in QDirIteratorPrivate::QDirIteratorPrivate(QFileSystemEntry const&, QStringList const&, QFlags<QDir::Filter>, QFlags<QDirIterator::IteratorFlag>, bool) (/Volumes/ToolChain/qt-4.8/lib/QtCore.framework/Versions/4/QtCore+0xa3a7f)
    #4 0x10abd8b68 in QDirIterator::QDirIterator(QDir const&, QFlags<QDirIterator::IteratorFlag>) (/Volumes/ToolChain/qt-4.8/lib/QtCore.framework/Versions/4/QtCore+0xa4b68)
    #5 0x10abd7609 in QDirPrivate::initFileLists(QDir const&) const (/Volumes/ToolChain/qt-4.8/lib/QtCore.framework/Versions/4/QtCore+0xa3609)
    #6 0x10abd5394 in QDir::count() const (/Volumes/ToolChain/qt-4.8/lib/QtCore.framework/Versions/4/QtCore+0xa1394)
    #7 0x1084c205d in get_count(QFileInfo&) /Users/stebro/dev_vm/ui/ui/fsinfoprovider.cpp:36
...

This error doesn't cause the app to terminate when it's running unsanitized.

*I can't get code to link when using the -fsanitize=undefined (or -fsanitize=address,undefined) options.  I am including the -fsanitize=undefined line on both my compile & link commands, but I get link errors such as:
    Undefined symbols for architecture x86_64:
      "typeinfo for __cxxabiv1::__class_type_info", referenced from:
          __ubsan::checkDynamicType(void*, void*, unsigned long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
          isDerivedFromAtOffset(__cxxabiv1::__class_type_info const*, __cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
          findBaseAtOffset(__cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
    "typeinfo for __cxxabiv1::__si_class_type_info", referenced from:
          isDerivedFromAtOffset(__cxxabiv1::__class_type_info const*, __cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
          findBaseAtOffset(__cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
    "typeinfo for __cxxabiv1::__vmi_class_type_info", referenced from:
          isDerivedFromAtOffset(__cxxabiv1::__class_type_info const*, __cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
          findBaseAtOffset(__cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)

*I can't get blacklists to work, and -mllvm -asan-globals=0 or -mllvm -asan-stack=0 doesn't seem to work like I'd expect.  For example, the latter don't suppress the generation of the error listed in #1 above, and creating a blacklist that looks like the one below doesn't suppress the errors either:
fun:QDirPrivate::initFileLists
fun:get_count
fun:*opendir2*

*Finally, executables generated with these asan options cause lldb to crash.  I'm using the lldb shipped with XCode 5 tools; there was no lldb deployed with the homebew llvm package, and I can't figure out how to build it.  The build instructions enter link description here have a dead link that points to the source you're supposed to use; pulling the source directly from the svn repository, using:
svn co http://llvm.org/svn/llvm-project/lldb/tags/RELEASE_34/final lldb

results in code that doesn't compile (errors provided upon request).

A: *

*Addressability bugs (especially memory corruptions like the OOB write you've mentioned) are usually severe enough to worry about. Ignoring them can't undo their effects, and the program is very likely to crash in a totally unrelated place after you've skipped a heap corruption.
You can try to build your own Clang with checks in readdir_r disabled, but I'd try to fix the error in the first place.

*Can you please file a bug with reproduction steps at http://code.google.com/p/address-sanitizer ?

*Blacklists only disable addressability checks in the blacklisted functions by not instrumenting them, they do not check the stacks for certain frames. Your particular check occurs in a function interceptor compiled into the runtime library, so you can't even blacklist that. If the error in #1 is in some system library and can't be easily worked around we can look into adding a runtime option to disable the readdir_r checks.

*Again, a bug report will be appreciated.

A: You can build your project with -fsanitize=address -fsanitize-recover=address flags, and run with environment variable ASAN_OPTIONS=halt_on_error=0.
Source: https://github.com/google/sanitizers/wiki/AddressSanitizer

A: By the way -- I found a way to work around this heap overflow in Qt if you're building it from source. I believe the problem is related to 32-bit / 64-bit inodes (_DARWIN_FEATURE_64_BIT_INODE is not defined when I build Qt for some reason).

diff --git a/src/corelib/io/qfilesystemiterator_unix.cpp b/src/corelib/io/qfilesystemiterator_unix.cpp
index 029b989..76b176f 100644
--- a/src/corelib/io/qfilesystemiterator_unix.cpp
+++ b/src/corelib/io/qfilesystemiterator_unix.cpp
@@ -75,6 +75,7 @@ QFileSystemIterator::QFileSystemIterator(const QFileSystemEntry &entry, QDir::Fi
         size_t maxPathName = ::pathconf(nativePath.constData(), _PC_NAME_MAX);
         if (maxPathName == size_t(-1))
             maxPathName = FILENAME_MAX;
+        maxPathName = 99999;
         maxPathName += sizeof(QT_DIRENT) + 1;

         QT_DIRENT *p = reinterpret_cast(::malloc(maxPathName));


text:
Q: Define a max width for a group of columns in css-grid Is it possible to define a max width for a group of columns in css-grid?
I'm trying to use css-grid alongside bootstrap like flex-box markup to make fullwidth rows which align with the flex-box columns.

.container__grid {
  width: 100%;
  display: grid;
  grid-template-columns: [view-start] minmax(1em, 1fr) repeat(12, 95px [col])/* Specify a max-width and center */
  [view-end];
}

.col-9--viewport-edge {
  grid-column: view-start/col 9;
  background-image: url('https://images.unsplash.com/photo-1516139008210-96e45dccd83b?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=ac07676efc2ca5b11b548d8ae01301ba&auto=format&fit=crop&w=2200&q=80');
  background-position: bottom center;
  background-size: cover;
}

.col--remaining {
  grid-column-end: col 12;
}

col-3

There's a sandbox here in which the goal is to get the cat column starting at the viewport edge and finishing at column 9 so that both col-3's line up vertically.

A: Nothing fancy, but maybe something this will work for you.
Instead of this:
.container__grid{
   display: grid;
   grid-template-columns:
      [view-start] minmax(1em, 1fr)
      repeat(12, 95px [col])
      [view-end];
  }

.col-9--viewport-edge{
   grid-column: view-start/col 9;
}

.col--remaining{
  grid-column-end: col 12;
}

Try this:
.container__grid {
   display: grid;
   grid-template-columns: repeat(20, 5%);
}

.col-9--viewport-edge {
   grid-column: 1 / 16;
}

.col--remaining {
   grid-column: 16 / 21;
 }

Not sure how you want to handle wider screen sizes.
revised codepen