text:
Q: What is the formula for a quadratic curve with defined crossing and maxima points? This is a problem that I've been wrestling with on and off in the process of creating quadratic splines for a game I'm building.
Given crossing points $x_0$ and $x_1$, and a maximum point $m$, how does one derive a quadratic function $y = f(x)$ which fulfils these constraints?
For example, what is the equation for y, when you have crossing points $(0,0)$ and $(5,0)$, and maximum point $(3,3)$?

A: If you want to use smooth quadratic splines (order = 3), as you have 4 conditions (number = 4, three crossing points and one zero derivative at the maximum), your knot vector will have length 7 (number + order).
For a clamped spline this would be, in your example, $[0,0,0,\alpha,5,5,5]$, with $\alpha$ not determined.
There are many possible values for $\alpha$ and you have to add another condition (derivative not lower than 0, ...)

A: You are trying to construct a function $f$ that has four constraints, namely:
\begin{align}
f(0) &= 0  \\
f(5) &= 0  \\
f(3) &= 3  \\
f'(3) &=0
\end{align}
To satisfy these four constraints, you need a function with four degrees of freedom. The easiest solution would be a single cubic, say $f(x) = ax^3 + bx^2 +cx + d$. Then the four constraints give you the equations:
\begin{align}
d &= 0  \\
125a + 25b + 5c &= 0  \\
27a + 9b + 3c &= 3  \\
27a + 18b +c &=0
\end{align}
You can solve these equations to get $a,b,c,d$.
Alternatively, you can use a quadratic spline with two segments, one on the interval $[0,3]$ and the other on $[3,5]$. Suppose we use $g(x) = px^2 + qx + r$ to denote the quadratic on the interval $[0,3]$. Then we have
\begin{align}
g(0) &= 0  \\
g(3) &= 3  \\
g'(3) &=0
\end{align}
which gives us the equations
\begin{align}
r &= 0  \\
9p + 3q + r &= 3  \\
6p + q &=0
\end{align}
You can solve these equations to get $p,q,r$, and you can do a similar construction of another quadratic on the interval $[3,5]$.


text:
Q: prove a holomorphic function is polynomial Question :
Given a function f holomorphic in the unit disk D, and such that for every point z ∈ D, there exists an n ∈ N such that the nth derivative of f vanishes at z. Prove that f is a polynomial.
Intuitively I think the question is quite obvious, however , when I truly try to prove it formally , I am stuck.
Does anyone have any idea about this question? Truly grateful to any help!

A: Let be $D_n = \{z\in D: f^{(n)}(z) = 0\}$. By hypothesis, $D = \bigcup_{n\in\Bbb N}D_n$. As $D$ is uncountable, Some $D_n$ is uncountable...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sum of Columns of Two Tables in LINQ I have two related tables in MS SQL.
Example...
Table A – Room
RoomId
RoomCost

Table B – RoomItem
RoomItemId
ItemName
ItemCost
RoomId

I need help in writing a LINQ code that will add RoomCost then Sum ItemCost (if they have the same RoomId) and post the results in a WPF textbox.
So far I have tried
DataclassesDataContext dc= new DataclassesDataContext();
var RoomAmount = (from dbo in dc.Room select dbo.RoomCost).Single();
var ItemAmount = (from itm in dc.RoomItem select itm.ItemCost).Single();
decimal RmAmount = Convert.ToDecimal(RoomAmount);
decimal ItmAmount = Convert.ToDecimal(ItemAmount);
decimal TAmount=RmAmount+ItmAmout;
txtTotalAmount.Text=TAmount

I am a beginner in C#, Kindly help. If I haven't been clear enough, just ask. Thanks

A: How about using Sum() like (havent tested it):
Assuming that Room.RoomCost is decimal and RoomItem.ItemCost is decimal as well and myRoomId is the id of the room you want to sum up:
var roomAmount = dc.Room.Single(r => r.RoomId == myRoomId).RoomCost;
var itemAmount = dc.RoomItem.Where(i => i.RoomId == myRoomId).Sum(r => r.ItemCost);

txtTotalAmount.Text= roomAmount + itemAmount ;

A: Assuming correct associations on the room and room items.
var foo = from room in dc.Room
          select new { room , TotalCost = room.RoomCost + room.RoomItems.Sum(item => item.ItemCost) };
var bar = foo.Single(room => room.RoomId == myRoomId);

A: You are able to do this by linq inner join and group by
see example here : LINQ: Using INNER JOIN, Group and SUM and enter link description here
and to add two column see example http://forums.asp.net/t/1728644.aspx/1
so from this links your query like
var total = from room in dc.Room
        join item in dc.RoomItem on room.RoomID equals item.RoomID
        group item by room.RoomID into g
        select new {
            RoomID = room.RoomID,
            RoomCost = (room.RoomCost + g.Sum(t => t.ItemCost))
        };


text:
Q: Is it possible to "approximate" a compact set of the plane by compact sets with smooth boundary? Hi,
Let $K \subseteq \mathbb{C}$ compact. Suppose that $K$ is connected, and that the boundary of $K$ is a simple, closed, piecewise $C^1$ curve. Denote by $A(K)$ the set of all functions holomorphic on
$\mathbb{C}_{\infty} \setminus K$
and continuous to the boundary of $K$, where $\mathbb{C}_{\infty}$ is the Riemann sphere.
By the Riemann mapping theorem, it is possible to write $K = \cap_n K_n$, where $(K_n)$ is a decreasing sequence of compact sets such that the boundary of each $K_n$ is an analytic, simple and closed curve.
My question is the following :
Is it possible to find a decreasing sequence of compacts $(K_n)$ such that $K=\cap_n K_n$ and the boundary of each $K_n$ is an analytic simple closed curve, with the additional requirement that
$$\int_{\partial K_n} g(z) dz \rightarrow \int_{\partial K} g(z)dz$$
as $n \rightarrow \infty$, for each function $g \in A(K)$?
Thank you


text:
Q: Why does my sprite go to the wrong co-ordinates after the first move? Here is my movement method:
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    location = [touch locationInView: [touch view]];
    CGPoint location_ = [[CCDirector sharedDirector] convertToGL:location];
    NSLog(@"Click Position = (%f,%f)",location_.x,location_.y);

    float moveSpeed = 40.0;
    float moveDist = sqrt(pow(abs(location_.x - sprite.position.x),2) + pow(abs(location_.y - sprite.position.y),2));
    float moveTime = (moveDist / moveSpeed);

    [sprite runAction:[CCMoveTo actionWithDuration:moveTime position:location_]];
}

And here's my init method.
-(id) init
{
    // always call "super" init
    // Apple recommends to re-assign "self" with the "super" return value
    if( (self=[super init])) {
        self.isTouchEnabled = YES;
        // create and initialize a Label

        [self scheduleUpdate];  // available since v0.99.3
        [self schedule: @selector(update:) interval:0.5];

        CGSize size = [[CCDirector sharedDirector] winSize];

        bg = [CCSprite spriteWithFile:@"testBG.png"];
        bg.position = ccp(  size.width /2 , size.height/2 );
        [self addChild: bg];

        sprite = [CCSprite spriteWithFile:@"testSprite.png"];
        sprite.position = ccp(  size.width /2 , size.height/2 );
        [self addChild: sprite];

        [self runAction:[CCFollow actionWithTarget:sprite]];
    }
    return self;
}

My window follows the sprite around, but like I said, the sprite will go to a different point than touched after the first touch. Can anyone tell me what's going on?
edit: I'm thinking that it may have to do with the co-ordinate system itself, or maybe it's to do with
[touches anyObject];? My searches have turned up little.
edit2: I've found that if I return my sprite back to the middle of the bg sprite again, it'll behave normally again from there, until it's too far off.

A: I believe the problem is with [self runAction:[CCFollow actionWithTarget:sprite]];.
selfis your Scene that you don't want to move around.
The pattern for doing this would be to add a CCNodethat you would call a your _contentNodeto your sceneand add everything you would like to move as a child.
Then you would call [_contentNode runAction:[CCFollow actionWithTarget:sprite]];

A: IN this I'll suggest you a simple thing... Before adding a new action, stop the previous action on the sprite...
In your ccTouchesBegan method
[sprite stopAllActions];

[sprite runAction:[CCMoveTo actionWithDuration:moveTime position:location_]];

I think this will help as you sprite will stop once you touch..
In current case its undergoing an action.. Suppose its duration is 2 sec. and on next touch you run action of 1 sec. Then it will go to wrong point as previous action is still not completed.
Hope this helps.. :)


text:
Q: Finding average of line items from invoices - SQL I have this data -
[invoicedetails_key] -- specific line item id number
[invoicekey] -- invoice number
[invoicedetails_itemname] -- line item name
[invoicedetails_itemqty] -- line item qunatity
[invoicedetails_itemprice] -- line item price
FROM [dbo].[vetfeesinvoicedetails]

invoicedetails_key  invoicekey  invoicedetails_itemname invoicedetails_itemqty
1                   2           consult                 1.00
2                   2           lab services)(comp)     1.00
3                   3           urine analysis          1.00
4                   3           metacam                 0.34
5                   3           mirtazapine             1.00
6                   4           mirtazapine             1.00
7                   4           fluid administration    1.00
8                   5           fluid set up iv         1.00
9                   6           mirtazapine             1.00
10                  6           hospitalisation         1.00

From this i want to make a temp table of invoice key and invoicedetails key so i can find the average number of invoice line items per invoice.
(invoice details are id's for specific line items and invoice key are which invoice they are from 'invoice 2, invoice 3 etc)
I started with
CREATE TABLE #TempTable (
Invoicekey int,
invoicedetails_key int
)

SELECT *
FROM #TempTable

INSERT INTO #TempTable
SELECT [invoicedetails_key], [invoicekey]
FROM [dbo].[vetfeesinvoicedetails]

SELECT *
FROM #TempTable

What is the best way to group 'invoicedetails_key' by 'invoicekey' and then find the average ?

A: Okay so i did it step by step using @Charlieface's idea and managed to come up with this that gave me the correct answer.
SELECT [invoicedetails_key], [invoicekey]
INTO #TempTable3
FROM [dbo].[vetfeesinvoicedetails]

SELECT *
FROM #TempTable3

SELECT (cast(invoicekey as int)) as 'Avg'
FROM #TempTable3
GROUP BY invoicekey

SELECT invoicekey, COUNT(invoicedetails_key) AS 'numberoflineitems'
INTO #TempTable4
FROM #TempTable3
GROUP BY invoicekey
ORDER BY invoicekey asc

SELECT AVG(cast(numberoflineitems as decimal(16,4))) as 'Avg'
FROM #TempTable4 ```

A: You don't need to get data into temp table. You can just group by invoicekey, then use AVG() function in the select statement.
If you mean average of item qty, then it's
SELECT AVG([invoicedetails_itemqty])
FROM [dbo].[vetfeesinvoicedetails]
GROUP BY [invoicekey]

