text:
Q: How do I use IntBinaryOperator with a Switch Case Statement for Java Swing? (Simple Calculator) I'm having trouble getting an output while using the switch-statement and IntBinaryOperator. I'm trying to build a simple calculator in Java, and I found that the IntBinaryOperator cut down on unnecessary boilerplate code. I hope that you can show me the best approach. Thank you.
The three classes that I wrote are below.
package gui_calc;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.function.IntBinaryOperator;

public class CalculatorJFrame extends JFrame implements ActionListener {

    static protected JLabel lblOut;
    private JButton btnEq;
    private JButton btnClear;

    public CalculatorJFrame() {
        setTitle("CALCULATOR");
        JPanel container = new JPanel(); //create a JPanel inside the JFrame as a container
        container.setLayout(new BorderLayout());
        //add your components in here
        lblOut = new JLabel("");
        btnEq = new JButton("=");
        btnClear = new JButton("C");
        btnEq.addActionListener(this);
        btnClear.addActionListener(this);
        NumButtonsJP numBtns = new NumButtonsJP(); //create an instance of NumButtonsJP
        OpButtonsJP opBtns = new OpButtonsJP(); //create an instance of OpButtonsJP

        container.add(btnClear, BorderLayout.WEST);
        container.add(btnEq, BorderLayout.EAST);
        container.add(lblOut, BorderLayout.NORTH);
        container.add(numBtns, BorderLayout.CENTER); //add the numBtns JPanel to the container
        container.add(opBtns, BorderLayout.SOUTH); //add the opBtns JPanel to the container
        add(container); //add container to the JFrame
    }

    static protected void updateOutLabel(String suffix) {
        String currLblContent = lblOut.getText().trim(); //get current content of lblOut
        lblOut.setText(currLblContent + suffix); //update the output label on the main container
    }

    static protected void clearOutLabel() {
        lblOut.setText("");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String face = e.getActionCommand().trim();

        switch (face) {
            case "=":
                //do math... get the values... and reset the label with the result
                updateOutLabel("=" + getResultFromQuestion(lblOut.getText()));
                break;
            case "+":
                IntBinaryOperator add = (a,b) -> a + b;

                System.out.println("Your answer is" + (add));
                break;
            case "-":
                IntBinaryOperator substract = (a, b) -> a - b;
                System.out.println("Your answer is" + (substract.applyAsInt(lblOut.getText().charAt(0),lblOut.getText().charAt(1))));
                break;
            case "*":
                IntBinaryOperator multiply = (a, b) -> a * b;
                System.out.println("Your answer is" + (multiply));
                break;
            case "/":
                IntBinaryOperator divide = (a, b) -> a / b;
                System.out.println("Your answer is" + divide);
            case "C":
                clearOutLabel();
                break;
        }

    }

    private String getResultFromQuestion(String text) {
        double resultStr = 10;

        return "" + resultStr;
    }

    public static void main(String[] args) {
        //create instance of calculator and run it
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CalculatorJFrame calcGUI = new CalculatorJFrame();
                calcGUI.setDefaultCloseOperation(calcGUI.EXIT_ON_CLOSE);
                calcGUI.setSize(300, 300);
                calcGUI.setVisible(true);
            }
        });
    }

  package gui_calc;

    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    import javax.swing.JButton;
    import javax.swing.JPanel;

    public class OpButtonsJP extends JPanel implements ActionListener{

        JButton btnAdd = new JButton("+");
        JButton btnSub = new JButton("-");
        JButton btnMul = new JButton("*");
        JButton btnDiv = new JButton("/");
        JButton [] opsBtns = {btnAdd, btnSub, btnMul, btnDiv};//array of jbuttons

        public OpButtonsJP(){
            setLayout(new GridLayout(1,4));
            for(int i=0; i<opsBtns.length; i++){
                add(opsBtns[i]); //add the button to the JPanel
                opsBtns[i].addActionListener(this); //add the ActionListener to make the button functional
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String face = e.getActionCommand();
            System.out.println(face + " was clicked");
            CalculatorJFrame.updateOutLabel(face);
            //String currLblContent = CalculatorJFrame.lblOut.getText();
            //CalculatorJFrame.lblOut.setText(currLblContent + face); //update the output label on the main container
        }

    }

package gui_calc;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class NumButtonsJP extends JPanel implements ActionListener {

    JButton numButtons[];

    public NumButtonsJP() {
        setLayout(new GridLayout(4, 3));
        numButtons = new JButton[10];
        for (int i = 1; i < 10; i++) {
            //create a JButton with the number on its face and add it to the array of JButtons
            numButtons[i] = new JButton("" + i);
            numButtons[i].addActionListener(this); //make the button trigger the event
            //add the JButton to the JPanel
            add(numButtons[i]);
        }
        JLabel spaceHolder = new JLabel(); //create the spaceHolder as a blank label
        add(spaceHolder); //add the spaceHolder to the JPanel
        numButtons[0] = new JButton("0"); //create the Zero button
        numButtons[0].addActionListener(this);//make the Zero button trigger actioNPerformed
        add(numButtons[0]); //add the Zero button to the JPanel
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        String face = e.getActionCommand();
        System.out.println(face + " was clicked");
        int num = Integer.parseInt(face.trim()); // parse to an int so we can use in math
        CalculatorJFrame.updateOutLabel(face);
        //String currLblContent = CalculatorJFrame.lblOut.getText();
        //CalculatorJFrame.lblOut.setText(currLblContent + face); //update the output label on the main container

    }

}

A: I change a little your code, basically I'm adding an evaluator of expressions.
The UI basically construct the expression and pass to your getResultFromQuestion() function which takes the input and then try to parse to a math function.
You must handle the exceptions properly, and it brokes your BinaryOperators since you could entry two of more operands.
@Override
public void actionPerformed(ActionEvent e) {
    String face = e.getActionCommand().trim();
    switch (face) {
    case "=":
        // do math... get the values... and reset the label with the result
        updateOutLabel("=" + getResultFromQuestion(lblOut.getText()));
        break;
    case "C":
        clearOutLabel();
        break;
    }
}
private String getResultFromQuestion(String text) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    Object result = null;
    try {
        result = engine.eval(text);
    } catch (ScriptException e) {
        //Do something with the exception
    }
    return result.toString();
}


text:
Q: Contradicting Logs If $\log(10^2)=2$
and $(\log10)^2=(1)^2=1$
Then
$10^{\log(10^2)}=10^2=100$
But what about
$10^{(\log10)^2}$ ?
We get 2 solutions:
A. $10^{(\log10)^2}=10^{\log10} \times 10^{\log10}=10^1 \times 10^1=100$
B. $10^{(\log10)^2}=10^{1^2}=10^1=10$
What gives ?

A: Hint:
$(a^x)^y \ne a^{x^y}$
(you have proved this fact)

A: You have missed the fact that $$a^x a^y = a^{x+y},$$ not $$a^x a^y \ne a^{xy}.$$  Hence, in (A), $$10^{(\log 10)^2} \ne 10^{\log 10} 10^{\log 10} = 10^{2 \log 10}.$$

A: Your question is "What gives?"
$$x^{(y^z)}\ne {(x^y)}^z$$
For example,
$$2417851639229258349412352=2^{(3^4)}\ne {(2^3)}^4=4096$$  This is essentially the fallacy in lines A. and B.. The logarithms obscure this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Test if the number input is not a text - RUBY I tried to create a program that will test if the inserted input is a text or a number or special character. So I used !a.is_a? Integer. However my code doesn't seem to work. I got this error:

syntax error, unexpected TCONSTANT. expecting keyword then ,

Here's my code:
print "Enter Number Please: "
a = gets.chomp.to_i

answer = case a

when 3
  "OUTPUT: a is 3"
when 4
 "OUTPUT: a is 4"
when !a.is_a? Integer
    "You did not enter a number."
else
  "OUTPUT: a is neither 3, nor 4"
end

puts answer

I understand this could be better to try with Integer(obj) but is there a way to make this work?

A: There's several things to note here. For one, the result of to_i is always an Integer type value. Testing that !a.is_a? Integer is redundant as that will never fail.
You'll also need to remember that the case statement itself makes it very easy to compare to classes:
case (a)
when Integer
  puts "I'm a number!"
when String
  puts "I'm a string!"
end

Note that the first condition is automatically triggered for any Integer values.
There's limits on what you can put in a when clause even if they are fairly generous. To get the parser to properly interpret what you're asking for, you'd have to express it like this:
when !a.is_a?(Integer)

Though as noted this can be reduced down to when Integer so the rest of that is redundant.
You'll also want to avoid specifying something in the case part, and then later referring to a variable. It's confusing to anyone reading your code and probably unnecessary. If you're dealing with complicated logic, use a series of if statements to make things clear.

A: You can do it with a ternary as well I think, like so:
def integer?(number)
  number.is_a?(Integer) ? "This is a number" : "This is not a number"
end


text:
Q: Scaling on 2 monitors with different resolution My monitor setup is a 1920x1080 on the left and a 3840x2160 monitor on the right, running an NVIDIA driver.
My problem is everything is very small on the 4K display and normal sized on the Full HD one. If I change the scaling in Display settings everything on the Full HD one is too big.
So I did some research and tried to get Wayland to work, but I have an NVIDIA GPU so it wouldn't work and I didn't want to install the nouveau drivers since I heard those have bad performance.
I read that this problem could be fixed with xrandr, and I tried a lot of commands too but I never got it to work. One time I was really close to having it work with xrandr but than after a restart, everything was reset again.


text:
Q: Can I have multiline statusline in Vim? Is there any way to make the status line in Vim spanning across multiple lines (e.g. inserting a newline character or something similar)?
I'd like to have full path (%F) to the opened file in one line and some other info in next one because I'm frequently opening files within long paths and the full path "expands" over the whole status line, hiding all other indicators and flags. On the other hand I still want to see the full path to the current file.
I know I can set the upper limit on the width of the full path, e.g. %.40F, I just want to know if there is some other way for this.

A: No, sorry. Statuslines cannot span over multiple lines.
You seem to know your way around statuslines, so I'll skip that part. One possible solution would be to put the filepath+filename in let's say, title, if you're on windows.

A: There currently is a patch for Vim that is adding this. Check this Gist for it: https://gist.github.com/3158492
It is by the vim-jp GitHub organization (Japanese Vim users). It is currently only in Japanese, all the conversation that is, but jump to the end where I asked them some questions.
Hope this helps. :)


text:
Q: Nodes of a list being freed before usage I have a one-dimensional template list that contains nodes, each node has a link to next node.
It works rather well on it's own, but not when it contains another linked list.
LinkedList and Node looks something like that:
template <class T>
class LinkedList
{
    private:
        Node<T>* pPreHead;
    public:
        LinkedList(void);
        ~LinkedList(void);
        Node<T>* getHead(void);
        int size();
        void addElementToEnd(T& value);
        void deleteNextNode(Node<T>* pNodeBefore);
}

template <class T>
class Node
{
    private:
        T value;
        Node* next;
    public:
        Node();
        Node* getNext();
        Node* getValue();
        void setNext(Node* nextElem);
        void setValue(T elem);
};

