text:
Q: Create singleton instance via extension per app? In the Apple documentation, it says that some instances need to be create once per app like HKHealthStore:

You need only a single HealthKit store per app. These are long-lived objects. Create the store once, and keep a reference for later use.

Is doing something convenient like below safe or is there a better way?
public extension HKHealthStore {

    class var sharedInstance: HKHealthStore? {
        if !HKHealthStore.isHealthDataAvailable() {
            return nil
        }

        struct Singleton {
            static let instance = HKHealthStore()
        }

        return Singleton.instance
    }

}

That way I can do this without polluting with custom managers:
HKHealthStore.shareInstance?.requestAuthorizationToShareTypes
Is this ok or is there a better architectural approach?

A: I would do it in this way:
class MyHealthStore:HKHealthStore {
    static let sharedInstance = MyHealthStore()
}

Now you can use MyHealthStore.sharedInstance and it will always return the same store.
You can also achieve the same without any subclassing:
class MyCustomClass:NSObject {
    static let sharedInstance = MyCustomClass()
    let healthStore = HKHealthStore()
}

And now you can use MyCustomClass.sharedInstance.healthStore


text:
Q: How do I solve the error "expected ')' before '->' token" in my code? First the code,
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>

void printAttributes(de->d_name, &statBuff);

int main(){

    struct stat{
    } statBuff;

    int err;

    struct dirent *de;

    DIR *dr = opendir(".");

    if (dr == NULL) {
        printf("Could not open current directory");
        return 0;
    }

    while ((de = readdir(dr)) != NULL){
        err = stat(de->d_name, &statBuff);
        printf("%s\n", de->d_name);

        if(err == -1){
            printf("Error in Stat\n");
            printf("Press 'Enter' to continue\n");
            getChar();
            return 1;
        }

        printAttributes(de->d_name, &statBuff);
    }
    closedir(dr);
    return 0;
}

void printAttributes(de->d_name, &statBuff){
//function bs here
}

The compiler is saying the error is occurring on both lines 8 and 43 which obviously lead me to believe something is wrong with the function prototype/call but i cannot figure out what it is. Any help would be appreciated.

A: As mentioned in a comment, you've misunderstood the difference between a function definition, declaration and call
Take a look at this: https://www.tutorialspoint.com/cprogramming/c_functions.htm
Also, as a general tip for both debugging stuff you don't understand and asking for help:
Try to make the example as short and simple as possible.
I usually find that in the process of simplifying, I find the error I'm looking for.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Any way to ensure I get the return value from a sequence of async functions I'm working with repos and trying to get the pull requests, issues and commits for a repo. I have the following code:
const axios = require('axios');
var gitPullApiLink = "https://api.github.com/repos/alirezadir/Production-Level-Deep-Learning/pulls"
var listOfCommits = [];
var listOfSHAs = [];
var mapOfInfoObjects = new Map();
var mapPullRequestNumberToCommits = new Map();
var mapPRNumbersToCommitObjects = new Map();
var listOfPrObjects = [];
var setOfFileObjects = new Set();
var listOfNumbersOfTargetedIssues = [];
 var mapPRnumberToCloseOpenDateObjects = new Map();

class PullRequestParser {

async getListOfPullRequests(pullrequestLink) {
    const message = await axios.get(pullrequestLink);
    //console.log(message);
    listOfPrObjects = message['data'];
}

async getCommitsForEachPullRequestAndPRinformation() {
    var listOfPrNumbers = [];
    var k;
    // this loop will just make a list of Pull Request Numbers
    for (k = 0; k < listOfPrObjects.length; k++){
        var currPrNumber = listOfPrObjects[k]['number'];
        listOfPrNumbers.push(currPrNumber);
    }
    // I created a separate list just because... I did it this way because on the github API website it seems
    // like the pull request has the same number as the issue it affects. I explain how you can see this down below
    listOfNumbersOfTargetedIssues = listOfPrNumbers;
    // next loop will make objects that contain information about each pull request.
    var n;
    for (n = 0; n < listOfPrNumbers; n++){
        var ApiLinkForEachPullRequest = gitPullApiLink + "/" + listOfPrNumbers[n];
        const mes = await axios.get(ApiLinkForEachPullRequest);
        var temp = {OpeningDate: mes['data']['created_at'],
            ClosingDate: mes['data']['closed_at'],
            IssueLink: mes['data']['_links']['issue']['href']};
        //mapPRnumberToCloseOpenDateObjects will be a map where the key is the pull request number and the value
        // is the object that stores the open date, close date, and issue link for that pull request. The reason
        // why I said I think the pull request number is the same as the number of the issue it affects is because
        // if you take any object from the map, say you do mapPRnumberToCloseOpenDateObjects.get(10). You'll
        // get an object with a pull request number 10. Now if you take this object and look at it's "IssueLink"
        // field, the very last part of the link will have the number 10, and if you look at the github API
        // it says for a single issue, you do: /repos/:owner/:repo/issues/:issue_number <---- As you can see,
        // the IssueLink field will have this structure and in place of the issue_number, the field will be 10
        // for our example object.
        mapPRnumberToCloseOpenDateObjects.set(listOfPrNumbers[n], temp);
    }
    //up to this point, we have the pull request numbers. we will now start getting the commits associated with
    //each pull request
    var j;
    for (j = 0; j < listOfPrNumbers.length; j++){
        var currentApiLink = gitPullApiLink + "/" + listOfPrNumbers[j] + "/commits";
        const res = await axios.get(currentApiLink);
        //here we map a single pull request to the information containing the commits. I'll just warn you in
        // advance: there's another object called mapPRNumbersToCommitObjects. THIS MAP IS DIFFERENT! I know it's
        // subtle, but I hope the language can make the distinction: mapPullRequestNumberToCommits will just
        // map a pull request number to some data about the commits it's linked to. In contrast,
        // mapPRNumbersToCommitObjects will be the map that actually maps pull request numbers to objects
        // containing information about the commits a pull request is associated with!
        mapPullRequestNumberToCommits.set(listOfPrNumbers[j], res['data']);
    }
    // console.log("hewoihoiewa");
}

async createCommitObjects(){
    var x;
    // the initial loop using x will loop over all pull requests and get the associated commits
    for (x = 0; x < listOfPrObjects.length; x++){
        //here we will get the commits
        var currCommitObjects = mapPullRequestNumberToCommits.get(listOfPrObjects[x]['number']);
        //console.log('dhsiu');
        // the loop using y will iterate over all commits that we get from a single pull request
        var y;
        for (y = 0; y < currCommitObjects.length; y++){

            var currentSHA = currCommitObjects[y]['sha'];
            listOfSHAs.push(currentSHA);
            var currApiLink = "https://api.github.com/repos/alirezadir/Production-Level-Deep-Learning/commits/" + currentSHA;
            const response = await axios.get(currApiLink);
            //console.log("up to here");
            // here we start extracting some information from a single commit
            var currentAuthorName = response['data']['commit']['committer']['name'];
            var currentDate = response['data']['commit']['committer']['date'];
            var currentFiles = response['data']['files'];
            // this loop will iterate over all changed files for a single commit. Remember, every commit has a list
            // of changed files, so this loop will iterate over all those files, get the necessary information
            // from those files.
            var z;
            // we create this temporary list of file objects because for every file, we want to make an object
            // that will store the necessary information for that one file. after we store all the objects for
            // each file, we will add this list of file objects as a field for our bigger commit object (see down below)
            var tempListOfFileObjects = [];
            for (z = 0; z < currentFiles.length; z++){
                var fileInConsideration = currentFiles[z];
                var nameOfFile = fileInConsideration['filename'];
                var numberOfAdditions = fileInConsideration['additions'];
                var numberOfDeletions = fileInConsideration['deletions'];
                var totalNumberOfChangesToFile = fileInConsideration['changes'];
                //console.log("with file");
                var tempFileObject = {fileName: nameOfFile, totalAdditions: numberOfAdditions,
                    totalDeletions: numberOfDeletions, numberOfChanges: totalNumberOfChangesToFile};
                // we add the same file objects to both a temporary, local list and a global set. Don't be tripped
                // up by this; they're doing the same thing!
                setOfFileObjects.add(tempFileObject);
                tempListOfFileObjects.push(tempFileObject);
            }
            // here we make an object that stores information for a single commit. sha, authorName, date are single
            // values, but files will be a list of file objects and these file objects will store further information
            // for each file.
            var tempObj = {sha: currentSHA, authorName: currentAuthorName, date: currentDate, files: tempListOfFileObjects};
            var currPrNumber = listOfPrObjects[x]['number'];

            console.log(currPrNumber);
            // here we will make a single pull request number to an object that will contain all the information for
            // every single commit associated with that pull request. So for every pull request, it will map to a list
            // of objects where each object stores information about a commit associated with the pull request.
            mapPRNumbersToCommitObjects.set(currPrNumber, tempObj);
        }
    }
    return mapPRNumbersToCommitObjects;
}

startParsingPullRequests() {
    this.getListOfPullRequests(gitPullApiLink  + "?state=all").then(() => {
        this.getCommitsForEachPullRequestAndPRinformation().then(() => {
            this.createCommitObjects().then((response) => {
                console.log("functions were successful");
                return mapPRNumbersToCommitObjects;
            }).catch((error) => {
                console.log("printing first error");
                console.log(error);
            })
        }).catch((error2) => {
            console.log("printing the second error");
            console.log(error2);
        })
    }).catch((error3) => {
        console.log("printing the third error");
        console.log(error3);
    });
}

//adding some getter methods so they can be used to work with whatever information people may need.
//I start all of them with the this.startParsingPullRequests() method because by calling that method it gets all
// the information for the global variables.

async getSetOfFileObjects(){
    var dummyMap = this.startParsingPullRequests();
    return setOfFileObjects;
}

async OpenCloseDateObjects(){
    var dummyMap = this.startParsingPullRequests();
    return mapPRnumberToCloseOpenDateObjects;
}

async getNumbersOfTargetedIssues(){
    var dummyMap = this.startParsingPullRequests();
    return listOfNumbersOfTargetedIssues;
}

}

I'm trying to make a "dummy map" that gets the return value of calling startParsingPullRequests() in the following way:
var dummy = new PullRequestParser();
var dummyMap = dummy.startParsingPullRequests();
console.log(dummyMap);

But I end up with the following output:
undefined
3
1
functions were successful

I understand dummyMap is undefined because startParsingPullRequests() makes a series of async calls, but I'm wondering how do I go about making sure dummyMap gets its value and then prints. Thanks!