Not quite sure what you mean by "find the average number of invoice line items per invoice". Can you show me the sample supposed result from this grid above?

A: You need to group by invoicekey and get the count of rows, then aggregate again and get the average of all groups.
SELECT
  AVG(id.count * 1.0) AS AverageCount,
  AVG(id.TotalQty * 1.0) AS AverageQty
FROM (
    SELECT
      COUNT(*) AS count,
      SUM(id.invoicedetails_itemqty) AS TotalQty
    FROM dbo.vetfeesinvoicedetails id
    GROUP BY
      id.invoicekey
) id;


text:
Q: Inverse matrix of sin and cos being multiplied. find the inverse
$$\begin{pmatrix}
 5 e^{2 t} \sin(2 t) & 5 e^{3 t} \cos(2 t)\\
-6 e^{2 t} \cos(2 t)& 6 e^{3 t} \sin(2 t)
\end{pmatrix}$$
I understand the inverse of
$$\begin{pmatrix}
\cos(t) & -\sin(t) \\
\sin(t) &  \cos(t) \\
\end{pmatrix} $$
being
$$\begin{pmatrix}
 \cos(t) & \sin(t) \\
-\sin(t) & \cos(t) \\
\end{pmatrix} $$
But not am confused with the extra parts.
so would my set up be
$$
\begin{pmatrix}
\sin(t) & -\cos(t) \\
\cos(t) &  \sin(t) \\
\end{pmatrix} $$

A: The straightforward thing would be to apply the formula $$\begin{bmatrix} a & b \\ c & d \end{bmatrix}^{-1}=\frac{1}{ad-bc}\begin{bmatrix} d & -b \\ -c & a \end{bmatrix}.$$
If you want to use the inverse you already know, you can think of your matrix $A$ as the product $$A=\begin{bmatrix} 5 & 0 \\ 0 & 6 \end{bmatrix} \begin{bmatrix}\sin 2t & \cos 2t\\ -\cos 2t & \sin 2t \end{bmatrix} \begin{bmatrix} e^{2t} & 0 \\ 0 & e^{3t} \end{bmatrix} $$ and so  (see https://www.lem.ma/ZN)  $$A^{-1}= \begin{bmatrix} e^{2t} & 0 \\ 0 & e^{3t} \end{bmatrix}^{-1}\begin{bmatrix}\sin 2t & \cos 2t\\ -\cos 2t & \sin 2t \end{bmatrix}^{-1}\begin{bmatrix} 5 & 0 \\ 0 & 6 \end{bmatrix} ^{-1}\\ = \begin{bmatrix} e^{-2t} & 0 \\ 0 & e^{-3t} \end{bmatrix}
\begin{bmatrix}\sin 2t & -\cos 2t\\ \cos 2t & \sin 2t \end{bmatrix}\begin{bmatrix} 1/5 & 0 \\ 0 & 1/6 \end{bmatrix}$$
and now you can multiply the product out.

A: A $2$x$2$ matrix has an inverse defined as follows:$$\begin{bmatrix}
a & b\\
c & d\end{bmatrix}^{-1}=\frac{1}{\underbrace{ad-bc}_{\text{determinant}}}\begin{bmatrix}
d & -b\\
-c & a\end{bmatrix}$$
It only exists if the determinant is non-zero.
Replace $a$, $b$, $c$ and $d$ by your expressions and turn the handle...

A: Hint you may make everything in e ie $$\sin(x)=Ie^{ix},\cos(x)
=R(e^{ix})$$ then finding inverse can be done.


text:
Q: PEP-526 Is not compatible with docstrings for class variables? It appears if I use PEP-526 for class-level variables I must document them in the class's docstring in which case I need to pick my favorite way to do this.
Python 3.6.4 pylint==1.8.4
class Joe(object):
  counter: int = 0
  """This is a counter"""

pylint says (correctly, regardless of whether the variable is assigned to):

W:  3, 2: String statement has no effect (pointless-string-statement)

A: It's not PEP 526 being incompatible with the docstring; it's Pylint not understanding what you've done. Wait for an update.
Some tools support a concept of docstrings for class variables, but it's never been part of Python itself, and PEP 526 doesn't change things.

A: In this case pylint understand line with comment as string expression, not class doc comment. It mean that it string as expression not stored in any variables and will be lost after expression executed. It is the same example:
def foo():
    a = 1
    """ this is string expression, not doc string """
    b = 2

In your case more correctly will be put docstring in top class body:
class Joe(object):
    """This is a counter"""
    counter: int = 0

and pylint understand it correctly:
************* Module tt
C:  4, 0: Trailing newlines (trailing-newlines)
C:  1, 0: Missing module docstring (missing-docstring)
R:  1, 0: Too few public methods (0/2) (too-few-public-methods)


text:
Q: React conceptual problem : An interval which triggers a timeout Imagine this structure in pseudo React code :
export const App = () => {

    const onTick = () => {
        //? (continue reading)
    }

    return (
    <Root>
       <Ticker onTick={onTick}/>
       <UIComponent mustTick={?}/>
    </Root>
    );
}

Without detailing, Ticker contains a system of setInterval/clearInterval that guarantees that "ontick" is called every 5 seconds. So far so good.
What I want is UIComponent to display a message every time a tick happens, but only for one second. Then hide the message again until the next tick.
This is easily achieved inside UIComponent with a setTimeout
(still in pseudo-code )
export const UIComponent = (mustTick : boolean) => {
    const [messageVisible, setMessageVisible] = useState(false);
    //Also store timeout in state (not detailed)

    const onTimeoutFinished = useCallback(() => {
          //clear timeout (not detailed)
          setMessageVisible(false);
       },
       [setMessageVisible]
    );

    useEffect(() => {
         if(mustTick && !messageVisible) {
            setMessageVisible(true);
            setTimeout(1000ms, onTimeoutFinished);
         }
      },
      [mustTick, messageVisible]);

      return messageVisible? (<>Message</>) : (<></>);
}

MY PROBLEM : The part that I don't know how to manage is to communicate the tick only as an impulse to UIComponent. I'm not sure how to avoid heavy wiring to manage it going back to false instantly after becoming true, and who should do it.
How I do it at the moment :
(still in pseudo-code )
export const App = () => {

    const [mustTick, setMustTick] = useState(false);

    const onTick = useCallback(() => {
        setMustTick(true);
    },
    [setMustTick]);

    const onTickProcessed = useCallback(() => {
        setMustTick(false);
    },
    [setMustTick]);

    return (
    <Root>
       <Ticker onTick={onTick}/>
       <UIComponent mustTick={mustTick} onTickProcessed/>
    </Root>
    );
}

I hate that the parent ("App") has to manage that boolean, and in such a verbose way.
Isn't there a better way to keep the state management in the children as much as possible? the children really have a very different purpose, and UIComponent will even probably be disabled in Prod :
Ticker is really all about doing something internally at every tick, while UIComponent is really all about flashing a message briefly at every tick, for informing the user.

A: I think the best way to "teleport" an impulse from one are of the code to another (in this case : make the callback accessible anywhere) will be to manage the tick at top level and transform it into a React Context. Then make UIComponent consume the context.


text:
Q: How to put controls into a Design State Mode just like the Form Designer does? This one has been puzzling me for some time now and maybe the answer is an easy one, or perhaps it involves much more VCL hacking or magic to accomplish what I am looking for but either way I am at a loss as to how to solve my problem.
If you look at the Delphi Form Designer you will see that none of the controls animate when the mouse moves over them, they also cannot receive focus or input (eg you cannot type into a TEdit, click a TCheckBox or move a TScrollBar etc), only at runtime do the controls behave normally and respond to user interaction.
I want to know how can I implement this type of behavior to any control at runtime, eg set controls into like a Designer State Mode? However, controls should also still respond to Mouse Events such as OnMouseDown, OnMouseMove, OnMouseUp etc so they can be moved and sized if needed for example.
This is the closest that I managed:
procedure SetControlState(Control: TWinControl; Active: Boolean);
begin
  SendMessage(Control.Handle, WM_SETREDRAW, Ord(Active), 0);
  InvalidateRect(Control.Handle, nil, True);
end;

Which could be called simply like so:
procedure TForm1.chkActiveClick(Sender: TObject);
begin
  SetControlState(Button1, chkActive.Checked);
  SetControlState(Button2, chkActive.Checked);
  SetControlState(Edit1, chkActive.Checked);
end;

Or for example, all controls on the form:
procedure TForm1.chkActiveClick(Sender: TObject);
var
  I: Integer;
  Ctrl: TWinControl;
begin
  for I := 0 to Form1.ControlCount -1 do
  begin
    if Form1.Controls[I] is TWinControl then
    begin
      Ctrl := TWinControl(Form1.Controls[I]);
      if (Ctrl <> nil) and not (Ctrl = chkActive) then
      begin
        SetControlState(Ctrl, chkActive.Checked);
      end;
    end;
  end;
end;

Two problems I have noticed with the above is that whilst the controls do appear to become Design State like, some controls such as TButton still have the animation effect painted on them. The other issue is when pressing the left Alt key when the controls are Design State like causes them to disappear.
So my question is, how do I put controls into a Design State mode at runtime just like the Delphi Form Designer does, where those controls do not animate (based on Windows Theme) and cannot receive focus or input?
To make that bit clearer, look at this sample image based off the above code sample where the controls are no longer active, but the TButton's animation paint is still active:

But should actually be:

From the two images above, only the TCheckBox control can be interacted with.
Is there a procedure hidden away somewhere that can change the state of a control? Or perhaps a more suitable approach to achieving this? The code I managed to get so far just presents more problems.
Setting the controls to Enabled := False is not an answer I am looking for either, yes the behavior is kind of the same but of course the controls paint differently to show they are disabled which is not what I am looking for.

A: What you are looking for is not a feature of the controls themselves, but rather is an implementation of the Form Designer itself. At design-time, user input is intercepted before it can be processed by any given control. The VCL defines a CM_DESIGNHITTEST message to allow each control to specify whether it wants to receive user input at design-time (for example to allow visual resizing of list/grid column headers). It is an opt-in feature.
What you can do, though, is put the desired controls onto a borderless TPanel, and then simply enable/disable the TPanel itself as needed.  That will effectively enable/disable all user input and animations for its child controls.  Also, when the TPanel is disabled, the child controls will not render themselves as looking disabled.

A: Remy Lebeau's answer on putting controls into a container such as a TPanel, and then setting the panel to Enabled := False does put the controls into the state I was looking for. I also discovered that overriding the controls WM_HITTEST put the controls into the same state, eg they don't receive focus and cannot be interacted with. The problem with those two is that the controls still need to be able to respond to MouseDown, MouseMove and MouseUp events etc but they no longer cannot.
Remy also suggested writing a class and implement Vcl.Forms.IDesignerHook, something I have not attempted yet as maybe it requires too much work for what I need.
Anyway, after lots of playing around I found another alternative way, it involves the use of PaintTo to draw the control onto a canvas. The steps I did are as follows:

*

*Create a custom TPanel with an exposed Canvas

*At FormCreate create and align the custom panel to client

*Add controls to the form at runtime (bringing the custom panel to the front)

*Call the controls PaintTo method onto the custom panels Canvas
What this is essentially doing is creating the components and using the Form as the parent with our custom panel sitting on top. The controls are then painted onto the panels canvas which makes it appear as if the control is on the panel, when actually it sits underneath on the form undisturbed.
Because the controls are underneath the panel, in order for them to respond to events such as MouseDown, MouseMove and MouseUp etc I overrided the WM_NCHitTest in the panel and set the result to HTTRANSPARENT.
In code it would look something like this:
Custom panel:
type
  TMyPanel = class(TPanel)
  protected
     procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHitTest;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

    property Canvas;
  end;

{ TMyPanel }

constructor TMyPanel.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);

  Align := alClient;
  BorderStyle := bsNone;
  Caption := '';
