text:
Q: Why does this function return the largest integer less than or equal to √n? I've been asked this question by my teacher. The function I'm talking about is the following:
SqrtFloor[n_Integer] :=
 Module[{a = n, b = Quotient[n + 1, 2]},
  While[b < a, a = b; b = Quotient[a^2 + n, 2 a]]; a]

I understand the code, but I don't know what is the mathematical concept behind it. Why does it return the largest integer less than or equal to √n?

A: This is a discretized version of Newton's Method where f(x) = x^2 - a, which has a zero at x = Sqrt[a]. Wikipedia With initial guess x = n, (x^2 + n)/(2 x) decreases at each step until x <= Sqrt(n).


text:
Q: How can I generate a Warning when using certain RTL/VCL or Delphi language elements I would like to mark certain elements, functions and classes as deprecated, so that the compiler generates a warning.
My intention is to modernize certain aspects of the source. Especially when focusing on more platform independence.
E.g. By marking the WinAPI and special Windows classes (such as TRegistry) as "deprecated" they could be replaced or at least moved and made platform independent.
As for the language elements, I would especially like to deprecate the with, label and goto keywords.
I already tried to generate a warning for functions and classes by inserting a {$IF DECLARED(...)}{$MESSAGE WARN...} into the bottom of the unit file, but this will evidently fail with the core units...
Does somebody know a Tool that does this?

A: There is no way you can deprecate keywords like with, goto, etc. If you want to modernize your code, simply look for these words as whole word and if you find them, change your code.
The same is true for identifiers in the Win.* core units. You could modify the RTL and recompile it, or you could download the JEDI API headers from here and designate all the routines and types platform, or just the units. I would recommend against recompiling the RTL. What you do with, say, units from JEDI, is up to you.
Except for the Win.* units, most of the RTL is actually platform independent, and even withand goto will work in 64 bit or on the Mac too.
My advice: find a better way to modernize your code. Don't try to deprecate what the RTL offers.

A: You cannot put a warning on core language features like with, label and goto no matter how much you hate them.
The fact that these are reserved words should have tipped you off on this.
These features are not in any unit, they are a feature of the Pascal language (and have been since its beginning) and build deep into the compiler.
You can't even redefine them because they are reserved words.

A: As an alternative to warnings, you could go with a simple app that parses all source code and reports the use of these constructs.
With a little investigation, I'm sure you can find some static code analysis tools that will even go a bit further and alert you to certain code-smells. (E.g. incorrect use of try..finally, swallowed exceptions).
Plug the app or the static code analyser in as a step in your build process, and you have the equivalent to compile-time warnings.

A: First, I do NOT advise you go the route you want to go in, for all the reasons others have stated.  BUT, if you feel you must, then here is a method that will do some of what you are asking for.
You can turn on warnings for platform specific code in your project.  As for other things that you consider deprecated but are not actually deprecated by Delphi, I have a solution that will take some work.
Create a unit that redeclares the classes that you want deprecated, like the following:
unit PleaseDeprecateThisStuff;

uses
  Registry;

interface

type
  TRegistry = class (Registry.TRegistry)
  end deprecated;

implementation

end;

EDIT2: I feel I should explain the source further.  For each class, like the TRegistry example, you'll need to include a same-name version of it in this unit and make it identical to the version in another unit.  Make sure you include that unit in the uses clause of this unit (duh) AND prefix the class reference in the type section, like the example of Registry.TRegistry.
Include everything you want deprecated and then include this unit at the end of the interface uses clause of EVERY unit you want to "protect".
EDIT: This trick will only help with classes, variables, and constants... not reserved words.
Again, let me state this is a horrible idea.  :p

redpajama_set_name: RedPajamaStackExchange


text:
Q: Input Password - HTML5, Intel xdk, Cordova Estou tendo um problema com o input type="password".
No Android o input password fica sempre iniciando com a letra maiúscula. Como faço para quando clicar no input a primeira letra já aparecer minúscula?
No IOS ele funciona corretamente. Segue o código que estou utilizando:
<input type="password" name="senha" value="">

A: Junior, tente usar o autocapitalize como off
<input type="password" name="senha" value="" autocapitalize="off">


text:
Q: Validation data in Laravel fails even it is true I need to validate data, but when I use Validation Form, it doesn't pass even if the test is true, my code below fails when I try to validate in the for loop, for the every single product. So I need to check if the user will put all the products before save data
public function store(Request $request)
   {
           $request->validate([
           'fature_number' => 'required',
           'date' => 'required',
           'product_item'=>'required'
           ]);
           if($request->product_item !=0){
               for ($i = 1; $i <= $request->product_item; $i++)
               {
                   $this->validate($request,['product_id'=>'required']); // here is the fail

                    ...

                   }
               }
          ...
   }


text:
Q: Why does change configuration on Azure Cloud Service take so long? I have an Azure Cloud Service. One of the Web Role contains a configuration which I need to change its value every few days.
Each time when I change the value, Azure takes about 10~15 min to finish the procedure. Which make me quite confusing, since what I've changed is just a configuration value.
So I'm wondering what does Azure do in the background that make it so slow?

A: See the following documentation: Use the RoleEnvironment.Changing Event
In summary, if your role does not handle the RoleEnvironment.Changing event, the instance is taken offline, the updated configuration value is applied, and then the instance is brought back online
Therefore, you may want to handle this event, and respond to the configuration change so that the instance isn't restarted.

A: Note: this should be a comment on the accepted answer but I'm apparently not allowed to post them yet ...
While this seems to work for single instance deployments, I find that if I deploy 2 or more instances, Azure still restarts them one by one.
In the portal they change from "unknown" to "busy" before eventually coming online so I assume that's what it's doing. And of course this takes way longer than it should.
There's nothing in the documentation that talks about this behaviour however, which I find odd.

A: Your instances are being restarted. There is a dated but good and relevant writeup by Steven Nagy here:
http://www.codeproject.com/Articles/63977/Windows-Azure-Development-Deep-Dive-Working-With-C


text:
Q: Angular 8 mat video player time is not working? I want to achieve that pause video on particular time, also in mat video player mentioned - time    number (two-way bindable)   Get or set the timestamp of the video   0.
HTML template file:
<mat-video #video [src]="src" title="My Tutorial Title" [(time)]="ctime"  [autoplay]="true" [preload]="true" [download]="false" color="accent" spinner="spin">
</mat-video>

TypeScript code:
ctime = 30;
src="assets/bloodborne pathogens.mp4";


text:
Q: Publish r-markdown to rpubs directly I use R version:
              _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          3
minor          5.1
year           2018
month          07
day            02
svn rev        74947
language       R
version.string R version 3.5.1 (2018-07-02)
nickname       Feather Spray

and use R.markdown, as I want to publish a tutorial in Rpubs. When I was using a previous R version, I was able to do so, by going upper right in the script section and hitting on "Publish Document" (RPubs would appear as an option). Now it requires that I can connect to an R Studio server, which I don't wish to do.
How can I connect directly to Rpubs and publish there directly?


text:
Q: MDX- Divide Each row by a value based on parent I am in a situation where I need to calculate Percentage for every fiscal year depending on distinct count of the rows.
I have achieved the distinct count (fairly simple task) for each year city-wise and reached till these 2 listings in cube.
The first listing is state wide distinct count for given year.
Second listing is city wise distinct count for given year with percentage based on state-wide count for that year for that city.
My problem is that I need to prepare a calculated member for the percentage column for each given year.
For eg, In year 2009, City 1 has distinct count of 2697 and percentage raise of 32.94%. (Formula used= 2697/8187 ).
I tried with  ([Measures].[Distinct Count])/(SUM(ROOT(),[Measures].[Distinct Count])) but no luck.
Any help is highly appreciated.
Thanks in advance.
PS: City wide sum of year 2009 can never be equal to statewide distinct count of that year. This is because we are calculating the distinct count for city and state both.

A: You need to create a Region Hierarchy for this, like State -> City. The create a calculation like below. Then in the browser put your Hierarchy on the left and the sales and calculated percentage in values.
([Dim].[Region].CurrentMember, [Measures].[Salesamt]) /
iif(
    ([Dim].[Region].CurrentMember.Parent, [Measures].[Salesamt]) = 0,
    ([Dim].[Region].CurrentMember, [Measures].[Salesamt]),
    ([Dim].[Region].CurrentMember.Parent, [Measures].[Salesamt])
)


text:
Q: How to set Input Mask and QValidator to a QLineEdit at a time in Qt? I want a line edit which accepts an ip address. If I give input mask as:
ui->lineEdit->setInputMask("000.000.000.000");

It is accepting values greater than 255. If I give a validator then we have to give a dot(.) after every three digits. What would the best way to handle it?

A: The easier method is try inputmask option
ui->lineEdit_IP->setInputMask( "000.000.000.000" );

and in your validation code use the following simple condition
QHostAddress myIP;
   if( myIP.setAddress( ui->lineEdit_IP->text()) )
   qDebug()<<"Valid IP Address";
   else
   qDebug()<<"Invalid IP address";

A: Hi I had almost the same problem. Solutions with inputmask or regExp were unsatisfactory. I decided to make my own bicycle.
Header:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QLineEdit>
#include <QFrame>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

//=============================================================================
class CustomIpEditor : public QFrame
{
    Q_OBJECT
public:
    explicit CustomIpEditor(QWidget *parent = 0);
    virtual ~CustomIpEditor() {}
};

//=============================================================================
class CustomLineEdit : public QLineEdit
{
    Q_OBJECT
public:
    explicit CustomLineEdit(const QString & contents = "", QWidget *parent = 0);
    virtual ~CustomLineEdit() {}

signals:
    void jumpForward();
    void jumpBackward();

public slots:
    void jumpIn();

protected:
    virtual void focusInEvent(QFocusEvent *event);
    virtual void keyPressEvent(QKeyEvent * event);
    virtual void mouseReleaseEvent(QMouseEvent *event);

private:
    bool selectOnMouseRelease;
};

#endif // MAINWINDOW_H

Source:
#include <QVBoxLayout>
#include <QKeyEvent>

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    centralWidget()->setLayout(new QVBoxLayout);

    CustomIpEditor *myed = new CustomIpEditor;
    centralWidget()->layout()->addWidget(myed);

}

MainWindow::~MainWindow()
{
    delete ui;
}

//=============================================================================
CustomLineEdit::CustomLineEdit(const QString & contents, QWidget *parent) :
    QLineEdit(contents, parent), selectOnMouseRelease(false)
{
    QIntValidator *valid = new QIntValidator(0, 255, this);
    setValidator(valid);
}

void CustomLineEdit::jumpIn()
{
    setFocus();

    selectOnMouseRelease = false;
    selectAll();
}

void CustomLineEdit::focusInEvent(QFocusEvent *event)
{
    QLineEdit::focusInEvent(event);
    selectOnMouseRelease = true;
}

void CustomLineEdit::keyPressEvent(QKeyEvent * event)
{
    int key = event->key();
    int cursorPos = cursorPosition();

    // Jump forward by Space
    if (key == Qt::Key_Space) {
        emit jumpForward();
        event->accept();
        return;
    }

    // Jump Backward only from 0 cursor position
    if (cursorPos == 0) {
        if ((key == Qt::Key_Left) || (key == Qt::Key_Backspace)) {
            emit jumpBackward();
            event->accept();
            return;
        }
    }

    // Jump forward from last postion by right arrow
    if (cursorPos == text().count()) {
        if (key == Qt::Key_Right) {
            emit jumpForward();
            event->accept();
            return;
        }
    }

    // After key is placed cursor has new position
    QLineEdit::keyPressEvent(event);
    int freshCurPos = cursorPosition();

    if ((freshCurPos == 3) && (key != Qt::Key_Right))
        emit jumpForward();
}