A: Since you already have code using async/await, why are you changing to .then? When you are using .then/.catch, it can be a lot harder to tell where things are waiting and what they are waiting on.
Here is your function converted to use async/await. With this change, you can await this function (though in that case, you might want to not catch the error and let the caller handle it, otherwise you need to check the return for undefined to "detect" the error). I've also simplified the error handling (but again, unless the code here can "fix" the problem, no reason to handle it here)

async startParsingPullRequests() {
  try {
    await this.getListOfPullRequests(gitPullApiLink + "?state=all");
    await this.getCommitsForEachPullRequestAndPRinformation();
    const response = await this.createCommitObjects();
    console.log("functions were successful");
    return mapPRNumbersToCommitObjects;
  } catch (error) {
    console.log("printing error");
    console.log(error);
  }
}


text:
Q: Trying to combine multiple datasets into one bar graph in R I'm trying to create a bar graph that has the same variables on the x-axis except separated by year. I want to show an increase/decrease over time but I'm not sure how to insert each dataset into the graph and have the years labelled.  Each dataset is election results from a specific year.
Here's one dataset for example:

1992Election
   Political  Party           18-29,30-44,45-59,60+  (the numbered headings are age groups)
  Democrat      0.40,0.37,0.40, 0.47  (voting percentages)
  Republican  0.35,0.41,0.42, 0.47

For the first dataset I have the following code to create one bar graph:
1992Election
colnames(`1992Election`)[colnames(`1992Election`)=="X.18.29."] <- "18-29"
colnames(`1992Election`)[colnames(`1992Election`)=="X.30.44."] <- "30-44"
colnames(`1992Election`)[colnames(`1992Election`)=="X.45.59."] <- "45-59"
colnames(`1992Election`)[colnames(`1992Election`)=="X.60.."] <- "60+"

Party92 = rownames(`1992Election`)
n.group92 = nrow(`1992Election`)

color.names92 = c("royalblue2", "red2")

barplot(as.matrix(`1992Election`),beside = TRUE, xlab = "Age Group",
        ylab = "Percent Voted", ylim = c(0,.7), col = color.names92)
title(main = "Presidential Election Votes by Age in Ohio\n Year 1992")
legend("topright", title = "Political Party", Party92, fill = color.names92,
  cex = 0.4)

this results in this graph: 1992Electiongraph
I would like to have the same variables along the x axis but grouped together by year
For ex: X- axis [the age groups (1992), [same age groups (1996), etc] if that makes sense, thanks.

A: Depending on what your data looks like and how it is structured, here's a simple solution using R base graphics:
Let's assume your data is roughly structured like this df, with one column for the years in which elections were held, and one column each for the results of the two parties:
y <- c(10, 14, 18, 22, 26)
df <- data.frame(
  Year = c(paste("20",y, sep = "")),
  Rep = c(rnorm(5, 10)),
  Dem = c(rnorm(5, 15))
)

then you could save the election results in one vector, transposing them using tand cbinding them:
election.results <- t(cbind(df$Rep, df$Dem))

Now you could graph election.results in a barplot, using the besideargument and df$Yearfor the names in names.arg plus using legend to provide the key:
barplot(election.results, beside=T, names.arg = df$Year, col=c("red","blue"))
par(xpd=T) # this will probably not be necessary with the real data
legend(19, c("Republicans", "Democrats"), horiz = T, col=c("red","blue"), fill=c("red","blue"))

A: If the 2 datasets are similar, the simplest approach would be to bind your 2 datasets together. With rbind you get age groups together.
barplot(as.matrix(rbind(El92, El96)), beside=TRUE)

Or with cbind you get 8 groups of 2 bars, and if you want to change the order you can specify that:
barplot(as.matrix(cbind(El92, El96)[c(1,5,2,6,3,7,4,8)]), beside=TRUE)


text:
Q: How to get rid of the selection box around my selection I'm trying to create a website for myself and just ran into this issue:

As you can see there is some kind of selection visible in both images which I don't want to be displayed.
The first image is taken after I clicked the menu item.
The second image is taken after the first when I additionally move the mouse over it.
These menu items are shown in a table.
I am using FireFox 3.6.10.
Does anybody have an idea how to get rid of these selections?

A: Check out the outline CSS property. You should specify outline: none for your links in this case. The outline indicates that the given element has focus. You should provide something instead to make keyboard-only navigation possible.

A: If you remove focus from the link when the user clicks it, you will effectively get rid of that box. However, many people advise against this because it is considered bad practice and isn't very accessible.
Anyways, if you want to do it and don't mind JQuery, you can use this:
$('a').click(function () { $(this).blur() });

As "elusive" pointed out, you can also use the CSS outline property to prevent it, but that doesn't work on all browsers. (Read: IE7 and older.)


text:
Q: nan shows up on my boxplot but there is no column labeled nan? I started with:
print(NAsales_boxplotdf)

and I got the following output:
              Genre  NA_Sales
0            Sports     41.49
1          Platform     29.08
2            Racing     15.85
3            Sports     15.75
4      Role-Playing     11.27
...             ...       ...
16594       Shooter      0.01
16595        Racing      0.00
16596        Puzzle      0.00
16597      Platform      0.01
16598           NaN       NaN

[16599 rows x 2 columns]

I then pivoted the the dataframe as follows:
NAsales_boxplotpivot = NAsales_boxplotdf.pivot(values = 'NA_Sales', columns = 'Genre')

to get:
Genre  NaN  Action  Adventure  Fighting  Misc  Platform  Puzzle  Racing  \
0      NaN     NaN        NaN       NaN   NaN       NaN     NaN     NaN
1      NaN     NaN        NaN       NaN   NaN     29.08     NaN     NaN
2      NaN     NaN        NaN       NaN   NaN       NaN     NaN   15.85
3      NaN     NaN        NaN       NaN   NaN       NaN     NaN     NaN
4      NaN     NaN        NaN       NaN   NaN       NaN     NaN     NaN
...    ...     ...        ...       ...   ...       ...     ...     ...
16594  NaN     NaN        NaN       NaN   NaN       NaN     NaN     NaN
16595  NaN     NaN        NaN       NaN   NaN       NaN     NaN    0.00
16596  NaN     NaN        NaN       NaN   NaN       NaN     0.0     NaN
16597  NaN     NaN        NaN       NaN   NaN      0.01     NaN     NaN
16598  NaN     NaN        NaN       NaN   NaN       NaN     NaN     NaN

Genre  Role-Playing  Shooter  Simulation  Sports  Strategy
0               NaN      NaN         NaN   41.49       NaN
1               NaN      NaN         NaN     NaN       NaN
2               NaN      NaN         NaN     NaN       NaN
3               NaN      NaN         NaN   15.75       NaN
4             11.27      NaN         NaN     NaN       NaN
...             ...      ...         ...     ...       ...
16594           NaN     0.01         NaN     NaN       NaN
16595           NaN      NaN         NaN     NaN       NaN
16596           NaN      NaN         NaN     NaN       NaN
16597           NaN      NaN         NaN     NaN       NaN
16598           NaN      NaN         NaN     NaN       NaN

[16599 rows x 13 columns]

I dropped the NaN column using:
NAsales_boxplotpivot[NAsales_boxplotpivot.columns.dropna()]

to get this and then I put put it in a boxplot using:
NAsales_boxplotpivot.plot(kind='box', rot = 90, figsize = (20,10), showfliers = False)

to get this.

A: In the image you posted, you displayed
NAsales_boxplotpivot[NAsales_boxplotpivot.columns.dropna()]

using Jupyter notebook, but you did not store the result in NAsales_boxplotpivot. However, you used NAsales_boxplotpivot to create the boxplot. Thus, the boxplot is created from the original dataframe with the NAN column.
To remove the NAN column and store the result you'd need to write
NAsales_boxplotpivot = NAsales_boxplotpivot[NAsales_boxplotpivot.columns.dropna()]


text:
Q: Asp.net Master page navigation with content pages I have a master page design with the following structure:
main.master
index.aspx
    folder A
      indexa.aspx
    folder B
      indexb.aspx
    folder C
      indexc.aspx

when i run the app, the index.aspx is the default page . From that page i want to navigate between all the pages. Ex. navigate from the index.aspx to indexa.aspx and from indexa.aspx to indexc.aspx, and so on. but actually i am getting resource not found

A: From your structure:
C:/projects/
    main.master
    index.aspx
    folder A/
      indexa.aspx
    folder B/
      indexb.aspx
    folder C/
      indexc.aspx

The URL
    "~/../folder A/indexa.aspx"
would take you to
    "C:/folder A/indexa.aspx"
You want
    "~/folder A/indexa.aspx"
to take you to
    "C:/projects/folder a/indexa.aspx"
From my understanding however, you need to use a server control for "~" to work properly. use of tilde (~) in asp.net path


text:
Q: Running the application on emulator doesn't show up as the XML design page in android studio As us can see guys there is a difference and I don't know why it occurs
I've added the horizontal and vertical also that's not the problem I don't know what it is
Here is my XML Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/fghdfhdfhdfghdfgh"
    tools:context=".Screen1">

    <Button
        android:id="@+id/login"
        android:layout_width="174dp"
        android:layout_height="144dp"
        android:layout_marginStart="28dp"
        android:layout_marginTop="496dp"
        android:background="@drawable/b2111"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/signup"
        android:layout_width="174dp"
        android:layout_height="144dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="496dp"
        android:background="@drawable/b111"
        app:layout_constraintStart_toEndOf="@+id/login"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

A: You might be using constraint layout and your design in XML has bigger screen size than your emulator. Have you tried using other emulator device with bigger screen? Or maybe you can provide your XML codes.


text:
Q: OpenCl is a Library or is a Compiler? I started to learn OpenCl.
I read these links:
https://en.wikipedia.org/wiki/OpenCL
https://github.com/KhronosGroup/OpenCL-Guide/blob/main/chapters/os_tooling.md
https://www.khronos.org/opencl/

but I did not understand well that OpenCl is a library by including header file in source code or it is a compiler by using OpenCl C Compiler?!

A: It is both a library and a compiler.
The OpenCL C/C++ bindings that you include as header files and that you link against are a library. These provide the necessary functions and commands in C/C++ to control the device (GPU).
For the device, you write OpenCL C code. This language is not C or C++, but rather based on C99 and has some specific limitations (for example only 1D arrays) as well as extensions (math and vector functionality).
The OpenCL compiler sits in between the C/C++ bindings and the OpenCL C part. Using the C/C++ bindings, you run the compiler at runtime of the executable with the command clBuildProgram (C bindings) or program.build(...) (C++). It then at runtime once compiles the OpenCL C code to the device-specific assembly, which is different for every vendor. With an Nvidia GPU, you can for example look at the Compiler PTX assembly for the device.

A: If you know OpenGL then OpenCL works on the same principle.
Disclaimer: Self-learned knowledge ahead. I wanted to learn OpenCL and found the OpenCL term as confusing as you do. So I did some painful research until I got my first OpenCL hello-world program working.
Overview
OpenCL is an open standard - i.e. just API specification which targets heterogeneous computing hardware in particular.
The standard comprises a set of documents available here. It is up to the manufacturers to implement the standard for their devices and make OpenCL available e.g. through GPU drivers to users. Perhaps in the form of a shared library.
It is also up to the manufacturers to provide tools for developer to make applications using OpenCL.
Here's where it gets complicated.
SDKs
Manufacturers provide SDKs - software packages that contain everything the said developer needs. (See the link above). But they are specific for each - e.g. NVIDIA SDK won't work without their gpu.
ICD Loader
Because of SDKs being tied to a signle vendor, the most portable(IMHO) solution is to use what is known as Khronos' ICD loader. It is kind of "meta-driver" that will, during run-time, search for other ICDs present in the system by AMD, Intel, NVIDIA, and others; then forward them calls from our application. So, as a developer, we can develop against this generic driver and use clGetPlatformIDs to fetch the available platforms and devices. It is availble as libOpenCL.so, at least on Linux, and we should link against it.
Counterpart for OpenGL's libOpenGL, well almost, because the vast majority of OpenGL(1.1+) is present in the form of extensions and must be loaded separately with e.g. GLAD. In that sense, GLAD is very similar to the ICD loader.
Again, it does not contain any actual "computing" code, only stub implementations of the API which forward everything to the chosen platform's ICD.
Headers
We are still missing the headers, thankfully Khronos organization releases C headers and also C++ bindings. But nothing is stopping you from writing them yourself based on the official API documents. It would just be really tedious and error-prone.
Here we can find yet another parallel with OpenGL because the headers are also just the consequence of the Standard and GLAD generates them directly from its XML version! How cool is that?!
Summary
To write a simple OpenCL application we need to:

*

*Download an ICD from the device's manufactures - e.g. up-to-date GPU drivers is enough.

*Download the headers and place them in some folder.

*Download, build, and install an ICD loader. It will likely need the headers too.

*Include the headers, use API in them, and link against the ICD loader.

For Debian, maybe Ubuntu and others there is a simpler approach:

*

*Download the drivers... look for <vendor>-opencl-icd, the drivers on Linux are usually not as monolithic as on Windows and might span many packages.

*Install ocl-icd-opencl-dev which contains C, C++ headers + the loader.

*Use the headers and link the library.


text:
Q: How do I traverse a tree in Scheme? I'm new to scheme and I am trying to learn how to traverse a B-tree. I'm limited to certain commands from the language which is making this even more complicated.
Here's what I have so far:
(define tree'("R" 100 999
(
 ("R" 100 199
      (
       ("L" 120 140 160 180)
      )
  )

 ("R" 200 299
      (
       ("L" 220 240 260 280)
       )
  )
 )))

