text:
Q: Fastest way to get char* from file in C I have function which gets arguments: char* filedata (stores whole file) and FILE *fp (the opened file).
void read_file(char *filedata, FILE *fp){
  char buffer[1000];

  while(fgets(buffer, sizeof(buffer), fp))
  {
    char *new_str;
    if((new_str = malloc(strlen(filedata) + strlen(buffer)+1)) != NULL)
    {
      new_str[0] = '\0'; // ensures the memory is an empty string
      strcat(new_str, filedata);
      strcat(new_str, buffer);
    }
    else
    {
      printf("malloc failed!\n");
    }
    strcpy(filedata, new_str);
  }

  fclose(fp);
}

But this isn't too fast... is there faster way to read the whole file?

A: Below's my function illustrating how I usually do it. Not sure how fast it is compared to all other possible C implementations. But I'd imagine they're all pretty similar unless poorly programmed in one way or another, which might lead to slower, less efficient execution.
/* ==========================================================================
 * Function:    readfile ( FILE *ptr, int *nbytes )
 * Purpose:     read open file ptr into internal buffer
 * --------------------------------------------------------------------------
 * Arguments:   ptr (I)         FILE * to already open (via fopen)
 *                              file, whose contents are to be read
 *              nbytes (O)      int * returning #bytes in returned buffer
 * --------------------------------------------------------------------------
 * Returns:     ( unsigned char * )  buffer with ptr's contents
 * --------------------------------------------------------------------------
 * Notes:     o caller should free() returned output buffer ptr when finished
 * ======================================================================= */
/* --- entry point --- */
unsigned char *readfile ( FILE *ptr, int *nbytes ) {
  /* ---
   * allocations and declarations
   * ------------------------------- */
  unsigned char *outbuff = NULL;        /* malloc'ed and realloc'ed below */
  int  allocsz=0, reallocsz=500000,     /*total #bytes allocated, #realloc */
       blksz=9900, nread=0,             /* #bytes to read, #actually read */
       buffsz = 0;                      /* total #bytes in buffer */
  /* ---
   * collect all bytes from ptr
   * ----------------------------- */
   if ( ptr != NULL ) {                 /* return NULL error if no input */
    while ( 1 ) {                       /* read all input from file */
      if ( buffsz+blksz + 99 >= allocsz ) { /* first realloc more memory */
        allocsz += reallocsz;           /*add reallocsz to current allocation*/
        if ( (outbuff=realloc(outbuff,allocsz)) == NULL ) /* reallocate */
          goto end_of_job; }            /* quit with NULL ptr if failed */
      nread = fread(outbuff+buffsz,1,blksz,ptr); /* read next block */
      if ( nread < 1 ) break;           /* all done, nothing left to read */
      buffsz += nread;                  /* add #bytes from current block */
      } /* --- end-of-while(1) --- */
    fclose(ptr);                        /* close fopen()'ed file ptr */
    } /* --- end-of-if(ptr!=NULL) --- */
  end_of_job:
    if ( nbytes != NULL ) *nbytes = buffsz; /* #bytes in outbuff */
    return ( outbuff );                 /* back to caller with output or NULL*/
  } /* --- end-of-function readfile() --- */

A: With some caveats, you can read the entire file into an appropriately-sized buffer in one fell swoop using the fread() function.
The following code outlines how to open the file, determine its size, allocate a buffer of that size, then read the file's data (all of it) into that buffer. But note the caveats about the fseek and ftell functions (discussed afterwards):
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char* filename = "MyFile.txt"; // Or whatever
    FILE* fp = fopen(filename, "rb"); // Open in binary mode
    int seek = fseek(fp, 0, SEEK_END); // CAVEAT: Files in BINARY mode may not support SEEK_END ...
    if (seek != 0) {
        printf("Cannot fseek on binary file!\n");
        fclose(fp);
        return 1;
    }
    size_t filesize = (size_t)ftell(fp); // ... but this is not reliable if opened in TEXT mode!
    char* filedata = calloc(filesize + 1, 1); // Add 1 for the terminating "nul" character
    rewind(fp);
    fread(filedata, 1, filesize, fp); // Read whole file

    // Clean up ...
    fclose(fp);
    free(filedata);

    return 0;
}

Caveats:
Note that files opened in BINARY mode (as in the "rb" mode argument I gave in the fopen() call) are not required to support the SEEK_END origin in calls to fseek(); if this is the case on your platform, then this answer offers some alternatives to determine the file's size. From cppreference:

… Binary streams are not required to support SEEK_END, in
particular if additional null bytes are output.

However, on the other hand, opening the file in TEXT mode (using "rt") will make the call to ftell effectively meaningless, in terms of the required size for your input buffer and the value specified to fread; from cppreference:

If the stream is open in text mode, the value returned by this
function is unspecified and is only meaningful as the input to
fseek().

Also note that, as pointed out in the comments, the fseek() and ftell() functions will fail if the size of the file is larger than the maximum value that can be stored in a long int variable; to handle such cases, you can use the (platform-dependent) 64-bit equivalents, as I described in an answer I posted some time ago.

A: Annotating your function (not mentioning the leaks, etc) and counting the operations on the character buffers:

void read_file(char *filedata, FILE *fp){
  char buffer[1000];

  while(fgets(buffer, sizeof(buffer), fp))      // <<-- NEW_SIZE
  {
    char *new_str;
    if((new_str = malloc(strlen(filedata)       // <<-- OLD_SIZE
         + strlen(buffer)                       // <<-- NEW_SIZE
        +1)) != NULL)
    {
      new_str[0] = '\0'; // ensures the memory is an empty string
      strcat(new_str, filedata);                // <<-- OLD_SIZE
      strcat(new_str, buffer);                  // <<-- OLD_SIZE + NEW_SIZE
    }
    else
    {
      printf("malloc failed!\n");
    }
    strcpy(filedata, new_str);                  // <<-- OLD_SIZE + NEW_SIZE
  }

  fclose(fp);
}

fgets(). strlen(), strcat() and strcpy() all need to loop over a character buffer.
Only the fgets() is actually needed, the rest of the copying can be avoided.
Adding the number of passes over the buffers:
sum of operations per loop: 4 * OLD_SIZE + 4 * NEW_SIZE
and: keep in mind that OLD_SIZE is actually SUM(NEW_SIZE), recursively, so your function has
QUADRATIC behavior wrt the number of times the loop iterates.(basically the number of lines read)
So you end up with:
Number of times a character is inspected
    = 4 * N_LINE * LINE_SIZE
    + 8 * (NLINE * (NLINE-1) ) * LINE_SIZE
    ;

, which implies that for a 100 line file you need about 40K passes over the string(s).
[this is the "Schlemiel, the painter" story]


text:
Q: How to give a list as arguments to a function in elisp? I'm trying to learn elisp and emacs customization. I setq'ed a list of arguments to a variable. How do I go about passing this list to a function instead of just giving the arguments directly.
Thanks in advance.