end;

destructor TMyPanel.Destroy;
begin
  inherited Destroy;
end;

procedure TMyPanel.WMNCHitTest(var Message: TWMNCHitTest);
begin
  Message.Result := HTTRANSPARENT;
end;

Form:
type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    FMyPanel: TMyPanel;
    procedure ControlMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
  public
    { Public declarations }
  end;

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
  FMyPanel := TMyPanel.Create(nil);
  FMyPanel.Parent := Form1;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FMyPanel.Free;
end;

procedure TForm1.ControlMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if Sender is TWinControl then
  begin
    ShowMessage('You clicked: ' + TWinControl(Sender).Name);
  end;
end;

Example of adding a TButton to the form:
procedure TForm1.Button1Click(Sender: TObject);
var
  Button: TButton;
begin
  Button := TButton.Create(Form1);
  Button.Parent := Form1;

  FMyPanel.BringToFront;

  with Button do
  begin
    Caption := 'Button';
    Left := 25;
    Name := 'Button';
    Top  := 15;
    OnMouseDown := ControlMouseDown;

    PaintTo(FMyPanel.Canvas, Left, Top);
    Invalidate;
  end;
end;

If you try running the above, you will see that the TButton we created does not animate or receive focus, but it can respond to MouseDown events we attached in the code above, that is because we are not actually looking at the control, instead we are viewing a graphical copy of the control.

A: I'm not sure if this is what you're after or not, but Greatis has a Form Designer component.  See:  http://www.greatis.com/delphicb/formdes/


text:
Q: jQuery button to to activate DIV I want to make a simple action  where a user clicks a button that says "access", rather than submitting the form, I want it to slide down a div.

A: $("#myButton").click(function() {
    $("#myDiv").slideDown();
});

A:

$(function() {
  $('input[value=access]').click(function() {
    $('#access').slideDown();
  });
});
<input type="button" value="access" />

  Here, this will slide down

A: u can use like this

JS

HTML

    Hello World

<button id="mybutton" >Access</button>


text:
Q: Frame titles for PDF chapters in Beamer Pardon me if this question has been duplicated elsewhere, I'm still coming to terms with tex terminology.
I am generating a presentation in Beamer. I like the use of PDF chapters to navigate between slides as well. I use sections to break up the presentation into... sections. However, the ideal subsection heading is just the frametitle. Is there any way to automate the process of retroactively creating subsections based on input to \frametitle?
My document is set up a bit like the following:
\documentclass{beamer}
\begin{document}

\section{Introduction}
\begin{frame}
\frametitle{Research essentials}
Researchers are responsible for many aspects of study design and protocols
\end{frame}

\begin{frame}
\frametitle{Overview}
In this presentation we will be talking about Review Boards, Funding Mechanisms, Statistical Analysis Plans, and Manuscripts
\end{frame}

\section{IRBs}

\begin{frame}
\frametitle{Institutional Review Boards}
IRBs independently review study applications to ensure that the degree of invasiveness is justified, the results of scientific interest, and the confidentiality of study participants protected
\end{frame}
\end{document}

I would like the PDF chapters left hand bar on Adobe to show the following breakdown
Introduction
- Research Essentials
- Overview
IRBs
- Institutional Review Boards


text:
Q: Font Size in Preference How can I change font size in PreferenceScreen
I'm attempting to do the above... It works like a charm, however my SwitchPreference that i'm using no longer have their toggle button. How do i get the button's back?
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <PreferenceCategory
        android:title="@string/pref_user_profile"
        android:textSize="20px"
        android:layout="@layout/pref_layout">

        <SwitchPreference
                android:title="@+string/pref_frequency"
                android:summary="@+string/pref_frequency_summary"
                android:key="frequency"
                android:defaultValue="true"
            android:layout="@layout/pref_layout"/>

        <SwitchPreference
                android:title="@+string/pref_time"
                android:summary="@+string/pref_time_summary"
                android:key="time"
                android:defaultValue="true"
            android:layout="@layout/pref_layout"/>

        <SwitchPreference
                android:title="@+string/pref_symptothermal"
                android:summary="@+string/pref_symptothermal_summary"
                android:key="symptothermal"
                android:defaultValue="true"
            android:layout="@layout/pref_layout"/>

        <SwitchPreference
                android:title="@+string/pref_cervical_mucus"
                android:summary="@+string/pref_cervical_mucus_summary"
                android:key="cervical_mucus"
                android:defaultValue="true"
            android:layout="@layout/pref_layout"/>

        <SwitchPreference
                android:title="@+string/pref_mucus_stamps"
                android:summary="@+string/pref_mucus_stamps_summary"
                android:key="mucus_stamps"
                android:defaultValue="true"
            android:layout="@layout/pref_layout"/>

        <SwitchPreference
                android:title="@+string/pref_fertile_infertile"
                android:summary="@+string/pref_fertile_infertile_summary"
                android:key="fertile_infertil"
                android:defaultValue="true"
            android:layout="@layout/pref_layout"/>
    </PreferenceCategory>

</PreferenceScreen>

And
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView android:id="@+android:id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15sp"/>

    <TextView android:id="@+android:id/summary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12sp"/>

</LinearLayout>

A: Concluding the answer...
The layout should contain a TextView with id "@+android:id/title", a second one with id "@+android:id/summary" and finally (and most important) a container for the preference component with the id "@+android:id/widget_frame".
Here is my proposal.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:baselineAligned="false"
    android:padding="10dp"
    android:weightSum="100" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="50"
        android:orientation="vertical" >

        <TextView
            android:id="@+android:id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+android:id/summary"
            style="@style/SmallText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/darker_gray" />
    </LinearLayout>

    <LinearLayout
        android:id="@+android:id/widget_frame"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:minWidth="64dp"
        android:orientation="vertical"
        android:layout_weight="50" />
</LinearLayout>

You should be aware to style the two textboxes accordingly.

A: I found this little snip that fixed it
<LinearLayout
    android:id="@+android:id/widget_frame"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:gravity="center"
    android:minWidth="48dp"
    android:orientation="vertical" />


text:
Q: Cambiar color de icono al llenar input de formulario Tengo un Login que dentro de su input tiene un icono dentro de un span. Lo que deseo es que cuando el input este lleno por el id del usuario y pase al password, el icono cambie a color verde (para indicar, y estética).
Como puedo lograrlo? dejo el código que eh usado en html y una imagen de los inputs.

  <input type="text" id="user" name="usuario" maxlength="15" placeholder="Usuario" onkeypress="return justNumbers(event)" required >

A: Podes usar la pseudo-clase :valid. Como el input tiene un required, en cuanto escribís un carácter, se le aplica :valid.
Se puede resolver con CSS en la medida que el ícono esté después del input (por como funcionan los selectores), si estuviera antes tendrías que utilizar JavaScript.

.lnr {
  color: #ccc;
}

#user:valid + .lnr {
  color: #0f0;
}

  <input type="text" id="user" name="usuario" maxlength="15" placeholder="Usuario" required>
  Ícono

A: Una solución podría ser esta:

html, body
{
  height: 100%;
}

body
{
  align-items: center;
  display: flex;
  font-family: sans-serif;
  justify-content: center;
  margin: 0;
}

section
{
  background-color: #f2f2f7;
  border-radius: 5px;
  box-sizing: border-box;
  padding: 1em;
  width: 50%;
}

h1
{
  font-size: 1em;
  margin: 0 0 1em;
}

input
{
  background-color: #fff;
  background-image: url('https://i.imgur.com/XmrvrGt.png');
  background-position: left;
  background-repeat: no-repeat;
  background-size: 10%;
  border: 0;
  border-radius: 5px;
  box-sizing: border-box;
  font-size: 1em;
  padding: .5em;
  padding-left: 2em;
  width: 100%;
}

input:invalid
{
  background-image: url('https://i.imgur.com/mOsYsfn.png');
}

Username

  <input pattern="[a-z]{1,15}">

A: Estoy de acuerdo con @azeós: puedes utilizar la pseudo-clase :valid. Como icon utilizaría elementos SVG cuyo stroke es el currentColor
En el input he añadido: pattern="\w{5,10}". Esto dice que el valor del input tiene que ser alpha numeric entre 5 y 10 caracteres. si el valor introducido no cumple esta condición el color cambia al inicial

*{box-sizing:border-box;}
input{height:24px;}
.input-icon{display:flex;}

.lnr {
  color: #333;
}

#user:valid + .lnr {
  color: #0f0;
}

.lnr svg{stroke:currentColor}

  <input type="text" id="user" name="usuario" maxlength="15" placeholder="Usuario" pattern="\w{5,10}" required >

    <svg width='24' viewBox='0 0 24 24'><title>person outline</title>
<path d='M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1-2.1-.94-2.1-2.1.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1h-12.2v-1.1c0-.64 3.13-2.1 6.1-2.1m0-10.9c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 9c-2.67 0-8 1.34-8 4v3h16v-3c0-2.66-5.33-4-8-4z'></path>
</svg>


text:
Q: How to find if a clicked item has a certain data attribute value I have these two radio buttons
<input id="119715_0" type="radio" name="119715" value="76952" data-logic="yes" required />Yes

<input id="119715_1" type="radio" name="119715" value="76953" data-logic="no" required />No

I need to find out first, if they have the data-logic attribute and then the value in order to put together an if statement for if the value is yes or if the value is no. I cant use the id's because there might be multiple buttons on the page that have data-logic so I'm trying to use $(this) so it runs on whichever is getting clicked.
I've found this link How to select elements with jQuery that have a certain value in a data attribute array but it's specific to just the type of tag. I dont know how to use it with $(this)
I have currently been messing around with
function checkLogic() {

if ($(this).attr("data-logic")) {

alert("haslogic");

}
}