(define (treeTraversal a)
  (if(equal? (null? a) #t) 0
  (cdr (treeTraversal (cdr a)))))

(treeTraversal tree)

When I run it via debugger it shows that it is going down the list first clipping that first "R" off then 100, then 999, but from there the list goes null and show's "()" in the debugger. After that I get the error:

mcdr: contract violation
  expected: mpair?
  given: 0

I understand that it is returning 0 because the function sees an empty list now but I don't understand why the list goes null instead of continuing to read into the nested list.
Any ideas and suggestions are appreciated. This is my first time posting a question so please be patient with me :)

A: (define (treeTraversal a)
  (if (null? a)
      #!null
      (if (pair? a)
          (cons (treeTraversal (car a))
                (treeTraversal (cdr a)))
          a)))

will traverse and duplicate your tree.


text:
Q: What will be the integral of this natural log function? I want to do this integral:
$$\int_{0}^{1} (-L) \gamma_{avg}  ln(1-p)  p^L dp$$ the solution provided is :
$$\gamma_{avg} \sum_{k=1}^{L} \frac{1}{k} $$
But I am not able to get it, I even tried integration with parts, but of no use.

A: Let $$A(L)=(1+L)\int_0^1 p^L\ln(1-p)dp$$
Then, using integration by parts:
$$\int_0^1\ln(1-p)p^Ldp=$$ $$\underbrace{\bigg[p^L(p-1)\ln(1-p)-p^{L+1}\bigg]_0^1}_{-1}-L\int_0^1 p^{L-1}(p-1)\ln(1-p)dp+\underbrace{L\int_0^1 p^Ldp}_{\dfrac L{L+1}}$$
$$\int_0^1\ln(1-p)p^Ldp=-L\int_0^1 p^L\ln(1-p)dp+L\int_0^1 p^{L-1}\ln(1-p)-\frac 1{L+1}$$
$$\color{red}{\implies}(1+L)\int_0^1\ln(1-p)p^Ldp=L\int_0^1 p^{L-1}\ln(1-p)dp-\frac 1{L+1}$$
$$\color{red}{\implies} A(L)=A(L-1)-\frac 1{L+1}$$
$$A(L)=A(L-2)-\frac 1L-\frac1{L+1}$$
$$\cdots$$
$$A(L)=A(0)-\sum_{k=2}^{L+1} \frac 1k$$
$$A(0)=\int_0^1 \ln(1-p)dp=-1$$
$$A(L)=-\sum_{k=1}^{L+1} \frac 1k$$
$$\int _0^1 p^L\ln(1-p)dp=-\frac 1{L+1}\sum_{k=1}^{L+1} \frac 1k$$
If in fact what you are really looking for is:
$$\int_0^1 (-L)\gamma \ln(1-p)p^{\color{red}{L-1}}dp$$ then
$$A(L-1)=L\int_0^1 \ln(1-p)p^{L-1}dp=-\sum_{k=1}^{\color{red}{L}}\frac 1k$$
So that finally
$$\boxed{\color{blue}{\gamma \int_0^1(-L)p^{L-1}\ln(1-p)dp}=-\gamma A(L-1)=\color{blue}{\gamma \sum_{k=1}^L \frac 1k}} $$


text:
Q: How can I relate 2 classes via NHibernate? Let's say I have one class "User", and it "has" a property of type "Profile". How can I configure my mappings to generate the schema and create both tables in the database?

A: <many-to-one/>

A: As an aside, if you are not a great fan of scripting up hibernate mappings (which I'm not) then you have a couple of other options.
Castle ActiveRecord is one alternative - it's a layer on top of NHibernate which (among other things) lets you declare your relationships using attributes on your classes and properties.
And Fluent NHibernate is another - it lets you programmatically setup your classes and relationships.
Both are a great improvement over writing your mapping xml by hand!

A: If you are asking about the mapping, you can use the join as shown below. note: you obviously have to add some additional attributes  to suit your app.
   <?xml version="1.0" encoding="utf-8" ?>
   <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"    namespace="MyNamespace" assembly="MyAssembly"    default-lazy="true">
   <class name="User" table="User">
   <id name="Id" column="user_id" unsaved-value="0">
   <generator class="native" />
   </id>
   <property name="Profile" column="profile" />
   </class>
   </hibernate-mapping>

   <?xml version="1.0" encoding="utf-8" ?>
   <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"    namespace="MyNamespace" assembly="MyAssembly"    default-lazy="true">
   <class name="Profile" table="Profile">
   <id name="Id" column="profile_id" unsaved-value="0">
   <generator class="native" />
   </id>
   <property name="Profile" column="profile" />
   </class>
   </hibernate-mapping>


text:
Q: Height of the body part of my layout I need a height problem looked at...
Here is a link to my page:
http://www.whiterootmedia.com/database/test/relative.html
If you zoom all the way out, the #article div background will not go to the footer. How do I make the #article's height 100% minus the banner, nav, and footer given that the nav div will be a dynamic height.
I was trying to position:absolute the footer, but I don't think I can do the same to the banner and nav divs.

A: Try the CSS Sticky Footer. It works cross browser and doesn't need any javascript.

A: you can try min-height in CSS, is it important to scroll out ?
and don´t position it absolute !


text:
Q: I get InvocationTargetException and I don't know how to know real error? I have a class that have a method that sends an email using javax.mail .I've compiled the code and it was working fine,then suddenly I started to get InvocationTargetException and I don't know what is causing it.
Here is my code :
    import java.lang.reflect.InvocationTargetException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendEmailClass {

    private static String USER_NAME = "email@domain.com"  ;
    private static String PASSWORD = "Password";
    private static String RECIPIENT = "email@domain.com";

 private SendEmailClass () {

    }

    public static String getStr (String str)   {

        String from = USER_NAME;
        String pass = PASSWORD;
        String[] to = { RECIPIENT }; // list of recipient email addresses
        String subject = "Test Email";
        String body = "mail notification  " + str ;

        SendEmail(from, pass, to, subject, body);

return "test" + str ;

    }

 public static void SendEmail(String from, String pass, String[] to, String subject, String body)  {

        Properties props = System.getProperties();
        String host = "Some IP Address";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        MimeMessage message = new MimeMessage(session);

        try {
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];

            // To get the array of addresses
            for( int i = 0; i < to.length; i++ ) {
                toAddress[i] = new InternetAddress(to[i]);
            }

            for( int i = 0; i < toAddress.length; i++) {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            }

            message.setSubject(subject);
            message.setText(body);
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

        }

        catch (AddressException ae) {
            ae.printStackTrace();
        }
        catch (MessagingException me) {
            me.printStackTrace();
        }

    }

}

When I invoke method "getStr" I get that exception ,I tried to handle it by putting catch block after at the end of "SendEmail" method , so the method becomes like this :
public static void SendEmail(String from, String pass, String[] to, String subject, String body)  {

        Properties props = System.getProperties();
        String host = "40.101.62.34";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        MimeMessage message = new MimeMessage(session);

        try {
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];

            // To get the array of addresses
            for( int i = 0; i < to.length; i++ ) {
                toAddress[i] = new InternetAddress(to[i]);
            }

            for( int i = 0; i < toAddress.length; i++) {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            }

            message.setSubject(subject);
            message.setText(body);
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

        }

        catch (AddressException ae) {
            ae.printStackTrace();
        }
        catch (MessagingException me) {
            me.printStackTrace();
        }

        catch (InvocationTargetException ex){
            // handle exception
        }

    }

}

But then I get that : "Unreachable catch block for InvocationTargetException. This exception is never thrown from the try statement body"
How do I handles this and find what causing the exception?
Please help .