A: Use the apply function:
(apply 'function arglist)

For example:
(apply '+ '(1 2 3 4))
==> 10

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parsing data from one sheet to many others There is one sheet, where all data is listed and there are over 9,000 other sheets that reference to that one and take some of that data.
What I have to do manually now: In every single one of that many, I should write formula in certain cell, that references to our "Data-sheet" and takes certain data. Cell is exactly the same in all sheets. The formula looks like this:
=ListOfData!A1

and for second sheet it looks like:
=ListOfData!A2

...and so forth and so on.
Can I write those formulas in all of the sheets without hardcoding?

A: If I understand what you're needing, here's a quick macro I did for you:
Sub addFormula()
Dim ws As Worksheet
Dim cel As Range

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

For Each ws In ActiveWorkbook.Worksheets
    If ws.Name <> "ListofData" Then
        With ws
            'This places the formula in cell A1 of each sheet. Change as necessary!
            .Cells(1, 1).Formula = "=ListOfData!A" & ws.Index
        End With
    End If
Next ws

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub

Place that in the Workbook module.  What it will do is use the Sheet Index to determine the formula (i.e. the second sheet in the index will have =ListofData!A2 in Cell A1.
To change where your formula goes, edit the .Cells(1,1) to fix that (format is .Cells([Row],[Column]).
Since you have over 9000 sheets, I am hoping to all the gods that their indexes are the same number you want.  If not, you'll need to specify how we know which sheet gets A1, A2,...,A9000 in the formula.
I highly suggest trying this in a copy of the workbook, with say 40 sheets before using this on the large one.


text:
Q: Prevent  from expanding when inserting content I have a table of fixed width and height containing three rows and columns. Rows and columns are automatically equal size, but when I put innerHTML (or image) into table cell, cell with text inside expands at the cost of other columns. How to prevent table cells from expanding after inserting content inside? I've tried solutions from similar stack overflow questions, but nothing worked.
JS fiddle: https://jsfiddle.net/m20akmdx/14/

document.getElementById('8').innerHTML = 'R';
table {
  width: 360px;
  height: 360px;
  border: 1px solid black;
  border-collapse: collapse;
}

td {
  border: 1px solid black;
  text-align: center;
}

A: Try using fixed table layout.
table {
  table-layout: fixed;
  ...
}

And adding a no-break space into each cell.
td:after {
  content: "\00A0";
}

document.getElementById('8').innerHTML = 'R';
table {
  table-layout: fixed;
  width: 360px;
  height: 360px;
  border: 1px solid black;
  border-collapse: collapse;
}

td {
  border: 1px solid black;
  text-align: center;
}

td:after {
  content: "\00A0";
}

A: Set the width and height of the td elements rather than a width and height for the table and you will get the desired behaviour.

document.getElementById('8').innerHTML = 'Raaaa';
table{

  border: 1px solid black;
  border-collapse: collapse;
}
td{
  width:120px;
  height:120px;
  border: 1px solid black;
  text-align: center;
}

A: set a max-width
td{
   border: 1px solid black;
   text-align: center;
   max-width: 200px;
}

or
td{
   border: 1px solid black;
   text-align: center;
   max-width: 30%;
}

A: You will need to specify the td width, and maybe the height as well:
https://jsfiddle.net/m20akmdx/23/

document.getElementById('8').innerHTML = 'my long text gets wrapped';
table {
  width: 360px;
  height: 360px;
  border: 1px solid black;
  border-collapse: collapse;
}

td {
  width: calc(100% / 3);
  height: calc(100% / 3);
  border: 1px solid black;
  text-align: center;
}


text:
Q: Is it possible to work with DateTime value in C++? I'm working with an API which offers date and time data as a double precision decimal value, which is compatible with the Windows Date/Time format.  I'm writing a program in C++ and I'd like to be able to access elements of the data contained within the double Date/Time value and format them as human readable.  For example take the Date/Time value like so 41411.583333 and print a string as DD/MM/YYYY HH:MM:SS using C++.  Please can someone explain if/how this can be done?

A: The COleDateTime class (provided in the MFC and ATL libraries) provides everything you need. It includes a Format member function that can print date/time in numerous formats:
http://msdn.microsoft.com/en-us/library/c1ayhyhk(v=vs.80).aspx

A: There's also the Boost.Date_Time library.  Documentation here.


text:
Q: SQL insert slow on 1 million rows WITH TOP 100000 (100k) this query is finished in about 3 seconds
WITH TOP 1000000 (1mil) this query is finished in about 2 minutes
SELECT TOP 1000000
    db_id = IDENTITY(int, 1, 1), *
INTO dbo.tablename
FROM dbname.dbo.tablename

Actual execution plan is always:
clustered index scan 4% cost
top
top
compute scalar
insert (96% cost)
select into

The table has 1.3 mil rows and has an int primary key on first column
Can I speed it up somehow? I'm using SQL Server 2008 R2.

A: The results showed that 100,000 records takes 159 ms, and 1,000,000 records takes 1,435 ms. On a Raid 1 OS, Raid 1 Data, Raid 1 Log, Raid 1 TempDb all separate drives. Our Dev enviroment.
The results showed that 100,000 records takes 113 ms, and 1,000,000 records takes 996 ms. On my laptop with a single SSD (Samsung 840 250GB). SSD's rock!!!
The results showed that 100,000 records takes 188 ms, and 1,000,000 records takes 1,880 ms. On a Raid 1 OS, Raid 10 Data, Raid 10 Log, Raid 1 TempDb all separate drives under a production load.

A: Here is a complete script that shows that the 1 million takes less than ten times as long as 100,000. Your situation is likely slightly different, but this shows that the fundamentals are not the issue.
The results show that 100,000 records takes 146 ms, and 1,000,000 records takes 1,315 ms.
These results are from my desktop. If someone else could run the script and post their results, that would be very useful.
Rob
USE master;
GO
-- Drop database SourceDB
IF EXISTS (SELECT * FROM sys.databases WHERE name = 'SourceDB') ALTER DATABASE SourceDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
IF EXISTS (SELECT * FROM sys.databases WHERE name = 'SourceDB') DROP DATABASE  SourceDB;
GO
-- Create database SourceDB
CREATE DATABASE SourceDB;
ALTER DATABASE SourceDB SET RECOVERY SIMPLE;
GO
USE SourceDB;
GO
-- Create table SourceDB.dbo.SourceTable
CREATE TABLE dbo.SourceTable (
    ColID int PRIMARY KEY
);
GO
-- Populate table SourceDB.dbo.SourceTable
DECLARE @i int = 0;
WHILE @i < 1300000
BEGIN
    SET @i += 1;
    INSERT INTO dbo.SourceTable (ColID) VALUES (@i);
END;
GO
-- Drop database Test1
IF EXISTS (SELECT * FROM sys.databases WHERE name = 'Test1') ALTER DATABASE Test1 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
IF EXISTS (SELECT * FROM sys.databases WHERE name = 'Test1') DROP DATABASE  Test1;
GO
-- Create database Test1
CREATE DATABASE Test1;
ALTER DATABASE Test1 SET RECOVERY SIMPLE;
ALTER DATABASE Test1 MODIFY FILE (NAME = Test1, SIZE = 3000MB, MAXSIZE = 8TB);
ALTER DATABASE Test1 MODIFY FILE (NAME = Test1_log, SIZE = 3000MB, MAXSIZE = 2TB);
GO
USE Test1;
GO
IF EXISTS (SELECT * FROM sys.tables WHERE [OBJECT_ID] = OBJECT_ID('dbo.DestinationTable1')) DROP TABLE dbo.DestinationTable1;
IF EXISTS (SELECT * FROM sys.tables WHERE [OBJECT_ID] = OBJECT_ID('dbo.DestinationTable2')) DROP TABLE dbo.DestinationTable2;
GO
DECLARE @n  int       = 100000;
DECLARE @t1 datetime2 = SYSDATETIME();
SELECT TOP (@n) db_id = IDENTITY(int, 1, 1), *
INTO dbo.DestinationTable1
FROM SourceDB.dbo.SourceTable;
SELECT DATEDIFF(ms, @t1, SYSDATETIME()) AS ElapsedMs;
GO
DECLARE @n  int       = 1000000;
DECLARE @t1 datetime2 = SYSDATETIME();
SELECT TOP (@n) db_id = IDENTITY(int, 1, 1), *
INTO dbo.DestinationTable2
FROM SourceDB.dbo.SourceTable;
SELECT DATEDIFF(ms, @t1, SYSDATETIME()) AS ElapsedMs;
GO


text:
Q: exporting man pages to postscript I found that I can save man page into ps format:
man -t man > file.ps

or to pdf:
man -t man | ps2pdf - file.pdf

Apart from the man page itself, the export includes man version, page numbers and date.
2.6.2    2012-06-18     1

How can I remove the date ?
How can I configure what is added ?

A: The date is set in the source code for the man page
-bash-4.2$ man -w man
/usr/share/man/man1/man.1.gz
-bash-4.2$ zcat $(man -w man) | fgrep 2012
.TH MAN 1 "2012-09-17" "2.6.3" "Manual pager utils"
-bash-4.2$

Not portably, as OpenBSD for example instead places the date in .Dd
$ man -w man
/usr/share/man/man1/man.1
/usr/share/man/man7/man.7
$ grep 2017 $(man -w 1 man)
.\"     $OpenBSD: man.1,v 1.30 2017/08/19 22:05:22 schwarze Exp $
.\" Copyright (c) 2010, 2011, 2014-2017 Ingo Schwarze <schwarze@openbsd.org>
.Dd $Mdocdate: August 19 2017 $
$

In either case your options are limited; either edit the source to remove or change the date, or write your own troff parser that does the same.


text:
Q: Jenkins pipeline failure due to 'sudo: unknown uid 1001: who are you?' I am trying to deploy my Django application using Jenkins and Django.
I see that pipelines fails on sudo command for UID 1001. However, I have explicitly created a user with UID on docker image. I am quite naive in Docker and Jenkins. Could you help to identify what could have possibly gone wrong?Pipeline steps Users Output on Jenkins
Here is the jenkins script:
void setBuildStatus(String message, String state) {
  step([
      $class: "GitHubCommitStatusSetter",
      reposSource: [$class: "ManuallyEnteredRepositorySource", url: "https://github.com/***"],
      contextSource: [$class: "ManuallyEnteredCommitContextSource", context: "ci/jenkins/build-status"],
      errorHandlers: [[$class: "ChangingBuildStatusErrorHandler", result: "UNSTABLE"]],
      statusResultSource: [ $class: "ConditionalStatusResultSource", results: [[$class: "AnyBuildResult", message: message, state: state]] ]
  ]);
}
node('linux-builder')
{
    def tmpDirName = UUID.randomUUID().toString()
    stage('Linux:Workspace cleanup')
    {
        step([$class: 'WsCleanup'])
    }
    stage('Linux:Repo clone')
    {
        // Clone abc repository
        checkout([$class: 'GitSCM',
            branches: [[name: "master"]],
            extensions: [[$class: 'GitLFSPull']],
            userRemoteConfigs: [[credentialsId: '***',
                 url: 'git@github.com:***']]
        ])
    }
    setBuildStatus("Build pending", "PENDING")
    try
    {
        stage('Run tests')
        {
            sh "cp /home/jenkins/.ansible-vault-key.txt ansible/.ansible-vault-key.txt"
            docker.image('***:2.2').inside('--entrypoint=')
            {
                sh """export CI=jenkins
                      sudo service postgresql start
                      export LC_ALL=C.UTF-8
                      export LANG=C.UTF-8
                      sudo script/bootstrap
                      export CI=jenkins
                      script/deploy master"""
            }
        }
        setBuildStatus("Build succeeded", "SUCCESS");
    }
    catch(e)
    {
        setBuildStatus("Build failed", "FAILURE");
    }
}

The script particularly fails on the postgresql service start command.


text:
Q: Measure time for external API call: handle asynchronism in angular I just need a simple angular application to call an external API (get request) and measure how long the application need to get the data.
My code looked like this:
  measureData(): {
    this.t0 = performance.now();

    this.errors = '';

    this.getHello().subscribe(
      (result: string) =>
        {
          this.text = result
          console.log("test")
          return this.text
        },
        error => {
          this.errors = error.message
          console.log(error.message)
          return this.errors
        }
    )
    this.t1 = performance.now();
    this.test = this.t1 - this.t0;
    console.log("Action took " + this.test + " milliseconds.")
    this.times.push(this.test);
  }

In this case I am in trouble with asynchronism. So I tried this:
main(){
    this.measureData().subscribe(
      (result: String) => {
        this.measurePerformance();
      }
    )
  }

  measureData(): Observable<any> {
    this.t0 = performance.now();

    this.errors = '';

    this.getHello().subscribe(
      (result: string) =>
        {
          this.text = result
          console.log("test")
          return this.text
        },
        error => {
          this.errors = error.message
          console.log(error.message)
          return this.errors
        }
    )
    return
  }

  measurePerformance() {
    this.t1 = performance.now();
    this.test = this.t1 - this.t0;
    console.log("Action took " + this.test + " milliseconds.")
    this.times.push(this.test);
  }

In this case I am getting this error:
ERROR TypeError: Cannot read property 'subscribe' of undefined

A: You can measure the time elapsed with the following:
var start = new Date().getTime();

// Your code
var end = new Date().getTime();

var elapsedTime = end -start;

console.log("Time", elapsedTime );

A: For my solution I used await delay(500).
const delay = ms => new Promise(res => setTimeout(res, ms));

My full code:
async measureData() {

   this.errors = '';
   const delay = ms => new Promise(res => setTimeout(res, ms));

   for (let i = 0; i < this.numberMeasurements; i++) {
     this.t0 = performance.now();
     this.getHello().subscribe(
       (result: string) => {
         this.text = result
         this.t1 = performance.now();
         this.test = this.t1 - this.t0;
         console.log("Action took " + this.test + " milliseconds.")
         this.times.push(this.test);
         console.log(result)
       },
       error => {
         this.errors = error.message
         console.log(error.message)
       }
     )
     await delay(500);
   }

 }


text:
Q: xunit and System.Interactive.Async I am trying to get the unit tests running in my .NET Core 1.0 solution. When I run an empty test it works fine. However, as soon as I try to create new instance of ApplicationDbContext the test fails with the following exception:
  System.IO.FileLoadException : Could not load file or assembly 'System.Interactive.Async, Version=3.0.0.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
  Stack Trace:
       at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServiceCollectionExtensions.AddQuery(IServiceCollection serviceCollection)
       at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServiceCollectionExtensions.AddEntityFramework(IServiceCollection serviceCollection)
       at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<>c__DisplayClass4_0.<GetOrAdd>b__1(Int64 k)
       at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
       at Microsoft.EntityFrameworkCore.DbContext..ctor(DbContextOptions options)
(2 more stack trace lines from my code)

Not sure why the System.Interactive.Async is needed at all, but I added it as dependency to my Tests project. The dll does not seem to be copied to bin\Debug\netcoreapp1.0 folder on build, however. If I copy it there manually the effect it exactly the same. Any ideas what else can I do to get it working?

A: For me this error was being thrown because in my project.json I had correctly added:
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-*",

to use core, but I hadn't removed this line which was further down my file between other dependencies:
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",

Once I deleted that line, I got past this error.

A: I am using SQLite and Entity Framework Core. I was facing the below exception.
Could not load file or assembly 'System.Interactive.Async, Version=3.0.3000.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263' or one of its dependencies

I have installed all necessary packages but it didn't solve.
There is a package named System.Interactive.Async (Ix Async) which can be installed through Nuget
Then my runtime exception was solved.

A: For me it was an errant line

EntityFramework.InMemory

in addition to Microsoft.EntityFrameworkCore.InMemory in project.json. Once I deleted, it started working

A: In my case problem was same as mentioned above - i found forgotten "EntityFramework.MicrosoftSqlServer" dependency in linked project.
To investigate problem, I use my project's project.lock.json. There was 2 packets with System.Interactive.Async.dll - Ix-Async/1.2.5 and System.Interactive.Async/3.0.0.
Then look which packet dependent from Ix-Async (still surfing in project.lock.json) and found that it was EntityFramework.Core/7.0.0-rc1-final . As there was no more packets that depends on EntityFramework.Core I realized that i have EntityFramework.Core in some of my own dependencies (one of my project's project.json)

A: I got a similar issue and I had to update binding redirect in app.config file to point to the appropriate version as shown below:
<dependentAssembly>
    <assemblyIdentity name="System.Interactive.Async" publicKeyToken="94bc3704cddfc263" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.3000.0" newVersion="3.0.1000.0" />
</dependentAssembly>

Look at the oldVersion and newVersion in the above code sample.

A: I'm not 100% sure, but, I think it may be a bug where you need to restart Visual Studio after you have updated NuGet packages such as System.Interactive.Async. I was running into the same error and tried adjusting  the version redirects in App.config. I couldn't get it to work. It kept giving me the error about not being able to load the assembly. It gave me the error even when downgrading the version to what it was looking for and rebuilding. I restarted Visual Studio and then it was all right. The only thing I can think of is maybe the test runner had something cached in memory. I'm using Visual Studio 2017.

A: For those who may be newer, it might be as simple as restoring the NuGet packages at the project level.
In your solution, right click the project and click the Restore Packages option.


text:
Q: read in file in python I have a  function in python that parses in a file that looks like this:
Led Zeppelin
1979 In Through the Outdoor
-In the Evening
-South Bound Saurez
-Fool in the Rain
-Hot Dog
-Carouselambra
-All My Love
-I'm Gonna Crawl

Led Zeppelin
1969 II
-Whole Lotta Love
-What Is and What Should Never Be
-The Lemon Song
-Thank You
-Heartbreaker
-Living Loving Maid (She's Just a Woman)
-Ramble On
-Moby Dick
-Bring It on Home

Bob Dylan
1966 Blonde on Blonde
-Rainy Day Women #12 & 35
-Pledging My Time
-Visions of Johanna
-One of Us Must Know (Sooner or Later)
-I Want You
-Stuck Inside of Mobile with the Memphis Blues Again
-Leopard-Skin Pill-Box Hat
-Just Like a Woman
-Most Likely You Go Your Way (And I'll Go Mine)
-Temporary Like Achilles
-Absolutely Sweet Marie
-4th Time Around
-Obviously 5 Believers
-Sad Eyed Lady of the Lowlands

It is supposed to read in the file until it hits the new line and then stop reading it and print what it has read.  But, for some reason it is stuck in an infinite loop of reading new lines and I cannot pinpoint why.  Would there be a simple fix for this? Maybe something small I am overlooking?  Any help would be greatly appreciated!
def parseData() :
    filename="testdata.txt"
    file=open(filename,"r+")

    while file.read() not in ['\n', '\r\n']:
        album=file.read()
    print album

A: The last line of your read(s) will not return \n but an empty string, to indicate that the file was read completely.
Why not use something like
with open("testdata.txt") as infile:
    lines = infile.readlines()

block = ""
for line in lines:
    if line.strip() == "": break
    block += line

you can then analyze each line separately.

A: For example you can read all file line by line at once to get information which you need.
lines = [line.rstrip('\n') for line in open(filename)]

for x in lines:
    print x

A: file.read() reads the entire file at once and once you have reached the end of the file file.read() will return an empty string. So it's never going to be equal to \n or \r\n and thus never break out of the while loop.
If you want to loop through the lines until the end of a paragraph you can use:
paragraph = ""

for line in f:
    if line in ["\n", "\r\n"]:
        break
    paragraph += line

print(paragraph)

A: Your file.read() is not in ['\n', '\r\n'] as it contains the whole file. You could use:
filename="text.txt"
block = []
for line in open(filename):
    block.append(line)
    if line in ('\n', '\r\n'):
        print(block)
        block=[] # remove if you want to use the content of the block
        break #stops the loop - remove if you want all blocks printed


text:
Q: how to take sum of column of datatype str and group by another column I am trying to calculate sum of column_name "Email" and trying to groupby column_name "country". The error is in converting str to int
Script:
df3 = pd.read_csv('hi.csv',sep = ',')
df3['h1'] = df3['h1'].astype(int)
new_df3=df3.groupby(['country']).h1.sum().to_frame('count').reset_index()
print(new_df3)

Input:
cou h1
A   hi
C   watsup
G   hi

A: try this
df3.groupby('country')['Email1'].count()

there is no need to convert email to int just counting emails should do the work.


text:
Q: trying to overload operator ++ for my date class. still getting the error: cannot increment value of type 'Date' I have written a Date class and Im trying to practice operator overloading on this class. I have tried to overload the operator++ to increment the day by one, but i still get this error: cannot increment value of type 'Date'!
here is my method for overloading this operator:
Date Date::operator++()
{
  day++;
  if (day > days_of_month(month, year)) {
    day = 1;
    month++;
    if (month > 12) {
      month = 1;
      year++;
    }
  }
  return *this;
}

and this is the days_of_month method:
int days_of_month(int m, int y)
{
  if (m < 7)
    return 31;
  else if (m < 12)
    return 30;
  else if (m == 12)
    return is_leap_year(y) ? 30 : 29;
  else
    abort();
}

A: There are two types of incrementation - post-increment and pre-increment. What you've overloaded is the latter and you're trying to use the former.
Usually you provide the two for a class. It looks like this:
Date& Date::operator++() // for ++d
Date Date::operator++(int) // for d++


text:
Q: How to create digitally signed Xml message using standard ISO20022 in java? How to create digitally signed Xml message using standard ISO20022 in java?
xml message like this:
<MessagePayload>
    <AppHdr xmlns="urn:iso:std:iso:20022:tech:xsd:head.001.001.01">
        <CharSet>UTF-8</CharSet>
        <Sgntr></Sgntr>
    </AppHdr>
    <Document xmlns="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.06">
        <FIToFICstmrCdtTrf>
            ...
        </FIToFICstmrCdtTrf>
    </Document>
</MessagePayload>

reference like this:
<Reference URI="#keyInfoId">
    <Transforms>
        <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
    </Transforms>
    <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
</Reference>
<Reference URI="">
    <Transforms>
        <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
        <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
    </Transforms>
    <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
</Reference>
<Reference>
    <Transforms>
        <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
    </Transforms>
    <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
</Reference>

i try the code , but the result is not correct. please help me!!
otherwise, i do not know how to create the reference with no uri , it is not means  but means .


text:
Q: Plugin Development Output I'm trying to put together a plugin of the onScrollBlur effect seen on Medium.
At the moment I am trying to get output of the HTML via a shortcode, but I'm outputting nothing - including the JS and CSS files.
I'm not a PHP specialist, just trying to get a bit better.
<?php
/**
* Plugin Name: OnScrollBlur
* Plugin URI: http://antpowerwebdevelopment.com
* Description: Medium/Twitter style Image Header onScrollBlur,great stylish header for your new build
* Version: 1.0.0
* Author: Ant Power
* Author URI: http://antpowerwebdevelopment.com
*
*/
?>
<?php

// register jquery and style on initialization
add_action('init', 'register_script');
function register_script(){
  wp_register_script( 'script_js', plugins_url('/js/script.js'));
  wp_register_style( 'style_css', plugins_url('/css/style1.css'));
}

// use the registered jquery and style above
add_action('wp_enqueue_scripts', 'enqueue_style');
function enqueue_style(){
  wp_enqueue_script('script_js');
  wp_enqueue_style( 'style_css' );
}

add_action( 'admin_menu', 'register_onScrollPage' );
function register_onScrollPage(){
  add_menu_page( 'onScrollBlur', 'onScrollBlur', 'manage_options',   'onScrollBlur_admin-menu', 'onScollBlur_configure', plugins_url( 'myplugin/images/icon.png' ), 6 );
}

function onScrollBlur(){
  ?>

        Medium

        Everyone's stories and ideas

      Learn more

  <?php
}

add_shortcode('onScrollBlur1', 'onScrollBlur');
?>

A: It appears you are missing your plugin folder when enqueueing your scripts.
plugins_url outputs the URL to your wp plugins folder it does not include your custom plugin folder.
wp_register_script( 'script_js', plugins_url('/YOUR_FOLDER/js/script.js')); // Add your plugin folder
wp_register_script( 'script_js', plugins_url('/js/script.js',__FILE__)); // Let php add your folder

Also you don't need to register your scripts / styles first you can just enqueue them straight up. Registering them first is only useful if they are dependencies of other scripts.
Eg.
add_action('wp_enqueue_scripts', 'enqueue_style');
function enqueue_style(){
  wp_enqueue_script( 'script_js', plugins_url('/js/script.js', __FILE__ ) );
  wp_enqueue_style( 'style_css', plugins_url('/css/style1.css', __FILE__ ) );
}

And now for your shortcode output you need to capture the output with the php function ob_start()
function onScrollBlur(){
  ob_start();
  ?>

        Medium

        Everyone's stories and ideas

      Learn more

  <?php
  return ob_get_clean();
}

You can read more about the Shortcode API here: https://codex.wordpress.org/Shortcode_API#Output


text:
Q: AppleScript how to get current display resolution? I'm trying to get the current display resolution of both of my displays depending on where the mouse cursor is.
i.e. when the mouse cursor is on the first display I want to get the resolution of this display.
With a shell script I can get both resolutions:
set screenWidth to (do shell script "system_profiler SPDisplaysDataType | grep Resolution | awk '{print $2}'")

But I don't get which display is currently "active".
Any ideas?

A: For the sake of even more completeness, here is the code to get the width, height, and Retina scale of a specific display (main or built-in).
This is the code to get the resolution and Retina scale of the built-in display:
set {width, height, scale} to words of (do shell script "system_profiler SPDisplaysDataType | awk '/Built-In: Yes/{found=1} /Resolution/{width=$2; height=$4} /Retina/{scale=($2 == \"Yes\" ? 2 : 1)} /^ {8}[^ ]+/{if(found) {exit}; scale=1} END{printf \"%d %d %d\\n\", width, height, scale}'")

And this is the code to get the resolution and Retina scale of the main display:
set {width, height, scale} to words of (do shell script "system_profiler SPDisplaysDataType | awk '/Main Display: Yes/{found=1} /Resolution/{width=$2; height=$4} /Retina/{scale=($2 == \"Yes\" ? 2 : 1)} /^ {8}[^ ]+/{if(found) {exit}; scale=1} END{printf \"%d %d %d\\n\", width, height, scale}'")

The code is based on this post by Jessi Baughman and the other answers given here.

A: The following does not solve the OP's problem, but may be helpful to those wanting to determine the resolution of ALL attached displays in AppleScript (thanks to @JoelReid and @iloveitaly for the building blocks):
set resolutions to {}
repeat with p in paragraphs of ¬
  (do shell script "system_profiler SPDisplaysDataType | awk '/Resolution:/{ printf \"%s %s\\n\", $2, $4 }'")
  set resolutions to resolutions & {{word 1 of p as number, word 2 of p as number}}
end repeat
# `resolutions` now contains a list of size lists;
# e.g., with 2 displays, something like {{2560, 1440}, {1920, 1200}}

A: For the sake of completeness, here is the code to grab the screen height:
do shell script "system_profiler SPDisplaysDataType | awk '/Resolution/{print $4}'"}

A: Multi-Monitor and Retina detection
To get the width, height and scaling (retina = 2, else = 1) for all monitors:
set resolutions to {}
repeat with p in paragraphs of ¬
    (do shell script "system_profiler SPDisplaysDataType | awk '/Resolution:/{ printf \"%s %s %s\\n\", $2, $4, ($5 == \"Retina\" ? 2 : 1) }'")
    set resolutions to resolutions & {{word 1 of p as number, word 2 of p as number, word 3 of p as number}}
end repeat

get resolutions

Based on answers above.
Results in something like this:
{{2304, 1440, 2}, {1920, 1080, 1}}

A: This does the trick:
tell application "Finder"
set screen_resolution to bounds of window of desktop
end tell

A: Applescript does not have any access to cursor location, even via System Events. Sorry.
[There are a couple commercial solutions, but I'm guessing they're not worth the trouble in this case? I suppose I could also whip up a quick command-line tool that just returns the current cursor location... worth the trouble?]
p.s. awk is great at finding matching lines:
set screenWidth to (do shell script "system_profiler SPDisplaysDataType | awk '/Resolution/{print $2}'")

A: On my machine system_profiler takes nearly a second to return a reply. For my purposes, that way too long.
Pre-10.12, I used ASObjC Runner but apparently that no longer works.
This is much faster for me:
tell application "Finder" to get bounds of window of desktop
(Taken from https://superuser.com/a/735330/64606)

A: I have a shell script that makes use of cliclick and displayplacer, both available in Homebrew: https://github.com/huyz/trustytools/blob/master/mac/get-bounds-of-mouse-display.sh
To use from within AppleScript:
set displayBounds to do shell script "PATH=/opt/homebrew/bin:$PATH /Users/huyz/bin/get-bounds-of-mouse-display | xargs -n 1 echo"
set displayBounds to the paragraphs of displayBounds


text:
Q: Reaplaced AMQ with SQS using JMS but some property values in Message object are null In some old project, I need to replace AMQ with SQS. The problem I have is when I'm receiving the message some "Message" attributes like (getJMSType()) are null for example:
inside the onMessage method I have:
@Override
    public void onMessage(Message message) {
        LOG.info(CLASS_NAME, new Date() + " Message received... ");
        Converter.EVENT_TYPE eventType = null;
        String serviceType = null;
        try {
            if (message instanceof TextMessage) {
                TextMessage txtMsg = (TextMessage) message;
                String onMessageRequestXML = txtMsg.getText();

                serviceType = txtMsg.getJMSType(); <----------------- THESE ONE
                if (serviceType == null) {
                    LOG.warning(CLASS_NAME, "JMS message type is null!");
                    return;
                }
                eventType = converter.getEventType(onMessageRequestXML);
                LOG.info(CLASS_NAME, "Message received is of EventType: " + eventType + " ServiceType : " + serviceType);

                if (serviceType.equalsIgnoreCase(ServiceConstants.MW_METER_MGMT_HOUSEHOLD_UPDATE_REQUEST_JMS_TYPE)) {

In my "message sender" code I set the message content and also the value for JMSType
example:
connection = connectionFactory.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(session.createQueue("nonprod-mbo-sqs-api-hybridcollection-dev-mwcfgsend"));

            String mes = "TEST...";
            TextMessage message = session.createTextMessage(mes);
            message.setJMSType("MW_METER_MGMT_HOUSEHOLD_UPDATE_REQUEST_JMS_TYPE");
            message.setJMSMessageID(""+System.currentTimeMillis());
            producer.send(message);

In my project, I'm using amazon-sqs-java-messaging-lib version 1.0.8.
Have also tried to use SQSTextMessage instead of TextMessage but the result is the same.
Any Idea why the values are not included when I receive the message?


text:
Q: Name Extraction - CV/Resume - Stanford NER/OpenNLP I'm currently on a learning project to extract an individuals name from their CV/Resume.
Currently I'm working with Stanford-NER and OpenNLP which both perform with a degree of success out of the box on, tending to struggle on "non-western" type names (no offence intended towards anybody).
My question is - given the general lack of sentence structure or context in relation to an individuals name in a CV/Resume, am I likely to gain any significant improvement in name identification by creating something akin to a CV corpus?
My initial thoughts are that I'd probably have a more success by sentence splitting, removing obvious text and applying a bit of logic to make a best guess on the individual's name.
I can see how training would work if the a name appears in within a structured sentence, however as a standalone entity without context (Akbar Agho for example) I suspect it will struggle regardless of the training.
Is there a level of AI that if given enough data would begin to formulate a pattern for finding a name or should I maybe just go for applying a level of logic based string extraction?
I'd appreciate people's thoughts, opinions and suggestions.
Side note: I having been using PHP with Appache Tika to do the initial text extraction from Doc/Pdf and am experimenting with Stanford and OpenNLP via PHP/Commandline.
Chris

A: My 2cents on the problem.
So sticking to the NER taggers you listed above will be my first block in the pipeline, if I can identify things there, Viola, no need to go ahead if not then I suggest you go for a Rule Based Approach.
When we speak about a resume, name of a candidate is generally in the top 10% lines of the resume. In many cases it is also followed by "Name : Ankit Solanki " If that fails try to find the email address and match that with different NP pairs you get from other text in the resume, the one with the closest match you find should be your name, As in majority of cases email address of people for professional purpose like a resume will have their name, example john.mayer89abc.com will get cleaned to john.mayer which in turn goes through a algo which will find the closest noun phrase to the cleaned email name.
Let me know your thoughts on this.
Best,
Ankit

A: I guess you'll probably improve name identification if you create a CV corpus, this also depends on the size of your corpus (you could gather such a corpus by crawling CV websites).
Using data mining is probably, in my opinion, your best option. I don't know in details what options are proposed by Apache Tika, but the more information you have on the layout of the CV, the better. For instance, patterns should probably rely on the fact that names are on top of the document, and close to birth date / marital status / image / address.
In that case, you won't be any more in a sequential labelling case (as Stanford NER does): in a CV, a name is usually not surrounded by text. It should most probably be a classification task of candidates segments of text to which patterns may be converted as (numeric or binary) attributes.
Pattern extractor may easily be found or implemented and should be considered as a preprocessing before machine learning. Don't forget, indeed, to also use lists of first and last names (and frequent prefixes / suffixes : -son, -vitch, -man, Ben-, de, etc.) that are indeed unavoidable criteria to decide what segment is likely to be a name. As other names often appear in a CV, this is why I believe using layout should also be an important feature.
I'd be interested to know what features are efficient... would you let us know?


text:
Q: Is my proof of if $B \subseteq A$ then $P(B) \setminus P(A) = \emptyset$ correct? My try:
Suppose $B \subseteq A$.
Further suppose $X \in P(B) \setminus P(A)$. By the definition of the "$\setminus$" operator, we know $X \in P(B)$ and $X \notin P(A)$. By the properties of powerset, we know $X \subseteq B$ and by the properties that we proved, we know $X \subseteq A$. Hence, by the definition of powerset, we got that $X \in P(A)$. But that's a contradiction, because $X \in P(B)$ and $X \notin P(A)$.
Hence, by absurd, we got that $P(A) \setminus P(B) = \emptyset$

A: There is a simple schematic for conditional proofs $P\implies Q$. However, keep in mind, at no point, you can assume anything about the consequent.
You suppose $P$, and show $Q$.
In this case, Suppose: $$B\subseteq A$$
Now, suppose:$$X\subseteq A$$
If $X\subseteq B$, it follows from out assumption, $B\subseteq A$, that $X\subseteq A$.
Therefore, $\forall X\subseteq B$, it follows that $X\subseteq A$.
By definition of power set: $\forall X\subseteq B \implies X\in P(B)$, by the proof above it implies $X\in P(A)$ aswell.
Thus, if all the elements in $P(B)$ are also in $P(A)$, then that implies $P(B)\setminus P(A)=\emptyset$.
Every consequent follows from the antecedent. Which, in turn, follows from the initial assumption. Clear and concise.

A: Your proof by contradiction looks fine to me (once the formatting problems were fixed). I would make one adjustment. Instead of saying:

By the properties of powerset, we know $X \subseteq B$ and by the properties that we proved, we know $X \subseteq A$.

I would word this as:

By the definition of a power set, we know that $X \subseteq B$. But since our initial assumption was that $B \subseteq A$, it follows by the transitivity of the $\subseteq$ relation that $X \subseteq A$.

A: I hope this proof helps:
Prove: $A\subseteq B$ iff $A\setminus B = \emptyset$
Proof:
$\Rightarrow$ Suppose $A\subseteq B$ and $x\in (A\setminus B)$. Then $x\in A$ and $x\in B$ since $A\subseteq B$. So, $x\in A\cap B$ which implies $A\cap B\subseteq B$. Note we can write $$A = (A\cap B)\cup (A\setminus B)$$
then clearly we have $A\setminus B = \emptyset$.
$\Leftarrow$ Conversely, suppose $A\setminus B = \emptyset$, if $x\notin B$ then $x\in A\setminus B = \emptyset$, so $x\in B$ thus $A\subseteq B$.


text:
Q: pandas rename columns with method chaining I have a dataframe and did some feature engineering and now would like to change the column names.
I know how to change them if I do a new assignment but I would like to do it with method chaining. I tried the below (the rename row) but it doesn't work. How could I write it so it works?
df = pd.DataFrame({'ID':[1,2,2,3,3,3], 'date': ['2021-10-12','2021-10-16','2021-10-15','2021-10-10','2021-10-19','2021-10-01'],
                   'location':['up','up','down','up','up','down'],
                   'code':[False, False, False, True, False, False]})

df = (df
     .assign(date = lambda x: pd.to_datetime(x.date))
     .assign(entries_per_ID = lambda x: x.groupby('ID').ID.transform('size'))
     .pivot_table(values=['entries_per_ID'], index=['ID','date','code'],
                   columns=['location'], aggfunc=np.max)
     .reset_index()
     #.rename(columns=lambda x: dict(zip(x.columns, ['_'.join(col).strip() if col[1]!='' else col[0] for col in x.columns.values])))
     )

This here works, but that's not how I would like to write it.
df.columns = ['_'.join(col).strip() if col[1]!='' else col[0] for col in df.columns.values ]

A: Renaming columns in a chain
Use set_axis along axis=1:
df.set_axis(['foo', 'bar', 'baz'], axis=1)

Using groupby, pivot, melt, etc
If the new columns depend on some earlier step in the chain, combine set_axis with pipe. For example, to capitalize pivoted columns in a chain:

*

*We cannot directly chain set_axis:
# does NOT work since df.columns are the original columns, not pivoted columns
df.pivot(...).set_axis(df.columns.str.upper(), axis=1))

*But we can pipe the pivoted result into set_axis:
# does work since we've piped the pivoted df
df.pivot(...).pipe(lambda piv: piv.set_axis(piv.columns.str.upper(), axis=1)))
#                         ^    ^            ^

OP's example
Since OP has created a pivot_table and wants to conditionally collapse those pivoted MultiIndex, we pipe the pivot_table into the list comprehension:
(df.assign(date=pd.to_datetime(df.date))
   .assign(entries_per_ID=df.groupby('ID').ID.transform('size'))
   .pivot_table(index=['ID', 'date', 'code'],
                columns='location',
                values='entries_per_ID',
                aggfunc='max')
   .reset_index()
   .pipe(lambda piv: piv.set_axis(['_'.join(col).strip() if col[1] else col[0] for col in piv.columns],
                                  axis=1)))

#    ID        date   code  entries_per_ID_down  entries_per_ID_up
# 0   1  2021-10-12  False                  NaN                1.0
# 1   2  2021-10-15  False                  2.0                NaN
# 2   2  2021-10-16  False                  NaN                2.0
# 3   3  2021-10-01  False                  3.0                NaN
# 4   3  2021-10-10   True                  NaN                3.0
# 5   3  2021-10-19  False                  NaN                3.0


text:
Q: Generating the output file through java IO I have developed a java code that reads files from the folder chosen by the user. It displays how many lines of code are in each file, it reads only .java filesonly and final outcome is shown on console , I was thinking that output to be get displayed on console but along with a text file conataing the same information to be get stored on desktop also, please advise how to that and the name of the file that is generated its name is to be based on timestamp lets assume that name of the output file would be 'output06282012' and that text file should contain the same information that is shown on the console , here is my piece of code...
public static void main(String[] args) throws FileNotFoundException {

        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("C:" + File.separator));
        chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
                if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
        {      Map<String, Integer> result = new HashMap<String, Integer>();
             File directory = new File(chooser.getSelectedFile().getAbsolutePath());
             int totalLineCount = 0;
             File[] files = directory.listFiles(new FilenameFilter(){
                  @Override
                  public boolean accept(File directory, String name) {
                      if(name.endsWith(".java"))
                      return true;
                    else
                      return false;
                  }
                }
   );
              for (File file : files)
            {
                if (file.isFile())
                {    Scanner scanner = new Scanner(new FileReader(file));
                    int lineCount = 0;
                     try
                    { for (lineCount = 0; scanner.nextLine() != null; lineCount++) ;
                          } catch (NoSuchElementException e)
                    {   result.put(file.getName(), lineCount);
                    totalLineCount += lineCount;
                                    }

                } }
              System.out.println("*****************************************");
              System.out.println("FILE NAME FOLLOWED BY LOC");
              System.out.println("*****************************************");

            for (Map.Entry<String, Integer> entry : result.entrySet())
            {   System.out.println(entry.getKey() + " ==> " + entry.getValue());
            }
            System.out.println("*****************************************");
            System.out.println("SUM OF FILES SCANNED ==>"+"\t"+result.size());
            System.out.println("SUM OF ALL THE LINES ==>"+"\t"+ totalLineCount);

             }

    }

Now the idea in my mind id for this logic
1) construct the file name you want to use
2) open the file for write
3) each time you call a System.out.println(), make a similar call to write the same message to the file
4) when you are all done, make sure you close the file handle.
I have an rough idea something like this
try{

 java.util.Date date= new java.util.Date();
 System.out.println(new Timestamp(date.getTime()));

BufferedWriter out = new BufferedWriter(new FileWriter("C://Desktop//output"+new Timestamp(date.getTime())+".txt"));

out.write("some information");

out.close;

}catch(IOException e){
  e.printStackTrace();
 }

please advise how to that and the name of the file that is generated its name is to be based on timestamp lets assume that name of the output file would be 'output06282012' and that text file should contain the same information that is shown on the console

A: As far as I can tell, this is the only thing you are actually asking:

Please advise how to that and the name of the file that is generated its name is to be based on timestamp.  Lets assume that name of the output file would be 'output06282012' ...

The simple answer is:
    String fileName = "output" + new Date().getTime();

You then go on to say:

.... and that text file should contain the same information that is shown on the console

You've got two choices:

*

*You can change where System.out goes to by calling System.setOut(...).  (Check the javadoc for details.)

*You can create a PrintWriter or PrintStream wrapper for your file stream and write to  that instead of writing to System.out.
In my opinion, it is a bad idea to use System.setOut(...) unless you've got no choice.  It is a "global action" that affects the entire application.  It is better to pass the writer that you want to use as a parameter ...

could you please sow in code as I have done that will clear the understanding

Sorry, I don't write people's programs for them (unless it is an interesting problem!).  You need to write and debug the code yourself, using the information provided in the relevant javadocs.  You can find the Java documentation online on the Oracle website: http://docs.oracle.com/javase/7/docs/


text:
Q: zfs error behind LSI raidcontroller So ZFS is reporting some "read issues", so it would seem that this disk is failing, based on the fact nothing given in the ZFS-8000-9P document reports has occurred we are aware of. These disks are fairly new, the only issue we had recently was a full ZFS.
The ZFS runs on top of a LSI MegaRAID 9271-8i, all disks run "raid 0" per disk. I am not very familiar with this raid card, so I found a script that returns data derived from the megacli command line tool. I added 1 drive to show the setup, they are all setup the same. (system disks are different)
zpool status output
  pool: data
 state: ONLINE
status: One or more devices has experienced an unrecoverable error.  An
        attempt was made to correct the error.  Applications are unaffected.
action: Determine if the device needs to be replaced, and clear the errors
        using 'zpool clear' or replace the device with 'zpool replace'.
   see: http://zfsonlinux.org/msg/ZFS-8000-9P
  scan: none requested
config:

        NAME        STATE     READ WRITE CKSUM
        data        ONLINE       0     0     0
          raidz2-0  ONLINE       0     0     0
            br0c2   ONLINE       0     0     0
            br1c2   ONLINE       0     0     0
            br2c2   ONLINE       0     0     0
            br0c3   ONLINE       0     0     0
            br1c3   ONLINE       0     0     0
            br2c3   ONLINE       0     0     0
            r2c1    ONLINE       0     0     0
            r1c2    ONLINE       0     0     0
            r5c3    ONLINE       0     0     0
            sdb     ONLINE       0     0     0
            sdc     ONLINE       0     0     0
            sdd     ONLINE       0     0     0
            sde     ONLINE       0     0     0
            sdf     ONLINE       0     0     0
            sdg     ONLINE       0     0     0
            r3c1    ONLINE       0     0     0
            r4c1    ONLINE       2     0     0
... cut raidz2-1 ...
errors: No known data errors

The output of LSI script
Virtual Drive: 32 (Target Id: 32)
Name                :
RAID Level          : Primary-0, Secondary-0, RAID Level Qualifier-0
Size                : 3.637 TB
Sector Size         : 512
Is VD emulated      : No
Parity Size         : 0
State               : Optimal
Strip Size          : 512 KB
Number Of Drives    : 1
Span Depth          : 1
Default Cache Policy: WriteBack, ReadAheadNone, Direct, No Write Cache if Bad BBU
Current Cache Policy: WriteBack, ReadAheadNone, Direct, No Write Cache if Bad BBU
Default Access Policy: Read/Write
Current Access Policy: Read/Write
Disk Cache Policy   : Disk's Default
Encryption Type     : None
PI type: No PI

Is VD Cached: No

The script doesn't report any faulty disk, nor does the raidcontroller mark the drive as faulty. I found some other topics zpool error that gave the advice to clear the error and run a scrub. Now my question is, when is the threshold to run a scrub, how long would this take (assuming this zfs raid will take a performance hit for running scrub) Also when this disk is really fautly, will hot-swapping initialize a "rebuild" ?
All the disks are "Western Digital RE 4TB, SAS II, 32MB, 7200rpm, enterprise 24/7/365". Is there a system that will check for zfs errors, since this was just a routine manual check ?
zfs version : 0.6.4.1 zfsonlinux
I know 2 read errors are not allot, but i'd prefer to be replacing disks to early then to late.

A: I'd do what ZFS tells you to do in this case. Please run a scrub.
I scrub my systems weekly on a schedule. I also use the zfswatcher daemon to monitor the health of Linux ZFS installs.
Your ZFS array is probably untuned, so there are some values that can help improve scrubbing performance, but at this point, you should just run it.
And for the other question, your hot swap probably won't do what you expect it to... See rant below.

rant:
Having a bunch of RAID-0 virtual drives behind a hardware controller is a bad idea!
You have the worst of both worlds. Recoverability and error checking is limited. A failed disk is essentially a failed virtual drive and there are hot-swap implications. Let's say you remove the disk(s) in question. You'd likely need to create a new virtual disk or may end up with different drive enumeration.
At a certain point, it's better to get a real HBA and run the disks as try passthrough devices (with no RAID metadata) or just run ZFS on top of vdevs protected by hardware arrays. E.g. run a RAID-6 on your controller and install ZFS on top. Or run multiple RAID-X groups and have ZFS mirror or stripe the resulting vdevs.

A: zfs scrub is the "system that will check for zfs errors". It will take as long as it takes to read all data stored in the volume (going in sequential order of txg, so it can be seeking a lot, depending on how full the pool is and how the data was written). Once started, zfs status will show some estimate. Running scrub can be stopped.
If you want something to periodically check zpool status, the simplest way would be to run something like zpool status | grep -C 100 Status periodically (once a 6 hours) and email the output if any. You could probably find a plugin for your favourite monitoring system, like nagios. Or it'd be pretty straightforward to write yourself.
Just hot swapping the drive will not trigger resilver. You will have to run zfs replace for that to happen.
The read error you are seeing may as well be some kind of controller mishap. Even though it's an enterprise hardware, these (HW RAID) controllers sometimes behave weird. And these errors may, for example, be a result of a command taking too long - controller being busy with whatever. That's why I try to stay away from those unless necessary.
I'd go with checking the SMART data on the drive (see man smartctl) and scrubbing the pool. If both look OK, clear the errors and do not mess with your pool. Because if the pool is near full reading all the data during resilver can actually trigger another error. Start panicing once you see errors on the same drive again ;).
btw. for best performance you should use n^2+2 drives in RAIDZ2 vdevs.


text:
Q: Google Storage signed URL expiration results in 400 error with no CORS headers Long story short: request to expired signed PUT URL response does not include the CORS headers that a successful upload to a non-expired signed PUT URL does.
We operate a service that allows users to upload videos. Our backend API produces a signed Google Storage URLs that the browser-based client application can upload chunks to.
Unfortunately, on slower connections, it's possible for these URLs to expire before they are used. When we use Azure Blob Storage or Amazon S3 as a storage medium, our retry mechanism will detect the failure (403), request a new URL for that particular chunk, and then continue with the upload.
On Google Storage this doesn't work, for one simple reason: while OPTIONS returns successfully, and successful PUT requests include the access-control-allow-origin header, failing uploads (those receiving the 400 status code) do not, and we get the following error logged in the console:

Access to XMLHttpRequest at 'https://storage.googleapis.com/ourbucket/uploads%2F20190308%2F5c822a942d1bd1000183a4a6%2Flawbarnd.mp4_c6b701ce-1687-4fb5-a453-61875c1b6d9a__000007?GoogleAccessId=user@project.iam.gserviceaccount.com&Expires=1552034512&Signature=L6pvUQX5UEa7GESO%2Bj12yR8%2FXln3tz1SDUA%2Bkf1NNx9eTvmUxTdgROYo30p4s%2FGGhXYwr%2BUdgnDuZ66pjX7YS0N5PO5BIr6LULtpR6i2xNC8Y2sKmpv5QF66FHqSBWK0YoLc%2B21MnJMPRgUBSXMcoyWJCJ%2FAapVgRe9QH%2BQt86agf6h0yEmHv48qgVJpzRH%2FbiNJKD7oiOyJc%2Fcon2y2hqsCo6x8buZVuPzTZg6ddHqmqKkscjABoT7bq1%2Bz7Sqkq3Vul%2B5XQfw3CvoNjELpuqVQA%2F0v0RXE86JkOnXf2kQKKlL%2Fq9AwidsEMF05n1LlBVRKSdv8qNKTCVFwBOU%2BMg%3D%3D' from origin 'https://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Our bucket CORS configuration is as follows:
[
    {
        "maxAgeSeconds": 3600,
        "method": ["*"],
        "origin": ["https://www.example.com"],
        "responseHeader": ["*"]
    }
]

Our client-side upload code:
this.bytesUploaded = 0;
this.xhr = new XMLHttpRequest();
this.xhr.open(method, url, true);

let keys = _.keys(headers);
if (keys !== null && keys !== undefined && keys.length > 0) {
    for (let i = 0; i < keys.length; ++i) {
        this.xhr.setRequestHeader(keys[i], headers[keys[i]]);
    }
}

this.xhr.upload.addEventListener('progress', this.onProgress);
this.xhr.addEventListener('load', this.onLoad);
this.xhr.addEventListener('error', this.onError);
this.xhr.addEventListener('abort', this.onAbort);

this.xhr.setRequestHeader('Content-Type', ' '); // we unset this because it interferes with signed URLs. This works fine.

this.xhr.send(this.data);

Response headers from a successful request (via Fiddler):
HTTP/1.1 200 OK
X-GUploader-UploadID: AEnB2UrZdsd-DAl0VdYOtKGVD_4AJLf6qeukybq0jBSv5HI5M4fRTqFVnoxko5LJBMttKYz8ExXG1c3BeASH4IuO8iKfCBb-iw
ETag: "87a742c72cc29950f03e5dd86dc95cf4"
x-goog-generation: 1552036072503518
x-goog-metageneration: 1
x-goog-hash: crc32c=u2rTqA==
x-goog-hash: md5=h6dCxyzCmVDwPl3Ybclc9A==
x-goog-stored-content-length: 239170
x-goog-stored-content-encoding: identity
Access-Control-Allow-Origin: https://www.example.com
Access-Control-Expose-Headers: *, Content-Length, Content-Type, Date, Server, Transfer-Encoding, X-GUploader-UploadID, X-Google-Trace
Vary: Origin
Content-Length: 0
Date: Fri, 08 Mar 2019 09:07:52 GMT
Server: UploadServer
Content-Type: text/html; charset=UTF-8
Alt-Svc: quic=":443"; ma=2592000; v="46,44,43,39"

Response from a failing request (via Fiddler):
HTTP/1.1 400 Bad Request
X-GUploader-UploadID: AEnB2UpjxOthcO6AZgBgw_P8Msw1zeZFkEqMhEWF5pV9jPORajlBnizndw48WSBtW_Ft9G7NOHu_HWxjgywpG7dqhZ0QUz8znA
Content-Type: application/xml; charset=UTF-8
Content-Length: 202
Date: Fri, 08 Mar 2019 09:01:39 GMT
Server: UploadServer
Alt-Svc: quic=":443"; ma=2592000; v="46,44,43,39"

<?xml version='1.0' encoding='UTF-8'?><Error>ExpiredToken<Message>The provided token has expired.</Message>Request signature expired at: 2019-03-08T09:01:24+00:00</Error>

Is there a configuration option we're missing on the bucket? Is there a way we can ignore CORS in case of failure in order to extract the failing status code? At the moment we only receive -1 which isn't helpful.
Edit in response to Yasser Karout's question:
The browser, to complete the XHR PUT request, first makes a pre-flight OPTIONS call:
OPTIONS https://storage.googleapis.com/example-com-media/uploads%2F20190404%2F5ca556b3d72f640001981487%2Fu1equspb.mp4_2c69f05f-0cb7-4c08-bd20-3858b06f6d51__000005?GoogleAccessId=example-com-media@stalwart-kite-714.iam.gserviceaccount.com&Expires=1554339568&Signature=IWjzT0D3Vxzw96JSTwqclhlJWZ%2B%2FBHYviL9SPnZCT3c5P2%2FSqJaq0Grxc%2BpDNLQ2DABH7LdnINR1ZJWF5TMsHoVyWwcwF5OnOqJiKUaGldKos0XFqwXMWo4c%2F7RN1fnKqBkfeSoQXccqwIxr19fh6NYojc09wDwAggcqmBYPmLv7g%2Bui%2FtkEyRTqs4%2Fw4Csl5kmXcOJliX9EWlOmsaJKlFXOmeQEM1IePtBBf4hjJJ%2FnKeRjfdjdmz1d%2BZ1F2LP6qGHCe5ay%2FSn7%2Fw23GfAaWZHFlcevLxgNuu0dpRW4yN6dTjckpgRonXYupGizMDzkQ7K6d1rKEl5bSpXBROMp7Q%3D%3D HTTP/1.1
Host: storage.googleapis.com
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: PUT
Origin: https://www.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
X-Client-Data: CJW2yQEIpLbJAQjEtskBCKmdygEIqKPKAQi8pMoBCLGnygEI4qjKAQjxqcoB
Referer: https://www.example.com/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.9,ja;q=0.8

The response to this is 200 OK and does include the CORS headers:
HTTP/1.1 200 OK
X-GUploader-UploadID: AEnB2UqxbjqsngYYKdvLmrHj21htyUusQkR2W3tge38fMd30TehyRy7wDDmq6U9a7oYIL1OCGJP9hw3uXNVFH8_qbIR-Skhpag
Access-Control-Allow-Origin: https://www.example.com
Access-Control-Max-Age: 3600
Access-Control-Allow-Methods: PUT
Access-Control-Allow-Headers: content-type
Vary: Origin
Date: Thu, 04 Apr 2019 01:00:39 GMT
Expires: Thu, 04 Apr 2019 01:00:39 GMT
Cache-Control: private, max-age=0
Content-Length: 0
Server: UploadServer
Content-Type: text/html; charset=UTF-8
Alt-Svc: quic=":443"; ma=2592000; v="46,44,43,39"

Because this is OK the browser then makes the PUT request:
PUT https://storage.googleapis.com/example-com-media/uploads%2F20190404%2F5ca556b3d72f640001981487%2Fu1equspb.mp4_2c69f05f-0cb7-4c08-bd20-3858b06f6d51__000005?GoogleAccessId=example-com-media@stalwart-kite-714.iam.gserviceaccount.com&Expires=1554339568&Signature=IWjzT0D3Vxzw96JSTwqclhlJWZ%2B%2FBHYviL9SPnZCT3c5P2%2FSqJaq0Grxc%2BpDNLQ2DABH7LdnINR1ZJWF5TMsHoVyWwcwF5OnOqJiKUaGldKos0XFqwXMWo4c%2F7RN1fnKqBkfeSoQXccqwIxr19fh6NYojc09wDwAggcqmBYPmLv7g%2Bui%2FtkEyRTqs4%2Fw4Csl5kmXcOJliX9EWlOmsaJKlFXOmeQEM1IePtBBf4hjJJ%2FnKeRjfdjdmz1d%2BZ1F2LP6qGHCe5ay%2FSn7%2Fw23GfAaWZHFlcevLxgNuu0dpRW4yN6dTjckpgRonXYupGizMDzkQ7K6d1rKEl5bSpXBROMp7Q%3D%3D HTTP/1.1
Host: storage.googleapis.com
Connection: keep-alive
Content-Length: 1332887
Pragma: no-cache
Cache-Control: no-cache
Origin: https://www.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36
Content-Type:
Accept: */*
X-Client-Data: CJW2yQEIpLbJAQjEtskBCKmdygEIqKPKAQi8pMoBCLGnygEI4qjKAQjxqcoB
Referer: https://www.example.com/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.9,ja;q=0.8

viewing the HTTP request in Telerik's Fiddler I can see the following response:
HTTP/1.1 400 Bad Request
X-GUploader-UploadID: AEnB2UqdCe0t1tcfu_vgw7xirkbY6ACX_rZRac4UuufCU5vLufAsFQIQ06uNuE7zzCg7u8OXZN0aEu5ygD7TAJdqv4kVkBDf0w
Content-Type: application/xml; charset=UTF-8
Content-Length: 202
Date: Thu, 04 Apr 2019 01:00:39 GMT
Server: UploadServer
Alt-Svc: quic=":443"; ma=2592000; v="46,44,43,39"

<?xml version='1.0' encoding='UTF-8'?><Error>ExpiredToken<Message>The provided token has expired.</Message>Request signature expired at: 2019-04-04T00:59:28+00:00</Error>

So to answer Yasser's question: yes a 400 status code is returned, but because the CORS headers are not present, that response is never supplied to the calling Javascript code by the browser, so it's impossible to know why the request failed. All it's safe to say is that the request failed.

A: Thanks for clarifying. After looking into this further, it's looking like this is the expected behavior currently for an expired signed URL. The header 'Access-Control-Allow-Origin' header is not present causing the error.
There is an open Feature Request for this, which is also linked to an internal feature request with the Storage Team. I will provide this Stack post as an extra use case internally as well.


text:
Q: Como ordernar um relacionamento hasMany com base em um relacionamento hasOne contido no segundo nível no Laravel? Possuo a classe Perguntas que tem um relacionamento hasMany com a classe Respostas (Uma pergunta pode ter várias respostas). A classe Respostas possui um relacionamento hasOne com a classe categoria (cada resposta pertence a uma categoria).
class Perguntas
{
    public function respostas()
    {
         return $this->hasMany(Respostas::class, 'pergunta_id', 'id');
    }

    public function tags()
    {
         return $this->hasMany(Tags::class, 'pergunta_id', 'id');
    }

}

class Respostas
{
    public function categoria()
    {
         return $this->hasOne(Categorias::class, 'id', 'categoria_id');
    }

}

Realizando a consulta abaixo:
$perguntas = Perguntas::with(['respostas.categoria', 'tags'])->latest()->paginate(10);

Como eu posso obter o vetor de respostas ordenado de acordo com o nome da categoria?

A: Para pegar só as respostas ordenadas pela categoria da para usar o método sortBy(), ficando assim:
$respostas = Resposta::with("categoria")->get()->sortBy(fn ($resposta) => $resposta->categoria->name)->values();

O sortBy() recebe um parâmetro podendo ser uma função anônima, com isso, dá para acessar a categoria da resposta. Nesse exemplo eu ordenei baseado no campo name da categoria.
Se você quiser colocar essa ordenação na mesma query onde você pega as perguntas, ficaria algo assim:
$perguntas = Pergunta::with(['respostas.categoria', 'tags'])->latest()->paginate(10);

$perguntasCollection = $perguntas->getCollection();

$perguntasOrdenadas = $perguntasCollection->map(function ($item) {
    $item->respostas->sortBy(fn ($resposta) => $resposta->categoria->name)->values();
    return $item;
})->values();

O método paginate() retorna um objeto do tipo Illuminate\Pagination\LengthAwarePaginator e para pegar os resultados como uma collection é preciso usar o método getCollection(). Após isso é só colocar o mesmo trecho de código usado para ordenar as respostas dentro de uma funcao map().
Ou então, se você quiser mudar sua paginação para depois de executar a query toda, ficaria assim:
$perguntas = Pergunta::with(['respostas.categoria', 'tags'])->latest()->get();

$perguntasOrdenadas = $perguntas->map(function ($item) {
    $item->respostas->sortBy(fn ($resposta) => $resposta->categoria->name)->values();
    return $item;
})->forPage(1,10);


text:
Q: collectionView divided into three lines swift 4 I need to create a collectionView to display a series of images, individually for each photo. I'm trying to reproduce what you see in the picture, view a photo and then scroll left or right for the next. I can not create the layout of the collectionView

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.datasource.count
}

//UICollectionViewDelegateFlowLayout - constraint della collecion view da innestare
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = (UIScreen.main.bounds.size.width - 3) / 3
    let height = width
    return CGSize(width: width, height: height)
}

A: swift 4:
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

     //calculation of cell size
    return CGSize(width: self.collectionview.frame.size.width,height: 180)
      }

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    // indentation
    return UIEdgeInsetsMake(0, 23, 20, 20)
    }

If you want to drag to horizontal or vertical, in collectionview there is a "scroll Direction" attribute. You can change it to horizontal or vertical.


text:
Q: @RequestMapping in spring i'm new in spring mvc and i don't understand how to use the annotation @RequestMapping.
this's the code of the controller login:
 @Controller
 @RequestMapping(value="/")
 public class LoginController {
       protected final Logger log = Logger.getLogger(LoginController.class);

       @Autowired // The authenticate service is automatically injected into this controller
       private AuthenticateService service;

       @RequestMapping(value = "{pathLogin}", method = RequestMethod.GET)
       public String initFrom(@PathVariable("pathLogin") String path) {
            log.info("Return on log view...."+path);
            return "login";
        }

       @RequestMapping(value = "{pathOnSubmit}", method = RequestMethod.POST)
       public String onSubmit(@RequestParam("username") String username,
                          @RequestParam("password") String password,  @PathVariable("pathOnSubmit") String path, HttpServletRequest request) {
          String message = "Invalid credential or Inexistent Username";
          if(!service.authentification(username, password)) {
               path = "login";
               return "login";
          }else {
             path = "homePage";
             return "homePage";
          }
        }

And the form in login.jsp is:
    <form method="post" action="">
          //here some input for the form
    </from>

when i make a GET request in URL:"http:/...../Project_administration/login.htm" everything it's okay. But when i submit making a POST request, in the controller if i put the correct username and password, ELSE block is execute and the request is forwarding in "/WEB-INF/jsp/homePage.jsp" in InternalResourceView. The problem is The URL, which didn't change in "http:/...../Project_administration/homePage.htm". I don't known why.
Someone can help??
Thank...


text:
Q: How to subset a data after intersecting in shiny I have 3 sets of data taken from URL and 1 user input CSV file. All 4 datasets are yearly, and the time period available is different. I want all 4 data for the same period for my further calculation. I did some checking and found I could intersect the 4 data (GTA, SST, DMI, and AMP) and subset using the intersected result. This is how did it in r.
n <- intersect(intersect(intersect(AMP$Year,SST$Year), GTA$Year),DMI$Year)
AMP1 <- subset(AMP, Year %in% intersect(AMP$Year,n))

I want this in my shiny App. This is a portion of my shiny App that I created to subset my data. I worked out the intersect part. Now I need help with how to subset my data using my intersected column?
library(shiny)
library(data.table)

a <- fread('https://www.cpc.ncep.noaa.gov/data/indices/sstoi.indices',header = TRUE)
b <- as.matrix(a[,c(1,2,9)])
df <- data.frame( Year = b[,1],month = b[,2], value = b[,3])
SS <- df %>% filter(!between(month, 4, 10)) %>%
  arrange(Year, month) %>%
  filter(!(Year == min(Year) & month %in% 1:3 |
             Year == max(Year) & month %in% 11:12)) %>%
  group_by(grp = cumsum(month == 11)) %>%
  summarise(Year = last(Year),
            value = mean(value)) %>%
  select(-grp)

SST <- as.matrix(SS)

d <- fread('https://www.metoffice.gov.uk/hadobs/hadcrut4/data/current/time_series/HadCRUT.4.6.0.0.annual_ns_avg.txt',
           header = FALSE)

GTA <- as.matrix(d[,1:2])

dat <- fread('https://psl.noaa.gov/gcos_wgsp/Timeseries/Data/dmi.had.long.data',header = FALSE,fill = TRUE)
e <- dat[,c(1,7:12)][complete.cases(dat[,c(1,7:12)]),]
f <- matrix(as.numeric(unlist(e)),nrow=nrow(e))
g <- replace(f, f== -9999.000, NA)
h <- g[complete.cases(g),]
me = rowMeans(h[,2:7],na.rm = T)

DMI <- as.matrix(data.frame(Year = h[,1],value = me))

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      fileInput("file", "Choose observation precipitation CSV File", accept = ".csv"),
      checkboxInput("header", "Header", TRUE),
    ),
    mainPanel(
      tableOutput('ID')
    )
  )
)
server <- function(input, output,session) {

  inputdata <- reactive({
    infile = input$file
    if(is.null(infile))
      return(NULL)
    df <- read.csv(infile$datapath,header=input$header)
    return(df)
  })
  output$ID <- renderTable({
    req(inputdata())
    AMP <- as.matrix(inputdata())
    n <- intersect(intersect(intersect(AMP[,1],SST[,1]), GTA[,1]),DMI[,1])
  return(n)
  })

}

shinyApp(ui, server)

The AMP data is user input, but it can be taken as below.
set.seed(123)
df1 <- data.frame(year = rep(1971:2013),value = rnorm(43))

If a there better way to do this, I am all ears. I didn't find a lot on comparing more than 2 data frames in r.
Any help would be appreciated. Thank you.

A: Maybe you can try this -
library(shiny)
library(data.table)

a <- fread('https://www.cpc.ncep.noaa.gov/data/indices/sstoi.indices',header = TRUE)
b <- as.matrix(a[,c(1,2,9)])
df <- data.frame( Year = b[,1],month = b[,2], value = b[,3])
SS <- df %>% filter(!between(month, 4, 10)) %>%
  arrange(Year, month) %>%
  filter(!(Year == min(Year) & month %in% 1:3 |
             Year == max(Year) & month %in% 11:12)) %>%
  group_by(grp = cumsum(month == 11)) %>%
  summarise(Year = last(Year),
            value = mean(value)) %>%
  select(-grp)

SST <- as.matrix(SS)

d <- fread('https://www.metoffice.gov.uk/hadobs/hadcrut4/data/current/time_series/HadCRUT.4.6.0.0.annual_ns_avg.txt',
           header = FALSE)

GTA <- as.matrix(d[,1:2])

dat <- fread('https://psl.noaa.gov/gcos_wgsp/Timeseries/Data/dmi.had.long.data',header = FALSE,fill = TRUE)
e <- dat[,c(1,7:12)][complete.cases(dat[,c(1,7:12)]),]
f <- matrix(as.numeric(unlist(e)),nrow=nrow(e))
g <- replace(f, f== -9999.000, NA)
h <- g[complete.cases(g),]
me = rowMeans(h[,2:7],na.rm = T)

DMI <- as.matrix(data.frame(Year = h[,1],value = me))

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      fileInput("file", "Choose observation precipitation CSV File", accept = ".csv"),
      checkboxInput("header", "Header", TRUE),
    ),
    mainPanel(
      tableOutput('ID')
    )
  )
)
server <- function(input, output,session) {

  inputdata <- reactive({
    infile = input$file
    if(is.null(infile))
      return(NULL)
    df <- read.csv(infile$datapath,header=input$header)
    df
  })
  output$ID <- renderTable({
    req(inputdata())
    AMP <- as.matrix(inputdata())
    n <- intersect(intersect(intersect(AMP[,1],SST[,1]), GTA[,1]),DMI[,1])
    AMP1 <- AMP[AMP[, 1] %in% n, ]
    AMP1
  })

}

shinyApp(ui, server)


text:
Q: can you deploy applications written in smalltalk/squeak/pharo like a Java app? Recently I've been exploring the world of smalltalk dialects and am very impressed (from here on in understand that when I write 'smalltalk' I'm referencing any of the modern smalltalk dialects - squeak/pharo/etc). I like the small footprint of the VM and the language itself.
As grad student and often need to write tools that support my research. Typically I use Java because I can easily deploy a tool to my colleagues without worrying too much about what their computer setup is or how tech savvy they are. It's pretty easy to whip up a GUI interface and all the end user has to do is double click on an executable JAR and they are gtg. The problem is that Java has all sorts of security issues and doesn't always run in the same way on every platform. Smalltalk, therefore, is starting to look pretty attractive.
I know that it's possible to create a smalltalk program that fires up with one double click of an icon. What I'm wondering about is whether or not I can create a sandboxed smalltalk world such that the only thing the user sees and is able to interact with is my application. I don't want them to see any aspect of the smalltalk world. This way, users  can't accidentally muck things up or get confused because they have access to a plethora of options that aren't directly relevant to use of the program. Is this possible, and if so, how do I do it?

A: Apologies - I should've done a better job of RTFM prior to posting this question. It is apparently possible to do this via Lockdown:
http://map.squeak.org/sm/packagebyname/lockdown
Also helpful:
http://wiki.squeak.org/squeak/3563

A: In Pharo, you can send openWorldWithSpec to your UI so that it is full screen. An example of this is the Pharo Launcher: https://ci.inria.fr/pharo-contribution/job/PharoLauncher. When you launch this image, you can't access the rest of Pharo (at least, not easily).