$("input").click(checkLogic);

but have been unsuccessful

A: Check with the .data function:  http://jsfiddle.net/byzLG/1/
$('input[name="119715"]').click(function() {
    if ($(this).data('logic') !== undefined) {
        alert('Has data-logic');
    } else {
        alert('Does not have data-logic');
    }
});

Use case where if ($(this).data('logic')) didn't work as you wanted in my original code was if the value was 0.  I'm sure a value of false would have broken it as well.

A: use the .data() method:
$("input").on("click", function(){
  if($(this).data("logic"))
    alert("haslogic");
});

EXAMPLE

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically
  pulled in to jQuery's data object. The treatment of attributes with
  embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5
  specification.

A: You can use plain JavaScript:
if(element.getAttribute("data-logic") === null) {
   // Doesn't have attribute
}

JSFiddle.

A: $("input").click(function() {
    var dataAttr = $(this).attr("data-logic");

    if (dataAttr == "yes") {
      var value = $(this).attr("value");
      alert('Has logic ' + value);
    }

});

http://jsfiddle.net/wCRLE/1/

A: You should check the values with types. Javascript is really wrong with types so you need to be extra cautious:
if (typeof($(this).attr('data-type')) === "undefined")


text:
Q: Why the data comes out from sklearn PCA multiple pca_components different from the original data I am now trying to decomposition the data.
Here is my code:
import xlrd
import xlrd
import xlwt
import numpy as np
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
data = xlrd.open_workbook('x.xlsx')
sh=data.sheet_by_index(1)
num_rows = sh.nrows -1
num_cells = sh.ncols -1
inputData = np.empty([sh.nrows - 1, sh.ncols])
curr_row = -1
while curr_row < num_rows: # for each row
    curr_row += 1
    row = sh.row(curr_row)
    if curr_row > 0: # don't want the first row because those are labels
        for col_ind, el in enumerate(row):
            inputData[curr_row - 1, col_ind] = el.value

print(inputData.shape)
pca = PCA(n_components=3)
newData = pca.fit_transform(inputData)
print(inputData - np.dot(newData, pca.components_))

I think that the the difference between inputData and np.dot(newData, pca.components_) should be very small, but the thing is that the result seems far away from the original data.
Can you help me?

A: You need to add the mean back. To do the reconstruction:
rec = np.dot(newData, pca.components_) + pca.mean_

print(inputData - rec)


text:
Q: Integral of $(-1/(1 + x^2))$ I had a doubt that the integral of $\frac{-1}{1+x^2}$ is given as negative tan inverse $x$. Isn't it equal to $\cot$ inverse ($x$) ?

A: The answers are completely equivalent:
$$
\int-\frac{1}{1+x^2}\,dx=-\arctan x+c
$$
but also
$$
\int-\frac{1}{1+x^2}\,dx=\operatorname{arccot} x+c
$$
because the functions $-\arctan x$ and $\operatorname{arccot} x$ differ by a constant: indeed
$$
\operatorname{arccot} x+\arctan x=\dfrac{\pi}{2}
$$


text:
Q: Incrementing a score counter on a gesture match I have the following method that gets called when a gesture is match within my application but the counter only increments once within the method, so each additional match after the initial match doesn't increment the counter and label. Can someone see where if this is a flaw in my counter logic or if I should be implementing a counter differently?
This is my current solution which only increments on the first match:
void matcher_GestureMatch(Gesture gesture)
        {
            int scoreCntr = 0;
            lblGestureMatch.Content = gesture.Name;
            scoreCntr++;

            var soundEffects = Properties.Resources.punchSound;
            var player = new SoundPlayer(soundEffects);
            player.Load();
            player.Play();

            lblScoreCntr.Content = scoreCntr;

        }

A: You are resetting your count to 0 each time you run the method.  Quickest fix is just declare the variable outside the method:
int scoreCntr = 0;
void matcher_GestureMatch(Gesture gesture)
{
    lblGestureMatch.Content = gesture.Name;
    scoreCntr++;

    var soundEffects = Properties.Resources.punchSound;
    var player = new SoundPlayer(soundEffects);
    player.Load();
    player.Play();

    lblScoreCntr.Content = scoreCntr;
}

A: You need to move scoreCntr out of scope of the method. It is only "alive" when that method runs, so you want to keep it alive during the lifetime of the class it is in. Here is an example of what it would look like:
    private int scoreCntr = 0;

    void matcher_GestureMatch(Gesture gesture)
    {
        lblGestureMatch.Content = gesture.Name;
        Interlocked.Increment(ref scoreCntr);

        var soundEffects = Properties.Resources.punchSound;
        var player = new SoundPlayer(soundEffects);
        player.Load();
        player.Play();

        lblScoreCntr.Content = scoreCntr;
    }


text:
Q: after call does not save data flutter I make a call where I checked it happens correctly, but then when I try to retrieve a data received by the call me from null. I can not understand why but .. quancuno of you can give me a hand?
    Future<UserDataByCode> sendCode() async {
  var url = "$_baseUrl/api/users/ABC124";

  try {
    var response = await _dio.get(
      url,
      options: Options(headers: {"x-access-token": _loginData.token}),
    );

    if (response.statusCode == 200) {
      var userData = UserDataByCode.fromJson(response.data);
      return userDataByCode;
    } else {
      _printLog("Upload sendCode 2", response, level: Level.WARNING);
      return null;
    }
  } on DioError catch (e) {
    _printLog("Upload sendCode 3", e, level: Level.SHOUT);
    return null;
  }
}

This is the UserDataByCode model which should return the data to insert as name in the text after making the call, but it returns null:import 'dart:convert';
class UserDataByCode {
  String firstName;
  String surname;
  int balance;
  double ticketValue;
  int remainingTickets;

  UserDataByCode(
      {this.firstName,
      this.surname,
      this.balance,
      this.ticketValue,
      this.remainingTickets,
      });

  UserDataByCode.fromJson(Map<String, dynamic> json) {
    firstName = json['user_name_first'];
    surname = json['user_name_surname'];
    balance = json['tckt_balance'];
    ticketValue = json['ticket_value'];
    remainingTickets = json['remaining_tickets'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['firstName'] = this.firstName;
    data['surname'] = this.surname;
    data['balance'] = this.balance;
    data['ticketValue'] = this.ticketValue;
    data['remainingTickets'] = this.remainingTickets;
    return data;
  }

  @override
  String toString() {
    return jsonEncode(toJson());
  }
}

In my ContentManager I put this, since for the other calls whoever worked before me did well I hurt the same thing ..
      Future<UserDataByCode> getUserDataByCode() async {
    return _userDataByCode = await connection.sendCode();
  }