A: The compiler is telling you that you have code that tries to handle an InvocationTargetException which it can tell will never be thrown so it is superfluous, and can be safely deleted without changing the behavior of your program.
Delete this catch block and try again.


text:
Q: Infinite subset of finite complement space intersects open sets https://proofwiki.org/wiki/Infinite_Subset_of_Finite_Complement_Space_Intersects_Open_Sets
In this wikipedia page I didn't understand that ....why  H intersection closure of U is finite ..
Because closure of U is bigger than U so intersection of H with closure of U must be bigger than U..

A: $\complement_S \left({U}\right)$ stands for complement. Not closure.

A: If $H$ is infinite in $X$ (an infinite set with the finite-complement topology) and $U$ is non-empty open, this means that $X\setminus U$ is finite.
So $H$, being infinite, is not a subset of $X \setminus U$, so there is an $x \in H$, such that $x \notin X\setminus U$, or equivalently $x \in U$. So $U \cap H \neq \emptyset$.
The proof on the referred page uses $C_S(U)$ for $S \setminus U$. (i.e. complement of $U$ inside $S$, which is the whole space, where I used $X$).


text:
Q: Cutting hole in raster using polygon in ArcGIS Desktop? I have two layers: a layer with a raster and a layer with a polygon, I need to cut a polygon from a layer with a raster, how to do it?
It is necessary to make a straight hole, and not to create a new layer
not true:

just like this:

A: If you are using ArcGIS, an option is the Erase tool

There are steps you can follow that I found clip hole in raster
Here are the steps... (Just swap out your layers accordingly.)

*

*Create a vector polygon of the entire US (including Texas).

*Use the "Erase" tool to clip out (erase) Texas from the US shapefile. Now you will have a polygon of the US with Texas removed.

*Use the Extract By Mask tool and have the DEM as your input raster and the new vector shapefile of the US (with Texas erased) as the other input.

*You will now have a DEM with everything but Texas.


text:
Q: No user-context-has FOSHttpCacheBundle + Varnish I'm french, so sorry for my English.
My config:
Varnish on port 80
Apache2 on port 8080
Symfony: 2.5.9
I can not have the X-User-Context-Hash my response headers. Can you help me or point me because then I block.
config.vcl:
the same here: http://foshttpcache.readthedocs.org/en/latest/varnish-configuration.html#varnish-user-context except I changed "/user_context_hash.php" by "/ user-context- hash "
sub vcl_recv {

    # Prevent tampering attacks on the hash mechanism
    if (req.restarts == 0
        && (req.http.accept ~ "application/vnd.fos.user-context-hash"
            || req.http.x-user-context-hash
        )
    ) {
        return (synth(400));
    }

    # Lookup the context hash if there are credentials on the request
    # Only do this for cacheable requests. Returning a hash lookup discards the request body.
    # https://www.varnish-cache.org/trac/ticket/652
    if (req.restarts == 0
        && (req.http.cookie || req.http.authorization)
        && (req.method == "GET" || req.method == "HEAD")
    ) {
        # Backup accept header, if set
        if (req.http.accept) {
            set req.http.x-fos-original-accept = req.http.accept;
        }
        set req.http.accept = "application/vnd.fos.user-context-hash";

        # Backup original URL
        set req.http.x-fos-original-url = req.url;
        set req.url = "/user-context-hash";

        # Force the lookup, the backend must tell not to cache or vary on all
        # headers that are used to build the hash.
        return (hash);
    }

    # Rebuild the original request which now has the hash.
    if (req.restarts > 0
        && req.http.accept == "application/vnd.fos.user-context-hash"
    ) {
        set req.url = req.http.x-fos-original-url;
        unset req.http.x-fos-original-url;
        if (req.http.x-fos-original-accept) {
            set req.http.accept = req.http.x-fos-original-accept;
            unset req.http.x-fos-original-accept;
        } else {
            # If accept header was not set in original request, remove the header here.
            unset req.http.accept;
        }

        # Force the lookup, the backend must tell not to cache or vary on the
        # user hash to properly separate cached data.

        return (hash);
    }
}

sub vcl_backend_response {
    if (bereq.http.accept ~ "application/vnd.fos.user-context-hash"
        && beresp.status >= 500
    ) {
        return (abandon);
    }
}

sub vcl_deliver {
    # On receiving the hash response, copy the hash header to the original
    # request and restart.
    if (req.restarts == 0
        && resp.http.content-type ~ "application/vnd.fos.user-context-hash"
    ) {
        set req.http.x-user-context-hash = resp.http.x-user-context-hash;

        return (restart);
    }

    # If we get here, this is a real response that gets sent to the client.

    # Remove the vary on context user hash, this is nothing public. Keep all
    # other vary headers.
    set resp.http.Vary = regsub(resp.http.Vary, "(?i),? *x-user-context-hash *", "");
    set resp.http.Vary = regsub(resp.http.Vary, "^, *", "");
    if (resp.http.Vary == "") {
        unset resp.http.Vary;
    }

    # Sanity check to prevent ever exposing the hash to a client.
    unset resp.http.x-user-context-hash;
}

config_cache.yml
fos_http_cache:
    user_context:
        enabled: true
        role_provider: true
    cache_control:
        defaults:
            overwrite: true
        rules:
            -
                match:
                    path: ^/
                headers:
                    overwrite: true
                    cache_control:
                        public: true
                        max_age: 60000
                        s_maxage: 56000
                    last_modified: "-1 hour"
                    vary: [Accept-Encoding, Accept-Language]

routing_cache.yml :
user_context_hash:
    path: /user-context-hash

app_dev.php :
/*require_once __DIR__.'/../app/AppCache.php';*/
/*$kernel = new AppCache($kernel);*/

composer.json:
"friendsofsymfony/http-cache-bundle": "1.2.0"

Réponse headers:
headers
Date: Mon, 26 Jan 2015 20:11:48 GMT
Server: Apache/2.2.22 (Debian)
X-Powered-By: PHP/5.4.35-0+deb7u2
Cache-Control: max-age=60000, public, s-maxage=56000
X-Cache-Debug: 1
Last-Modified: Mon, 26 Jan 2015 19:11:48 GMT
x-url: /
x-host: datav1.XXX.com
X-Varnish: 229440 229433
Age: 84
Via: 1.1 varnish-v4
Vary: Accept-Encoding,Accept-Language
Content-Encoding: gzip
Content-Type: text/html; charset=UTF-8
Accept-Ranges: bytes

THX !

A: Varnish makes several sub-requests internally (called "restarts") to deal with x-user-context-hash feature provided by the bundle.
As you can see in the last line in vcl_deliver you unset that header, so it won't be exposed among response headers. You can comment out that line while doing development, though it is not recommended to do on production.


text:
Q: copy by value object with no __deepcopy__ attr I'm trying to deepcopy an instance of a class, but I get a:
object has no __deepcopy__ atrribute

error.
The class is locked away in a .pyd, so it cannot be modified.
Is there a way to copy these objects by value without using deepcopy?

A: You'll have to copy the object state. The easiest way would be to use the pickle module:
import pickle

copy = pickle.loads(pickle.dumps(someobject))

This is not guaranteed to work. All the pickle module does for you in the general case is to pickle the instance attributes, and restore the instance a-new from the class reference and restore the attribute contents on that.
Since this is a C extension object, if the instance state is not exposed to you, and pickling is not explicitly supported by the type, this won't work either. In that case, you have no other options, I'm afraid.


text:
Q: Meu listview esta sem clique Não sei porque , mas os itens não clicam.
Meu layout:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_gravity="center"
        android:src="@drawable/manager"
        android:background="#9b1136">
    </ImageView>

    <ListView
        android:layout_marginTop="10dp"
        android:id="@+id/lista"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

Activity:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ActionBar bar = getActionBar();
    bar.hide();

    listView = (ListView) findViewById(R.id.lista);

    listView.setOnItemClickListener(this);

}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub

    Toast.makeText(DiretorioView.this, "teste", 1000).show();

}

Itens
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:padding="5sp">

        <Button
            android:id="@+id/imageview"
            android:layout_marginLeft="20dp"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:drawableTop="@drawable/lixo"
            android:text="Button" />

        <TextView
            android:id="@+id/text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textSize="20dp"
            android:layout_marginLeft="14sp"
            android:textStyle="bold"
            android:textColor="#FFFFFF"
            android:gravity="center_vertical"/>

    </LinearLayout>
</LinearLayout>

A: Esse problema ocorre quando você tem um item na sua lista que possui um foco, (seu Button) o que causa a não chamada o método OnItemClickListener (veja esse bug reportado aqui)
Isso não quer dizer que você não possa ter um botão dentro de uma lista, você pode utilizar (dependendo de sua necessidade):
1) Inserir o parametro android:descendantFocusability="blocksDescendants" no pai de seu item na lista, e implementar o clique do botão normalmente em seu adapter, por exemplo:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
...
            Button btn= (Button) convertView.findViewById(R.id.youtButton);
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ...
                }
            });
...
}

2) Colocar dentro da tag do seu Button o parametro android:focusable="false" e android:focusableInTouchMode="false"


text:
Q: How do I solve this matrix equation? I am kinda confused about the sum with a scalar part The equation is  XA = A + 3X
A =
\begin{pmatrix}4 & -6 & 2\\-1 & 8 & 0\\-1 & 7 & -2\end{pmatrix}
What I do:
XA - 3X = A
XA - 3X * I = A (I = the identity matrix)
X(A - 3I) = A
But I am not sure It works like that. Then I solve A - 3I by which I mean subtracting
\begin{pmatrix}3 & 0 & 0\\0 & 3 & 0\\0 & 0 & 3\end{pmatrix} from A and the rest is obvious but still I don't think matrix equations work like that. I would appreciate any clues to the right directions or answer if I am doing it right.


text:
Q: re2 Regex for extracting domain In Google Sheets, I am trying to extract domain names from URLs, which may (or may not) have http://, https://, and a subdomain (whether www. or something else like mail.). For example:

*

*http://www.google.com -> google.com

*mail.yahoo.com -> yahoo.com

*www.my-site.org -> my-site.org

Google Sheets uses the re2 syntax for regular expressions. The best I've been able to do so far is:
http[s]?://www.([[:alpha:]]*.[[:alpha:]]*)
This regular expression doesn't work for three main scenarios I've encountered:

*

*when the "http(s)" doesn't exist, but I'm having trouble figuring out how to get the subdomain (www., mail.) to also be recognized as optional

*when the domain name has a non-alphanumeric character, like a dash

*when the top-level domain has multiple levels, like .co.uk

A: use:
=INDEX(IFERROR(REGEXEXTRACT(A1:A, "^(?:https?:\/\/)?(?:ftp:\/\/)?(?:www\.)?([^\/]+)")))


