text:
Q: cc, bcc, problems in google script -- This script worked fine until today, when I added cc and bcc variables to the automated email script. Now, I'm getting an error with the recipient email addresses, and I think I also have a problem with the object for options cc and bcc. There error is an invalid email address, with and without cc and bcc. That is, somehow I broke the script, and even the old version doesn't work--did google update something? Any help is much appreciated.
function sendEmails1() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("Send-Emails"));
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:O10");
var data = dataRange.getValues();

for (i in data) {
var rowData = data[i];
var build = rowData[0];
var emailAddress1 = rowData[1];
var emailAddress2 = rowData[2];
var emailAddress3 = rowData[3];
var emailAddress4 = rowData[4];
var cc1 = rowData[11];
var cc2 = rowData[12];
var bcc1 = rowData[13];
var bcc2 = rowData[14];
var options = {
  cc: "'" + cc1 + "," +  cc2 + "'" ,
  bcc: "'" + bcc1 + "," +  bcc2 + "'"
}

var recipient = rowData[5];
var text2 = rowData[6];
var signoff = 'text';

var message = recipient + ', ' + text2 + signoff + '\n\n' + sender;
var subject = 'text';

//prompt the user with the composed email for review
var confirm = Browser.msgBox('Send the following email?', 'text', Browser.Buttons.YES_NO);

if(confirm === 'yes'){

MailApp.sendEmail(emailAddress1 + "," + emailAddress2 + "," + emailAddress3 + "," + emailAddress4, subject, message, options);

}

A: My script for draft writing with no receiver had the same problem, returning an undefined error when the cell was empty. I wrote in a test for blank cells, and if so, put 'null' in the parameter. Now my script works:
if(recipient==""){GmailApp.createDraft(null, sub, null, {cc: seesee, bcc:
                   beeseesee, htmlBody: body1});}
else{
  GmailApp.createDraft(recipient, sub,null, {cc: seesee, bcc: beeseesee,
 htmlBody: body1}); }

Where recipient, seesee, sub, body1, and beeseesee are my variables.

A: This code script in Google scripts helps to create a draft email in Gmail with cc, so I hope it helps someone.
function myFunction() {
  // The code below creates a draft email with the current date and time.
var now = new Date();
  var ccmail = "dummy@gmail.com"
  GmailApp.createDraft("main@gmail.com,", "current time", "The time is: " +
now.toString(), {cc: ccmail} );
}


text:
Q: What does the compiler do when you make a function template? I was learning about function templates and the tutorial said:
"Once a template is defined, the compiler can use the template to generate as many overloaded functions (or classes) as needed, each using different actual types!".
Is this true? Does that mean that a function template is just the compiler generating overloaded functions for different types? Does the compiler scan through your code checking if you made any user-defined types and then generates overloaded functions for those user-defined types?
Is that all there is to function templates or does the compiler do additional things?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Probability Involving Combinations Problem: Three cards are selected at random from a group of 7. Two of the cards have been marked with winning numbers. What is the probability that at least 1 of  the 3 cards has a winning number?
The sample space is 35 from 7C5.
The first problem was "What is  the probability that exactly 1 of the 3 cards has a winning number?" I did 2C1 X 5C2 / 35  and got the correct answer of 57%.
On this problem, I did (2C2 X 5C2) + (2C1 X 5C2) = 10 + 20 = 30. 30/35 is 85%.
The answer is supposed to be 71.4%. What did I do wrong, and how do I do this correctly? I don't really understand these "at least" problems.

A: At least $1$ has a winning number is the complement of no card has a winning number.
Hence the probability is
$$1-\frac{\binom53}{\binom73}\approx 0.714$$
Your mistake is it should be
$$\frac{\binom{2}{2}\cdot \binom{5}{\color{red}1}+20}{35}\approx 0.714$$


text:
Q: Android Studio Project Structure screen looks broken I am migrating a project to the latest android studio and the project structure screen looks rather broken. E.g. I need to configure the usage of Gooogle APIs API Level 19 and cannot do that.... how could I fix that? Could it be my project contains some broken android studio metadata or so?

A: I believe your Project Structure to look fine. This is the latest Android Studio (0.5.4).

When you click on Modules tab you should be able to change to the latest SDK.


text:
Q: Javascript multiple setIntervals I have a scenario where i have one setInterval based code checking for value of an ajax call return. Like so:
var processInterval = setInterval(function () {

    var processResult = getVideoStatus(data.file_name);

    console.log(processResult);

    if (processResult === "ready") {

        clearInterval(processInterval);
        //Logic

    }

}, 1000);

As for the getVideoStatus function, here it is:
var getVideoStatus = function () {

    var result = null;
    jQuery.ajax({
        url: 'someurl',
        type: 'GET',
        dataType: 'html',
        success: function (response) {

            result = response;

        }
    });

    var statusTimeout = setInterval(function () {

        if (result != null) {

            clearInterval(statusTimeout);
            alert(result);
            return result;

        }

    }, 100);

}

What i tried to do in getVideoStatus function is for it to return value only when ajax call is completed and result is not null. I see that it does returns/alerts correct value but when i try to console.log(processResult), it does not log anything at all.
I think it has something to do with first interval because the getVideoStatus seems to return value alright. Is there any logic issue?

A: The approach you have chosen is not ideal to say less. Just use proper Promise/thenable API which is available for providing callback when data is available. In your case:
var getVideoStatus = function () {
    return jQuery.ajax({
        url: 'someurl',
        type: 'GET',
        dataType: 'html'
    });
}

getVideoStatus().then(function(result) {
    console.log(result);
});

Benefits: cleaner and more predictable code behavior.

A: Your problem is getVideoStatus does not return anything. So this code:
var processResult = getVideoStatus(data.file_name);
Is not working as you expect. There is a better way to do what you want. It is to use jQuery Deferreds like so:
var getVideoStatus = function(){
return jQuery.ajax({
    url : 'someurl',
    type: 'GET',
    dataType: 'html',
    success : function (response) {

        result =  response;

    }
  });
}

var deferred = getVideoStatus(data.file_name);

deferred.then(
  function success(data) {
    // do something here, call came back w/ data
  },
  function error() {
    // handle error
  }
);

The thing you are not getting is that an AJAX request is asynchronous. The code will not continue running step by step -- instead, the browser will run the request and then come back and you can continue running but it won't be back in the same place that you started the request.
You can get something like that to work but nobody who uses jQuery would do that and it is complicated -- you need to use setInterval and check the ready state of the XHR request. jQuery does all that for you. So start with that and then go read how it works if you want to implement your own.


text:
Q: Insert byte at location 0 and right shift the remaining data bits I am really struggling to complete this piece, any thoughts or pointers will help me a lot. Here is my problem:

*

*I am working on ISO 8583 layer and data element 32 is defined as n ..11, which means the element is numeric, variable length with max size 11.

*and this need to be sent in binary format (not ASCII).

*We need to show LLNN, ex ISO binary raw should look like this : 11 06 01 04 00 00 00
Till now I was able to complete fill the byte[] array with (11/2)+(11%2) size of 6 with BCD(06 01 04 00 00 00). and I got the total length of the field calculated as 11, Now I need to insert this at byte[0] with the 11 not 0B i.e 0001 0001 packed to one byte byte[]as 11 , my logic as shown below when I give nBytes=1(first 255 chars in BCD ISO) it will insert the length field value as either 0b 01 04 00 00 00 or if i pass nBytes as 2, its giving 00 0b 04 00 00 00. Something going wrong with the right shift logic...
Can somebody help me and correct this below logic to bring the results as 11 06 01 04 00 00 00
int nBytes=1;
for (int i = nBytes - 1; i >= 0; i--) {
    buf[i] = (byte)(length & 0xFF);
    length >>= 8;
}
outstream.write(buf);

A: I think this function performs the BCD conversion you are looking for:
class T {
    public static byte toBCD(int n)
    {
        // a*10 + b -> a*16 + b;
        byte a = (byte)(n / 10);
        byte b = (byte)(n % 10);

        return (byte) (a * 0x10 + b);
    }

    public static void main(String[] args)
    {
        assert(toBCD(11) == 0x11);
        assert(toBCD(28) == 0x28);
    }
}

A: I have finally ended up using the two byte array objects. One holding the original request and calculating the length of the field in decimal and putting it in the first location i.e. 0 index of the secondary byte array and appending the original byte array to this.


text:
Q: Parsing/formatting api responses (nodejs/express) I'm currently struggling with the size/format of response objects I get back from APIs.
I just often find it difficult to see nested objects of a response in my node terminal - keeping track of the indentation across what can be several hundred lines seems fairly unmanageable, to the point where I think I must be doing something wrong?
Are there any standard practices or helpful tools I can use? JSON.stringify() is slightly better, as at least I can see the entire response, but then it's just a wall of text, so sort of the opposite problem.
Apologies if this is obvious!

A: You can use util inspect from native node modules:
// Node.js syntax to demonstrate
// the util.inspect() method

// Importing util library
const util = require('util');

// Object
const nestedObject = {};
nestedObject.a = [nestedObject];
nestedObject.b = [['a', ['b']], 'b', 'c', 'd'];
nestedObject.b = {};
nestedObject.b.inner = nestedObject.b;
nestedObject.b.obj = nestedObject;

// Inspect by basic method
console.log("1.>", util.inspect(nestedObject));

// Random class
class geeksForGeeks { }

// Inspecting geeksForGeeks class
console.log("2.>", util.inspect(new geeksForGeeks()));

// Inspect by passing options to method
console.log("3.>", util.inspect(
        nestedObject, true, 0, false));

// Inspect by calling option name
console.log("4.>", util.inspect(nestedObject,
    showHidden = false, depth = 0, colorize = true));

// Inspect by passing in JSON format
console.log("5.>", util.inspect(nestedObject,
    { showHidden: false, depth: 0, colorize: true }));

// Inspect by directly calling inspect from 'util'
const { inspect } = require('util');

// Directly calling inspect method
// with single property
console.log("6.>", inspect(nestedObject),
        { colorize: true });

// Directly passing the JSON data
console.log("7.>", util.inspect([
    { name: "Amit", city: "Ayodhya" },
    { name: "Satyam", city: "Lucknow" },
    { name: "Sahai", city: "Lucknow" }],
    false, 3, true));

// Directly calling inspect method with single property
console.log("8.>", inspect(nestedObject), { depth: 0 });

Source: [https://www.geeksforgeeks.org/node-js-util-inspect-method/]


text:
Q: Problems with simple differential equation At first: I am new to differential equations, so this question might seam a little bit obvious.
The differential eqation was $y'x^3 = 2y -5$.
I rearranged it to: $\frac{dx^3}{dx} = \frac{d(2y-5)}{dy}$.
The Problem is, if i derive it, there is no y left: $3x^2 = 2$, so how do I do this?
Thanks a lot!

A: Your equation is
$$\frac{dy}{dx}x^3=2y-5.$$
You cannot rearrange it to
$$\frac{dx^3}{dx} = \frac{d(2y-5)}{dy}$$
(why would those differentials appear at the numerators ?) but to
$$\frac{dx}{x^3} = \frac{dy}{2y-5}.$$
This integrates as
$$-\frac{1}{2x^2}=\frac12\log|2y-5|+C.$$

A: The ODE is linear
$$y'-2\frac{y}{x^3}=\frac{-5}{x^3}.$$
its integrating factor is $I=\exp[\int \frac{-2}{x^3} dx]=e^{1/x^2}.$
So its solution is $$y=e^{-1/x^3} \int e^{1/x^2}~ \frac{-5}{x^3} dx+ C e^{-1/x^2} \implies y= \frac{5}{2} e^{-1/x^2} \int e^u du+Ce^{-1/x^2}, u=\frac{1}{x^2} $$
$$\implies y=\frac{5}{2}+C e^{-1/x^2}$$


text:
Q: Variables not being updated by setters Im creating a tetris game, and want the user to be able to choose their board size, from 3 different sizes. I have a Board backend that handles the right, left, down, drop movements, and I have a BoardGUI that creates the shapes and animates it. So when updating the size I need to both update the backend and my GUI for the board. My size keeps getting initialized back to 10 x 20 which is the default size.
here is my BoadGUI snippet (I deleted all unnecessary code, i may have missed something, sorry)
public class BoardGUI extends JPanel implements Observer {

private static final int BLOCK_WIDTH = 20;

private Board myBoard;
private MainGUI myFrame;
private int myWidth;
private int myHeight;

public BoardGUI(MainGUI theFrame, int theWidth, int theHeight){
    myWidth = theWidth;
    myHeight = theHeight;
    this.myBoard = new Board(myWidth, myHeight);
    this.myFrame = theFrame;
    setupComponents();
    myBoard.newGame();

}
public Board getBoard() {
    return myBoard;
}
public void setPanelSize(int theWidth, int theHeight){ // gets correct values
    this.myWidth = theWidth;
    this.myHeight = theHeight;
}

private void setupComponents() {
    setLayout(new BorderLayout());
    this.setPreferredSize(new Dimension(myWidth * BLOCK_WIDTH,  myHeight * BLOCK_WIDTH)); // setting this panel size
    System.out.println(myWidth + " " + myHeight); // DOES NOT PRINT CORRECT SIZE
    myFrame.pack();

}

here is my MainGUI where I set the size
private int myWidth;
private int myHeight;

public MainGUI() {
    super();
    myWidth = 10;
    myHeight = 20;

}

/**
 *
 */
private static final long serialVersionUID = -5056050661369885282L;
private JMenuBar myMenuBar;
public void start() {
    setTitle("Tetris");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    myEastPanel = new JPanel(new BorderLayout());

    NextPiece nextPanel = new NextPiece();
    myBoardGUI = new BoardGUI(this, myWidth, myHeight);
    myMainBoard = myBoardGUI.getBoard();
    setResizable(false);

    pack();
    setLocationRelativeTo(null);
    setVisible(true);
 }
 public JMenuBar createMenuBar() {
    myMenuBar = new JMenuBar();
    myWindow = new JMenu("Window");
    final JFrame frame = this;
    myMenuBar.add(myWindow);
    setWindowSize();
    myMenuBar.setVisible(true);

    return myMenuBar;

}
private void setWindowSize() {
    ButtonGroup group = new ButtonGroup();
    JCheckBox def = new JCheckBox("Default");
    JCheckBox size1 = new JCheckBox("150 x 250");
    myWindow.add(def);
    myWindow.addSeparator();
    myWindow.add(size1);
    group.add(def);
    group.add(size1);
    JFrame frame = this;
    def.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            myWidth = 10;
            myHeight = 20;
             myBoardGUI.setPanelSize(myWidth,myHeight); //setting here

        }

    });
    size1.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
           // myBoardGUI.setPanelSize(15, 25);
            myWidth = 15;
            myHeight = 25;
            myBoardGUI.setPanelSize(myWidth,myHeight); // Setting here

        }

    });
}