  UserDataByCode getUserDataByCodeSync() {
    if (_userDataByCode == null) {
      print("Still no _userDataByCode");
      return null;
    }
    return _userDataByCode;
  }

UPDATE:
Receive this
UPDATE 2:
    return FutureBuilder<UserData>(
    future: contentManager.getUserData(),
    builder: (context, AsyncSnapshot<UserData> snapUserData) {

All widget code:
      Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    _buttonHeight = size.height * .05;
    //double splitPoint = size.height / 7;

    return FutureBuilder<UserData>(
        future: contentManager.getUserData(),
        builder: (context, AsyncSnapshot<UserData> snapUserData) {
          if (snapUserData.hasError)
            return Container(
              child: Center(
                child: Text("There was some error"),
              ),
            );
          if (snapUserData.connectionState != ConnectionState.done)
            return Container(
              child: Center(
                child: CircularProgressIndicator(valueColor: new AlwaysStoppedAnimation<Color>(appColors.yellow)),
              ),
            );
            return Container(
              color: appColors.primaryColor,
              child: ListView(
                primary: false,
                      children: [
                        // TITOLO
                        Align(
                          alignment: Alignment.center,
                            child: Container(
                            child: Text(
                                    localization.showQR,
                                    style: Theme.of(context).primaryTextTheme.headline5.copyWith(
                                      color: appColors.green,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                            ),
                        Align(
                          alignment: Alignment.center,
                            child: Container(
                                    child: qrCodeHolder
                                ),
                            ),
                        Align(
                          alignment: Alignment.center,
                            child: Container(
                                  child: AutoSizeText(
                                    localization.home_subLabel,
                                    textAlign: TextAlign.center,
                                    maxLines: 1,
                                    style: Theme.of(context).primaryTextTheme.headline5.copyWith(
                                      color: appColors.green,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                            ),
                        Padding(
                          padding: EdgeInsets.all(15.0),
                          //top: size.height * .02,
                          //right: size.width * .02,
                          child: Row(
                            children: [
                              Expanded(
                                  child: TextField(
                                    inputFormatters: [
                                      new LengthLimitingTextInputFormatter(11),
                                    ],
                                    decoration: InputDecoration(
                                      filled: true,
                                      fillColor: Colors.white,
                                      focusedBorder: OutlineInputBorder(
                                        borderSide: BorderSide(color: Colors.white),
                                      ),
                                      enabledBorder: UnderlineInputBorder(
                                        borderSide: BorderSide(color: Colors.white),
                                      ),
                                    ),
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                      fontSize: 18.0,
                                      color: Colors.black,
                                    ),
                                  ),
                                ),
                              IconButton(
                                icon: Image.asset("assets/images/send.png"),
                                onPressed: () async {
                                  connection.sendCode().then((value) {
                                      if (value != null) {
                                        showDialog(context: context, builder: (_) => PaymentDialog());
                                      } else {
                                        showDialog(context: context, builder: (_) => PaymentDialog());
                                      }
                                    });
                                  }
                                //onPressed: () => showDialog(context: context, builder: (_) => PaymentDialog()),
                              ),
                            ]
                          ),
                        ),
                      ],
                  padding: EdgeInsets.all(20.0),
                ),
              );
        });
  }
}


text:
Q: amqplib sendToQueue() is not sending messages to RabbitMQ I am building a Typescript package around amqplib's Promise API to make it simpler for me to send messages between two RabbitMQ queues.
This is a method inside a class of said package that is responsible for sending a message to RabbitMQ. It's not actually sending messages, because I can't see them from CloudAMQP.
class PostOffice {
    connection: any;

    constructor(connection: any) {
        this.connection = connection;
    }

    //...

    // TMQMessage is an object that can be trivially serialized to JSON
    // The Writer class holds the channel because I'm having trouble
    // making Typescript class member updates stick after a method returns.
    async send(writer: Writer, message: TMQMessage) {
        //...RabbitMQ code begins here
        let channel = writer.stageConsume[0]; // This channel is created elsewhere

        // Queue is created here and I can see it in CloudAMQP.
        await channel.assertQueue(message.to + "/stage/1", {
            durable: true,
        }); // `message.to` is a string indicating destination, e.g. 'test/hello'

        // According to docs, the content should be converted to Buffer
        await channel.sendToQueue(message.to + "/stage/1", Buffer.from(JSON.stringify(message)));

        channel.close()
    }

}

This is a class I made that creates connections and channels, which is being used here:
import { Writer } from "./Writer";

export class ConnectionFactory {
    url: string;
    amqp: any;
    constructor(url: string) {
        this.url = url;
        this.amqp = require('amqplib');
    }

    async connect(timeout: number = 2000) {
        let connection = await this.amqp.connect(this.url, {
            // timeout for a message acknowledge.
            timeout, // Make the timeout 2s per now
        })
        return connection;
    }
    async createChannels(connection: any, writer: Writer) {
        //... relevant code starts here
        let stageChannels = [];
        stageChannels.push(await connection.createChannel())
        writer.stageConsume = stageChannels;
        return writer;
    }
}

}
My connection factory seems to be working properly, because I can see the connections from CloudAMQP's dashboard. Also I can see the Queues that have been created (asserted in my code) from the dashboard too. However, I am unable to get amqplib to send a message out to CloudAMQP.
Here's the (async) code I'm using to call my package:
let Cf = new ConnectionFactory(url)
let connection = await Cf.connect()
let writer = new Writer();

let message: TMQMessage = {
    //... message content in JSON
}

writer = await Cf.createChannels(connection, writer)
let po = new PostOffice(connection)
await po.send(writer, message)

What seems to be wrong?

A: Probably want to await the close method too. But in general I would recommend amqp-client.js (that also have TypeScript definitions), https://github.com/cloudamqp/amqp-client.js/


text:
Q: apt-get fails with unmet dependencies: Breaks, Depends, Recommends - what does it all mean? I am attempting to patch the Dirty Cow vulnerability by running the following command on my Ubuntu 12.04 server:
sudo apt-get update && sudo apt-get dist-upgrade

This results in the follow error(s):
The following packages have unmet dependencies:
 lsb-base : Breaks: upstart (< 1.12.1-0ubuntu8)
            Breaks: upstart:i386 (< 1.12.1-0ubuntu8)
 plymouth : Depends: initramfs-tools but it is not going to be installed
            Recommends: plymouth-theme-ubuntu-text but it is not going to be installed or
                        plymouth-theme
 udev : Depends: initramfs-tools (>= 0.92bubuntu63) but it is not going to be installed
        Depends: util-linux (> 2.15~rc2)
E: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages.

What do I need to do in order to fix these errors?

A: I recommend to fix the dependencies dist-upgrade is complaining about to run these commands in order separately to update and upgrade and thusly correct any dependencies that are not currently being met.
sudo apt-get update

then
sudo apt-get upgrade

then
sudo apt-get dist-upgrade

Together update with upgrade has helped correct a lot of issues I've stumbled into in the past. Update helps upgrade know where what when and how to upgrade.
A simplified example would be you have v.1, while dist-upgrade was requiring you to be in v.2 which running update only got you to v.1.5 while upgrade finished the job and got you to v.2 making your system welcoming and ready for dist-upgrade.
Glad to hear it helped!


text:
Q: SQL Server 2008 change tracking Is it possible to make schema change to SQL server 2008 internal change tracking tables ( I don't mind to put the database in single user mode on Dedicated Admin Connection (DAC) if required).
For Ex, I want to change a single column primary key to Composite primary Key on a User table, but i don't want to loose the change tracking data for that table. Is it possible to update the Change tracking table schema to include the composite key?
Thanks

A: Why don't you archive the change tracking data somewhere before you change the keys and re-initiate CT? If the columns can still line up, you can create a view that unions the two tables. Seems much simpler (never mind supported) to me.


text:
Q: Android Studio onClick for a display method not working at all I was trying to make an onClick method for buttons in an array list, but for some reason it kept saying it didn't work because "could not find method in a parent context" is not given, I tried countless times and basically gave up (so let's leave that for now). NOW I copied the code to a very simple method to check the problem then the button still won't work, more specifically when the displayQuantity is called (when I tried the debugger). Any help with that. (also I'm a beginner so pls go easy on me).
public class world_tour extends AppCompatActivity {

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

    int quantity = 1;

    /**
     * This method displays the given quantity value on the screen.
     */
    private void displayQuantity(int number) {
        TextView quantityTextView = findViewById(R.id.world_text_view);
        quantityTextView.setText(number);
    }

    /** this method is used to increase quantity*/
    public void add (View view) {
        quantity = quantity + 1;

        displayQuantity(quantity);
    }
}

XML
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".world_tour">

    <TextView
        android:id="@+id/world_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:paddingBottom="16dp"
        android:text="1"
        android:textAlignment="center"
        android:textColor="#000000"
        android:textSize="16sp"/>

    <Button
        android:layout_width="48dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="16dp"
        android:text="+"
        android:onClick="add"/>

</LinearLayout>

the logcat

java.lang.IllegalStateException: Could not execute method for android:onClick
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
        at android.view.View.performClick(View.java:6205)
        at android.widget.TextView.performClick(TextView.java:11103)
        at android.view.View$PerformClick.run(View.java:23653)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:6205)
        at android.widget.TextView.performClick(TextView.java:11103)
        at android.view.View$PerformClick.run(View.java:23653)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
     Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x2
        at android.content.res.Resources.getText(Resources.java:1178)
        at android.widget.TextView.setText(TextView.java:5164)
        at com.example.android.franchjapp.world_tour.displayQuantity(world_tour.java:25)
        at com.example.android.franchjapp.world_tour.add(world_tour.java:33)

A: You have to cast your number to a String:
quantityTextView.setText(""+number);

I think this will do your job

A: The problem is that setText() is expecting a string resource id, not a numeric value. You can see this by looking the all stacktrace:
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x2
You have to cast your number to a String: quantityTextView.setText(String.valueOf(number));
Then you will be calling a method that expects a CharSequence.


text:
Q: PHPDoc interface binding in PhpStorm I have a class that is bound to interface in Laravel, so when I inject the interface I have access to the bound methods and properties.
I don't why, but PhpStorm detect the bound method but not the properties !
Is there anyway to till the IDE about the properties ?
e.g:
class cls{
    public $pro;

    public function foo()
    {

    }
}

interface clsInterface{
}

now binding it in AppServiceProvider:
$this->app->bind(clsInterface::class,cls::class);

after that, in any controller I inject the interface:
class P2PController extends Controller
{

    public function __construct(clsInterface $interface)
    {
        //now when calling $interface-> , phpstorm detect foo function but doesn't detect $pro
        // if I type $interface->pro; phpstorm will raise warning "field pro not found"

    }

}


text:
Q: Count active Angular httpClient calls to show loading spinner using rxjs operators In the below code, this.busyCount++ is called just once per call to my get method but the this.busyCount-- inside tap() is being called multiple times. This is causing isBusy to always be false.
What is the correct way to increment and decrement busyCount to find out if there is an active http request.
The showBusy parameter determines if loading spinner is displayed or not. I'm not sure how I would pass this to an interceptor or I could use the approach here.
I've tried using finalize operator to decrement but I faced the same issue.
@Injectable()
export class DataService {

    constructor(private http: HttpClient) { }

    public busyCount = 0;
    public get isBusy(): boolean { return this.busyCount > 0; }

    get<T>(relativeUrl: string, showBusy: boolean = true): Observable<T> {
        if (showBusy)
            this.busyCount++;
        return this.http.get<T>(`${this.baseURL}${relativeUrl}`)
            .pipe(
                tap(s => {
                    if (showBusy)
                        this.busyCount--;
                }),
                catchError((err: HttpErrorResponse) => {
                    if (showBusy)
                        this.busyCount--;
                    return Observable.throw(err)
                })
            );
    }
}

A: According to the examples in the documentation, using tap with http.get may give you more events than just the success response you're expecting. For one thing, it will emit on both success and failure, and I suspect on redirects as well.
If you restrict your decrement operation to only occur when the event is HttpResponse I believe you'll get the behavior you're looking for:
return this.http.get<T>(/*...*/).pipe(
    tap(event => {
        if (showBusy && event instanceof HttpResponse)
            this.busyCount--;
    }),
    catchError /* ... */
}

A: You are returning an observable from the service. Each time you create this observable you increment the busy count but no http call has been made until something subscribes to the observable. So your busy count goes up by one but it is not necessarily busy yet.
Each time something subscribes to the observable the busy count will go down as the request finishes.
Without seeing how you use the observables it is not possible to predict how many times you subscribe to the same observable but you only ever increment once and decrement every time a subscription fires.
Having a single flag for all activity seems undesirable to me anyway.
You can read my article about Angular state management with my RxCache library and see the pattern I use here https://medium.com/@adrianbrand/angular-state-management-with-rxcache-468a865fc3fb

A: This is hacky but works so we ended up using this
@Injectable()
export class DataService {

    constructor(private http: HttpClient) { }

    public busyCount = 0;
    public get isBusy(): boolean { return this.busyCount > 0; }

    get<T>(relativeUrl: string, showBusy: boolean = true): Observable<T> {
        return this.handleHttpRequest(this.http.get<T>(`${this.baseURL}${relativeUrl}`), showBusy);
    }

    private handleHttpRequest<T>(httpResponse$: Observable<T>, showBusy: boolean = true): Observable<T> {
        return Observable.from([0])
            .do(() => {
                if (showBusy) {
                    this.busyCount++;
                }
            })
            .switchMap(() => {
                return httpResponse$;
            })
            .pipe(
                catchError((err: HttpErrorResponse) => {
                    return Observable.throw(err)
                }),
                finalize(() => {
                    if (showBusy) {
                        this.busyCount--;
                    }
                })
            );
    }

}


text:
Q: If a and b generate groups of their own, then any linear combination of the integers, will also generate a group? sorry if the wording of the question was a little confusing. But I am confused by a theorem that was provided in my algebra textbook. There was a proposition which stated that:
Theorem 1: Let S be a subgroup of the additive group $\mathbb{Z}^{+}$. Either S is the trivial subgroup {0}, or else it has the form, $\mathbb{Z}$ where a is the smallest positive integer in S.
This makes intuitive sense to me. Now, here is the proposition that is confusing to me:
Subgroups that contain two integers a, and b. (I am not sure how a subgroup can only contain two integers, first of all). The set of all integer combinations of ra + sb, of a and b,
$S = \mathbb{Z}a + \mathbb{Z}b = \{n \in \mathbb{Z}| n = ra + sb\}$for some integers r,s.
Why must this necessarily be true? I don't see any intuitive reason why any linear combination of the generators must be part of some subgroup?
Furthermore,it stated:
Proposition : Let a and b be integers both not 0, and let d be their greatest common divisor, the positive integer that generates the subgroup $S = \mathbb{Z}a + \mathbb{Z}b$. Why must this value d be the greatest common divisor? Can someone please help me understand the reasoning?


text:
Q: Entity Framework CreateIfNotExists on Database side I am working on a project where there is table called Groups.
Groups has primary key on the Id column which is string but stores GUID.
The project has a mobile app which allows offline data store. So when a group gets created on Mobile app, it first stores the group on local storage of mobile. Then it uses synchronization mechanism to synchronize the local mobile database with the one on server.
So let's say, there is one group with ID 5e77d8be57ee4505afc1d6ceffe9e3f1 stored on mobile local storage which is about to get synchronized, the mobile app will send create request on POST Groups and the API will try to create group with following code.... (Simplified one)
...
if (dbContext.Groups.Any(s => s.GroupId == group.GroupId))
{
    return;
}

dbContext.Groups.Add(group);
dbContext.SaveChanges();
...

The code works fine in most of the scenario but does not when the mobile app sends multiple request to synchronize the same group. In which case, it sometimes throws an error

Violation of PRIMARY KEY constraint 'PK_dbo.Groups'. Cannot insert duplicate key in object 'dbo.Groups'

My question is, how can I handle this error with a way to CreateIfNotExists on the database side?


text:
Q: os.path.split, changing file name with out compromising the Path i have followed Python get file name and change & save it in variable. which work fine and change the file name as required.
but now i am facing problem with path where the file is getting saved. as the file is getting saved in "media/ok_abc.txt" whereas it should be media/documents/ok_abc.txt
e.g.
docfile = /media/documents/abc.csv
after applaying below instruction
filename = os.path.splitext(docfile.name)[0]
newfilename = 'ok_%s.txt' % filename

am able to change the file name but the path is getting reduced as /media/ok_abc.txt, it should be /media/documents/abc.txt
how i can change the file name with out compromising on the Path

A: Extract the directory from the full file path, and later add it back.
path, filename = os.path.split(docfile)
filename = os.path.splitext(filename)[0]
newfilename = 'ok_%s.txt' % filename
newpath = os.path.join(path, newfilename)


text:
Q: How should i go about using a user input in an equation like Fahrenheit to Celsius? When I run the code it says it is the conversion line #taking temperature in fahrenheit
fahrenheit = float(input("Enter temperature degrees in fahrenheit:"))

#Coversion formula
conv_for = (input - 32) * 5/9

#calculation for celcius
celcius = conv_for
    print("%02f degrees in fahrenheit is equal to %02f degrees in celcius")

I am fairly new to coding so are their any other ways to improve this?

A: In this line, you're taking the temperature the user enters and storing it in a variable called fahrenheit.
#taking temperature in fahrenheit
fahrenheit = float(input("Enter temperature degrees in fahrenheit:"))

So if the user typed in, say, 76, then fahrenheit would store the value 76. In this line, however, you're using input instead of fahrenheit.
#Coversion formula
conv_for = (input - 32) * 5/9

input is essentially a function that takes what the user types in and stores it. I think what you're actually wanting is, instead of input, to use fahrenheit. While we're at it, let's assign that to celsius instead of conv_for for clarity. Here's the corrected version of the above:
celsius = (fahrenheit - 32) * 5/9

Similarly, your print statement needs to specify which variables go in for each spot:
print(f"{fahrenheit} degrees in fahrenheit is equal to {celsius} degrees in celsius")

You could alternatively do it like you were doing before and it will then round at 2 decimal places (that is what 02 means):
print("%.02f degrees in fahrenheit is equal to %.02f degrees in celsius" % (fahrenheit, celsius))

A: Here is the corrected code:
fahrenheit = float(input("Enter temperature degrees in fahrenheit:"))

#Coversion formula
conv_for = (fahrenheit - 32) * 5/9

#calculation for celcius
celcius = conv_for
print(f"{fahrenheit} degrees in fahrenheit is equal to {celcius} degrees in celcius")

A: ok first thing indention is important in python so be careful,

# Taking temperature in fahrenheit
fahrenheit = float(input("Enter temperature degrees in fahrenheit:"))

# Calculation for celcius
celcius = (fahrenheit - 32) * 5/9

#Displaying the output
print("%s degrees in fahrenheit is equal to %s degrees in celcius"%(fahrenheit, celcius))


text:
Q: Using multiple materials with THREE.CylinderGeometry - create a wheel from cylinder I want to create a wheel from cylinder (because importing 3D models makes it slower). But I cannot use multiple materials with cylinder geometry. It uses only the first material in an array.
    var geometry = new THREE.CylinderGeometry(this.diameterWheel/2,this.diameterWheel/2,this.lastikGenisligi, 20, 4);

    var materialArray = [];
    materialArray.push(new THREE.MeshBasicMaterial( { color: 0x000000 }));
    materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( '../textures/wheel.png' ) }));
    materialArray.push(new THREE.MeshBasicMaterial( { color: 0x0000FF }));
    materialArray.push(new THREE.MeshBasicMaterial( { color: 0xFF0000 }));

    var material = new THREE.MeshFaceMaterial(materialArray);

    var mesh = new THREE.Mesh(geometry, material);

