text:
Q: Error uploading a file with TUSD to Cloudflare R2 I am trying to use tus-js-client with TUSD Docker image to upload a file to Cloudflare R2.
I've used the same docker-compose.yml to upload to AWS S3 bucket successfully, like shown.
TUSD provides a way to upload a file using a S3 compatible endpoint with -s3-endpoint parameter and Cloudflare R2 provides such endpoint and the credentials needed (Access Key ID and Secret Access Key).
When the file is sended by the frontend app the first request worked fine, creating the metadata .info file into the R2 bucket.
The problem begins with the subsequent requests to upload the file chuncks.
Looking the request at the console there is no response with a status code. The error below is presented by the tus-js-client. The next retry is a HEAD request and returns a 404 status code.
I've tried at first with a start a nginx reverse proxy with -behind-proxy=true and after the error I tried with -behind-proxy=false. Nothing changed.
I removed the nginx and tried again only with tusd server. Nothing changed too.
tus-js-client error
Error: tus: failed to upload chunk at offset 0, caused by [object ProgressEvent], originated from request (method: PATCH, url: http://12.23.45.67/files/3087adfc92d0d045b5b28c73ee32289a+ALtBKUtgElTHNGK2gGlbb4K9ne0uZmmAQdXz7mFZrvAAZkACIDmLY+0L+DvFlSwksYLGtil11ve/LH5UqOKoxvywNSKzLZHX8IwEkplpOk935LDJQTVBANm5PILybEhgcCwPrH3039iCaoa7QOKM4XfOFroZ0p7RO7FPaKrgys97n+h5vXBD87KiFcl2RDUnUdS2UkA1I1YXrCeSd87Yi3nzK2wBWjBPm3PX94ltujtvtVXOPU3pIO7sEaPZQBDGxxLdBStxVFnMNYMfxuiBKiF/9RkEw7kcWdGGApfmG5FvYNfBfM3sF/Wl/BYHw0HwfA==, response code: n/a, response text: n/a, request id: n/a)

TUSD log
tus_1  | [tusd] 2022/10/29 01:56:01.822078 Using 0.00MB as maximum size.
tus_1  | [tusd] 2022/10/29 01:56:01.822475 Using 0.0.0.0:1080 as address to listen.
tus_1  | [tusd] 2022/10/29 01:56:01.822804 Using /files/ as the base path.
tus_1  | [tusd] 2022/10/29 01:56:01.823180 Using /metrics as the metrics path.
tus_1  | [tusd] 2022/10/29 01:56:01.823545 Supported tus extensions: creation,creation-with-upload,termination,concatenation,creation-defer-length
tus_1  | [tusd] 2022/10/29 01:56:01.824120 You can now upload files to: http://0.0.0.0:1080/files/
tus_1  | [tusd] 2022/10/29 01:56:15 event="RequestIncoming" method="POST" path="" requestId=""
tus_1  | [tusd] 2022/10/29 01:56:16 event="UploadCreated" id="54a4a47b064f1d1033c6a2ab31b5f08d+AO8ImmEviOzNx4pKspyfdIAO/LhLOo89yfvbMmgpyyrewhAmEGeO0sNici3idH/wBqomvVuItdUUWecHMKAdf4U0P+rqDSajq6LRE8pxmbS/aB++tChiN93FEtpMIZUXIyQOFq9L/cspKb1ocUzzXBFdR1n+EAjLwi8mJ3Sqw6Dj9CRxff9jQ7WkRgHOGUeYebLXTzNZnNvv86IWDCekPCPj1BoztjPM2nS7+1HYABHShcOfioQ6C42rYUkfLWV4eU4yRClMMemvql+FjgdtTOrQrjASEj8SRbjr3Rvhs3iix3h7peqs5p2gUvGvhrbw/g==" size="1053651" url="http://52.87.247.28/files/54a4a47b064f1d1033c6a2ab31b5f08d+AO8ImmEviOzNx4pKspyfdIAO/LhLOo89yfvbMmgpyyrewhAmEGeO0sNici3idH/wBqomvVuItdUUWecHMKAdf4U0P+rqDSajq6LRE8pxmbS/aB++tChiN93FEtpMIZUXIyQOFq9L/cspKb1ocUzzXBFdR1n+EAjLwi8mJ3Sqw6Dj9CRxff9jQ7WkRgHOGUeYebLXTzNZnNvv86IWDCekPCPj1BoztjPM2nS7+1HYABHShcOfioQ6C42rYUkfLWV4eU4yRClMMemvql+FjgdtTOrQrjASEj8SRbjr3Rvhs3iix3h7peqs5p2gUvGvhrbw/g=="
tus_1  | [tusd] 2022/10/29 01:56:16 event="ResponseOutgoing" status="201" method="POST" path="" requestId=""
tus_1  | [tusd] 2022/10/29 01:56:16 event="RequestIncoming" method="OPTIONS" path="54a4a47b064f1d1033c6a2ab31b5f08d+AO8ImmEviOzNx4pKspyfdIAO/LhLOo89yfvbMmgpyyrewhAmEGeO0sNici3idH/wBqomvVuItdUUWecHMKAdf4U0P+rqDSajq6LRE8pxmbS/aB++tChiN93FEtpMIZUXIyQOFq9L/cspKb1ocUzzXBFdR1n+EAjLwi8mJ3Sqw6Dj9CRxff9jQ7WkRgHOGUeYebLXTzNZnNvv86IWDCekPCPj1BoztjPM2nS7+1HYABHShcOfioQ6C42rYUkfLWV4eU4yRClMMemvql+FjgdtTOrQrjASEj8SRbjr3Rvhs3iix3h7peqs5p2gUvGvhrbw/g==" requestId=""
tus_1  | [tusd] 2022/10/29 01:56:16 event="ResponseOutgoing" status="200" method="OPTIONS" path="54a4a47b064f1d1033c6a2ab31b5f08d+AO8ImmEviOzNx4pKspyfdIAO/LhLOo89yfvbMmgpyyrewhAmEGeO0sNici3idH/wBqomvVuItdUUWecHMKAdf4U0P+rqDSajq6LRE8pxmbS/aB++tChiN93FEtpMIZUXIyQOFq9L/cspKb1ocUzzXBFdR1n+EAjLwi8mJ3Sqw6Dj9CRxff9jQ7WkRgHOGUeYebLXTzNZnNvv86IWDCekPCPj1BoztjPM2nS7+1HYABHShcOfioQ6C42rYUkfLWV4eU4yRClMMemvql+FjgdtTOrQrjASEj8SRbjr3Rvhs3iix3h7peqs5p2gUvGvhrbw/g==" requestId=""
tus_1  | [tusd] 2022/10/29 01:56:16 event="RequestIncoming" method="PATCH" path="54a4a47b064f1d1033c6a2ab31b5f08d+AO8ImmEviOzNx4pKspyfdIAO/LhLOo89yfvbMmgpyyrewhAmEGeO0sNici3idH/wBqomvVuItdUUWecHMKAdf4U0P+rqDSajq6LRE8pxmbS/aB++tChiN93FEtpMIZUXIyQOFq9L/cspKb1ocUzzXBFdR1n+EAjLwi8mJ3Sqw6Dj9CRxff9jQ7WkRgHOGUeYebLXTzNZnNvv86IWDCekPCPj1BoztjPM2nS7+1HYABHShcOfioQ6C42rYUkfLWV4eU4yRClMMemvql+FjgdtTOrQrjASEj8SRbjr3Rvhs3iix3h7peqs5p2gUvGvhrbw/g==" requestId=""
tus_1  | [tusd] 2022/10/29 01:56:17 event="RequestIncoming" method="PATCH" path="54a4a47b064f1d1033c6a2ab31b5f08d+AO8ImmEviOzNx4pKspyfdIAO/LhLOo89yfvbMmgpyyrewhAmEGeO0sNici3idH/wBqomvVuItdUUWecHMKAdf4U0P+rqDSajq6LRE8pxmbS/aB++tChiN93FEtpMIZUXIyQOFq9L/cspKb1ocUzzXBFdR1n+EAjLwi8mJ3Sqw6Dj9CRxff9jQ7WkRgHOGUeYebLXTzNZnNvv86IWDCekPCPj1BoztjPM2nS7+1HYABHShcOfioQ6C42rYUkfLWV4eU4yRClMMemvql+FjgdtTOrQrjASEj8SRbjr3Rvhs3iix3h7peqs5p2gUvGvhrbw/g==" requestId=""
tus_1  | [tusd] 2022/10/29 01:56:17 event="RequestIncoming" method="HEAD" path="54a4a47b064f1d1033c6a2ab31b5f08d+AO8ImmEviOzNx4pKspyfdIAO/LhLOo89yfvbMmgpyyrewhAmEGeO0sNici3idH/wBqomvVuItdUUWecHMKAdf4U0P+rqDSajq6LRE8pxmbS/aB++tChiN93FEtpMIZUXIyQOFq9L/cspKb1ocUzzXBFdR1n+EAjLwi8mJ3Sqw6Dj9CRxff9jQ7WkRgHOGUeYebLXTzNZnNvv86IWDCekPCPj1BoztjPM2nS7+1HYABHShcOfioQ6C42rYUkfLWV4eU4yRClMMemvql+FjgdtTOrQrjASEj8SRbjr3Rvhs3iix3h7peqs5p2gUvGvhrbw/g==" requestId=""

docker-compose.yml
version: '2'

services:
    tus:
        image: tusproject/tusd
        command: -s3-bucket=my-bucket -behind-proxy=false -s3-endpoint=https://abcdef.r2.cloudflarestorage.com
        environment:
            - AWS_ACCESS_KEY_ID=XXXXXXXXXXXXXXXXXXXXX
            - AWS_SECRET_ACCESS_KEY=YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
            - AWS_REGION=us-east-1
        ports:
            - "80:1080"
        restart: always
        networks:
            - code-network
networks:
    code-network:
        driver: bridge


text:
Q: DirectoryInfo.Delete vs Directory.Delete I want to delete the contents of some temp files so I am working on small program that deletes them for me. I have these two code samples but I'm confused as to:

*

*Which code sample is better?

*The first sample, code1, deletes the files 1 and 2 but the second sample, code2 will delete the contains of folder 1 and 2?

code1
    public void DeleteContains(string Pathz)
    {
        List<DirectoryInfo> FolderToClear = new List<DirectoryInfo>();
        FolderToClear.Add(new DirectoryInfo(@"C:\Users\user\Desktop\1"));
        FolderToClear.Add(new DirectoryInfo(@"C:\Users\user\Desktop\2"));

        foreach (DirectoryInfo x in FolderToClear)
        {
            x.Delete(true);
        }
    }

code 2
    private void DeleteContents(string Path)
    {
        string[] DirectoryList = Directory.GetDirectories(Path);
        string[] FileList = Directory.GetFiles(Path);

        foreach (string file in FileList)
        {
            File.Delete(file);
        }
        foreach ( string directoryin DirectoryList)
        {
            Directory.Delete(directory, true);
        }
    }

A: EDIT: I believe the OP wants a comparison of DirectoryInfo.Delete and Directory.Delete.
If you look at the decompiled source for each method (I used resharper to show me), you can see that DirectoryInfo.Delete and Directory.Delete both call the Delete method with 4 arguments. IMHO, the only difference is that Directory.Delete has to call Path.GetFullPathInternal to get the fullpath. Path.GetFullPathInternal is actually a very long method with lots of checks. Without doing a series of tests for performance, it would be unlikely to determine which is faster and by how much.
Directory.Delete
    [ResourceExposure(ResourceScope.Machine)]
    [ResourceConsumption(ResourceScope.Machine)]
    public static void Delete(String path, bool recursive)
    {
        String fullPath = Path.GetFullPathInternal(path);
        Delete(fullPath, path, recursive, true);
    }

DirectoryInfo.Delete
    [ResourceExposure(ResourceScope.None)]
    [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
    public void Delete(bool recursive)
    {
        Directory.Delete(FullPath, OriginalPath, recursive, true);
    }

A: The first code sample will only delete the folders "C:\Users\user\Desktop\1" and "C:\Users\user\Desktop\2" regardless of what is passed in the parameter.
The second code sample will delete all files and folders that are inside the directory specified by the parameter.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Replace same string with different one every time I have a string that contains same value in different place. For instance:

Salam. Men yaxsiyam sen necesen? Sen ne vaxt geleceksen? Sen oralarda ne edirsen?

How can I change this string like below?

Salam. Men yaxsiyam sen1 necesen? Sen2 ne vaxt geleceksen? Sen3 oralarda ne edirsen?

P.S I searched but couldn't find any source.
I also tried string.Replace(), StringBuilder.Replace(), Regex.Replace() methods. But didn't reached to result.

A: You can indeed use Regex.Replace for this. You can use the overload with MatchEvaluator (Regex.Replace(string input, string pattern, MatchEvaluator evaluator)). This method replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.  For example:
int i = 0;
string s = "Salam. Men yaxsiyam sen necesen? Sen ne vaxt geleceksen? Sen oralarda ne edirsen?";
Console.WriteLine(Regex.Replace(s, "(?i)sen", match => match.Value + i++));

Outputs:

Salam. Men yaxsiyam sen0 necesen1? Sen2 ne vaxt geleceksen3? Sen4 oralarda ne edirsen5?

But this is just an example. You can do more.
Edit:
This regex (\s(?i)sen(?=\s)) with starting i at 1 will give exactly the same results you want.

A: The Regex.Replace will do the work, you can use groups if you want to match only full words.
var str = "Salam. Men yaxsiyam sen necesen? Sen ne vaxt geleceksen? Sen oralarda ne edirsen?";
int indexer = 0;
var str2 = Regex.Replace(str, @"(?<pre>[^\w])(?<content>sen)(?<post>[^\w])", m => m.Groups["pre"].Value + m.Groups["content"].Value + (indexer++) + m.Groups["post"].Value, RegexOptions.IgnoreCase);


text:
Q: Problem retrieving the image after updating the Access database (System.ArgumentException: 'Parameter is not valid.') First and foremost, I apologize for my grammatical errors; my first language is Persian (Iran).
I use the following code to insert the image and retrieve it from the Access database, and I have no problem retrieving it after inserting the image.
           BitmapImage BM;
           private void UploadButton_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
           {
            System.Windows.Forms.OpenFileDialog OpenFileDialog = new System.Windows.Forms.OpenFileDialog();
            OpenFileDialog.AutoUpgradeEnabled = false;
            if (App.EnumLanguage.Equals(AllLanguage.English))
            {
                OpenFileDialog.Title = "Selecting Image";
            }
            else
            {
                OpenFileDialog.Title = "انتخاب تصویر";
            }
            OpenFileDialog.Filter = "JPG(*.jpg)|*.jpg|BMP(*.bmp)|*.bmp|GIF(*.gif)|*.gif|PNG(*.png)|*.png|All Files|*.*";
            if (OpenFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var IMG = System.Drawing.Image.FromFile(OpenFileDialog.FileName);
                BM = new BitmapImage(new Uri(OpenFileDialog.FileName));
                BitmapImage BitMapImage = new BitmapImage();
                BitMapImage.BeginInit();
                System.IO.MemoryStream MemoryStream = new System.IO.MemoryStream();
                IMG.Save(MemoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
                MemoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                BitMapImage.StreamSource = MemoryStream;
                BitMapImage.EndInit();
                BookImage.Source = BitMapImage;
                OpenFileDialog.Dispose();
            }
           }
           private static byte[] ImageToBytes(BitmapImage image)
           {
            byte[] Data;
            JpegBitmapEncoder JpegEncoder = new JpegBitmapEncoder();
            JpegEncoder.Frames.Add(BitmapFrame.Create(image));
            using (System.IO.MemoryStream MS = new System.IO.MemoryStream())
            {
                JpegEncoder.Save(MS);
                Data = MS.ToArray();
            }
            return Data;
           }
           private BitmapImage GetImageFromBytes(byte[] bytes)
           {
            System.IO.MemoryStream Stream = new System.IO.MemoryStream();
            Stream.Write(bytes, 0, bytes.Length);
            Stream.Position = 0;
            System.Drawing.Image img = System.Drawing.Image.FromStream(Stream);
            BitmapImage bitImage = new BitmapImage();
            bitImage.BeginInit();
            System.IO.MemoryStream MS = new System.IO.MemoryStream();
            img.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg);
            MS.Seek(0, System.IO.SeekOrigin.Begin);
            bitImage.StreamSource = MS;
            bitImage.EndInit();
            return bitImage;
           }
           private void Add_Button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
           {
            OleDbConnect.Open();
            if (BM != null)
            {
                byte[] Image_Bytes = ImageToBytes(BM);
                OleDbParameter Parameter = new OleDbParameter();
                Parameter.OleDbType = OleDbType.Binary;
                Parameter.ParameterName = "Image";
                Parameter.Value = Image_Bytes;
                OleDbCommand OleDbCommand_Insert = new OleDbCommand("Insert Into [BookTable](BookName,Publisher,Category,IDNumber,Status,HistoryTaken,RecipientName,ReturnDate,BookImage)values('" + BookName_TextBox.Text + "','" + Publisher_TextBox.Text + "','" + Category_ComboBox.Text + "','" + IDNumber_TextBox.Text + "','" + Status_ComboBox.Text + "','" + HistoryTaken_TextBox.Text + "','" + RecipientName_TextBox.Text + "','" + ReturnDate_TextBox.Text + "',@Image)", OleDbConnect);
                OleDbCommand_Insert.Parameters.Add(Parameter);
                OleDbCommand_Insert.ExecuteScalar();
            }
            OleDbConnect.Close();
           }

           \\\ retrieving information from Access Database

           OleDbCommand OleDCmd = new OleDbCommand("Select * From BookTable Where IDNumber='" + Search_ComboBox.Text.Trim() + "'", OleDbConnect);
           OleDCmd.CommandType = System.Data.CommandType.Text;
           OleDbConnect.Open();
           OleDbDataReader DataReader = OleDCmd.ExecuteReader();
           while (DataReader.Read())
           {
             BookName_TextBox.Text = DataReader[0].ToString();
             Publisher_TextBox.Text = DataReader[1].ToString();
             Category_ComboBox.Text = DataReader[2].ToString();
             IDNumber_TextBox.Text = DataReader[3].ToString();
             Status_ComboBox.Text = DataReader[4].ToString();
             HistoryTaken_TextBox.Text = DataReader[5].ToString();
             RecipientName_TextBox.Text = DataReader[6].ToString();
             ReturnDate_TextBox.Text = DataReader[7].ToString();
             BitmapImage BMP = GetImageFromBytes((byte[])DataReader[8]);
             BookImage.Source = BMP;
           }

But when I use the following commands to update the image and other information, this error is displayed when I want to retrieve the information.
                byte[] Image_Bytes = ImageToBytes(BM);
                OleDbParameter Parameter = new OleDbParameter();
                Parameter.OleDbType = OleDbType.Binary;
                Parameter.ParameterName = "Image";
                Parameter.Value = Image_Bytes;
                OleDbCommand OleDbCommand_Update = new OleDbCommand("Update [BookTable] Set BookName='"+BookName_TextBox.Text.Trim()+"',Publisher='"+Publisher_TextBox.Text.Trim()+"',Category='"+Category_ComboBox.Text.Trim()+"',Status='"+Status_ComboBox.Text.Trim()+"',HistoryTaken='"+HistoryTaken_TextBox.Text.Trim()+"',RecipientName='"+RecipientName_TextBox.Text.Trim()+"',ReturnDate='"+ReturnDate_TextBox.Text.Trim() +"',BookImage='"+ "@Image" + "'Where IDNumber='" + IDNumber_TextBox.Text.Trim()+ "'", OleDbConnect);
                OleDbCommand_Update.Parameters.Add(Parameter);
                OleDbCommand_Update.ExecuteScalar();

System.ArgumentException: 'Parameter is not valid.'
Line 6 gives an error
                private BitmapImage GetImageFromBytes(byte[] bytes)
                {
                 System.IO.MemoryStream Stream = new System.IO.MemoryStream();
                 Stream.Write(bytes, 0, bytes.Length);
                 Stream.Position = 0;
                 System.Drawing.Image img = System.Drawing.Image.FromStream(Stream);\\System.ArgumentException: 'Parameter is not valid.'
                 BitmapImage bitImage = new BitmapImage();
                 bitImage.BeginInit();
                 System.IO.MemoryStream MS = new System.IO.MemoryStream();
                 img.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg);
                 MS.Seek(0, System.IO.SeekOrigin.Begin);
                 bitImage.StreamSource = MS;
                 bitImage.EndInit();
                 return bitImage;
                }

In short:in insert command i have no problem to retrieve image but in update command i have problem to retrieve image.
In my opinion, the Update command does not save the image properly in the Access database.
Thanks

A: Hooray, hooray I found the solution (I found it myself).if IDNumber data type as be number data type in Access Database , this code works 100%.
Just Replace this code...
OleDbCommand OleDbCommand_Update = new OleDbCommand("Update [BookTable] Set BookName='"+BookName_TextBox.Text.Trim()+"',Publisher='"+Publisher_TextBox.Text.Trim()+"',Category='"+Category_ComboBox.Text.Trim()+"',Status='"+Status_ComboBox.Text.Trim()+"',HistoryTaken='"+HistoryTaken_TextBox.Text.Trim()+"',RecipientName='"+RecipientName_TextBox.Text.Trim()+"',ReturnDate='"+ReturnDate_TextBox.Text.Trim() +"',BookImage='"+ "@Image" + "'Where IDNumber='" + IDNumber_TextBox.Text.Trim()+ "'", OleDbConnect);

With the following code (this is how the UPDATE Query command should be written)
OleDbCommand OleDbCommand_Update = new OleDbCommand("Update [BookTable] Set BookImage=Image,BookName='" +BookWindow.BookName_TextBox.Text.Trim() + "',Publisher='" + BookWindow.Publisher_TextBox.Text.Trim() + "',Category='" + BookWindow.Category_ComboBox.Text.Trim() + "',Status='" + BookWindow.Status_ComboBox.Text.Trim() + "',HistoryTaken='" + BookWindow.HistoryTaken_TextBox.Text.Trim() + "',RecipientName='" + BookWindow.RecipientName_TextBox.Text.Trim() + "',ReturnDate='" + BookWindow.ReturnDate_TextBox.Text.Trim() + "'Where IDNumber=" + BookWindow.IDNumber_TextBox.Text.Trim(), OleDbConnect);

I tested a lot until I finally got the result.
Thanks a lot for your help.


text:
Q: T-SQL- calculate rota patterns I'm using SQL 2012.
I have a database table populated with personnel data. Every individual has a Start Date (1/1/1990, 24/11/2004, 3/4/2018 etc).
Every individual has a rota of a set length which starts on their respective start date.
The pattern rolls for its length E.g. 7, 14, 21 days before reoccurring and is governed by Contract Length
Fields:

If you had a length '4' and on day 2 you are fully available the database will show your contract as day 0 start end, day 1 start end, day 3 start end because the way the database records data, it only tells you when you aren't available and you must infer that you are available
We're looking to create a script so that based on someone's start date and pattern, we can determine what day of the rota they are on at [user defined date].


text:
Q: Evaluation of $\int_s ^t dW(s)$ without using Ito's rule I would like to solve $\int_s^t dW(s)$ without using Ito's rule. I'm currently thinking about this but I'm still worried this is not fully correct..
\begin{align}
I
&= \int_s ^t dW(s) = \int_0 ^t dW(s) - \int_0 ^s dW(s) \\
&= \lim_{ N \rightarrow \infty} \sum_{j=0}^{N-1} \Big[W(t_{j+1}) - W(t_j)) - (W(s_{j+1})-W(s_j)\Big] \\
&= \lim_{ N \rightarrow \infty} W(t_N) - W(s_N)
\end{align}
However, as $N \rightarrow \infty$, we have for $T = n\,\Delta t$, that $\Delta t \rightarrow 0$, hence this means that $I = W(t) - W(s)$.
It feels rather logical but I'm not really sure. Could someone tell me if this is right?


text:
Q: I am not able to create any resource using terraform, I have installed terraform in windows 11 and tried, please let me know what went wrong? Terraform CODE:
provider "aws" {
  region = "us-east-1"
  access_key = "*********************"
  secret_key = "***************************"
}

resource "aws_vpc" "mainvpc" {
  cidr_block = "10.1.0.0/16"
  tags = {
    Name = "example"
  }
}

resource "aws_subnet" "main" {
  vpc_id     = aws_vpc.mainvpc.id
  cidr_block = "10.0.1.0/24"

  tags = {
    Name = "Main"
  }
}

Terminal Output:
\`PS C:\\Users\\surya\\Documents\\Terraform_project\> terraform init

Initializing the backend...

Initializing provider plugins...

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
PS C:\\Users\\surya\\Documents\\Terraform_project\> terraform plan

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.
PS C:\\Users\\surya\\Documents\\Terraform_project\> terraform apply

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.\`


text:
Q: How many four-digit numbers are there formed from the digits 1, 2, 3, 4, 5 (with possible repetition) that are evenly divisible by 4? I am stuck on this problem.
I started to solve the problem by finding the set of all possible numbers that can be formed without concern about divisibility by $4$, that is
$5 \cdot 5 \cdot 5 \cdot 5 \cdot 5 = 5^{4}$
since if it divisible by $4$, it must be even number I must find the set of odd numbers that end with $1,3,5$ and exclude it from the main set,
that is
$5^{3}+5^{3}+5^{3}$
but I got stuck at the set that ends with $2,4$ since it is not guaranteed that those numbers must be divisible by $4$.
Can anyone help me?

A: A number is divisible by four if its last two digits are divisible by four. The set of possible answers is:

*

***12

***24

***32

***44

***52

Where * is any of $\{1,2,3,4,5\}$. There are $5\cdot 5 = 25$ permutation options for each **. Thus there are $25 \times 5 = 125$ numbers divisible by four from the digits $\{1,2,3,4,5\}$.

A: The number formed by last two digits must be divisible by 4, to make the number divisible by 4.
Therefore the four digit number that can be formed are
_ _ $12$
_ _ $24$
_ _ $32$
_ _ $52$
_ _ $44$
You need to fill the spaces with five digits.
So for first combination there are $5 \cdot 5$ ways.
For five combinations there are $5 \cdot 5 \cdot 5$ ways.


text:
Q: Add recipient in MFMailComposeViewController from Label represented I have an application that allows users to send emails by MFMailcomposeViewController.
composeVC.setToRecipients(["email@gmail.com"])

In the same view controller i have a label which is representing the email of the people which is downloaded from Firestore. How can i setToRecipients instead of (["email@gmail.com"]) to (["mailRepresentedLabel@gmail.com"])
I want it to pull the data from mail represented label and add it automatically to the recipient so the end user is not required to add the email to setToRecipient it will be automatically pulled from mailRepresentedLabel
Please help.
My current code is look like this
               if !MFMailComposeViewController.canSendMail() {
                   print("Не удается отправить Имэйл")
                   return
               }
               let composeVC = MFMailComposeViewController()
               composeVC.mailComposeDelegate = self

               // Configure the fields of the interface.
        composeVC.setToRecipients(["\(String(describing: mailRepLabel))"])
               composeVC.setSubject("Register your client details with us")
               composeVC.setMessageBody("Dear agent please register your client with us by replying on that email in order for us to track the information that this client is came with you. if aftersometime the client would like to come without you we will always have the information that this client is came with you and we will send him back to you. Please reply with the following details: Client Name, Passport number Property Managers name.", isHTML: false)

               // Present the view controller modally.
               self.present(composeVC, animated: true, completion: nil)
               print("done")
           }

}

extension AgentViewController: MFMailComposeViewControllerDelegate {
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        if let _ = error {
            controller.dismiss(animated: true)

        return

        }
        switch result {
        case .cancelled:
            print("Canceled")
        case.failed:
            print("Failed to send")
        case.saved:
            print("Saved")
        case.sent:
            print("Email Sent")
        }
        controller.dismiss(animated: true)
    }
}```

A: You can access the text content of your label with the text attribute. So... Something like this?
mailComposer.setToRecipients([mailRepLabel.text])


text:
Q: Is it possible to open tabs in selenium(python) using a link that is generated by python? I have a program which generates a link in python and names its N. It will generate multiple such links and I wanted to use selenium to open it in Google Chrome.
I tried this
browser.execute_script('''window.open('N', "_blank");''') for all my N links hoping it would open a bunch of tabs with the links but it just seems to open empty tabs.

A: It is, you have to insert the url properly in that execute script:
def open_random_url(url):
    driver.execute_script('window.open("{}","_blank");'.format(url))

open_random_url('https://stackoverflow.com')


text:
Q: Rect datepicker component breaks page structure when clicked I'm using react datepicker component (https://reactdatepicker.com/) in a div with others elements in the same line.

When I click on the input date and the calendar is shown, it brokes the page structure, moving the search button to the bottom.

I have no experience with html or css so I kind of stuck here.
My html code is quite simple:

        <form>
           Driver ID:
          <input name="driverID" />

            Day:
          <DatePicker/>

          <input type="submit" value="Search" />
        </form >

A: Here is how I made single line 'from' from you code:

      <form class="form-inline">
         Driver ID:
        <input name="driverID" />
         Day:
        <DatePicker />
        <input type="submit" value="Search" />
      </form>

Then at the top of this file I added:
import "./App.css";  //App.css is name of the css file.

Here is code in my App.css:
.form-inline {
  display: flex;
  flex-flow: row wrap;
  align-items: center;
}

This made sure that all the inputs, labels and buttons remain in the first line.


text:
Q: In the internal language of the topos of sheaves on a topological space, can we define locally constant real-valued functions? For the purposes of this question, in a Grothendieck topos, we will call "definable" the objects and relations obtained from the terminal object, the natural numbers object and the subobject classifier, by taking finite products, finite coproducts, exponentials (internal homs) and taking subobjects defined by [edit 2021-02-16] finitary formulas in the internal language (using previously defined objects and relations).  (I'm saying this a bit concisely in the hope that there are no major subtleties.)
In particular, if $X$ is a topological space and we consider the topos of sheaves on $X$, the sheaf of continuous functions with values in each one of the following is definable (along with its usual algebraic structure):

*

*$\mathbb{N}$ with the discrete topology (this is the natural numbers object),

*$\mathbb{Z}$ with the discrete topology (this is the Grothendieck group of the previous),

*$\mathbb{Q}$ with the discrete topology (this is the fraction field of the previous),

*$\mathbb{R}$ with the usual (Euclidean) topology (by Dedekind cuts).
Let us call $\mathbf{N}, \mathbf{Z}, \mathbf{Q}, \mathbf{R}$ the corresponding definable objects of the topos.
Now for a long time I thought one could not define the sheaf of continuous functions with values in

*

*$\mathbb{Q}$ with the usual (i.e. induced by $\mathbb{R}$) topology,

but I serendipitously realized that you can, namely it is given by the following object:
$$\{x\in\mathbf{R} : \forall y\in\mathbf{R}. ((\forall z\in\mathbf{Q}.(y\mathrel{\#}z)) \Rightarrow  (x\mathrel{\#}y))\}$$
where $x\mathrel{\#}y$ stands for $(x<y)\lor(x>y)$ or, equivalently, $\exists z\in\mathbf{R}.(z\cdot(x-y)=1)$.
(This is easy to see: first note that $\{x\in\mathbf{R} : \forall y\in\mathbf{Q}. (x\mathrel{\#}y)\}$ defines the sheaf of continuous functions with values in $\mathbb{R}\setminus\mathbb{Q}$ with the usual topology, then repeat the reasoning.)
So now I am curious to know whether the "converse" is possible:

*

*$\mathbb{R}$ with the discrete topology;

in other words:
Question: is the sheaf of locally constant real-valued functions on $X$ definable, uniformly in $X$, as a subobject of $\mathbf{R}$ in the topos of sheaves on $X$?
I imagine there is little hope of finding a good answer to the very general question "for which topological spaces $Y$ is the sheaf of continuous $Y$-valued functions on $X$ definable as an object in the topos?", but of course, if someone wants a crack at it rather than the particular case above, by all means do!

A: I can offer a helpful observation. Andrew Swan and I proved in Every metric space is separable in function realizability that in Kleene's function realizability topos every metric space is separable. One consequence of this is that in the internal language of a topos one cannot construct a non-separable metric space, or an uncountable set with decidable equality. Moreover, it is consistent to assume that every set with decidable equality is countable (Theorem 2.5, but see the comment following it.)
While this is not a complete answer to your question, it shows that if there is a definition of the discrete $\mathbb{R}$ in sheaves, we will not be able to prove intuitionistically that it is uncountable and has decidable equality.

A: It seems to me that for any set $S$ (e.g. $S = \mathbb R$), the classifying topos for locally-constant $S$-valued functions is the slice topos $Set/S$ of $S$-indexed sets, as this is equivalent to the topos of sheaves on $S$ regarded as a discrete topological space.
So because locally-constant $S$-valued functions admit a classifying topos, they can be axiomatized by a theory $T_S$ in geometric logic. I don't know what the axiomatization says, exactly, but one should be able to work it out from the literature. I don't know if a truly infinitary definition in geometric logic counts as "definable" for you, but I think this gives some form of positive answer.
If "locally constant $\mathbb R$-valued function" is supposed to mean something more closely related to the internal Dedekind reals $\mathbf R$ which doesn't agree with $T_{\mathbb R}$, then it's not clear to me what this distinct meaning is supposed to be. That is, if the theory $T_{\mathbb R}$ is not what you're looking for, then what is an example of a topos $\mathcal E$ where locally-constant $\mathbf R$-valued functions are not the same as models of $T_{\mathbb R}$?


text:
Q: SSAS PowerPivot MDX Problems w/ Measures Format_string I am investigating a problem about Calculated Measures format issue from an OLAP Cube.
I get these numbers :

I am using this mdx request:
WITH MEMBER [Measures].[Ristournable Format] AS [Measures].[Ristournable], FORMAT_STRING = 'Currency'
SELECT
NON EMPTY { [Measures].[Ristournable Format] } ON COLUMNS,
NON EMPTY { ([Affaire].[Affaire].[Affaire].ALLMEMBERS ) } ON ROWS
FROM [CUBE]

But it doesn't work. I think the problem comes from the "." instand of "," for the numbers so my MDX request is using it as String. That's why I tried to force the numeric conversion with the first sentence "WITH MEMBER ...". Unfortunately this doesn't work either.
Could you please help me to solve it?

A: Have you tried FORMAT_STRING='$##0.00' or some other explicit way of telling MDX exactly what you want, rather than just passing 'Currency'?


text:
Q: In multiple inheritance ( diamond shape), grand parent's default constructor called #include<iostream>
using namespace std;
class Person {
   // Data members of person
public:
    Person(int x)  { cout << "Person::Person(int ) called" << endl;   }
};

class Faculty : public Person {
   // data members of Faculty
public:
    Faculty(int x):Person(x)   {
       cout<<"Faculty::Faculty(int ) called"<< endl;
    }
};

class Student : public Person {
   // data members of Student
public:
    Student(int x):Person(x) {
        cout<<"Student::Student(int ) called"<< endl;
    }
};

class TA : public Faculty, public Student  {
public:
    TA(int x):Student(x), Faculty(x)   {
        cout<<"TA::TA(int ) called"<< endl;
    }
};

int main()  {
    TA ta1(30);
}

O/p:
Person::Person() called
Faculty::Faculty(int ) called
Student::Student(int ) called
TA::TA(int ) called

In the above diamond shape, two parents classes are inherited from grand parent with virtual keyword, Hence the constructor of Person class is called only once. But Why grand parent's default constructor called here. Can anyone tell me the exact reason
Thanks alot

A: TA is a Person, so there is nothing unexpected about Person's constructor being called. If you used virtual inheritance like you claimed, your TA class would have a single Person sub-object, so the fact that it's constructor is called once is to be expected. If you had not used virtual inheritance, TA would have two Person sub-objects, and you could expect two Person constructor calls.

A: Diamond configurations require virtual base classes or your going to get duplicity in object representation.
class A
{
}

class B : virtual public A
{
};

class C : virtual public A
{
}

class D: public B, public C
{
}

This will ensure only a single representation of A makes it into the final object of type D, and it will be shared by all.
I leave it as an exercise to the questioner how to pass constructor parameters through this. It is not intuitive, but google + "virtual base class" will be more than enlightening.

A: C++ Faq answers your question nicely:

[25.12] What special considerations do I need to know about when I inherit from a class that uses virtual inheritance?
Initialization list of most-derived-class's ctor directly invokes the virtual base class's ctor.
Because a virtual base class subobject occurs only once in an instance, there are special rules to make sure the virtual base class's constructor and destructor get called exactly once per instance. The C++ rules say that virtual base classes are constructed before all non-virtual base classes. The thing you as a programmer need to know is this: constructors for virtual base classes anywhere in your class's inheritance hierarchy are called by the "most derived" class's constructor.
Practically speaking, this means that when you create a concrete class that has a virtual base class, you must be prepared to pass whatever parameters are required to call the virtual base class's constructor. And, of course, if there are several virtual base classes anywhere in your classes ancestry, you must be prepared to call all their constructors. This might mean that the most-derived class's constructor needs more parameters than you might otherwise think.
However, if the author of the virtual base class followed the guideline in the previous FAQ, then the virtual base class's constructor probably takes no parameters since it doesn't have any data to initialize. This means (fortunately!) the authors of the concrete classes that inherit eventually from the virtual base class do not need to worry about taking extra parameters to pass to the virtual base class's ctor.


text:
Q: How can I combine multiple sets of properties in Java to avoid duplication? The title might be a little confusing, but let me explain what I mean. I'm trying to create classes that all have the same base fields, but then each of the classes has fields that are shared by some, but not all like this:
abstract class BaseClass {
    private final int a;
    private final int b;
    private final int c;
}

class A extends BaseClass {
    private final int j;
    private final int y;
}

class B extends BaseClass {
    private final int j;
    private final int x;
}

class C extends BaseClass {
    private final int k;
    private final int y;
}

class D extends BaseClass {
    private final int k;
    private final int x;
}

I also drew up a little diagram to illustrate what I'm trying to accomplish
Now I know that what I'm describing here is multiple inheritance, but unfortunately (or fortunately I suppose, depending on your perspective) Java doesn't support multiple inheritance. That leaves me with 2 options:

*

*Just duplicate the fields wherever I need them like in the example above

*Put the properties into separate classes which then become the fields in the concrete classes like this:
abstract class BaseClass {
    private final int a;
    private final int b;
    private final int c;
}

class PropertiesClassJ {
    private final int j;
}

class PropertiesClassK {
    private final int k;
}

class PropertiesClassX {
    private final int x;
}

class PropertiesClassY {
    private final int y;
}

class ConcreteClass1 extends BaseClass {
    private final PropertiesClassJ propertiesClassJ;
    private final PropertiesClassK propertiesClassK;
}

class ConcreteClass2 extends BaseClass {
    private final PropertiesClassJ propertiesClassJ;
    private final PropertiesClassX propertiesClassX;
}

Obviously option 1 is not really the way to go, but I don't really like option 2 either since it doesn't really match the structure that the final object is trying to represent. Is there another option here to get what I want, or is option 2 my best choice?


text:
Q: Neo4j commit callback over REST API? I came across https://github.com/neo4j/neo4j/blob/master/community/kernel/src/main/java/org/neo4j/graphdb/event/TransactionData.java which allows to capture data that was changed within the course of a transaction.
My application uses two data stores, postgresql and Neo4j. To revert to a consistent state upon crash/failure, I am hoping to maintain data from this event which could be useful to reconcile data between databases.
However, we are using the neo4j server REST api, and this event is available to using neo4j in embedded mode. Is it possible to get a response similar to 'created_nodes' and 'created_relationships' over rest batch commits?

A: The TransactionData instances are only exposed to a TransactionEventHandler. That is a component to be written in Java (or other JVM language) you can register with your graph database, either in embedded mode or when running as server. TransactionEventHandler are typically used to implement cross cutting concerns.
Access to TransactionData is not available using the REST API.


text:
Q: R Sentiment Analysis with syuzhet tm corpus I'm newbie to text analysis in R, is there an easy way to apply the syuzhet: get_nrc_sentiment to a corpus with x elements (loaded individual text files)? I'm guessing you need turn the corpus back to a combined plain text file and use that?
s<-get_nrc_sentiment(.....)
thanks

A: Solved: use unlist on the corpus, e.g.  data.frame(text=unlist(sapply(a, [)), stringsAsFactors=F) then get_nrc_sentiment on the text column of that dataframe


text:
Q: Can I use any other encoding other than Base64 while passing client Id & client secret in Authorization header Can I use any other encoding other than Base64 while passing client Id & client secret in Authorization header while obtaining token from OAuth provider.
Any direction is much appreciated.

A: You can you use any encoding you want, as long as you are decoding it properly. But the Base64 is the standard.

A: Standard "Authorization" basic header must use base 64 encoding. In contrast if you need to use a different mechanism to communicate clientid and secret, indeed you can use given the below conditions are satisfied.
1) You should not use basic authorization header to pass information. (If you use this, you must use base 64 encoding)
2) The server should know how to decode it. In the latest versions of wso2 products you can write custom OAuth client authenticator which knows how to decode your custom information and derive client id and secret. Below is a sample on how to do it.
https://docs.wso2.com/display/IS550/Writing+A+New+OAuth+Client+Authenticator
Or else the easiest option is, you can pass client id and secret in the body of the request (Not as a header). In this method you don't need to encode it. It's just plain text


text:
Q: How do I refer to a value in a column in r? I am working with clinical data that includes the patient names as rows and the proteins as columns. An extra column includes the white cell count for the patients and the values are Low, Medium, and High. How do I create a table that only includes patients with low white cell count
Here is an image of my table. The column names are protein IDs

A: If you are familiar with tidyverse, this is one way you could do it;
df %>%
   filter(wcc_group == "Low")

Or, you could use base-r
df <- subset(df, subset = (wcc_group == "Low"))

Where df is the name of your data.frame.


text:
Q: Linux + Active directory authentication + only letting certain groups login I have some linux boxes that use Windows Active Directory authentication, that works just fine (Samba + Winbind).
What I would like to do now though is only allow certain people or certain groups to login using Active Directory credentials. Currently anyone with a valid AD account can login. I want to limit this to only a few groups. Is this doable?

A: Assuming the groups are available to the Linux system, I recommend editing /etc/security/access.conf for Ubuntu, RedHat distributions (and their forks) and probably a bunch of others.  This doesn't require editing PAM files, and is a nicely standard place to do it.  There are usually examples in the file, commented out.

A: I currently use the AllowGroups directive in /etc/ssh/sshd_config to limit who's able to log in. Specify a one or more AD groups on that line, and those people will be the only ones able to log in.
Keep in mind that this only works if your users are only accessing the server remotely via ssh. If they're singing in locally, you'll need to find another solution.

A: (I'm talking about samba 3 here, no experience on samba 4 now.)
There is no need to edit those /etc/pam.d/xxx files. pam_winbind.conf is the file you want, it is usually located at /etc/security/pam_winbind.conf.
It is the configuration file of pam_winbind module, and it works for both CentOS/Redhat and Debian/Ubuntu. You can read the man page of pam_winbind.conf for reference.
Here is an example file.
#
# pam_winbind configuration file
#
# /etc/security/pam_winbind.conf
#

[global]

# turn on debugging
;debug = no

# turn on extended PAM state debugging
;debug_state = no

# request a cached login if possible
# (needs "winbind offline logon = yes" in smb.conf)
cached_login = yes

# authenticate using kerberos
;krb5_auth = no

# when using kerberos, request a "FILE" krb5 credential cache type
# (leave empty to just do krb5 authentication but not have a ticket
# afterwards)
;krb5_ccache_type =

# make successful authentication dependend on membership of one SID
# (can also take a name)
# require_membership_of = SID,SID,SID
require_membership_of = S-1-5-21-4255311587-2195296704-2687208041-1794

# password expiry warning period in days
;warn_pwd_expire = 14

# omit pam conversations
;silent = no

# create homedirectory on the fly
mkhomedir = yes

A: Yes, there are a few ways of doing this depending on what you're trying to accomplish exactly.
The first method can be done through the samba config. This will only allow these users to connect to Samba, other users can still login through other services (ssh, local term, etc). With this, you'll want to add a line to your [global] section in smb.conf:
valid users = @groupA @groupB

The other method is by modifying PAM rules. Different distributions have slight differences here, but generally speaking there are PAM rules per service as well as common rules, you can decide what is best. You'll want to add an account restriction using the pam_require module. An example on my laptop (Fedora 13) would be to modify the account section in /etc/pam.d/system-auth to:
account     required      pam_unix.so
account     required      pam_require.so @groupA @groupB
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 500 quiet
account     required      pam_permit.so

To simplify administration, you might want to create a new group in AD for the purpose of tracking users that can login to this server.

A: I struggled with getting any of the above to work for me in RHEL 7. Below is what I was able to get to work.
/etc/sssd/sssd.conf
Change
access_provider = ad
to access_provider = simple
+ simple_allow_groups = @group1-admins@xxx.xxx.com, @group2@xxx.xxx.com
visudo

*

*%group1-admins@xxx.xxx.com ALL=(ALL)       ALL
restart the sssd service.

A: I have achieved let only one AD_USER or AD_GROUP to ssh login the linux box via AD authentication.
The details are listed as here: (pay attention to step 7 and 8)
https://gist.githubusercontent.com/xianlin/8c09d916994dac7630b9/raw/ee07817a03bc5904a5404a7e7c94e08ea0c7560a/CentOS_AD_Integration


text:
Q: Show two view components in one controller but from two files (xib/storyboard) I would like to implement something like below:

But, I would like to have my first version app without the map, later on, I will add the map. So, the eventual goal is to show both map and the other things showing on above screen.
My question is, how to make it happen? It sounds like I should have the map and the rest UI in two files (xib or storyboard) respectively, then later on, combine them together. But I am not sure what is the right way to implement these things in iOS?
Can I implement a view component which only contains map, then, another view component only contains the rest, then later on, combine them & one UIViewController associate with the combined view? If so, how to do it? If not, what is the correct way to achieve this?

A: I think you can achieve that by using container views; add 2 container views to your view controller in your Storyboard, the upper container view will contain the map and its stuff, and the bottom one will contain anything else.
To hide the first container view in your first version of the app you'll only need to set the height constraint of the upper container view to 0 after setting the other constraints properly.
If you wanted to use a view controller from another Storyboard file, you can check my answer here.


text:
Q: Argument list too long for ls while moving files from one dir to other in bash shell Below is the command I am using for moving files from dir a to dir b
  ls /<someloc>/a/* | tail -2000 | xargs -I{} mv {} /<someloc>/b/
    -bash: /usr/bin/ls: Argument list too long

folder a has files in millions ..
Need your help to fix this please.

A: If the locations of both directories are on the same disk/partition and folder b is originally empty, you can do the following
$ rmdir /path/to/b
$ mv /other/path/to/a /path/to/b
$ mkdir /other/path/to/a

If folder b is not empty, then you can do something like this:
find /path/to/a/ -type f -exec mv -t /path/to/b {} +

If you just want to move 2000 files, you can do
find /path/to/a/ -type f -print | tail -2000 | xargs mv -t /path/to/b

But this can be problematic with some filenames. A cleaner way would be is to use -print0 of find, but the problem is that head and tail can't process those, so you have to use awk for this.
# first 2000 files (mimick head)
find /path/to/a -type f -print0        \
  | awk 'BEGIN{RS=ORS="\0"}(NR<=2000)' \
  | xargs -0 mv -t /path/to/b

# last 2000 files (mimick tail)
find /path/to/a -type f -print0        \
  | awk 'BEGIN{RS=ORS="\0"}{a[NR%2000]=$0}END{for(i=1;i<=2000;++i) print a[i]}' \
  | xargs -0 mv -t /path/to/b

A: The ls in the code in the question does nothing useful.  The glob (/<someloc>/a/*) produces a sorted list of files, and ls just copies it (after re-sorting it), if it works at all.  See "Argument list too long": How do I deal with it, without changing my command? for the reason why ls is failing.
One way to make the code work is to replace ls with printf:
printf '%s\n' /<someloc>/a/* | tail -2000 | xargs -I{} mv {} /<someloc>/b/

printf is a Bash builtin, so running it doesn't create a subprocess, and the "Argument list too long" problem doesn't occur.
This code will still fail if any of the files contains a newline character in its name.  See the answer by kvantour for alternatives that are not vulnerable to this problem.


text:
Q: Is it undefined behaviour to not call the destructor of an object? This may seem like an obvious question, however I haven't been able to find the answer written anywhere explicitly. Consider the following code:
{
    std::aligned_storage_t<sizeof(int), alignof(int)> storage;
    int& i = *new(&storage) int;
}

Here, I start the lifetime of an objected named i but this lifetime has no explicit "end" since there should be no call to ~int.
I'm not sure if the answer to this question depends on whether or not the type is trivial, so I will provide this second example:

class MyMem : public std::pmr::memory_resource
{
    std::size_t mem_size = 0u;
    char* mem_handle = nullptr;

    virtual void* do_allocate(std::size_t bytes, std::size_t) final
    {
        mem_size += bytes;
        mem_handle = static_cast<char*>(std::realloc(mem_handle, mem_size));
        return mem_handle + mem_size - bytes;
    }
    virtual void do_deallocate(void*, std::size_t, std::size_t) final {}
    virtual bool do_is_equal(const std::pmr::memory_resource&) const noexcept { return false; }

public:
    void* data() const noexcept { return mem_handle; }
};

//...
MyMem mbr;
{
    std::aligned_storage_t<sizeof(std::pmr::vector<int>), alignof(std::pmr::vector<int>)> vec_storage;
    auto& vec = *new(&vec_storage) std::pmr::vector<int>(&mbr);
    vec.resize(N);
}
// Free the data here
std::free(mbr.data());

Using a custom memory resource I can get a handle to the data allocated by the call to vector::resize and ensure we don't leak memory. However the actual destructor call for the vector is missing, and so is the destructor call for each int object allocated in that memory.

A: No this is not undefined behavior. The destructor of an object does not need to be called. (C++ standard example)
N.B: Nevertheless, the life-time of the int object created by the placement new expression ends at the closing brace in you example. An object life-time ends if the destructor for that object is called or if its storage is released or reused [basic.life]/1:
{
  std::aligned_storage_t<sizeof(int), alignof(int)> storage;
  int& i = *new(&storage) int;
} // storage released => end of life of the int.

{
  std::aligned_storage_t<sizeof(std::pmr::vector<int>),
                                alignof(std::pmr::vector<int>)> vec_storage;
  auto& vec = *new(&vec_storage) std::pmr::vector<int>(&mbr);
  vec.resize(N);
} // end of life of the vector, without destructor call

{
  std::aligned_storage_t<sizeof(std::pmr::vector<int>),
                                alignof(std::pmr::vector<int>)> vec_storage;
  auto& vec = *new(&vec_storage) std::pmr::vector<int>(&mbr);
  vec.resize(N);
  // next statement end the life of the vector refered by vec, no destructor called
  auto& vec2 = *new(&vec_storage) std::pmr::vector<int>(&mbr);
} // end of life of the vector referred by vec2, no destructor called

N.B.2: in the last block, as no destructor is called, you will have a memory leak. But memory leaks are allowed.


text:
Q: Asp.net define enter button action I have 2 buttons in my webpage.When i press "Enter",it auto perform "close_topic",but i want my enter button to perform "button_click".
 <asp:Button ID="btnLogout" Text="Close Topic" OnClick="close_topic" runat="server" />

 <asp:Button ID="ButtonTT" Text="Click" runat="server" OnClick="button_click" />

protected void button_Click(object sender, EventArgs e)
{

}

protected void close_topic(object sender, EventArgs e)
{

}

tried to use  <asp:Panel ID="Panel1" runat="server" DefaultButton="ButtonTT">,but not working.

A: Did you wrap your panel around the 2 buttons? As follows:
<asp:Panel ID="Panel1" runat="server" DefaultButton="ButtonTT">
    <asp:Button ID="btnLogout" Text="Close Topic" OnClick="close_topic" runat="server" />
    <asp:Button ID="ButtonTT" Text="Click" runat="server" OnClick="button_click" />
</asp:Panel>

Edit
Based on how to set a default 'enter' on a certain button, you can do it using code also:
Me.Form.DefaultButton = Me.btn.UniqueID;

or
Me.Page.Form.DefaultButton = = Me.btn.UniqueID;

Replacing the Me.Page with whatever your page name is.


text:
Q: How to deal with probability problems in proper class sample spaces? Here my focus is mainly on $Ord$ and questions such as:

*

*An ordinal is chosen by random. What is the probability of the event that it is a cardinal number?

*A coin is tossed proper class many times. What is the probability of an event in which the first $\alpha$ tosses have resulted in tail?

In some sense these questions are similar to the following questions which take place in sample spaces $\mathbb{N}$ and $\{0,1\}^{\mathbb{N}}$ respectively:

*

*A natural number is chosen by random. What is the probability of the event that it is a prime number?

*A coin is tossed (countably) infinite times. What is the probability of an event in which the first $n$ tosses have resulted in tail?

The difficulty is that $Ord$ is a proper class and it is not immediately clear what type of object should the $\sigma$-algebra of events be. It seems formalizing the notion of a probability space for a proper class sample space needs some works and stronger axiomatic systems than ZFC.

Question: How to formalize the notion of probability space for proper class sample spaces? Are there any references for development and use of theory of probability for proper class spaces?

A: Under the usual product measure on $2^{ORD}$ (whatever that may mean), the probability that the first $\alpha$ coin tosses be tail is $2^{-|\alpha|}$ which is zero unless $\alpha$ is finite. I cannot make sense of your first question.


text:
Q: What packages do I need to include to use AutomationCore? I am setting up a C#/Selenium automation framework/test by following the article found here
In the following code, "Test" is a custom test framework that was built in previous steps.
using NUnit.Framework;
using OpenQA.Selenium;
using Test;
namespace AutomatedTestCases
{
    [TestFixture]
    public class Sanity : AutomationCore
    {
        [Test]
        public void ClickContactUs()
        {
            Browsers.getDriver.FindElement(By.Id("menu-item-1296")).Click();
        }
    }
}

The issue I am having is I can't find what package needs to be included in order to inherit from "AutomationCore" and the Google is failing me. Is this a typo or is there actually an AutomationCore class somewhere?

A: AutomationCore is a class that your Sanity class is inheriting from. You need to create that class and implement it first.


text:
Q: Monitoring Solutions for IBM iSeries & AIX I'm curious to know if anyone out in StackOverflow works with monitoring solutions for the IBM iSeries & AIX? We're looking into solutions that provide a single-pane of glass into both systems, rather than two separate solutions.
Any thoughts or input is much appreciated.
Thanks!


text:
Q: Child component calls a method in Parent component AND return a value Parent
HTML
 <tr
    [onTotalWeights]="totalWeights"
  >

Code
totalWeights(): number {
   return // Get sum of fields over the whole array
  }

Child
  @Input() onTotalWeights: () => number;

   canApplyChanges() {
     return this.onTotalWeights() <= 100 && this.form.valid;
  }

I want to call a method on the parent from the child and return a value.
The problem at the moment is that in the child the this.onTotalWeights() when it is called the "this" keyword refers to the methods/variables inside the child component and not from the parent component. Somehow the context is lost when I passed down the totalWeights function.
How can I fix that?

A: That's normal JS behavior. You can customize it by calling .bind()
totalWeights(): number { ... }

totalWeightsFn = this.totalWeights.bind(this);

[onTotalWeights]="totalWeightsFn"


text:
Q: why do i get "acces denied" when trying to use file_get_contents() in a file in a bucket s3? i'm trying to use php functions for reading and writing files in a s3 bucket,i've tried uploading some files and it works fine , but when trying this code :
 ini_set('display_errors', 1);
    require 'vendor/autoload.php';

    use Aws\S3\S3Client;
    use Aws\S3\Exception\S3Exception;

    // Instantiate an S3 client
    $client = S3Client::factory(array(
            'key' => 'key',
            'secret' => 'secret-key',
            'region' => 'region'
        ));

    $client->registerStreamWrapper();
    $data = file_get_contents("s3://bucket_name/file.txt");
    echo $data;

i get this error :
AccessDenied Access Denied

plz any idea.
Thanks.

A: This error mean that php don't have permission to read this file you can change file permission to 0777 for example.


text:
Q: Use opencv in python with gpu support to rotate images I have compiled opencv 4.6.0 from source files with the cuda support. I have followed the guide for windows 10
The process is completed and I can see my gpu. I want to rotate an image by using GPU. In other words I have this simple code
import cv2
img = cv2.imread("cat.3.jpg")
a = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
cv2.imshow("cat", a)
cv2.waitKey(0)

It works fine, but on CPU. I want a similar code in Python that runs on GPU. A similar solution presented here
for C++.

A: I have found the solution. This is the code that I have developed
import cv2
import cv2.cuda as cuda
image = cv2.imread("myimage.jpg")

# Storing the image on GPU
src = cv2.cuda_GpuMat()
src.upload(image)

# Applying the rotation
a = cv2.cuda.rotate(src=src, dsize = (414,500), angle = 12, xShift= 0, yShift=0, interpolation=cv2.INTER_NEAREST)

# Downloading the image from GPU and visualizing the image
result = a.download()
cv2.imshow("cat", result)
cv2.waitKey(0)


text:
Q: Animated Series: Alien black spider robot crashes on Earth I need help identifying a sci-fi animated series I remember watching at some point in the later '90s. I remember watching it on TV sometime around 1996-1998.
In the episode I saw a UFO/alien craft of some kind crashed somewhere on Earth. The alien aboard was some kind of large black spider-like robot.
At least one of the protagonists was a scientist (I believe working with the government). I think his title was either Dr. or Professor.
The government(?) recovered the craft, and held it in a kind of Area 51-like base in a hangar. Then at some point the spider-robot-alien escaped in the UFO.
They had to shoot down the UFO using some kind of special ray gun/machine gun turret. It was a massive gun turret that they had to wheel out. I remember the scientist (Dr. or Professor) operated the gun by sitting behind/beside the turret.
It was very urgent they shoot down the UFO before it escaped (I think), and at the end of the episode they were able to bring it down.
The main things I remember are the spider-like robot in the UFO, and the scientist using the advanced space gun turret at the end to shoot down the UFO.
Any help would be much appreciated! Thanks!

A: It sounds like an episode of the original Johnny Quest....
The Robot Spy"  November 6, 1964
The Quest nemesis, Dr. Zin, sends a giant, cyclops, robot spider (by flying saucer-like craft) to a U.S. government research facility in the American Southwest to steal the secrets of a ray gun project on which Dr. Quest is working.
https://www.dailymotion.com/video/x20bx4i


text:
Q: Exception: DTD must be defined before the document root element I am generating an XML document in the following code. At line
xmlDocument.LoadXml(end);

throws exception saying: DTD must be defined before the document root element
So i found xmlDocument.DocumentType is null and realized Document Type Definition(DTD) must be added to the xmldocument object. so i added
 xmlDocument.CreateDocumentType("sample", null, null, null);

But still it throws same exception.
CODE:
            XmlDocument xmlDocument = new XmlDocument()
            {
                PreserveWhitespace = true
            };
            XmlElement soap = SoapUtil.ToSoap(samlMessage.GetXml(), xmlDocument);
            xmlDocument.AppendChild(soap);
            object[] outerXml = new object[] { xmlDocument.OuterXml };
            SamlTrace.Log(LogLevel.Verbose, "SOAP request to send: {0}", outerXml);
            webRequest.Method = "POST";
            webRequest.ContentType = "text/xml";
            webRequest.Headers.Add("SOAPAction", "http://oasis-open.org/committees/security");
            using (Stream requestStream = webRequest.GetRequestStream())
            {
                xmlDocument.Save(requestStream);
            }
            using (WebResponse response = webRequest.GetResponse())
            {
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                {
                    string end = streamReader.ReadToEnd();
                    SamlTrace.Log(LogLevel.Verbose, "Received SOAP response message: {0}", new object[] { end });
-------->           xmlDocument.LoadXml(end); //exception thrown at this line
                }
            }
            XmlElement xmlElement1 = SoapUtil.FromSoap(xmlDocument.DocumentElement);
            object[] objArray = new object[] { xmlElement1.OuterXml };
            SamlTrace.Log(LogLevel.Verbose, "Response converted from SOAP message: {0}", objArray);
            xmlElement = xmlElement1;

Update 1:
 xmlDocument.LoadXml(streamReader.ReadToEnd().ToString());

i passed streamReader and converting it to a string.
Now it throws a new exception.
"Root element is missing."


text:
Q: How do you iterate through files in a list? I have a list of file pathnames, and I want to iterate through this list opening each file and extracting certain data points from it.
However, when I run the code, it doesn't open the file it just takes the nth character from the file pathname and adds it to the target list, instead of the value from the file that I want.
    for filename in file_list:
       file_data = open(filename, 'r')
       data_one.append(filename[5])
       data_two.append(filename[6])
       data_three.append(filename[7])
       data_four.append(filename[8])
       data_five.append(filename[9])
       file_data.close()

What have I missed to make it so that it doesn't actually open the files?

A: You want to read from the file-like object file_data, not the file name, in order to update each list. Further, file-like objects are iterable, but they cannot be indexed. If you want lines 6-10, you'll want something like itertools.islice.
from itertools import islice

for file_name in file_list:
    with open(file_name) as f:
        points = islice(f, 5, 10)
        data_one.append(points[0])
        data_two.append(points[1])
        # etc

I'm probably making too many assumptions about the actual file format, but the main point is: you have to use the file-like object returned by open instead of the file name.

A: Assuming that your file looks like:
line0
line1
line2
line3
line4
line5
line6
line7
line8
line9

and you want to read lines "line5" to "line9", this is the correct code:
for filename in file_list:
   with open(filename, 'r') as f:  # This line opens the file and will close it
       data = f.readlines()
       data_one.append(data[5])    # These lines use `data` and not the filename
       data_two.append(data[6])
       data_three.append(data[7])
       data_four.append(data[8])
       data_five.append(data[9])


text:
Q: will ReactiveMongoRepository support lock? I have one lower questions. I have several micro services process on same mongo db database.
In every micro service, we will have update to same database. At same time, update to same entity in same collection could happen. Will ReactiveMongoRepository support this scenario and make sure data consistency? Or we need do lock first write later logic in application level?
thanks in advance.


text:
Q: How many ways he can attempt the paper? Joey has to attempt a question paper that has 3 sections with 6 questions in each section .
If he has to attempt any 8 questions , choosing atleast 2 questions from each section.
Then in how many ways he can attempt the paper?
I tried by taking 2 question in each section as
6C2 ways.
So in all 3 section , he can select 6 questions in 6C2 * 6C2 * 6C2 ways.
Now remaining 2 question he can select from  remaining 12 question in 12C2 ways.
So total ways are 6C2 * 6C2 * 6C2 * 12C2 ways.
But the answer is not coming correct.
Is my approach incorrect?
Or i am missing any cases?
Thanks in advance.

A: First, let's split the problem to subproblems depending on how many questions do we choose from each section.
For example "2 questions from the first section, 4 questions from the second section, 2 questions from the third section" would be one such subproblem. How many are they?

 With 8 questions, 3 sections, and at least 2 questions per section, our choices are these: 2+2+4; 2+3+3; 2+4+2; 3+2+3; 3+3+2; 4+2+2. There are essentially just two subproblems, 2+2+4 and 2+3+3, each of them repeated 3 times.

Now, in how many ways can Joey attempt each of these subproblems?

 To choose 2+2+4 questions he has 6C2 * 6C2 * 6C4 options. To choose 2+3+3 questions he has 6C2 * 6C3 * 6C3 options. The answer is: 3 * 6C2 * 6C2 * 6C4 + 3 * 6C2 * 6C3 * 6C3.

A: There are $\binom{18}8$ ways to choose $8$ of the $18$ questions. Let's count the number that are not acceptable.
There are $\binom{12}8$ ways to choose them so as to have none from the first section, and another $\binom61\binom{12}7$ ways to choose them so as to have exactly $1$ from the first section. Thus, there are $\binom{12}8+\binom61\binom{12}7$ ways to choose them so as to have fewer than $2$ from the first section. There are just as many ways to choose fewer than $2$ from the second section, and just as many again to choose fewer than $2$ from the third section, so as a first approximation there are $$3\left(\binom{12}8+\binom61\binom{12}7\right)\tag{1}$$ unacceptable choices.
However, $(1)$ is too big, because we counted some unacceptable choices twice. Specifically, any set of $8$ questions that includes fewer than $2$ from two sections got counted as bad for each of those sections, so it got counted twice in $(1)$. To correct for this, we must subtract from $(1)$ the number of unacceptable sets that have too few questions from two sections. Such a set must have all $6$ questions from one section and one question from each of the other two sections. There are $3$ ways to choose the section that contributes $6$ questions and then $6^2$ ways to choose one question from each of the other two sections, so there are $3\cdot6^2$ sets that have fewer than $2$ questions from each of two sections. Thus, $(1)$ should be corrected to $$3\left(\binom{12}8+\binom61\binom{12}7\right)-3\cdot6^2\;.\tag{2}$$ Since it's not possible to choose $8$ questions and get fewer than $2$ from each of the three sections, $(2)$ is the number of unacceptable choices. The desired result is therefore $$\binom{18}8-3\left(\binom{12}8+\binom61\binom{12}7\right)-3\cdot6^2\;;$$ if I've done the arithmetic correctly, this is $43~758$.
(In this problem it's equally easy to count the number of acceptable sets directly, as Viliam Búr has done in his answer.)


text:
Q: So LWP::UserAgent can automatically detect the charset?   our $ua = LWP::UserAgent->new;
  my $response = $ua->get($url);
  if($response->is_success) {
    my $perl_hash_or_arrayref = decode_json(encode("UTF-8", $response->decoded_content));

The above code converts the response to UTF-8 encoding,without the need to tell it which encoding the response is using.
I asume this may fail under certain cases.
How can I explicitly tell LWP::UserAgent the response encoding?

A: See the docs for decoded_content in HTTP::Message:

$mess->decoded_content( %options )
    Returns the content with any Content-Encoding undone and for
 textual content the raw content encoded to Perl's Unicode strings.
 If the Content-Encoding or charset of the message is unknown this
 method will fail by returning undef.

    The following options can be specified.

    charset

        This override the charset parameter for text content. The value
 none can used to suppress decoding of the charset.


text:
Q: Aurelia Jest with aurelia-ui-virtualization plugin unit testing errors We implemented a feature in a component using aurelia-ui-virtualization and all works well. The problem is that it broke almost all our of unit tests. It throws an error now.

TypeError: Cannot read property 'attrToRemove' of undefined

I believe this is because of the virtual-repeat.for attribute.
I've created a simple test for this example:
import {StageComponent} from 'aurelia-testing';
import {bootstrap} from 'aurelia-bootstrapper';

describe('c-form-select component', () => {
    let component;

    describe('Integration', () => {
        // Test if search is enabled
        it('testing search', async done => {
            component = StageComponent.withResources()
                .inView('<c-form-select search.bind="customsearch"></c-form-select>')
                .boundTo({
                    customSearch: 1,
                });

            try {
                component.bootstrap(au => au.use.standardConfiguration().feature('src'));
                await component.create(bootstrap);
                expect(component.viewModel.search).toBe(false);
                component.dispose();
                done();
            } catch (e) {
                done.fail(e);
            }
        });
    });
});

So I assume aurelia needs to load the aurelia-ui-virtualization plugin. So I change this code:
                component.bootstrap(au =>
                    au.use
                        .standardConfiguration()
                        .plugin('aurelia-ui-virtualization')
                        .feature('src'),
                );

And I get this error:

Cannot find module '/Users/dustin/dev/bindable/aurelia-ui-virtualization' from 'aurelia-loader-nodejs.js'

I'm not sure why it is not looking in my node_modules directory. I assume it might be because of this part of my jest-pretest.ts file:
import {Options} from 'aurelia-loader-nodejs';

Options.relativeToDir = path.join(__dirname, '../');

But I do have a jest.config.js file that has my node_modules directory included:
    modulePaths: [
        '<rootDir>/src',
        '<rootDir>/node_modules'
    ],

If I change the plugin path to node_modules/aurelia-ui-virtualization then I get this error:
    TypeError: Cannot read property 'bind' of undefined

      at Object.<anonymous> (node_modules/aurelia-ui-virtualization/dist/commonjs/aurelia-ui-virtualization.js:70:34)
      at advancedRequire (node_modules/aurelia-loader-nodejs/dist/commonjs/aurelia-loader-nodejs.js:78:28)
      at NodeJsLoader.<anonymous> (node_modules/aurelia-loader-nodejs/dist/commonjs/aurelia-loader-nodejs.js:196:46)
      at step (node_modules/aurelia-loader-nodejs/dist/commonjs/aurelia-loader-nodejs.js:42:23)
      at Object.next (node_modules/aurelia-loader-nodejs/dist/commonjs/aurelia-loader-nodejs.js:23:53)
      at node_modules/aurelia-loader-nodejs/dist/commonjs/aurelia-loader-nodejs.js:17:71

I've been spinning my wheels on this for a couple of days. If anyone can point me in the right direction to fix my unit tests I'd really be grateful!

A: I found a solution. I learned jsdom does not implement reqeustAnimationFrame. I added a pollyfill and made it global in my jest-pretest.ts file:
// Add requestAnimationFrame pollyfill to fix aurelia-ui-virtualiztion issues
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license
(function(window, rAF, cAF) {
    var lastTime = 0,
        vendors = ['ms', 'moz', 'webkit', 'o'],
        x;

    for (x = 0; x < vendors.length && !window[rAF]; ++x) {
        window[rAF] = window[vendors[x] + 'RequestAnimationFrame'];
        window[cAF] = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
    }

    if (!window[rAF]) {
        window[rAF] = function(callback) {
            var currTime = new Date().getTime(),
                timeToCall = Math.max(0, 16 - (currTime - lastTime)),
                id = window.setTimeout(function() {
                    callback(currTime + timeToCall);
                }, timeToCall);

            lastTime = currTime + timeToCall;

            return id;
        };
    }

    if (!window[cAF]) {
        window[cAF] = function(id) {
            window.clearTimeout(id);
        };
    }
})(global.window, 'requestAnimationFrame', 'cancelAnimationFrame');

global.requestAnimationFrame = global.window.requestAnimationFrame;


text:
Q: can't bring https protocol to running I have a wordpress website, hosted on Windows Server 2012. http is working, but https is not!

*

*I got a SSL certificate from the provider (via digicert), and installed in into the Certificate Store in "Personal"

*In IIS, on the website, I chose "Edit Bindings" and entered https protocol for the IP on port 443. And I selected the SSL Certificate.

*Port 443 is definitively open (checked firewall settings)
But when I want to access the website from a client computer via https, I always get a timeout.
Any ideas?

A: Problem solved. Actually the provider was blocking from outside. It turned out the support guy has given me a wrong answer in the first place.


text:
Q: Restricting access to admin module with nginx not always working I need to restrict the admin module in my website. Unfortunately it's not always working. I'm migrating from apache to nginx and my nginx configuration is.
server {

    listen 80;
    server_name example.com;

    charset utf-8;

    index index.php;

    root /websites/example/www/;

    location /admin {
            allow 192.168.3.137;
            deny all;

            try_files $uri /index.php;
    }

    location / {
            try_files $uri /index.php;
    }

location ~* \.php$ {

        fastcgi_pass unix:/var/run/php5-fpm.sock;

        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        fastcgi_param APPLICATION_ENV dev;

        include fastcgi_params;
    }

When I try to open http://example.com/admin/ in Firefox I am redirected to my home page. If the url is without the trailing slash http://example.com/admin, it opens the admin login which is correct. In this case access log has only record for "/" (home page). I don't have problems with Chrome and IE. I use Zend Framework for the php app.

A: All files ending with .php are processed by the location ~* \.php$ block, which effectively bypasses your access rules in the location / block.
One approach might be to use a nested location block and duplicate the PHP block. For example:
location / {
    try_files $uri /index.php;
}

location ~* \.php$ {
    include fastcgi_params;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param APPLICATION_ENV dev;
}

location ^~ /admin {
    allow 192.168.3.137;
    deny all;

    try_files $uri /admin/index.php;

    location ~* \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param APPLICATION_ENV dev;
    }
}

The ^~ modifier ensures that the location block processes all URIs beginning with /admin. The allow/deny rules are inherited by the nested location block.
To manage the duplicated code, you may want to offload the fastcgi directives into a separate file and include them into each location.
See this document for more information.

A: Thank you for the reply.
I deleted the FF cookies and cache and the problem was solved.


text:
Q: Pandas repeating indexes drop rows on groupby where a condition is met I have a specific operation I wasn't able to find the appropriate solution and hope you might have a way to help me figure it out.
Taking the following dataframe where we have multiple rows per id (as it is a recording per second of a value)
idx = np.array([1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 4, 4, 4])
value1 = np.array([600, 600, 600, 2.37, 4.57, 700, 700, 1.4, 2.5, 3.8, 500, 500, 2])
df = pd.DataFrame({'id': idx, 'value':value1}).set_index('id')

The dataframe looks like:

id | value
 1    600
 1    600
 1    600
 1    2.37
 1    4.57
 2    700
 2    700
 2    1.4
 2    2.5
 2    3.8
 4    500
 4    500
 4     2

I would like to drop certain rows to obtain this result dataframe
id | value
 1    2.37
 1    4.57
 2    1.4
 2    2.5
 2    3.8
 4     2

where for each IDs, I only keep the rows where value is inferior to the max value of this grouped by ID (< df.groupby("id")[value].max()).
Meaning:
For id 1, df[value]< 600
For id 2, df[value]< 700
For id 3, df[value]< 500
Is there a more elegant/efficient solution than creating a new column to fill it in with the max and then compare each "value" to its max (as I'm working with high volume datasets (millions of records) ?
df[max_value_id] = df.groupby(['id'])['value'].transform(max)

df[df[value] < df[max_value_id]]

Thanks for your inputs!

A: Using a mask based on results of transform() provides this result.
df.loc[df.value<df.groupby("id")["value"].transform("max")]

id
value

1
2.37

1
4.57

2
1.4

2
2.5

2
3.8

4
2


text:
Q: Do we use 'any' with a countable noun? I am an English tutor. I also lived in the USA for 2 years. Today when I was explaining to my student the use of 'any' in questions and negations, I got stuck. I know we use it before countable nouns in plural and we use it before an uncountable noun. But from my experience speaking English on a daily basis back in the USA I remember people using 'any' with a singular countable noun. For example, 'Is there any room available?'. What are your thoughts on that? Maybe it's the matter of British and American English?

A: 'Is there any room available?' Whether the room here is countable or uncountable (meaning space), any can be used with it as explained below:
NOTE: The following text and screen shots attached are from Practical English Usage by Michael Swan

'Any' can be used to emphasise the idea of 'free choice', with the meaning of 'it doesn't matter who/which/what'. With this meaning, any is common in affirmative clauses as well as questions and negatives, and is often used with singular countable nouns as well as uncountables and plurals."
Examples:
She goes out with any boy who asks her.
Can get a meal here at any time of the day?
I don't do just any work - I choose jobs that interest me.
But, 'any' can be used with plurals and uncountables in the same meaning as the article a/an has with singular countable nouns. With this meaning, 'any' is unusual with singular countable nouns.
Examples:
Is there  a tin-opener in the house? And, are there any plates?
She hasn't got a job. NOT She hasn't got any job.
Do you know a good doctor? NOT Do you know any good doctor?


text:
Q: How to add webrtc dependency in android studio bumblebee? I am trying to add this dependency  :
// https://mvnrepository.com/artifact/org.webrtc/google-webrtc
implementation 'org.webrtc:google-webrtc:1.0.32006'

But I can not get it in studio bumblebee. Showing following error:
Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all files for configuration ':app:debugRuntimeClasspath'.

I tried to add maven url maven { url 'https://jitpack.io' } and https://mvnrepository.com/ in settings.gradles dependencyResolutionManagement - repositories block. But did not solve it. I am not certain which URL or what else to add to resolve this. Can anyone tell me please?


text:
Q: Delete option on suggested edits queue doesn't do anything There's a delete option next to each post on suggested edits queue (for moderators)

For this suggested edit, the best option is to delete the entire post, so I click on the delete button. But, despite clicking on delete, the post still remains and the suggested edit is also pending

A: Since no activity has occurred here in nearly 3 years, I'm assuming a reliable repro couldn't be found.


text:
Q: Wave function of Hydrogen Atom Wavefunction of a Hydrogen atom is expressed in eigenfunctions as:
$$\psi(\boldsymbol r,t=0)=1/\sqrt{14}(2\psi_{100}(\boldsymbol r)-3\psi_{200}(\boldsymbol r)+\psi_{322}(\boldsymbol r) ).$$

*

*Is this an eigenfunction of parity operator?

*What is probability of finding system in state (100),(200),(322)?

*In another energy eigenstate?

*What is the expectation value of energy, $L^2$,$L_z$?
I know some algebra but I don't know what the subscript of eigenfunction means ._.
The only thing I know is about parity operator and its eigenfunctions. Others are just like foreign language.

A: Just some things which might help:

*

*the subscript of $\psi_{nlm}$ refer to the principal quantum number $n$, the azimuthal quantum number $l$, and the magnetic quantum number $m$; the properties of last two you can understand from properties of the spherical hamronics $Y_{lm}$ by noting that $\psi_{nlm}(r,\theta,\phi) = R_{nl}(r) Y_{lm}(\theta,\phi)$.

*the parity operator $P$ acts like $P: \mathbf{r}\mapsto -\mathbf{r}$ which corresponds to $\theta\mapsto\pi-\theta$ and $\phi\mapsto \pi+\phi$. It is easy to convince yourself that $Y_{lm}(\pi-\theta,\phi) = (-1)^l Y_{lm}(\theta,\phi)$ such that $P \psi_{nlm} = (-1)^l \psi_{nlm}$.

*also from the properties of the spherical harmonics, you can show that $$\langle \psi_{nlm} | L^2 | \psi_{nlm} \rangle = \hbar^2 l (l+1)$$ and $$\langle \psi_{nlm} | L_z | \psi_{nlm} \rangle = \hbar m.$$

*the answers to your questions follow easily from the statements above, the linearity of expectation values, and from the fact that states $\psi_{nlm}$ with different $(nlm)$ are orthogonal to each other.

A: To answer this question, you don't actually have to know the meaning of those subscripts. First I'll try and point you in the right direction -
To find the probability of say, $(100)$ occurring, you can think of a (hopefully) more familiar example of a state (say $|\psi\rangle$) given by $$|\psi\rangle = \frac{|a\rangle}{\sqrt{2}} + \frac{|b\rangle}{2} + \frac{|c\rangle}{2}$$
Looking at it, I'm sure you'll be able to guess the probability that when $|\psi\rangle$ is observed, it falls into either $|a\rangle$, $|b\rangle$, or $|c\rangle$. It's an exactly analogous situation in your problem.
Once you've calculated the probability of each energy eigenstate occurring, it's trivial to calculate the probability of it being in any other state except those three.
--
Coming to what the numbers actually mean - If you see the eigenstate of a hydrogen atom written as $\psi_{100}(\vec r)$, the $(100)$ means that the electron in question has the quantum numbers $n = 1$, $l = 0$, $m = 0$.
Now, the quantum number $n = 1$ means that the electron is in the first orbital (also referred to as the $s$ orbital), $l = 0$ means the orbital angular momentum eigenvalue is zero, and $m = 0$ means the spin angular momentum eigenvalue is zero. The $n$, $l$ and $m$ values come from a solution of the schrodinger equation with a spherically symmetric coloumb potential. If you know what spherical harmonics are, you can see that the $l$ and $m$ values are the same as the $Y_{l}^{m}(\theta, \phi)$.
Edit:
You need to calculate the expectation of $E$, $L_{z}$ and $L^{2}$. As you probably know, the equations for that are given by $$\langle E \rangle = \langle \psi| E |\psi \rangle$$ $$\langle L^{2} \rangle = \langle \psi | L^{2} |\psi \rangle $$ $$\langle L_{z} \rangle = \langle \psi | L_{z} | \psi \rangle $$
So clearly all you need to know is how each one of those operators acts on $|\psi \rangle$ and you'll get your answer.