A: You save the variables, but you never reset the preferred size.
this.setPreferredSize(new Dimension(myWidth * BLOCK_WIDTH,  myHeight * BLOCK_WIDTH));

The problem is that you should NOT be using the setPreferredSize() method. This makes the size fixed NOT dynamic.
Instead you SHOULD be overriding the getPreferredSize() method of your panel. Something like:
@Override
public Dimension getPreferredSize()
{
    return new Dimension(myWidth * BLOCK_WIDTH,  myHeight * BLOCK_WIDTH));
}

This will allow the size to be dynamically calculated whenever Swing needs to do so.
Now in your panel.setSize() method after you update the variables you need to invoke:
revalidate();
repaint();

So the layout manager can be invoked and the new size of the panel will be considered.


text:
Q: Exceptions when connecting to the HandHeld RFID Reader with C# I'm developing an application in C# in Visual Studio 2008 with the EMDK v2.3 to read tags with a RFID reader integrated in the HandHeld MC9090G with Windows Mobile 6.1. I've read the documentation to perform this task, but when I run the code it's throwing exceptions that I couldn't find the cause.
I'm using the Symbol.RFID3 assembly.
When I use
1) Throws the exception: "OperationFailureException"
string hostname = "localhost";//localhost because the RFID reader is included in the HandHeld
RFIDReader rfid3 = new RFIDReader(hostname, 0, 0);
rfid3.Connect(); // line that throws the Exception

2) Throws the exception: "InvalidUsageException"
string hostname = "localhost";//localhost because the RFID reader is included in the HandHeld
RFIDReader rfid3 = new RFIDReader(hostname, 5084, 10);
rfid3.Connect(); //line that throws the Exception"

Any ideas regarding the cause?

A: The first one is wrong as you are not connecting to port 0.  Use the second one.  I suggest trying 127.0.0.1 instead of localhost.  You should also double check that the port that the RFID component is listening on is indeed 5084.  You are currently specifiying too shot of a timeout.  Try 10000 milliseconds, not 10.  Finally, the RFID component needs to be running.


text:
Q: Sending Message to a iFrame using postMessage from parent? Is there a way to send a postMessage to a iFrame from the parent window? I know how you can send from the iFrame to the parent, I need to send a response message after the parent receives it.
EDIT---------------
I have the following.
Parent Window:
function toFrame(type, data) {
    $("iframe[data-atdl='schedule']").contentWindow.postMessage({
        type: type,
        data: data
    }, "*");
}

iFrame:
window.addEventListener("message", fromParent, false);

function fromParent(e) {
        var data = e.data.data;
        var type = e.data.type;

        sendParentData("ALERT","Action " + type + " :: " + data);
    }

~Z


text:
Q: how to save the user_id after using "create!" in rails 3? I've recently updated my controller code to this for create
class MicropostsController < ApplicationController
  before_filter :signed_in_user

   def create
  @micropost = current_user.microposts.build(params[:micropost])

  if @micropost.review
      params[:micropost].delete :review
      @thread = Discussion.create!(params[:micropost])
    else
      @micropost.save

    end
    redirect_to root_path
  end

When I use the above, it seems to work as the Discussion or the Micropost gets created. However, I believe that using "create!" does not save the user_id. When I view the Discussions, the user_id is nil. How can I save the user_id with whoever made the post?
Tables in schema.db
create_table "users", :force => true do |t|
    t.string    "name"
    t.string    "email"
    t.timestamp "created_at",                         :null => false
    t.timestamp "updated_at",                         :null => false
    t.string    "password_digest"
    t.string    "remember_token"
    t.boolean   "admin",           :default => false
  end

  create_table "discussions", :force => true do |t|
    t.string   "content"
    t.integer  "user_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

A: The create! method basically  runs a new and then a save! throwing a validation exception if there is one.
When you write this:
@micropost = current_user.microposts.build(params[:micropost])

It initializes (normally) a new micropost with the current_user id as if you had run:
@micropost = Micropost.new(params[:micropost].merge(user_id: current_user.id))

And @micropost.save saves it... Which in short does exactly the same as your create! method.
In conclusion I think you should delete this line:
@micropost = Micropost.create!(params[:micropost])

A: Change
@thread = Discussion.create!(params[:micropost])

To:
@thread = current_user.discussions.create(params[:micropost])

This will get you the user_id
However... I think your controller is trying to "do too much".  If this is the create action for microposts Why would it create a discussion and not a micropost?
Also if there are validation errors in that @micropost.save the user won't get any feedback, it'll just fail silently.  Same goes for the discussion create, you don't want them to get the generic http status 500 error page "Something went wrong" when the discussion fails validation when you use the create! method.


text:
Q: SQL Server function errors trying to run. Throws conversion failed error I'm not sure why I am getting a conversion issues when executing my function.  I don't seem to see where I'm trying to convert from nvarchar to int anywhere.
SELECT *
FROM [dbo].[Sample_Position]('D84: 0.5 Hr PD')

I get this error:

Msg 245, Level 16, State 1, Line 15
Conversion failed when converting the nvarchar value '0.5' to data type int.

This is my complete code:
CREATE FUNCTION [dbo].[Sample_Position]
    (@field nvarchar(MAX))
RETURNS @tbl TABLE
             (
                 POS_ID int NOT NULL IDENTITY(1,1),
                 POS_Type  nvarchar(100),
                 POS_Sort1 nvarchar(100),
                 POS_Sort2 nvarchar(100),
                 POS_Sort3 nvarchar(100)
             )
AS
BEGIN
    DECLARE @pos_Type  nvarchar(4000),
            @pos_Sort1 nvarchar(4000),
            @pos_Sort2 nvarchar(4000),
            @pos_Sort3 nvarchar(4000)

    BEGIN
        SELECT
            @pos_Type = CASE
                            WHEN LEFT(@field, 1) = 'D' THEN 'Day'
                            WHEN LEFT(@field, 1) = 'W' THEN 'Week'
                            WHEN LEFT(@field, 2) = 'GD' THEN 'Gestation Day'
                            WHEN LEFT(@field, 3) = 'PND' THEN 'Prenatal Day'
                            WHEN LEFT(@field, 3) = 'PPD' THEN 'Post Partum Day'
                            WHEN LEFT(@field, 2) = 'BD' THEN 'Birth Day'
                            WHEN LEFT(@field, 3) = 'Phy' THEN 'Physical'
                            WHEN LEFT(@field, 4) = 'UNSC' THEN 'Unscheduled'
                            WHEN LEFT(@field, 5) = 'PreTx' THEN 'Pre Treatment'
                            WHEN LEFT(@field, 3) = 'Imm' THEN 'Immediate'
                            WHEN LEFT(@field, 3) = 'EOI' THEN 'End of Infusion'
                            WHEN LEFT(@field, 3) = 'SOI' THEN 'Start of Infusion'
                            WHEN LEFT(@field, 3) = 'KLH' THEN 'Key Lymphoid'
                            WHEN LEFT(@field, 4) = 'KLHC' THEN 'Key Lymphoid Challenge'
                            WHEN LEFT(@field, 4) = 'PKLH' THEN 'Pre Key Lymphoid'
                            WHEN LEFT(@field, 3) = 'TTC' THEN 'Tetinus Toxoid'
                            WHEN LEFT(@field, 4) = 'PTTC' THEN 'Pre-Tetinus Toxoid'
                            ELSE @field
                        END

        SELECT @pos_Sort1 = CASE
                        WHEN @pos_Type = 'Day' then SUBSTRING(@field, PATINDEX('%[0-9]%', @field), PATINDEX('%[0-9][^0-9]%', @field + 't') - PATINDEX('%[0-9]%', @field) + 1)
                        ELSE 1
                        END

        SELECT @pos_Sort2 = CASE
                        WHEN @pos_Type = 'Day' then SUBSTRING(right(@field, len(@field)- PATINDEX('%[ ]%', @field)), PATINDEX('%[0-9.]%', right(@field, len(@field)- PATINDEX('%[ ]%', @field))), PATINDEX('%[0-9.][^0-9.]%', right(@field, len(@field)- PATINDEX('%[ ]%', @field)) + 't') - PATINDEX('%[0-9.]%', right(@field, len(@field)- PATINDEX('%[ ]%', @field))) + 1)
                        ELSE 2
                        END

        SELECT @pos_Sort3 = @field

        INSERT INTO @tbl (POS_Type, POS_Sort1, POS_Sort2, POS_Sort3)
        VALUES (@pos_Type, @pos_Sort1, @pos_Sort2, @pos_Sort3)
    END

    RETURN