void CustomLineEdit::mouseReleaseEvent(QMouseEvent *event)
{
    if(!selectOnMouseRelease)
        return;

    selectOnMouseRelease = false;
    selectAll();

    QLineEdit::mouseReleaseEvent(event);
}

//=============================================================================
void makeCommonStyle(QLineEdit* line) {
    line->setContentsMargins(0, 0, 0, 0);
    line->setAlignment(Qt::AlignCenter);
    line->setStyleSheet("QLineEdit { border: 0px none; }");
    line->setFrame(false);
    line->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
}

QLineEdit* makeIpSpliter() {
    QLineEdit *spliter = new QLineEdit(".");
    makeCommonStyle(spliter);

    spliter->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    spliter->setMaximumWidth(10);
    spliter->setReadOnly(true);
    spliter->setFocusPolicy(Qt::NoFocus);
    return spliter;
}

CustomIpEditor::CustomIpEditor(QWidget *parent) :
    QFrame(parent)
{
    setContentsMargins(0, 0, 0, 0);
    setStyleSheet("QFrame { background-color: white;  border: 1px solid white; border-radius: 15px; }");

    QList <CustomLineEdit *>  lines;
    QList <CustomLineEdit *>::iterator linesIterator;

    lines.append(new CustomLineEdit);
    lines.append(new CustomLineEdit);
    lines.append(new CustomLineEdit);
    lines.append(new CustomLineEdit);

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->setSpacing(0);
    setLayout(mainLayout);

    for (linesIterator = lines.begin(); linesIterator != lines.end(); ++linesIterator) {
        makeCommonStyle(*linesIterator);
        mainLayout->addWidget(*linesIterator);

        if (*linesIterator != lines.last()) {
            connect(*linesIterator, &CustomLineEdit::jumpForward,
                    *(linesIterator+1), &CustomLineEdit::jumpIn);
            mainLayout->addWidget(makeIpSpliter());
        }
        if (*linesIterator != lines.first()) {
            connect(*linesIterator, &CustomLineEdit::jumpBackward,
                    *(linesIterator-1), &CustomLineEdit::jumpIn);
        }
    }

}

A:
It is accepting value greater than 255.

Absolutely, because '0' means this:
ASCII digit permitted but not required.

As you can see, this is not your cup of tea. There are at least the following ways to circumvent it:

*

*Write a custom validator

*Use regex

*Split the input into four entries and validate each entry on its own while still having visual delimiters between the entries.
The regex solution would be probably the quick, but also ugliest IMHO:
QString ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])";
// You may want to use QRegularExpression for new code with Qt 5 (not mandatory).
QRegExp ipRegex ("^" + ipRange
                 + "\\." + ipRange
                 + "\\." + ipRange
                 + "\\." + ipRange + "$");
QRegExpValidator *ipValidator = new QRegExpValidator(ipRegex, this);
lineEdit->setValidator(ipValidator);

Disclaimer: this will only validate IP4 addresses properly, so it will not work for IP6 should you need that in the future.

A: For those who wonder about the following hint in the QT doku:

To get range control (e.g., for an IP address) use masks together with validators.

In this case the validator needs to take care of blanks. My solution, adapted from lpapp's answer and this Qt forum post, therefore reads:
QString ipRange = "(([ 0]+)|([ 0]*[0-9] *)|([0-9][0-9] )|([ 0][0-9][0-9])|(1[0-9][0-9])|([2][0-4][0-9])|(25[0-5]))";
// You may want to use QRegularExpression for new code with Qt 5 (not mandatory).
QRegExp ipRegex ("^" + ipRange
                 + "\\." + ipRange
                 + "\\." + ipRange
                 + "\\." + ipRange + "$");
QRegExpValidator *ipValidator = new QRegExpValidator(ipRegex, this);
lineEdit->setValidator(ipValidator);
lineEdit->setInputMask("000.000.000.000");
// Avoid having to move cursor before typing
linEdit->setCursorPosition(0);

I am a beginner at using regular expressions, so feel free to recommend improvements.

A: In accordance to Arun Kumar K S's answer:
If myIP.setAddress() was successfull, you can write the ip back to the line edit as a formatted string:
ui->lineEdit->setText(myIP->toString());

Consequently, you don't neccessarily need to set a mask (nor a validator or regex).
Note
setAddress() writes/overwrites your myIP also if it fails to read the ip. Thus, calling toString() in this case results in an empty string.


text:
Q: KQL query to filter unique ID with highest value If my KQL query is returning this

ID
Value

123
1000

123
50

456
100

456
1400

How can I get it to return only one result per ID, of which has the highest value, e.g.

ID
Value

123
1000

456
1400

A: summarize
datatable (ID:int, Value:int)
[
     123    ,1000
    ,123    ,50
    ,456    ,100
    ,456    ,1400
]
| summarize max(Value) by ID

ID
max_Value

123
1000

456
1400

Fiddle


text:
Q: Insert dots at the end of a phrase I need some help with a table of contents.
I'm trying to automatically add dots (take a look at red rectangles) at the end of a phrase with the number of the page, as shown in this example image I have found in the internet:

A: To add the dots to your table of contents, select the table, choose the Text inspector, then select the leader as dots.

If you don't have a table of contents, place the cursor where you wish to insert the table of contents, then Insert → Table of Contents and choose the scope.

A: I just found what I was looking for:
https://support.apple.com/kb/PH23640?locale=en_US
Thank you all.


text:
Q: SQL how to split Quantity into Multiple Rows based on Quantity on Target source I have two table where i want to join and show quantity with details.
table are join with ITM,DIA , and total Qty is equal in both table on ITM/DIA combination
I want to split table2 quantity on table1 and populate table2 data along with table1 data.
I have below data for your reference, "table1" and "table2". and you can see my expected result in table "tableResult"
CREATE TABLE table1
    (`ITM` varchar(5), `DIA` varchar(4), `LOC` varchar(4), `ID` varchar(3), `QTY` int)
;

INSERT INTO table1
    (`ITM`, `DIA`, `LOC`, `ID`, `QTY`)
VALUES
    ('Item1', 'DIA1', 'LOC1', 'ID1', 3),
    ('Item1', 'DIA1', 'LOC2', 'ID2', 4),
    ('Item1', 'DIA1', 'LOC2', 'ID2', 6),
    ('Item1', 'DIA2', 'LOC2', 'ID2', 6),
    ('Item1', 'DIA2', 'LOC3', 'ID3', 18),
    ('Item1', 'DIA2', 'LOC4', 'ID4', 90),
    ('Item1', 'DIA2', 'LOC4', 'ID5', 23),
    ('Item1', 'DIA3', 'LOC5', 'ID6', 50),
    ('Item1', 'DIA3', 'LOC6', 'ID7', 20),
    ('Item2', 'DIA1', 'LOC4', 'ID8', 44),
    ('Item2', 'DIA2', 'LOC5', 'ID8', 21),
    ('Item2', 'DIA3', 'LOC6', 'ID9', 20)
;

CREATE TABLE table2
    (`ITM` varchar(5), `DIA` varchar(4), `NTA` varchar(5), `QTY` int)
;

INSERT INTO table2
    (`ITM`, `DIA`, `NTA`, `QTY`)
VALUES
    ('Item1', 'DIA1', 'NTA1', 10),
    ('Item1', 'DIA1', 'NTA2', 3),
    ('Item1', 'DIA2', 'NTA3', 30),
    ('Item1', 'DIA2', 'NTA4', 7),
    ('Item1', 'DIA2', 'NTA5', 100),
    ('Item1', 'DIA3', 'NTA6', 70),
    ('Item2', 'DIA1', 'NTA7', 22),
    ('Item2', 'DIA1', 'NTA8', 20),
    ('Item2', 'DIA2', 'NTA9', 6),
    ('Item2', 'DIA2', 'NTA10', 15),
    ('Item2', 'DIA3', 'NTA11', 8),
    ('Item2', 'DIA3', 'NTA11', 12)
;

CREATE TABLE tableResult
    (`ITM` varchar(5), `DIA` varchar(4), `LOC` varchar(4), `ID` varchar(3), `QTY` int, `NTA` varchar(5), `NewQTY` int)
;

INSERT INTO tableResult
    (`ITM`, `DIA`, `LOC`, `ID`, `QTY`, `NTA`, `NewQTY`)
VALUES
    ('Item1', 'DIA1', 'LOC1', 'ID1', 3, 'NTA1', 3),
    ('Item1', 'DIA1', 'LOC2', 'ID2', 4, 'NTA1', 4),
    ('Item1', 'DIA1', 'LOC2', 'ID2', 6, 'NTA1', 3),
    ('Item1', 'DIA1', 'LOC2', 'ID2', 6, 'NTA2', 3),
    ('Item1', 'DIA2', 'LOC2', 'ID2', 6, 'NTA3', 6),
    ('Item1', 'DIA2', 'LOC3', 'ID3', 18, 'NTA3', 18),
    ('Item1', 'DIA2', 'LOC4', 'ID4', 90, 'NTA3', 6),
    ('Item1', 'DIA2', 'LOC4', 'ID4', 90, 'NTA4', 7),
    ('Item1', 'DIA2', 'LOC4', 'ID4', 90, 'NTA5', 77),
    ('Item1', 'DIA2', 'LOC4', 'ID5', 23, 'NTA5', 23),
    ('Item1', 'DIA3', 'LOC5', 'ID6', 50, 'NTA6', 50),
    ('Item1', 'DIA3', 'LOC6', 'ID7', 20, 'NTA6', 20),
    ('Item2', 'DIA1', 'LOC4', 'ID8', 44, 'NTA7', 22),
    ('Item2', 'DIA1', 'LOC4', 'ID8', 44, 'NTA8', 20),
    ('Item2', 'DIA2', 'LOC5', 'ID8', 21, 'NTA9', 6),
    ('Item2', 'DIA2', 'LOC5', 'ID8', 21, 'NTA10', 15),
    ('Item2', 'DIA3', 'LOC6', 'ID9', 20, 'NTA11', 8),
    ('Item2', 'DIA3', 'LOC6', 'ID9', 20, 'NTA11', 12)
;

Below is screenshot of data;

I can make it with a proc and follow cursor, but I want to is there any easy way with SQL 2014 and I know for a fact CTE recusive trick will help..
Could you please share your solution on this? appreciate lot on your valuable ideas..

A: You simply need to explode quantities in units both for table1 and table2 and then couple them side by side.
Pay attention to FN_NUMBERS(n), it is a function that returns only one column with numbers from 1 to n, you need it in you database, there are many ways to do it, just google for "tally tables" or look here.
I use the following:
CREATE FUNCTION FN_NUMBERS(
     @MAX INT
)
RETURNS @N TABLE (N INT NOT NULL PRIMARY KEY)
BEGIN
     WITH
       Pass0 as (select '1' as C union all select '1'),       --2 rows
       Pass1 as (select '1' as C from Pass0 as A, Pass0 as B),--4 rows
       Pass2 as (select '1' as C from Pass1 as A, Pass1 as B),--16 rows
       Pass3 as (select '1' as C from Pass2 as A, Pass2 as B),--256 rows
       Pass4 as (select TOP (@MAX) '1' as C from Pass3 as A, Pass3 as B)    --65536 rows
       ,Tally as (select TOP (@MAX) '1' as C from Pass4 as A, Pass2 as B, Pass1 as C)  --4194304 rows
       --,Tally as (select TOP (@MAX) '1' as C from Pass4 as A, Pass3 as B)               --16777216 rows
       --,Tally as (select TOP (@MAX) '1' as C from Pass4 as A, Pass4 as B)               --4294836225 rows
     INSERT INTO @N
     SELECT TOP (@MAX) ROW_NUMBER() OVER(ORDER BY C) AS N
     FROM Tally
     RETURN