What I want to create is a wheel which will have wheel.png wheel image on upper and bottom sides and black coverage on between them.

A: You need to loop through each face on the cylinder and tell which of the array materials the face uses.
geometry.faces[a].materialIndex = b;

Where a is the face index. You need to figure out yourself which face is which to choose the correct material through some system, ie. faces 0-10 with one color, etc. This depends on the cylindergeometry parameters. And b is the material index.


text:
Q: Does empty "else" cost any time Is there any difference in computational cost of
if(something){
    return something;
}else{
    return somethingElse;
}

and
if(something){
    return something;
}
//else (put in comments for readibility purposes)
return somethingElse;

In theory we have command (else) but it doesn't seem it should make an actuall difference.
Edit:
After running code for different set sizes, I found that there actually is a differrence, code without else appears to be about 1.5% more efficient. But it most likely depends on compiler, as stated by many people below. Code I tested it on:
int withoutElse(bool a){
if(a)
    return 0;
return 1;

}

int withElse(bool a){
if(a)
    return 0;
else
    return 1;
}

int main(){
using namespace std;
bool a=true;
clock_t begin,end;
begin= clock();
for(__int64 i=0;i<1000000000;i++){
    a=!a;
    withElse(a);
}
end = clock();
cout<<end-begin<<endl;

begin= clock();
for(__int64 i=0;i<1000000000;i++){
    a=!a;
    withoutElse(a);
}
end = clock();
cout<<end-begin<<endl;

return 0;
}

