text:
Q: Drawing checkerboard's reference frame for pose estimation using OpenCV (solvePnP+projectPoints) I have followed the tutorial at https://docs.opencv.org/master/d7/d53/tutorial_py_pose.html based on calibration data obtained following the tutorial at https://docs.opencv.org/master/dc/dbb/tutorial_py_calibration.html.
The end objective is to obtain the pose of the checkerboard with respect to the camera, but first I am trying to draw the checkerboard's reference frame.
The input data is a set of 2 snapshots I have taken of my webcam feed pointed at a printed 10x7 checkerboard.
The calibration seems to succeed:

But the output is totally wrong:

Here is the patched-up code:
import cv2 as cv
import numpy as np
import glob
import argparse

# algorithm parameters
CHECKERBOARD_WIDTH = 9
CHECKERBOARD_HEIGHT = 6

# termination criteria
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.001)

#=== CALIBRATE CAMERA ============================================================================

#Prepare object points
objp = np.zeros((CHECKERBOARD_HEIGHT * CHECKERBOARD_WIDTH, 3), np.float32)
objp[:,:2] = np.mgrid[0:CHECKERBOARD_HEIGHT, 0:CHECKERBOARD_WIDTH].T.reshape(-1,2)

# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.

# Load the images
ap = argparse.ArgumentParser()
ap.add_argument('-f', '--folder', required=True,  help='Path to the images folder with last slash')
ap.add_argument('-e', '--ext', required=True,  help='Extension of image files without the dot')
args = vars(ap.parse_args())

images = glob.glob(args['folder']+'*.'+args['ext'])

#Process the images
for fname in images:
    print('Calibrating on '+fname)
    img = cv.imread(fname)
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    # Find the chess board corners
    ret, corners = cv.findChessboardCorners(gray, (CHECKERBOARD_WIDTH,CHECKERBOARD_HEIGHT), None)
    # If found, add object points, image points (after refining them)
    if ret == True:
        print('Found corners')
        objpoints.append(objp)
        corners2 = cv.cornerSubPix(gray,corners, (11,11), (-1,-1), criteria)
        imgpoints.append(corners)
        # Draw and display the corners as feedback to the user
        cv.drawChessboardCorners(img, (CHECKERBOARD_WIDTH,CHECKERBOARD_HEIGHT), corners2, ret)
        cv.imshow('Calibration', img)
        k = cv.waitKey(0) & 0xFF
        if k == ord('s'):
            cv.imwrite(fname+'_calib.png', img)

cv.destroyAllWindows()

#Obtain camera parameters
ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)

#=== FIND POSE OF TARGETS ===========================================================================

#Prepare object points
objp = np.zeros((CHECKERBOARD_HEIGHT * CHECKERBOARD_WIDTH, 3), np.float32)
objp[:,:2] = np.mgrid[0:CHECKERBOARD_HEIGHT, 0:CHECKERBOARD_WIDTH].T.reshape(-1,2)

axis = np.float32([[3,0,0], [0,3,0], [0,0,-3]]).reshape(-1,3)

#Display
def draw(img, corners, imgpts):
    corner = tuple(corners[0].ravel())
    img = cv.line(img, corner, tuple(imgpts[0].ravel()), (255,0,0), 5)
    img = cv.line(img, corner, tuple(imgpts[1].ravel()), (0,255,0), 5)
    img = cv.line(img, corner, tuple(imgpts[2].ravel()), (0,0,255), 5)
    return img

for fname in images:
    print('Processing '+fname)
    img = cv.imread(fname)
    gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
    ret, corners = cv.findChessboardCorners(gray, (CHECKERBOARD_WIDTH,CHECKERBOARD_HEIGHT), None)
    if ret == True:
        print('Found corners')
        corners2 = cv.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
        # Find the rotation and translation vectors.
        ret,rvecs, tvecs = cv.solvePnP(objp, corners2, mtx, dist)
        # project 3D points to image plane
        imgpts, jac = cv.projectPoints(axis, rvecs, tvecs, mtx, dist)
        img = draw(img,corners2,imgpts)
        cv.imshow('img',img)
        k = cv.waitKey(0) & 0xFF
        if k == ord('s'):
            cv.imwrite(fname+'_output.png', img)

cv.destroyAllWindows()

Called e.g. with:
python3 test_cvpnp.py --folder ./images/ --ext png

The images for calibration and for the processing are the same, which should yield good results. What is happening?
The original images are as follows, in case you might want to reproduce the behaviour:

Edit: I have tested opening my webcam frame-by-frame and processing 30-40 frames (at 2 FPS) in different orientations instead of 2 to get more data, but the reference frames are still drawn completely incorrectly and the RMS error for calibration is ~100 apparently. The improved code can be found here. What's wrong?

A: Getting 100 pixel RMS error means your calibration is very wrong.
Your images show a target that is not very flat, and some blurring.
Suggest you follow these guidelines.

A: It took me a long, long, long time comparing my code with an example as-is formatted in the same way, to finally notice I had swapped Width and Height when calling findChessboardCorners()... Problem solved, everything works as expected with an RMS error between 0.2 and 0.6. The pose of the target is very accurately tracked, so I can confirm we do not need expensive targets to have sub-pixel RMS accuracy.


text:
Q: Editing Java Web Application I have a small workshop "Modern Autos Workshop" and i am managing my maintenance activities via a Computerized Maintenance Management Software. The application was developed by a freelancer and he simply gave me a windows installer .EXECUTABLE file. The application was designed on JAVA, in short, it was a DYNAMIC JAVA WEB DATABASE APPLICATION. Now i have changed the name of my workshop and i don't know how to change the name displayed on my software and invoices.
When i opened the installation directory, following folders were found:
 1= app (contains number of .jar files including "Modern Autos
    Workshop Run.jar" and a "Modern Autos Workshop.war" file)
        2= db (contains .DAT files)
        3= JRE 6 (contains lib folder)
        4= Jetty Temp (contains files extracted from .war file from 1= app folder)
        5= my db (contains lib folder)
        6= my db backup (contains lib folder)
        7= Modern Autos Workshop Run.jar file

i am not a programmer, but  please help me if some one can do this impossible thing..!

A: It would be possible using a decompiler to do what you are trying to do but it will be very hard unless you are an experienced developer.
If you have access to the original source code (at the very least it will have files called ".java" in it) then it is a bit easier but unless you already know the basics of programming it will not be trivial.
Ideally there will be a configuration file or database table that you can change so I would look for files with the extension "properties" or "txt" and also look in the database tables.
For an experienced developer (assuming they have the source code) it will be a very fast and easy job.

A: Without source code it will be quite difficult. You have to decompile byte code and then perform change and after that compile code again. Assuming you have all the tools, it can be quite complex even for skilled developers.
You can only analize your database if there is data which you can change. That change will be easy. Everything else is not easy, especially not for non-programmers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Efficient low rank matrix-vector multiplication If I have large matrix, but with very low rank, say 2. Is there an efficient way to multiply this matrix by vector (to achieve linear complexity)?

A: If you have an SVD representation of the matrix, you can use this to compute the product in linear time.  I'm not sure how to efficiently compute this representation, though.  You can also truncate the SVD of a higher-rank matrix to get a low-rank approximation.
More specifically, if an $m\times n$ matrix is of rank $r$, its (compact) SVD representation is the product of an $m\times r$ matrix, an $r \times r$ diagonal matrix, and an $r \times n$ matrix.  If $r$ is constant, you can multiply this by a vector in $O(m+n)$ time.


text:
Q: Shared element activity transition between fragments in separate activities Shared element transitions are with us for a considerable time now and still there are some things that are not (at least explicitly) said.
My problem is following:
I have two activities, lets call them FirstActivity and SecondActivity. Both of them have their fragments, FirstFragment is settled in FirstActivity and SecondFragment is in SecondActivity.
Element that I want animated is in FirstFragment. His transition destination is in SecondFragment.
Research has gotten me to a (I hope wrong) conclusion that what I want to achieve is not possible.
My question for you guys is: is there a possibility to make this work or should I move my logic from SecondFragment to SecondActivity and ditch the fragment?


text:
Q: AS3 drawing movement path for object So I want to create a game for a touch table and I am looking for a code that creates a path by drawing it. I want it for now with a mouse_down event so if anyone could help me out or tell me if it's possible that would be great. I have no code to show what I have for the path, But I am now using the move to mouse position click event.
Well I hope I gave you peeps enough information on this matter.
Greeting,
Angelo

A: Yes it is possible, and I am sure a quick Google would show many ways to do it.
You can use the Graphics API to draw lines. You might want to store the mouse position on mouse move, and draw a line from the previous position to the current position on move.
You will probably mostly want the moveTo and lineTo functions.


text:
Q: Modify undo/redo behaviour on a textarea/menu in electron I devel electron application.
An application that edits a UML sequence diagram using canvas and multiple textarea.
Since textarea on the window takes Undo (Ctrl + z), Undo on Electron's Menu will not be called.
How can I invalidate the textarea's Undo and pass Control + z to the Electron's Menu?
Steps to reproduce
Register Undo (Ctrl + z) in Electron's Menu.
Create application screen including textarea.
Launch application.
Edit textarea.
(Without focus on textarea) Press Ctrl + z.
What I expected to see
Undo in Electron's Menu is called.
What I saw instead
The focus moves to the textarea.
The contents of textarea are undoed.
Undo in Electron's Menu is not called.
Other
Disable Chrome's text input undo/redo (CTRL+Z / CTRL+Y) was not perfect.

A: I encountered the same problem today. I think it's a bug in electron that they don't override the native ctrl + z and ctrl + y of input fields when an accelerator is set.
I found a workaround with this hack:
let zDown = false;
let zFired = false;
let yDown = false;
let yFired = false;
document.onkeydown = function(e) {
    if (e.ctrlKey) {
        if (e.key === 'z') {
            zDown = true;
        }
        else if (e.key === 'y') {
            yDown = true;
        }
    }
};
document.onkeyup = function(e) {
    if (e.key === 'z' && zDown) {
        if (!zFired) {
            menu.getMenuItemById('undo').click();
        }
        zDown = zFired = false;
    }
    else if (e.key === 'y' && yDown) {
        if (!yFired) {
            menu.getMenuItemById('redo').click();
        }
        yDown = yFired = false;
    }
};

let menu = Menu.buildFromTemplate([{
    "label": "Edit",
    "submenu": [{
        "id": "undo",
        "label": "Undo",
        "accelerator": "CmdOrCtrl + z",
        click: () => {
            zFired = true;
            app.undo();
        }
    }, {
        "id": "redo",
        "label": "Redo",
        "accelerator": "CmdOrCtrl + y",
        click: () => {
            yFired = true;
            app.redo();
        }
    }]
}]);

It's dirty, but it works.


text:
Q: How to do POST and GET request same button jQuery I have been stuck on this same problem now for 2 weeks with 10-15 hours a day.
I am using dynamic buttons that append more buttons which work like tabs on my view which are dynamic.
I can only use 1 form for this so the dynamic buttons are being used to know which model ID to load.
I have to use only 1 form Simple jquery is this:
$("#copy-link").click(function (e) {
    e.preventDefault();

    var num_tabs = $("div#tabSequence ul li").length + 1;
    $("div#tabSequence ul").append(
        "
#" + num_tabs + "
"
    );

    var data =  $('#campaign-form').serialize();

      $.ajax(
            {
                dataType: 'html',
                type: 'POST',
                url: "campaigns/sequencesave",
                data: data,
                success: function(response){
                    var campaignId = response;
                    var test2 = document.getElementById("link" + num_tabs);
                    console.log(test2);
                    test2.setAttribute("data-campaign", campaignId);
                }

            }
    )
});

Is there a way I can POST form data and also load form content for the Tab button clicked?
$("body").on("click", ".nav-tabs li a", function() {
        var data =  $('#campaign-form').serialize();

        $.ajax(
            {
                dataType: 'html',
                type: 'POST',
                url: "campaigns/sequenceupdate",
                data: { 'campaign_uid' : $(this).attr('data-campaign'), csrf_token: csrfTokenValue },

            }
        )
    })

^^ that same button clicked has to save what is currently on the view and then load contents for the button clicked. I am appending an ID of the Model needed to the button when user clicks #copy-link and saving it automatically

A: Im not a jQuery wiz but you can do this with straight up javascript in conjunction with Jquery.
function postInfo(event){
    httpRequest = new XMLHttpRequest();
    if (!httpRequest) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }
    httpRequest.onreadystatechange = results;
    httpRequest.open('POST', 'ENTER YOUR URL HERE');
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send('serverpin='+ServerPIN+'&restuarantid='+RestaurantID); //<-these are the variables you are posting
  }