END

Back to the sql..
;with
t1 as (
    select *, ROW_NUMBER() over (partition by itm,dia order by loc,id) rn
    from table1 t1
    join FN_NUMBERS(500) on n<=t1.qty
),
t2 as (
    select *, ROW_NUMBER() over (partition by itm,dia order by nta) rn
    from table2 t2
    join FN_NUMBERS(500) on n<=t2.qty
),
t3 as (
    select t1.itm, t1.dia, t1.loc, t1.id, t1.qty, t2.nta, count(t1.n) NewQTY
    from  t1
    join  t2 on t1.itm=t2.itm and t1.dia = t2.dia and t1.rn=t2.rn
    group by t1.itm, t1.dia, t1.loc, t1.id, t1.qty, t2.nta
)
select *
from t3
order by 1,2,3,4,5,6


text:
Q: ZSH And VSCode - Default Shells I've started setting up ZSH for VSCode. It worked for a small bit, but then it changed to Git Bash (my previous default shell). I tried changing the shell back to ZSH, but it didn't display in the list of opinions. Though, it does display WSL, which displays a completely different theme
My theme (in windows terminal, unbuntu, ect):

The theme that is in VSCode:

I've tried adding this to my settings.json:
"terminal.integrated.shell.windows": "/bin/zsh",

But it says: "The terminal process failed to launch: Path to shell executable "\bin\zsh" does not exist."
How can I fix this (change the default shell back to ZSH)?

A: open "~/.config/Code/User/settings.json"
add your default shell depending on you OS:
"terminal.integrated.defaultProfile.linux": "zsh"
"terminal.integrated.defaultProfile.osx": "zsh"
"terminal.integrated.defaultProfile.windows": "zsh"

A: Try which zsh to confirm the path of your zsh executable. You might be having path error.

Or Try the GUI way.

*

*Open Command Palette

Windows - Ctrl + Shift + P
Mac - ⌘ + Shift + P

*Search For Terminal: Select Default Shell and select it.

*See the list of available shells and select one. If you cannot see zsh here, then you might have some configuration issues with zsh.

It also likely that the zsh installation/configuration error caused your entry in settings.json file to be invalid. Once you have selected the shell, hit ctrl + ~ or ⌘ + J to open the terminal window and see the results. If you already opened a terminal then you would have to trash it or open another one.
You could also open your settings.json and see or add the following entry directly.
// Edit July 2021 - New Updated Snippet
"terminal.integrated.defaultProfile.osx": "zsh"

// Now deprecated
"terminal.integrated.shell.osx": "/bin/zsh"

A: Looks like it has changed slightly on Macs.
Mac - ⌘ + Shift + P
Type "Terminal: Select Default Profile", and select it.

Then you will see this:

Choose bash or whatever, and then you must close and restart VS Code.

A: Here's the solution:
terminal.integrated.shell.osx has been deprecated for terminal.integrated.defaultProfile.osx (shell to defaultProfile) but the new rule instead defaults to bash (at the time of this post)
What actually happens is this: (got it by using the GUI instead) - it's the path. terminal.integrated.defaultProfile.osx actually works, but the value has to be changed from /bin/zsh to zsh.
So the setting should be "terminal.integrated.defaultProfile.osx": "zsh" instead of "terminal.integrated.defaultProfile.osx": "/bin/zsh".
Also note the language changed from Default shell to defaultProfile.


text:
Q: Is it possible to renew MCSD SharePoint 2013 certifications by just watching courses? Is it possible to renew MCSD SharePoint 2013 certifications by just watching courses ?
Few years ago, one was able to renew there certifications for MCSD for SharePoint 2013 by watching courses online, does anyone knows if it still works ?
thanks

A: As far as I know, that was never possible. Microsoft technical certifications require either upgrade exams or new exams. (There may have been other options for end-user "certifications".)
Several online courses offered extra cost certificates (like edX) but they were only proof of attendance, not certification.


text:
Q: ldd exits with error on armhf target I have been facing the following issue on an armhf ubuntu target (arm9, omap4). I am trying to execute the maliit keyboard using Ubuntu 12.04 arm-linux-gnueabihf toolchain. I successfully cross compiled Qt5 and the different libs used by maliit-framework but when executing maliit-server or maliit-exampleapp-plainqt it exits right after the dynamic libraries have been opened. Here is the end of strace output :
open("/mnt/internal/library/icu_4.8.1.1/lib/libicudata.so.48", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0(\0\1\0\0\0T\2\0\0004\0\0\0"..., 512) = 512
lseek(3, 18280604, SEEK_SET)            = 18280604
read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 480) = 480
lseek(3, 18280460, SEEK_SET)            = 18280460
read(3, "A \0\0\0aeabi\0\1\26\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4,"..., 33) = 33
exit_group(1)                           = ?
+++ exited with 1 +++

I first thought it was related to an arm floating point incompatibility between the different libraries but a readelf -h on the libraries gives me this (except for some of them that have       Tag_ABI_optimization_goals: Aggressive Speed) :
Attribute Section: aeabi
File Attributes
  Tag_CPU_name: "7-A"
  Tag_CPU_arch: v7
  Tag_CPU_arch_profile: Application
  Tag_ARM_ISA_use: Yes
  Tag_THUMB_ISA_use: Thumb-2
  Tag_FP_arch: VFPv3-D16
  Tag_ABI_PCS_wchar_t: 4
  Tag_ABI_FP_denormal: Needed
  Tag_ABI_FP_exceptions: Needed
  Tag_ABI_FP_number_model: IEEE 754
  Tag_ABI_align_needed: 8-byte
  Tag_ABI_align_preserved: 8-byte, except leaf SP
  Tag_ABI_enum_size: int
  Tag_ABI_HardFP_use: SP and DP
  Tag_ABI_VFP_args: VFP registers
  Tag_CPU_unaligned_access: v6
  Tag_DIV_use: Not allowed

I can see through strace that all the libraries have been found. Grepping "aeabi" on strace gives me the following output :
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\3\f"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A4\0\0\0aeabi\0\1*\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 53) = 53
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A6\0\0\0aeabi\0\1,\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 55) = 55
read(3, "A \0\0\0aeabi\0\1\26\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4,"..., 33) = 33

ldd also exits without displaying all the different libraries needed and returns 1.
Does anyone know what is here happening ?


text:
Q: MATLAB - S&P daily return matrix: Substitution of the zero matrix inside the for - loop Good evening,
I have to create a daily return matrix based on 174 daily prices of the S&P index.
The table from which I fetch such prices is called "prices", and the objective matrix I have to plug the values in is called "stockreturns".
I have tried setting up a nested for - loop after pre-allocating a 173*500 array with zeroes (otherwise the process takes 1+ hours), but the output I get is a zero matrix.
Could anyone help me out? This is the code I am using:
    stockreturns = zeros(173,500)
for k = 1:500;
    for h = 1:173;
        stockreturns(h,k) = ((prices{h+1,k}/prices{(h),k})-1)
    end
end

A: Assuming prices is a 174 x 500 table, you can just use MATLAB's in-built element-wise operations.
prices = table2array(prices);
stockreturns = prices(2:end, :) ./ prices(1:end-1, :) - 1;