END

A: If you run the statement below, you will see an output of '0.5' and then a conversion error.
PRINT CASE WHEN 1=1 THEN '0.5' ELSE 1.5 END

PRINT CASE WHEN 1=1 THEN '0.5' ELSE 1 END

This is because SQL Server is inferring the resulting data type based on the literal you coded into your statement.
To get around this return a string literal instead.
PRINT CASE WHEN 1=1 THEN '0.5' ELSE '1' END

CASE statements return data based on data type precedence rules. All possible results are evaluated. The first statement above does not error out because all evaluated results are compatible. In the second statement, the last result can not be converted into the data type of the first possible result.

A: Your problem, as mentioned, is that one side of your CASE is a varchar, the other an int or numeric. And int has a higher precedence, so the varchar is converted to int and fails.
You can get around this by just putting 1 and 2 into quotes '1' and 2'. Alternatively, you can cast your substring expressions to int, but be careful, as that could fail, and it would be best to use TRY_CAST.
Aside from that, you are using a multi-statement Table Valued Function, which can be slow, especially when run in a correlated APPLY. Instead use an inline TVF.
This also shows how to use CROSS APPLY and virtual tables (SELECT with no FROM, or a VALUES table), and feed them on into the next.
CREATE OR ALTER FUNCTION dbo.Sample_Position
    (@field nvarchar(MAX))
RETURNS TABLE
AS RETURN

SELECT

  POS_ID = 1,

  v1.pos_Type,

  pos_Sort1 = CASE
              WHEN v1.pos_Type = 'Day' THEN
                   SUBSTRING(
                     @field,
                     v1.FirstDigit,
                     PATINDEX(
                       '%[0-9][^0-9]%',
                       @field + 't'
                     ) - v1.FirstDigit + 1
                   )
              ELSE
                  '1'
              END,

  pos_Sort2 = CASE
              WHEN v1.pos_Type = 'Day' THEN
                SUBSTRING(
                  v2.AfterSpace,
                  v3.DigitAfterSpace,
                  PATINDEX(
                    '%[0-9.][^0-9.]%',
                    v2.AfterSpace + 't'
                   ) - v3.DigitAfterSpace + 1
                )
              ELSE
               '2'
              END,

  pos_Sort3 = @field

FROM (
    SELECT
      pos_Type =
        CASE
        WHEN LEFT(@field, 1) = 'D' THEN 'Day'
        WHEN LEFT(@field, 1) = 'W' THEN 'Week'
        WHEN LEFT(@field, 2) = 'GD' THEN 'Gestation Day'
        WHEN LEFT(@field, 3) = 'PND' THEN 'Prenatal Day'
        WHEN LEFT(@field, 3) = 'PPD' THEN 'Post Partum Day'
        WHEN LEFT(@field, 2) = 'BD' THEN 'Birth Day'
        WHEN LEFT(@field, 3) = 'Phy' THEN 'Physical'
        WHEN LEFT(@field, 4) = 'UNSC' THEN 'Unscheduled'
        WHEN LEFT(@field, 5) = 'PreTx' THEN 'Pre Treatment'
        WHEN LEFT(@field, 3) = 'Imm' THEN 'Immediate'
        WHEN LEFT(@field, 3) = 'EOI' THEN 'End of Infusion'
        WHEN LEFT(@field, 3) = 'SOI' THEN 'Start of Infusion'
        WHEN LEFT(@field, 3) = 'KLH' THEN 'Key Lymphoid'
        WHEN LEFT(@field, 4) = 'KLHC' THEN 'Key Lymphoid Challenge'
        WHEN LEFT(@field, 4) = 'PKLH' THEN 'Pre Key Lymphoid'
        WHEN LEFT(@field, 3) = 'TTC' THEN 'Tetinus Toxoid'
        WHEN LEFT(@field, 4) = 'PTTC' THEN 'Pre-Tetinus Toxoid'
        ELSE @field
        END,

    FirstDigit =
      PATINDEX(
        '%[0-9]%',
        @field
      ),

    FirstSpace =
      PATINDEX(
        '%[ ]%',
        @field
      )

) v1

CROSS APPLY (
    SELECT
      AfterSpace =
        right(
          @field,
          len(@field) - v1.FirstSpace
        )
) v2

CROSS APPLY (
    SELECT
      DigitAfterSpace =
        PATINDEX(
          '%[0-9.]%',
          v2.AfterSpace
        )
) v3
;


text:
Q: Err: constructor intent undefined I got this error message: Syntax error on token
This is the code I have:
    package com.BartH.klok;

import android.app.Activity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;

public class help extends Activity {

    Button button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.help);

        addListenerOnButton();

    }

    public void addListenerOnButton() {

        button = (Button) findViewById(R.id.buttonback);

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent intent5 = new Intent(this, Fullscreen.class);
                startActivity(intent5);
            }
        });
    }
    }

Basically I just want to go back to the activity 'fullscreen' after the press of 'buttonback'. But the buttons are new from me so im not sure how to do this.
This is the only error i get.
thanks for looking

A: this refers to the current object, in this case the OnClickListener, not your Activity. Use:
Intent intent5 = new Intent(help.this, Fullscreen.class);

Also please read about Java naming conventions which state that Classes should start with an uppercase letter (CamelCase). So your Activity should be named Help.

A: It should be:
 Intent intent5 = new Intent(help.this, Fullscreen.class);


text:
Q: Restore purchases is not working on iOS Until my update to Xcode 8.0 it was all working fine but after the update I am not able to restore purchases on my iOS app. This is my functions which gets triggered after pressing the restore button.
func restorePurchases(){
        print("restore purchase method called")
        if(SKPaymentQueue.canMakePayments()){
            print("can make purchase")
            SKPaymentQueue.default().add(self)
            SKPaymentQueue.default().restoreCompletedTransactions()
        } else{
            print("can't make purchase")
        }
}

The issue is it doesn't even connect to iTunes store. There is no sign in prompt either. Absolutely no callback be it updatedTransactions or restoreCompletedTransactionsFailedWithError or paymentQueueRestoreCompletedTransactionsFinished.
More interesting thing is I get the itunes sign in prompt once i press the home button to leave the app but now transaction doesn't succeed as the app is out of focus.
Any one have any ideas how to get it sort?


text:
Q: How do I get a list of twitter bootstrap 3 colors? I'm using the twitter bootstrap sass 3.0.3.0 gem which should correspond to the latest twitter bootstrap 3.0.3. I was looking at the 'customize' section of the lESS variables but cannot find too many colors. How do I get a list of colors provided by bootstrap 3?
For example, searching for blue bootstrap 3 docs returns no result. Whereas searching for blue at bootsrap 2 docs shows the color blue.
Thanks!

A: They no longer name their classes or variables that way, because they are trying in release 3 to be more semantic, ie naming stuff for what it does rather than what it looks like.  So @Blue might have become @btn-default-color.
That is better in the long run because your implementation might make it green, so @blue does not adequately describe it anymore.  Unfortunately unless you know color hex codes this makes it a little harder.
You can always (in a modern browser) right click the color you see and choose "inspect element", steal the color from the CSS code on the right hand side and then search for THAT color code in the docs.
http://getbootstrap.com/customize/#less-variables


text:
Q: regex match string but not another I have the two following strings
/signon/default.wl?rs=WLW11.10&vr=2.0&fn=_top
/signon/default.wl?fn=%5Ftop&newdoor=true&rs=WLW11%2E10&vr=2%2

I would like to match all the strings except the ones that do not contain newdoor
so far i have the following regex

/signon/default.wl\?(?=[\w]*)(?!newdoor)

but it matches all strings.
can anyone point out what im doing wrong.

A: You can try this /signon/default.wl\?(?!.*newdoor).*
It asserts using negative lookahead that there is no occurrence of newdoor  in the input string. Code will look like this
resultString = Regex.Match(subjectString, @"/signon/default.wl\?(?!.*newdoor).*",
               RegexOptions.IgnoreCase).Value;

A: /signon/default.wl\?(?=[\w]*)(?!newdoor)

Both (?=) and (?!) are zero-width assertions that don't consume any input. Try:
/signon/default.wl\?(.(?!newdoor))*$

A: why not use something like:
subjectString.contains("newdoor");