function results(){
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        // WHATEVER YOU WANT TO MAKE IT DO IF THE REQUEST IS SUCCESSFUL
      } else {
        alert('There was a problem with the request.');
      }
    }
  }

And then to invoke it I use an event listener like this
document.getElementById('WHATEVERIDMATTERS').addEventListener('click',postOrder);


text:
Q: Operator not working correctly help needed My program is almost done, but the output just doesn't get the right numbers.
Baby names:
 1. Reading file: "src/people.txt" ... Number of lines in text file: 258000 number of lines in file is: 15 file has been read!
 2. Sorted by popularity:
  BabyNames object
    1:  John 1880 0.081541 0
    2:   0 0 0
    3:   0 0 0
    4:   0 0 0
    5:   0 0 0
    6:   0 0 0
    7:   0 0 0
    8:   0 0 0
    9:   0 0 0
    10:   0 0 0
    11:   0 0 0
    12:   0 0 0
    13:   0 0 0
    14:   0 0 0
    15:   0 0 0
 3. Sorted by name:
  BabyNames object
    1:  John 1880 0.081541 0
    2:   0 0 0
    3:   0 0 0
    4:   0 0 0
    5:   0 0 0
    6:   0 0 0
    7:   0 0 0
    8:   0 0 0
    9:   0 0 0
    10:   0 0 0
    11:   0 0 0
    12:   0 0 0
    13:   0 0 0
    14:   0 0 0
    15:   0 0 0
 4. Sorted by year:
  BabyNames object
    1:  John 1880 0.081541 0
    2:   0 0 0
    3:   0 0 0
    4:   0 0 0
    5:   0 0 0
    6:   0 0 0
    7:   0 0 0
    8:   0 0 0
    9:   0 0 0
    10:   0 0 0
    11:   0 0 0
    12:   0 0 0
    13:   0 0 0
    14:   0 0 0
    15:   0 0 0
 5. Original names:
  BabyNames object
    1:  John 1880 0.081541 0
    2:   0 0 0
    3:   0 0 0
    4:   0 0 0
    5:   0 0 0
    6:   0 0 0
    7:   0 0 0
    8:   0 0 0
    9:   0 0 0
    10:   0 0 0
    11:   0 0 0
    12:   0 0 0
    13:   0 0 0
    14:   0 0 0
    15:   0 0 0
Destructor to deallocate memory... Done!
Destructor to deallocate memory... Done!
Destructor to deallocate memory... Done!
Destructor to deallocate memory... Done!
... all done!

This is what it print. All of the 2-15 should have names and stats in them, but for some reason it is all 0.
Here is my code
BabyNames.h
#ifndef BABYNAMES_H_
#define BABYNAMES_H_
#include <string>
#include <fstream>
using namespace std;

/**
 * gender: an enum to hold types boy and girl
 */
enum gender {boy, girl};

/**
 * PeopleStats: a data struct to hold year, name, double, and the enum type
 * gender
 */
struct PeopleStats {
    short year;
    string name;
    double percent;
    gender sex;
};

/**
 * Names: A class that reads data from a file into a PeopleStats Array
 * and is capable of sorting them by name and by popularity percentage
 */
class BabyNames {

public:

    BabyNames(const BabyNames& bn);
    BabyNames( const int numLines);
    ~BabyNames();
    const gender parseSex(string s);
    void swap(int i);
    const int getCapacity();//getter for dataSize
    const PeopleStats& get(int i) const; //getter for objects of the data array
    void sortByName();      //Sorts the names alphabetically
    void sortByPopularity();//Sorts the names by popularity
    void sortByYear();
    void addArrayFillCount();
    friend std::ostream& operator << (std::ostream& os, const PeopleStats& d);
    friend std::ostream& operator << (std::ostream& os, const BabyNames& bn);
    //friend std::istream& operator >> (std::istream& in, const PeopleStats& ac);
    friend std::istream& operator >> (std::istream& in, const BabyNames& ac);
private:

    PeopleStats* people;
    int capacity;
    int arrayFillCount; // to keep track of how many array locations have data objects in them
    static const int OUT_OF_BOUNDS = -1;

};//end of class

#endif  /* BABYNAMES_H */

BabyNames.cpp
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
#include "BabyNames.h"

/**
 * BabyNames: A class that reads data from a file into a PeopleStats Array
 * and is capable of sorting them by name and by popularity percentage
 */

BabyNames::BabyNames(const int numberOfLines) {
    people = new PeopleStats[numberOfLines];
    capacity = numberOfLines;
    arrayFillCount = 0;

    for (int i=0 ; i<capacity; i++){
        people[i].year = 0;
        people[i].name = "";
        people[i].percent = 0;
        people[i].sex = boy;
    }
}

//Copy Constructor
BabyNames::BabyNames(const BabyNames& bn){
    capacity = bn.capacity;
        arrayFillCount = bn.arrayFillCount;
        people = new PeopleStats[ bn.capacity ];
    for (int i=0; i< bn.capacity ;i++)
        people[i] = bn.people[i];
}

BabyNames::~BabyNames(){
    cout << "Destructor to deallocate memory... Done!" << endl;
    delete[]people;
}

/*
 * sortByName - Sorts the entire array of people by name using the bubble
 * sort algorithm. Array is sorted according to name, within the structure
 * Algorithm becomes extremely slow if capacity > 3000
 */
void BabyNames::sortByName(){
    //sorted is set to true if no changes were made
    bool sorted = false;
    //change tells the loop if we made a swap or not
    bool change = false;
    while (!sorted) {
        for (int i = 0; i < capacity - 1; i++) {
            int compare = people[i].name.compare(people[i + 1].name);
            if (compare == 1) {
                swap(i);
                change = true;
            }
        }
        //if the array was not changed,
        //changed sorted to true and exit loop
        if (change == false)
            sorted = true;
        //otherwise reset change and repeat the loop
        else
            change = false;
    }
}

/**
 * sortByPopularity - sorts the entire array using the bubble sort algorithm
 * Method is almost exactly the same as sortByName, except the compare
 * variable is a double consisting of the difference of the two popularity
 * percentages.
 * Algorithm becomes extremely slow if capacity > 3000
 */
void BabyNames::sortByPopularity(){
    bool sorted = false;
    bool change = false;
    while (!sorted) {
        for (int i = 0; i < capacity - 1; i++) {
            double compare = people[i].percent - people[i + 1].percent;
            if (compare < 0) {
                swap(i);
                change = true;
                break;
            }
        }
        if (change == false)
            sorted = true;
        change = false;
    }
}

void BabyNames::sortByYear(){
    bool sorted = false;
    bool change = false;
    while (!sorted) {
        for (int i = 0; i < capacity - 1; i++) {
            double compare = people[i].year - people[i + 1].year;
            if (compare < 0) {
                swap(i);
                change = true;
                break;
            }
        }
        if (change == false)
            sorted = true;
        change = false;
    }
}
/**
 * swap - swaps the positions of people[i] and people[i + 1]
 * @param i - index of the people array that will get swapped with i + 1
 */
void BabyNames::swap(int i) {
    PeopleStats temp = people[i + 1];
    people[i + 1] = people[i];
    people[i] = temp;
}

/**
 * getCapacity: returns the number of data entries stored.
 * @return size of the data
 */
const int BabyNames::getCapacity(){
    return capacity;
}

/**
 * get: returns one PeopleStat Object
 * @param i
 * @require: i < capacity
 * @return PeopleStat object
 */
const PeopleStats& BabyNames::get(int i) const {
    if (i>=0 && i < capacity)
        return people[i];
    throw OUT_OF_BOUNDS;
}
/**
 * << - overloads the outstream operator for PeopleStats object
 * @param os
 * @param d
 * @return os : output stream
 */
std::ostream & operator << (std::ostream& os, const PeopleStats& d){
    os << d.name << " " << d.year << " " << d.percent << " " << d.sex;
    return os;
}

/**
 * <<: overloads the outstream operator for the BabyNames object
 * @param os
 * @param bn
 * @return
 */
std::ostream& operator << (std::ostream& os, const BabyNames& bn) {
    os << "  BabyNames object " << std::endl;
    for (int i=0; i < bn.capacity; i++ )
        os << "    " << (i+1) <<":  " << bn.get( i ) << std::endl;
    return os;
}//end of operator

/*std::istream& operator >> (std::istream& in, const PeopleStats& ac){
    in>>ac.year>>ac.name>>ac.percent>>ac.sex;
    //struct doesnt need a loop in the operator
    return in;
}*/