Now for the task I need to use LinkedList>, which is filled via a loop.
It looks something like this:
ifstream fl;
fl.open("test1.in", std::ifstream::in);
while (fl.good())
{
    string currentLine;
    getline(fl, currentLine);

    LinkedList<string> newDNA;

    //newDNA being filled here so I skipped code

    DNAStorage.addElementToEnd(newDNA);

    //Place 1
}

//Place 2

Now if I insert some test output code in "Place 1" everything is fine, but when the loop enters new iteration newDNA variable gets freed and so is the pointer inside DNAStorage (which is LinkedList<LinkedList<string>> in question), and when I try to print anything in "Place 2" I get segmentation fault.
Unfortunately I can't use any other data structures since this is the kind of task I need to do.
My question is - how can this be fixed, so that it actually is not freed prematurely?
Edit:
Here's my code for AddElementToEnd(T& value):
template <class T>
void LinkedList<T>::addElementToEnd(T &value)
{
    Node<T> *newtail = new Node<T>;
    newtail.setNext(NULL);
    newtail.setValue(value);

    if(pPreHead == NULL)
    {
        pPreHead = newtail;
        return;
    }

    Node<T> *tail = pPreHead;
    while(tail.getNext() != NULL)
    {
        tail = tail.getNext();
    }

    tail.setNext(newtail);
}

A: The problem is that you are storing references to objects that are going out of scope, causing undefined behavior when you try and access them.  Your LinkedList<string> newDNA gets created and destroyed with each iteration of the while loop, yet you pass a reference to be stored in DNAStorage list.
One solution would be to store a copy of each object (not reference) in the list when addElementToEnd() gets called.


text:
Q: Pandas finding identical coulmns between twe dataframes I have to dataframes with different indexes and some shard coulmns (coulmn name + all values locations).
e.g.:
data1 = {"col1": ["A", "B", "C", "D"], "col2": ["E", "F", "G", "H"], "col3": ["Z", "Z", "Z", "Z"], "col4": ["Q", "Q", "Q", "Q"]}
df1 = pd.DataFrame(index=[0,1,2,3], data=data1)
data2 = {"col1": ["A", "B", "C", "D"], "col2": ["E", "F", "G", "H"], "col3": ["Z", "Z", "Z", "X"]}
df2 = pd.DataFrame(index=[4,5,6,7], data=data2)

df1
  col1 col2 col3 col4
0   A   E    Z    Q
1   B   F    Z    Q
2   C   G    Z    Q
3   D   H    Z    Q

df2
  col1 col2 col3
4   A   E    Z
5   B   F    Z
6   C   G    Z
7   D   H    X

I want the output to be only the identical coulmns (name+values location), even though indexing is different. In my example, It should be col1, col2.

A: First you get columns that are common by using intersection and then see if their values are all equal.
cols = df1.columns.intersection(df2.columns)
out = [col for col in cols if (df1[col].values == df2[col].values).all()]

print(out)

['col1', 'col2']

A: df1.loc[:, df1.eq(df2.set_axis(df1.index)).all()]

output:
  col1  col2
0   A   E
1   B   F
2   C   G
3   D   H


text:
Q: Correct way to check if a blob field has already been fetched when using poFetchBlobsOnDemand I have a TClientDataSet with several records, and I want o load all the records, but load the blob field on Demand, one at a time.
I noticed that calling FetchBlobs twice fetches the blob twice and also that checking the field's IsNull property always returns False.
So the only solution I found so far is to access a property like Value or BlobSize and if the blob has not been fetched an exception is raised EDBClient with message "Blob has not been fetched", so if this exception is raised I call the FetchBlobs.
Is there some better way of doing this?
  try
    cdsIMG.BlobSize;
  except
    on E: EDBClient do
      cds.FetchBlobs;
  end;

A: I'm not sure if this is 100% correct but it's the best I could do. See for yourself.
type
  THackCustomClientDataSet = class(TCustomClientDataSet);

function IsBlobFetched(DataSet: TCustomClientDataSet; BlobField: TField): Boolean;
var
  I: Integer;
  Status: DBResult;
  BlobLen: Cardinal;
begin
  Result := False;
  BlobLen := 0;

  with THackCustomClientDataSet(DataSet) do
    if Assigned(DSCursor) and (ActiveBuffer <> nil) then
    begin
      Status := DSCursor.GetBlobLen(ActiveBuffer, BlobField.FieldNo, BlobLen);
      case Status of
        DBERR_NONE:
          Result := True;
        DBERR_BLOBNOTFETCHED:
          ;
        else
          Check(Status);
      end;
    end;
end;

There seems to be DBERR_BLOBNOTFETCHED defined in DSIntf unit to be returned by GetBlobLen in case the blob has not been fetched yet. So that return code means 'blob not fetched', success return code means 'blob fetched already', and any other error code probably indicates some other error.
Inspired by TCustomClientDataSet.CreateBlobStream.

A: If you had to know if a blob's data had been retrieved, I believe, TOndrej's answer would be the way to go. But you don't have to..
When poFetchBlobsOnDemand is set in 'DataSetProvider's options, and FetchOnDemand is set on the 'ClientDataSet', the behavior is already as you describe. I.e. the client data set calls FetchBlobs only if the blob data has not already been retrieved and only when it is needed.
From "Provider.TProviderOption Enumeration":

poFetchBlobsOnDemand    BLOB fields are
  not included in data packets. [...] If the
  client dataset's FetchOnDemand
  property is true, the client requests
  these values automatically. [...]


text:
Q: How to identify the roles that taking up more cost in snowflakes Help me with the query that gives details of roles and cost contributed by each role to the over all billing.

A: The only way to accurately determine which roles are spending the most on your compute is to separate the warehouses by role, so that each role has their own warehouse cost.  Otherwise, it is very difficult to estimate the cost associated with a role based on their query history.  You could estimate it by dividing the per-second credit costs to each query by how many queries were executing at that time, but that's a complex query.  Your other choice is a rough-estimate by taking the total duration of queries for each role using query history.  That'll give you an idea of which roles are using the most compute, but not accurately by any means.


text:
Q: Subscribe to a property of a service from another component I have a property loggedIn on my authentication service that I need to be subscribed to by a few other services, how can I return an observable to let the other components subscribe to the property?
loggedIn: boolean;

// ...

loggedIn(): Observable<boolean>  {
    // ?
}

A: loggedIn: BehaviorSubject<boolean> = new BehaviorSubject(false);

loggedIn(): Observable<boolean> {
 return this.loggedIn;
}

The init value of being logged in is false. When you sign in, you need to call loggedIn.next(true) on it.


text:
Q: Toggling a system sound - swift I want to make it so that a button can be clicked, which will start repeatedly playing a system sound over and over (without overlapping the sounds) until the button is clicked again - so essentially, the button will toggle the repeated playing of an audio services system sound on/off.
If anyone would know how to do this I would greatly appreciate it.
Thanks

A: To do this use an AVAudioplayer with infinite repeat, and then pause/play it when button is pressed.
First make a audioPlayer variable, outside of any function:
var audioPlayer : AVAudioPlayer!

Then initialise the audioPlayer inside of viewDidLoad:
override func viewDidLoad() {
    super.viewDidLoad()

    guard let url = Bundle.main.path(forResource: "myOwnSound", ofType: "wav") else { //your own file name AND extension type of course
       print("file not found")
       return
    }
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
        try audioPlayer = AVAudioPlayer(contentsOf: URL(string: url)!)
        audioPlayer!.prepareToPlay()
        audioPlayer.numberOfLoops = -1
    } catch let error as NSError {
        print("error while initialising sound: \(error)")
    }
}

Then inside a function linked to your button, in my case I named that function buttonPressed:
@IBAction func buttonPress(_ sender:AnyObject){
    if audioPlayer.isPlaying {
       audioPlayer.pause()
    }
    else {
       audioPlayer.play()
    }
}

A:
You can use AVFoundation and AVAudioPlayer to manage music and
  sound inside you application

Import following
import AVFoundation

Create a property of  AVAudioPlayer to manage play/stop and add following code inside the scope of your music button
 var player : AVAudioPlayer?

@IBAction func openListAction(_ sender: UIButton) {
       // moveToGame()
        if sender.isSelected {
            sender.isSelected = false
            player?.stop()
        }
        else {
            sender.isSelected = true
            let bundle = Bundle.init(for: self.classForCoder)
            let path = bundle.path(forResource: "soundFileName", ofType : "soundFileExtension")! //.mp3, .caf etc
            let url = URL(fileURLWithPath : path)
            do {
                player = try AVAudioPlayer(contentsOf: url)
                player?.play()

            } catch {
                print ("Error to load music")
            }
        }
    }


text:
Q: Direct (and simple!) AJAX upload to AWS S3 from (AngularJS) Single Page App I know there's been a lot of coverage on upload to AWS S3. However, I've been struggling with this for about 24 hours now and I have not found any answer that fits my situation.
What I'm trying to do
Upload a file to AWS S3 directly from my client to my S3 bucket. The situation is:

*

*It's a Single Page App, so upload request must be in AJAX

*My server and my client are not on the same domain

*The S3 bucket is of the newest sort (Frankfurt), for which some signature-generating libraries don't work (see below)

*Client is in AngularJS

*Server is in ExpressJS

What I've tried

*

*Heroku's article on direct upload to S3. Doesn't fit my client/server configuration (plus it really does not fit harmoniously with Angular)

*ready-made directives like ng-s3upload. Does not work because their signature-generating algorithm is not accepted by recent s3 buckets.