text:
Q: PHP : 'use' inside of the class definition Recently I came across a class that uses use statement inside of the class definition.
Could someone explain what exactly does it do - as I can't find any information about it.
I understand that it might be a way of moving it away form a global scope of the given file, but does it perhaps allow the given class inherit from multiple parent classes as well - since extends only allows one parent class reference?
The example I saw was in the User model of the original installation of Laravel:
<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

}

and I've seen some examples of this model actually using methods included within the UserTrait class - hence my suspicion, but would really like to find out more about the meaning of the enclosed use statements.
PHP documentation says:

The use keyword must be declared in the outermost scope of a file (the
  global scope) or inside namespace declarations. This is because the
  importing is done at compile time and not runtime, so it cannot be
  block scoped. The following example will show an illegal use of the
  use keyword:

followed by the example:
namespace Languages;

class Greenlandic
{
    use Languages\Danish;

    ...
}

which would indicate that it is an incorrect use of the use keyword - any clues?

A: They are called Traits and are available since PHP 5.4. They are imported into another class or namespace using use keyword which is included since PHP 5.0 like importing a regular class into another class. They are single inheritance. The primary reason for the implementation of traits is because of the limitation of single inheritance.
For more details see the PHP trait manual:


text:
Q: Xamarin, Viewpager using Fragments I have followed this tutorial (https://github.com/xamarin/monodroid-samples/tree/master/android5.0/Cheesesquare) for creating a Tab View with Viewpager.
The example works fine, but I want to add this code in another big project and my Fragment class already extends from another Fragment, so I cannot use this:
public class LoginFragment : Android.Support.V4.App.Fragment

Do you have any solution?


text:
Q: Attach onClick analytics tracking code in a href link using jQuery I'm pretty new with JavaScript and jQuery and i'm having a hard time attaching onClick Google Analytics tracking inside an A link in our website redesign using jQuery.
I know that I can just do this:
link

However SharePoint html field deletes the onClick code whenever I put it there so I need a script that does that for me.
So far I have this:
Read PDF

jQuery(document).ready(function($) {
    $(".tracking").click(function() {
        _gaq.push(['_trackPageview', 'url']);
    });
});

The clicked PDF doesn't show up in the real time analytics page when I checked. So I need something that would ensure that when the link is clicked, it shows up in the Analytics tracker in real time. Can I use a script that adds the onClick tracking event inside the A link.
Please help.
Thanks!

A: You can generate a page view with the following code:
$(document).ready(function() {
    $(".tracking").click(function() {
        ga('send','pageview','my-pdf-document')
    });
});

You can actually pass even more data. See the official doc here: https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#send
ga('send', 'pageview', {
  'page': '/my-pdf.pdf',
  'title': 'My PDF Title'
});

UPDATE
You could definitely use your href dynamically like this
ga('send','pageview', $(this).attr('href'));

or even use some HTML-5, you can have your link like this:
link

and do
ga('send', 'pageview', {
    'page': $(this).attr("href"),
    'title': $(this).data("title")
});

EDIT 2
If you're still using ga.js, you can do it this way then:
_gaq.push(['_trackPageview', $(this).attr('href')]);


text:
Q: How to use applymap in a DataFrame on condition that an element is greater than the one which is at the same column but last row? I have a DataFrame df, say, 100 rows and 10 columns. I would like to get values on condition that an element in each column is greater than the element in that column but last row.
df = pd.DataFrame.from_dict({
    'a': {0: 1, 1: 3, 2: 2, 3: 4},
    'b': {0: 1, 1: 4, 2: 2, 3: 6},
    'c': {0: 0, 1: 1, 2: 2, 3: 4},
    'd': {0: 0, 1: 0, 2: 1, 3: 6},
})

from the 2nd row, index = 1, I have to judge that, for each column

*

*if the 3rd row is greater than 2nd row, return diff

*if the 3rd row is smaller than 2nd row, return sum

*if the 3rd row is equal to 2nd row, return 0

for example, I would like to get
df_outcome = pd.DataFrame.from_dict({
    'a': {0: 1, 1: 2, 2: 5, 3: 2},
    'b': {0: 1, 1: 3, 2: 6, 3: 4},
    'c': {0: 0, 1: 1, 2: 1, 3: 2},
    'd': {0: 0, 1: 0, 2: 0, 3: 5},
})

because
df.iloc[2,0] < df.iloc[1,0]
df_outcome.iloc[2,0] = df.iloc[2,0] + df.iloc[1,0] = 3 + 2

also because
df.iloc[2,2] > df.iloc[1,2]
df_outcome.iloc[2,2] = df.iloc[2,2] - df.iloc[1,2] = 2 - 1 = 1

Yeah, I use an awkward way to achieve this. I wonder whether .applymap is available in this case. If it is, how could I code that func which contains the element last row at the same column?
The complicated original code is as followed.
weightMatrix = pd.DataFrame(np.random.random((100,10)))

def func(weightMatrix):
    cfList = pd.DataFrame(weightMatrix,columns = weightMatrix.columns)
    for col in range(len(weightMatrix.columns)):
        for row in range(len(weightMatrix)):
            if row == 0:
                cfList.iloc[row,col] = weightMatrix.iloc[row,col]
                continue
            if (weightMatrix.iloc[row,col] * weightMatrix.iloc[row-1,col] > 0 ) & (weightMatrix.iloc[row,col]>0 ):
                cfList.iloc[row,col] = np.max(weightMatrix.iloc[row,col] - weightMatrix.iloc[row-1,col],0)
            elif (weightMatrix.iloc[row,col] * weightMatrix.iloc[row-1,col] > 0 ) & (weightMatrix.iloc[row,col]<0 ):
                cfList.iloc[row,col] = np.max(weightMatrix.iloc[row-1,col] - weightMatrix.iloc[row,col],0)
            elif (weightMatrix.iloc[row,col] * weightMatrix.iloc[row-1,col] == 0 ) & (weightMatrix.iloc[row-1,col] == 0 ):
                cfList.iloc[row,col] = np.abs(weightMatrix.iloc[row,col])
            elif (weightMatrix.iloc[row,col] * weightMatrix.iloc[row-1,col] == 0 ) & (weightMatrix.iloc[row-1,col] != 0 ):
                cfList.iloc[row,col] = 0
            else:
                cfList.iloc[row,col] = np.abs(weightMatrix.iloc[row,col])
    return cfList

A: If you want to compare a row with the previous or next row, df.shift() is your friend
If you want to do things depending on certain conditions, df.where() can help you
df1 = df.shift(1,).iloc[1:].astype(int)
df2 = df.iloc[1:]

result = df2.copy()
result = df2.where(df1!=df2, 0)
result = (df2 - df1).where(df1 < df2, result)
result = (df1 + df2).where(df1 > df2, result)
result = pd.concat((df.iloc[[0]], result), axis=0)

  a   b   c   d
0 1   1   0   0
1 2   3   1   0
2 5   6   1   1
3 2   4   2   5

PS. I think your df_outcome is wrong for element d2, If not, I missed something in  your explanation


text:
Q: Import array indices from Excel In an Excel file, I have some numbers which I will use as the indices of arrays. I want to read those numbers and assign them as the array indices in Mathematica.
For instance, in Excel I have

and I want the rows to be imported as follows in Mathematica:
{{x[[1]], x[[1]], x[[10]], x[[12]], x[[1]], x[[2]], x[[11]], x[[3]]},
 {x[[1]], x[[1]], x[[12]], x[[14]], x[[1]], x[[3]], x[[13]], x[[4]]},
 ... }

Link to download the excel file: http://www.datafilehost.com/d/477a157f

A: Given your data in the link, e.g.:
arrayList =
 Map[x[[#]] &,
  First@Round[Import["c:\\users\\rasher\\downloads\\nodenumbers.xlsx"]], {2}];

will give you the symbol arrayList containing the list of lists of x indexed using the values in the spreadsheet.
Note that if x does not already exist with enough values, you'll get error messages. You can append //Quiet to the above if you just want a list of lists of indexed x - if/when you create and fill x, arrayList entries will take on the appropriate values. The messages (if x does not exist in proper form) are from attempting to reference something non-existent. You could also Hold the entries to avoid this, but I'm not clear what the end result you're after is...
If there's something else you had in mind, you'll need to further clarify your question.

A: Here's another version:
Import["~/Downloads/NodeNumbers.xlsx"] /. ind_Real :> x[[Floor@ind]]


text:
Q: Spark starting more executors than specified I'm running Spark 1.5.1 in standalone (client) mode using Pyspark. I'm trying to start a job that seems to be memory heavy (in python that is, so that should not be part of the executor-memory setting). I'm testing on a machine with 96 cores and 128 GB of RAM.
I have a master and worker running, started using the start-all.sh script in /sbin.
These are the config files I use in /conf.
spark-defaults.conf:
spark.eventLog.enabled           true
spark.eventLog.dir               /home/kv/Spark/spark-1.5.1-bin-hadoop2.6/logs
spark.serializer                 org.apache.spark.serializer.KryoSerializer
spark.dynamicAllocation.enabled  false
spark.deploy.
defaultCores       40

spark-env.sh:
PARK_MASTER_IP='5.153.14.30'  # Will become deprecated
SPARK_MASTER_HOST='5.153.14.30'
SPARK_MASTER_PORT=7079
SPARK_MASTER_WEBUI_PORT=8080
SPARK_WORKER_WEBUI_PORT=8081

I'm starting my script using the following command:
export SPARK_MASTER=spark://5.153.14.30:7079  #"local[*]"
spark-submit \
    --master ${SPARK_MASTER} \
    --num-executors 1 \
    --driver-memory 20g \
    --executor-memory 30g \
    --executor-cores 40 \
    --py-files code.zip \
<script>

Now, I'm noticing behaviour that I don't understand:

*

*When I start my application with the settings above, I expect there to be 1 executor. However, 2 executors are started, each having 30g of memory and 40 cores. Why does spark do this? I'm trying to limit the number of cores to have more memory per core, how can I enforce this? Now my application gets killed because it uses too much memory.

*When I increase executor-cores to over 40, my job does not get started because of not enough resources. I expect that this is because of the defaultCores 40 setting in my spark-defaults. But is't this just as a backup for when my application does not provide a maximum number of cores? I should be able to overwrite that right?

Extract from the error messages I get:
Lost task 1532.0 in stage 2.0 (TID 5252, 5.153.14.30): org.apache.spark.SparkException: Python worker exited unexpectedly (crashed)
    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:203)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:207)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:125)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:297)
    at org.apache.spark.CacheManager.getOrCompute(CacheManager.scala:69)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:262)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:297)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:264)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:88)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.EOFException
    at java.io.DataInputStream.readInt(DataInputStream.java:392)
    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:139)
    ... 15 more