text:
Q: Why Do If/Else Spacebars Tags Not Work? Hey for some reason this if/else statement in my template is not working:

          {{#if addingSubreddit}}
            <input class="form-control input-lg" type="text">

              <button class="btn btn-info btn-lg" id="addSubreddit" type="submit">

              </button>
          {{else}}
            <button id="newSubreddit" class="btn btn-info btn-lg" type="submit">

            </button>
          {{/if}}

It gives me this error:
Your app is crashing. Here's the latest log.

Errors prevented startup:

While building the application:
client/views/subreddits.html:14: Unexpected {{else}}
...n>           {{else}}           hey      ...
                        ^

Your application has errors. Waiting for file change.

I cannot figure out why this doesn't work?

A: You have placed span tag wrong. you have coded the {{#if}} outside the span tag but coded the {{else}} inside the  tag which is wrong.
instead this might solve the problem:

      {{#if addingSubreddit}}
        <input class="form-control input-lg" type="text">

          <button class="btn btn-info btn-lg" id="addSubreddit" type="submit">

          </button>

      {{else}}

          <button id="newSubreddit" class="btn btn-info btn-lg" type="submit">

          </button>

      {{/if}}

A: You can't let tags unclosed inside block helpers, so you have to rewrite your template code like this :

          {{#if addingSubreddit}}
            <input class="form-control input-lg" type="text">
          {{/if}}

            {{#if addingSubreddit}}
              <button class="btn btn-info btn-lg" id="addSubreddit" type="submit">

              </button>
            {{else}}
              <button id="newSubreddit" class="btn btn-info btn-lg" type="submit">

              </button>
            {{/if}}


text:
Q: Can appium be detected as bot? Hi i just discovered appium and it looks promising to use on my next project
Basically i want to use real android phones and emulate chrome to visit and perform actions on specific websites like login etc
My question is can appium be detected as a bot? Does it share variables that can be detected just like in selenium?
If yes what do i need to change modify to the web driver?
And what about emulator case?
I tested the website and logged in fine but im worry more about long-term.
I'm fairly new to this and did not see a same question online
Thanks

A: Appium is black-box automation tool, so all the interactions are done without your app/ device modification.
I don't see a case when its session can be detected as bot. However it cannot handle Captcha, FaceID, FingerPrint, etc. so you should be precise on what scenarios you want to automate.


text:
Q: error in C++: out-of-line definition CustomerInfo.cpp
#include "CustomerInfo.h"  //  <==== Funtion Definition

CustomerInfo::CustomerInfo()  //  <==== The Scope Resolution which is two colons :: gives me access to the class
{
    newZipCode = 0;
}

CustomerInfo::CustomerInfo(string name, string address, int zipCode)
{
    newName = name;
    newAddress = address;
    newZipCode = zipCode;
}

CustomerInfo::~CustomerInfo()
{
}

string CustomerInfo::getName() const
{
    return newName;
}

string CustomerInfo::getAddress() const
{
    return newAddress;
}

int CustomerInfo::getZipCode() const
{
    return newZipCode;
}

The main.cpp file
#include <iostream>
#include <string>
#include "CustomerInfo.h"

using namespace std;

int main()
{
    string name;
    string address;
    int zipCode;

    cout << "Enter your name: ";
    getline (cin, name);
    cout << "Enter your address" << endl;
    getline (cin, address);
    cout << "Enter your ZipCode: ";
    cin >> zipCode;

    CustomerInfo Real_1(name, address, zipCode);

    cout << endl << " Name: " << Real_1.getName() << endl <<
        "Address:  " << Real_1.getAddress() << endl <<
        "ZipCode:  " << Real_1.getZipCode() << endl;

    return 0;
}

The CustomerInfo.h file
#ifndef CUSTOMERINFO_H
#define CUSTOMERINFO_H
// Header ==> Function Declaration
#include <iostream>
#include <string>

using namespace std;

class CustomerInfo
{
 public:
    CustomerInfo(); //  <====  Default Constructor

    CustomerInfo(string, int); //  <==== Overload Constructor

   ~CustomerInfo();   //  <===== Destructor - Done using an object it will be destroyed out of memory'

    string getName() const;   //   <==== Accessor Functions - Return member variables one value at a time. In addition, no void function will be used.
    // getName - returns name of person
    string getAddress() const;
    // getAddress - returns address of person
    int getZipCode() const;
    // getZipCode - returns zipcode of person

private:
    //Member Variables
    string newName;
    string newAddress;
    int newZipCode;
};  //  <=== Requires semicolon after brackets for classes

#endif // CUSTOMERINFO_H

The error I receive is out-of-line definition of 'CustomerInfo' does not match any declaration in 'CustomerInfo'
The following line is the error
CustomerInfo::CustomerInfo(string name, string address, int zipCode)

A: Your problem seems to be that you define a constructor
CustomerInfo::CustomerInfo(string name, string address, int zipCode)

which does not appear in the class definition (in CustomerInfo.h).  The closest one is
CustomerInfo(string, int);

but it doesn't match the signature.  Just replace it with
CustomerInfo(string name, string address, int zipCode);

to your class definition in the header file.


text:
Q: Wordpress;how to remove_action from a Plugin to hide admin_notices created by another Plugin I am a beginner to WP hooks, (actions and filters)
I was able to create a Plugin that shows all 4 admin notices in WP dashboard
here the Plugin-one code
    /* Start admin notices on */

function display_admin_notice() {
    ?>

Congratulatios! it seems you have a nice success notice

What a nice error message

WARNING!!! site about to blow up in pieces

INFO - you must renew license

    <?php
  }
  add_action( 'admin_notices', 'display_admin_notice' );

/* Stop admin notices on */

it works perfectly.
Now I have another plugin that hides ALL notifications
/* Start Block ALL admin notices */

add_action('admin_enqueue_scripts', 'block_dismissable_admin_notices');
add_action('login_enqueue_scripts', 'block_dismissable_admin_notices');

function block_dismissable_admin_notices() {
   echo '';
}

/* Stop Block ALL admin notices */

it works fine too
BUT I need to REMOVE the action from the first Plugin, NOT to hide all notifications, I mean, is there a way to get the
add_action( 'admin_notices', 'display_admin_notice'

from the first Plugin and remove_action so the Plugin hides/block ONLY the admin_notices from THAT plugin and NOT from all  the Wordpress  core or   another plugins?
Thanks in advance

A: Instead of loading code and then unloading it (pointless) you could add an if statement to conditionally check if the action hook is needed.
eg.
$noticesOn = true; // Conditional setting could be here

if ( $noticesOn == true ) {
    add_action('admin_enqueue_scripts', 'block_dismissable_admin_notices');
    add_action('login_enqueue_scripts', 'block_dismissable_admin_notices');
}

A: ok, I finally got it
this is the solution
add_action( 'init', 'remove_my_action' );
function remove_my_action()
{
global $wp_filter;
remove_action( 'admin_notices', 'display_admin_notice');
}

it works perfect


text:
Q: Grails HTTPClient Connection Reset Error I am using an HTTPClient object for posting to a resource that resides on another Server. The POST request performed by HTTPClient is done in a loop as I have multiple requests (in fact the number can be 10,000 or even more). After some time while the logic is sending requests the whole process breaks and "Connection reset" error is logged in the log file.
Any ideas as to why this might be happening? Any suggestions?

A: I got this error too, but , mine is another way.
In your situration , perhaps is caused by "keep-alive"...Forgive me , I forget what this was called for, I just remembered it had two parameters:"keep-alive" and "closed".
Suggest you to check it in this point.
Hope this can help you ^_^


text:
Q: Make element with smaller z-index clickable I got two elements, one stacked upon the other with z-index. Now my problem is I need to make the element with the lower z-index clickable, too.
How can I achieve this?
Example:

.b {
  margin-top: -50px;
  z-index: 5;
  color: red;
}

    ...

    ...

A: Just add pointer-events: none to your element with higher z-index.


text:
Q: Consider a set A of 100, 000 arbitrary integers. Prove that there is some subset of 22 integers that end in the same last three digits. Consider a set A of 100, 000 arbitrary integers. Prove that there is
some subset of 22 integers that end in the same last three digits.
I'm new to this principle and need help on this problem.

A: If each of the 1000 combinations of final three digits occured at most 21 times, the total number of integers in $A$ would be at most $21\cdot 1000=21000$. The problem statement seems to be very wasteful as 22 could be replaced with 100.


text:
Q: How to add time durations expressed in days-hh:min:ss.nnn format? The format of the file is as follows:
aaa 1-00:12:43.122
aaa 0-21:14:43.133
bbb 3-11:14:54.433
bbb 2-00:00:10

The numbers on the second column are of the format d-hh:mm:ss.nnn. The last three decimal digits are absent in some cases. I am trying to figure how to sum them grouped by first column to get the total duration for each user. So, for this example, the result would be:
aaa 1-21:27:26.255
bbb 5-11:15:04.433

A: Use this awk script:
BEGIN {
   FS=" |-|:"
}
{
   data[$1][2]+=$2
   data[$1][3]+=$3
   data[$1][4]+=$4
   data[$1][5]+=$5
}
END {
   for( record in data ) {
      if( data[record][5]>=60 ) {
         data[record][4]+=1
         data[record][5]-=60.0
      }
      if( data[record][4]>=60 ) {
         data[record][3]+=1
         data[record][4]-=60
      }
      if( data[record][3]>=24 ) {
         data[record][2]+=1
         data[record][3]-=24
      }
      printf( "%s %d-%02.0f:%02.0f:%06.3f\n", record, data[record][2], data[record][3], data[record][4], data[record][5] )
   }
}

Usage:
~/scratch/se/379631$ cat input
aaa 1-00:12:43.122
aaa 0-21:14:43.133
bbb 3-11:14:54.433
bbb 2-00:00:10
~/scratch/se/379631$ gawk -f 379631.awk input
aaa 1-21:27:26.255
bbb 5-11:15:04.433

A: With perl, using a hash and the DateTime::Format::Duration module, with a regex substitution to regularize the nanoseconds:
perl -MDateTime::Format::Duration -ane '
  BEGIN {
    $p = DateTime::Format::Duration->new(pattern => "%e-%H:%M:%S.%N");
  }

  $F[1] =~ s/\d+(\.\d+)?$/sprintf "%02.9f", $&/e;
  $h{$F[0]} = $h{$F[0]} ? $dt->add_duration($h{$F[0]}) : $dt if $dt = $p->parse_duration($F[1]);

  END {
    $p = DateTime::Format::Duration->new(pattern => "%e-%H:%M:%S.%3N", normalize => 1);
    for $k (sort keys %h) {printf "%s %s\n", $k, $p->format_duration($h{$k})}
  }
' file
aaa 1-21:27:26.255
bbb 5-11:15:04.433

A: perl -F'\h+|[-.:]' -lane '
   $h[keys %h]=$F[0] unless $h{$F[0]};
   $h{$F[0]}[$_-1] += $F[$_] for 1..$#F}{for ( @h )
   {
      my @Arefs = map { \$_ } my($days, $hrs, $mins, $secs, $msec) = @{$h{$_}};
      while ( $msec >= 1000 ) { $secs++; $msec -= 1000; }
      while ( $secs >=   60 ) { $mins++; $secs -=   60; }
      while ( $mins >=   60 ) { $hrs++;  $mins -=   60; }
      while ( $hrs  >=   24 ) { $days++; $hrs  -=   24; }
      print $_, sprintf " %d-%02d:%02d:%02d.%03d", map $$_, @Arefs;
   }
' text.file

perl -F'\h+|[-.:]' -lane '
   $h[keys %h]=$F[0] unless $h{$F[0]};
   $h{$F[0]}[$_-1] += $F[$_] for 1..$#F}{for ( @h )
   {
      use integer;
      my @A = @{$h{$_}};
      $A[0] += ($A[1] += ($A[2] += ($A[3] += $A[4]/1000)/60)/60)/24;
      $A[4] %= 1000; $A[3] %= 60;$A[2] %= 60; $A[1] %= 24;
      print $_, sprintf " %d-%02d:%02d:%02d.%03d", @A;
   }
' text_file

Results
aaa 1-21:27:26.255
bbb 5-11:15:04.433

Explanation

*

*Field separator is set to take apart the milliseconds, seconds, minutes, hours, days, and first field key.

*The input line is split up and stored in an array @F with the elements:
$F[0] -> key (aaa/bbb/etc.)
$F[1] -> days, $F[2] -> hours, $F[3] -> minutes, $F[4] -> seconds, $F[5] -> milliseconds.

*Hash keys by their very nature are accessed not in the order they were created, hence we have an array @h whose elements are hash %h keys in the order they were seen.

*Hash %h is constituted this manner:

%h = (
    aaa => [ days, hours, minutes, seconds, milliseconds ],
    bbb => [                    ...                      ],
    ...
 );


text:
Q: Influxdb 2.0 how to get a tag all values? I'm using influxdb 2.0 to store stock history data.
I use ticker as tag name and AAPL(GOOG.. etc..) as tag value to store stock history candle data.
Now, I want to get a tag all values by flux language in my program. In other words, get all values of tag ticker for getting all stock symbols.
But I don't know how to do this. I have search google but all answer that I found is talking about influxdb 1.x not the 2.0.

A: Maybe can try this: InfluxDB Docs.
The code in Function definition works for me.
I added
|> group(columns: ["tag_name"])
|> distinct(column: "tag_name")
|> keep(columns: ["_value"])

after my filter, and then I got all the tag values.

A: Please see below code which will return all values of tag ticker :
from(bucket: "<Your bucket name>")
// Give range of start and stop as per your usecase
|> range (start: 2015-08-01T00:00:00Z, stop: 2021-06-01T00:00:00Z)
|> filter(fn:(r) => r._measurement == "<Your Measurement Name>")
|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")
|> group()
|> distinct(column: "ticker")


text:
Q: Draw Overlay in Android (system wide) Is there a way to draw an overlay window always on top of any android application?
I am using Android x86 port and have system rights.
@Edit: The view below the overlay should receive all events.

A: It's possible to do that by creating a Service that adds the view in the current WindowManager:
public class OverlayService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();

        WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        View overlay = /* create your overlay here */;

        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
            PixelFormat.TRANSLUCENT);
        windowManager.addView(overlay , params);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

But you need this extra permission:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

And then just register the service in the manifest:
<service android:name=".OverlayService" ></service>

and start it:
startService(new Intent(this, OverlayService.class));

A: You can use my library just removing this method addWatermarkWithinApplicationLifecycle() which sticks the overlay with the app lifecycle (As you want to show the overlay all over the phone app). Please also don't forget to add these permissions -
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"  />
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
<uses-permission android:name="android.permission.ACTION_MANAGE_OVERLAY_PERMISSION"/>

The gif preview of my library -


text:
Q: Best way to iterate over an array that uses its own output Firstly, I'd like to apologize for the badly worded title - I can't currently think of a better way to phrase it. Basically, I'm wondering if there's a faster way to implement an array operation in Python where each operation depends on previous outputs in an iterative fashion (e.g. forward differencing operations, filtering, etc.). Basically, operations that are of a form like:
for n in range(1, len(X)):
    Y[n] = X[n] + X[n - 1] + Y[n-1]

Where X is an array of values, and Y is the output. In this case, Y[0] is assumed to be known or calculated separately before the above loop. My question is: Is there a NumPy functionality to speed up this sort of self-referential loop? This is the major bottleneck in almost all the scripts I have. I know NumPy routines benefit from being executed from C routines, so I was curious if anyone knew of any numpy routines that would help here. Else failing that, are there better ways to program this loop (in Python) that would speed up its execution for large array sizes? (>500,000 data points).

A: It's pretty simple using np.cumsum:
#!/usr/bin/env python3
import numpy as np
import random

def r():
    return random.randint(100, 1000)
X = np.array([r() for _ in range(10)])
fast_Y = np.ndarray(X.shape, dtype=X.dtype)
slow_Y = np.ndarray(X.shape, dtype=X.dtype)
slow_Y[0] = fast_Y[0] = r()

# fast method
fast_Y[1:] = X[1:] + X[:-1]
np.cumsum(fast_Y, out=fast_Y)

# original method
for n in range(1, len(X)):
    slow_Y[n] = X[n] + X[n - 1] + slow_Y[n-1]

assert (fast_Y == slow_Y).all()

A: The situation you describe is basically a discrete filter operation. This is implemented in scipy.signal.lfilter. The particular condition you describe corresponds to a = [1, -1] and b = [1, 1].
import numpy as np
import scipy.signal

a = [1, -1]
b = [1, 1]

X = np.random.random(10000)
Y = np.zeros(10000)

newY = scipy.signal.lfilter(b, a, X) + (Y[0] - X[0])

On my computer, the timings work out as follows:
%timeit func4(X, Y.copy())
# 100000 loops, best of 3: 14.6 µs per loop

% timeit newY = scipy.signal.lfilter(b, a, X) - (Y[0] - X[0])
# 10000 loops, best of 3: 68.1 µs per loop

A: Accessing single NumPy array elements or (elementwise-)iterating over a NumPy array is slow (like really slow). If you ever want to do a manual iteration over a NumPy array: Just don't do it!
But you got some options. The easiest is to convert the array to a Python list and iterate over the list (sounds silly, but stay with me - I'll present some benchmarks at the end of the answer 1):
X = X.tolist()
Y = Y.tolist()
for n in range(1, len(X)):
    Y[n] = X[n] + X[n - 1] + Y[n-1]

If you also use direct iteration over the lists, it could be even faster:
X = X.tolist()
Y = Y.tolist()
for idx, (Y_n_m1, X_n, X_n_m1) in enumerate(zip(Y, X[1:], X), 1):
    Y[idx] = X_n + X_n_m1 + Y_n_m1

Then there are more sophisticated options that require additional packages. Most notably Cython and Numba, these are designed to work on the array-elements directly and avoid Python overhead whenever possible. For example with Numba you could just use your approach inside a jitted (just-in-time compiled) function:
import numba as nb

@nb.njit
def func(X, Y):
    for n in range(1, len(X)):
        Y[n] = X[n] + X[n - 1] + Y[n-1]

There X and Y can be NumPy arrays but numba will work on the buffer directly, out-speeding the other approaches (possibly by orders of magnitude).
Numba is a "heavier" dependency than Cython, but it can be faster and easier to use. But without conda it's hard to install numba... YMMV
However here's also a Cython version of the code (compiled using IPython magic, it's a bit different if you're not using IPython):
In [1]: %load_ext cython

In [2]: %%cython
   ...:
   ...: cimport cython
   ...:
   ...: @cython.boundscheck(False)
   ...: @cython.wraparound(False)
   ...: cpdef cython_indexing(double[:] X, double[:] Y):
   ...:     cdef Py_ssize_t n
   ...:     for n in range(1, len(X)):
   ...:         Y[n] = X[n] + X[n - 1] + Y[n-1]
   ...:     return Y

Just to give an example (based on the timing framework from my answer to another question), regarding the timings:
import numpy as np
import numba as nb
import scipy.signal

def numpy_indexing(X, Y):
    for n in range(1, len(X)):
        Y[n] = X[n] + X[n - 1] + Y[n-1]
    return Y

def list_indexing(X, Y):
    X = X.tolist()
    Y = Y.tolist()
    for n in range(1, len(X)):
        Y[n] = X[n] + X[n - 1] + Y[n-1]
    return Y

def list_direct(X, Y):
    X = X.tolist()
    Y = Y.tolist()
    for idx, (Y_n_m1, X_n, X_n_m1) in enumerate(zip(Y, X[1:], X), 1):
        Y[idx] = X_n + X_n_m1 + Y_n_m1
    return Y

@nb.njit
def numba_indexing(X, Y):
    for n in range(1, len(X)):
        Y[n] = X[n] + X[n - 1] + Y[n-1]
    return Y

def numpy_cumsum(X, Y):
    Y[1:] = X[1:] + X[:-1]
    np.cumsum(Y, out=Y)
    return Y

def scipy_lfilter(X, Y):
    a = [1, -1]
    b = [1, 1]
    return Y[0] - X[0] + scipy.signal.lfilter(b, a, X)

# Make sure the approaches give the same result
X = np.random.random(10000)
Y = np.zeros(10000)
Y[0] = np.random.random()

np.testing.assert_array_equal(numba_indexing(X, Y), numpy_indexing(X, Y))
np.testing.assert_array_equal(numba_indexing(X, Y), numpy_cumsum(X, Y))
np.testing.assert_almost_equal(numba_indexing(X, Y), scipy_lfilter(X, Y))
np.testing.assert_array_equal(numba_indexing(X, Y), cython_indexing(X, Y))

# Timing setup
timings = {numpy_indexing: [],
           list_indexing: [],
           list_direct: [],
           numba_indexing: [],
           numpy_cumsum: [],
           scipy_lfilter: [],
           cython_indexing: []}
sizes = [2**i for i in range(1, 20, 2)]

# Timing
for size in sizes:
    X = np.random.random(size=size)
    Y = np.zeros(size)
    Y[0] = np.random.random()
    for func in timings:
        res = %timeit -o func(X, Y)
        timings[func].append(res)

# Plottig absolute times

%matplotlib notebook
import matplotlib.pyplot as plt

fig = plt.figure(1)
ax = plt.subplot(111)

for func in timings:
    ax.plot(sizes,
            [time.best for time in timings[func]],
            label=str(func.__name__))
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel('size')
ax.set_ylabel('time [seconds]')
ax.grid(which='both')
ax.legend()
plt.tight_layout()

# Plotting relative times

fig = plt.figure(1)
ax = plt.subplot(111)

baseline = numba_indexing # choose one function as baseline
for func in timings:
    ax.plot(sizes,
            [time.best / ref.best for time, ref in zip(timings[func], timings[baseline])],
            label=str(func.__name__))
ax.set_yscale('log')
ax.set_xscale('log')
ax.set_xlabel('size')
ax.set_ylabel('time relative to "{}"'.format(baseline.__name__))
ax.grid(which='both')
ax.legend()

plt.tight_layout()

With the following results:
Absolute runtimes

Relative runtimes (compared to the numba function)

So, just by converting it to a list you will be roughly 3 times faster! By iterating directly over these lists you get another (yet smaller) speedup, only 20% in this benchmark but we're almost 4 times faster now compared to the original solution. With numba you can speed it by a factor of more than 100 compared to the list operations! And Cython is only a bit slower than numba (~40-50%), probably because I haven't squeezed out every possible optimization (usually it's not more than 10-20% slower) you could do with Cython. However for large arrays the difference gets smaller.
1 I did go into more details in another answer. That Q+A was about converting to a set but because set uses (hidden) "manual iteration" it also applies here.
I included the timings for the NumPy cumsum and Scipy lfilter approaches. These were roughly 20 times slower for small arrays and 4 times slower for large arrays compared to the numba function. However if I interpret the question correctly you looked for general ways not only ones that applied in the example. Not every self-referencing loop can be implemented using cum* functions from NumPy or SciPys filters. But even then it seems like they can't compete with Cython and/or numba.


text:
Q: Flyway and JPA integration My current Spring 3.0 project is integrating with Flyway.
Thanks to the google site so there are document I can counting on. But unfortunately there is not much talking about integration with JPA.
So the questions is:

*

*How to integrate Flyway with persistence.xml? And how does it work? Each time JPA provider will auto generate schema update so how we run a script before or after then?

*I guess the query by flyway so far does not support HQL and such so is there any sample code then I can go through to know how to integrate the migration event? Design an interceptor or a new aspect?What to do on a domain level?
Any hint is appreciated. Thanks in advance.

A: Flyway has no support for JPA and Spring. It basically runs your SQL (not HQL) scripts in order and keeps track of them. And does it well. It remains agnostic to how you use your database and how you produce your upgrade scripts.
However, there's hope. Your persistence provider will most likely support updating existing schema (I know hibernate and eclipselink can), running ALTER and CREATE statements on startup. The migration SQL scripts aren't perfect and it won't always work, but it's a good start. Log these scripts, collect into SQL file, clean-up and use as V_*.sql file supplied to Flyway.
UPDATE: although there is no direct support for spring framework, you can easily integrate it with existing Spring application. This approach is proven to work on production and plays nicely:
<bean id="flyway" class="com.googlecode.flyway.core.Flyway" init-method="migrate">
  <property name="dataSource" ref="..."/>
  ...
</bean>

Bonus: it works great with Java configuration (with Scala) as well:
@Bean(initMethod = "migrate")
def flyway() = {
    val fly = new Flyway()
    fly.setDataSource(dataSource)
    fly
}


text:
Q: how to use it to add in-lined values or multiline strings in vb.net I don't know create a multi line string please the best solution. The code below does not all use multi line strings. You can see the code I commented out was because I didn't know how to create a multi line string.
Thanks Jack

'information code
Public Shared Function GetReceipt(ByVal transaction_Conflict As Transaction) As String
            Return GenerateReceiptTemplate().Replace("<Orders/>", GetOrderRows(transaction_Conflict)).Replace("<Total/>", transaction_Conflict.Total.ToString() & "PHP").Replace("<Cash/>", transaction_Conflict.Cash.ToString() & "PHP").Replace("<Change/>", transaction_Conflict.Change.ToString() & "PHP").Replace("<Id/>", transaction_Conflict.Id).Replace("<Cashier/>", transaction_Conflict.GetCashier().Fullname).Replace("<Date/>", transaction_Conflict.Date.ToString())
        End Function

Private Shared Function GetOrderRows(ByVal transaction_Conflict As Transaction) As String
            Dim result As String = ""
            transaction_Conflict.GetOrders().ForEach(Sub(item As Order)
                result &= "
"
                result &= "" & item.GetProduct().Name & "	"
                result &= "x " & item.Quantity & "	"
                result &= "" & item.Subtotal & "PHP	"
                result &= "
"
            End Sub)
            Return result
        End Function

 'code output in VB.NET

 Private Shared Function GenerateReceiptTemplate() As String
            Return "" & vbCrLf &
                           "WcDonalds
" & vbCrLf &
                           "wcdonalds@gmail.com" & vbCrLf &
                       "" & vbCrLf &
                       "

" & vbCrLf &
                       "
" & vbCrLf &
                           "
" & vbCrLf &
                               "
" & vbCrLf &
                                   "Product Name	" & vbCrLf &
                                   "Quantity	" & vbCrLf &
                                   "Subtotal	" & vbCrLf &
                               "
" & vbCrLf &
                           "
" & vbCrLf &
                           "
" & vbCrLf &
                               "<Orders/>" & vbCrLf &
                           "
" & vbCrLf &
                       "
" & vbCrLf &
                       "
" & vbCrLf &
                       "---------------------------------------" & vbCrLf &
                       "
" & vbCrLf &

            'Total: <Total/>

            'Cash: <Cash/>

            'Change: <Change/>

            '

            'Transaction ID:   #<Id/>

            'Cashier: <Cashier/>

            'Date: <Date/>

            '

            '               ---------------------------------------
            '

            '               Thanks For visiting WcDonalds

        End Function

A: You just type the String literal over multiple lines, with the opening double-quote on the first line and the closing double-quote on the last line. Just note that you'll need to push all but the first physical line to the left of the code window as any leading whitespace you include will be considered part of the String. E.g.
    Dim str = "First Line
Second Line
Third Line"

I can't recall exactly when this feature was introduced, so it may not be available in VB 2010. In that case, you can still use an XML literal, e.g.
    Dim str = <text>First Line
Second Line
Third Line</text>.Value

A: Your HTML is a mess.  This is just a little better.
    Dim xe As XElement =

WcDonalds

wcdonalds@gmail.com

                                         Product Name
                                         Quantity
                                         Subtotal

                                         a product
                                         1
                                         $1.23

---------------------------------------

Total

Cash

Change

---------------------------------------

Thanks For visiting WcDonalds

    Return xe.ToString

A: The text can be saved as an Embedded Resource (Text file) and retrieved from there. This helps one's code to look cleaner.
Try the following:
VS 2010:
Open Solution Explorer

*

*In VS menu, select View

*Select Solution Explorer
Open Properties Window

*

*In VS menu, select View

*Select Properties Window
Add Folder (name: Templates)

*

*In Solution Explorer, right-click <project name>

*Select Add

*Select New Folder

*Type desired name (ex: Templates)

Add Text File (name: ReceiptTemplate.txt)

*

*In Solution Explorer, right-click on the new folder you just created (ex: Templates)

*Select Add

*Select New Item

*Expand Common Items

*Click General

*Select Text File (name: ReceiptTemplate.txt)

*Click Add
Set Properties for Text File

*

*In Solution Explorer, click the text file that you added (ex: ReceiptTemplate.txt)

*In the Properties Window, set Build Action to Embedded Resource
Add desired text to text file. For example:
ReceiptTemplate.txt:

    ABC Cafe

  abccafe@gmail.com

            Product Name
            Quantity
            Subtotal

        <Orders/>

---------------------------------------

Total: <Total/>

Cash: <Cash/>

Change: <Change/>

Transaction ID:   #<Id/>

Cashier: <Cashier/>

Date: <Date/>

---------------------------------------

Thanks For visiting ABC Cafe

Add a module (name: HelperLoadResource.vb)
'Notes:
'        Need to set property Build Action: Embedded Resource For Each file that
'        needs to be loaded
'
'Resources:
'        https'stackoverflow.com/questions/3314140/how-to-read-embedded-resource-text-file

Imports System.Text
Imports System.IO
Imports System.Reflection

Module HelperLoadResource

    Public Function ReadResource(filename As String) As String
        Return ReadResource(filename, System.Text.Encoding.UTF8)
    End Function

    Public Function ReadResource(filename As String, fileEncoding As System.Text.Encoding) As String
        Dim fqResourceName As String = String.Empty
        Dim result As String = String.Empty

        'get executing assembly
        Dim execAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()

        'get resource names
        Dim resourceNames As String() = execAssembly.GetManifestResourceNames()

        If resourceNames IsNot Nothing AndAlso resourceNames.Length > 0 Then
            For Each rName As String In resourceNames
                If rName.EndsWith(filename) Then
                    fqResourceName = rName
                    Exit For
                End If
            Next

            If String.IsNullOrEmpty(fqResourceName) Then
                Throw New Exception(String.Format("Resource '{0}' not found.", filename))
            End If

            'get file text
            Using s As Stream = execAssembly.GetManifestResourceStream(fqResourceName)
                Using reader As StreamReader = New StreamReader(s, fileEncoding)

                    'read text
                    result = reader.ReadToEnd()
                End Using
            End Using
        End If

        Return result
    End Function
End Module

Note: This also works for newer versions of Visual Studio, however some of the steps listed in "Add Text File" are different.

The file/folder structure should look similar to the following:

Usage:
Dim receiptTemplate As String = HelperLoadResource.ReadResource("ReceiptTemplate.txt")

Resources:

*

*How to read embedded resource text file

A: All right, all what you need here is the first function to generate and return the receipt. I'll modify the answer of your previous question using the same XElement approach to get the values from transaction_Conflict parameter.
For the labels, append the corresponding values from the transaction_Conflict object enclosed with <%= %>. For the table part, call the transaction_Conflict.GetOrders() method in <%= %> to get the list and call the .Select extension method to create the rows and cells as shown in the code.
Public Shared Function GetReceipt(ByVal transaction_Conflict As Transaction) As String
    Return

                    WcDonalds

                    wcdonalds@gmail.com

                            Product Name
                            Quantity
                            Subtotal

                        <%= transaction_Conflict.GetOrders().Select(
                            Function(order)
                                Return _

                            <%= order.GetProduct().Name %>
                            <%= order.Quantity %>
                            <%= order.SubTotal %>

                            End Function) %>

                Total: <%= transaction_Conflict.Total %> PHP

                Cash: <%= transaction_Conflict.Cash %> PHP

                Change: <%= transaction_Conflict.Change %> PHP

                Transaction ID: #<%= transaction_Conflict.Id %>

                Cashier: <%= transaction_Conflict.GetCashier().Fullname %>>

                Date: <%= transaction_Conflict.Date.ToString() %>

                Thanks For visiting WcDonalds
            .ToString()
End Function

Which generates in my browser something like:


text:
Q: Why heap memory still accessible after HeapFree I wrote a simple C program which creates a singly linked list. It works; for instance, I pushed a few numbers to a list and the function print_list(...) prints the numbers to the console.
However, I then added a clear_list(...) function and called it before print_list(...) to see what would happen. After the call to clear_list, print_list still prints numbers as before.
How does print_list print numbers from freed memory? I use HeapAlloc for allocation of the list structure and HeapFree to deallocate.
Code below:
static BOOL push_list(DWORD a)
{
    LIST *ptr = NULL;

    ptr = (PLIST)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,     sizeof(LIST));
    if (ptr == NULL)
    {
        printf("Error push list\n");
        return FALSE;
    }

    ptr->i = a;

    ptr->next = LIST_HEAD;
    LIST_HEAD  = ptr;

    return TRUE;
}

void free_dir_list(void)
{
    PLIST pTemp = NULL;
    P_LIST PTR = LIST_HEAD;

    while (PTR != NULL)
    {
        pTemp = PTR;
        PTR = PTR->next;
        HeapFree(GetProcessHeap(), 0, pTemp);
    }
}

A: Using deallocated memory is undefined behavior in C.
It works here because nothing has altered the memory after it was deallocated. This is usually the case immediately after memory is deallocated. Functions like HeapFree(...) or just the standard C free(...) do not commonly zero out the memory; they just alter internal state managed by the runtime such that the memory is known to be free.


text:
Q: Retrofit. Response body is null I use retrofit 2.0.0 and GSON converter.
I have Response string
{"errors":["Incorrect unlock code"]}

I try convert it to object:
public class User {
    ArrayList<String> errors;
}

But in callback response.body() is null. For other objects, which don't contains arrays, only string and int fields, all is ok!
This is how i init retrofit:
    OkHttpClient client = new OkHttpClient();
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.interceptors().add(interceptor);

    retrofit = new Retrofit.Builder()
            .baseUrl("http://testurl.com")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    service = retrofit.create(SignApi.class);


text:
Q: Formula too long and \split fails | contains "sqrt" (square root) I'm quite new to LaTex and I guess I need some help. I'm writing a report and I need to display a specific formula. If I use the simple equation environment the formula gets too long for one line. Therefore I tried to use the split envornment inside the equation environment. Here is my code:
\begin{equation}
\begin{split}

K_{b}   &=  \sqrt{ \max \left( 0, \sum_{k} \max \left( CVR_{k},0\right)^{2}\\
    &+  \sum_{k} \sum_{k\neq l} \rho_{kl} CVR_{k}CVR_{l}\psi \left(CVR_{k},CVR_{l}\right)
    \right)
}
\end{split}
\end{equation}

If I apply this code I'm getting the following error message:

Missing } inserted. \end{split}

Do you have any idea how to display the formula correctly?
Thanks in advance!!
Kind regards,
Felix

A: *

*I used the align environment.

*In addition, using \left( and \right. to open a bracket and close it invisible to be able to split.

*I used \notag to avoid the equation number in the first line.

*I avoided the sqrt by using ^{1/2}.

*Make sure to read Big Parenthesis in an Equation, see \biggl and \biggr as an alternative approach to the automatic bracket size (\left and \right).

*You can use \vphantom to force the same size for all brackets in different lines, see Linebreak between \left and \right for example.

*I think that most of my code needs the amsmath package (or mathtools which builds on amsmath).

\documentclass{article}

\usepackage{amsmath}

\begin{document}

\section*{Original}

\begin{equation}
K_{b}   =   \left(\max
            \left( 0, \sum_{k} \max
            \left( CVR_{k},0
            \right)^{2}
            +
            \sum_{k} \sum_{k\neq l} \rho_{kl} CVR_{k}CVR_{l} \psi
            \left(CVR_{k},CVR_{l}
            \right)
            \right)
            \right)^{1/2}
\end{equation}

\section*{Basic Idea}

\begin{align}
K_{b}   = &     \left( \max \left( \right. \right. \\
            & +
            \left. abc \left. \right) \right)
\end{align}

\section*{Proposal}

\begin{align}
K_{b}   = &     \left( \max  \left(
            0, \sum_{k} \max \left( CVR_{k},0 \right)^{2}
            \right. \right.
            +
            \notag
            \\
            & +
            \left. \left.
        \sum_{k} \sum_{k\neq l} \rho_{kl} CVR_{k}CVR_{l} \psi   \left(CVR_{k},CVR_{l}       \right)
            \right) \right)^{\frac{1}{2}}
\end{align}

\end{document}

(added by daleif)
In a case like this auto scaling should not be used as it easily comes out in the wrong size. Here are two example with manual scaling. The latter use the fact that are are a bit away whatever is tall, so we do not need the fences that all,  plus using different inner braces makes it a lot easier to match what ever goes together.
\begin{align}
K_{b}   = &     \biggl( \max  \biggl(
            0, \sum_{k} \max ( CVR_{k},0 )^{2}
            +
            \notag
            \\
            & +
            \sum_{k} \sum_{k\neq l} \rho_{kl} CVR_{k}CVR_{l} \psi   (CVR_{k},CVR_{l}       )
            \biggr) \biggr)^{\frac{1}{2}}
\end{align}
\begin{align}
K_{b}   = &     \Bigl( \max  \Bigl\{
            0, \sum_{k} \max ( CVR_{k},0 )^{2}
            +
            \notag
            \\
            & +
            \sum_{k} \sum_{k\neq l} \rho_{kl} CVR_{k}CVR_{l} \psi   (CVR_{k},CVR_{l}       )
            \Bigr\} \Bigr)^{\frac{1}{2}}
\end{align}

A: You can easily avoid having to split your equation, in two ways:
Replacing the double sum with a single sum with a double index and using the \mediummath command from nccmath (ca 80 % of \displaystyle):
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{mathtools}
\usepackage[showframe]{geometry}

\begin{document}
\vspace*{1cm}

\begin{equation}
  K_{b} = \sqrt{\max \Bigl( 0, \sum_{k} \max \left( CVR_{k},0\right)^{2}
    +\smashoperator{ \sum_{k, l ~k \neq l}} \rho_{kl} CVR_{k}CVR_{l}\psi \left(CVR_{k},CVR_{l}\right)
    \Bigr)}
\end{equation}

\end{document}

If you don't use margin notes, loading the geometry package will give you more decent default margins, which are enough to have the formula in displaystyle:
 \documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{mathtools, nccmath}
\usepackage{showframe}
\renewcommand{\ShowFrameLinethickness}{0.3pt}

\begin{document}
\vspace*{1cm}

\begin{equation}
  \medmath{K_{b} = \sqrt{\max \Bigl( 0, \sum_{k} \max \left( CVR_{k},0\right)^{2}
      +\smashoperator{ \sum_{k, l ~k \neq l}} \rho_{kl} CVR_{k}CVR_{l}\psi \left(CVR_{k},CVR_{l}\right)
      \Bigr)}}
\end{equation}

\end{document}


text:
Q: PostgreSQL error: FATAL: password authentication failed for user "pgadmin" I am making a Telegram bot with a PostgreSQL database. Everything works correctly on the local computer, but when I upload the code to the server using docker-compose, the following errors appear in the console from time to time:
2021-10-10 02:08:58.865 UTC [3458] FATAL:  password authentication failed for user "pgadmin"
2021-10-10 02:08:58.865 UTC [3458] DETAIL:  Role "pgadmin" does not exist.
    Connection matched pg_hba.conf line 94: "host all all 0.0.0.0/0 md5"

2021-10-09 16:27:22.198 UTC [2259] FATAL:  password authentication failed for user "pgsql"
2021-10-09 16:27:22.198 UTC [2259] DETAIL:  Role "pgsql" does not exist.
    Connection matched pg_hba.conf line 94: "host all all 0.0.0.0/0 md5"

2021-10-09 16:25:16.113 UTC [2250] FATAL:  password authentication failed for user "postgres"
2021-10-09 16:25:18.992 UTC [2252] DETAIL:  Password does not match for user "postgres".
    Connection matched pg_hba.conf line 94: "host all all 0.0.0.0/0 md5"

2021-10-09 21:06:32.169 UTC [2831] FATAL:  expected password response, got message type 0
2021-10-09 21:07:39.610 UTC [2834] FATAL:  unsupported frontend protocol 0.0: server supports 2.0 to 3.0
2021-10-09 21:07:39.819 UTC [2835] FATAL:  unsupported frontend protocol 255.255: server supports 2.0 to 3.0
2021-10-09 21:07:40.029 UTC [2836] FATAL:  no PostgreSQL user name specified in startup packet

And I don't use these users. It seems to me that someone else is trying to access the database. If so, is it possible to somehow specify the IP addresses from which traffic will be allowed? But my bot parses sites, so you need to limit the IP so that it would not affect its work. Thanks!
UPD:
As I was prompted in the comments, maybe the contents of the docker files will help
Dockerfile:
FROM python:3.9.5

WORKDIR /src
COPY requirements.txt /src
RUN pip install -r requirements.txt
COPY . /src

docker-compose.yml:
version: "3.1"

services:
  steamtrader_db:
    container_name: steamtrader_db
    image: sameersbn/postgresql:10-2
    environment:
      PG_PASSWORD: $PGPASSWORD
      DB_USER: $PGUSER
      DB_PASS: $PGPASSWORD
      DB_NAME: $DATABASE
    restart: always
    ports:
      - 5432:5432
    networks:
      - steamtrader_botnet
    volumes:
      - ./pgdata:/var/lib/postgresql

  steamtrader_bot:
    container_name: steamtrader
    build:
      context: .
    command: python bot.py
    restart: always
    networks:
      - steamtrader_botnet
    env_file:
      - ".env"
    volumes:
      - .:/src
    depends_on:
      - steamtrader_db

networks:
  steamtrader_botnet:
    driver: bridge


text:
Q: Bound KL divergence between two distributions by KL divergence of two Gaussian mixture models I'm trying to bound the KL divergence between two continuous random variables with the KL divergence between two Gaussian mixture approximations motivated by the fact that the Gaussian mixture model is a universal approximator of densities, see https://stats.stackexchange.com/questions/365155/a-gaussian-mixture-model-is-a-universal-approximator-of-densities/365158#365158
In the end I would like to plug in the KL divergence for Gaussians.
So my question: Are there any results about the parameters of the mixture model approximating a given density and how the KL divergence between a function and its Gaussian mixture approximation behaves?


text:
Q: How to Prevent Users from opening other pages without login It is Login Page Code which is accepting Username and Password. But other pages are also opening with URL. Used Session Start Also. Please help me with modifications in code.
<?php
if(isset($_POST["submit"])){

if(!empty($_POST['user']) && !empty($_POST['pass'])) {
    $user=$_POST['user'];
    $pass=$_POST['pass'];

    $con=mysqli_connect('localhost','root','') or die(mysql_error());
    mysqli_select_db($con, 'user_registration') or die("cannot select DB");

    $query=mysqli_query($con, "SELECT * FROM login WHERE username='".$user."' AND password='".$pass."'");
    $numrows=mysqli_num_rows($query);
    if($numrows!=0)
    {
    while($row=mysqli_fetch_assoc($query))
    {
    $dbusername=$row['username'];
    $dbpassword=$row['password'];
    }

    if($user == $dbusername && $pass == $dbpassword)
    {
    session_start();
    $_SESSION['sess_user']=$user;

    /* Redirect browser */
    header("Location: index.php");
    }
    } else {
    echo "Invalid username or password!";
    }

} else {
    echo "All fields are required!";
}
}
?>


text:
Q: How do I mount a Vue 3 CLI project like codepen I have written a working pen here.
I'm trying to replicate the same app within a vue-cli project. Everything is on default settings (vue3 preview), except for these 2 files:
main.js
import { createApp } from 'vue'
import BoostApp from './App.vue'

createApp(BoostApp).mount('#box')

App.vue
<template>

      Compound vault

    Deposit
    <input type="number" min="0" v-model="deposit" style="width:6em" /> USD (in stablecoins)

CRV needed for 2.5x boost:

    {{Math.ceil(deposit/CRVneeded*100)/100}} CRV for 4 years

</template>

It builds fine with 'npm run serve', but when I visit http://localhost:8080/ I just get a blank screen.
Where am I going wrong? Thanks!

A: The app mounts to the div in index.html, not the one in App.vue.  So if you haven't renamed the div id to box in index.html, this is why.
You could also change this back to #app instead (recommended):
createApp(BoostApp).mount('#app')


text:
Q: Uninitialised Constant Iconv Recently was advised to used the following code in order to avoid UTF-8 problems with input text into a database.
ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')
#valid_string = ic.iconv(untrusted_string + ' ')[0..-2]
row[4] = ic.iconv(row[4] + ' ')[0..-2]
row[5] = ic.iconv(row[5] + ' ')[0..-2]

In development this works perfectly, however, once pushed onto our server we get the problem "uninitialised constant iconv" when we try to run the rake file containing the above code.
Is there an easy way to fix this issue?  Tried adding gem 'iconv' to the gem file and running bundle install  but this produced loads of errors, so assuming this is not the correct way to fix it...

A: Fixed it by adding require 'iconv' at the top of the rake file


text:
Q: The type conversion of inheritance type between the Generics type List<List<object>> all = new List<List<object>>();
List<string> k = new List<string>();
all.Add(k);

The error is "cannot convert from List<string> to List<object>. "
I wonder how to transform type like these.

A: You would have to cast your list of string to objects
Here is a simple solution
List<List<object>> all = new List<List<object>>();
List<string> k = new List<string>();
all.Add(k.Cast<object>().ToList());

A: List<T> implements non-generic IList interface, so depending on your purpose it is possible to use List<IList>() list:
var all = new List<IList>();
var k = new List<string>() { "a", "b", "c" };
var num = new List<int>() { 1, 2, 3 };
all.Add(k);
all.Add(num);
string b = (string)all[0][1]; // "b"
int two = (int)all[1][1]; // 2


text:
Q: SQL SUM over multiple tables Thanks to Gustav I'm a lot closer to the solution of my problem.
I'm using his code but it's not able to correctly sum.
tblKasse
tblKursspielbuchung
I debugged my code and when I want to sum for 1 year I get this sql query: "SELECT Datum, Sum(Kosten) FROM tblKursspielbuchung, tblKasse WHERE tblKursspielbuchung.Datum >= #2019/01/01# AND tblKursspielbuchung.Datum < #2020/01/01# GROUP BY Datum"
For example I'm receiving 1460 instead of 730 which would be the correct answer.
I can only think of having multiplt rows for Flights with the cost might be the problem. I'm having problems getting rid of them when I sum them. I'd appreciate it if someone could tell me how to use distinct or something similar in that situation. If nothing works I have to change the code so that I don't have the same cost in multiple rows.

A: Often the issue with comparing dates is that the way you build the compare sets it up to compare as a string as opposed to comparing as a date.  I would do a date conversion before inserting the value into your select string.  If the compare is happening in MS ACCESS you will need to wrap the date with the # character - i.e. #date#

A: In MS Access, date constants have a special syntax.  I also strongly recommend JOIN.  I suspect you want something like this:
SELECT ks.Datum, Sum(Kosten)
FROM tblKursspielbuchung as ks INNER JOIN
     tblKasse as k
     ON ks.Datum = k.Datum
WHERE ks.Datum >= #01/01/2019# AND 'ks.Datum < #01/01/2010#
GROUP BY ks.Datum;

A: You could build your SQL like this:
int year = int.Parse(txtJahr.Text);

"SELECT Datum, Sum(Kosten) FROM tblKursspielbuchung, tblKasse WHERE tblKursspielbuchung.Datum >= #" + new DateTime(year, 1, 1).ToString("yyyy'/'MM'/'dd") + "# AND tblKursspielbuchung.Datum < #" + new DateTime(year + 1, 1, 1).ToString("yyyy'/'MM'/'dd") + "# GROUP BY Datum";


text:
Q: Автообновление блока Здравствуйте, сегодня связался с одной проблемой как автообновление блока AJAX. Проблема собственно в том, что жрет много трафика, хотелось бы сделать, чтобы обновляло при получении новых данных в базу. Вот скрипт динамического обновление который стоит сейчас:
function groups()
        {
            $.ajax({
                url: "/obr/groups.php",
                cache: false,
                success: function(html){
                    $("#groups").html(html);
                }
            });
        }

        $(document).ready(function(){
            groups();
            setInterval('groups()',1000);
        });

Примечание: скрипт отлично работает.

A: Снизить нагрузку таким способом можно только, разве что, сделав обновление намного реже.
Правильный способ - использование сокетов.
В одном сообщение все не уместишь - советую поискать на эту тему информацию, а также очень хорошая статья с тестовым примером чата на php.
habrahabr.ru


text:
Q: Functions without arguments, with unit as argument in scala def foo(x: Int, f: Unit => Int) = println(f())

foo(2, { Unit => 3 + 4 })

// case 1
def loop: Int = 7
foo(2, loop) // does not compile

changing loop to
// case 2
def loop(): Int = 7
foo(2, loop) // does not compile

changing loop to
// case 3
def loop(x: Unit): Int = 7 // changing according to Don's Comments
foo(2, loop) // compiles and works fine

Shouldn't case 1 and case 2 also work? Why are they not working?
Defining foo as
def foo(x: Int, y: () => Int)

then case 2 works but not case 1.
Arent they all supposed to work, defining the functions either way?
Also I think () => Int in foo is a bad style, y:=> Int does not work. Comments?

A: Scala distinguishes between the following things:

*

*Functions/methods with no parameter lists ("by-name parameter" if a function)

*Functions with one empty parameter list

*Functions with one parameter of type Unit
None of these are equivalent, although as a convenience Scala allows you to elide empty parameter lists.  (Incidentally, two empty parameter lists are also not the same.)
So, even though Unit is written (), this is not the same as the function argument parens () for a function or method.  Instead, think of () as a Tuple0.
So, if you say f: Unit => Int, what you mean is "f takes one parameter, but it's a really boring parameter because it is Unit, which must always be the same boring Tuple0 value ()".  What you're writing is really short for f: (Unit) => Int.
If you say f: () => Int, then you mean that "f takes no parameters and produces an Int".
If you say f: => Int, then you mean that "delay the execution of whatever statement produces an Int value until we use it in this code (and re-evaluate it each time)".  Functionally, this ends up being basically the same as f: () => Int (and internally is converted into the same Function0 class), but it has a different usage, presumably to allow for a more compact form of closures (you always omit the => in the calling code).

A: In case 1 and 2 above, the return value of loop rather than loop itself is type checked for the second argument to foo and fails: Int != Unit => Int
The change to loop has a typo.

A: ()=>Int is Function0[Int] while Unit=>Int is Function1[Unit,Int]
scala> val function0: () => Int = () => 5
function0: () => Int = <function0>

scala> val function1: Unit => Int = u => 5
function1: (Unit) => Int = <function1>

scala> function0()
res0: Int = 5

scala> function1("anything")
res1: Int = 5

scala> function1(100)
res2: Int = 5

scala>

Also note that () is an object of Unit
scala> function1(())
res11: Int = 5

scala> function1 ()
res12: Int = 5

scala> function1()
res13: Int = 5

scala> val unit = ()
unit: Unit = ()

scala> function1(unit)
res15: Int = 5

scala> function1 apply unit
res16: Int = 5

scala>


text:
Q: is_valid always False (Django) I have the following form with dynamic fields:
1) In models.py I want to pass in a value to the form to query
class InsertValuesForm(forms.Form):
    def __init__(self, idfield, *args, **kwargs):

        super(InsertValuesForm, self).__init__(*args, **kwargs)

        for f in Parameter.objects.filter(id=idfield):

            if Part.objects.get(parameter=f.parameter_name).isfunction:
                self.fields.update({
                            f.parameter_name) : forms.CharField(widget=forms.TextInput() )})

1) In views.py
def something(request)
#......
                idfield = request.GET.get('feid','0')

                form = InsertValuesForm(request.POST,idfield)

                if request.method == 'POST':

                    if form.is_valid():

                       #some code

                else:

                    form = InsertValuesForm(idfield)

                return render_to_response('fuzz/configuration.html', {
                'form': form,
            },context_instance=RequestContext(request))

In number 1 situation, I was able to display the dynamic fields in the for loop. However, the form threw me this error after filling up all of the fields and submitting(POST):
int() argument must be a string or a number, not 'QueryDict'. I was thinking it is the request.POST that is causing the error.
after doing some research on this problem, there were similar solutions like this:
http://groups.google.com/group/django-users/browse_thread/thread/ddefd76324ffe6cd
http://groups.google.com/group/django-users/browse_thread/thread/495a917396b20b37/c430d71a31204e5d#c430d71a31204e5d
2) In models.py
class InsertValuesForm(forms.Form):
    def __init__(self, *args, **kwargs):

        idfield = kwargs.pop('idfield', False)

        super(InsertValuesForm, self).__init__(*args, **kwargs)

        for f in Parameter.objects.filter(id=idfield):

            if Part.objects.get(parameter=f.parameter_name).isfunction:
                self.fields.update({
                            f.parameter_name) : forms.CharField(widget=forms.TextInput() )})

and
the following snippet of views.py(same as number 1)
def something(request)
#......
                idfield = request.GET.get('feid','0')

                form = InsertValuesForm(request.POST,idfield)

                if request.method == 'POST':

                    if form.is_valid():

                       #some code

                else:

                    form = InsertValuesForm(idfield)

                return render_to_response('fuzz/configuration.html', {
                'form': form,
            },context_instance=RequestContext(request))

Now the above code doesn't even display the dynamic textboxes and is just displayed as blank page. Appreciate if anybody can shed some light on
how to display these dynamic textboxes and at the same time,
getting the values of these textboxes via request.POST and also making the form validate. Thanks

A: You have changed the signature of the form's __init__ so that the first positional parameter is idfield. Don't do that, because now when you instantiate it with form = InsertValuesForm(request.POST,idfield), it's taking the first parameter to be idfield, rather than request.POST.
Instead, define the method like this:
 def __init__(self, *args, **kwargs):
      idfield = kwargs.pop('idfield', None)
      ...etc...

and instantiate it with a keyword arg:
form = InsertValuesForm(request.POST, idfield=idfield)


text:
Q: Is dataframe name required when using case_when inside mutate? full <- full %>%
  mutate(Title = case_when(
    Title %in% c('Mlle', 'Ms') ~ 'Miss',
    Title == 'Mme' ~ 'Mrs',
    Title %in% rare_title ~ 'Rare Title',
    TRUE ~ Title
  ))

Code above gives an error: Error in eval(substitute(expr), envir, enclos) : object 'Title' not found
However, below code works. Is the data-frame name required inside case_when (makes the code more verbose).
full <- full %>%
  mutate(Title = case_when(
    full$Title %in% c('Mlle', 'Ms') ~ 'Miss',
    full$Title == 'Mme' ~ 'Mrs',
    full$Title %in% rare_title ~ 'Rare Title',
    TRUE ~ full$Title
  ))

A: We can use .$ instead of calling full$
full <- full %>%
          mutate(Title = case_when(
                 .$Title %in% c('Mlle', 'Ms') ~ 'Miss',
                  .$Title == 'Mme' ~ 'Mrs',
                   .$Title %in% rare_title ~ 'Rare Title',
                    TRUE ~ .$Title
             ))

data
set.seed(24)
full <- data.frame(Title = sample(c('Mlle', 'Ms', 'Mme', 'Colonel', 'Jr'), 20,
                 replace=TRUE), stringsAsFactors= FALSE)
rare_title <- 'Colonel'


text:
Q: Automatically update xcore/ecore attribute In an Eclipse plug-in I have a custom model defined in an .xcore file and it contains this EClass definition:
class Person {
    String name
    String surname

    Date dateUpdated
}

My question here is: if I manually edit any of the attributes of an instance of this class (in the Eclipse properties view), is there a way to automatically update the dateUpdated attribute?
I know that this can be done with an EContentAdapter, but is there an easier way to define this in the Xcore file or through some other mechanism?


text:
Q: Why is the regex replace method not working? In the following code I want to replace every occurrence of "U.S.A" with "united states of America" and every occurrence of "uk" with "united kingdom" in a string, but it does not seem to work. How do I fix it?
class Program
    {
        static void Main(string[] args)
        {
            string s = "the U.S.A love UK";
            Console.WriteLine(replace(s));
        }

        public static string replace(string s)
        {
            s = Regex.Replace(s, @"^U.S.A", " United state Of America");
            s = Regex.Replace(s, @"^Uk", "United kingdom");
            return s;
        }

    }

A: Well, look at the search pattern in your regex.
The ^ has a specific meaning. (as do the . but they won't actually fail in this case, but they aren't doing what you think they are)

A: *

*The . in your U.S.A expression will match any single character.  I doubt that's what you intend.

*The ^ pins your expression to the beginning of the string.  You don't want it.

*By default, regular expressions are case sensitive.  If you want Uk to match UK you need to specify a case-insensitive compare.

A: To expand upon annakata's answer:
In regular expressions the '^' character means "match at the beginning of the String", so if you wanted "U.S.A." to be replaced, it would have to be the first six characters in the string, same for UK. Drop the '^' from your RE, and it should work.
And regarding the comment about the '.' character, in regular expressions this means match any character. If you wish to match a literal '.' you must escape it like this "."

A: For simple replacements, you don't need Regular expressions:
string s = "the U.S.A love UK";
s = s.Replace("U.S.A", "United States of America").Replace("UK", "United Kingdom");

A: There are already enough correct answers above.  So I'll just add that an excellent resource for better understanding regular expressions is Mastering Regular Expressions


text:
Q: Junk in my downloads folder Windows 10 I have random files in my downloads folder. Their names are like u1,u2... Is it safe to delete them?image

A: If they  have some file extensions like .opdownload or .crdownload or anything like opera web document, it is completely safe to delete them. They are incomplete downloads caused due to technical errors..
Check the file type.


text:
Q: How to load/refresh ngAfterViewInit after query params value changes on same component? I am loading createComponent(this.queryparams) method ngAfterViewInit() event and passing the queryparams value in createComponent method. Depending upon the query params value I am loading Component dynamically.
But the component is loading once only on page load and when query param value is changing it is not loading the component.
How to refresh/load the ngAfterViewInit() on query param value changes?

A: You could subscribe to actvatedRoute params, and when params change, just simply reload the method where you use those params. Let's see that in action:
component.html:
***
constructor(){
 this.activatedRoute.params.subscribe(params => {
        this.id = params.id;
        this.name = params.name;
        this.ngAfterViewInit(); // or some other method where you are using those query parameters
    });
***

Hope this will help you!

A: please try this:
ngOnChanges(changes: SimpleChanges) {
       this.createComponent(this.wizardData);
   }


text:
Q: Find out CPU usage by reporting server Is there a way to found out what is the CPU usage of the reporting server? Sometimes the CPU usage is rised up by 40% percent for several seconds. I think the reporting server is causing it but I am not able to track it down.
I have try different techniques:

*

*SQL Server Performance Dashboard Reports

*sp_whoisactive

*Activity top session report

*this query

*looking at ExecutionLog3 View
The major problem is that the CPU usage value is raised from 20 to 60 percent for several seconds only. A lot of queries are executed and I am not able to identify which ones belongs to the reporting server.
Also, a bit of offtopic, but I have read that is a good practice to use the reporting server of the secondary databases when you have Always on Availability Group - is there any other licence requirements?

A: Regarding running reports from an Availability Group secondary server, you will need to license that instance of SQL Server.  Since the AG requirements require identical equipment, your secondary's licensing cost will reflect the primary server's licensing cost
Using the secondary server strictly for High Availability/Disaster Recovery does not require licensing the secondary server since it is only in use when the primary fails.
Regarding the brief spikes in CPU utilization, is it causing you a problem now?  Since it is hard for you to see who is responsible, consider loading sp_whoisactive from Adam Machanic's site: http://whoisactive.com  This stored procedure has numerous options to control what information you can query.
Brent Ozar also has an article on using sp_whoisactive to track issues within your system, logging the output to a file for later review.  http://www.brentozar.com/responder/log-sp_whoisactive-to-a-table/
Perhaps these tools will help you find out what is happening.