*Manually creating a file upload directive and logic on the client like in this article (using FormData and Angular's $http). It consisted of getting a signed URL from AWS on the server (and that part worked), then AJAX-uploading to that URL. It failed with some mysterious CORS-related message (although I did set a CORS config on Heroku)

It seems I'm facing 2 difficulties: having a file input that works in my Single Page App, and getting AWS's workflow right.
The kind of solution I'm looking for
If possible, I'd like to avoid 'all included' solutions that manage the whole process while hiding of all of the complexity, making it hard to adapt to special cases. I'd much rather have a simple explanation breaking down the flow of data between the various components involved, even if it requires some more plumbing from me.

A: You can use the ng-file-upload $upload.http method in conjunction with the aws-sdk getSignedUrl to accomplish this.  After you get the signedUrl back from your server, this is the client code:
var fileReader = new FileReader();
fileReader.readAsArrayBuffer(file);
fileReader.onload = function(e) {
$upload.http({
  method: 'PUT',
  headers: {'Content-Type': file.type != '' ? file.type : 'application/octet-stream'},
  url: signedUrl,
  data: e.target.result
}).progress(function (evt) {
  var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
  console.log('progress: ' + progressPercentage + '% ' + file.name);
}).success(function (data, status, headers, config) {
  console.log('file ' + file.name + 'uploaded. Response: ' + data);
});

A: I finally managed. The key points were:

*

*Let go of Angular's $http, and use native XMLHttpRequest instead.

*Use the getSignedUrl feature of AWS's SDK, instead on implementing my own signature-generating workflow like many libraries do.

*Set the AWS configuration to use the proper signature version (v4 at the time of writing) and region ('eu-central-1' in the case of Frankfurt).

Here below is a step-by-step guide of what I did; it uses AngularJS and NodeJS on the server, but should be rather easy to adapt to other stacks, especially because it deals with the most pathological cases (SPA on a different domain that the server, with a bucket in a recent - at the time of writing - region).

Workflow summary

*

*The user selects a file in the browser; your JavaScript keeps a reference to it.

*the client sends a request to your server to obtain a signed upload URL.

*Your server chooses a name for the object to put in the bucket (make sure to avoid name collisions!).

*The server obtains a signed URL for your object using the AWS SDK, and sends it back to the client. This involves the object's name and the AWS credentials.

*Given the file and the signed URL, the client sends a PUT request directly to your S3 Bucket.

Before you start
Make sure that:

*

*Your server has the AWS SDK

*Your server has AWS credentials with proper access rights to your bucket

*Your S3 bucket has a proper CORS configuration for your client.

Step 1: setup a SPA-friendly file upload form / widget.
All that matters is to have a workflow that eventually gives you programmatic access to a File object - without uploading it.
In my case, I used the ng-file-select and ng-file-drop directives of the excellent angular-file-upload library. But there are other ways of doing it (see this post for example.).
Note that you can access useful information in your file object such as file.name, file.type etc.
Step 2: Get a signed URL for the file on your server
On your server, you can use the AWS SDK to obtain a secure, temporary URL to PUT your file from someplace else (like your frontend).
In NodeJS, I did it this way:
// ---------------------------------
// some initial configuration
var aws = require('aws-sdk');

aws.config.update({
  accessKeyId: process.env.AWS_ACCESS_KEY,
  secretAccessKey: process.env.AWS_SECRET_KEY,
  signatureVersion: 'v4',
  region: 'eu-central-1'
});

// ---------------------------------
// now say you want fetch a URL for an object named `objectName`
var s3 = new aws.S3();
var s3_params = {
  Bucket: MY_BUCKET_NAME,
  Key: objectName,
  Expires: 60,
  ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function (err, signedUrl) {
  // send signedUrl back to client
  // [...]
});

You'll probably want to know the URL to GET your object to (typically if it's an image). To do this, I simply removed the query string from the URL:
var url = require('url');
// ...
var parsedUrl = url.parse(signedUrl);
parsedUrl.search = null;
var objectUrl = url.format(parsedUrl);

Step 3: send the PUT request from the client
Now that your client has your File object and the signed URL, it can send the PUT request to S3. My advice in Angular's case is to just use XMLHttpRequest instead of the $http service:
var signedUrl, file;
// ...
var d_completed = $q.defer(); // since I'm working with Angular, I use $q for asynchronous control flow, but it's not mandatory
var xhr = new XMLHttpRequest();
xhr.file = file; // not necessary if you create scopes like this

xhr.onreadystatechange = function(e) {
  if ( 4 == this.readyState ) {
    // done uploading! HURRAY!
    d_completed.resolve(true);
  }
};
xhr.open('PUT', signedUrl, true);
xhr.setRequestHeader("Content-Type","application/octet-stream");
xhr.send(file);

Acknowledgements
I would like to thank emil10001 and Will Webberley, whose publications were very valuable to me for this issue.

A: To do multipart uploads, or those larger than 5 GB, this process gets a bit more complicated, as each part needs its own signature.  Conveniently, there is a JS library for that:
https://github.com/TTLabs/EvaporateJS
via https://github.com/aws/aws-sdk-js/issues/468

A: Use s3-file-upload open source directive having dynamic data-binding and auto-callback functions - https://github.com/vinayvnvv/s3FileUpload


text:
Q: Letting Hibernate know of hidden entity relationships Assuming that I have an entity which is mapped with Hibernate (E) and a view which queries the table of the entity, also mapped with Hibernate (V).
If I persist an instance of E and then query V in the same session, then hibernate does not flush the persistence queue since it does not know that the two entities are related, and therefore the result of the query on V will be incorrect.
I am currently flushing the session manually, but I find this a unsatisfying solution, since it assumes too much knowledge about the way the mappings are done.
What other options are there to make sure queries over views are correct?

A: The most straightforward approach is to use @Synchronize.
This behaviour is controlled by EntityPersister.getQuerySpaces().
You can try to override that method and configure Hibernate to use your custom persister with @Persister annotation. Check SessionImpl.autoFlushIfRequired() in debugger to find out how that spaces should look like (I guess they are names of dependent tables).


text:
Q: where can I find build files in eclipse? Im using eclipse to build a android application (java and c code)
where can I find (1) ant file and (2) c build file
auto generated in eclipse?
They are called ant and build.xml ?
I want to take them and edit a bit

A: Go to your eclipse workspace directory and run the following command -

find . -name build.xml
  find . -name ant

A: Press ctrl-shift-r and type build.xml, this will take you directly to the ant build script in the IDE.


text:
Q: In HTML, how do I select all images from a folder to be shown in img src Rather than listing a bunch of image sources, how do I just select all images in a folder.
Current HTML code looks like this...

Is there a way I can avoid listing each individual jpeg and just select all that are in a folder?
Thanks


text:
Q: FATAL: password authentication failed for user "postgresq" When I try to run my app on http://localhost:3000 I get following error
 FATAL: password authentication failed for user "postgresq".

Not sure what is the issue, because in database.yml file my password is correct:
default: &default
  adapter: postgresql
  database: Dzeus
  encoding: unicode
  username: postgresq
  password: mypassword
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

I'm able to connect to the database via pg admin program using the same password. Yesterday it worked fine but today something changed and I'm getting this error. Could you please help?


text:
Q: Keep bounty remark after it is ended Sometime I see bounties are set to gain the attention plus adding extra features to the question.
I cannot see the bounty remark after it is awarded or ended. So the answer may not be valid if the extra feature is added to the answer.
So IMHO the bounty remark(user comment on bounty) should be kept as it is the part of question.


text:
Q: Write data form specific csv cell to another file with python I have data in a csv file and need to put the content of specific cells in other files. Here is a simplified version of the csv file.
A;B;C;D
A1;B1;C1;D1
A2;B2;C2;D2
A3;B3;C3;D3
A4;B4;C4;D4

The csv file should be converted into a twodimensional array, preferably with numpy. After that the data from the array should be written into some other files. Here is a snippet of the simplified code.
import numpy
table = numpy.genfromtxt('table.csv', delimiter=';', skip_header=1)

for row in range (4):
    output = open('array %s.txt' %(row+1), 'w')
    for clmn in range (4):
        output.write('%s' %table[row][clmn])

output.close()

I have been struggeling finding out a proper way to put the data in the array. Any ideas how this could be realised or have you found any mistakes I made?

Edit: I have found the problem.
numpy was not properly installed.
I also had to make some tweaks to the code.
import numpy

#get table size
table = numpy.genfromtxt('table.csv', delimiter=';')
rows, cols = table.shape

#get table data
table = numpy.recfromtxt('table.csv', delimiter=';', dtype=str)

#write table in different files
for row in range(rows):
    output = open('array %s.txt' %row, 'w')
    for clmn in range(cols):
        output.write('%s\t' %table[row][clmn])
    output.close()

This is the new code and it outputs the files as intended
array 0.txt A  B   C   D
array 1.txt A1 B1  C1  D1
array 2.txt A2 B2  C2  D2
array 3.txt A3 B3  C3  D3
array 4.txt A4 B4  C4  D4

A: output.close() must be in the loop, Try with it:
import numpy

table = numpy.genfromtxt('table.csv', delimiter=';', skip_header=1)
rows, cols = table.shape
for row in range(rows):
    output = open('array %s.txt' % (row + 1), 'w')
    for clmn in range(cols):
        output.write('%s\t' % table[row][clmn])

    output.close()

A: If you don't need the numpy array, something like this might work for you.
import csv

with open('table.csv', 'r') as csv_file:
   reader = list(csv.reader(csv_file, delimiter=';'))

   # skips header line
   for row in range(1, len(reader)):
      with open('array %s.txt' % row, 'w') as out_file:
         for i in reader[row]:
            # Modify this line to change what the output file contains
            out_file.write('%s' % i)

A: You can write a csv with np.savetxt;
For example, taking your example as literal (is it really floats?)
In [1]: txt = b"""A;B;C;D
   ...: A1;B1;C1;D1
   ...: A2;B2;C2;D2
   ...: A3;B3;C3;D3
   ...: A4;B4;C4;D4
   ...: """.splitlines()

In [7]: table= np.genfromtxt(txt,delimiter=';',skip_header=1,dtype='U2')
In [8]: table
Out[8]:
array([['A1', 'B1', 'C1', 'D1'],
       ['A2', 'B2', 'C2', 'D2'],
       ['A3', 'B3', 'C3', 'D3'],
       ['A4', 'B4', 'C4', 'D4']],
      dtype='<U2')
In [9]: np.savetxt('test.csv',table,header='A,B,C,D',delimiter=',',fmt='%3s')
In [10]: cat test.csv
# A,B,C,D
 A1, B1, C1, D1
 A2, B2, C2, D2
 A3, B3, C3, D3
 A4, B4, C4, D4

Here I've written the same values back out, with different delimiter and formatting.
savetxt does, basically
 for row in table:
    f.write(fmt%tuple(row))

where fmt is one you provide in full, or created from your fmt:
In [11]: np.savetxt('test.csv',table,header='A,B,C,D',fmt='%s %s  %s   %s')
In [12]: cat test.csv
# A,B,C,D
A1 B1  C1   D1
...

So you could modify your write along these lines:
In [13]: for row in table:
    ...:     print('%s %s,%s;%s'%tuple(row))
    ...:
A1 B1,C1;D1
A2 B2,C2;D2
A3 B3,C3;D3
A4 B4,C4;D4


text:
Q: How can I put a table next to another on pdf using jsPdf I have a page with two graphics and two tables and I want to put those tables next to each other in a pdf, I'm using jsPDF, but when I put the second table it go right bellow the first one table, how can I put the table bellow??
Here is my code:
let canvas = document.getElementById('chart-s') as HTMLCanvasElement;
let canvas2 = document.getElementById('chart-m') as HTMLCanvasElement;
let canvasImg = canvas.toDataURL("image/jpg", 1.0);
let canvasImg2 = canvas2.toDataURL("image/jpg", 1.0);
let doc = new jsPDF();
doc.setFontSize(20);
doc.text(15, 15, `${moment().format("MMMM")} ${moment().format("YYYY")} - `+"Year");
doc.addImage(canvasImg, 'JPEG', 10, 20, 190, 70 );
doc.addImage(canvasImg2, 'JPEG', 10, 100, 190, 70 );

let tableOne = document.getElementById("table");
let res = doc.autoTableHtmlToJson(tableOne);
doc.autoTable({
  head: [[`${moment().subtract(1, "year").format("YYYY")}`, `${moment().format("YYYY")}`]],
  body: res.data,
  margin: {top: 175, right: 10},
  tableWidth: 85
});
let tableTwo = document.getElementById("mtable");
let resd = doc.autoTableHtmlToJson(tableTwo);
doc.autoTable({
  head: [[`${moment().subtract(1, "year").format("YYYY")}`, `${moment().format("YYYY")}`]],
  body: resd.data,
  margin: {right: 50, bottom: 175},
  tableWidth: 85
});

doc.save('canvas.pdf');


text:
Q: Sockets use threads instead of select() I have a question about multi sockets.
I know that I have to use select() for multi sockets. select() waits for a fd ...
But why we need to use select() when we can create a thread for each socket and perform accept() on each one seperatly ? Is it even a bad idea ? Is it just about "too many sockets, too many threads so" or what ??

A: It's true, you can avoid multiplexing sockets by instead spawning one thread for each socket, and then using blocking I/O on each thread.
That saves you from having to deal with select() (or poll() or etc); but now you have to deal with multiple threads instead, which is often worse.
Whether threads will be more of a hassle to manage than socket-multiplexing in your particular program depends a lot on what your program is trying to do.  For example, if the threads in your program don't need to communicate/co-operate with each other or share any resources, then a multithreaded design can work well (as would a multiprocess design).  On the other hand, if your threads all need to access a shared data structure or other resource, or if they need to interact with each other, then you've got a bit of a programming challenge on your hands, which you'll need to solve 100% perfectly or you'll end up with a program that "seems to work most of the time" but then occasionally deadlocks, crashes, or gives incorrect results due to incorrect/insufficient synchronization.  This phenomenon of "meta-stability" is much more common/severe amongst buggy multithreaded programs than in buggy single-threaded programs, since a multithreaded program's exact flow of execution will be different every time you run it (due to the asynchronous nature of the threads with respect to each other).
Stability and code-correctness issues aside, there are a couple of other problems particular to multithreading that you avoid by using a single-threaded design:

*

*Most OS's don't scale well above a few dozen threads.  So if you're thinking one-thread-per-client, and you want to support hundreds or thousands of simultaneous clients, you're in for some performance problems.

*It's hard to control a thread that is blocked in a blocking-socket call.  Say the user has pressed Command-Q (or whatever the appropriate equivalent is) so it's now time for your program to quit.  If you have one or more threads blocked inside a blocking-socket call, there's no straightforward way to do that:

*

*You can't just call unilaterally call exit(), because while the main thread is tearing down process-global resources, one or more threads might still be using them, leading to an occasional crash

*You can't ask the threads to exit (via atomic-boolean or whatever) and then call join() to wait for them, because they are blocking inside I/O calls and thus might take minutes/hours/days before they respond

*You can't send a signal to the threads and have them react in a signal-handler, because signals are per-process, and you can't control which thread will receive the signal.

*You can't just unilaterally kill the threads, because they might be holding resources (like mutexes or file handles) that would then remain unreleased forever, potentially causing deadlocks or other problems

*You can't close down the threads' sockets for them, and hope that this will cause the threads to error out and terminate, as this leads to race condition if the threads also try to close down those same resources.

*So even in a multithreaded design, if you want a clean shutdown (or any other sort of local control of a network-thread) you usually end up having to use non-blocking I/O and/or socket multiplexing inside each thread anyway, so now you've got the worst of both worlds, complexity-wise.


text:
Q: CORS from multiple origins I have a web service that I access from multiple domains. For reasons I'm unable to fathom, the session seems to be shared between different sites.

*

*So, I make a request from WebAppA to the API. This works.

*Then I make a same request from WebAppB, to the same web service. This reports that it's blocked due to the CORS policy, e.g.
 The 'Access-Control-Allow-Origin' header has a value 'WebAppA' that is not equal to the supplied origin.
 Origin 'WebAppB' is therefore not allowed access.

But the Tomcat code for the web service claims that it allows CORS:
I have this in my web.xml:
<param-name>Access-Control-Allow-Origin</param-name>
<param-value>*</param-value>

and this in the java class that handles requests:
if (StringUtils.isNotBlank(origin)) {
     response.setHeader("Access-Control-Allow-Origin", origin);
}

Logically, this should be allowing the requests from WebAppB through, but instead it still sees WebAppA as the only permitted origin.  Given the snippet above, one option that springs to mind is that the Origin header might be blank. But if it was, then surely it wouldn't say WebAppB isn't allow access, because it wouldn't know that the origin was WebAppB!?
Clearing the cache fixes the issue, so it's clearly session-associated somehow, but I can't see any cookies that look like they're relevant.
Question How can I fix this so that both webapp A and B can access the same web service, without clearing the cache in between?
Disclaimer: This is a follow-on from Possible CORS issue. What's going on and how can I fix it?, but I've done a lot more investigation since so I can define the issue more clearly. (I hope).

A: I suspect an error in org/intermine/webservice/server/WebService.java.
It says
origin = StringUtils.defaultIfBlank(
                    webProperties.getProperty("ws.response.origin"),
                    request.getHeader("Origin"));

The method parameters (src,default) are supplied in a wrong order, which causes the server to always return a default value in "Access-control-allow-origin", instead of considering the actual current request...


text:
Q: What port numbers are used by Mobility Agent installed on On-Premise machine to communicate with Process Server in Azure ASR? Which ports the on-premise mobility agent communicates with to transfer the data to process server ? I need to know the ports used on On-Premise server by the Mobility Agent.

A: It uses port 443, As Telnet from the process server on port 443.
telnet  443, If the telnet is working there will be No issues from client to the process server connectivity!
9443 port uses for on-promises to Process server - data
Mobility agent send data using port 9443 to PS, Process Server send data to azure Storage using port 443


text:
Q: Get domain name from IP address in Go I'm trying to resolve the host name from an IP address, which is apparently proving to be a little more challenging than I thought it'd be.
I've tried using a couple of functions, including the net.LookupHost method, but all of them seem to be just returning the IP address which I input.
Here's the code which I am using:
package main

import (
    "fmt"
    "net"
)

func main() {
    // obtained from ping -c 1 stackoverflow.com, should print "stackoverflow.com"
    addr, err := net.LookupHost("198.252.206.16")
    fmt.Println(addr, err)
}

A: You need LookupAddr instead of LookupHost.

A: For example,
package main

import (
    "fmt"
    "net"
)

func main() {
    // obtained from ping -c 1 stackoverflow.com, should print "stackoverflow.com"
    addr, err := net.LookupAddr("198.252.206.16")
    fmt.Println(addr, err)
}

Output:
[stackoverflow.com.] <nil>


text:
Q: Downloading a PDF file using VueJS and GraphQL, however first download results in a network error I am running a frontend application via VueJS on my local machine that queries GraphQL. One of the queries is a download which works fine, however I think there is an issue with my javascript code. Everytime I click the download button it triggers the download function, i.e. @click="download".
The download functions are as follows (the bottom one runs first):
sleep(ms) {
            return new Promise((resolve) => {
                setTimeout(resolve, ms);
            });

downloadFile() {
            const vm = this;
            vm.count ++;
            axios.post("http://0.0.0.0/graphql", {
            query:
            `mutation download_doc($object_path:String!) {
                download_doc(object_path:$object_path) {
                    file_name
                    encoded_file
                }
                }
            `,
            variables : {
                object_path: this.object_path
            }
            })
            .then(response => vm.file_info = response.data.data.download_doc.encoded_file)
            .then(function() { console.log(vm.file_info);})
        },

downloadBase64File(base64Data, fileName) {
            const linkSource = `data:text/plain;base64,${base64Data}`;
            const downloadLink = document.createElement("a");
            downloadLink.href = linkSource;
            downloadLink.download = fileName;
            downloadLink.click();
        },

async download() {
            this.downloadFile();
            await this.sleep(1000);
            this.downloadBase64File(this.file_info, this.object_path);
            await this.sleep(1000);
            if (this.count >= 2) {
                this.clearForm()
            }

However, on the first click, I get a network error and it only downloads on the second click. Sometimes third click for particularly large files, with the second click also resulting in a failed network error.
I am relatively new to using javascript so not sure if the fix is easy. Does anyone know how to resolve this issue?


text:
Q: Pop Up HTML Image when clicked Hi so I have a few pictures on a website that im creating (Please not im learning as I go along). I would like users to be able to click the image and view a full a pop up of the image, so like the original size of the actual image, I have added the code for the pictures below.

Marble

Marble

Marble

Hover:
.image.fit >img:hover {
            width: 1000px;
            height: 1000px;
            position: absolute;
        }

A: The span elements should be completely removed and its classes placed on the image elements themselves.
Also, you have a nested section element that isn't doing anything for you.
Lastly, do not use HTML heading elements (
...
) because of the way they style the text. Formatting is the job of CSS. Instead of headings, it is more appropriate to surround each image and its accompanying text with figure and figcaption elements.

img {
  width:200px;
  border:1px solid black; /* This is only added for testing purposes*/
}

.thumbnail:hover {
   width: 500px;
   height:auto;
   position:relative;
   /* push image to the right by 1/2 the screen width and 1/2 the image width */
   margin-left:calc(50% - 250px);
}

Marble

Marble

Marble

A: I've taken Scott Marcus' answer and adapted to click, which was your original request.
The main diffence is the addition of a tags targeting elements on the page and using :target in the css.

img {
  width:200px;
  border:1px solid black; /* This is only added for testing purposes*/
}

.thumbnail:target {
   width: 500px;
   height:auto;
   position:relative;
   /* push image to the right by 1/2 the screen width and 1/2 the image width */
   margin-left:calc(50% - 250px);
}

Marble

Marble

Marble


text:
Q: Can't initialize repository (mapped network drive) I've got a mapped network location "E:\folder\subfolder" where I have my project which I'd like to sync to github.
In VS code,

*

*clicking on "intialize repository",

*the command line ask a folder,

*the preset is fine (although manually browsing is the same)

*nothing happens

Doing the same procedure on
"C:\folder\subfolder": works just fine.
How to fix this?
I tried setting the permissions (which were already good, but tried 'full control' as well).
(mapped drive "E" is a NAS folder)
2022-11-06 19:15:18.574 [info] Validating found git in: C:\Program Files\Git\cmd\git.exe
2022-11-06 19:15:18.607 [info] Using git 2.38.1.windows.1 from C:\Program Files\Git\cmd\git.exe
2022-11-06 19:15:18.696 [info] > git rev-parse --show-toplevel [83ms]
2022-11-06 19:15:18.696 [info] fatal: detected dubious ownership in repository at '//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle'
'//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle' is owned by:
    'S-1-5-21-2272522387-2785212326-2585521355-3048'
but the current user is:
    'S-1-5-21-3398360568-3200424794-839922802-1001'
To add an exception for this directory, call:

    git config --global --add safe.directory '%(prefix)///192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle'
2022-11-06 19:15:18.746 [info] > git rev-parse --show-toplevel [46ms]
2022-11-06 19:15:18.746 [info] fatal: detected dubious ownership in repository at '//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle'
'//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle' is owned by:
    'S-1-5-21-2272522387-2785212326-2585521355-3048'
but the current user is:
    'S-1-5-21-3398360568-3200424794-839922802-1001'
To add an exception for this directory, call:

    git config --global --add safe.directory '%(prefix)///192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle'
2022-11-06 19:15:18.799 [info] > git rev-parse --show-toplevel [50ms]
2022-11-06 19:15:18.800 [info] fatal: detected dubious ownership in repository at '//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension'
'//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension' is owned by:
    'S-1-5-21-2272522387-2785212326-2585521355-3048'
but the current user is:
    'S-1-5-21-3398360568-3200424794-839922802-1001'
To add an exception for this directory, call:

    git config --global --add safe.directory '%(prefix)///192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension'
2022-11-06 19:15:18.833 [info] > git rev-parse --show-toplevel [31ms]
2022-11-06 19:15:18.833 [info] fatal: detected dubious ownership in repository at '//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle'
'//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle' is owned by:
    'S-1-5-21-2272522387-2785212326-2585521355-3048'
but the current user is:
    'S-1-5-21-3398360568-3200424794-839922802-1001'
To add an exception for this directory, call:

    git config --global --add safe.directory '%(prefix)///192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle'
2022-11-06 19:15:18.886 [info] > git rev-parse --show-toplevel [50ms]
2022-11-06 19:15:18.886 [info] fatal: detected dubious ownership in repository at '//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle'
'//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle' is owned by:
    'S-1-5-21-2272522387-2785212326-2585521355-3048'
but the current user is:
    'S-1-5-21-3398360568-3200424794-839922802-1001'
To add an exception for this directory, call:

    git config --global --add safe.directory '%(prefix)///192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle'
2022-11-06 19:15:18.963 [info] > git rev-parse --show-toplevel [41ms]
2022-11-06 19:15:18.963 [info] fatal: detected dubious ownership in repository at '//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle'
'//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle' is owned by:
    'S-1-5-21-2272522387-2785212326-2585521355-3048'
but the current user is:
    'S-1-5-21-3398360568-3200424794-839922802-1001'
To add an exception for this directory, call:

    git config --global --add safe.directory '%(prefix)///192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle'
2022-11-06 19:15:53.100 [info] > git rev-parse --show-toplevel [108ms]
2022-11-06 19:15:53.100 [info] fatal: detected dubious ownership in repository at '//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension'
'//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension' is owned by:
    'S-1-5-21-2272522387-2785212326-2585521355-3048'
but the current user is:
    'S-1-5-21-3398360568-3200424794-839922802-1001'
To add an exception for this directory, call:

    git config --global --add safe.directory '%(prefix)///192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension'
2022-11-06 19:16:19.893 [info] > git rev-parse --show-toplevel [46ms]
2022-11-06 19:16:19.893 [info] fatal: detected dubious ownership in repository at '//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension'
'//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension' is owned by:
    'S-1-5-21-2272522387-2785212326-2585521355-3048'
but the current user is:
    'S-1-5-21-3398360568-3200424794-839922802-1001'
To add an exception for this directory, call:

    git config --global --add safe.directory '%(prefix)///192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension'
2022-11-06 19:16:34.246 [info] > git rev-parse --show-toplevel [47ms]
2022-11-06 19:16:34.246 [info] fatal: detected dubious ownership in repository at '//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension'
'//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension' is owned by:
    'S-1-5-21-2272522387-2785212326-2585521355-3048'
but the current user is:
    'S-1-5-21-3398360568-3200424794-839922802-1001'
To add an exception for this directory, call:

    git config --global --add safe.directory '%(prefix)///192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension'
2022-11-06 19:16:40.597 [info] > git rev-parse --show-toplevel [90ms]
2022-11-06 19:16:40.597 [info] fatal: detected dubious ownership in repository at '//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension'
'//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension' is owned by:
    'S-1-5-21-2272522387-2785212326-2585521355-3048'
but the current user is:
    'S-1-5-21-3398360568-3200424794-839922802-1001'
To add an exception for this directory, call:

    git config --global --add safe.directory '%(prefix)///192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension'
2022-11-06 19:16:40.633 [info] > git rev-parse --show-toplevel [33ms]
2022-11-06 19:16:40.633 [info] fatal: detected dubious ownership in repository at '//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension'
'//192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension' is owned by:
    'S-1-5-21-2272522387-2785212326-2585521355-3048'
but the current user is:
    'S-1-5-21-3398360568-3200424794-839922802-1001'
To add an exception for this directory, call:

    git config --global --add safe.directory '%(prefix)///192.168.2.151/Google Drive __ pyfiddle/github test/py_fiddle/pyfiddle.extension'

A: Show us your git log:

*

*Type Ctrl + Maj + P (As the same time), a typebox open

*Type Terminal: Focus on Terminal View

*Go to Output tab

*In the dropdown list select Git
Copy an paste the content


text:
Q: returning a mysql query from a selection in a drop down box Hi I have created a drop down combo box on a form using a mysql query of 3 tables and this is working fine, now I want to perform another query on the datasabase when I select an item in the drop down combo with this running a query on the database and returning the values required to populate the form with additional data in defined fields.
below is how far I have got to date....
$query3 = "SELECT customers.id, customers.email, customers_customfields.customer_id, customers_customfields.field_value, orders.sign_date, orders.sub_id, orders.domain_name, orders.cust_status
FROM customers, customers_customfields, customers_orders, orders
WHERE customers_orders.order_id = orders.sub_id
AND customers.id = customers_orders.customer_id
AND customers.id = customers_customfields.customer_id
AND customers_customfields.field_id = 1";

$result = mysql_query ($query3);
echo "<select name=orders value='Select from the list provided '>";

while($drop=mysql_fetch_array($result)){

//data stored in $drop
echo "<option value=$drop[id]>$drop[sub_id]    $drop[id]  $drop[field_value]  $drop[sign_date]  $drop[domain_name]    $drop[cust_status]</option>";

}
echo "</select>";

A: PHP is strictly a server-side language. If you want to have fields from a database dynamically update the application for the user (without having to submit and refresh), you're going to have to use AJAX.
Read through some AJAX tutorials to get the general idea.
Also, it would be a good idea to use a database abstract layer such as PDO.
It's helpful in almost any context, allowing for the use of prepared statements, as well as other goodies. Also, use MySqli in place of MySql, which is deprecated.
Ajax tutorials: http://www.smashingmagazine.com/2008/10/16/50-excellent-ajax-tutorials/
PDO: http://php.net/manual/en/book.pdo.php
Prepared statements: http://php.net/manual/en/pdo.prepared-statements.php
MySqli: http://php.net/manual/en/book.mysqli.php

A: You should indeed work with AJAX and PHP.
For example, first set a jQuery.change trigger on your dropdown doing like this:
$(document).ready(function () {

    $('#yourDropDown').change(function (e) {
        yourFunction($(this).val());
    });
});

function yourFunction(inputString) {
        $.ajax({

            url: "../folder/yourPHP.php",
//The inputString will contain the value of your DropDown, you will give this parameter in the querystring
            data: 'queryString=' + inputString,
            success: function (msg) {
//MSG will be the "message" from the query
//As you see you'll put the MSG in your HTML of your #yourFormTag
//This message can contain everything you want
                if (msg.length > 0) {
                    $('#yourFormTag').html(msg);

                }
            }
        });
}

Just AN Example of A .PHP file:
<?php
if (isset($_REQUEST['queryString'])) {

    include '../yourConnection.php';

    $inputString = $_GET['queryString'];

    $select_query = "SELECT <yourColumns>

            FROM <yourTable>
            WHERE <Where you want to check if inputString is the same> LIKE CONCAT('%', :inputString, '%')
            ORDER BY <order if you want? ASC";

    $get = $db->prepare($select_query);

    $get->execute(array(':inputString' => $inputString);

    //For example to fill a select
    echo '<select>';

    while ($row = $get->fetch(PDO::FETCH_ASSOC)) {
        echo "<option value='" . $row['yourColumn'] . "'>" . $row['yourColumn'] . "</option>";
    }

    echo '</select>';

}
?>

As I said the .PHP file is an example.
Hope this helps, Cheers!


text:
Q: Making a tensor with the outside dimension ragged Suppose you have a tf.data.Dataset of the following definition:
tf.data.Dataset.from_generator(gen, output_signature=(
            tf.TensorSpec(shape=(1, self.n_channels, self.height, self.width)),
            tf.RaggedTensorSpec(shape=(1, None, self.agent_dim), ragged_rank=1)
        ))

These ones in the beginning do not do you any good, since using .batch(batch_size) on this Dataset adds another dimension. Now you have two approaches: to reshape ragged tensors as soon as they get into keras.Model.train_step, squeezing the excess dimensions, or to drop this 1 in tf.RaggedTensorSpec(shape=(1, None, self.agent_dim), ragged_rank=1).

*

*For the first one, can one cast a RaggedTensor to a shape? A related question

*For the second one, can one create a RaggedTensor with the first dimension being None?

Thank you for your attention in advance


text:
Q: Oracle SQL : summarize genealogy data into sequential order I have a parent-child relationship table as below
src_data      date       dst_data         key
---------------------------------------------
P1         2018-01-01       D2            123
D2         2018-01-02       D3            123
D3         2018-01-03       D4            123

I wanted to create a query/SQL to display as below
key        link
-----------------
123        P1
123        D2
123        D3
123        D4

How can I do it? Thank you for the help.

A: Although, your question is not pretty much clear but below is the query for the required output
SELECT srcData as Link, KEY
FROM tableA
UNION
SELECT dst_data As Link, Key
FROM tableA

A: If you use a hierarchical query, the rows are already ordered as you want it:
SELECT key, src_data, dst_data
  FROM t
 WHERE key = 123
 START WITH src_data = 'P1'
 CONNECT BY src_data =  PRIOR dst_data;

123 P1  D2
123 D2  D3
123 D3  D4

Does that answer your question?

A: Use self full outer join and add some type of order sequence or primary key. And please try to prepare test data next time to save us time typing:
WITH test_data AS
(
SELECT 1 row_seq, 'P1' src_data,  '2018-01-01' src_date,  'D2' dst_data, 123 data_key FROM dual
UNION ALL
SELECT 2, 'D2', '2018-01-02', 'D3', 123  FROM dual
UNION ALL
SELECT 3, 'D3', '2018-01-03', 'D4', 123  FROM dual
)
SELECT NVL(a.src_data, b.dst_data) all_data
FROM test_data a FULL OUTER JOIN test_data b ON a.src_data = b.dst_data
ORDER BY a.row_seq
/

Output - you can add the rest of columns:
ALL_DATA
---------
P1
D2
D3
D4


text:
Q: How can I debug a process started from another process? I have a hub application that is responsible for handling the launching of three other programs. I am having considerable difficulty with this - When I launch one of the three alone, everything is fine; when I try to run them from the main hub application, they crash.
I need to figure out how I can keep the hub open, and open the process I start with the debugger after it launches right off, so I can catch the issues and debug it properly.
To give an example for how I am starting the processes from the main program -
this.Hide( );
Process.Start( FilePath).WaitForExit( );
Process.GetCurrentProcess( ).Kill( );

A: Visual Studio has a setup that allows it to debug any application that crashes before calling ExitProcess() and in case the process threw an exception, if the exception is not caught (i.e. try + catch(...) + exit(1)).
I always let the installer turn on that feature, but if you have it turned off, you should be able to turn it back on by going in the settings. Once one, on a crash, you get a message box asking you whether you want to debug the crashing process.


text:
Q: How can I calculate the eigenvalues of a symbolic matrix in Python? import sympy
p1, p2, p3 = sympy.symbols('p1, p2, p3')

A  = sympy.Matrix([(p1+p2+p3) + 5, p2, p3],[p1, (p1+p2+p3) + 8, p3],[p1, p2, (p1+p2+p3) + 8] )

print(A.eigenvals())

I get an error of the values not being integers. What is the proper way to calculate this?

A: You need another [ and ] inside the Matrix:
A  = Matrix([[(p1+p2+p3) + 5, p2, p3],[p1, (p1+p2+p3) + 8, p3],[p1, p2, (p1+p2+p3) + 8]])

will construct the matrix without raising an error.


text:
Q: How to use Derby database with Using Join And aggregate functions together? I have  two table in my data base As below:
CUSTOMER (
  ID integer Generated Always As Identity,
  FIRSTNAME varchar(32) not null,
  LASTNAME varchar(32) not null,
  PHONENUMBER varchar(11) not null,
  ADDRESS varchar(225),
primary key (id)
);

and
APP.ORDERS (
  ID integer not null default AUTOINCREMENT: start 1 increment 1,
  CUSTOMER_ID integer References Customer(ID) ,
  EMPLOYEEID integer References Employee(ID),
  DATEOFDELIVERY date,
  primary key (id),
);

When I try To join This two table as below every thing is fine:
 SELECT CUSTOMER_ID,firstname,LASTNAME,Address,phoneNumber From APP.Customer
 INNER JOIN APP.Orders ON customer.ID = customer_ID
 WHERE ORDERS.dateOfDelivery Between '2012-09-01' AND '2012-11-11'

but When I use Aggregate Function as below it give me Error:
SELECT Count(CUSTOMER_ID),firstname,LASTNAME,Address,phoneNumber
From APP.Customer
INNER JOIN APP.Orders ON customer.ID = customer_ID
WHERE ORDERS.dateOfDelivery Between '2012-09-01' AND '2012-11-11' ;

Error:
[2012-07-20 08:07:04] [42Y35][30000] Column reference 'FIRSTNAME' is invalid. When the SELECT list contains at least one aggregate then all entries must be valid aggregate expressions.

I try to change the last code above to Orders.Count(CUSTOMR_ID) to tell the database the correct table but it give me error that there is no schema with name Orders so I change it to APP.Orders.Count(CUSTOMER_ID) but it never solve the problem.
 Error :Schema 'ORDERS' does not exist
UPDATING QUESTION:
I Figur out that very simple Query Like :
SELECT COUNT(*),ID FROM Orders

will caused to This Error :
[2012-07-20 09:01:50] [42Y35][30000] Column reference 'ID' is invalid. When the SELECT list contains at least one aggregate then all entries must be valid aggregate expressions.

So It means that it is not possible to have both aggregate function and simple column names together but I am wonder how to supply the expected out put with any equivalent Query?Any Idea?

A: GROUP BY is the correct approach. You need to group by all the non-aggregate columns, as in:
SELECT Count(CUSTOMER_ID),firstname,LASTNAME,Address,phoneNumber
From APP.Customer
INNER JOIN APP.Orders ON customer.ID = customer_ID
WHERE ORDERS.dateOfDelivery Between '2012-09-01' AND '2012-11-11'
group by firstname,lastname,address,phonenumber;

Think about it this way: you want to gather together all the orders for a particular customer (that's what GROUP BY does), then you want to count up all those orders (that's what the COUNT() function does).

A: Try this
SELECT CUSTOMER_ID,Count(CUSTOMER_ID),firstname,LASTNAME,Address,phoneNumber
From APP.Customer
INNER JOIN APP.Orders ON customer.ID = customer_ID
WHERE ORDERS.dateOfDelivery Between '2012-09-01' AND '2012-11-11'
GROUP BY CUSTOMER_ID,firstname,LASTNAME,Address,phoneNumber

A: The equivalent query in derby database is as below :
SELECT customer.firstName As FirstName ,
       customer.lastName AS LastName,
       customer.phoneNumber AS Telephone,
       customer.address AS Address,
       (SELECT COUNT(OrderID) FROM Orders)
  FROM Customer join Orders On orders.customer_ID = customer.id WHERE orders.dateOfDelivery Between '2012-09-01' And '2012-11-11'

The fact is that this database can not realize queries that contains both aggregation function  and column name together like other data bases. The equivalent query that I mentioned will give the same out put but according to http://old.nabble.com/Nested-query-in-conjunction-with-ordering---unreasonably-slow-td15259785.html its performance is not good.The Query that mentioned by Bryan Pendleton also is true equivalent for this query.


text:
Q: Perl select function hanging indefinitely I am sorry for this really basic question but I do not seem to find root cause of my issue.
Environment details:
Perl 5.14.1
Connecting to MS SQL Server via freeTDS tsql
Linux x64
Here is my code:
#!/usr/bin/perl -w
use IO::Select;
use strict;

my $query = "";
my $s = IO::Select->new();
$s->add(\*STDIN);
my @STD_IN = ();
if ($s->can_read(.5)) {
      @STD_IN = <STDIN>;
        }
$query .= "@STD_IN\n@ARGV";

my $myTmpFile = `mktemp /tmp/$ENV{USER}QueryXXXX`; chomp($myTmpFile);
`echo "use testDB\n$dbQuery\ngo\nquit" > $myTmpFile`;

print(`/usr/bin/tsql -H myhost -p 9999 -U myuser -P mypass -o q < $myTmpFile`);

When I run this script, like this
$>./myscript "select * from mytable"

it works fine sometimes but often I see the script hanging indefninitly.
I did some debugging by running ps -ef here is how it looks:
kedar 24659 24574  0 05:50 ttyp3    00:00:00 /usr/bin/perl -w /home/kedar/myscript select * from mytable

What can be the cause for hang here? I do not understand yet - it is a very simple script.
I checked the perl documentation for IO::Select and this is what it says -
can_read

$s->can_read([timeout])
Returns array of handles that are ready for reading. timeout is the maximum amount of time to wait before returning an empty list. If timeout is not given, and any handles are registered, then the call blocks.

But I do have timeout in my script.
Any idea? Please help as I am stuck with issue
PS: Some variables, filenames and other things have been modified from original due to few constraints.
Also, this script is written by someone else previously and I need to fix the hang first. So if you can think of alternate and clean way of doing this - it would be great !

A: @STD_IN = <STDIN> reads from the filehandle STDIN in list context, meaning it will block until it receives an eof on the filehandle. The functions of IO::Select, on the other hand, will just tell you if there is any input on the selected filehandle, not whether it contains all the input.
So in this case you want to read STDIN in scalar context(*). It could look something like this:
if ($s->can_read(.5)) {
    push @STD_IN, scalar <STDIN>;
    # check if there is more than one line of input ready ...
    while ($s->can_read(0)) {
        push @STD_IN, scalar <STDIN>;
    }
}

(*) - scalar context might not be sufficient here, either. Scalar context will read from the filehandle up until the next end-of-line character or character sequence. For buffered input or unstructured input, IO::Select might tell you that input is available but that input might not contain a new line, and a scalar <STDIN> call will block. In that case, you may have to resort to loading input one character at a time (with getc, or read/sysread) or, if your OS supports it, setting up a non-blocking filehandle.

A: It might be hung waiting for STDIN as others have suggested, but one other thing to look into: are you sure that it is not the tsql command that is hanging? When you see a hung perl process, do you ALSO see a hung tsql process?
With backtick, the command is run synchronously, and control is not handed back to the next line of your Perl script until that command finishes. So if that hangs, your perl script will hang too, waiting for that tsql system command to finish.

A: This code is (conditionally) trying to read from standard input, i.e. you, where it says<STDIN>. The "hang" is waiting for you to type something. Or more likely this code was designed to have something piped into it. Try typing ctrl-d next time it "hangs", to verify.

A: ./myscript "select * from mytable"

Inside double quotes "*" is expanded by Bash to a list of files in the current directory. Use single quotes to use the string verbatim.


text:
Q: Extract embedded file from PDF with python CSV inside PDF
See picture.

Been trying to extract an embedded csv file from the PDF doc using pyPDF2 but I just dont understand PDF and cant seem to get a useful error response.

Tried using the stream method, outline method, cached... nothing
How do I extract the CSV file?
Thanks!

A: #This module contains all the functions for working with PDF documents.
import PyPDF2 as pf

# Step 1 Read pdf into a variable
pdf = pf.PdfFileReader('*your file location*')

# Step 2 "The process of traversing the PDF tree structure"

catalog = pdf.trailer['/Root']
fDetail = catalog['/Names']['/EmbeddedFiles']['/Names']
soup = fDetail[1].getObject()

# Step 3 Stream data to a variable for further use
file = soup['/EF']['/F'].getData()

Further information can be found on these 2 resources
https://pythonhosted.org/PyPDF2/
https://fossies.org/dox/openslides-2.3-portable/classPyPDF2_1_1generic_1_1EncodedStreamObject.html

A: You have to have 50 reputation to comment so I'll just respond here but you can treat this as a comment under ClaudNova's answer.
His code worked for me, apart from the PDF structure. It gave me a key error for the second [/Names]. I just changed this:
    fDetail = catalog['/Names']['/EmbeddedFiles']['/Names']

to this:
    fDetail = catalog['/Names']['/EmbeddedFiles']['/Kids'][0].getObject()['/Names']

Hope this helps.
Edit, this was used to extract an embedded JSON file from the PDF rather than a CSV. I'm unsure if that changes anything.


text:
Q: The vanishing of covariant derivative of an alternative metric tensor Let $(M,g)$ be a Riemannian manifold, endowed with the Levi-Civita connexion $\nabla$ induced by $g$. By the very definition of the Levi-Civita connexion $\nabla$, we indeed know that $\nabla g=0$, i.e., the (total) covariant derivative of the metric tensor vanishes. Now assume that $G$ is another metric tensor field on $M$, such that it satisfies $\nabla G=0$, that is, the (total) covariant derivative of this alternative metric tensor vanishes, as well.
I have realised that trivially $G=k g$, where $k\in\mathbb{R}^+$, is a solution for $\nabla G=0$. However, I am interested to know whether this is the most general case, or else if there are other alternative metric tensors $G$ with vanishing covariant derivatives (with respect to the Levi-Civita connextion induced by $g$), which are not positive multiples of the original metric tensor $g$.

A: In an irreducible Riemannian manifold $(M,g)$, every symmetric tensor that satisfies $\nabla^{g}T=0$ must be of the form $T=kg$ for some constant $k$. See Theorem 10.3.2 in Chapter 10 of Peter Peterson's Riemannian geometry, 3rd Edition. It is shown there how to use this fact to conclude that irreducible symmetric spaces are in fact Einstein manifolds.
In a reducible manifold,  this mustn't be the case: given $(M,g)$ simply connected and complete, a theorem of de Rham tells us that it can be written as a product $(M,g)=(M_{1}\times...\times M_{n},g_{1}+...+g_{n})$, where the sum of the metric tensors is orthogonal, and each $(M_{i},g_{i})$ is an irreducible space. Then, one can define $T=k^{i}g_{i}$ for any real constants $k^{i}$, which may be different from one another. Thus $T$ is not a multiplication of $g$ by a factor. If $(M,g)$ is not simply-connected or not complete, then this simply becomes a local argument, where $M$ and $M_{i}$ are replaced with local simply connected neighborhoods.
The example above in the comments is a private case of this: a locally-flat space can always be locally decomposed into an orthogonal Riemannian products of $\mathbb{R}$.
I suspect that the other direction is also true, namely that every $\nabla^{g}T=0$ must be locally of this form. But I have no reference for this nor verified this myself.


text:
Q: Table column split issue in XSL I am pullng my hair to find the error in this code, my table column is cutting into two line but I want to display the column data in single line. Same table is used for displaying data in other senario and works fine. I belive the column data "Data Not Available" is pulling the content into 2 lines, anyinput wil be a great help.

<xsl:for-each select="webpage/param">

    <xsl:if test="@type !='i'">

    <xsl:if test="@indent !=''">

        <xsl:variable name="count" select="@indent"/>
        <xsl:for-each select="(//*)[position()<=$count]">
            <xsl:text> </xsl:text>
        </xsl:for-each>

    </xsl:if>
    <xsl:choose>
        <xsl:when test="@isBold='1'">
            <xsl:value-of select="@name"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="@name"/>
        </xsl:otherwise>
    </xsl:choose>
    <xsl:text> </xsl:text>
    <xsl:text> </xsl:text>
    <xsl:text> </xsl:text>
    <xsl:text> </xsl:text>
    <xsl:text> </xsl:text>
    <xsl:text> </xsl:text>
    <xsl:text> </xsl:text>
    <xsl:text> </xsl:text>
    <xsl:text> </xsl:text>
    <xsl:text> </xsl:text>

    </xsl:if>

A: Try using style

  <xsl:value-of select="@name"/>


text:
Q: Calculating average by using the previous row's value and following row's value I have calculated average values for each month. Some months are NULL and my manager wants me to use the previous row's value and following month's value and fill the months which are having NULL values.
Current result (see below pic):

Expected Result

DECLARE @DATE DATE = '2017-01-01';
WITH DATEDIM AS
(
  SELECT DISTINCT DTM.FirstDayOfMonth
  FROM DATEDIM DTM
  WHERE Date >= '01/01/2017'
  AND Date <= DATEADD(mm,-1,Getdate())
),
Tab1 AS
(
  SELECT
    T1.FirstDayOfMonth AS MONTH_START,
    AVG1,
    ROW_NUMBER() OVER (
      ORDER BY DATEADD(MM,DATEDIFF(MM, 0, T1.FirstDayOfMonth),0) DESC
    ) AS RNK
  FROM DATEDIM T1
  LEFT OUTER JOIN (
    SELECT
      DATEADD(MM,DATEDIFF(MM, 0, StartDate),0) MONTH_START,
      AVG(CAST(DATEDIFF(dd, StartDate, EndDate) AS FLOAT)) AS AVG1
    FROM DATATable
    WHERE EndDate >= StartDate
    AND StartDate >= @DATE
    AND EndDate >= @DATE
    GROUP BY DATEADD(MM,DATEDIFF(MM, 0, StartDate),0)
  ) T2 ON T1.FirstDayOfMonth = T2.MONTH_START
)
SELECT *
FROM Tab1

A: Using your CTEs
select MONTH_START,
    case when AVG1 is null then
       (select top(1) t2.AVG1
        from Tab1 t2
        where t1.RNK > t2.RNK and t2.AVG1 is not null
        order by t2.RNK desc)
    else AVG1 end AVG1,
    RNK
from Tab1 t1

Edit
Version for an average of nearest peceding and nearest following non-nulls. Both must exist otherwise NULL is returned.
select MONTH_START,
    case when AVG1 is null then
     ( (select top(1) t2.AVG1
        from Tab1 t2
        where t1.RNK > t2.RNK and t2.AVG1 is not null
        order by t2.RNK desc)
       +(select top(1) t2.AVG1
        from Tab1 t2
        where t1.RNK < t2.RNK and t2.AVG1 is not null
        order by t2.RNK)
      ) / 2
    else AVG1 end AVG1,
    RNK
from Tab1 t1

A: You can manipulate previous and following row values using window functions:
SELECT MAX(row_value) OVER(
  ORDER BY ... ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS Previous_Value,
MAX(row_value) OVER(
  ORDER BY ... ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) AS Next_Value

Alternatively you can use LAG/LEAD functions and modify your sub-query where you get the AVG:
SELECT
  src.MONTH_START,
  CASE
    WHEN src.prev_val IS NULL OR src.next_val IS NULL
      THEN COALESCE(src.prev_val, src.next_val) -- Return non-NULL value (if exists)
    ELSE (src.prev_val + src.next_val ) / 2
  END AS AVG_new
FROM (
  SELECT
    DATEADD(MM,DATEDIFF(MM, 0, StartDate),0) MONTH_START,
    LEAD(CAST(DATEDIFF(dd, StartDate, EndDate) AS FLOAT)) OVER(ORDER BY ...) AS prev_val,
    LAG(CAST(DATEDIFF(dd, StartDate, EndDate) AS FLOAT)) OVER(ORDER BY ...) AS next_val
  -- AVG(CAST(DATEDIFF(dd, StartDate, EndDate) AS FLOAT)) AS AVG1
  FROM DATATable
  WHERE EndDate >= StartDate
  AND StartDate >= @DATE
  AND EndDate >= @DATE
  GROUP BY DATEADD(MM,DATEDIFF(MM, 0, StartDate),0)
) AS src

I haven't tested it, but give it a shot and see how it works.  You may need to put at least one column in the ORDER BY portion of the window function.

A: I can't quite tell what you are trying to calculate the average of, but this is quite simple with window functions:
select t.*,
       avg(val) over (order by month_start rows between 1 preceding and 1 rollowing)
from t;

In your case, I think this translates as:
select datefromparts(year(startdate), month(startdate), 1) as float,
       avg(val) as monthaverage,
       avg(avg(val)) over (order by min(startdate) rows between 1 preceding and 1 following)
from datatable d
where . . .
group by datefromparts(year(startdate), month(startdate), 1)

A: You could try this query (I just reflected in my sample data relevant parts, I omitted date column):
declare @tbl table (rank int, value int);
insert into @tbl values
(1, null),
(2, 20),
(3, 30),
(4, null),
(5, null),
(6, null),
(7, 40),
(8, null),
(9, null),
(10, 36),
(11, 22);

;with cte as (
    select *,
           DENSE_RANK() over (order by case when value is null then rank else value end) drank,
           case when value is null then lag(value) over (order by rank) end lag,
           case when value is null then lead(value) over (order by rank) end lead
    from @tbl
)

select rank, value, case when value is null then
         max(lag) over (partition by grp) / 2 +
         max(lead) over (partition by grp) / 2
       else value end valueWithAvg
from (
    select *,
           rank - drank grp from cte
) a order by rank


text:
Q: Batch File If command I'm trying to create a batch file for the first time. This will be to download a file that is being update once every week with a new ID. This is the batch file that I have created till now -
@echo off
echo open SERVER> temp.txt
echo USERNAME>> temp.txt
echo PWD>> temp.txt
echo cd />> temp.txt
echo cd Events/_PPV_Barker>> temp.txt
echo binary>> temp.txt
echo get Barker*_480i.ts>> temp.txt
ftp -s:temp.txt
del temp.txt

I know that everytime the new file will be uploaded on the server, the start of the file name will be Barker and the file name will end with 480i.ts. I tried * like shown above, but it doesn't work. How can I use the if command to get the file with a unique ID everytime? or is there any other way apart from the if command?
Any help will be appreciated.
Thank you
Keshav

A: If I understand you correctly, there is a new file each time you access the server, but you don't know the details of its name. What I don't know is whether the file is removed after you down-load it, or whether you have an ever-increasing number of files and you have to choose the latest.
In the simplest case, there is only one file, and here your solution is almost correct: there is one simple change needed, to replace get by mget, when the wild card * will work:-
echo mget Barker*_480i.ts>> temp.txt

If there many files that match this file mask, then you will down-load an increasing number of files on each access. A quick and dirty fix is to keep the files in your current directory and make them read-only: you will get a lot of errors, but the new file will down-load and you won't have the overhead of transferring the files you have got previously.
If you have full access to the remote directory, then you can delete, move or rename the down-loaded file on the remote, so that you will have only one file each time which matches the file mask.
If you can't do any of these things, then you will need two ftp calls: the first will get a directory list from the remote, which you will then compare with your previous remote list, so that you can then identify the new file and build a second ftp call to retrieve it. A batch file to do this will not be easy to write, but it's possible - I do things like this when I am processing WebCam files.

A: If you're willing to place your password and user name in the script (in plain text!) then you shouldn't mind using them on the command line itself.
If you keep local copies of the old files after downloading them, and don't change them, or their timestamps, you can eliminate the whole batch file idea by using wget for Windows, and include the --timestamping option. That will compare the size and timestamp of local files with remote files, only downloading remote files when either one is different, or the local file doesn't exist. As an added benefit, if you missed prior updates, it will download all new files, not just the newest one.
Your command line would look something like this:
`wget --ftp-user=<user> --ftp-password=<password> --timestamping ftp://example.com/Events/_PPV_Barker/Barker*_480i.ts`

Of course, this assumes you have the proper priveleges to install wget, and that you keep the prior copies locally.

A: try using the:
mget

command.  I looked it up, and it says get multiple files.

A: Other programs/ ways
Using ftp is not secure.
The secure version of ftp is named ftps, ftp secure. Try to use it instead of ftp, if you can.
It's always a good exercise to do your own scripts, but it is better to use the tools created for that purpose when they exist. As alternatives more cosy you can use wget (see below) that will not require any other server installed remotely.
Since you have access to the remote computer if it is installed you can use rsync too.
If it misses try to use scp -p, or sftp taking advantage from the ssh-key[4].
If you want to stick with ftp, use the mget option that will blindly copy all the files from the directory, but set in advance the mode of file transfer to binary with the binary command.

Wget
wget - The non-interactive network downloader [1,2]. You can use:
wget -S -N "ftp://YourSite/Events/_PPV_Barker/Barker*_480i.ts"

The option -N is to keep timestamps and to download only files newer than the local ones.
The quote " may be needed to avoid shell expansion under Linux.
It works under windows too (of course with the windows version of the program).

A more complete commandline in your case (and in only one line) should be:
wget -user=USERNAME -password=PASSWORD
     -N "ftp://YourSite/Events/_PPV_Barker/Barker*_480i.ts"

Of course it is more wise to avoid to write password in your commandline or in scripts... you can simply use the self-explaining option --ask-password instead.
A more fine solution under Linux is to put the information needed in a file named .wgetrc. It should be easy to find the equivalent name in the windows documentation

$ cat ~/.wgetrc
ftp_user=UsernameOnTheRemoteFTP
ftp_password=PasswordOnTheRemoteFTP
http_user=UsernameOnTheRemoteHTTP
http_password=PasswordOnTheRemoteHTTP

You can read from wget --help, or from man wget:

-N,  --timestamping            don't re-retrieve files unless newer than local
-S, --server-response           print server response.
--user=user
--password=password
     Specify the username user and password password for both FTP and HTTP file retrieval.  These parameters can be overridden using the --ftp-user and --ftp-password options for FTP connections and the --http-user and --http-password options for HTTP connections.


text:
Q: Word: How do I find all locked fields in a document? is it possible to get a list of all the fields I used in a word document? I want to find out which field is locked without going through each field separately. Something similar to the the list when you show all linked files lie the one you can access for example in the menu: File -> Information -> Edit linked files.
Usually I use VBA code to go through locked fields (like this example: https://word.tips.net/T001367_Locating_Locked_Fields.html) but in this case I need to do it without the help of VBA.
Maybe there's an option I haven't found yet like marking all locked fields red, that would work as well (although I would prefer a list).

A: Without VBA you are not going to find a feature that creates a list of fields in the document. What you can do from the Home tab choose the GoTo item from the Edit group and select Fields. You can then cycle thru the document fields pretty quickly.

A: With VBA you can add a comment on each locked field in the document. That gets you closer to the original list you wanted.
Sub FindLockedFields()
Dim rng As Word.Range
ActiveDocument.Fields.ToggleShowCodes
For Each rng In ActiveDocument.StoryRanges
    With rng.Find
        .ClearFormatting
        .Format = True
        .Forward = True
        .Text = "^d"
        .Wrap = wdFindStop
        .Execute
        Do While .Found
            If rng.Fields.Locked = True Then
                rng.Comments.Add rng, "Locked"
            End If
            rng.Collapse Word.WdCollapseDirection.wdCollapseEnd
            .Execute
        Loop
    End With
Next
ActiveDocument.Fields.ToggleShowCodes

End Sub
Hope this helps


text:
Q: How execute with parameters python script in WLS2 from C# under Windows 10 I have big project with C# and WinForms on Windows 10. I want to run from this program python script with ML libraries. Unfortunately i have some problems with work ML in native on Windows and want use WLS2 with Linux environment. It's real? How I should execute python script under WLS2 from C# under Windows10? Can it have access to MS SQL local server under Windows?

A: You can totally use WSL for your development. Your best option would be to use VS Code with remote extension for WSL. See the doumentation.


text:
Q: Need Support to finalize the Migration method to migrate a Azure SQL MI Databases from Azure Cloud-Company Account to Azure Cloud-Clients Accounts We are trying to Migrate Azure SQL Managed Instance Databases from Azure Cloud - Company Account to Another Cloud in Clients Accounts. Need help to choose the right migration methods to migration the Azure SQL MI Databases across subscription and different accounts.

A: Export your Database to your local machine as bacpac file:
https://learn.microsoft.com/en-us/azure/azure-sql/database/database-export
Upload into a Blob storage and import your bacpac file into the new subscription:
https://learn.microsoft.com/en-us/azure/azure-sql/database/database-import?tabs=azure-powershell


text:
Q: How to get time since frame start in Unity for loading purposes I am building a big world (1000+ game objects). It takes 2s on the device. I am doing it in the background (the world is hidden until fully loaded). I have figured out that I can maintain the FPS of the active scene by switching to coroutines and making yield return null;.
The main issue is when to fire yield return null;. If I do it too often, then it will slow down the loading. If I do it too rarely, it will reduce FPS on low-end devices.
My idea is simple to detect how much milliseconds have passed since the start of the frame and fire yield return null; just after I have spent for example 12ms (to leave some time to render everything else and maintain something near 60FPS).
However, I can not find an efficient way of getting the time since frame start? Unity should have something as the async loading of assets seems to consume just right time to maintain stable FPS.

A: DMGregory has given the great and right answer on GameDev StackExchange.

A: You can use and assign Time.time to some variable (example lastFrameTime) and in next frame check if Time.time - lastFrameTime > amountOfTimeToRefresh...
Or Time.delta time assign to lastFrameTime and do the same if...
and if that condition is true do whatever you want and reset lastFrameTime to 0
Hope it helps...


text:
Q: EnumSet modifiers inside an enum in Java It makes sense declaring an EnumSet within a enum with the modifiers static and final? Or are redundant?
Example:
public enum Guitar {
    STRATOCASTER,
    LES_PAUL,
    CLASSIC;

    private static final EnumSet electrics = EnumSet.of(STRATOCASTER, LES_PAUL);
}

Thank you!

A:
It makes sense declaring an EnumSet within a enum with the modifiers
static and final? Or are redundant?

No, they are not redundant. Consider the following example in which nonElectrics can be set because it's not final.
import java.util.EnumSet;

enum Guitar {
    STRATOCASTER, LES_PAUL, CLASSIC;

    private static final EnumSet<Guitar> electrics = EnumSet.of(STRATOCASTER, LES_PAUL);
    static EnumSet<Guitar> nonElectrics = EnumSet.of(CLASSIC);

    public static EnumSet<Guitar> getNonElectrics() {
        return nonElectrics;
    }

    public static void setNonElectrics(EnumSet<Guitar> nonElectrics) {
        Guitar.nonElectrics = nonElectrics;
    }

    public static EnumSet<Guitar> getElectrics() {
        return electrics;
    }

    public boolean isElectronics() {
        return electrics.contains(this);
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Guitar.STRATOCASTER.isElectronics());
        System.out.println(Guitar.CLASSIC.isElectronics());
        EnumSet<Guitar> electrics = EnumSet.of(Guitar.STRATOCASTER, Guitar.LES_PAUL);
        Guitar.setNonElectrics(electrics);
        System.out.println(Guitar.getNonElectrics());
    }
}

A: tl;dr
static final public Set ELECTRICS = Set.of( STRATOCASTER , LES_PAUL ) ;

Details
Regarding your code:

private static final EnumSet electrics = EnumSet.of(STRATOCASTER, LES_PAUL);

private
As written, no need for private.
If marked private no other code would have access to this set. So it would serve no purpose.
static
Yes, static is appropriate. An enum defines a specific number of named instances of its class. The instantiation happens automatically when the class first loads at runtime. So each enum object is a separate object. No need for each of them to have their own set. The set is unchanging, so just define a single instance of that set by marking it static.
This makes the syntax more clear as we do not involve any of the enum objects by name. Example code:
Set < Guitar > guitars = Guitar.ELECTRICS ;

Or:
Guitar.ELECTRICS.stream.forEach( System.out::println ) ;

final
Yes, mark it as final if this set will be unchanging during the entire run of this app. Marking as final prevents any other set from being assigned to that field.
EnumSet ➠ Set
Regarding the first EnumSet, make that simply Set.
Generally better to promise a more general superclass or interface rather than lock yourself into a specific concrete class.
electrics ➠ ELECTRICS
The name electrics should be in all uppercase, if you intend this set to be fixed, unchanging. Constants in Java are named in all uppercase, by convention. So, ELECTRICS.
Plural naming of collection
Good that you named ELECTRICS in plural. This name suggests the fact that is a collection rather than a singular enum object.
Set.of for unmodifiable collection
As for the second EnumSet, generally using EnumSet is the right choice for handling enum objects. The EnumSet class is highly optimized for enums, resulting in very fast performance while using very little memory.
But the problem here is that EnumSet is mutable. I expect you do not want any errant code to be adding or removing elements from your set.
So we want an immutable collection there. Java provides an unmodifiable set via the Set.of… methods.
Under the covers, those methods are free to use any concrete class they want, and so are free to optimize in the choice of underlying class. So you might end up with an efficient concrete class like EnumSet. But that is not paramount, as being immuable trumps performance in this situation.
Solution code
So I would write that code as:
static final public Set ELECTRICS = Set.of( STRATOCASTER , LES_PAUL ) ;

Explicitly immutable collections in third-party library
An alternative to using Set.of is to add a library to your project that provides immutability as an explicit part of its collection data types. Perhaps Eclipse Collections or Google Guava.
As for redundancy, see correct Answer by Live and Let Live.

A: This is not redundant, fields in enum class not static or final.
But, you can't invoke not static enum's fields from other classes.


text:
Q: Как исправить приход на почту? Приходит серверным емейлом.
X-Mailer:PHP/7.0.32@ul14.1gb.ua
и не всегда приходит.
а нужно что бы мой откого@сайт.com.ua вписывало
<?php

$post = (!empty($_POST)) ? true : false;

if($post){
    $email = trim($_POST['email']);
    $name = htmlspecialchars($_POST['name']);
    $email = htmlspecialchars($_POST['email']);
    $message = htmlspecialchars($_POST['message']);
    $tel = htmlspecialchars($_POST["tel"]);
    $phonefull = htmlspecialchars($_POST["phone-full"]);
    $error = '';

    if(!$name){
        $error .= 'Пожалуйста введите ваше имя.
';
    }

    if(!$tel){
        $error .= "Пожалуйста введите телефон.
";
    }

    if(!$error){
        $subject ="Заявка с сайта ";
        $name_tema = "=?utf-8?b?". base64_encode($name) ."?=";
        $message ="\n\nИмя: ".$name."\n\nНомер телефона: "
            .$tel."\n\nСообщение: ".$message."\n\n";
        $mail = mail("куда@gmail.com", $subject, $message,
            "From: откого@сайт.com.ua"."Reply-To: ".$email." "." X-Mailer: PHP/" . phpversion());

        if($mail){
            echo 'OK';
        }
    } else {
        echo '
'.$error.'
';
    }
}

A: Как пример (https://habr.com/sandbox/48759/):
<?php
$to  = "<mail@example.com>, " ;
$to .= "mail2@example.com>";

$subject = "Заголовок письма";

$message = '
Текст письма

 1-ая строчка
2-ая строчка
';

$headers  = "Content-type: text/html; charset=windows-1251 \r\n";
$headers .= "From: От кого письмо <from@example.com>\r\n";
$headers .= "Reply-To: reply-to@example.com\r\n";

mail($to, $subject, $message, $headers);
?>


text:
Q: How to query automatical date in Bigquery¿? I've differents queries at Bigquery but only need run one time for month (with all close data from the last month).
At the moment i change the dates manually at the query but i need change this and make a function that give me the data from the last past.
For exemple: I run this queries the 1st or 2nd day of July, and need that the query takes the data from 1st to 30th of June.
(The query is write in Standard SQL Dialect)
Thanks.
Code:
SELECT
  hits.contentGroup.contentgroup2 AS CampaignGrouping,
  custd.value AS member_PK,
  PARSE_TIMESTAMP('%Y%m%d',date) AS date,
  'WebMobile' AS Canal,
  'MX' AS country_id,
  SUM(hits.contentGroup.contentGroupUniqueViews2) AS VistasUnicas
FROM
  `bigquery-xxxx-xxxxx.111111.ga_sessions*`,
  UNNEST(customdimensions) custd,
  UNNEST(hits) AS hits
WHERE
  1 = 1
  AND PARSE_TIMESTAMP('%Y%m%d', REGEXP_EXTRACT(_table_suffix, r'.*_(.*)')) BETWEEN TIMESTAMP('2017-06-01') AND TIMESTAMP('2017-06-30')
  AND custd.index=30
  and hits.contentGroup.contentGroup2 <> '(not set)'
  AND custd.value <> 'null'
  AND hits.contentGroup.contentGroupUniqueViews2 IS NOT NULL
 GROUP BY 1, 2, 3, 4, 5

A: Below is for BigQuery Standard SQL, assuming there is a date field dt that holds date info
#standardSQL
SELECT *
FROM yourTable
WHERE DATE_TRUNC(dt, MONTH) =
  DATE_TRUNC(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), MONTH)

above assumes data type of dt field is DATE
In case if dt is STRING type - try below
#standardSQL
WITH yourTableAS (
  SELECT '2017-05-30' AS dt UNION ALL
  SELECT '2017-05-31' UNION ALL
  SELECT '2017-06-01' UNION ALL
  SELECT '2017-06-02' UNION ALL
  SELECT '2017-06-03'
)
SELECT *
FROM yourTable
WHERE DATE_TRUNC(CAST(dt AS DATE), MONTH) =
  DATE_TRUNC(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), MONTH)

In case if dt has different format than 'YYYY-MM-DD' you can use PARSE_DATE to CAST string to date