Checked on loops from 1 000 000 to 1 000 000 000, and results were consistently different
Edit 2:
Assembly code (once again, generated using Visual Studio 2010) also shows small difference (appareantly, I'm no good with assemblers :()
   ?withElse@@YAH_N@Z PROC                  ; withElse, COMDAT
   ; Line 12
push    ebp
mov ebp, esp
sub esp, 192                ; 000000c0H
push    ebx
push    esi
push    edi
lea edi, DWORD PTR [ebp-192]
mov ecx, 48                 ; 00000030H
mov eax, -858993460             ; ccccccccH
rep stosd
   ; Line 13
movzx   eax, BYTE PTR _a$[ebp]
test    eax, eax
je  SHORT $LN2@withElse
   ; Line 14
xor eax, eax
jmp SHORT $LN3@withElse
   ; Line 15
jmp SHORT $LN3@withElse
   $LN2@withElse:
   ; Line 16
mov eax, 1
   $LN3@withElse:
   ; Line 17
pop edi
pop esi
pop ebx
mov esp, ebp
pop ebp
ret 0
   ?withElse@@YAH_N@Z ENDP                  ; withElse

and
   ?withoutElse@@YAH_N@Z PROC               ; withoutElse, COMDAT
   ; Line 4
push    ebp
mov ebp, esp
sub esp, 192                ; 000000c0H
push    ebx
push    esi
push    edi
lea edi, DWORD PTR [ebp-192]
mov ecx, 48                 ; 00000030H
mov eax, -858993460             ; ccccccccH
rep stosd
   ; Line 5
movzx   eax, BYTE PTR _a$[ebp]
test    eax, eax
je  SHORT $LN1@withoutEls
   ; Line 6
xor eax, eax
jmp SHORT $LN2@withoutEls
   $LN1@withoutEls:
   ; Line 7
mov eax, 1
   $LN2@withoutEls:
   ; Line 9
pop edi
pop esi
pop ebx
mov esp, ebp
pop ebp
ret 0
   ?withoutElse@@YAH_N@Z ENDP               ; withoutElse

A: It is generically different, but the compiler may decide to execute the same jump in both cases (it will practically do this always).
The best way to see what a compiler does is reading the assembler. Assuming that you are using gcc you can try with
gcc -g -c -fverbose-asm myfile.c; objdump -d -M intel -S myfile.o > myfile.s

which creates a mix of assembler/c code and makes the job easier at the beginning.
As for your example it is:
CASE1
if(something){
23: 83 7d fc 00             cmp    DWORD PTR [ebp-0x4],0x0
27: 74 05                   je     2e <main+0x19>
    return something;
29: 8b 45 fc                mov    eax,DWORD PTR [ebp-0x4]
2c: eb 05                   jmp    33 <main+0x1e>
}else{
    return 0;
2e: b8 00 00 00 00          mov    eax,0x0
}

CASE2
if(something){
23: 83 7d fc 00             cmp    DWORD PTR [ebp-0x4],0x0
27: 74 05                   je     2e <main+0x19>
    return something;
29: 8b 45 fc                mov    eax,DWORD PTR [ebp-0x4]
2c: eb 05                   jmp    33 <main+0x1e>
return 0;
2e: b8 00 00 00 00          mov    eax,0x0

As you could imagine there are no differences!

A: It won't compile if you type `return
Think that once the code gets compiled, all ifs, elses and loops are changed to goto's
If (cond) { code A } code B

turns to
if cond is false jump to code b
code A
code B

and
    If (cond) { code A } else { code B } code C
turns to
if cond is false jump to code B
code A
ALWAYS jump to code C
code B

code C

Most processors 'guess' whether they're going to jump or not before checking if they actually jump. Depending on the processor, it might affect the performance to fail a guess.
So the answer is YES! (unless there's an ALWAYS jump at the end of first comparison) It will take 2-3 cycles to do the ALWAYS jump which isn't in the first if.


text:
Q: DNN 9.8 - EventLogController is obsolete - Does anyone have an example on how to use the Dependency Injection method to fix this error? Does anyone perhaps have an example to replace the old Error logging in DNN module?
I have looked at the following articles:

*

*https://dnncommunity.org/forums/aft/1527

*Has anyone implemented DotNetNuke.Abstractions.Portals.IPortalAliasInfo.HttpAlias in DNN version 9.9?
I currently get the following error:

catch (Exception ex)
    {
      EventLogController logController = new EventLogController();
      logController.AddLog("Problem Getting Product Description, Title, or Image URL.", ex.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
    }

Do you need to create a startup file?
If so, do you need to create a startup file for each module or put it in the root folder?

A: Here is some code that works for me:
using DotNetNuke.Abstractions;
using DotNetNuke.Abstractions.Logging;
using Microsoft.Extensions.DependencyInjection;

namespace myCompany.DNN.Modules.myModule {
   private readonly IEventLogger _eventLogger;
   public class myControl {
      public myControl() {      // this is the constructor of the class
         _eventlogger = DependencyProvider.GetRequiredService<IEventLogger>();
      }
   }

   protected override void someEvent(object sender, EventArgs e) {
      try {
         // some code
      } catch(Exception ex) {
         _eventLogger.AddLog("Problem Getting Product Description, Title, or Image URL.", ex.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
      }
   }
}

And this article could be useful, too...


text:
Q: jquery 1.5 mock ajax In jquery 1.5, what is the recommend approach for mocking ajax requests? Is it to use the ajax extension transports?
http://api.jquery.com/extending-ajax/#Transports

A: Have you tried extending $.ajax with the 1.5 update and finding out if you can call .resolve on the jqXHR.
As long as you get it to not remove the .promise read-only Deferred object you should be able to fake a completion of the ajax request.
Alternative you can always just mock out a node.js server.
Anywhere you can hook into and get the jqXHR object you might be able to call .resolve on it with the mock paramaters.

A: I have a similar question here :
How to test jquery and ajax calls using JsTestDriver?
And I found solutions, maybe there are others better, but it works with our JsTestDriver tests.

A: I have created on mock for jQuery AJAX, and I used three extension points that jQuery 1.5+ provided (prefitler, transport, and converters). Please check this out
https://github.com/fredyang/ajaxMock
for detail usage, please check the test case, all the test cases are passed, and they are just the living document about how to use it.
Here is the url of the test case
https://github.com/fredyang/ajaxMock/blob/master/test/test.js
Here is the link that run the test case
http://code.semanticsworks.com/ajaxMock/test/index.html
and here is the link of the mock
http://code.semanticsworks.com/ajaxMock/src/ajaxMock.js


text:
Q: ViewPager c видимыми частями соседних страниц Есть ViewPager. Подскажите, как сделать так, чтобы в центре был один элемент и было видно слева и справа края соседних элементов?

A: Если я правильно Вас понял, то есть вариант использовать PageTransformer.
Посмотреть пример как это можно сделать можно здесь.

A: Тут описывается как это сделать.
ViewPager With Protruding Children
ViewPager with previous and next page boundaries
Если вкратце, то для ViewPager необходимо установить 2 атрибута:

*

*setClipToPadding(false)

*Установить left & right padding

И в Adapter переопределить метод PagerAdapter.getPageWith().


text:
Q: Missing package "metro-config" (React Native) Hi guys I'm making my first app in react-native and i got a problem while installing.
Missing package "metro-config" in the project at: C:\Users\Luc\Downloads\dashboard\ToDo APP\todoList
This usually means `react-native` is not installed. Please verify that dependencies in package.json include "react-native" and run `yarn` or `npm install`.
Error: Missing package "metro-config" in the project at: C:\Users\Luc\Downloads\dashboard\ToDo APP\todoList
This usually means `react-native` is not installed. Please verify that dependencies in package.json include "react-native" and run `yarn` or `npm install`.
    at resolveFromProject (C:\Users\Luc\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\metro-config\src\importMetroFromProject.ts:19:11)
    at importFromProject (C:\Users\Luc\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\metro-config\src\importMetroFromProject.ts:25:18)
ts:29:10)
    at getDefaultConfig (C:\Users\Luc\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\metro-config\src\ExpoMetroConfig.ts:89:23)
    at Object.loadAsync (C:\Users\Luc\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\metro-config\src\ExpoMetroConfig.ts:268:23)
    at runMetroDevServerAsync (C:\Users\Luc\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\dev-server\src\MetroDevServer.ts:58:45)
    at startDevServerAsync (C:\Users\Luc\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\src\start\startDevServerAsync.ts:69:55)
    at startAsync (C:\Users\Luc\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\src\start\startAsync.ts:74:41)

A: Try

npm install

yarn install

if it's your first project. I think you may get started with expo-cli. It is similar to react-native CLI with a simple workflow.
But I recomend you to re-install/re-follow doc steps.
Check this out
https://reactnative.dev/docs/environment-setup

A: I think you have forked or copied the code from somewhere and trying to learn how things work.I js projects we may have a lot of dependencies and that dependencies also may some dependencies thus the modules we require would be huge enough.While we are storing our code or sharing our code,we basically ignore the node_modules folder and when you are running the app .At first  you should install all the required modules.

npm install

if you are using npm as your package manager

yarn install

if you are using yarn as your package manager

Either of these commands will install the required modules for your project and then try to run it.happy coding!!!


text:
Q: Yii2 rule which would allow all the letters (including special ones), but without special characters? I have a problem here. My username rule allowing to enter only letters without special characters, but could someone help me to make that it would allow letters (including special letters), but without special characters?
F.e:
Test - good,
Tęęęst - good,
Test2 - bad.
My rule is:
['username', 'match',
   'pattern' => '/[a-z]+$/',
]

Thanks for any help

A: Use this but remember it does not work on the client side since JavaScript does not support unicode regex flags (at least without special plugins):
['username', 'match', 'pattern' => '/^\p{L}+$/u']

This allows letters (in all languages) only.


text:
Q: Changing font color in each PairGrid Seaborn plot based on pearsonr value: I am plotting using seaborn and I am using seaborn.PairGrid function (code below).
I am able calculate pearsonr value and set my color list.
Is there way to use to change each pairplot color based on the pearsonr correlation values?
global my_colors
my_colors = []

def corrfunc(x, y, **kws):
    r = stats.pearsonr(x, y)[0] ** 2
    ax = plt.gca()
    ax.annotate("r$^2$ = {:.2f}".format(r),
                 xy=(.1, .9), xycoords=ax.transAxes)
    if r > 0.6:
       my_colors.append('g')
    elif r < 0.6:
       my_colors.append('r')
    return r

df = pd.read_excel(Inp_Filename, sheetname='IC_Data')

IC_Plot = sns.PairGrid(df)
IC_Plot.map_offdiag(corrfunc)

IC_Plot.map_offdiag(sns.regplot, color='g')
#Need to change color of each
#pairplot based on the pearsonr value

IC_Plot.map_offdiag(plt.scatter, s=10)

IC_Plot.savefig("IC_Pair.png")

A: You may call the plotting method from within the function that determines the color. In that way the color can simply be given as an argument to the plotting function.
import seaborn.apionly as sns
import matplotlib.pyplot as plt
from scipy.stats import pearsonr

df = sns.load_dataset("iris")

def corrfunc(x, y, **kws):
    r = pearsonr(x, y)[0] ** 2
    ax = plt.gca()
    ax.annotate("r$^2$ = {:.2f}".format(r),
                 xy=(.1, .9), xycoords=ax.transAxes)
    if r > 0.6:
       col = "g"
    elif r < 0.6:
       col= 'r'

    sns.regplot(x,y,color=col)
    return r

IC_Plot = sns.PairGrid(df)
IC_Plot.map_offdiag(corrfunc)

plt.show()


text:
Q: i am checking if username exist in database and then sending response code 200/400 users.js
import express from 'express'
import Validator from 'validator'
import isEmpty from 'lodash/isEmpty'
import isEmail from 'validator/lib/isEmail';
import {MongoClient} from 'mongodb'

let router = express.Router()

function validatInput(data){
    var error = {}

    if(data.username === ""){
        error.email = "this field is req"
    }

    if(!isEmail(data.username)){
        error.email = "email is not valid "
    }

    if(data.password === ""){
        error.password = "this field is req"
    }

    return{
        error:error,
        isValid:isEmpty(error)
    }
}

router.post('/',(reqs,resP)=>{
    var url ="mongodb://localhost:27017/loginUsers"

    const {error,isValid} = validatInput(reqs.body)
    error.email = err
    console.log(error.email +"body")

    if(!isValid ){
        console.log("not valid")
        resP.status(400).send(error)
    }

    let err=""
    MongoClient.connect(url,function (err,db) {
        if(err){
            console.log("database connection error")
        }
        else{
            var collection = db.collection('UsersList')

            var student = reqs.body
            console.log(" email "+ reqs.body.username)
            collection.find({"username":reqs.body.username},function(err,res){

                if(err){
                    console.log(err)
                }
                else if(!res){
                    err=null
                    console.log(" not find" )
                    collection.insert([student],function(err,res){
                        if(err){
                            console.log("data not inserted")
                        }else{
                            console.log(res)
                        }
                    })
                    resP.status("success")
                }
                else{
                    console.log("usere present")
                    error.email = "email is not valid "
                   resP.status(400).send(error)
                }
            })
        }
    })
})

export default router

it first check if data in field is valid or not and then check if data base have same username or not
it is success when field are correct/incorrect
but when i verify database (due to asynchronous behaviour ) it do not wait. and goes to server.js and send 200 status always
i check network in chrome and their it show pending status of users.js
so how to solve this problem
so that after checking in mongodb i can send data only
index.js
import express from 'express';
import webpack from 'webpack';
import path from 'path';
import config from '../webpack.config.dev';
import open from 'open';
import bodyparser from 'body-parser'

import users from './routes/users'
/* eslint-disable no-console */

const port = 3000;
const app = express();
const compiler = webpack(config);

app.use(bodyparser.json())

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

app.use('/api/users',users)

app.get('*', function(req, res) {
  console.log("i am sending file")
  res.sendFile(path.join( __dirname, '../src/index.html'));
});

app.listen(port, function(err) {
  if (err) {
    console.log(err);
  } else {
    open(`http://localhost:${port}`);
  }
});

A: Try maybe improving the flow of your code using Promises and the async keyword (you issue is tough to see due to the callback nature of your code).
Let me know if this works
import express from 'express'
import Validator from 'validator'
import isEmpty from 'lodash/isEmpty'
import isEmail from 'validator/lib/isEmail';
import {MongoClient} from 'mongodb'

let router = express.Router()

function validatInput(data){
    var error = {}

    if(data.username === ""){
        error.email = "this field is req"
    }

    if(!isEmail(data.username)){
        error.email = "email is not valid "
    }

    if(data.password === ""){
        error.password = "this field is req"
    }

    return {
        error: error,
        isValid: isEmpty(error)
    }
}

router.post('/',async function (reqs,resP) {
    var url ="mongodb://localhost:27017/loginUsers"

    const { error, isValid } = validatInput(reqs.body)
    error.email = err
    console.log(error.email +"body")

    if(!isValid ){
        console.log("not valid")
        resP.status(400).send(error)
    }else{
        try{
            const db = await MongoClient.connect(url);
            const collection = db.collection('UsersList')
            const student = reqs.body
            console.log(" email "+ reqs.body.username)

            const dbUser = await collection.find({"username":reqs.body.username});

            if(!dbUser){
                console.log("User Not Found" )
                await collection.insert([student]);
                resP.status("success")
            }else{
                console.log("usere present")
                error.email = "email is not valid "
                resP.status(400).send(error)
            }
        }catch(e){
            console.log("database connection error")
            resP.status(500).send(error)
        }
    }
})


text:
Q: Computation Speed of Functions I have a quick question about optimizing the speed of my code.
Is it faster to return a double in a function or to have a pointer to your double as one of your arguments?
Returning double
double multiply(double x,double y) {
    return x * y;
}

Pointer argument
void multiply(double x,double y,double *xy) {
    *xy = x * y;
}

A: The sort of decision you're talking about here is often called a microoptimization - you're optimizing the code by making a tiny change rather than rethinking the overall strategy of the program. Typically, "microoptimization" has the connotation of "rewriting something in a less obvious way with the intent of squeezing out a little bit more performance." The language's explicit way of communicating data out of a function is through return values and programmers are used to seeing that for primitive types, so if you're going to go "off script" and use an outparameter like this, there should be a good reason to do so.
Are you absolutely certain that this code is executed so frequently that it's worth considering a rewrite that makes it harder to read in the interest of efficiency? A good optimizing compiler is likely to inline this function call anyway, so chances are there's not much of a cost at all. To make sure it's worth actually rewriting the code, you should start off by running a profiler and getting hard evidence that this particular code really is a bottleneck.
Once you've gathered evidence that this actually is slowing your program down, take a step and ask - why are you doing so many multiplications? Rather than doing a microoptimization, you might ask whether there's a different algorithm you could use that requires fewer multiplications. Changes like those are more likely to lead to performance increases.
Finally, if you're sure this is the bottleneck, and you're sure that there is no way to get rid of the multiplications, then you should ask whether this change would do anything. And for that, the only real way to find out would be to make the change and measure the difference. This change is so minor that most good compilers would be smart enough to realize what you're doing and optimize accordingly. As a result, I'd be astonished if you actually saw a performance increase here.
To summarize:

*

*Readability is so much more valuable than efficiency that, as a starting point, it's worth using the "right" language feature for the job. Just use a return statement initially.

*If you have hard, concrete evidence that the function you have is a bottleneck, see whether you actually need to call the function that many times by looking for bigger-picture ways of optimizing the code.

*If you absolutely need to call the function that many times, then make the change and see if it works - but don't expect that it's actually going to make a difference because the change is minor and optimizing compilers are smart.


text:
Q: Node C++ Addon - How do I access a Typed Array (Float32Array) when it's been passed as an argument? I'd like to make use of the V8 Float32Array data structure. How can I initialise it?
I'd also be interested in direct memory access to the data. How could that be done?

A: Updated
The best way now is to use the helper Nan::TypedArrayContents.
assert(args[i]->IsFloat32Array());
Local<Float32Array> myarr = args[i].As<Float32Array>();
Nan::TypedArrayContents<float> dest(myarr);
// Now use dest, e.g. (*dest)[0]

There's a good example of this in node-canvas.

Original Answer, which shows why the helper is useful
The v8 API is changing rapidly right now so this depends on your version of node/io.js. To access the data from the array provided as an argument, this should work for node 0.12 through io.js <3.0:
assert(args[i]->IsFloat32Array()); // These type-check methods are available.
Local<Float32Array> myarr = args[i].As<Float32Array>();
void* dataPtr = myarr->GetIndexedPropertiesExternalArrayData();

In io.js >=3.0 (v8 4.3) you should instead use ArrayBuffer::GetContents. (I haven't used this yet and will update this when 3.0 is released.) Docs are here.
In node 0.10, TypedArrays were home-brewed. This was one way of doing it:
Local<Object> buffer = args[i]->Get(NanNew("buffer"))->ToObject();
void* dataPtr = buffer->GetPointerFromInternalField(0);

Constructing a typed array can be done with:
 Float32Array::New(ArrayBuffer::New(Isolate::GetCurrent(), size * 4), 0, size);


text:
Q: Filtering columns in python Hello everyone i've a code who gives me the output of the command "show vlan brief" on a cisco switch.
from netmiko import ConnectHandler
import pandas as pd

file1 =  open ("./iptest.txt", "r")
lines = file1.readlines()
for line in lines:
    NetworkDevice = {"host": f"{line}",
             "username": "username",
             "password": "mdp",
             "device_type": "cisco_ios",

   }
    Connect = ConnectHandler(**NetworkDevice)

    Connect.enable()
    command = "sh vl br"
    fin = print(Connect.send_command(command))
    #dataframe = pd.DataFrame(list(fin))
    #rslt_df = dataframe.loc[dataframe['Ports'] != ""]

    #print('\nResult dataframe :\n', rslt_df)

I've the output below and i'd like to get the same but with hiding "Ports" columns when it's empty.
Is that possible ?
I tried with pandas but too hard for me atm, i'm a noob in python
Thanks for answer ! :)
VLAN Name                             Status    Ports
---- -------------------------------- --------- ------------------
1    default                          active    Gi0/3, Gi0/4, Gi0/5
2    Test1                            active
4    Test2                            active
5    Test3                            active
6    Test4                            active
7    Test5                            active
8    Test6                            active    Gi0/1

UPDATE :
First, thanks for your answer it's so sweet from you and that's exactly the output I wanted :)
So, I tried with this code :
df = pd.read_csv(StringIO(fin), sep="\s{2,}", engine='python', skiprows=2, header=None)
df.columns = re.split('\s+', fin.split('\n', 1)[0]) # getting headers
df.set_index('VLAN', inplace=True) # if it's more convenient to use VLAN as index (optional)
print(df[~df['Ports'].isna()])

But it returns me a pandas error that i corrected with error_bad_lines=False
df = pd.read_csv(StringIO(fin), sep="\s{2,}", engine='python', skiprows=2, header=None, error_bad_lines=False)

I get an other error : KeyError: "None of ['VLAN'] are in the columns"
So, like u said it's optionnal and I decided to comment the line to do my tests
At the end I've the error KeyError: 'Ports'
After all the morning on this issue I can't find how to declare it proprely in the code
The code I currently have is :
df = pd.read_csv(StringIO(fin), sep="\s{2,}", engine='python', skiprows=2, header=None, error_bad_lines=False)
df.columns = re.split('\s+', fin.split('\n', 1)[0]) # getting headers
#df.set_index('VLAN', inplace=True) # if it's more convenient to use VLAN as index (optional)
print(df[~df['Ports'].isna()])

And the output of this is :
Traceback (most recent call last):
  File "d:\PROGRAMMES\PROJET_VLAN\vlans.py", line 26, in <module>
    print(df[~df['Ports'].isna()])
  File "C:\Users\lucas\AppData\Local\Programs\Python\Python39-32\lib\site-packages\pandas\core\frame.py", line 3505, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Users\lucas\AppData\Local\Programs\Python\Python39-32\lib\site-packages\pandas\core\indexes\base.py", line 3623, in get_loc
    raise KeyError(key) from err
KeyError: 'Ports'

I thank you if you could help me a bit :)
UPDATE 2 :
This is the final code causing the error ValueError: Length mismatch: Expected axis has 3 elements, new values have 4 elements
import re
from netmiko import ConnectHandler
import pandas as pd
from io import StringIO

switches=[]

file1 =  open ("./iptest.txt", "r")
lines = file1.readlines()
for line in lines:
    NetworkDevice = {"host": f"{line}",
                 "username": "admin",
                 "password": "mdp",
                 "device_type": "cisco_ios",

    }
    Connect = ConnectHandler(**NetworkDevice)

    Connect.enable()
    command = "sh vl br"
    fin = Connect.send_command(command).strip('\n')
    print(fin)

    df = pd.read_csv(StringIO(fin), sep="\s{2,}", engine='python', skiprows=2, header=None, error_bad_lines=False)
    df.columns = re.split('\s+', fin.split('\n', 1)[0])
    final = df[~df['Ports'].isna()]
    final1 = f"\nSWICTH IP : {line} \n" + final.to_string()
    switches.append(final1)

with open(r".\output.txt","w") as filout:
            for j in switches:
                filout.write(f"{j}\n")

Working on some switches, and error on some others (which are the same)
Full error message :
df = pd.read_csv(StringIO(fin), sep="\s{2,}", engine='python', skiprows=2, header=None, error_bad_lines=False)
Skipping line 11: Expected 3 fields in line 11, saw 4. Error could possibly be due to quotes being ignored when a multi-char delimiter is used.
Skipping line 72: Expected 3 fields in line 72, saw 4. Error could possibly be due to quotes being ignored when a multi-char delimiter is used.
Skipping line 76: Expected 3 fields in line 76, saw 4. Error could possibly be due to quotes being ignored when a multi-char delimiter is used.
Traceback (most recent call last):
  File "d:\PROGRAMMES\PROJET_VLAN\vlans copy.py", line 26, in <module>
    df.columns = re.split('\s+', fin.split('\n', 1)[0])
  File "C:\Users\lucas\AppData\Local\Programs\Python\Python39-32\lib\site-packages\pandas\core\generic.py", line 5588, in __setattr__
    return object.__setattr__(self, name, value)
  File "pandas\_libs\properties.pyx", line 70, in pandas._libs.properties.AxisProperty.__set__
  File "C:\Users\lucas\AppData\Local\Programs\Python\Python39-32\lib\site-packages\pandas\core\generic.py", line 769, in _set_axis
    self._mgr.set_axis(axis, labels)
  File "C:\Users\lucas\AppData\Local\Programs\Python\Python39-32\lib\site-packages\pandas\core\internals\managers.py", line 214, in set_axis
    self._validate_set_axis(axis, new_labels)
  File "C:\Users\lucas\AppData\Local\Programs\Python\Python39-32\lib\site-packages\pandas\core\internals\base.py", line 69, in _validate_set_axis
    raise ValueError(
ValueError: Length mismatch: Expected axis has 3 elements, new values have 4 elements

A: First the print function returns None so you should do:
fin = Connect.send_command(command).strip()
print(fin)

Edit: you might have leading empty lines in fin, so remove them with strip
Then you'll have to parse fin as a csv with pandas. It's a bit tricky cause the separators are two or more whitespaces, except for the headers:
import re
from io import StringIO

header = re.split('\s+', fin.split('\n', 1)[0]) # getting headers

df = pd.read_csv(StringIO(fin), sep="\s{2,}", engine='python', skiprows=2, names=header)

df.set_index('VLAN', inplace=True) # if it's more convenient to use VLAN as index (optional)
print(df[~df['Ports'].isna()])

Edit 2: getting headers before parsing csv, otherwise pandas might expect wrong number of columns.
Output:
         Name  Status                Ports
VLAN
1     default  active  Gi0/3, Gi0/4, Gi0/5
8       Test6  active                Gi0/1