[...]

py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 111 in stage 2.0 failed 4 times, most recent failure: Lost task 111.3 in stage 2.0 (TID 5673, 5.153.14.30): org.apache.spark.SparkException: Python worker exited unexpectedly (crashed)

A: Check or set the value for spark.executor.instances. The default is 2, which may explain why you get 2 executors.
Since your server has 96 cores, and you set defaultcores to 40, you only have room for 2 executors since 2*40 = 80. The remaining 16 cores are insufficient for another executor and the driver also requires CPU cores.

A:
I expect there to be 1 executor. However, 2 executors are started

I think the one executor you see, it's actually the driver.
So one master, one slave (2 nodes in totals).
You can add to your script these configuration flags:
--conf spark.executor.cores=8        <-- will set it 8, you probably want less
--conf spark.driver.cores=8          <-- same, but for driver only

my job does not get started because of not enough resources.

I believe the container gets killed. You see, you ask for too many resources, so every container/task/core tries to take as much memory as possible, and your system can't simple give more.
The container might exceed its memory limits (you should be able to see more in the logs to be certain though).


text:
Q: java Reading unknown formats from DataInputStream I am developing an client server application that will be communicating using UDP and packets.
I will be encoding a decoding data from these packets using DataOutputStream and DataInputStream.
The way i would like to store my data is inside a custom packet class extended from another custom base packet class.
This packet base class contains a list of objects, the packet data, (these objects will be in multiple formats; String, Int, Boolean...) and will be encoded to a DataOuputStream using the following method:
public ByteArrayOutputStream getDataOS(){
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    DataOutputStream os = new DataOutputStream(data);

    try {
        for(Object obj : packetData){
            if(obj instanceof String)
                os.writeUTF((String) obj);
            else if(obj instanceof Integer)
                os.writeInt((int) obj);
            else if(obj instanceof Byte)
                os.writeByte((Byte) obj);
            else if(obj instanceof Double)
                os.writeDouble((double) obj);
            else if(obj instanceof Boolean)
                os.writeBoolean((Boolean) obj);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return data;
}

This ByteArrayOutputStream will then be sent off to my packet handler and forwarded on to the client/server.
The road block i have run into is regarding how to read this packets DataInputStream on the other end.
As i will not be knowing what format each of the objects will be, i will not be able to read them using is.readUTF(); for example.
One method i have thought to combat this would be to send a byte object type identifier before each sent object. I.e int would be 0, UTF would be 1 and so on. This would allow me to prepare for each object read by using a case statement on the byte type identifier.
This will obviously add more data to my packets, which is not optimal. The reason i want to do it like this however is to avoid hard-coding each data read for each, possibly hundreds of packets.
What my question really is, is if this is a sensible way of going about this? Or is there an easier way of sending through custom structured packets, and reading them on the other side not necessarily knowing the data format..?

A: Obviously you have to write a token ahead of each item announcing what type it is.
Or use an ObjectOutputStream and just write and read objects, and use instanceof at the *receiving * end.


text:
Q: QtSql connect to multiple databases I am having a problem with Python 3.7 PyQt5 QtSql. I am trying to have multiple MSSQL databases connected, but cannot figure how to do it.
I have the following function to connect:
from PyQt5 import QtSql
def connectDb(database_name):
    SERVER_NAME = 'COMPUTER\\SQLEXPRESS'
    DATABASE_NAME = database_name
    connString = f'DRIVER={{SQL Server}};'\
                 f'SERVER={SERVER_NAME};'\
                 f'DATABASE={DATABASE_NAME}'
    db = QtSql.QSqlDatabase.addDatabase("QODBC")
    db.setDatabaseName(connString)
    if not db.open():
        print(db.lastError().text())
    return db

To connect to a database:
db1 = connectDb("Database1")
db2 = connectDb("Database2")

However, when trying to connect to the second database, I get the message:
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.

The reason I want to keep multiple databases open is that it is far too slow to keep opening and closing database connections each time I need to query a different database in my code. I'd rather keep them all open and close them when the program exits.

A: When a QSqlDataBase is created using the addDatabase() method then the names passed through the connectionName parameter are stored in a dictionary where the key takes that value, if that parameter is not passed then "qt_sql_default_connection" is used causing the creation of the Second database you get a duplicate in the dictionary so Qt issues that warning. A possible solution is to pass it a different name (not tested):
from PyQt5 import QtSql

def connectDb(database_name, connection_name):
    SERVER_NAME = "COMPUTER\\SQLEXPRESS"
    DATABASE_NAME = database_name
    connString = (
        f"DRIVER={{SQL Server}};" f"SERVER={SERVER_NAME};" f"DATABASE={DATABASE_NAME}"
    )
    db = QtSql.QSqlDatabase.addDatabase("QSQLITE", connection_name)
    db.setDatabaseName(connString)
    if not db.open():
        print(db.lastError().text())
    return db
db1 = connectDb("Database1", "connection_1")
db2 = connectDb("Database2", "connection_2")


text:
Q: enabling compression during "gsutil cp" download The gsutil command supports options to enable compression during transport only (with -J or -j ext), allowing you to compress during transport only, thereby saving network bandwidth and speeding up the copy itself.
Is there an equivalent way to do this when downloading from GCS to local machine? That is, if I have an uncompressed text file at gs://foo/bar/file.json, is there some equivalent to -J that will compress the contents of "file.json" during transport only?
The goal is to speed up a copy from remote to local, and not just for a single file but dozens. I'm already using -m to do parallel copies, but would like to transmit compressed data to reduce network transfer time.
I didn't find anything relevant in the docs, and including -J doesn't appear to do anything during downloads. I've tried the following, but the "ETA" numbers printed by gsutil look identical whether -J is present or absent:
gsutil -cp -J gs://foo/bar/file.json .

A: This feature is not yet available.
As an alternative, you will need to implement your own solution for compressing, be it an App Engine, Cloud Function or Cloud Run. Your application will need to compress your files while they are on Cloud Storage.
The ideal solution would be to use -m along with the compressed files. This entails that you're making parallel copies of compressed files. Consider the following structures. If [1] is how you are doing your you are downloading each file individually. If you look at [2], you would only download the compressed files.
[1]
Bucket Foo
├───FooScripts
│   ├───SysWipe.sh
│   └───DropAll.sql
├───barconfig
│   ├───barRecreate.sh
│   └───reGenAll.sql
├───Baz
│   ├───BadBaz.sh
│   └───Drop.sh
...

[2]
Bucket Foo
├───FooScripts
│   ├───SysWipe.sh
│   └───DropAll.sql
│   ├───FooScripts.zip
├───barconfig
│   ├───barRecreate.sh
│   └───reGenAll.sql
│   ├───barconfig.zip
├───Baz
│   ├───BadBaz.sh
│   └───Drop.sh
│   ├───Baz.zip
...

Once your data has been downloaded, you should consider deleting the compressed files as they are no longer needed for your operations and you will be charged for them. Alternatively, you can raise a Feature Request on the Public Issue Tracker, which will be sent to the Cloud Storage team, who can look into the feasibility of this request.


text:
Q: How to make backgrounds white for QgsLayoutItems in QGIS Python console? I would like the background of my label and scale bar items to be white rather than transparent.

I am using Python in QGIS. My code is below. See the # Add Scalebar and # Add Title sections towards the end. Note that this code is within a loop because I will be generating and exporting a series of maps with the same layout. I generate the render colors in code outside the loop but don't include it here because the code is already long.
I tried this based on another post but it didn't work for me.
    scalebar = super(QgsLayoutItem, scalebar)
    scalebar.setBrush(QColor(255,255,255))

for i in range(0,len(targ)):

    # Load Raster File
    fn = "/".join([fldr, targ[i]])
    fi = QFileInfo(fn)
    fname = fi.baseName()
    rlayer = iface.addRasterLayer(fn, fname)

    renderer = QgsSingleBandPseudoColorRenderer(rlayer.dataProvider(), 1, shader)
    rlayer.setRenderer(renderer)

    # Create and Export Print Layout
    # Identify Layer for Map
    layers = QgsProject.instance().mapLayersByName(fname)
    layer = layers[0]
    project = QgsProject.instance()
    manager = project.layoutManager()
    layoutName = " ".join(['Temp Pred Maps', str(i)])
    layouts_list = manager.printLayouts()

    # Remove any duplicate layouts
    for i in layouts_list:
        if i.name() == layoutName:
            manager.removeLayout(i)

    # Add add layout to QGIS
    layout = QgsPrintLayout(project)
    layout.initializeDefaults()
    layout.setName(layoutName)
    manager.addLayout(layout)

    # SET PAGE SIZE HERE
    #*** HOW TO SET PAGE SIZE? ***
    page = QgsLayoutItemPage(layout)
    page_size = QgsLayoutSize(200, 200, QgsUnitTypes.LayoutMillimeters)
    #page.QgsPageSize(page_size.size) # Error
    page.attemptResize(page_size) # Does Nothing???
    #layout.addLayoutItem(page) # Adds second page
    #layout.removeLayoutItem(layout)

    # Create map item in the layout
    map = QgsLayoutItemMap(layout)
    map.setRect(20,20,20,20)

    # set the map extent
    ms = QgsMapSettings()
    ms.setLayers([layer]) # set layers to be mapped
    rect = QgsRectangle(can_ext)
    rect.scale(1)
    ms.setExtent(rect)
    map.setExtent(rect)
    layout.addLayoutItem(map)
    map.attemptMove(QgsLayoutPoint(0, 0, QgsUnitTypes.LayoutMillimeters))
    map.attemptResize(QgsLayoutSize(200, 200, QgsUnitTypes.LayoutMillimeters))

    # Create Legend *** NEED TO GET TEMP VALUES IN LEGENED ***
    legend = QgsLayoutItemLegend(layout)
    legend.setTitle("")
    layer.setName("Temperature (C)") # change layer name for legend
    layerTree = QgsLayerTree()
    layerTree.addLayer(layer)
    legend.model().setRootGroup(layerTree)
    legend.setStyleFont(QgsLegendStyle.Subgroup, QFont('Arial', 20))
    layout.addLayoutItem(legend)
    legend.attemptMove(QgsLayoutPoint(140, 0, QgsUnitTypes.LayoutMillimeters))
    # legend.update()
    # layout.removeLayoutItem(legend)

    # Add Scalebar
    scalebar = QgsLayoutItemScaleBar(layout)
    scalebar.setStyle('Single Box')
    scalebar.setUnits(QgsUnitTypes.DistanceMeters)
    scalebar.setNumberOfSegments(2)
    scalebar.setNumberOfSegmentsLeft(0)
    scalebar.setUnitsPerSegment(100)
    scalebar.setLinkedMap(map)
    scalebar.setUnitLabel('m')
    scalebar.setFont(QFont('Arial', 20))
    scalebar.update()
    layout.addLayoutItem(scalebar)
    scalebar.attemptMove(QgsLayoutPoint(120, 193, QgsUnitTypes.LayoutMillimeters))

    scalebar = super(QgsLayoutItem, scalebar)
    scalebar.setBrush(QColor(255,255,255)) # This isn't working

    # Add Title
    #   Generate Titles
    date_time = re.split("T[1/2/3] ", fname)[1]
    date_only = re.split(" ", date_time)[0]
    time_only = re.split(" ", date_time)[1]
    time_only = re.split("-", time_only)[0]+":"+re.split("-", time_only)[1]

    #    Date Title
    title = QgsLayoutItemLabel(layout)
    title.setText(date_only)
    title.setFont(QFont('Arial', 30))
    title.adjustSizeToText()
    title.setBackgroundColor(QColor(255, 255, 255, 255)) # Not working???
    layout. addLayoutItem(title)
    title.attemptMove(QgsLayoutPoint(3, 3, QgsUnitTypes.LayoutMillimeters))
    # title.update()
    # layout.removeLayoutItem(title2)

    #   Time Title
    title2 = QgsLayoutItemLabel(layout)
    title2.setText(time_only)
    title2.setFont(QFont('Arial', 30))
    title2.adjustSizeToText()
    title2.setBackgroundColor(QColor(255, 255, 255, 255)) # Not working???
    layout. addLayoutItem(title2)
    title2.attemptMove(QgsLayoutPoint(3, 20, QgsUnitTypes.LayoutMillimeters))

    # Export Map Layout
    # layout = manager.layoutByName(layoutName)
    exporter = QgsLayoutExporter(layout)
    fn = export_folder + "/" + fname + ".jpg" # file export directory and filename
    exporter.exportToImage(fn, QgsLayoutExporter.ImageExportSettings())

A: You need to enable the background (it is white by default).
title.setBackgroundEnabled(True)


text:
Q: Are there fine lines separating content types in databases? Well, I have a number of different content types that I want to make available.  Some are so similar, I feel they belong in the same category.  There are columns that apply to come of the content types and not to others, though.  Should I store them all in a nodes table, or should I create a new table for each content type?  Should I break the tables up over incompatible columns?
Here are some examples content types: book, blog entry, ad, profile, spotlight story, archival story, static page, contact form, quiz, poll.
I've been thinking about splitting the tables up like this:
post: book, spotlight story, archival story, blog entry

questionnaire: quiz, poll

static: static page, profile

ad

contact form

It wasn't apparent to me which method was best after reading about database normalization, unfortunately, but I had a great deal of trouble understanding anything beyond the third normal form.  What I found particularly troubling when I started reading about third normal form was that people in industry often neglect to adhere to it intentionally, for the sake of speed.  So, if anyone could use my example to bring me some clarity about what's actually reasonable, I would really appreciate that.

A: TL;DR: It depends.
Normalization implies you'd have a table for the common properties, and separate tables for each type's unique properties. If there's a large number of common properties, and it makes sense to refer to each of the types that share those properties as the same "super type", then I prefer this.
If speed matters, you may not want to do this, as it will force a join every time you access one of the sub-types. Whether or not that level of tuning is meaningful depends on a bunch of things.
If each sub-type has a "small" number of unique properties, it might be just as easy to store a type and each property in a single table ("single table inheritance"), or if speed actually becomes an issue.
Another option is to actually do both: keep a relational model, but use triggers to keep a collection of flat data. I'm not sure that makes sense in your case, since there probably wouldn't be a "large" number of joins--but for really complicated DB models, it's handy, especially for reporting.


text:
Q: Wildcard on Geoserver SQL View I have made the following SQL view on Geoserver:
SELECT *
FROM areas
WHERE landuse = '%landuse%'

This works perfectly fine when I specify the landuse in the URL, for example 'grass'. However when I want the query to return all features regardless the type of landuse I do not know what I have to enter in the URL.

A: The simplest answer is to use a CQL filter in the WMS request to restrict which landuse types are drawn on the map. There is a full tutorial available to get you going. However in your case it would be something like:
http://...../geoserver/wms?....&CQL_FILTER=landuse='grass'

when you want to filter by grass or more complex options like:
http://...../geoserver/wms?....&CQL_FILTER=landuse='grass' or landuse='trees'

Or just leave it off completely to show all types. Note you will need to make sure the URL is correctly encoded for the spaces and = etc.

A: In the past I've overcome this by replacing the whole where clause with a parameter, and then set the default to 1=1
SELECT *
FROM areas
WHERE %query&

you can then supply the full clause e.g. landuse = 'grass' within the parameter declaration in the URL.
I appreciate this is a slightly unsatisfactory, and there would be more elegant solutions depending on the underlying database.  Are you using PostGIS?
And I forgot to mention, as @iant point out below, that you should really be using a CQL Filter, unless there's some reason it's not possible to use.


text:
Q: Is ++i in for loop faster than i++ for int? C++ i have a question, we know that ++i is faster to use as a iterator in for loop for classes such as list, because compiler doesn't create a temp object to store previous value. But, does that work also for int? I mean is ++i faster to use than i++ in for loop with int?
for(auto it = myList.begin(); it != myList.end(); ++it) {} - faster
for(auto it = myList.begin(); it != myList.end(); it++) {} - slower

for(int i=0; i<SIZE; ++i) {} - faster?
for(int i=0; i<SIZE; i++) {} - slower?


text:
Q: Error in kivy app: object.__init__() takes exactly one argument (the instance to initialize) I am trying to make a form app and I don't understand the error. I unfortunately failed in many directions to solve it:
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
Here is the code:

from kivy.uix.gridlayout import GridLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.graphics import Color, Rectangle
import kivy.utils

class UsersBanner(GridLayout):

    def __init__(self, **kwargs):
        self.rows = 1
        super(UsersBanner, self).__init__(**kwargs)
        with self.canvas.before:
            Color(rgb=(kivy.utils.get_color_from_hex("#67697C")))
            self.rect = Rectangle(size=self.size, pos=self.pos)
        self.bind(pos=self.update_rect, size=self.update_rect)

        # need left float layout
        left = FloatLayout()
        user_label = Label(text=str(kwargs['user_name']), size_hint=(1, .3), pos_hint={"top": .225, "right": 1})
        left.add_widget(user_label)
        # need middle float layout
        middle = FloatLayout()
        nationality_label = Label(text=str(kwargs['nationality']), size_hint=(1, .3), pos_hint={"top": .225, "right": .9})
        middle.add_widget(nationality_label)
        # need right float layout
        right = FloatLayout()
        user_image = Image(source="icons/users/" + kwargs['user_image'], size_hint=(1, .3),
                           pos_hint={"top": .225, "right": .7})
        right.add_widget(user_image)

        self.add_widget(left)
        self.add_widget(middle)
        self.add_widget(right)

    def update_rect(self, *args):
        self.rect.pos = self.pos
        self.rect.size = self.size

Error :
File "/Users/alexisdsc/PycharmProjects/app_arabe/main.py", line 74, in <module>
     MainApp().run()
   File "/Users/alexisdsc/Library/Python/3.9/lib/python/site-packages/kivy/app.py", line 949, in run
     self._run_prepare()
   File "/Users/alexisdsc/Library/Python/3.9/lib/python/site-packages/kivy/app.py", line 944, in _run_prepare
     self.dispatch('on_start')
   File "_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "/Users/alexisdsc/PycharmProjects/app_arabe/main.py", line 62, in on_start
     uu = UsersBanner(user_name=user['user_name'],  nationality=user['nationality'],
   File "/Users/alexisdsc/PycharmProjects/app_arabe/usersbanners.py", line 13, in __init__
     super(UsersBanner, self).__init__(**kwargs)
   File "/Users/alexisdsc/Library/Python/3.9/lib/python/site-packages/kivy/uix/gridlayout.py", line 279, in __init__
     super(GridLayout, self).__init__(**kwargs)
   File "/Users/alexisdsc/Library/Python/3.9/lib/python/site-packages/kivy/uix/layout.py", line 76, in __init__
     super(Layout, self).__init__(**kwargs)
   File "/Users/alexisdsc/Library/Python/3.9/lib/python/site-packages/kivy/uix/widget.py", line 350, in __init__
     super(Widget, self).__init__(**kwargs)
   File "_event.pyx", line 245, in kivy._event.EventDispatcher.__init__
 TypeError: object.__init__() takes exactly one argument (the instance to initialize)

A: If you are creating an object with these two parameters only
uu = UsersBanner(user_name=user['user_name'],  nationality=user['nationality'])

could you please try this in USerbanner init
def __init__(self,user_name,nationality, **kwargs):   # intead of def __init__(self, **kwargs):

you can add other variables if you have any


text:
Q: How to use fetch API to get an Array back? I have an API which will return an array to me.
I tried to use fetch API to get the array back.
I know that if I use fetch to acquire some data, the real body in the response is ReadableStream.
I usually to deal with it by response.json() in then function if data is json.
What I don't know is how to deal with array data?

A: If your API is not returning a JSON array [1,2,3] then you can use the .text function to get the raw value:
fetch('/api/text').then(function(response) {
  return response.text()
}).then(function (text) {
  // parse the text here how you want, for csv:
  // return text.split(',')
})

Otherwise you can simply just use the .json method to get the array value.
The ArrayBuffer that you mention is to read a binary buffer, it can be useful for fetching songs or etc... If your API is returning this, I would check out the link to see what you can do. You will most likely be required to decode the buffer and how that is done is completely dependent on how your API is encoding it and I cannot answer that without more detail regarding your API response.


text:
Q: How do I get the entry point of other binary(executable) in Linux without recompile? I'm trying to get the entry point of other binary.
I want to write the program in C which hooking the specified function of other binary in Linux.
There are 2 programs.

*

*binary (any language, any compile option)

*The program that executes the hooks

I search how to do that without recompile Program 1.
It is assumed that I know the name of the function specified.
I don't want to modify Program 1.
So I need the entry point of function of other binary for hooking without recompile.
On the other hand, Program 2, I can make as many changes as I like.
What should I do?
Here's an overview
Goal:

*

*How to get the entry point of other binary(executable) in Linux?

Assumes:

*

*Program 1 is generated by compiling the C language.(any options)
It is better if I could support not only C language.

*Program 2 is generated by compiling the C language.
Requirement:

*

*without recompile Program 1.


text:
Q: Calculate elevation (view) angle with incidence angle I want to calculate the elevation (view) angle of a satellite using the incidence angle.see image
On this site there is a tool which you can use to calculate it but without description.
https://www.intelligence-airbusds.com/en/8719-angle-conversion
Does any body have an idea how I could do that?
Additionally I have the satellite position and the earth is an ellipsoid.

A: As far as I see the drawing is following:


text:
Q: Uploading recipe changes to chef server using Berkshelf I'm in the process of customizing community cookbooks (cassandra and elasticsearch) for use in production. From trying to get to grips with Berkshelf I have found myself uploading changes to my wrapper cookbook recipes from within my ~/chef-repo/cookbooks/ by executing:
Berks upload -b ./Berksfile --no-ssl-verify --force

This gets past the fact that my chef server is not certified, and overcomes the "frozen" cookbooks.
I'm sure that there's a better way to upload simple changes to my chef-server, as it feels somewhat extreme to force a re-upload of the entire cookbook and all it's dependencies?
Thanks in advance for any help.

A: Berks upload -b ./Berksfile --no-ssl-verify --force <my cookbook name>
That will upload just the one cookbook you want (ie, the one you changed)


text:
Q: Require suggestions for writing telugu font through english letters typing( english keyboard) in android app I would like to develop an meme android app in which I require English to Telugu conversion API.
When I type letters in English language that has to be converted and displayed right away in Telugu font.  For example i type "hyderabad" there should be instant conversion display of "హైదరాబాద్".
Any suggestions or code snippets or at least any API resources are appreciable.


text:
Q: Concatenate comma delimited column values are remove duplicates I need to concatenate comma delimited column values stored in an oracle table.  I will also need to remove duplicated values when I concatenate the column values.  I'm new to oracle and not sure where to start.  Can someone help me achieve the following in oracle 11g?
Table:
rec_id     affiliations
1          P,QE,D
2          EE,ED-D
1          QE,PO-D, D
2          A,EE

Desired output:
rec_id    affiliations
1         P,QE,D,PO-D
2         EE,ED-D,A,EE

A: The first part of this query parses the input into a separate row for each affiliation; the final select concatenates them into a single list for each rec_id.
with parsed as (
  select distinct
         rec_id
        ,ltrim(regexp_substr(','||affiliations,',([^,])+',1,i), ',') k
  from t, (select rownum i from dual connect by level <= 100)
  where regexp_substr(','||affiliations,',([^,])+',1,i) is not null)
select distinct
       rec_id
      ,listagg(k, ',') within group (order by k) over (partition by rec_id) affiliations
from parsed
order by rec_id;

Adjust the number (e.g. 100) to the maximum number of items you'd expect to see in the input.
http://sqlfiddle.com/#!4/37b44/4


text:
Q: Subversion: why "mixed revisions" when revision numbers are sequential? An example: Say that after an svn update I am on revision 10. If I now add a file and perform a commit, svnversion will report that I am in a state of mixed revisions; namely 10:11. But since these numbers are in sequence, clearly there has not been any other commit in between. Couldn't subversion deduct from this that my version is up to date (=HEAD) so I wouldn't need to run another svn update in order to remove this mixed revisions state?
I realize this is no big deal; I just wonder if I am missing some special case were the above reasoning may not be true.

A: I'm actually a bit surprised that Subversion claims that your modified files are version 11, because they might not be. If somebody else were to commit a version 11 before you, then your files would end up being version 12 or greater.
I guess the reason is that your local subversion can't claim that your version with added files is fully version 11, because it doesn't know for sure yet.

A: If I've understood your issue right, I can tell you that your working copy will almost always have mixed-revisions. This is because different files have been committed in different revisions and have changed then. Have you noticed that some files (for e.g.) show revision 10 and others 25, but yet you're still in the HEAD revision. This is because your workspace holds additional metadata for the files and revisions.
Generally this should not be a problem at all and as far as I am concerned it is part of the SVN workflow. I recall that this is explained somewhere in the SVN documentation but I can't seem to find it right now. I will edit my answer accordingly if I do so.


text:
Q: How to push my code from local machine to Azure devops in a different branch other than master using GIT? How to add project folder from my local machine to a git repository on Azure using GIT?
In the local directory for the root of the project
git init

git remote add origin <URL for Azure Git repo>

git add .

git commit -m 'initial commit'

git push -u origin master

I know these commands after doing a basic research on stack-overflow but my question is, if we have a branch named "dev" and I create a folder named "sandbox" in that branch, so if I want to add my project in that particular folder can I do just by copying the https link by going to that folder and what should be typed in
git push -u origin master

instead of master? Do I have to write "dev" as this is the branch I will be pushing my code in?

A: To push to origin dev you can do
git push -u origin dev

A quick git tutorial
I'll explain how to create a git repo, create a new branch, setting upstream and pushing the branch to remote.
Init a git repo and make some dummy commits in master
# init a git repo
git init

# Add a remote for the git repo
git remote add origin <URL for Azure Git repo>

# create a dummy file
touch file1

# stage all changes made to git repo so they can be commited
git add .

# make a commit for the staged changes
git commit -m 'initial commit'

# push commit to remote
git push

# The same as previous step, buy done explicitly by specifying the remote address and branch name
git push -u origin master

Adding a demo commit in a new branch
# create a new file
touch file2

# stage changes
git add .

# decided to push these changes to dev instead of the master branch
# create a new branch and checkout to dev
git checkout -b "dev"

# make commit to the dev branch
git commit -m 'dev commit'

# push the changes
git push

# or

# Only push the changes of dev to remote address origin
git push -u origin dev

In the end your git log would look like this (with pretty print and formatting)
* 2e48c23 - (HEAD -> dev, origin/dev)
|           dev commit - clmno
* fad2e5b - (master, origin/master)
            initial commit - clmno


text:
Q: Bubble sort double linked list Hello everyone I'm trying to sort my double linked list in C using bubble sort algorithm. Here is my code:
struct node {
                unsigned char key;
                unsigned char num;
                struct node *left;
                struct node *right;
            };

Here is my sort funcion:
void sort(int count, struct node *t_node)
{
    struct node *tmp,*nextnode, *node1, *node2;

    for(node1 = t_node;node1->right != NULL ;node1 = node1->right) {
        for(node2 = node1->right; node2->right != NULL; node2 = node2->right) {
            if(node2->key > node2->right->key)
            {
                nextnode = node2->right;
                tmp = node2->left;
                node2->right = nextnode->right;
                node2->left = nextnode->left;
                nextnode->right = node2;
                nextnode->left = tmp;
            }
        }
    }

}

It works in 80% because for example data:
node1 key=3
node2 key=144
node3 key=49
node4 key=207

The result after sort is:
node1 key=3
node2 key=144
node4 key=207

Why my third node disappeared? Where is the problem?

A: It's a double-linked list. To swap two nodes, typically 6 pointers need to be updated. Say we have A <-> B <-> C <-> D and you want to swap B and C: you'll need to update right of A, B, and C, and also left of B, C, and D.
Your code is only updating 4 pointers here:
        if(node2->key > node2->right->key)
        {
            nextnode = node2->right;
            tmp = node2->left;
            node2->right = nextnode->right;
            node2->left = nextnode->left;
            nextnode->right = node2;
            nextnode->left = tmp;
        }

This shall fix your issue:
        if(node2->key > node2->right->key)
        {
            nextnode = node2->right;
            tmp = node2->left;
            if (tmp)
                tmp->right = nextnode;
            if (nextnode->right)
                nextnode->right->left = node2;
            node2->right = nextnode->right;
            node2->left = nextnode->left;
            nextnode->right = node2;
            nextnode->left = tmp;
        }

A: You also need to replace the previous node (tmp in your code but I'd suggest a more explicit name...) right pointer, and the next-next node's left pointer :
tmp <-> node1 <-> node2 <-> nextnext

You are on node1 and detect you need to swap it with node2 :

*

*You need to have tmp -> node1  changed to tmp -> node2

*You need to have node2 <- nextnext changed to node1 <- nextnext as well


text:
Q: How to route mywebsite.com/filename to some action method? I am creating file downloading backend in asp.net core 3.1 and I want to enter file name after my site name (for example www.something.com/file_txt) to get redirected to home controller and file action method with string filename as parameter. In that action method I will then open file.txt and send it as response to user. Idea is to get some file without entering something long like www.something.com/home/file/image_jpg
Is that possible in asp.net core?

A: Yes. something like this
    [Route("/{filename}")]
    public IActionResult File(string filename)
    {
        //return file here. you have it's name in filename argument
    }


text:
Q: Message Boxes in ASP.NET (MVC) Web Application In a windows form application, I would typically use the code MessageBox.Show("error!") to notify a user of an error for data validation, and I am aware that you can't do this in an asp.net application. After doing some basic research on the problem, I have come to the conclusion that a JQuery dialog box is probably the closest thing to a message box. What are some other alternatives to solve this problem, and is the JQuery dialog box the best way to handle this kind of problem? I am new to software development, mvc and JQuery, I just want to know the best programming practice to handle this problem.
Currently, this is the code I have in my controller:
if (String.IsNullOrEmpty(dateSearchBegin) || String.IsNullOrEmpty(dateSearchEnd))
{
    //string message = "Both date fields are required";
}
else
{
   var dtFrom = DateTime.Parse(dateSearchBegin);
   var dtTo = DateTime.Parse(dateSearchEnd);
   return View(db.PurchaseOrders.Where(x => x.Date >= dtFrom && x.Date <= dtTo).OrderBy(i => i.Date).ToPagedList(page ?? 1, 15));
}

I want to put the string message in the validation, how should I combat this problem?

A: You can use ModelState for add custom error message
if (String.IsNullOrEmpty(dateSearchBegin) || String.IsNullOrEmpty(dateSearchEnd))
 {
   ModelState.AddModelError("CustomError", "Both date fields are required");
 }

End show in view:
@Html.ValidationMessage("CustomError")

A: If you're looking to add validation to a model object, look into Model Validation in asp.net-mvc.

If you're looking for a way to notify the user of some message from the controller, check out ControllerBase.TempData. It handles this precise scenario very well.
As a side note, I created a nuget package, based on Bootstrap Notifications, that wraps this functionality up nicely in Bootstrap, and enables you to easily notify users from the controller using:
this.AddNotification("You have errors because you did it wrong!", NotificationType.ERROR);

from any Controller.

A: Use Ajax to make the Post to the Server , then return JsonResult from your Action. You can send back text/numbers to the client which you check to detect if your condition was not met on the server-side then display a javascript alert on the client browser.