text:
Q: Custom command for drawing a lens in tikzpicture I wanted to draw a convex lens in tikzpicture. I'm fairly new to writing these commands, so I drafted the following.
% Convex lens
% \convex[R0,R1,w,h] at (x,y);
\def\convex[#1,#2,#3,#4] at (#5,#6){
    % circle-circle intersection maths
    % with adjustment for clipping at specified height
    \def\R{#1};\def\r{#2};\def\d{(\R+\r-#3)};
    \def\x{(((\d*\d)-(\r*\r)+(\R*\R))/(2*\d))};\def\c{(\d-\x)};
    \def\y{sqrt((\R*\R)-(\x*\x))};\def\yh{min(\y,#4)};
    \def\g{asin(\yh/\R)};\def\p{asin(\yh/\r)};

    % sphere0 curves
    \draw ({#5-\x+\R},#6) arc (0:\g:\R);
    \draw ({#5-\x+\R},#6) arc (0:-\g:\R);

    % sphere1 curves
    \draw ({#5+\c-\r},#6) arc (180:180+\p:\r);
    \draw ({#5+\c-\r},#6) arc (180:180-\p:\r);

    % connecting lines (if clipped)
    \def\xg{\R*cos(\g)};\def\xp{\r*cos(\p)};
    \draw ({#5+\xg-\x},{\yh}) -- ({#5-\xp+\c},{\yh});
    \draw ({#5+\xg-\x},{-\yh}) -- ({#5-\xp+\c},{-\yh});
    }

This works, but I'd like to improve it a bit. Specific questions follow.

*

*Does it make sense to pass R0, R1, w, and h in this way? Is there a more standard way to pass arguments that is more in line with tikz/pgf philosophy?

*How can I pass optional arguments such as thick to my \draw commands? It seems like \def does not allow optional arguments. Is there another command I can use to define my lens?

*Is there a better way to do this math in tikz/pgf (i.e. can it be done in fewer commands/with less braces and parentheses)?


text:
Q: Setting cache file path in PayPal API SDK The whole process and the payment is working fine. The only thing that doesn't work is the cache after the completed money transfer:
Warning: mkdir(): Permission denied in PayPal\Cache\AuthorizationCache::push()
(Line 61 von /paypal/rest-api-sdk-php/lib/PayPal/Cache/AuthorizationCache.php).

That is correct because PayPal should not write into the directory it suggests in AuthorizationCache.php:
abstract class AuthorizationCache
{
    public static $CACHE_PATH = '/../../../var/auth.cache';

Now I'm setting my apiContext - which is working fine as well (the log file will be written at the correct place where PayPal would be allowed to write to) but the cache file not. Currently I'm doing:
$apiContext->setConfig(
  array(
    'mode' => $config['paypal']['mode'],
    'log.LogEnabled' => TRUE,
    'log.FileName' => 'sites/rest-api-sdk-php/var/PayPal.log',
    'log.LogLevel' => 'FINE',
    'validation.level' => 'log',
    'cache.enabled' => TRUE,
    'cache.FileName' => 'sites/rest-api-sdk-php/var/auth.cache',
  )
);

But that doesn't seem to be working - how can I set the cach file path?

A: I was facing similar problem resolved by setting following configuration in config/paypal.php
Add this line

'cache.FileName'            => storage_path() . '/logs/auth.cache',

return [
    'client_id' => env('PAYPAL_CLIENT_ID',''),
    'secret'    => env('PAYPAL_SECRET',''),
    'settings'  => [
        'mode'                      => env('PAYPAL_MODE','sandbox'),
        'http.ConnectionTimeOut'    => 1000,
        'log.LogEnabled'            => true,
        'cache.enabled'             => true,
        'log.FileName'              => storage_path() . '/logs/paypal.log',
        'cache.FileName'            => storage_path() . '/logs/auth.cache',
        'log.LogLevel'              => 'FINE'
    ]
];

FYI i'm using laravel 5.8.18
I hope this helps.


text:
Q: finding $C^1$ path on an open and path connected set. Given an open and path connected set $U\subseteq \mathbb R^n$, is there a way to find a $C^1$ path between every $a,b\in U$?
If so, is there a general proof of existence of such path?

A: Given any two points in your domain, pick a continuous path between them. Because the closed interval $I$ is compact, you can cover this path with finitely many balls; use this to construct a piecewise linear path between the two points. (With enough care in this step and the previous you can ensure that the path is actually injective.) Now smooth the corners.

A: We can also use a tweaked version of the Weierstrass approximation theorem: Given $f$ continuous on $[a,b],$ there are polynomials $p_m \to f$ uniformly on $[a,b]$ such that $p_m(a) = f(a), p_m(b)=f(b)$ for all $m.$ (For the proof, see * below.)
Given this, suppose $\gamma:[0,1] \to U$ is a path from $x$ to $y$ in $U\subset \mathbb {R}^n.$ We can then choose $n$ polynomials that uniformly approximate the components of $\gamma,$ with agreement at the end points. Because the range of $\gamma $ is compact and these polynomial maps are as close to $\gamma $ desired, eventually they all map into $U$, and any one of these will be a polynomial path from $x$ to $y$ in $U.$
*Suppose first $f(a)=f(b)=0.$ Find polynomials $p_m \to f.$ (Here and below, the $\to $ sumbol means uniform convergence on $[a,b].$) Then $q_m = p_m - p_m(a) \to f$ and all $q_m(a) = 0.$ This implies $r_m(x)=q_m(x) -(x-a)q_m(b)/(b-a) \to f(x),$ and $r_m(a) = r_m(b) = 0$ for all $m.$ For the general $f,$ let $l(x)$ be the line through $(a,f(a)), (b,f(b)).$ Apply the above to find $r_m \to f-l$ with $r_m$ zero at the end points. Then $r_m+l$ does the job.


text:
Q: How to get home page layout programmatically in controller method In my custom module I used Ajax. I want to change product count depending on the layout. How to get home page layout programmatically in controller method?

A: I resolved this issue by adding hidden field in the template file.
<!-- For layout dependent Columns -->
<?php $layoutDepColCount = $this->getLayoutDependColumnCount();?>
<?php $_columnCount = empty($layoutDepColCount) ? $this->getColumnCount() : $layoutDepColCount;?>
<input type="hidden" name="columnCount" id="columnCount" value="<?php echo $_columnCount; ?>" />

I passed this column count as parameter to the ajax call.
var $j = jQuery.noConflict();
function showFeaturedProduct(pageno){
    $j(document).ready(function(){
         //For layout dependent Columns
        var columnCount = $j('#columnCount').val();
        $j.get("featuredproduct/index/pager", {p:pageno, cols:columnCount},
        function(data,status){
           if(status == 'success') {
              // alert("Data: " + data + "\nStatus: " + status);
               $j("#featuredproductlist").html(data);
           }
        }
        ,"html");
    });
}

Added new method in the block
/**
     * Get the layout dependent number of products.
     *
     * @return int column count
     */
    public function getLayoutDependColumnCount()
    {
        $columnCount = 0;
        $listBlock = $this->getLayout()->getBlock('featuredproduct.list.page');
        if ($listBlock) {
            $columnCount = abs(intval($this->getRequest()->getParam('cols')));
        }
        return $columnCount;
    }


text:
Q: Error on saving user input to an array perl I keep getting error in my perl script when using strict with array variables.
   #!/bin/perl

   use strict;
   use warnings;

   print "Enter Attributes for query: "
   my @ak = split(/\s+/, <>);
   foreach (@ak) {
       printf "%s\n", $_;
   }
   exit;

I keep getting this error:
Global symbol "@ak" requires explicit package name at ./test2.pl line 7.
Global symbol "@ak" requires explicit package name at ./test2.pl line 8.
Execution of ./test2.pl aborted due to compilation errors.

I used the page here as an example as to get user input.
What is wrong with my array declaration?

I found out that the script works without error if I declare the array at the top like: my @ak; and remove the my from the subsequent use of @ak.

A: There's nothing wrong with how you've declared @ak.  The problem is you're missing a semi-colon on line 6 just before the declaration.
Perl fails to recognize my @ak because it was in the middle of parsing the print statement.  This has confused the compiler and it doesn't give you a more useful error message.  In general, it's useful to look just before a syntax error in addition to the line the error is on.


text:
Q: Kubernetes + calico + replicaSet So I found myself in a pretty sticky situation. I'm trying to create a simple replicaSet, but unfortunately I ran into some problems with the calico.
I have 2 VM running on OracleVM. I have them configured to use enp0s8 interface. The IP of the master node is 192.168.56.2 and the worker node's ip is 192.168.56.3
Here is what I'm doing in Kubernetes. First I'm creating the kubernetes master node:
kubeadm init --pod-network-cidr=192.168.0.0/16 --apiserver-advertise-address=192.168.56.2

after successfuly initialzing I'm running:
export KUBECONFIG=/etc/kubernetes/admin.conf

Now I'm creating the POD network by running:
kubectl apply -f https://docs.projectcalico.org/v3.11/manifests/calico.yaml

after that I'm joining from the worker node successfully. Whenever I start the replica with:
*** edit: I don't have to create the replicaset to obtain the same result of the calico-node creation getting stuck
kubectl create -f replicaset-definition.yml

in which the yml looks like this:
kind: ReplicaSet
metadata:
  name: myapp-replicaset
  labels:
    app: myapp
    type: front-end
spec:
  template:
    metadata:
      name: myapp-pod
      labels:
        app: myapp
        type: front-end
    spec:
      containers:
        - name: nginx-container
          image: nginx
  replicas: 2
  selector:
    matchLabels:
      app: myapp

I'm getting a new calico-node created which eventually will get stuck
calico-node-mcb5g                          0/1     Running   6          8m58s
calico-node-t9p5n                          1/1     Running   0          12m

If I run
kubectl logs -n kube-system calico-node-mcb5g -f
on it I get the following logs:
2020-03-18 14:45:40.585 [INFO][8] startup.go 275: Using NODENAME environment for node name
2020-03-18 14:45:40.585 [INFO][8] startup.go 287: Determined node name: kubenode1
2020-03-18 14:45:40.587 [INFO][8] k8s.go 228: Using Calico IPAM
2020-03-18 14:45:40.588 [INFO][8] startup.go 319: Checking datastore connection
2020-03-18 14:46:10.589 [INFO][8] startup.go 334: Hit error connecting to datastore - retry error=Get https://10.96.0.1:443/api/v1/nodes/foo: dial tcp 10.96.0.1:443: i/o timeout
2020-03-18 14:46:41.591 [INFO][8] startup.go 334: Hit error connecting to datastore - retry error=Get https://10.96.0.1:443/api/v1/nodes/foo: dial tcp 10.96.0.1:443: i/o timeout

I've tried to configure the calico.yml and added the following line in env:
- name: IP_AUTODETECTION_METHOD
  value: "interface=enp0s8"

but the result is still the same.
Thank you so much for reading this and if you have any advice I will be sooo grateful!!!

A: Ok, so here it goes. What it seemed to be was that calico node crashed because the service CIDR and host CIDR overlaped.
If I initiate the master node with the CIDR changed as:
kubeadm init --pod-network-cidr=20.96.0.0/12 --apiserver-advertise-address=192.168.56.2

works like a charm.
This helped a lot:
Cluster Creation Successful but calico-node-xx pod is in CrashLoopBackOff Status


text:
Q: How to create a multiple buffer using geopandas I want to create buffers from any point in a multiple point file.
I can do it with a constant buffer using geopandas.buffer()
track.geometry = track['geometry'].buffer(0.05)
track_line = track.iloc[2:].head()

but the buffer is applied to all points.
I would like to apply different buffer values. For example, using values in another column of the data frame or a new csv column value.
For example,
 ID,latitude,longitude,buffer_value
 0,45.4,-156.0,0.3
 1,45.53,-156.98,0.4
 2,45.66,-156.97,0.34
 3,45.79,-156.957,0.23
 4,45.93,-156.942,0.45

How can I do it?

A: In the next version of GeoPandas this will be possible with the buffer method (https://github.com/geopandas/geopandas/pull/781), but for now you do it manually like this:
track['geometry'] = track.apply(
    lambda row: row.geometry.buffer(row.buffer_value), axis=1)


text:
Q: Calculate the Area under a Curve I would like to calculate the area under a curve to do integration without defining a function such as in integrate().
My data looks as this:
Date          Strike     Volatility
2003-01-01    20         0.2
2003-01-01    30         0.3
2003-01-01    40         0.4
etc.

I plotted plot(strike, volatility) to look at the volatility smile. Is there a way to integrate this plotted "curve"?

A: The AUC is approximated pretty easily by looking at a lot of trapezium figures, each time bound between x_i, x_{i+1}, y{i+1} and y_i. Using the rollmean of the zoo package, you can do:
library(zoo)

x <- 1:10
y <- 3*x+25
id <- order(x)

AUC <- sum(diff(x[id])*rollmean(y[id],2))

Make sure you order the x values, or your outcome won't make sense. If you have negative values somewhere along the y axis, you'd have to figure out how exactly you want to define the area under the curve, and adjust accordingly (e.g. using abs() )
Regarding your follow-up : if you don't have a formal function, how would you plot it? So if you only have values, the only thing you can approximate is a definite integral. Even if you have the function in R, you can only calculate definite integrals using integrate(). Plotting the formal function is only possible if you can also define it.

A: In the pharmacokinetics (PK) world, calculating different types of AUC is a common and fundamental task. The are lots of different AUC calculations for pharmacokietics, such as

*

*AUC0-t      = AUC from zero to time t

*AUC0-last   = AUC from zero to the last time point (may be same as above)

*AUC0-inf    = AUC from zero to time infinity

*AUCint      = AUC over a time interval

*AUCall      = AUC over the whole time period for which data exists

One of the best packages which does these calculations is the relatively new package PKNCA from the folks at Pfizer. Check it out.

A: Just add the following to your program and you will get the area under the curve:
require(pracma)
AUC = trapz(strike,volatility)

From ?trapz:

This approach matches exactly the approximation for integrating the
  function using the trapezoidal rule with basepoints x.

A: Three more options, including one using a spline method and one using Simpson's rule...
# get data
n <- 100
mean <- 50
sd <- 50

x <- seq(20, 80, length=n)
y <- dnorm(x, mean, sd) *100

# using sintegral in Bolstad2
require(Bolstad2)
sintegral(x,y)$int

# using auc in MESS
require(MESS)
auc(x,y, type = 'spline')

# using integrate.xy in sfsmisc
require(sfsmisc)
integrate.xy(x,y)

The trapezoidal method is less accurate than the spline method, so MESS::auc (uses spline method) or Bolstad2::sintegral (uses Simpson's rule) should probably be preferred. DIY versions of these (and an additional approach using the quadrature rule) are here: http://www.r-bloggers.com/one-dimensional-integrals/

A: OK so I arrive a bit late at the party but going over the answers a plain R solution to the problem is missing. Here goes, simple and clean:
sum(diff(x) * (head(y,-1)+tail(y,-1)))/2

The solution for OP then reads as:
sum(diff(strike) * (head(volatility,-1)+tail(volatility,-1)))/2

This effectively calculates the area using the trapezoidal method by taking the average of the "left" and "right" y-values.
NB: as @Joris already pointed out you could use abs(y) if that would make more sense.

A: Joris Meys's answer was great but I struggled to remove NAs from my samples. Here is the little function I wrote to deal with them :
library(zoo) #for the rollmean function

######
#' Calculate the Area Under Curve of y~x
#'
#'@param y Your y values (measures ?)
#'@param x Your x values (time ?)
#'@param start : The first x value
#'@param stop : The last x value
#'@param na.stop : returns NA if one value is NA
#'@param ex.na.stop : returns NA if the first or the last value is NA
#'
#'@examples
#'myX = 1:5
#'myY = c(17, 25, NA, 35, 56)
#'auc(myY, myX)
#'auc(myY, myX, na.stop=TRUE)
#'myY = c(17, 25, 28, 35, NA)
#'auc(myY, myX, ex.na.stop=FALSE)
auc = function(y, x, start=first(x), stop=last(x), na.stop=FALSE, ex.na.stop=TRUE){
  if(all(is.na(y))) return(NA)
  bounds = which(x==start):which(x==stop)
  x=x[bounds]
  y=y[bounds]
  r = which(is.na(y))
  if(length(r)>0){
    if(na.stop==TRUE) return(NA)
    if(ex.na.stop==TRUE & (is.na(first(y)) | is.na(last(y)))) return(NA)
    if(is.na(last(y))) warning("Last value is NA, so this AUC is bad and you should feel bad", call. = FALSE)
    if(is.na(first(y))) warning("First value is NA, so this AUC is bad and you should feel bad", call. = FALSE)
    x = x[-r]
    y = y[-r]
  }
  sum(diff(x[order(x)])*rollmean(y[order(x)],2))
}

I then use it with an apply onto my dataframe : myDF$auc = apply(myDF, MARGIN=1, FUN=auc, x=c(0,5,10,15,20))
Hope it can help noobs like me :-)
EDIT : added bounds

A: You can use ROCR package, where the following lines will give you the AUC:
pred <- prediction(classifier.labels, actual.labs)
attributes(performance(pred, 'auc'))$y.values[[1]]


text:
Q: Can't enumerate through Jekyll pages by tag goal
Generate a page list filtered by a single tag.
problem
List doesn't appear.
things I tried
I started with the  element in the default Jekyll site:

  {% for page in site.pages %}
    {% if page.title %}
      {{ page.title }}
    {% endif %}
  {% endfor %}

When the Jekyll site is served, this puts an "About" page in the nav element.
I added two tags to different pages' front matter on the site:
tags:
- eng
---

I tried both formats:
tags: eng
---

*

*Try enumerating through site.tags.eng (also tried site.tags[eng] and site.tags["eng"]):

     {% for page in site.tags.eng %}
        {% if page.title %}
          {{ page.title }}
        {% endif %}
      {% endfor %}

*Try testing for a tag (with or without quotes):

        {% for tag in site.tags %}
                  {% if tag == "eng" %}
            {% if page.title %}
            {{ page.title }}
            {% endif %}
                  {% endif %}
        {% endfor %}

*Also add a tag list to _config.yml:
# Tags
tags: [eng, jpn]

*Add a tag to the sample post to see if only posts are being indexed
other questions I looked at

*

*Generating a list of pages (not posts) in a given category: not sure how what I'm trying is fundamentally different

*http://jekyllrb.com/docs/variables/: the Jekyll main documentation doesn't say that tags have to be specified in the config YAML

*https://stackoverflow.com/questions/18944264/jekyll-plugin-liquid-tag-creation-not-working: It doesn't seem like I should have to build a whole plugin for this.

A: Settings tags on a page :
tags: [ tag1, tag3 ]
---
or
tags:
 - tag1
 - tag2
---

If you want to make a list from a tag :

  {% for p in site.pages %}
    {% if p.tags contains 'tag2' %}

{{ p.title }}

    {% endif %}
  {% endfor %}

Secondary answers :

*

*It's normal for about page to appear in pages list (default menu) it's a page

*Tagged pages will not appear in site.tags hash, only posts.


text:
Q: Chartkick graph keeps loading I'm trying to display a simple graph with Chartkick. I've installed the gems chartkick, groupdate, and active_median. I have a model (Client) that I want to test on the graph so I tried it using this line:
<%= line_chart Client.group_by_day(:created_at), id: random_chartkick_id %>

In my helper I have this method to generate a random ID for the chart
def random_chartkick_id
  return 'chart-#'+(Random.rand(10000)).to_s
end

I'm using google's jsapi via cdn:
<%= javascript_include_tag "http://www.google.com/jsapi", "chartkick" %>

However, the chart just says "loading". When I type a random number in the data field for creating the chart I get an empty chart.
What am I doing wrong? Thanks

A: Figured it out, just needed to add .count
<%= line_chart Client.group_by_day(:created_at).count, id: random_chartkick_id %>


text:
Q: How can I append a word in between an array of strings? I want to append the word AND between each string in an array, but I don't want it at the end of my string.  Here is what I'm trying:
Assuming I want to pass First, Second, Third
public void addString(String... myString) {
   StringBuilder sb = new StringBuilder();

   for(int i = 0; i < myString.length -1;) {
      sb.append("(" + myString[i] + " AND " + myString[i+1] + ")");
      i++;
   }

   System.out.println(sb);
}

My output is (First AND Second)(Second AND Third)
But I want (First AND Second AND Third)
What am I doing wrong?

A: Append the "(" before your for loop so it prints only once.  Similarly, append the ")" after your for loop so it prints only once.  Finally, you can loop through your entire myString array, appending only that element, instead of two elements at a time, and only appending " AND " if needed.

A: Tweak your answer like this:
public void addString(String... myString) {
   StringBuilder sb = new StringBuilder("(");

   for(int i = 0; i < myString.length -1; i++) {
      sb.append(myString[i] + " AND ");
   }
   if(myString.length == 0)
       sb.append(")");
   else
       sb.append(myString[myString.length - 1]);
   System.out.println(sb);
}

The only changes are:

*

*Create the StringBuilder containing the starting (

*Add all the elements except the last one, and append "AND" after it

*Add the final element and the closing )
The repetitive part of your algorithm is the one that places the inner elements. This also covers the case where myString has length 1. In case of having no elements, the last addition is skipped and the closing ")" is added.

A: You should seperate the parts that you want just once from you for loop like this. So you want ( and ) once and there is only one word for wich you dont need AND in front of it.
public void addString(String[] myString)
{
   StringBuilder sb = new StringBuilder();
   sb.append("("+myString[0]);
   for(int i = 1; i < myString.length;i++)
   {
      sb.append(" AND " + myString[i]);
   }
   sb.append(")")

   System.out.println(sb);
}

A: To do what you want I'd probably use the join method in StringUtils.
StringUtils.join Docs
From the docs:
public static String join(Object[] array,
          String separator)

Joins the elements of the provided array into a single String containing the provided list of elements.

No delimiter is added before or after the list. A null separator is the same as an empty String (""). Null objects or empty strings within the array are represented by empty strings.

 StringUtils.join(null, *)                = null
 StringUtils.join([], *)                  = ""
 StringUtils.join([null], *)              = ""
 StringUtils.join(["a", "b", "c"], "--")  = "a--b--c"
 StringUtils.join(["a", "b", "c"], null)  = "abc"
 StringUtils.join(["a", "b", "c"], "")    = "abc"
 StringUtils.join([null, "", "a"], ',')   = ",,a"

Parameters:
    array - the array of values to join together, may be null
    separator - the separator character to use, null treated as ""
Returns:
    the joined String, null if null array input

A: You can do the following -
Arrays.asList(myString).toString().replaceAll(",", " AND").replace("[", "(").replace("]", ")")

*

*Arrays.asList(myString) converts the array to a List.

*toString() converts it to a string which is like [ele1, ele2, ele
3].

*Then using the replaceAll and replace method gives the
appropriate output.

The second option is to use the join method provided by StringUtils.

A: The approach used most often when you want separators between elements is to add the separator first, then the string. Only skipping the separator before the first element.
public void addString(String... myString) {
    String separator = " AND ";

    StringBuilder sb = new StringBuilder();

    sb.append('(');

    boolean needSeparator = false;
    for(String string : myString) {
        if (needSeparator) {
            sb.append(separator);
        } else {
            needSeparator = true;
        }
        sb.append(string);
    }

    sb.append(')');

    System.out.println(sb);
 }

If you call addString("First", "Second", "Third") you'd get
(First AND Second AND Third)

This works perfectly fine with just 1 input addString("First")
(First)

Or even empty input addString() which would crash most other solutions I've seen here
()

It is possible to move printing the first element out of the loop so the loop does not have to check if it needs to omit the separator (minimal performance gain) but that results IMO in less readable code. E.g.:
if (myString.length > 0) {
    // append first element without separator
    sb.append(myString[0]);

    // implicitly checks that length > 1
    for (int i = 1; i < myString.length; i++) {
        // append separator unconditionally
        sb.append(separator);
        sb.append(myString[i]);
    }
}

A: Append the parenthesis before and after the For Loop.
Append only one element in the String at a time.
Remove the final "AND " at the end of the String after the For Loop.
public void addString(String... myString) {
    StringBuilder sb = new StringBuilder();

    sb.append("(");

    for(int i = 0; i < myString.length;) {
        sb.append(myString[i] + " AND ");
        i++;
    }

    sb = sb.substring(0, sb.length() - 5);

    sb.append(")");

    System.out.println(sb);
}

A: Get the Apache CommonsLang package http://commons.apache.org/proper/commons-lang/
then use its StringUtils join() method as described here: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html
System.out.println(StringUtils.join(myString, ' AND '));

A: Corrected code:
 public void addString(String... myString) {
       StringBuilder sb = new StringBuilder();

       for(int i = 0; i < myString.length; i++) {
          if(i = 0){
             sb.append("(" + myString[i])
          }else if (i = myString.length-1){
             sb.append(myString[i] + ")");
          }else{
             sb.append(myString[i])
          }
          sb.append("(" + myString[i] + " AND " + myString[i+1] + ")");
       }

       System.out.println(sb);
    }

EDIT: Here is a better version based off of one of the answers above:
public void addString(String[] myString)
    {
       StringBuilder sb = new StringBuilder();
       sb.append("(");
       for(int i = 0; i < myString.length; i++){
          sb.append(myString[i] + " AND ");
       }
       sb.append(")")

       System.out.println(sb);
    }

A: Try this:
public void addString(string[] myString) {
  StringBuilder sb = new StringBuilder();

   sb.Append("(");
   for(int i = 0; i < myString.length; i++) {
      sb.Append(myString[i] + " AND ");
   }

   string result = sb.ToString().Substring(0, sb.ToString().LastIndexOf("AND"));
   result += ")";

   System.out.println(result);
}


text:
Q: Spring Boot console application causes JUnit test case to wait I have Spring Boot console application which accepts user input. In the same application, there are service to perform some logic.
On running the service's JUnit test case directly, I am observing a behavior where the console application stays in the state of accepting user input, and thus not entering the JUnit tests.
Usually there is no issue becasue for a normal Spring Boot application, there is nothing to run on start up. But for this console application setup, it awaits user input.
May I know if there is any way that can make the test cases run while not triggering the console application? Thank you very much.
Observation: The console application is triggered on JUnit test case run, test case is not entered

Main application
import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ToyRobotApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(ToyRobotApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        // Instruct user to perform input
        System.out.println("Welcome to toy robot application!");
        System.out.println("Below are the possible operations:");
        System.out.println("PLACE <x-coordinate> <y-coordinate> <facing>");
        System.out.println("MOVE");
        System.out.println("LEFT");
        System.out.println("RIGHT");
        System.out.println("REPORT");

        while (true) {
            System.out.println("Please enter your command:");

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String usrInput = br.readLine();
            //...

        }
    }
}

Test case
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.somecompany.model.Facing;
import com.somecompany.model.Location;
import com.somecompany.model.Robot;
import com.somecompany.service.ToyRobotService;

@SpringBootTest
public class ToyRobotReportTest {

    @Autowired
    private Robot robot;

    @Autowired
    private ToyRobotService toyRobotService;

    @Test
    public void shouldBeAbleToReportLocation() {
        Location location = new Location();
        location.setXCor("1");
        location.setYCor("2");
        location.setFacing(Facing.NORTH);

        robot.setLocation(location);

        // Actual result
        String result = toyRobotService.report();

        // Assertion
        assertEquals("1,2,NORTH", result);
    }
}

Note: Other sources omitted

A: I got the setup working after some research. To get this to work, the JUnit test class should not be annotated with the usual @SpringBootTest annotation.
When the class is annotated with @SpringBootTest, it will start up the application's context (i.e. start the application). In most usual test scenarios, this should be fine if there is no waiting of user input.
In our case, we want the Spring Boot annotations (e.g. @Autowired) to be recognized, but do not want the application itself to be started up.
We can use the following in JUnit:
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = ToyRobotApplication.class, initializers = ConfigDataApplicationContextInitializer.class)
public class ToyRobotPlaceTest {
    ...
}

This will regonize spring annotations, but will not start the application context.


text:
Q: restrict content on django views I am trying to do this all vip user paid that contains type 2 allow to see the full information , but however it does as expect, but with a minor issue , it hide the lesson to the end-user if this doesnt belong to x user logged. I want to keep lesson displayed to the end-user, but however if the user tries to click to the lesson then display upgrade account instead of hidding content. how can I achieve this?
model
class Lesson(models.Model):
  content_title = models.CharField(max_length=120)
  content_text = models.CharField(max_length=200)
  thumbnail = models.ImageField(upload_to='xxx/xxx/xxx/xxx/xxx')
  link = models.CharField(max_length=200, null=True)
  allowed_memberships = models.ManyToManyField(Membership)

  def __str__(self):
    return self.content_title

view
def get_context_data(self, **kwargs):
    context = super(bootCamp, self).get_context_data(**kwargs)
    lesson = Lesson.objects.first()
    user_membership = UserMembership.objects.filter(user=self.request.user).first()
    user_membership_type = user_membership.membership.membership_type
    lesson_allowed_mem_types = lesson.allowed_memberships.all()
    context['lessons_allowed_mem_types'] = lesson_allowed_mem_types
    context['lessons'] = None
    if lesson_allowed_mem_types.filter(membership_type=user_membership_type).exists():
        if Lesson.objects.filter(allowed_memberships=1):
            context['lessons'] = Lesson.objects.filter(allowed_memberships=1).values()
        elif Lesson.objects.filter(allowed_memberships=2):
            context['lessons'] = Lesson.objects.filter(allowed_memberships=2).values()
        else:
            pass
    return context

template
  {% if lessons is not None %}
    {% for lessson in lessons %}

{{ lessson.content_title }}

{{ lessson.content_text }}

      {% endfor %}
  {% else %}

upgrade

  {% endif %}

A: I would recommend to check the count of the retrieved lessons if it is less than 1 then redirect to the upgrade view/template.


text:
Q: Nginx no inicia: directiva desconocida "pagespeed" Buenas,
Llevo más de un año usando Nginx con PageSpeed para incrementar la carga, compresión y caché de mis paginas web. Soy dueño de un acortador de URLS con millones de visitas mensuales. Instalé el certbot para añadir HTTPS al sitio web con Let's Encrypt y desde aquel momento reinicié Nginx con service nginx restart y comenzé a experimentar problemas.
A continuación dejo el error completo (fuente: systemctl status nginx.service) para depurificar el error que ocurre al iniciar Nginx.
systemctl status nginx.service
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Wed 2017-10-11 18:12:55 EDT; 4s ago
  Process: 9090 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=1/FAILURE)
 Main PID: 14066 (code=killed, signal=KILL)

Oct 11 18:12:55 vps118687 systemd[1]: Starting A high performance web server and a reverse proxy server...
Oct 11 18:12:55 vps118687 nginx[9090]: nginx: [emerg] unknown directive "pagespeed" in /etc/nginx/conf.d/pagepseed.conf:2
Oct 11 18:12:55 vps118687 nginx[9090]: nginx: configuration file /etc/nginx/nginx.conf test failed
Oct 11 18:12:55 vps118687 systemd[1]: nginx.service: Control process exited, code=exited status=1
Oct 11 18:12:55 vps118687 systemd[1]: Failed to start A high performance web server and a reverse proxy server.
Oct 11 18:12:55 vps118687 systemd[1]: nginx.service: Unit entered failed state.
Oct 11 18:12:55 vps118687 systemd[1]: nginx.service: Failed with result 'exit-code'.

ACTUALIZACION
Parece que al instalar el certbot nginx se volvió a instalar, como puedo solucionar esto y dejar la versión antigua?
whereis nginx retorna /usr/sbin/nginx /etc/nginx /usr/local/sbin/nginx /usr/local/nginx /usr/share/nginx
Gracias por sus respuestas.

A: debes instalar y cargar el módulo correspondiente para que la directiva pagespeed esté disponible en Nginx:
bash <(curl -f -L -sS https://ngxpagespeed.com/install) --nginx-version latest

Para más información ve a: https://developers.google.com/speed/pagespeed/module/?hl=es-419


text:
Q: Тег  в SVG при изменении ширины элемента в Safari запаздывает Отрисованные элементы, например <path>, <line>, <rect> и другие, при смене ширины браузера меняется моментально, но тег <text> обновляется с задержкой (рывками).
При этом text-rendering не срабатывает.
<text transform="matrix(1 0 0 1 1 8)" class="st0 st1 st2">Hello, world! This is a simple SVG text for testing.</text>

Код: https://codepen.io/jamesscreen/pen/oNovBYO

A:
Отрисованные элементы, например , ,  и другие, при
смене ширины браузера меняется моментально, но тег  обновляется
с задержкой (рывками).

Возможно и другое решение: заменить ресурсоёмкие матричные вычисления transform="matrix(1 0 0 1 1 8)" на позиционирование текста с помощью координат x y
<text x="1" y="8" class="st0 st1 st2">Hello, world! This is a simple SVG text for testing.</text>

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
    viewBox="0 0 129.7 9.5" style="enable-background:new 0 0 129.7 9.5;" xml:space="preserve">
<style type="text/css">
  @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@500');
    .st0{fill:#182540;}
  .st1{font-family:'Playfair Display';font-weight: 500;}
    .st2{font-size:5.496px;}
    .st3{fill:none;stroke:#324093;stroke-miterlimit:10;}
</style>
<text x="1" y="8" class="st0 st1 st2">Hello, world! This is a simple SVG text for testing.</text>
<rect class="st3" width="129.7" height="9.5"/>
<line class="st3" x1="2" y1="0.5" x2="2" y2="1.5"/>
<line class="st3" x1="4" y1="0.5" x2="4" y2="1.5"/>
<line class="st3" x1="6" y1="0.5" x2="6" y2="1.5"/>
<line class="st3" x1="8" y1="0.5" x2="8" y2="1.5"/>
<line class="st3" x1="10" y1="0" x2="10" y2="2"/>
<line class="st3" x1="12" y1="0.5" x2="12" y2="1.5"/>
<line class="st3" x1="14" y1="0.5" x2="14" y2="1.5"/>
<line class="st3" x1="16" y1="0.5" x2="16" y2="1.5"/>
<line class="st3" x1="18" y1="0.5" x2="18" y2="1.5"/>
<line class="st3" x1="20" y1="0" x2="20" y2="2"/>
<line class="st3" x1="22" y1="0.5" x2="22" y2="1.5"/>
<line class="st3" x1="24" y1="0.5" x2="24" y2="1.5"/>
<line class="st3" x1="26" y1="0.5" x2="26" y2="1.5"/>
<line class="st3" x1="28" y1="0.5" x2="28" y2="1.5"/>
<line class="st3" x1="30" y1="0" x2="30" y2="2"/>
<line class="st3" x1="32" y1="0.4" x2="32" y2="1.4"/>
<line class="st3" x1="34" y1="0.4" x2="34" y2="1.4"/>
<line class="st3" x1="36" y1="0.4" x2="36" y2="1.4"/>
<line class="st3" x1="38" y1="0.4" x2="38" y2="1.4"/>
<line class="st3" x1="40" y1="-0.1" x2="40" y2="1.9"/>
<line class="st3" x1="42" y1="0.4" x2="42" y2="1.4"/>
<line class="st3" x1="44" y1="0.4" x2="44" y2="1.4"/>
<line class="st3" x1="46" y1="0.4" x2="46" y2="1.4"/>
<line class="st3" x1="48" y1="0.4" x2="48" y2="1.4"/>
<line class="st3" x1="50" y1="0.4" x2="50" y2="3.4"/>
<line class="st3" x1="52" y1="0.4" x2="52" y2="1.4"/>
<line class="st3" x1="54" y1="0.4" x2="54" y2="1.4"/>
<line class="st3" x1="56" y1="0.4" x2="56" y2="1.4"/>
<line class="st3" x1="58" y1="0.4" x2="58" y2="1.4"/>
<line class="st3" x1="60" y1="-0.1" x2="60" y2="1.9"/>
<line class="st3" x1="62" y1="0.4" x2="62" y2="1.4"/>
<line class="st3" x1="64" y1="0.4" x2="64" y2="1.4"/>
<line class="st3" x1="66" y1="0.4" x2="66" y2="1.4"/>
<line class="st3" x1="68" y1="0.4" x2="68" y2="1.4"/>
<line class="st3" x1="70" y1="-0.1" x2="70" y2="1.9"/>
<line class="st3" x1="72" y1="0.4" x2="72" y2="1.4"/>
<line class="st3" x1="74" y1="0.4" x2="74" y2="1.4"/>
<line class="st3" x1="76" y1="0.4" x2="76" y2="1.4"/>
<line class="st3" x1="78" y1="0.4" x2="78" y2="1.4"/>
<line class="st3" x1="80" y1="-0.1" x2="80" y2="1.9"/>
<line class="st3" x1="82" y1="0.2" x2="82" y2="1.2"/>
<line class="st3" x1="84" y1="0.2" x2="84" y2="1.2"/>
<line class="st3" x1="86" y1="0.2" x2="86" y2="1.2"/>
<line class="st3" x1="88" y1="0.2" x2="88" y2="1.2"/>
<line class="st3" x1="90" y1="-0.2" x2="90" y2="1.8"/>
<line class="st3" x1="92" y1="0.2" x2="92" y2="1.2"/>
<line class="st3" x1="94" y1="0.2" x2="94" y2="1.2"/>
<line class="st3" x1="96" y1="0.2" x2="96" y2="1.2"/>
<line class="st3" x1="98" y1="0.2" x2="98" y2="1.2"/>
<line class="st3" x1="100" y1="0.2" x2="100" y2="3.2"/>
<line class="st3" x1="102" y1="0.1" x2="102" y2="1.1"/>
<line class="st3" x1="104" y1="0.1" x2="104" y2="1.1"/>
<line class="st3" x1="106" y1="0.1" x2="106" y2="1.1"/>
<line class="st3" x1="108" y1="0.1" x2="108" y2="1.1"/>
<line class="st3" x1="110" y1="-0.4" x2="110" y2="1.6"/>
<line class="st3" x1="112" y1="0.1" x2="112" y2="1.1"/>
<line class="st3" x1="114" y1="0.1" x2="114" y2="1.1"/>
<line class="st3" x1="116" y1="0.1" x2="116" y2="1.1"/>
<line class="st3" x1="118" y1="0.1" x2="118" y2="1.1"/>
<line class="st3" x1="120" y1="-0.4" x2="120" y2="1.6"/>
<line class="st3" x1="122" y1="0.1" x2="122" y2="1.1"/>
<line class="st3" x1="124" y1="0.1" x2="124" y2="1.1"/>
<line class="st3" x1="126" y1="0.1" x2="126" y2="1.1"/>
<line class="st3" x1="128" y1="0.1" x2="128" y2="1.1"/>
</svg>

Линейку зубцов можно заменить на svg pattern, код значительно уменьшится, не нужно будет прорисовывать каждую линию много раз.
В паттерне определяем 4 коротких, вертикальных  линии и одну длинную.  Далее этот паттерн автоматически, многократно повторяется на всей длине.
Подробнее о pattern

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
   viewBox="0 0 129.7 9.5">
<style type="text/css">
  @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@500');
    .st0{fill:#182540;}
  .st1{font-family:'Playfair Display';font-weight: 500;}
    .st2{font-size:5.496px;}
    .st3{fill:none;stroke:#324093;stroke-miterlimit:10;}
</style>
 <text x="1" y="8" class="st0 st1 st2">Hello, world! This is a simple SVG text for testing.</text>

<defs>
<pattern id="patt"
             x="1" y="0" width="10" height="9.5"
             patternUnits="userSpaceOnUse" >
      <g stroke="#324093" stroke-width="1">
 <line  x1="1" y1="0.5" x2="1" y2="1.5"/>
 <line  x1="3" y1="0.5" x2="3" y2="1.5"/>
 <line  x1="5" y1="0.5" x2="5" y2="1.5"/>
 <line  x1="7" y1="0.5" x2="7" y2="1.5"/>
 <line  x1="9" y1="0.5" x2="9" y2="2.5" stroke="1"/>
    </g>
</pattern>
</defs>
<rect  fill="url(#patt)" width="130" height="9.5" stroke="#324093"/>

</svg>

Это лишнее в шапке SVG:
style="enable-background:new 0 0 129.7 9.5;" xml:space="preserve"
Сейчас это не применяется, осталось как атавизм в векторных редакторах.

A: Недосмотрел. Решение оказалось простым. Нужно было прописать text-rendering со значением geometricPrecision либо в svg:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
    viewBox="0 0 129.7 9.5" style="enable-background:new 0 0 129.7 9.5;" xml:space="preserve" text-rendering="geometricPrecision">

либо в CSS стили
.st1{font-family:'Playfair Display';font-weight: 500;text-rendering:geometricPrecision}


text:
Q: Latex pgfplots graph axis scaling
I have the graph to the left. I want the graph to the right, or else I can't see the difference between the two lower ones.
\documentclass[a4paper,11pt]{article}
\usepackage{float}
\usepackage{tikz} \usetikzlibrary{trees}
\usetikzlibrary{pgfplots.groupplots}
\usepackage{siunitx}
\sisetup{per=slash, load=abbr}

\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{width=7cm, height=10cm, compat=1.4, every axis/.append style={thick}}
\begin{document}
\begin{figure}[H]
  \centering
  \pgfplotsset{
    scaled y ticks=false,
    scale only axis,
    legend style={at={(0,0.8)}, anchor=west, font=\tiny},
    xmin=7,
  }
  \begin{tikzpicture} [scale=0.7, font=\Large]
    \begin{axis}[
        title=Size of search tree linear scale,
        ylabel=Nodes,
        xtick=data,
        ymin=0,
    xlabel=xlabel ]
  \addplot[smooth,mark=square*, mark options={solid},red, dashed]
  coordinates{ (7,29788) (8,16760) (9,8770) (10,14248) (11,11456) (12,14602) (13,17456) (14,13112)
  }; \label{ie_plot} \addlegendentry{IntPairExact}
  \addplot[smooth,mark=square*, mark options={solid},blue, dotted]
  coordinates{ (7,30142) (8,16836) (9,8960) (10,14390) (11,11584) (12,14694) (13,17634) (14,13242)
  }; \label{ia_plot} \addlegendentry{IntPairApprox}
  \addplot[smooth,mark=*,mark options={solid},black]
  coordinates{ (7,256300) (8,254888) (9,144484) (10,194390) (11,135874) (12,233684) (13,243624) (14,221408)
  }; \label{int_plot} \addlegendentry{Integer}
    \end{axis}
  \end{tikzpicture}

\end{figure}
\end{document}


text:
Q: Navigation Drawer - Have only icons and very big I have a nav drawer implemented in my activity. The audience for my app is the elderly and I want the icons to be very large and take up the whole drawer height.

I am looking to have the 4 icons evenly spaced out and to have no text just big icons. I have tried playing around with the tag:
<dimen name="design_navigation_icon_size" tools:override="true"></dimen>

but I have not been able to get it to work. The icons simply keep overlapping each other when they get too big near the top. The images always seem to be contained in the header layout.

A: Create custom view and layout for drawer
 <android.support.design.widget.NavigationView
    android:id="@+id/nav_view_left"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_left" />

nav_header_left.xml
 <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:background="@color/right_side_header_bg_color"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:paddingTop="@dimen/fifty"
    android:paddingRight="@dimen/twenty"
    android:paddingLeft="@dimen/twenty"
    android:orientation="vertical"
    android:weightSum="4">

    <TextView
        android:id="@+id/add_txt"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:text="Gallery"
        android:drawableLeft="@android:drawable/ic_menu_gallery"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_weight="1"
        />
    <TextView
        android:id="@+id/gall_txt"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:text="Gallery"
        android:drawableLeft="@android:drawable/ic_menu_gallery"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_weight="1"
        />
    <TextView
        android:id="@+id/menu_add_txt"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:text="Gallery"
        android:drawableLeft="@android:drawable/ic_menu_add"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_weight="1"
        />

    <TextView
        android:id="@+id/media_txt"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:drawableLeft="@android:drawable/ic_media_rew"
        android:gravity="center"
        android:text="Gallery" />
    </LinearLayout>

A: Use this code for navigationView:
<android.support.v4.widget.DrawerLayout
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:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start"
android:theme="@style/AppTheme">

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@android:color/white"
            android:titleTextColor="@color/theme_color_dark"
            style="@style/AppTheme"
            android:theme="@style/AppTheme"/>

    </android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>
<fragment
    android:id="@+id/menu_fragement"
    android:tag="Menu"
    android:layout_width="250dp"
    android:layout_gravity="start"
    android:name="com.app.medcallz.fragments.MenuFragement"
    android:layout_height="match_parent"
    />
</android.support.v4.widget.DrawerLayout>

MenuFragment:
<LinearLayout
android:id="@+id/options_container"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_below="@+id/user_detail_container">

    <ImageView
        android:id="@+id/notificationsIcon"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/nav_notificatios"
        android:layout_weight="0.1"/>

    <View
        android:id="@+id/account_divider"
        android:layout_width="fill_parent"
        android:layout_height="@dimen/login_divider_width"
        android:background="@color/white_color"
        android:visibility="visible"

        />
</LinearLayout>


text:
Q: Testing booted method in Laravel I am using Laravel Cashier with Stripe, and I am trying to cover the the following lines in my tests, so far I tried mocking but that did not work, I was wondering what is the best practice to test them
use function Illuminate\Events\queueable;

/**
 * The "booted" method of the model.
 *
 * @return void
 */
protected static function booted()
{
    static::updated(queueable(function ($customer) {
        if ($customer->hasStripeId()) {
            $customer->syncStripeCustomerDetails();
        }
    }));
}

The code is taken from https://laravel.com/docs/9.x/billing#syncing-customer-data-with-stripe

A: You could achieve this by using a partial mock, Laravel has a helper for that method. Since you are actually using correct dependency injection, this would be my approach. It requires the queue setting in phpunit to be sync.
public function test_update_customer()
{
    $account = Account::factory()->create(['stripe_id' => 'fake']);

    $this->partialMock(Account::class, function ($mock) {
        $mock->shouldReceive('syncStripeCustomerDetails')
            ->once();
    });

    $response = $this->actingAs($someUser)
        ->put(route('billing.update', $account), [
            'name' => 'Some name',
            'email' => 'Another email',
        ]);

    $response->assertOk();
}


text:
Q: Confused about notation for conditional mutual information Consider discrete random variables $Z$, $W$, $X$, and some event $\mathcal{E}$:
I'm confused about the meaning of the conditional mutual information $I[ Z : W \mid X, \mathcal{E} ]$.
I'm aware of the standard definition of $I[ Z : W \mid X]$, but it seems to me that the event $\mathcal{E}$ makes the notation somewhat ambiguous, as there could be 2 distinct ways to interpret it:

*

*$I[ Z : W \mid X, \mathcal{E} ] := \sum_{x} \Pr[ X=x \mid \mathcal{E} ]\cdot I[ Z : W \mid X=x, \mathcal{E}]$

*$I[ Z : W \mid X, \mathcal{E} ] := \sum_{x} \Pr[ X=x ]\cdot I[ Z : W \mid X=x, \mathcal{E}]$
Which one of the two is correct and why is that so?


text:
Q: Spring Boot profile properties doesn't work with tests Spring Boot version 2.2.6. I have case that there is several application-{profile}.yml files in folder src/main/resources/ and I want't to build project with Maven e.g mvn clean package -Dspring.profiles.active=dev
Then I have just application.yml file in folder src/test/resources, this should be a properties file to all test (IT/unit).
Now when I build with command mvn clean package -Dspring.profiles.active=dev, properties src/main/resources/application-dev.yml and src/test/resources/application.yml are MERGED and used for the tests. Well in test properties there might be pretty fatal confs e.g Hibernate auto-ddl: create-drop.
Have been reading docs but I don't find any logic why properties files are MERGED in this case. Is there any good practice that tests can be forced to use ALWAYS certain properties file? I think that just using some annotations in test files isn't the best practice, e.g @TestPropertySource or @ActiveProfiles, cause when you forgot to use these annotations then the case is same again. Is there some global configuration for all tests or some other better solutions?

A: The application.yml file has higher precedence over any environment-specific file, for example, application-dev.yml file. The standard inheritance applies, so you can override the parent properties in the profile-specific YAML file.
application.yml
server:
  port: 9090

spring:
  jpa:
    hibernate:
      ddl-auto: create-drop

application-dev.yml
spring:
  jpa:
    hibernate:
      ddl-auto: none

In case you run with the dev profile, the value of spring.jpa.hibernate.ddl-auto parameter would be none.

A: I get that application.yml has higher precedence in folder /src/main, but that it takes over also from folder /src/test is kinda weird.
Yes that config can be made into profile-specific files (ddl-auto: none), tough I still have problem with datasource, somehow Spring Boot is picking application-dev.ymls datasource into tests also, this is working like other way around than that ddl-auto attribute.
src/test/resources/application.yml
spring:
  datasource:
    url: jdbc:h2:mem:test;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL

src/main/resources/application-dev.yml
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/db


text:
Q: How to set up Laravel 5 with Twig and translations? I want to have project with:

*

*Laravel 5

*Twig template engine

*trans tag in Twig, which works with standard Laravel translations (based on php arrays)

Here is my composer.json:
"require": {
    "laravel/framework": "5.1.*",
    "rcrowe/TwigBridge": "~0.8.1"
}

app.php:
'providers' => [
    // ...
    TwigBridge\ServiceProvider::class,
    // ...
]

'aliases' => [
    'Twig'      => TwigBridge\Facade\Twig::class,
],

Here is my controller:
class Page extends Controller
{
    public function home()
    {
        $name = 'Guest';
        return Twig::render('twig.twig', compact('name'));
    }
}

But I have this error:
ReflectionException in Container.php line 736:
Class view does not exist

A: I've used the TwigBridge multiple times in my projects without getting that error, but instead of Twig::render you can still use the standard Laravel View::make functionality. https://github.com/rcrowe/TwigBridge#usage
My steps for installation:

*

*Require in composer

*Add the service provider 'TwigBridge\ServiceProvider',

*Add the facase 'Twig' => 'TwigBridge\Facade\Twig',

*Use the View::make or view('view', $params)
The default translator class of Laravel is already included in the TwigBridge so you can just use {{ trans('website.key') }} if i remember correctly
https://github.com/rcrowe/TwigBridge#functionsfiltersvariables

A: I had the same problem as yours, try to add provider and aliases in the end of variables (after View)


text:
Q: how to set min height of router outlet in angular 5? in the below code the router-outlet is in between 'app-header' and 'app-footer' components.How can I retrieve the screen height and 'app-header' height? and I want to set deduction of these two heights((screen)-('app-header')) as the  min height of router outlet.is that possible?
app.components.ts
  <app-header (toggleMenu)="toggleMenu($event)" *ngIf="headerVisible"></app-header>

    <!-- Content -->
      <router-outlet (activate)="onActivate($event)"></router-outlet>
    <!-- Footer -->

      <app-footer (toggleFooterLanguage)="toggleFooterLanguage($event)" *ngIf="footerVisible"></app-footer>

A:
app.component.html

<div class="my-router-outlet">
    <router-outlet></router-outlet>
</div>

app.component.scss

.my-router-outlet {
   /* reduce the height of header and footer(170px) as an example*/
   min-height: calc(100vh - 170px);
}


text:
Q: $scope does not call inside function Right now we are facing an issue in a controller that calls a DataService (Parse), the problem is that this code does not work:
    function MainCtrl($scope, DataService, $location)
{

    $scope.actionList = function() {

            // Call the service and fetch the list of signatures that match the given action ID
            DataService.getActions(function (results) {
                $scope.$apply(function () {
                    // Apply the results to the signatureList model so it will refresh the table in the view
                    $scope.actionList = results;
                });
            });

    };
}

I put a breakpoint in the DataService line but it doesn't get hit, but if I implement the Ctrl in this way it does get call and It works!!:
function MainCtrl($scope, DataService, $location)
{

                // Call the service and fetch the list of signatures that match the given action ID
                DataService.getActions(function (results) {
                    $scope.$apply(function () {
                        // Apply the results to the signatureList model so it will refresh the table in the view
                        $scope.actionList = results;
                    });
                });

    }

Any idea why is this happening??
Apart from that once is working (with the second implementation) I would like to show a property of the activity, if I try to get the property like this it does not work:

{{action.get('Action')}}

But if I try to get the whole object like {{action}} I can actually see all the entries.

A: Change the controller to
function MainCtrl($scope, DataService, $location) {

    $scope.getActionList = function() {
        DataService.getActions(function(results) {
                    $scope.$apply(function() {
                                $scope.actionList = results;
                            });
                });

    };

    $scope.getActionList();
}

Then if you want to reload actionList call getActionList()

A:
Any idea why is this happening??

In your first example, you are simply defining a function named actionList on object $scope.  Defining a function won't execute it (see @Arun's answer).
To show your data in the view, you can use normal JavaScript dot notation.  If an action object looks like this:
{ prop1: 'property 1', prop2: [1, 2], prop3: { name: 'Javito'} }

You could write the view/HTML as follows:

      prop1: {{action.prop1}}

      prop2: {{action.prop2[0]}} {{ action.prop2[1] }}

      prop3.name: {{action.prop3.name}}


text:
Q: Why can't zc.buildout find pyconfig.h? I'm running zc.buildout with a simple buildout.cfg file:
[buildout]
parts = python

[python]
recipe = zc.recipe.egg
interpreter = python

I'm getting this error message in CentOS and Ubuntu:
# bin/buildout
Installing python.
Getting distribution for 'python'.
error: Setup script exited with error: pyconfig.h: No such file or directory
An error occurred when trying to install Python 2.5. Look above this message for any   errors that were output by easy_install.
While:
  Installing python.
  Getting distribution for 'python'.
Error: Couldn't install: Python 2.5

The Python development package is definitely installed.  pyconfig.h is in /usr/include/python2.7 on my Ubuntu system.  Do I need to configure buildout differently?

A: I don't think you are using zc.recipe.egg correctly without an 'egg' or 'eggs' option?  You bootstrap (I can only assume) with your system /usr/bin/python2.7 bootstrap.py and then you get error messages about Python 2.5?  The problem seems that buildout is trying to get a package distribution for Python 2.5, which makes no sense.
Try adding an empty eggs= option -- that should work.

A: Looks weird. I'd suspect that there's more in your buildout, especially some extra required package that needs to be compiled. That's the normal case in which buildout (or rather python itself) goes looking header files.
You say that the .h file exists just fine in your python 2.7 directory, but it looks like buildout runs with python 2.5, which cannot use the 2.7 one.
So if you're on ubuntu you'll need to install python2.5's dev package, too.
(But your question still looks weird to me, or rather things seem to be missing).


text:
Q: How to find the total number of the same dictionary value? What is the best way to find the total number of each value in dictionary variable?
This is my dictionary variable.
my_dict = {
        'mike':'football',
        'jack':'basketball',
        'tom':'basketball',
        'keanu':'basketball',
        'jason':'football'
}

And this is the output that i want.
Total number of each value

football : 2
basketball : 3

A: You could use collections.Counter:
from collections import Counter

my_dict = {
        'mike':'football',
        'jack':'basketball',
        'tom':'basketball',
        'keanu':'basketball',
        'jason':'football'
}
print(Counter(my_dict.values()))

Result:
Counter({'basketball': 3, 'football': 2})


text:
Q: How to align Div at right side bottom? Hi I am developing MVC4 application. I have one main div inside that I have three div tags. First two div tags are displaying correctly as per my requirement. However my third div tag appears in right middle. I want it in left bottom side. I tried all the ways.

            <input type="hidden" value="_upload_id" id="id" />

            Select your reason
            <select id="comments">
                <option value="1">Incorrect Document</option>
                <option value="2">document is not clear</option>
                <option value="3">document is not valid</option>
                <option value="4">other document</option>
            </select>
            <input type="button" id="reject" class="btn btn-primary btn-cons blue" value="Ok" onclick="reject();" tabindex="-1" style="float:right;">

Can someone give some insights regarding this? Thank you very much...

A: You can try this:

            <input type="hidden" value="_upload_id" id="id" />

            Select your reason
            <select id="comments">
                <option value="1">Incorrect Document</option>
                <option value="2">document is not clear</option>
                <option value="3">document is not valid</option>
                <option value="4">other document</option>
            </select>

<input type="button" id="reject" class="btn btn-primary btn-cons blue" value="Ok" onclick="reject();" tabindex="-1" style="margin-left:122px;">

A: I think you also need to split the third div into two parts so the right part should align with your second div
Try this :

First DIV

Second div

            <input type="hidden" value="_upload_id" id="id" />

            Select your reason
            <select id="comments">
            <option value="1">Incorrect Document</option>
            <option value="2">document is not clear</option>
            <option value="3">document is not valid</option>
            <option value="4">other document</option>
        </select>

                <input type="button" id="reject" class="btn btn-primary btn-cons blue" value="Ok" onclick="reject();" tabindex="-1" style="float:left;">


text:
Q: Can we invent a machine that produce more force than it takes with levers? For example, a heavy object is lifted by levers and dropped, producing energy with the force of falling (gravity + object), and that heavy object is lifted with less force than it produces, using levers, Can this be possible?

A: no it is not possible. When you lift a mass with a lever an use only say 1/5 of its weight yo can lift it only 1/5 of the height you could lift ist with the fullforcd, so it would drop only 1/5 of the way an you do not gain any energy. The golden rule of mechanics says: the smaller the force, the longer the way of the force, so to lift something a d inch,  you always have the work or energy mgd. The force to lift  mg can be half, than the distance for the force ist 2d.


text:
Q: Issue: ggplot2 replicates last plot of a list in grid I have some 16 plots. I want to plot all of these in  grid manner with ggplot2. But, whenever I plot, I get a grid with all the plots same, i.e, last plot saved in a list gets plotted at all the 16 places of grid. To replicate the same issue, here I am providing a simple example with two files. Although data are entirely different, but plots drawn are similar.
library(ggplot2)
library(grid)
library(gridExtra)
library(scales)

set.seed(1006)
date1<- as.POSIXct(seq(from=1443709107,by=3600,to=1446214707),origin="1970-01-01")
power <- rnorm(length(date1),100,5)#with normal distribution
write.csv(data.frame(date1,power),"file1.csv",row.names = FALSE,quote = FALSE)
# Now another dataset with uniform distribution
write.csv(data.frame(date1,power=runif(length(date1))),"file2.csv",row.names = FALSE,quote = FALSE)
    path=getwd()
    files=list.files(path,pattern="*.csv")
    plist<-list()# for saving intermediate ggplots
    for(i in 1:length(files))
      {
      dframe<-read.csv(paste(path,"/",files[i],sep = ""),head=TRUE,sep=",")
      dframe$date1= as.POSIXct(dframe$date1)
      plist[[i]]<- ggplot(dframe)+aes(dframe$date1,dframe$power)+geom_line()
      }
    grid.arrange(plist[[1]],plist[[2]],ncol = 1,nrow=2)

A: You need to remove the dframe from your call to aes. You should do that anyway because you have provided a data-argument. In this case it's even more important because while you save the ggplot-object, things don't get evaluated until the call to plot/grid.arrange. When you do that, it looks at the current value of dframe, which is the last dataset in your iteration.
You need to plot with:
ggplot(dframe)+aes(date1,power)+geom_line()


text:
Q: Averaged null energy condition for a perfect fluid The energy momentum Tensor for a perfect fluid reads $T^{\mu\nu}=(\rho_0+P)u^\mu u^\nu+Pg^{\mu\nu}$. I should apply now the averaged null energy condition to this energy momentum tensor and derive what it implies. The averaged null energy condition states
\begin{equation*}
\int dx^\lambda \langle T_{\mu\nu}\rangle k_\lambda k^\mu k^\nu \geq 0 .
\end{equation*}
$\langle\rangle$ denotes the expectation value and the integral extends from past to future null infinity. I don't know how to calculate this quantity and would be thankful for any help.