std::istream& operator >> (std::istream& in, const BabyNames& ac){

    short tempYear;
    string tempName;
    double tempPercent;
    string  tempSex;
    int arrayLocation = ac.arrayFillCount;
    in >> tempYear;
    in >> tempName;
    in >> tempPercent;
    in >> tempSex;
    //gender tempGender = parseSex(tempSex);
    ac.people[ arrayLocation ].year = tempYear;
    ac.people[ arrayLocation ].name = tempName;
    ac.people[ arrayLocation ].percent = tempPercent;

    if( tempSex.compare( "boy" ) == 0 )
        ac.people[ arrayLocation ].sex = boy;
    else if ( tempSex.compare( "girl" ) == 0 )
        ac.people[ arrayLocation ].sex = girl;
    else
        throw "invalid Gender";
    //addArrayFillCount();

    return in;
}
//Baby names extraction operator does need a loop

void BabyNames::addArrayFillCount(){
    arrayFillCount++;
}

Main
#include <iostream>
#include "BabyNames.h"

/**
 * main: The client function that controls the server, BabyNames
 * For reasons currently unknown, the program will take forever
 * to run after the  * 3000-5000 line mark.
 * @return 0 if successful
 */

int checkLines(string fn){
    int numberOfLines = 0;
    string temp;
    ifstream myfile( fn.c_str(), ios::in );
    while( getline( myfile, temp ) )
        numberOfLines++;
    std::cout << "Number of lines in text file: " << numberOfLines;
    return 15;
}//make a stand alone function

int main(void) {

    cout << "Baby names: " << endl;

    const char filename[] = "src/people.txt";
    cout << " 1. Reading file: \"" << filename << "\" ... ";
    int numberOfNames = checkLines(filename);
    cout << " number of lines in file is: " << numberOfNames;
    BabyNames* names = new BabyNames( numberOfNames );

    // read the contents of a file into names and print them
    ifstream myFile( filename, ios::in );
    //myfile.open(fn);
    myFile >> *names;
    cout << " file has been read!" << endl;

    // Sort and print
    cout << " 2. Sorted by popularity:" << endl;
    BabyNames* namesByPop = new BabyNames( *names );
    namesByPop->sortByPopularity();
    cout << *namesByPop;

    // Sort and print
    cout << " 3. Sorted by name:" << endl;
    BabyNames* namesByName = new BabyNames( *names );
    namesByName->sortByName();
    cout << *namesByName;

    // Sort and print
    cout << " 4. Sorted by year:" << endl;
    BabyNames* namesByYear = new BabyNames( *names );
    namesByYear->sortByYear();
    cout << *namesByYear;

    cout << " 5. Original names:" << endl;
    cout << *names;

    delete names;
    delete namesByYear;
    delete namesByName;
    delete namesByPop;

    cout << "... all done!" << endl;
}

The text file looks like this but there are 250000+ lines
1880 Henry 0.020641 boy
1880 Robert 0.020404 boy
1880 Edward 0.019965 boy
1880 Harry 0.018175 boy
1880 Walter 0.014822 boy
1880 Arthur 0.013504 boy
1880 Fred 0.013251 boy
1880 Albert 0.012609 boy

How do I get arrayFillCount to go up in the >> operator?

A: On myFile >> *names; you are calling std::istream& operator >> (std::istream&, const BabyNames&) which will execute the following code:
[...] // var declarations

in >> tempYear;
in >> tempName;
in >> tempPercent;
in >> tempSex;

ac.people[ arrayLocation ].year = tempYear;
ac.people[ arrayLocation ].name = tempName;
ac.people[ arrayLocation ].percent = tempPercent;

[...] // other checks and return

which will correctly read only the first line of the file and populate only the first of people inside the BabyNames object (the first time arrayLocation = 0).
You should execute myFile >> *names; for the number of lines you want to populate *names with.

I need to get arrayFillCount to go up with my >> operator. How do I do this?

You should just add arrayFillCount++; right after you fill ac.people[ arrayLocation ] data.


text:
Q: How to reset the value of a nested object? Below the given object i need to reset the value for the key "label", "value", "ward" and "tole" to empty(' ') using javascript.
state ={
         "label": "लुम्बिनी प्रदेश",
         "value": 21,

         "province": {
            "label": "लुम्बिनी प्रदेश",
            "value": "23"
         },
         "district": {
            "label": "अर्घाखाँची",
            "value": "20"
         },
         "local_level": {
            "label": "भूमिकास्थान नगरपालिका",
            "value": "17"
         },
         "ward": "10",
         "tole": "venas"
       }

I have tried to get the keys of the object
Object.keys(state).map(item=>({key: item}))

but don't have idea how to reset the value of the object.
The final result should look like this.
the state object may evolve i.e the key and value of the object may be added or may be removed.
state ={
         "label": '',
         "value": '',

         "province": {
            "label": '',
            "value": ''
         },
         "district": {
            "label": '',
            "value": ''
         },
         "local_level": {
            "label": '',
            "value": ''
         },
         "ward": '',
         "tole": ''
       }

A: You can iterate through the object using the for...in Loop in JS. And then, if you find those keys, then just replace their values with an empty string. And since, you also want to check again, that if the value of the keys are objects, and if they are, then you can again loop through them, and change their value to an empty string.
for (let key in state) {
  if (typeof state[key] === 'object') {

    // if the value of the key is an object, then we will again loop through the value of that key, and change the value of those keys to an empty string.

    for (let nestedKey in state[key]) {
      // console.log(nestedKey, state[key][nestedKey]);

      if (
        nestedKey === "label" ||
        nestedKey === "value" ||
        nestedKey === "ward" ||
        nestedKey === "tole"
      ) {
        state[key][nestedKey] = " ";
      }
    }
  }

  if (key === "label" || key === "value" || key === "ward" || key === "tole") {
    state[key] = " ";
  }
}

This code will work, and will change all those values to empty string.

A: let setToDefault = state => Object.assign(state, { label: '', value: '', ward: '', tole: '' });


text:
Q: parsing numbers in a string I'm trying to get my code to pass this test. If you've ever played magic the gathering, this might look familiar to you.
    Test.assert_equals(can_cast("11RB","10B","1R"), true)
    Test.assert_equals(can_cast("13BBRR","10BR","2R","B"), true)

But I can't seem to parse the correct numbers out of the elements correctly. Does anyone see a flaw in my code that's keeping me from passing these test?
def can_cast(hand, *spell_cost)
  colored_mana_hand = Array.new
  colored_mana_cost_aggregate = Array.new
  colored_mana_spent = Array.new

  colorless_mana_hand_array = []
  colorless_mana_hand = 0

  colorless_mana_cost_array = []
  colorless_mana_cost_aggregate_array = []
  colorless_mana_cost_aggregate = 0

  hand.split("").each do |i|
    if i.to_i != 0                        # extracting existing colorless mana from hand
    colorless_mana_hand_array << i
    else
    colored_mana_hand << i
    end
  end
  colorless_mana_hand = colorless_mana_hand_array.join.to_i

  spell_cost.each do |i|                   # extracting existing colorless mana from cost
    i.split("").each do |j|
      if j.to_i != 0
      colorless_mana_cost_array << j
    else
      colored_mana_cost_aggregate << j
    end
    end
      colorless_mana_cost_aggregate_array << colorless_mana_cost_array.join
      colorless_mana_cost_array.clear
  end

    colorless_mana_cost_aggregate_array.each do |i|
    colorless_mana_cost_aggregate += i.to_i
  end

    colored_mana_cost_aggregate.each do |i|                                                  # pay colored mana first
     if colored_mana_hand.include?(i)
       colored_mana_spent << i
       colored_mana_hand.rotate(colored_mana_hand.index(i)).shift
     end
  end

  (colored_mana_spent.sort == colored_mana_cost_aggregate.sort) && (colored_mana_hand.length + colorless_mana_hand) >= colorless_mana_cost_aggregate
end

A: This is a funny way to pull numbers out of the string. It would probably be easier to use scan, here is how you can use it:
# extracting existing colorless
colorless_mana_hand_array = hand.scan(/\d/).join.to_i

This will extract the digits from the string into an array, join them, and then convert to an integer.

A:
Does anyone see a flaw in my code that's keeping me from passing these test?

Yes, Indeed.
You split your spell_cost strings via:
i.split("").each do |j|
  # ...
end

The code will yield each single character to the block. For "10BR" this gives:
"10BR".split("").each do |j|
  p j: j
end

Output:
{:j=>"1"}
{:j=>"0"}
{:j=>"B"}
{:j=>"R"}

Furthermore you have this check:
if j.to_i != 0
  colorless_mana_cost_array << j
else
  colored_mana_cost_aggregate << j
end

For the above input, you get
colorless_mana_cost_array   #=> ["1"]
colored_mana_cost_aggregate #=> ["0", "B", "R"]

Because "0".to_i != 0 evaluate to false, just like "B" and "R".
If I understand your code correctly, "0" should go into the colorless_mana_cost_array.


text:
Q: Instancing Frame class I'm writing C#/XAML/UWP application and I'm wondering about instancing of frame control (https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.frame). I don't use caching, just standard scenario where each navigation creates a new instance of the specific Page subclass requested, and disposes the previous page instance. Each Page instance has Frame member, and navigation to another page is accomplished by:
this.Frame.Navigate(typeof(RequestedPage));

Can I assume, that for everypage this.Frame is the same object as "global variable" Window.Current.Content ? In what cases this assumption is not true?

A: Frame is a content control which supports the page navigation.
Page is a UserControl, this.Frame indicated which frame the page instance was contained.
You can assign any UI Element (e.g. Text Block) to Windows.Current.Content property to make the UI element show on the current window.
By default, the app will assign a rootFrame instance to Window.Current.Content. So it is not a "global variable".
About the cache of the Frame, you can check the document NavigationCacheMode enumeration.


text:
Q: Add Forgot password link to email signin with passwordless template I would like to add a Forgot Password link to the email signin page, like so:

I'm using the passwordless starter pack that splits Phone and Email signups/signins in different screens.
My problem is that I cannot find the right place to make the link appear in the email signin page. I followed the embedded password reset but I can only add it in the main page where it asks the user to type in his phone or email.
Here's the Relying party policy that I need to modify to add the password link SignUpSignInWithPhoneOrEmail:
<TrustFrameworkPolicy
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns="http://schemas.microsoft.com/online/cpim/schemas/2013/06"
  PolicySchemaVersion="0.3.0.0"
  TenantId="yourtenant.onmicrosoft.com"
  PolicyId="B2C_1A_SignUpOrSignInWithPhoneOrEmail"
  PublicPolicyUri="http://yourtenant.onmicrosoft.com/B2C_1A_SignUpOrSignInWithPhoneOrEmail"
  DeploymentMode="Development"
  UserJourneyRecorderEndpoint="urn:journeyrecorder:applicationinsights">

  <BasePolicy>
    <TenantId>yourtenant.onmicrosoft.com</TenantId>
    <PolicyId>B2C_1A_Phone_Email_Base_Extension</PolicyId>
  </BasePolicy>

  <UserJourneys>
    <UserJourney Id="SignUpOrSignInWithPhoneOrEmail-Custom">
      <OrchestrationSteps>
        <OrchestrationStep Order="1" Type="CombinedSignInAndSignUp" ContentDefinitionReferenceId="signuporsignin-phone-email">
          <ClaimsProviderSelections>
            <ClaimsProviderSelection ValidationClaimsExchangeId="LocalAccountSigninPhoneEmailExchange" />
            <ClaimsProviderSelection TargetClaimsExchangeId="SignUpWithEmail" />
            <ClaimsProviderSelection TargetClaimsExchangeId="SignUpWithPhone" />
            <ClaimsProviderSelection TargetClaimsExchangeId="ChangePhoneNumber" />
            <ClaimsProviderSelection TargetClaimsExchangeId="GoogleExchange" />
            <ClaimsProviderSelection TargetClaimsExchangeId="FacebookExchange" />
            <ClaimsProviderSelection TargetClaimsExchangeId="AppleExchange" />
          </ClaimsProviderSelections>
          <ClaimsExchanges>
            <ClaimsExchange Id="LocalAccountSigninPhoneEmailExchange" TechnicalProfileReferenceId="SelfAsserted-LocalAccountSignin-Phone-Email" />
          </ClaimsExchanges>
        </OrchestrationStep>
        <OrchestrationStep Order="2" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>isLocalAccountSignIn</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="GoogleExchange" TechnicalProfileReferenceId="Google-OAuth2" />
            <ClaimsExchange Id="FacebookExchange" TechnicalProfileReferenceId="Facebook-OAUTH" />
            <ClaimsExchange Id="AppleExchange" TechnicalProfileReferenceId="Apple-OIDC" />
            <ClaimsExchange Id="SignUpWithPhone" TechnicalProfileReferenceId="LocalAccountSignUpWithLogonPhoneNumber" />
            <ClaimsExchange Id="SignUpWithEmail" TechnicalProfileReferenceId="LocalAccountSignUpWithLogonEmail" />
            <ClaimsExchange Id="ChangePhoneNumber" TechnicalProfileReferenceId="PhoneInputPage-ChangePhoneNumberClaimsProviderSelection" />
          </ClaimsExchanges>
        </OrchestrationStep>
        <!-- If the user comes from phone signup, collect recovery email address  -->
        <OrchestrationStep Order="3" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>isLocalAccountSignIn</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>isEmailSignUp</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>isChangePhoneNumber</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
            <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
              <Value>authenticationSource</Value>
              <Value>socialIdpAuthentication</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="SignUpWithPhone_CollectEmailAddress" TechnicalProfileReferenceId="LocalAccountSignUpWithLogonPhoneNumber_CollectEmailAddress" />
          </ClaimsExchanges>
        </OrchestrationStep>
        <!-- Debugging Step (useful for the app insight)-->
        <OrchestrationStep Order="4" Type="ClaimsExchange">
          <ClaimsExchanges>
            <ClaimsExchange Id="Debugging Step to see the claim bag" TechnicalProfileReferenceId="Debug-TechProfile" />
          </ClaimsExchanges>
        </OrchestrationStep>
        <!-- For social IDP authentication, attempt to find the user account in the directory. -->
        <OrchestrationStep Order="5" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="false">
              <Value>authenticationSource</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
            <Precondition Type="ClaimEquals" ExecuteActionsIf="false">
              <Value>authenticationSource</Value>
              <Value>socialIdpAuthentication</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserReadUsingAlternativeSecurityId" TechnicalProfileReferenceId="AAD-UserReadUsingAlternativeSecurityId-NoError" />
          </ClaimsExchanges>
        </OrchestrationStep>
        <!-- Create the user in the directory if one does not already exist
             (verified using objectId which would be set from the last step if account was created in the directory. -->
        <OrchestrationStep Order="6" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="false">
              <Value>authenticationSource</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
            <Precondition Type="ClaimEquals" ExecuteActionsIf="false">
              <Value>authenticationSource</Value>
              <Value>socialIdpAuthentication</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserWrite" TechnicalProfileReferenceId="AAD-UserWriteUsingAlternativeSecurityId" />
          </ClaimsExchanges>
        </OrchestrationStep>
       <!-- Leave the rest of the template  -->
        <OrchestrationStep Order="7" Type="InvokeSubJourney">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="false">
              <Value>isLocalAccountSignIn</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <JourneyList>
            <Candidate SubJourneyReferenceId="SignInWithPhoneOrEmail" />
          </JourneyList>
        </OrchestrationStep>
        <OrchestrationStep Order="8" Type="InvokeSubJourney">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="false">
              <Value>isChangePhoneNumber</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <JourneyList>
            <Candidate SubJourneyReferenceId="ChangePhoneNumber" />
          </JourneyList>
        </OrchestrationStep>
        <OrchestrationStep Order="9" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>hasFullProfile</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserReadWithObjectId" TechnicalProfileReferenceId="AAD-UserReadUsingObjectId" />
          </ClaimsExchanges>
        </OrchestrationStep>
        <OrchestrationStep Order="10" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />
      </OrchestrationSteps>
      <ClientDefinition ReferenceId="DefaultWeb" />
    </UserJourney>
  </UserJourneys>

  <RelyingParty>
    <DefaultUserJourney ReferenceId="SignUpOrSignInWithPhoneOrEmail-Custom" />
    <UserJourneyBehaviors>
      <JourneyInsights TelemetryEngine="ApplicationInsights" InstrumentationKey="urkey" DeveloperMode="true" ClientEnabled="false" ServerEnabled="true" TelemetryVersion="1.0.0" />
      <ScriptExecution>Allow</ScriptExecution>
    </UserJourneyBehaviors>
    <TechnicalProfile Id="PolicyProfile">
      <DisplayName>PolicyProfile</DisplayName>
      <Protocol Name="OpenIdConnect" />
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="displayName" />
        <OutputClaim ClaimTypeReferenceId="givenName" />
        <OutputClaim ClaimTypeReferenceId="surname" />
        <OutputClaim ClaimTypeReferenceId="email" />
        <OutputClaim ClaimTypeReferenceId="signInNames.phoneNumber" />
        <OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
        <OutputClaim ClaimTypeReferenceId="strongAuthenticationEmailAddress" />
        <OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub" />
        <OutputClaim ClaimTypeReferenceId="identityProvider" />
        <OutputClaim ClaimTypeReferenceId="tenantId" AlwaysUseDefaultValue="true" DefaultValue="{Policy:TenantObjectId}" />
      </OutputClaims>
      <SubjectNamingInfo ClaimType="sub" />
    </TechnicalProfile>
  </RelyingParty>
</TrustFrameworkPolicy>

I have no clue what I need to modify to add the forgot password link since this email signin page is a separate screen different from the examples.

A: I posted a complete explanation on the original GH issue that explains how to add the link to any email signin screen. GH issue answer here


text:
Q: mvc 4 complex list returning null In other parts of my web site I'm using nested lists and am able to display and save without problem.
However, I can't seem to figure out why it is not working this time.
ViewModel
public class ActivityEditViewModel
{
    //Activity
    public int ActivityID { get; set; }

    //... more properties

    public List<ActivityService> ActivityServices { get; set; }
    public class ActivityService
    {
        public int ServiceID { get; set; }
        [DisplayName("Outcome Comment")]
        public string OutcomeComment { get; set; }

        //... more properties
    }
}

View (Relevant part)
@for (int i = 0; i < Model.ActivityServices.Count; i++)
{
    @Html.HiddenFor(x => x.ActivityServices[i].ServiceID)
    @Html.LabelFor(x => Model.ActivityServices[i].OutcomeComment)
    @Html.TextBoxFor(x => Model.ActivityServices[i].OutcomeComment)
}

Controller
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(ViewModels.ActivityEditViewModel vm)
    {
        //vm.ActivityServices <== is always null

Question
Why does vm.ActivityServices return null?

A: You can create a partial view for ActivityService and render this in foreach:
In your actual view:
@foreach(ActivityService item in Model.ActivityServices)
{
    @Html.Partial("ActivityService", item)
}

In a new partial view ActivityService.cshtml:
@model Proyect.Models.ActivityEditViewModel.ActivityService

@Html.HiddenFor(m => m.ServiceID)
@Html.LabelFor(m => m.OutcomeComment)
@Html.TextBoxFor(m => m.OutcomeComment)

A: So your design Razor syntax must be as below:
You could first remove all your skipping elements by adding a line of code to remove and then use it normally to obtain desired record.
@
{
Model.ActivityServices.RemoveAll(o=> //your skip condition);
for (int i = 0; i < Model.ActivityServices.Count; i++)
{
    @Html.HiddenFor(x => Model.ActivityServices[i].ServiceID)
    @Html.LabelFor(x => Model.ActivityServices[i].OutcomeComment)
    @Html.TextBoxFor(x => Model.ActivityServices[i].OutcomeComment)
}
}


text:
Q: data.table outer join based on groups in R I have a data with the following columns:

CaseID, Time, Value.

The 'time' column values are not at regular intervals of 1. I am trying to add the missing values of time with 'NA' for the rest of the columns except CaseID.
Case Value  Time
1    100    07:52:00
1    110    07:53:00
1    120    07:55:00
2    10     08:35:00
2    11     08:36:00
2    12     08:38:00

Desired output:
Case Value  Time
1    100    07:52:00
1    110    07:53:00
1    NA     07:54:00
1    120    07:55:00
2    10     08:35:00
2    11     08:36:00
2    NA     08:37:00
2    12     08:38:00

I tried dt[CJ(unique(CaseID),seq(min(Time),max(Time),"min"))] but it gives the following error:
Error in vecseq(f__, len__, if (allow.cartesian || notjoin) NULL else as.integer(max(nrow(x),  :
  Join results in 9827315 rows; more than 9620640 = max(nrow(x),nrow(i)). Check for duplicate key values in i, each of which join to the same group in x over and over again. If that's ok, try including `j` and dropping `by` (by-without-by) so that j runs for each group to avoid the large allocation. If you are sure you wish to proceed, rerun with allow.cartesian=TRUE. Otherwise, please search for this error message in the FAQ, Wiki, Stack Overflow and datatable-help for advice.

I cannot able to make it work..any help would be appreciated.

A: Like this??
dt[,Time:=as.POSIXct(Time,format="%H:%M:%S")]
result <- dt[,list(Time=seq(min(Time),max(Time),by="1 min")),by=Case]
setkey(result,Case,Time)
setkey(dt,Case,Time)
result <- dt[result][,Time:=format(Time,"%H:%M:%S")]
result
#    Case Value     Time
# 1:    1   100 07:52:00
# 2:    1   110 07:53:00
# 3:    1    NA 07:54:00
# 4:    1   120 07:55:00
# 5:    2    10 08:35:00
# 6:    2    11 08:36:00
# 7:    2    NA 08:37:00
# 8:    2    12 08:38:00

Another way:
dt[, Time := as.POSIXct(Time, format = "%H:%M:%S")]
setkey(dt, Time)
dt[, .SD[J(seq(min(Time), max(Time), by='1 min'))], by=Case]

We group by Case and join on Time on each group using .SD (hence setting key on Time). From here you can use format() as shown above.


text:
Q: InfluxDB - Aggregate data on state duration I have a measurement in InfluxDB that keeps track of the status of a system. For example, consider the following measures:
03/22/18 00:00:00AM    STATUS_A
03/22/18 09:00:00AM    STATUS_B
03/22/18 13:00:00AM    STATUS_C
03/22/18 18:00:00AM    STATUS_B
03/22/18 19:00:00AM    STATUS_D
03/22/18 21:00:00AM    STATUS_A

What I need to do now is to derive how long the system was in each state every day. In the above example, the desired result is something like
STATUS_A    12h (from 00:00 to 09:00 and from 21:00 to 24:00)
STATUS_B    5h (from 09:00 to 13:00 and from 18:00 to 19:00)
STATUS_C    5h (from 13:00 to 18:00)
STATUS_D    2h (from 09:00 to 21:00)

I'm very new to the TICK stack, so I could be missing something quite elementary. I was thinking to use Kapacitor to create the aggregate result, but I don't really know how to obtain the result

A: You mentioned TICK stack so I assume you are using InfluxDB version 1.
It is feasible to report the total duration for a given state in InfluxDB but only in Flux not InfluxQL (easily).
You could try these steps:

*

*Enable Flux in v1.8 with the configuration change here

*Sample Flux could be:
from(bucket: "yourDatabaseName/autogen") |> range(start: 2018-03-20T00:00:00Z, stop: 2018-03-20T23:59:59Z) |> filter(fn: (r) => r._measurement == "yourMeasurementName")  |> stateDuration(fn: (r) => r._value == "STATUS_A", column: "state", unit: 1h)
Again it's still not possible to do it yet in InfluxQL though the community has been waiting for this for a while. See more details here.


text:
Q: Laravel PHP Fatal error: require(): Failed opening required ... bootstrap/autoload.php on line 17 I'm trying to deploy a website built on Laravel to an amazon ec2 micro instance. I've cloned the project and then ran composer install with no problems. However when I view it in the browser I get the error:
Error in exception handler..
In the error logs I can see the following error:
[Wed Nov 12 12:12:47.550414 2014] [:error] [pid 21572] [client x.x.x.x:x] PHP Fatal
error:  require(): Failed opening required '/home/production/public_html/kcnr-tv/bootstrap
/../vendor/autoload.php' (include_path='.:/usr/share/php:/usr/share/pear') in
 /home/production/public_html/kcnr-tv/bootstrap/autoload.php on line 17

I've googled this problem and a few people seem to have this issue but in almost all cases they have forgotten to run composer install.
I've increased the PHP memory limit to 1GB and still no luck. There doesn't appear to be an issue with installing dependencies as far as I can see as they are all in the vendor folder after composer has finished.
Any help with this would be great as I'm all out of ideas to what this could be.

A: try this command
composer install --no-script

this will skip the composer scripts execution as vendor files are still missing.

A: I fixed it with the following solution: Error in exception handler. - Laravel.
The app/storage permissions needed updating.

A: You need to run to
composer update

A: Use dump-autoload to generate new autoload.php
composer dump-autoload

use artisan optimize to clean the project
php artisan optimize:clear

If you are on Linux you need to set write permission to bootstrap/cache and storage directories.
sudo chmod -R 777 bootstrap/cache storage


text:
Q: python script - Scraping Data but not looping and bringing back all results I am new to python and need some help
See py script below, it brings back information for one entry but I want it to bring back all items that come up on that URL including on the pages not shown, What needs changing on the below to do that?
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as Soup

my_url = 'https://www.newegg.com/global/uk/Product/ProductList.aspx?
Submit=ENE&DEPA=0&Order=BESTMATCH&Description=graphics+card&N=-1&isNodeId=1'

uClient=uReq(my_url)
page_html = uClient.read()
uClient.close()

page_soup = Soup(page_html, 'html.parser')
containers = page_soup.findAll('div',{'class':'item-container'})
for container in containers:
    brand = container.div.div.a.img['title']

    title_container = container.findAll('a',{'class':'item-title'})
    product_name = title_container [0].text

    price_container = container.findAll('li',{'class':'price-current'})
    Price = price_container[0].text.strip()

    print("brand: " + brand)
    print("product_name: " + product_name)
    print("Price: + " + Price)


text:
Q: Counting term frequency in list of strings in pd dataframe I have a dataframe and one column contains the lemmatized words of a paragraph. I wish to count the frequency of each word within the whole dataframe, not just within the record. There are over 40,000 records so the computation has to be quick and not reach the limit of my RAM.
For example, this basic input:
ID                             lemm
 1                ['test','health']
 2  ['complete','health','science']

would have this desired output:
'complete':1
'health':2
'science':1
'test':1
This is my current code:
from collections import Counter
cnt = Counter()
for entry in df.lemm:
  for word in entry:
    cnt[word]+=1
cnt

Which works when I manually enter a list of a list of strings (ex/[['completing', 'dog', 'cat'], ['completing','degree','health','health']]), but not when it iterates through the df.
I have also tried this:
top_N=20
word_dist = nltk.FreqDist(df_main.stem)
print('All frequences')
print('='*60)
rslt=pd.DataFrame(word_dist.most_common(top_N),columns=['Word','Frequency'])
print(rslt)

to return the top 20 terms, but the output lists the frequencies of terms within the entry, not the entire dataframe.
Any help would be appreciated!

A: You can try explode if you have Pandas 0.25+:
df.Text.explode().value_counts()

A: maybe you can the counter line to:
cnt = Counter(word for entry in df.lemm for word in entry)
Refer to: How to find the lemmas and frequency count of each word in list of sentences in a list?

A: Assuming your column names and input data:
 data = {
    "ID": [1, 2],
    "lemm": [['test', 'health'], ['complete', 'health', 'science']]
}
df = pd.DataFrame(data)
freq = df.explode("lemm").groupby(["lemm"]).count().rename(columns={"ID" : "Frecuency"})

Output:

A: from collections import Counter
cnt = df.apply(lambda x:Counter(x['lemm']),axis=1).sum()

Will do it for you. That will make cnt a Counter object so you can do most common on it or anything else counter offers.


text:
Q: macOS - Not authorized to send Apple Events to <> I'm using AppleScript (inside of a macOS app) to get the currently active tab name in a browser. The code is following:
"tell application \"Google Chrome\" to return title of active tab of front window"

Until recently, everything was working fine. However, when I switched to the new version of Catalina, I started getting the following errors:
skipped scripting addition "/Library/ScriptingAdditions/Adobe Unit Types.osax" because it is not SIP-protected.

{
    NSAppleScriptErrorAppName = "Google Chrome";
    NSAppleScriptErrorBriefMessage = "Not authorized to send Apple events to Google Chrome.";
    NSAppleScriptErrorMessage = "Not authorized to send Apple events to Google Chrome.";
    NSAppleScriptErrorNumber = "-1743";
    NSAppleScriptErrorRange = "NSRange: {43, 3}";
}

I've tried adding NSAppleEventsUsageDescription and setting its value, but that produced no changes.
Any suggestions?


text:
Q: IE image issue when changing heights using 'background-size: cover' In IE 9+, using background-size: cover is fine except when using it with jQuery to expand the height of an element. The background is stretching like its suppose to but it leaves some background image artifacts from the previous height.
It only happens when there is a scroll bar present. Re-sizing the window can fix it if the user takes the time to do that.
You can see the issue here:
https://jsfiddle.net/g2afLhv5/4/
Screenshots here:
http://imgur.com/a/jhoxo
Is there any way around this using JS or CSS?

A: Try to wrap the content with a
and apply the background image to this wrapper.

$('.t1').click(function() {
  $('.box').css('height','900px');
});
$('.t2').click(function() {
  $('.box').css('height','1900px');
});
body {
  margin:0;
}

.body-wrapper {
  background:url('http://i.imgur.com/b7RXF5u.gif') center 0 no-repeat;
  background-size: cover;
  padding: 0 50px;
}

.box {
  margin: 50px 0;
  background: rgba(255,255,255,0.8);
  min-height: 900px;
  clear: both;
  border: 2px solid red;
}
.tabs {
  float: right;
}
.tabs div {
  float: left;
  border: 1px solid black;
  background-color: white;
  cursor: pointer;
}

Tab1

Tab2

A: Hi just add the background-attachment property fixed to the body
background-attachment: fixed;

Here is a working fiddle
https://jsfiddle.net/okouobeu/


text:
Q: 'As' always to describe something happening at the same time? I heard the conjunction 'As' even when used to describe the reason for something implies it is happening at the same time. So, I'm wondering if the following sentence is a little strange to hear for the same reason.

*

*As your dad studied hard back in high school, he has the right to tell you to do the same. (X / O) ?
If I replaced 'As' with 'Because' at the begining of the sentence, would it be correct grammatically?

A: Yes, it would still be grammatically correct. The because clause in the beginning of a sentence gives extra focus to the reason.

Because breathing is something we do automatically, we rarely think
  about it.
  https://dictionary.cambridge.org/grammar/british-grammar/as-because-or-since


text:
Q: datatables server side only working at localhost I have problem with datatables server side at my server. There no data showing on my table. When I check console, show this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at...

But on my localhost, data showing on my table. I followed the instruction here
https://datatables.net/examples/data_sources/server_side.html
here my javascript code
<script>
$(document).ready(function() {
    $('#example').DataTable( {
        "scrollX": true,
        "processing": true,
        "serverSide": true,
        "ajax": "<?php echo $path; ?>ajax/server_processing.php"
    } );
} );
</script>

server_processing.php
<?php

/*
 * DataTables example server-side processing script.
 *
 * Please note that this script is intentionally extremely simply to show how
 * server-side processing can be implemented, and probably shouldn't be used as
 * the basis for a large complex system. It is suitable for simple use cases as
 * for learning.
 *
 * See http://datatables.net/usage/server-side for full details on the server-
 * side processing requirements of DataTables.
 *
 * @license MIT - http://datatables.net/license_mit
 */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Easy set variables
 */

// DB table to use
$table = 'data';

// Table's primary key
$primaryKey = 'id';

// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
    array( 'db' => 'scanning_timestamp', 'dt' => 0 ),
    array( 'db' => 'kPPCustomerFirstName',  'dt' => 1 ),
    array( 'db' => 'kPPCustomerFamilyName', 'dt' => 2),
    array( 'db' => 'kPPDateOfBirth',  'dt' => 3),
    array( 'db' => 'kPPHeightCm',   'dt' => 4 ),
    array( 'db' => 'kPPWeightKilograms',     'dt' => 5 ),
    array( 'db' => 'kPPCustomerMiddleName', 'dt' => 6 ),
    array( 'db' => 'kPPCustomerIdNumber',  'dt' => 7 ),
    array( 'db' => 'kPPOrganDonor',   'dt' => 8 ),
    array( 'db' => 'kPPWeightPounds',     'dt' => 9 ),
    array( 'db' => 'kPPAamvaVersionNumber', 'dt' => 10 ),
    array( 'db' => 'kPPHeight',  'dt' => 11 ),
    array( 'db' => 'kPPIssuerIdentificationNumber',   'dt' => 12 ),
    array( 'db' => 'kPPDocumentIssueDate',     'dt' => 13 ),
    array( 'db' => 'kPPAddressJurisdictionCode',  'dt' => 14 ),
    array( 'db' => 'kPPAddressStreet',   'dt' => 15 ),
    array( 'db' => 'kPPNonResident',     'dt' => 16 ),
    array( 'db' => 'kPPJurisdictionVehicleClass', 'dt' => 17 ),
    array( 'db' => 'kPPIssuingJurisdiction',  'dt' => 18 ),
    array( 'db' => 'kPPDocumentExpirationDate',   'dt' => 19 ),
    array( 'db' => 'kPPIssueTimestamp',     'dt' => 20 ),
    array( 'db' => 'kPPAddressCity', 'dt' => 21 ),
    array( 'db' => 'kPPHairColor',  'dt' => 22 ),
    array( 'db' => 'kPPHeightIn',   'dt' => 23 ),
    array( 'db' => 'kPPSex',     'dt' => 24 ),
    array( 'db' => 'kPPJurisdictionRestrictionCodes', 'dt' => 25 ),
    array( 'db' => 'kPPEyeColor',  'dt' => 26 ),
    array( 'db' => 'kPPJurisdictionVersionNumber',   'dt' => 27 ),
    array( 'db' => 'kPPCustomerFullName',     'dt' => 28 ),
    array( 'db' => 'kPPAddressPostalCode', 'dt' => 29 )
);

// SQL server connection information
$sql_details = array(
    'user' => 'root',
    'pass' => '',
    'db'   => 'bowen',
    'host' => 'localhost'
);

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */

require( 'ssp.class.php' );

echo json_encode(
    SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);

for ssp.class.php same as in https://datatables.net/examples/data_sources/server_side.html
*sorry if my english is not good


text:
Q: Next.js: Can't deploy production build; Works in dev; Am I using the async functions correctly? I am trying to create a production build for a next.js project. However I am getting the following error.
Error occurred prerendering page "/products". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: Cannot destructure property 'productList' of 'data' as it is undefined.
    at ProductTile (/Users/antonio-pavicevac-ortiz/Dropbox/developer_folder/jcrew-take-home-assignment/.next/server/chunks/619.js:39:5)
    at d (/Users/antonio-pavicevac-ortiz/Dropbox/developer_folder/jcrew-take-home-assignment/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:33:498)
    at bb (/Users/antonio-pavicevac-ortiz/Dropbox/developer_folder/jcrew-take-home-assignment/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:36:16)
    at a.b.render (/Users/antonio-pavicevac-ortiz/Dropbox/developer_folder/jcrew-take-home-assignment/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:42:43)
    at a.b.read (/Users/antonio-pavicevac-ortiz/Dropbox/developer_folder/jcrew-take-home-assignment/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:41:83)
    at exports.renderToString (/Users/antonio-pavicevac-ortiz/Dropbox/developer_folder/jcrew-take-home-assignment/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:52:138)
    at Object.renderPage (/Users/antonio-pavicevac-ortiz/Dropbox/developer_folder/jcrew-take-home-assignment/node_modules/next/dist/next-server/server/render.js:53:854)
    at Function.getInitialProps (/Users/antonio-pavicevac-ortiz/Dropbox/developer_folder/jcrew-take-home-assignment/.next/server/pages/_document.js:599:19)
    at loadGetInitialProps (/Users/antonio-pavicevac-ortiz/Dropbox/developer_folder/jcrew-take-home-assignment/node_modules/next/dist/next-server/lib/utils.js:5:101)
    at renderToHTML (/Users/antonio-pavicevac-ortiz/Dropbox/developer_folder/jcrew-take-home-assignment/node_modules/next/dist/next-server/server/render.js:53:1145)
errors FetchError: request to http://localhost:8000/category-server/ failed, reason: connect ECONNREFUSED 127.0.0.1:8000
    at ClientRequest.<anonymous> (/Users/antonio-pavicevac-ortiz/Dropbox/developer_folder/jcrew-take-home-assignment/node_modules/node-fetch/lib/index.js:1461:11)
    at ClientRequest.emit (node:events:327:20)
    at Socket.socketErrorListener (node:_http_client:478:9)
    at Socket.emit (node:events:327:20)
    at emitErrorNT (node:internal/streams/destroy:194:8)
    at emitErrorCloseNT (node:internal/streams/destroy:159:3)
    at processTicksAndRejections (node:internal/process/task_queues:80:21) {
  type: 'system',
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED'
}

I believe the crux of it is:
Error occurred prerendering page "/products". Read more: https://nextjs.org/docs/messages/prerender-error
But I can't figure it out—here are the asnyc files in questions:
[product].js
import React, { useEffect, useState } from 'react'
import Image from 'next/image'
import Link from 'next/link'

import Swatches from '../../components/Swatches.js'

function Product({ query }) {
  let { defaultColorCode, description, colors, product, price } = query;
  colors = JSON.parse(colors)

  let [productImage, setProductImage] = useState(`/${product}_${defaultColorCode}`);

  const handleProductChange = (productCode, defaultColorCode) => {
    setProductImage(`/${productCode}_${defaultColorCode}`)
  }

  const myLoader = ({ src }) => {
    return `https://www.jcrew.com/s7-img-facade/${src}`
  }

  return (

        <Image className="product-image" loader={myLoader}
          src={productImage} alt={description} layout="fill" />

{description}

          {
            price
          }

        <Swatches handleProductChange={handleProductChange} defaultColorCode={defaultColorCode} productImage={productImage} productCode={product} colors={colors} />

  )
}

export const getServerSideProps = ({ query }) => {
  return {
    props: {
      query
    }
  }
}

export default Product

The home page:
import Head from 'next/head'

import ProductPage from './products.js'

export const getStaticProps = async () => {
  try {
    const res = await fetch('http://localhost:8000/category-server/')
    const data = await res.json()

    return {
      props: {
        data: data
      },
    }
  } catch (error) {
    console.log('errors', error)
  }
}

export default function Home({ data }) {
  return (
    <>

        <title>Category Page </title>
        <meta charSet="utf-8" />
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />

      <ProductPage data={data} />
    </>
  )
}

Update:
I wound up updating the /server/category-server.js file:
const express = require('express')
const next = require('next')

const PORT = parseInt(process.env.PORT, 10) || 8000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  const server = express();

  server.get('https://jcrew-take-home-assignment.herokuapp.com/category-server', function (req, res) {
    res.json(require('./category'))
  })

  server.all('*', (req, res) => {
    return handle(req, res)
  })

  if (process.env.NODE_ENV === 'production') {
    server.use(express.static('.next/'));

        server.get('*', (req, res) => {
          res.sendFile(path.resolve(__dirname, '.next/', 'index.html'));
        });

        server.listen(PORT, err => {
          if (err) throw err;
          console.log(
            `> Ready and listening on PORT:${PORT} in the ${process.env.NODE_ENV} environment`
          );
        });
      } else {
        server.listen(PORT, err => {
          if (err) throw err;
          console.log(`> Ready and listening on http://localhost:${PORT}`);
        });
      }

My pages/index.js
    import Head from 'next/head'
    import absoluteUrl from 'next-absolute-url'
    import dynamic from 'next/dynamic'

    const ProductPage = dynamic(
      () => import('./products.js'),
      { ssr: false }
    )

    const fetchRelative = (req, path) => {
      const { origin } = absoluteUrl(req)
      return fetch(`${origin}${path}`);
    }

    export const getStaticProps = async ({ req, res }) => {
      if (typeof (window) !== 'undefined') {
        var res = await fetchRelative(req, '/category-server/')
        var data = await res.json()
      }
      return {
        props: {
          data: data || {}
        },
      }
    }

    export default function Home({ data }) {
      return (
        <>

            <title>Category Page </title>
            <meta charSet="utf-8" />
            <meta name="viewport" content="initial-scale=1.0, width=device-width" />

          <ProductPage data={data} />
        </>
      )
    }

And my ProductTile.js

import React from 'react'
import Image from 'next/image'
import Link from 'next/link'

const ProductTile = ({ data = {} }) => {
  let { productList } = data
  var [products] = productList || []
  var { products } = products || {};

  React.useEffect(() => {
    function remove_style(all) {
      var i = all.length;
      var j, is_hidden;

      // Presentational attributes.
      var attr = [
        'align',
        'background',
        'bgcolor',
        'border',
        'cellpadding',
        'cellspacing',
        'color',
        'face',
        'height',
        'hspace',
        'marginheight',
        'marginwidth',
        'noshade',
        'nowrap',
        'valign',
        'vspace',
        'width',
        'vlink',
        'alink',
        'text',
        'link',
        'frame',
        'frameborder',
        'clear',
        'scrolling',
        'style'
      ];

      var attr_len = attr.length;

      while (i--) {
        is_hidden = (all[i].style.display === 'none');

        j = attr_len;

        while (j--) {
          all[i].removeAttribute(attr[j]);
        }

        if (is_hidden) {
          all[i].style.display = 'none';
          is_hidden = false;
        }
      }
    }
    var all = window.document.getElementsByTagName('*');
    remove_style(all);
  }, [])

  const myLoader = ({ src }) => {
    return `https://www.jcrew.com/s7-img-facade/${src}`
  }

  const getColorSwatches = (products, index) => {
    if (products[index] != undefined) {
      return JSON.stringify(products[index].colors)
    }
  }

  return (

        {
          products != undefined && products.reduce((products, product) => products.find(x => x.productId === product.productId) ? products : [...products, product], []).map(({ colorCode, defaultColorCode, now, productId, productCode,
            productDescription, }, index) => {
            let path = `https://www.jcrew.com/s7-img-facade/${productCode}_${defaultColorCode}`
            let swatches = getColorSwatches(products, index)

            return (
              <Link key={`${productId}${index}`}
                href={{
                  pathname: '/s7-img-facade/[slug]',
                  query: {
                    defaultColorCode: defaultColorCode,
                    slug: productCode,
                    description: productDescription, image: path, price: now !== undefined
                      ? now.formatted
                      : 'Not-available',
                    colors: swatches

                  },
                }}
                passHref>

                  <Image className="product-image" loader={myLoader}
                    src={`/${productCode}_${defaultColorCode}`} alt={productDescription} layout="fill" />

{productDescription}

                    {
                      now !== undefined
                        ? now.formatted
                        : 'Not-available'
                    }

              </Link>
            )
          })}

  )
}

export default ProductTile


text:
Q: Simple linear equation question Sorry, school was like a long time ago for me, so this is really hard nowadays:
Lets say you have this loan/fee table:
Loan     Fee

$100 --> $15

$300 --> $25

$500 --> $35

The fee is made up of a base rate (e.g. 10 dollars) and a variable amount (e.g. 5 dollars per 100). Since there are two unknown variables, is there a way to solve this without using trial and error?
E.g. The answer that solves the above looks like this:
($10 + $5 per $100)

Also, not sure if this formula changes when the first hundred is excluded from the variable rate. E.g. Using same table as above:
Loan     Fee

$100 --> $10   **($10 + $0 per $100)**

$300 --> $20   ($10 + $5 per $100)

$500 --> $30   ($10 + $10 per $100)

I think this can be solved with linear equation but not sure how to write or solve it.

A: You can set up a system of equations using the given information and solve it to get the base rate and the variable rate:
$b=$ base
$x=$ variable rate
$$
  \begin{align}
     b+100x &=15 \\
     b+300x &=25     \\
     b+500x &=35
  \end{align}
$$
$
\left(
\begin{array}{cc|c}
  1 & 100 & 15 \\
  1 & 300 & 25 \\
  1 & 500 & 35 \\
\end{array}
\right)
$
$
\begin{matrix}
\\
R_2-R_1\\
R_3-R_1\\
\end{matrix}
$
$
\left(
\begin{array}{cc|c}
  1 & 100 & 15 \\
  0 & 200 & 10 \\
  0 & 400 & 20 \\
\end{array}
\right)
$
$
\begin{matrix}
2R_1-R_2\\
\\
R_3-2R_2\\
\end{matrix}
$
$
\left(
\begin{array}{cc|c}
  2 & 0 & 20 \\
  0 & 200 & 10 \\
  0 & 0 & 0 \\
\end{array}
\right)
$
$
\begin{matrix}
R_1\div2\\
\\
R_2\div200\\
\end{matrix}
$
$
\left(
\begin{array}{cc|c}
  1 & 0 & 10 \\
  0 & 1 & \frac 1{20} \\
  0 & 0 & 0 \\
\end{array}
\right)
$
$
\begin{matrix}
b=10\\
x=\frac1{20}\\
\\
\end{matrix}
$
So you get a solution to this system of equations with the base being $10$ and the variable rate is equal to $\frac 1{20}$ (i.e 5 for everyone 100). You really only needed two of the equations to solve for the variables, but the fact that there is a zero row in the bottom just confirms that all three equations are consistent.


text:
Q: How to Implement SIR Model in JAVA and Visualize it in Repast Simphony? I've been given a Project to Code a SIR Model (Agent Based Modeling) from Scratch in JAVA and then Visualize the same through Repast Simphony using different Values of Beta and Gamma. I have setup Java, Eclipse and Repast Simphony but I don't know where and how to begin Coding the same.
Any help is Appreciated. Thank You!

A: One approach would be to look at this paper and the associated project code. This uses the statecharts capability in Repast Simphony to build an SEIR model.


text:
Q: What is the best tool to query the text files(in compressed format) in HDFS? I have imported the log files in compressed format from Database into HDFS. I am querying data using Hive CLI tool.
Could you please share other tools better than Hive for querying the data files?
Note: I am aware of Spark framework which I can use to query. But, I was wondering if there's any other option which is faster or/and offer SQL like syntax.
Thanks in advance.

A: Impala, Drill, PrestoDB and Amazon Redshift all accept SQL syntax and offer better performance.
For more info, see:

*

*https://impala.apache.org/

*https://drill.apache.org/

*https://prestodb.io/

*(AWS only) https://aws.amazon.com/redshift/


text:
Q: Can Mathematica solve this type of recurrence? I have the following recursively defined equation:
 a[n_] := a[n] =  1 - Sum[Binomial[n, k] 2^(n - k - 1) a[k], {k, 0, n - 2}] -  2 n*a[n - 1]
 a[0] := a[0] = 1
 a[1] := a[1] = -1
 a[2] := a[2] = 3

I want to solve this particular recurrence equation using RSolve, but I'm not sure that Mathematica can handle recurrences of this type, based upon the particular outputs I'm getting.  Is there a way solve this type of recurrence using Mathematica?
I am looking for a closed form solution rather than computing a numerically.

A: One can certainly compute a[n] for arbitrary positive integer $n$.
a[n_] := 1 - Sum[Binomial[n, k] 2^(n - k - 1) a[k], {k, 0, n - 2}] - 2 n a[n - 1];
a[0] := 1;
a[1] := -1;
a[2] := 3;

a[15]

(*
$-694475294514315$
*)
 ListLogPlot[Table[a[i], {i, 1, 20}]]

Just note that many values of a[i] are negative and won't show up on the ListLogPlot.
However, attempts with FindSequenceFunction[] and FindGeneratingFunction[], even with appropriate FunctionSpace restrictions failed:
FindSequenceFunction[Table[{n, a[n]}, {n, 0, 20}],
FunctionSpace -> {"ConstantRecursive", "Hypergeometric"}]

I think the difficulty lies in the parametric nature of the sum's limits.


text:
Q: "Rejected" line of code in merge conflict. Now I can't get it to show up again in merge I'm new to the development world and it's my first question here I'm thankful for constructive input regarding my problem and also my question build-up. Let's get to the point.
I have Branch A and Branch B. Branch A is my feature branch which I'm working on. Branch B is only allowed to be merged into. No work is to be done on it.
I worked on Branch A and merged into Branch B. Some conflicts came up and I solved them. While solving it seems that I have rejected 2 lines of code from my Branch A. I deployed Branch B and realized that the lines are missing. So I went back and merged Branch A again into Branch B in the hopes to be able to get the missing lines in there. But it didn't work.
Is there a way to get those 2 lines into Branch B without working on it?
I looked for answers but I only find questions and answers regarding the merge conflict itself.
Thank you for reading this far =)

A:
So I went back and merged Branch A again into Branch B in the hopes to be able to get the missing lines in there. But it didn't work.

Git considers all (relevant) changes from the source branch at the time the merged was done to be included in the destination branch after merge is done. That includes the two missing lines, which the merge commit now implicit records as not wanted. Later merges of the source branch will not re-consider content from before the last commit.
What you can do however is to create a new (temporary) branch from the commit on the destination branch right before the merge was done. Then you can merge into that branch. That should then result in a merge that includes those two missing lines (and possibly more). The result from that operation can then be brought in to the destination branch.

So a concrete example. Hard boiled eggs recipe, the main branch adds text content, the formatting branch changes markdown formatting and adds an image link. The main branch is merged into the formatting which trigger a merge conflict, and in resolving those I deliberately chose to "lose" two lines with tips on how to avoid eggs cracking.
Gitk screenshot:
After this first merge, subsequent merges of main into formatting will not bring in those two lost lines because as far as git is concerned, all changes on the main branch are incorporated.
So to bring those "lost" changes back in I would do the following:
Step 1
Create a new branch from the commit from before the merge commit on formatting,
$ git branch merge_fix merge-commit^
$ git checkout merge_fix
$

Step 2
(This step is strictly speaking optional, but it will reduce the amount of conflicts that can arise). Bring in the changes done in the merge commit without recording it as a merge commit.
# Make the worktree identical to the content of commit tagged "merge-commit".
$ git diff HEAD merge-commit | git apply -
$ git add eggs.md                                # The only file changed.
$ git commit -m "Content from merge-commit"
$

Step 3
Merge main into merge_fix. This will still result in the same conflicts for the two lines as when the original merge that was done (although less conflicts overall with step 2 done).
This time I resolve the lines correctly to have them included (and changed to markdown list entries).
$ git merge main
$ git resolve-conflict-using-kdiff3    # https://github.com/hlovdal/git-resolve-conflict-using-kdiff3
$ git diff --cached | sed 1,4d
@@ -7,6 +7,8 @@

 ## Instructions

+* Pinch a hole in the top of the eggs to avoid that it cracks during boiling.
+* If the eggs have room temperature when starting, there is less chance of cracking.
 * Put enough water in the pot to completely cover the eggs.
 * Put on heat and wait for the water to start boiling.
 * Put in the eggs.
$ git commit
$

Now the latest commit on merge_fix branch contains all the missing changes we want to bring back.
Step 4, alternative 1
Conceptually, the simplest thing to do is perhaps then to just merge it into formatting,
$ git checkout formatting
$ git merge merge_fix
$ git resolve-conflict-using-kdiff3    # https://github.com/hlovdal/git-resolve-conflict-using-kdiff3
$ git commit
$ git b -d merge_fix

however you still get merge conflicts on this and the history from this becomes rather messy:

Step 4, alternative 2
So a better way that creates cleaner history is the following:
$ git branch formatting_fix merge-commit
$ git checkout formatting_fix
$ git diff HEAD merge_fix | git apply -
$ git add eggs.md                            # The only file changed.
$ git commit -m "Merge in missing changed from main branch"
# Chose one of the following rebases depending on your preference
$ git rebase formatting_fix formatting       # I chose this one.
$ git rebase formatting formatting_fix
$ git checkout formatting
$ git branch -d formatting_fix
$

So with this you get one clean commit with the missing lines added. Strictly speaking it is a merge commit and should have a second parent added (this should be possible so you can look into that if you want to).
Step 5, optional
However with the state from step 4.2 it is quite easy to actually fix the original merge commit to not have the lines missing in the first place. To do that run an interactive rebase where you select fixup for the commit created in step 4.2 and amend the merge commit:
$ git rebase --interactive --rebase-merges merge-commit^
# Change pick to fixup for the commit from step 4.2 (and move the line if you
# chose "git rebase formatting formatting_fix"). See text example below.
$

label onto

# Branch main
reset 17502fa # Initial text
pick 73bc309 Add tips
pick 730edf1 Add Ingredients and Instructions sections
label main

reset onto
merge -C 78b538e main # Merge branch 'main' into formatting
fixup 3bb3385 Merge in missing changed from main branch
pick 1f1e9b7 Add image link

This gives the following history.

At this point there is no need to keep the merge-commit tag and merge_fix branch, so those can be deleted.


text:
Q: win32com.client.Dispatch Class Label I am trying to connect to a COM object using python.
More specifically, I am using ASCOM standard drivers to connect to a MaxDome II, and do not know how to reference this driver.
In this link the author uses "Celestron.Telescope" as their parameter for the win32com.client.Dispatch instantiation.
My question is how to find this string. I understand that it is related to the installed drivers, which are installed on the computer, but I don't how to locate the specific string. Is there a way to use win32com.client to list COM objects?
By the way, operating on Windows 7 pro, 64 bit.
Thanks

A: I do not think it is possible to get the list of COM objects directly from python, however you can run the following code (and indeed run it from inside python) in Powershell:
Get-ChildItem HKLM:\Software\Classes -ErrorAction SilentlyContinue | Where-Object {
   $_.PSChildName -match '^\w+\.\w+$' -and (Test-Path -Path "$($_.PSPath)\CLSID")
} | Select-Object -ExpandProperty PSChildName

This will output a list of all valid names of COM objects on your system sorted alphabetically, and the syntax is normally MainProgram.SubFunction.
Some of the output on my machine:

I hope this helps!

A: This "Celestron.Telescope" string is called a ProgID (you can google on this term quite easily).
They arere located under the HKEY_LOCAL_MACHINE\SOFTWARE\Classes registry key for the whole machine and  in HKEY_CLASSES_ROOT for the current running user.
When COM creates an instance of a component, it will use the current user's view of the registry. Most keys are in HKLM but there can be some local overrides in HKCR.


text:
Q: How to add count total column to dataframe in R I have aggregated a dataframe by the number of times we observe a single word appears in a dataset for meetings on a particular date so it looks like this:
date <- c("2012-05-06", "2013-07-09", "2007-01-03")
word_count <- c("17", "2", "390")
df1 <- data.frame(date, word_count)

I also have a separate dataframe with total word counts for every date and then a series of other dates as well. It looks like this:
date <- c("2012-05-06", "2013-07-09", "2007-01-03", "2004-11-03", "1994-12-03")
word_total <- c("17000", "20", "39037", "39558", "58607")
df2 <- data.frame(date, word_count)

I now want to add another column to df1 that incorporates the totals for the dates that are in df2 but excludes data for any dates that are not in df1. I also want to transform the dataframe so that there is another column dividing word_total by word_count.
So the output would look like this:
date <- c("2012-05-06", "2013-07-09", "2007-01-03")
word_count <- c("17", "2", "390")
word_total <- c("17000", "20", "39037")
word_percentage <- c("0.001", "0.1", "0.00999")
df2 <- data.frame(date, word_count, word_total, word_percentage)`

I know how to use transform to get word_percentage once I have word_total loaded in but I have no idea how to add in relevant column data from word_total. I have tried using merge and intersect to no avail. Any ideas?
Thank you in advance for your help!

A: If the columns are numeric, then just do a merge and then create the column by dividing
transform(merge(df1, df2, by = c('date')),
        word_percentage = round(word_count/word_total, 3))

Or use match
df1$word_percentage <- df1$word_count/df2$word_total[match(df1$date, df2$date)]

data
df1$word_count <- as.integer(as.character(df1$word_count))
df2$word_total <- as.integer(as.character(df2$word_total))


text:
Q: Enumerating the align environment Consider the following MWE:
\documentclass{article}
\usepackage{amsmath}

\begin{document}

\setcounter{equation}{42}

\begin{align}
                 a & = b + c              \label{label1} \\
    \alpha_{i,j,k} & = \theta^2 + \phi^2  \label{label2} \\
      M_\text{res} & = a + \alpha_{i,j,k} \label{label3}
\end{align}

\end{document}

How can I enumerate the three equations? Wrapping the align environment in an enumerate environment and starting each equation line with \item won't work.
The equations should be enumerated like normal, and will thus depend on what comes before the align environment in question. I've arbitrarily set the equation counter to 42 to represent the content before the align. I also need to reference the equation labels as normal.

A: Use alignat and a \step macro:
\documentclass{article}
\usepackage{amsmath}

\newcounter{step}
\newcommand{\step}{\stepcounter{step}\thestep.\quad}

\begin{document}

\setcounter{equation}{42}

\setcounter{step}{0} % do this when you want to reset the numbering
\begin{alignat}{2}
\step&&              a & = b + c              \label{label1} \\
\step&& \alpha_{i,j,k} & = \theta^2 + \phi^2  \label{label2} \\
\step&&   M_\text{res} & = a + \alpha_{i,j,k} \label{label3}
\end{alignat}

\end{document}

A: A solution that uses the flalign environment:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\newcounter{algostep}
\newcommand\step{\stepcounter{algostep}\hskip\parindent\thealgostep.}
\usepackage{etoolbox}
\BeforeBeginEnvironment{flalign}{\setcounter{algostep}{0}}

\begin{document}
\setcounter{equation}{42}
Text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text.
    \begin{flalign}
&\step & a & = b + c \label{label1} & \\
&\step & q & = e + f \label{label2} \\
&\step & z & = a + d \label{label3}
\end{flalign}
Text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text.
\begin{flalign}
&\step & z & = a + d \label{label3} & \\
&\step & q & = e + f \label{label2} \\
&\step & a & = b + c \label{label1}
\end{flalign}

\end{document}


text:
Q: scanf field width string overflow Which one of the following is safe regarding buffer overflow?
char buf[10] = {0};
scanf("%10s", buf);

or
char buf[10] = {0};
scanf("%9s", buf);

From what I've read I'm going for the second (sizeof minus one), but the matter is quite subtle and I've seen code suggesting either. Any volunteer to quote the standard?

A: char buf[10] = {0};
scanf("%10s", buf);

is unsafe. You have to take into account the string null terminator.
char buf[10] = {0};
scanf("%9s", buf);

is safe.

A: The C standard states that:

An input item shall be defined as the longest sequence of input bytes (up to any specified maximum field width, which may be measured in characters or bytes dependent on the conversion specifier) which is an initial subsequence of a matching sequence.

That is, the maximum field width represents how many characters there can be in the input. The extra zero value at the end is not part of the input and needs an additional space.
The GNU libc manual makes this point explicit:

String input conversions store a null character to mark the end of the input; the maximum field width does not include this terminator.

So, the only safe version is scanf("%9s", buf).


text:
Q: How does PHP handle an array with a reference to itself as an element? Lets say I declare an array:
$data = array( 'foo' => 'bar' );

Now I'll add a reference to itself as a new element:
$data['baz'] = &$data;

Dumping the contents of $data will result in:
Array
(
[foo] => bar
[baz] => Array
    (
        [foo] => bar
        [baz] => Array
         *RECURSION*
    )

)

Now, I can dump the contents of $data['baz']['baz']['baz']['baz']['baz']['baz']['baz']['baz']['baz'] and the result will be exactly the same as the above because the array has a pointer to itself as an element.
What I'd like to know is if php handles the array as one single set of data with a pointer that is exactly the same pointer that I'd call upon when using $data or if it does something completely different.
Also, can PHP run out of memory trying while returning the contents of $data{['baz']*n}?

A: Internally in PHP everything is stored inside a variant container called a ZVAL. $data is represented by a ZVAL, each key and each value inside $data is a ZVAL, etc.
So after the initial assignment, from PHP has created three ZVALs:
   /-------------------\      /-------------------\
   | ZVAL #1           |  /==>| ZVAL #2           |
   |   type: array     |  |   |   type: string    |
   |   data: [         |  |   |   data: "foo"     |
   |      {            |  |   \-------------------/
   |          key: =======/                         /-------------------\
   |          val: ================================>| ZVAL #3           |
   |      }            |                            |   type: string    |
   |   ]               |                            |   data:  "bar"    |
   \-------------------/                            \-------------------/

Note: the internal representation of an array items does not correspond to what is shown above; I did not want to burden the answer with unnecessary detail. The representation of a ZVAL is also shown simplified for the same reason. If you want to learn more about PHP internals, please read the source and/or this.
You can see that the fact that "foo" and "bar" are being used as an array key/value pair is not possible to determine by looking at their ZVALs: you have to know that they are being referred to by the array.
After the assignment $data['baz'] = &$data, what happens is you now have a circular reference: somewhere inside ZVAL #1 there is a pointer back to ZVAL #1:
   /-------------------\      /-------------------\
   | ZVAL #1           |  /==>| ZVAL #2           |
/=>|   type: array     |  |   |   type: string    |
|  |   data: [         |  |   |   data: "foo"     |
|  |      {            |  |   \-------------------/
|  |          key: =======/                         /-------------------\
|  |          val: ================================>| ZVAL #3           |
|  |      },           |                            |   type: string    |
|  |      {            |                            |   data: "bar"     |
|  |          key: =========================\       \-------------------/
|  |          val: =========\               |
|  |      }            |    |               |       /-------------------\
|  |   ]               |    |               \======>| ZVAL #4           |
|  \-------------------/    |                       |   type: string    |
|                           |                       |   data: "baz"     |
\===========================/                       \-------------------/

So how does PHP resolve $data['baz']['baz']? It knows that $data is represented by ZVAL#1, and it sees that you are trying to index into it with array syntax. It looks at the ZVAL, sees that it's an array, finds the item having the key "baz" and gets the ZVAL that represents it. What do you know? That's ZVAL#1 once more. This concludes the resolution of $data['baz'].
At the next step, it sees that you are trying to index into $data['baz'] as an array. It knows that $data['baz'] is represented by ZVAL#1 so the same thing ends up happening again, and so on.
You will have noted that the process above does not involve storing any intermediate results (the first and second step are totally independent), which means that there is no resource limit to be hit by the PHP virtual machine when trying to resolve the array access.