text:
Q: Independence in Poisson regression when used for rates estimation I'm interested in using Poisson regression for estimating mortality rates. I've observations for a rather long period, and have to face the fact that covariates often vary over time. This is especially the case when the age of the people comes into play and the observation period exceeds a few months.
In this case, here is my way to deal with this issue : the observation period is divided into intervals where the covariates are constant. Each observation then becomes a set of observations and the exposures are calculated for each interval. However, the log-likelihood in Poisson regression models assume independence between the observations.
But, as I have, say for a person named Jack, a period where he is forty and another one where he is forty one, I will have for Jack two observations in my model, and I can't really say that those two observations are independent.
Can I just assume that the death rates are independent anyway, or are there specific methods to deal with this issue in a better way?
EDIT
In this lesson, at the paragrah 7.4.3 The Equivalent Poisson Model there is something that could let think my approach is not invalid. Nevertheless, as far as I'am aggregating data in each bunch of pseudo-observation (and not as in the text , one for each combination of individual and interval) I wonder if it still stand.
EDIT
About grouping data :
I have a set of thousands of observations. Each one relate to an individual, and for each one I have the date of entry in the study, the date of exit, the date of death, an indicator for smoking or not, the birth date, the gender (and a few other one but that don't matter here).
I cut the whole interval of time covered form the first entry to the last at each time something happen (someone entre or leave the study, or a covariate changes).
For each interval of time, and for each set of similar age and other covaraiates, I compute the total exposition, and the number of deaths. And I this way I get "pseudo-observations" with a number of death, an exposition, and covariates.
Then I fit a Poisson Regression (generalised linear model, with expostion as offset).

A: The notes you posted explain why creating these pseudo-observations and fitting a Poisson log-linear regression (Poisson GLM with log-link) is equivalent to a piece-wise exponential survival model. They also note that it is valid to aggregate the pseudo-observations with equal covariates. This is mentioned at the very end of the "The Equivalent Poisson Model" section. So I will stick to the question about independence as it relates to these intervals.
Why doesn't creating many small interval observations out of one big interval observation in Poisson regression violate some independence assumption?
The key thing is that by assuming your response is Poisson distributed, you already assume something about the independence of these smaller intervals.
Suppose your data set were simpler, and all observations represented a single unit interval of time, say January - December 2020, and each row represented a different subject. And suppose your response variable were a discrete count of something for each observation within this interval of time. You decide to do some form of Poisson regression, having made the following assumptions about the data:

*

*Your response variable is a Poisson distributed random variable. That is, you are counting events which occur independently of one another at a fixed rate in the interval.

*Your observations are independent of one another. That is, you have pairs $(X_i, y_i)$, and each pair is independent.

You then decide to split Jack's row into two sub-intervals. You partition it into a January - June sub-interval, and a July - December sub-interval, and distribute the count of something between the sub-intervals based on whether each something happened in Jan-Jun, or Jul-Dec. Maybe you are doing this for fun, or maybe it is because there is some covariate you think is important which changes half-way through the year (which, note, implies that you think the rate changes midway through the original interval, and also that it wouldn't be possible to include this covariate in a regression using the original data).
You started with one observation $(X_j, y_j)$ for Jack, now you have two observations $(X_{j1}, y_{j1})$ and $(X_{j2}, y_{j2})$. It sure "feels like" these aren't independent. Indeed, $X_{j1}$ and $X_{j2}$ are definitely not independent, they will be necessarily identical on all the covariates which you could have included before splitting into sub-intervals. But crucially, $y_{j1}$ and $y_{j2}$ are independent, by assumption. It is a property of the Poisson distribution that the occurrences of something we are counting in the original interval are occurring independently from one another. So necessarily, the count of something for Jack in the Jan-Jun sub-interval is independent of the count of something for him in the Jul-Dec sub-interval. Again, you got this for free once you assumed the response was Poisson.
What about the fact that $X_{j1}$ and $X_{j2}$ are not independent? Aren't we pretending we have two observations, when really it is only one? Well, this is part of what the exposure offset is for. When we maximize likelihood in a Poisson regression without exposure offsets (constant duration intervals), the log-likelihood function we're maximizing looks like this:
$$\sum_i{y_i \log{\mu_i} - \mu_i}.$$
But when we have differing interval lengths and exposure offsets, it looks like this:
$$\sum_i{y_i \log{(\mu_ie_i)} - \mu_ie_i} = \sum_i{y_i\log{(\mu_i)} + y_i\log(e_i)} - \mu_ie_i.$$
Which rearranges as:
$$\sum_i{e_i\left(\frac{y_i}{e_i}\log{(\mu_i)} - \mu_i\right) + y_i\log(e_i)}$$
The term on the right doesn't depend on $\mu$ and so is irrelevant. So, our likelihood function is equivalent to the likelihood function of a Poisson regression with $y_i/e_i$ as the response, and $e_i$ as the weight. Conceptually we are standardizing the observed rate of occurrence so that all observations have the same measurement unit (observations per unit time), and then we are weighting each observation by the amount of time it represents.
All that is to say, if we partition Jack's interval into two equal length sub-intervals, then each interval is only being treated as half an observation.

A: If you want to divide the observation period for each subject into epochs you can use generalized estimating equations (GEE) to model this as a quasi-Poisson process while accounting for the correlation between subject measurements across epochs.  I don't think this is standard practice, though.  It might be more appropriate to adjust a cross-sectional Poisson model for baseline age or other factors to investigate if the mortality rate differs across groups.  In either model I recommend including an additional scale parameter or using the empirical sandwich covariance estimator when estimating standard errors.

A: The answer by @JonnyLomond answers your question as posed (+1), but also raises some questions about how you will do the modeling. You say:

For each interval of time, and for each set of similar age and other covariates, I compute the total exposition, and the number of deaths,

which suggests that you are binning continuous predictors like age, which is not usually a good idea. You generally are better off modeling individuals directly with their actual covariate values, then displaying results as desired for particular combinations of covariate values.
Also, it sounds like you might not be using time-interval-specific piecewise-constant hazards as in those notes, but rather a single constant baseline hazard for all your data (related to the intercept in the Poisson modeling). As the course notes you cite say (Section 7.2.2):

treating the deaths as Poisson conditional on exposure time leads to exactly the same estimates (and standard errors) as treating the exposure times as censored observations from an exponential distribution.

If you have a single intercept shared by all time intervals, you are thus assuming an exponential survival model, which doesn't always work well. Unless there's a compelling reason to force an exponential model onto the data, you might do better with a Cox model, which allows the data to tell you the form of the baseline survival function as well as the hazards associated with the covariates.
Your data seem already to be arranged in a way close to the counting-process format used to fit Cox models with time-varying covariates. From your description, each individual is evidently represented by multiple rows covering non-overlapping time intervals. During each time interval, the individual's covariate values, included in that row, are constant. Each row contains an indication of an event time. The only necessary change would seem to be to set the end time for the row with the event to the event time itself, with an indicator variable for the event.
The independence argument for the Poisson model does require that there be at most 1 event possible per individual* and that covariate values only change at time-interval boundaries. Under those assumptions, the argument holds more generally for proportional-hazards models. Under proportional hazards, an individual contributes to the (partial) likelihood at all event times in the data set while at risk. At each event time, however, only the instantaneous covariate values are used to estimate the relative hazards; covariate values at prior times are irrelevant, unlike for other approaches like accelerated failure time models. As the R time-dependent survival vignette explains (page 4):

One common question with this data setup is whether we need to worry about correlated data, since a given subject has multiple observations. The answer is no, we do not. The reason is that this representation is simply a programming trick. The likelihood equations at any time point use only one copy of any subject, the program picks out the correct row of data at each time.

If you need a fully parametric model for some reason, you can use tools provided by the R flexsurv or eha packages with counting-process data. The latter can take individual IDs into account in model types that require it.

*If an individual can experience more than 1 event, then you do have to take intra-individual correlations into account with methods like cluster variances, frailty terms, or a random-effects model.


text:
Q: Python Tkinter - Update while funtion in running I'm learning Tkinter by making a GUI for a sudoku solver program (that was arleady built).
On the click of a button, the algorithm that solves the sudoku runs and sometimes it takes some time.
How could I update the sudoku on the screen when the function is called, so that users can see how its running?
I'm working with a gui script separate from the sudoku one, is it correct, in design terms, to have the gui and the logic separate?
Thank in advance
EDIT
This is my code:
Sudoku.py
class Sudoku(object):
    def __init__(self):
        self.__matrix = [[(0, Status.Guess) for x in range(9)] for y in range(9)]
    ...
    def solveSudoku(self):
        ...

GUI.py
class App:

    def __init__(self, master, su):
        self.__sudoku__ = su
        self.__root__ = master
        self.__entries__ = {}
        fsudoku = Frame(master)
        fsudoku.grid(row=0)
        self.displaysudoku(fsudoku) """grid of entrys"""
        tButton = Button(master,text="Solve", command=self.SolveAndDisplay)
        ...

    def refreshSudokuGrid(self):
        """USED AFTER SOLVING A SUDOKU"""
        for i in range(1,10):
            for j in range(1,10):
                val = self.__sudoku__.value(i,j)
                self.__entries__[i * 10 +j].delete(0, END)
                if (val!= 0):
                    self.__entries__[i * 10 + j].insert(0, val)
    def SolveAndDisplay(self):
        self.scanSudoku()
        self.__sudoku__.solveSudoku()
        self.refreshSudokuGrid()
    ...

root = Tk()
su = Sudoku()
s = App(root, su)
root.mainloop()

A: I guess you must be using some loop which solves the sudoku.If this is true:
The place where your function/command for your button is defined,
place the following code at the beginning of the primary loop which solves the sudoku (assuming root is your tkinter window):
root.update()

As such such a method is not fully threadsafe, but should solve the problem for general cases like yours.
Keeping GUI and logic separate is the best practice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to pull or push using VS2017 in github I am pushing changes to github repository. I am getting below error
Error encountered while pushing to the remote repository: Git failed with a fatal error.
HttpRequestException encountered.
   An error occurred while sending the request.
cannot spawn askpass: No such file or directory
could not read Username for 'https://github.com': terminal prompts disabled

A: Your issue is discussed in detail in this thread
It appears that updating Visual Studio to version 2017 15.5.7 or later will fix this issue.


text:
Q: connecting DVI monitor to HDMI port Can I connect computer monitor with the case by using DVI to HDMI cable?
monitor side is DVI and the case side id HDMI.
I want to choose the correct cable for this connection.
My graphic card is 2 GB build in
Thanks

A: Yes, you need an adapter HDMI to DVI.
There are two kinds: HDMI male to DVI female, with this you will need a DVI cable.

And a HDMI female to DVI male, in this one you will need a HDMI cable.
For more information you should read this great answer about different ports, qualities and ways for connect them.


text:
Q: How to build join with condition in Phalcon I have the following SQL:
SELECT  `settings`.*, `character_settings`.`value`
FROM    `settings`
LEFT JOIN
       `character_settings`
ON     `character_settings`.`setting_id` = `settings`.`id`
        AND `character_settings`.`character_id` = '1'

How the same query can be rewritten using Phalcon  CreateBuilder() ?

A: Try something like this:
$rows = $this->modelsManager
             ->createBuilder()
             ->columns(array('Settings.*', 'CharacterSettings.value as char_value'))
             ->from('Settings')
             ->leftJoin('CharacterSettings', 'Settings.id = CharacterSettings.setting_id AND CharacterSettings.character_id  = 1')
             ->getQuery()
             ->execute();

foreach ($rows as $row) {
    print_r($row->settings->id . ' : ' . $row->char_value);
}

Don't forget to add db columns as fields to your models:
class Settings extends Phalcon\Mvc\Model
{
    public $id;

    public $name;

    ...


text:
Q: Feature allowing SO to execute code snippets in a sandbox and produce useful results I think a useful although grandiose feature would be to allow SO to run posted code snippets inside a secure sandbox (for various languages) for the purposes of: finding syntax errors, validating code, sometimes producing and posting actual results or output.
I would find this feature useful because I don't have all compilers frameworks and tools installed for which I would like to quickly try some of the unique stuff I see posted on SO. Also source code answers could be validated at deeper levels for weighting usability, etc. Also it might be great just to see the immediate results of code, inline with the posted answer, rather than mentally processing it.
The words "results" and "output" are used loosely here and could be anything from a parse tree to a step-through of code to actual console text or anything in between, whichever representation best suits the situation at hand. It could be automatic or chosen by the poster.
This feature request might seem really "out there" but it's fun to speculate about (well, for me). With recognition a lot of thought and work would have to go into it, but anything is possible if desirable.
One of the biggest challenges would be the fact code is often a fragment so running the native compiler would produce lots of errors. However syntax highlighting on SO is already a step in the right direction because it proves recognition of language features to a degree. Missing code might be mocked by a tool.

A: Its a fantastic idea, and I'm sure that it would see a lot of use, but it strikes me as something more suitable as a separate project.
It would have much wider uses than just StackOverflow but it would also be far from trivial, especially if you wanted to support a number of different languages.

A: http://codepad.org/ does this beautifully, for C, C++,  and a bunch of other languages.
This would be an excellent feature in SO.   A single click to launch the code in codepad.
the obvious problem with this is that code examples would no longer be optimally concise.   but good solution to this would be some form of highlighting.
currently  each line of code must be preceded by four spaces.
if you were to alter it thus:
    //TESTCODE:
    #include <math.h>

->  float mod(float a, float N)
->  {
->      float ret = a - N * floor (a / N);

    printf("%f.1 mod %f.1 = %f.1 \n", a, N, ret);

->      return ret;
->  }

    int main (char* argc, char** argv)
    {
        printf ("fmodf(-10.2, 2.0) = %f.1  == FAIL! \n\n", x);

        float x;
        x = mod(10.2f, 2.0f);
        x = mod(10.2f, -2.0f);
        x = mod(-10.2f, 2.0f);
        x = mod(-10.2f, -2.0f);

        return 0;
    }

SO's Display mechanism should know initially only to display highlighted lines prefixed by '->'
a faint horizontal  jagged line could indicate that there is hidden code not essential to understanding the answer.
there would be a button to toggle ' expand all /  collapse '
when everything is expanded, '->' lines would be in bold
The  first line: '//TESTCODE:'  tells SO  that this code is capable of being run in sandbox
so a second button 'test & run code snippet' would appear
when the user clicks on this, it could just open it up in CodePad.  SO  wouldn't even need to take the liability of malicious code attacks.
on which note, we could only allow users of > 100  to use this feature, and warn them that
usage is logged,  and they will lose their points AND/OR membership if they get caught trying to hack it.
then SO could allow users to gain points by fixing up code chunks everywhere.   and if they don't have permission to fix a particular chunk, they could flag it with a request, and  supplying a replacement,  and a senior user could look over it and allow it with a single click.
Remember, points are increasingly hard to come by now that the easy questions have been asked. So it would be great to allow users to establish themselves a basic reputation by doing little jobs like cleaning and tidying.
and linking posts!   but I will write separately on this as it is another topic.
another benefit of testable code is that it would also encourage contributors to supply code in usable units.

A: For Javascript, I typically use links to Google's Code Playground which allows you to execute Javascript code written in the browser. Very neat. I think a similar concept would be difficult to deploy for compiled languages that couldn't be compiled on the client's machine.

A: There's a project: JSBIN
www.jsbin.com that does this for javascript.
There's also a python interpreter written in javascript (pyjamas)
a C interpreter in javascript (ClueCC)
a ruby interpreter (hotruby)
a java compiler (gwt)
and others. However, unless the question is language or compiler specific, javascript is sufficient for questions about algorithms, and the vast swath of SO questions that actually are about javascript, or html, or other such things.

A: I'm pretty sure that such a sandbox would immediately become the site of the hottest new game of who can bypass the sandbox and compromise the machine. Plus, this would be a huge job to set up and support, and who would decide what languages, frameworks and environments get supported? There are so many different configurations, and a lot of SO questions are about these subtle differences between environments.
If you want to set up a prototype to demonstrate how it would work, knock yourself out, but I doubt anyone official with SO would spend any time with this.
PS. Sorry for being grumpy today. :(

A: There's also http://ideone.com/

What is ideone?
  Ideone is something more than a pastebin; it's an
  online compiler and debugging tool which allows to compile and run
  code online in more than 40 programming languages.


text:
Q: Case Hierarchy in lwc Hi I have to create a custom component in which i have to display the hierarchy of case.
Issue is only the first level hierarchy is display not the other level.
Apex
public with sharing class DynamicTreeGridController {
    @AuraEnabled(cacheable=true)
    public static List<Case> getAllParentAccounts(Id recordId) {
        return [SELECT CaseNumber, Type FROM Case WHERE Id =: recordId];
    }

    @AuraEnabled
    public static List<Case> getChildAccounts(Id parentId) {
        return [
            SELECT CaseNumber, Type
            FROM Case
            WHERE ParentId = :parentId
        ];
    }
}

HTML
<template>
    <div>
        <lightning-tree-grid
            columns={gridColumns}
            data={gridData}
            is-loading={isLoading}
            key-field="Id"
            ontoggle={handleOnToggle}
        ></lightning-tree-grid>
    </div>
</template>

JS
import { LightningElement, wire ,api} from "lwc";
import { ShowToastEvent } from "lightning/platformShowToastEvent";

// Import the schema
import CASENUMBER from "@salesforce/schema/Case.CaseNumber";

// Import Apex
import getAllParentAccounts from "@salesforce/apex/DynamicTreeGridController.getAllParentAccounts";
import getChildAccounts from "@salesforce/apex/DynamicTreeGridController.getChildAccounts";

// Global Constants
const COLS = [
    { fieldName: "CaseNumber", label: "Case Number" }
    // { fieldName: "CaseURL", label: "Case Number" , type: "url",
    // typeAttributes: { label: { fieldName: "CaseNumber" }, tooltip: "Name", target: "_blank"}}
    // { fieldName: "ParentAccountName", label: "Parent Account" },
    // { fieldName: "Type", label: "Account Type" }
];

export default class DynamicTreeGrid extends LightningElement {
    @api recordId;
    gridColumns = COLS;
    isLoading = true;
    gridData = [];
    finalData = [];

    @wire(getAllParentAccounts, {recordId: '$recordId'})
    parentAccounts({ error, data }) {
        if (error) {
            console.error("error loading accounts", error);
        } else if (data) {
            this.gridData = data.map((account) => ({
                _children: [],
                ...account
                //CaseURL: this.gridData.forEach(item => item['CaseURL'] = '/lightning/r/Case/' + item['Id'] + '/view')
                //ParentAccountName: account.Parent?.Name
            }));
            this.isLoading = false;
        }
    }

    handleOnToggle(event) {
        console.log(event.detail.name);
        console.log(event.detail.hasChildrenContent);
        console.log(event.detail.isExpanded);
        console.log('recordId=='+this.recordId);
        const rowName = event.detail.name;
        if (!event.detail.hasChildrenContent && event.detail.isExpanded) {
            this.isLoading = true;
            getChildAccounts({ parentId: this.recordId })
                .then((result) => {
                    console.log(result);
                    if (result && result.length > 0) {
                        const newChildren = result.map((child) => ({
                            _children: [],
                            ...child
                           // CaseURL: this.gridData.forEach(item => item['CaseURL'] = '/lightning/r/Case/' + item['Id'] + '/view')
                            //ParentAccountName: child.Parent?.Name
                        }));
                        this.gridData = this.getNewDataWithChildren(
                            this.recordId,
                            this.gridData,
                            newChildren
                        );
                    } else {
                        this.dispatchEvent(
                            new ShowToastEvent({
                                title: "No children",
                                message: "No children for the selected Account",
                                variant: "warning"
                            })
                        );
                    }
                })
                .catch((error) => {
                    console.log("Error loading child accounts", error);
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: "Error Loading Children Accounts",
                            message: error + " " + error?.message,
                            variant: "error"
                        })
                    );
                })
                .finally(() => {
                    this.isLoading = false;
                });
        }
    }

    getNewDataWithChildren(rowName, data, children) {
        return data.map((row) => {
            let hasChildrenContent = false;
            if (
                Object.prototype.hasOwnProperty.call(row, "_children") &&
                Array.isArray(row._children) &&
                row._children.length > 0
            ) {
                hasChildrenContent = true;
            }

            if (row.Id === rowName) {
                row._children = children;
            } else if (hasChildrenContent) {
                this.getNewDataWithChildren(this.recordId, row._children, children);
            }
            return row;
        });
    }
}


text:
Q: What Java class can I extend to? What Java class can I extend to so that I gain inheritance to treeTableView? How do I extend a class that is already extended?
I'm currently extending it using treeTableView.
The demo file shows this:
final TreeItem<User> root = new RecursiveTreeItem<User>(users, RecursiveTreeObject::getChildren);

This is what I tried working out, but it's not working:
final TreeItem<Patient> root = new Patient(patients, Patient::getChildren);

What do I do?

A: I extended the Person superclass to RecursiveTreeObject. Through inheritance it worked.


text:
Q: How to make monitor edges match on Windows 7 I have two screens. My primary screen is a 3840x2160 laptop screen. My secondary screen is a 1920x1080 monitor. The issue I'm having is that due to the screen resolutions, Windows thinks the laptop monitor is ~4x larger than the external monitor, when in reality the laptop monitor is physically smaller.
What I would like is for the left edges of my laptop monitor to match up with the right edges of the external monitor.
How can I do this?
Edit: Without lowering the resolution of my laptop monitor.

A: Natively, you can't get rid of the unaligned edges unless you set the displays to the same resolution, and align the displays (on the side they share) in the display properties.
The program DisplayFusion has an option to prevent bumping against edges when moving between monitors at different resolutions, as well as ones that are not aligned exactly.

I've been happily using DF for years to deal with multiple monitors, and it's handy as heck. :)

A: Right click on your desktop and click Screen Resolution. Then drag and drop the monitors around to let them match what your needs.


text:
Q: Is it safe to delete unused Parse frameworks from an Xcode project? I am making an iOS app that requires push notifications, and figured that Parse would be the simplest way to do what I wanted. Unfortunately though, when I went to the quick start guide on their website, the instructions say that I have to import all of the Parse libraries.
My question therefore is, since I only need Parse.framework and Bolts.framework, is it safe to delete the others such as ParseFacebookUtils.framework that are just consuming space?
I tried removing some of the unused ones from the Link Binary with Libraries stage and then building - which seems to work - but I'm not sure that this will remain the case when I submit the app.
UPDATE: So apparently, deleting the unused frameworks works just fine (at least it works on the device that I tested it on). Now it's just a matter of submitting the app and hoping that it works in the app store as well. If anybody has faced this problem before and has submitted their app, do let me know.

A: UPDATE: So apparently, deleting the unused frameworks works just fine (at least it works on the device that I tested it on). Now it's just a matter of submitting the app and hoping that it works in the app store as well.

A: You could also consider using CocoaPods to manage your dependencies so you don't have to worry about these kinds of things.
If you've never used it before take a look at their website. Its very straightforward and makes it easy to install dependencies.
All you would need in your podfile for Parse is 'pod 'Parse''


text:
Q: How to derive the height of this closed vessel?
A closed vessel tapers to a point both at its top $E$ and its bottom $F$, and is fixed with $EF$ vertical. When the depth of the liquid inside equals $x\,\mathrm{cm}$,the volume of the liquid equals $x^2(15-x)\,\mathrm{cm}^3$. Find the length $EF$.

Given the above information, how can I find the length $EF$?

A: The volume is maximal when the vessel is full. Deriving:
$$\frac{dV}{dx} = \frac{d(x^2(15-x))}{dx} = -3x^2 + 30 x$$
To obtain an extremum, the derivative must equal 0:
$$-3x^2 + 30 x = 0 \iff x = 5 \pm 5$$
We obtain a minimal volume of $0\,\mathrm{cm}^3$ for $x = 0$, and a maximal volume of $500\,\mathrm{cm}^3$ for $x = 10$. As such, the height of the vessel is $10\,\mathrm{cm}.$


text:
Q: Windows 7 backup to network location out of space I've got a domain of 10-15 Windows 7 computers that I don't have physical access to. They are using Windows Backup to only backup certain files (Desktop, Fav's, PST, things like that). The problem I'm having is that my server is running out of room. How can I set the backup to use, say, only 20gb, or to delete backups older than one month?

A: Create a batch file with the following command line:
forfiles -p "C:\path\path" -s -m . -d  -c "cmd /c del @path"
Schedule that file to be ran on a daily basis.


text:
Q: Google Drive to Tableau Is it possible to use Google BigQuery to channel Google Documents into Tableau? Is there another way to do this without downloading the documents from drive onto a local machine?

A: If you are using tableau 8.0, there is data connection item for Google BigQuery so i would say yes


text:
Q: Ask for Advice for a New Machine That Can Support GTX 590 and GTX 460 I plan to buy a new machine for running my algorithm implemented in GPU under CUDA. I currently have a GTX 460 graphics card, and may get a GTX 590 a few months later.
I am not sure which CPU, mainboard, memory, case, power, etc. I should use, so as to make the machine run well.
Could you give me some advice?

A: Here are some advices based on my experience (I've tested several configurations for our university HPC center):
There is no difference which CPU to use (Intel or AMD), while it have at least (N + 1) cores, where N is numbers of GPUs you have.
Memory -- not less than your GPUs have.
Motherboard: must have PCI-Express 2.0 x16 slot for each card. Bus bandwidth is often limiting factor. No SLI needed.
Case and power --- just general considerarions (for reference, typical GPU consumes ~200W).
Of course, all common rules apply, I've mentioned only GPU-specific ones.


text:
Q: php getting value from DIV tag I have a code like this.
<form id="mainForm" method="post" action="">

6.897882999999999, 79.92221100000006

<input id="submit" type="submit" name="submit" value="submit"/>
</form>

I want to assign div tag value (6.897882999999999, 79.92221100000006) to php variable using div id . Is it possible. if yes, how to do this. thanks

A: The easiest solution: http://simplehtmldom.sourceforge.net/
Alternatives: Robust and Mature HTML Parser for PHP


text:
Q: writing single query from multiple query i have a table reading with column
 [code]|[Test Mk]
  -----   -----
  1231  |  22.5
  1223  |  13.5
  1231  |  24.25
  1232  |  25.0
  ....    ....

when i Query like this
select [code], COUNT([code]) as Total
from reading
group by [code]

is shows this result
code    |Total
----     ----
1237    |728
1233    |698
1232    |701
1236    |651
1231    |655
1235    |626
1234    |636
1238    |685

again when i query like this
select [code], COUNT([code]) as FAIL
from Reading
where ROUND([Test Mk],0) < 24
group by [code]

results
code    | FAIL
----    | ----
1237    | 617
1233    | 422
1232    | 60
1236    | 81
1231    | 271
1235    | 517
1234    | 149
1238    | 69

again when i query like this
select [code], COUNT([code]) as PASS
from Reading
where ROUND([Test Mk],0) >= 24
group by [code]

result
code    | PASS
----    | ----
1237    | 111
1233    | 276
1232    | 641
1236    | 570
1231    | 384
1235    | 109
1234    | 487
1238    | 616

i want a  single query which generate result in this format
[code] | [Total] | [PASS] | [FAIL]
----     ----       ----     ----
 1231  |  125   |  100   |  25
 1232  |  200   |  150   |  50

how do i do this

A: You need to use Conditional Aggregation
To get the PASS count, just count the rows only when ROUND([Test Mk],0) >= 24. This can be achieved like this.
Count(Case when ROUND([Test Mk],0) >= 24 then 1 END)

To get the FAIL count, just count the rows only when ROUND([Test Mk],0) < 24. This can be achieved like this.
Count(Case when ROUND([Test Mk],0) < 24 then 1 END)

Case statements generates 1 only when the row satisfies the condition else it will place NULL. Count aggregate skips the NULL values while counting
As a whole query
select [code],
       COUNT([code]) as Total,
       Count(Case when ROUND([Test Mk],0) >= 24 then 1 END) as  PASS,
       Count(Case when ROUND([Test Mk],0) < 24 then 1 END) as FAIL
from reading
group by [code]

A: Another way with SUM:
SELECT  [code],
        COUNT([code]) as [Total],
        SUM(CASE WHEN ROUND([Test Mk],0) >= 24 THEN 1 ELSE 0 END) as [PASS],
        SUM(CASE WHEN ROUND([Test Mk],0) < 24 THEN 1 ELSE 0 END) as [FAIL]
FROM reading
GROUP BY [code]

Yet another one (weird):
;WITH [code] As(
    select [code], COUNT([code]) as Total
    from reading
    group by [code]
), [fails] AS (
    select [code], COUNT([code]) as [FAIL]
    from Reading
    where ROUND([Test Mk],0) < 24
    group by [code]
), [passed] AS (
    select [code], COUNT([code]) as [PASS ]
    from Reading
    where ROUND([Test Mk],0) >= 24
    group by [code]
)

SELECT  c.[code],
        c.[Total],
        f.[FAIL],
        p.[PASS]
FROM [code] c
LEFT JOIN [fails] f
    ON c.[code] = f.[code]
LEFT JOIN [passed] p
    ON c.[code] = p.[code]


text:
Q: rvest - remove tags and its content from HTML string Suppose I have the below text:
x <- "
I would like to run tests for a package with testthat and compute code coverage with covr. Furthermore, the results from testthat should be saved in the JUnit XML format and the results from covr should be saved in the Cobertura format.
\n\n
The following code does the trick (when getwd() is the root of the package):
\n\n
options(\"testthat.output_file\" = \"test-results.xml\")\ndevtools::test(reporter = testthat::JunitReporter$new())\n\ncov <- covr::package_coverage()\ncovr::to_cobertura(cov, \"coverage.xml\")\n
\n\n
However, the tests are executed twice. Once with devtools::test and once with covr::package_coverage.
\n\n
My understanding is that covr::package_coverage executes the tests, but it does not produce test-results.xml.
\n\n
As the title suggests, I would like get both test-results.xml and coverage.xml with a single execution of the test suite.
\n"

**PROBLEM: **
I need to do remove all  tags and its content, regardless if they are on its own or inside another tag.

I HAVE TRIED:
I have tried the following, but as you can see, the tags are still there:
content <- xml2::read_html(x) %>%
    rvest::html_nodes(css = ":not(code)")
print(content)

But the result I get is the following, and the tags are still there:
{xml_nodeset (8)}
[1] \n
I would like to run tests for a package with testthat and compute code coverage with cov ...
[2]
I would like to run tests for a package with testthat and compute code coverage with covr ...
[3]
The following code does the trick (when getwd() is the root of the package):

[4]
options("testthat.output_file" = "test-results.xml")\ndevtools::test(reporter = testthat::JunitReporter$new ...
[5]
However, the tests are executed twice. Once with devtools::test and once with covr::pac ...
[6] twice
[7]
My understanding is that covr::package_coverage executes the tests, but it does not produce test ...
[8]
As the title suggests, I would like get both test-results.xml and coverage.xml with a sin ...

A: The solution was the following:
  content <- xml2::read_html(x)

  toRemove <- content %>% rvest::html_nodes(css = "code")
  xml_remove(toRemove)

After that, content had no code tags, nor its content, and this wasn't manipulated as string.


text:
Q: "Robust" Noninjectivity of a Continuous Mapping of a Sphere into the Plane Let $X=\mathbb{S}^2$ and $Y=\mathbb{R}^2$ and $f:X\to Y$ a continuous mapping. Is it true that there must exist a nonempty set $V\subset f(X)$, open in $f(X)$ (in the subspace topology), such that each point of $V$ has at least two preimages under $f$?
Two followup questions:

*

*If the answer is negative, what additional assumptions can we place on $f$ to make the answer positive? For example, is it enough to assume that $f$ sends open sets in $X$ to sets with nonempty interior in $Y$?

*Is dimension 2 important here?


text:
Q: Querying Latest Available Partition in Athena I am building an ETL pipeline using primarily state machines, Athena, S3, and the Glue catalog. In general things work in the following way:

*

*A table, partitioned by "version", exists in the Glue Catalog. The table represents the output destination of some ETL process.

*A step function (managed by some other process) executes "INSERT INTO" athena queries. The step function supplies a "version" that is used as part of the "INSERT INTO" query so that new data can be appended into the table defined in (1). The table contains all "versions" - it's a historical table that grows over time.

My question is: What is a good way of exposing a view/table that allows someone (or something) to query only the latest "version" partition for a given historically partitioned table?
I've looked into other table types AWS offers, including Governed tables and Iceberg tables. Each seems to have some incompatibility with our existing or planned future architecture:

*

*Governed tables do not support writes via athena insert queries. Only Glue ETL/Spark seems to be supported at the moment.

*Iceberg tables do not support Lake Formation data filters (which we'd like to use in the future to control data access)

*Iceberg tables also seem to have poor performance. Anecdotally, it can take several seconds to insert a very small handful of rows to a given iceberg table. I'd worry about future performance when we want to insert a million rows.


text:
Q: rails infinate scrolling loads 2 times single page Hi i am trying to create a infinite scrolling in rails with pagination gem. no other specific gem i am using for this.it works fine with loading a content but i loads a single page means next page 2 times instead of one time. even the request to the server goes from the page only once response also only once but content is coming 2 times.
i have tried to look how it returning the content 2 times but unable to find how it's working. some one can help me ??
JS to send a request for a 2nd page while Scrolling the page
$(window).on 'scroll', ->
    more_posts_url = $('.pagination .next_page').attr('href')
    if more_posts_url && $(window).scrollTop() > $(document).height() - $(window).height() - 60
      $('.pagination').html('
Loading......
')
      $.ajax more_posts_url,
      type: 'get'
      dataType: 'script'
    return

the controller where the request will received
 def show
@follow_unfollow = FollowerDetail.new
@songs = Song.user_filter(@user.id).paginate(:page => params[:page], :per_page => 2)
respond_to do |format|
    format.html { }
    format.js { }
end

end
the response JS from this controller
$('#my_songs').append("<%= j render partial: 'songshow' , :collection => @songs %>");
<% if @songs.next_page %>
   $('#infinite-scrolling').replaceWith('<%= j will_paginate @songs %>');
<% else %>
   $('.pagination').remove();
<% end %>


text:
Q: Allow user to select background from personalize screen In my widget, I want the user to be able to set the background of the main page by selecting a picture from their gallery and then that image would also show up in a imageView on the personalize screen (so they know what the image will look like).
So far, I have the imageView set up on the personalize page:
<?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="vertical" >

<TextView
    android:id="@+id/personalizetextView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/customize"
    android:textSize="30dip"
    android:gravity="center"
    android:layout_marginTop="20dip"/>

<TextView
    android:id="@+id/personalizetextviewChangeBackground"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/customizebackground"
    android:gravity="center" />

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/pattern1" />

<Button
    android:id="@+id/btnChangeImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/change_background" />

</LinearLayout>

When the btnChangeImage is selected, it leads the user to the gallery, as seen here:
package com.example.awesomefilebuilderwidget;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class Personalize extends Activity{
Button button;
ImageView image;
private static final int SELECT_PICTURE = 1;
private String  selectedImagePath;

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

    addListenerOnButton();

}

public void addListenerOnButton() {

    image = (ImageView) findViewById(R.id.imageView1);

    button = (Button) findViewById(R.id.btnChangeImage);
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, SELECT_PICTURE);
        }

        public void onActivityResult(int requestCode, int resultCode, Intent data)
            {
                if (resultCode == RESULT_OK) {
                    if (requestCode == SELECT_PICTURE)
                    {
                        Uri selectedImageUri = data.getData();
                        selectedImagePath = getPath(selectedImageUri);
                        try {
                            FileInputStream fileis=new FileInputStream(selectedImagePath);
                            BufferedInputStream bufferedstream=new BufferedInputStream(fileis);
                            byte[] bMapArray= new byte[bufferedstream.available()];
                            bufferedstream.read(bMapArray);
                            Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
                            //Here you can set this /Bitmap image to the button background image

                            if (fileis != null)
                            {
                                fileis.close();
                            }
                            if (bufferedstream != null)
                            {
                                bufferedstream.close();
                            }
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        public String getPath(Uri uri) {
                String[] projection = { MediaStore.Images.Media.DATA };
                Cursor cursor = managedQuery(uri, projection, null, null, null);
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            }

    });

}

}

How can I make it so that when the image is selected, that image shows up in the imageview? Then, whatever image is set up in the imageview becomes the background of the main file?
Right now on the main page, I just have a default image set up:
android:background="@drawable/pattern1"

A: Set your image from ActivityResult to ImageView:
image.setImageBitmap(bMap);

Save this image so you can use it again or in your main activity:
public boolean saveImageToInternalStorage(Bitmap image) {
   try {
      FileOutputStream fos = context.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
      image.compress(Bitmap.CompressFormat.PNG, 100, fos);
      fos.close();
      return true;
   } catch (Exception e) {
   return false;
   }
}

Load your image:
public Bitmap getThumbnail(String filename) {
   Bitmap thumbnail = null;
   try {
      File filePath = context.getFileStreamPath(filename);
      FileInputStream fi = new FileInputStream(filePath);
      thumbnail = BitmapFactory.decodeStream(fi);
   } catch (Exception ex) {
   Log.e("getThumbnail() on internal storage", ex.getMessage());
   }
   return thumbnail;
}

Set the loaded image as Background in your main page:
Drawable d = new BitmapDrawable(getResources(),bitmap);
yourBackgroundView.setBackground(d);


text:
Q: Continue a "ctrl-z"-ed job in background Is it possible to continue a stopped background job in background?
I have a process running, I used ctrl-z to stop it and return to bash. If I want to continue it, there's fg command available but that brings the job back to front. Is it possible to keep it in background but running, like it would have been run with & in the first place.

A: bg
See also "JOB CONTROL" in bash's manual page.


text:
Q: Limit a number of digits in expression Could you please help me write a regexp to limit humber of digits to 10 in a string (a telephone number). The problem is that we allow hyphens ("-") and spaces between the digit groups, so I can't just go with /^\d{10}$/.
So the number could be 1234 123 123, or 123-123-1234 or 1234234123, with only limitation of 10 digits.

A: Rather than a regular expression alone, use preg_replace() to strip out non-digit characters ([^\d]) and verify that the resultant string (digits only) length is ten:
if (strlen(preg_replace('/[^\d]/', '', $number)) !== 10) {
   // invalid
}

A: Check the value of your regex with strlen to make sure that you got the right data from the string:
<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
?>

A: Or without using regex:
<?php
  $v = "123-123-1234";
  $items = array();
  for ($i = 0; $i < strlen($v); $i++) {
     if ($v[$i] <= '9' && $v[$i] >= '0') {
       $items[] = $v[$i];
       if (count($items) == 10)
         break;
     }
  }
  print_r($items);
?>

A: $phone="92-456-asd-445";
$digits = preg_replace("[^0-9]", "",$phone); //92456445

if (strlen($digits)>10){
    echo "Bye";
}
else{
    echo "Hi";
}

A: "So the number could be 1234 123 123, or 123-123-1234 or 1234234123, with only limitation of 10 digits."
In this example "44" part is breaking limitation;
$i = 0;
$s = "1234 567 890-44";
preg_match_all("/(\d+|-+| +)/", $s, $ms);
foreach ($ms[0] as $m) {
    if (is_numeric($m)) {
        $i += strlen($m);
    }
}

echo $i ."\n";
if ($i > 10) {
    echo "limit exceed!";
}


text:
Q: How to install Beta Version of Jetpack Compose in Android Studio sorry if this question is not smart, I'm complete new to Android Studio. How can you install the beta version of Jetpack Compose in your App? Thanks for your answers.
Boothosh

A: Follow the instructions here: https://developer.android.com/jetpack/compose/setup
Also, make sure you're using the Canary version of Android Studio, which can be downloaded here: https://developer.android.com/studio/preview


text:
Q: loadHTML LIBXML_HTML_NOIMPLIED on an html fragment generates incorrect tags Using the LIBXML_HTML_NOIMPLIED flag with an html fragment generates incorrect tags:
$str = '
Lorem ipsum dolor sit amet.

Nunc vel vehicula ante.
';
$doc = new DOMDocument();
$doc->loadHTML($str, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
echo $doc->saveHTML();

Outputs:

Lorem ipsum dolor sit amet.
Nunc vel vehicula ante.

I have found hacks to work around this using regexes, but that defeats the purpose of using DOM. I have tested this with several versions of libxml and php, the latest with libxml 2.9.2, php 5.6.7 (Debian Jessy). Any suggestions appreciated.

A: The re-arrangement is done by the LIBXML_HTML_NOIMPLIED option you're using. Looks like it's not stable enough for your case.
Also you might want to not use it for portablility reasons, for example I've got one PHP 5.4.36 with Libxml 2.7.8 at hand that is not supporting LIBXML_HTML_NOIMPLIED (Libxml >= 2.7.7) but later LIBXML_HTML_NODEFDTD (Libxml >= 2.7.8) option.
I know this way of dealing with it. When you load the fragment, you wrap it into a
 element:
$doc->loadHTML("
$str
");

This helps to guide DOMDocument on the structure you want.
You can then extract this container from the document itself:
$container = $doc->getElementsByTagName('div')->item(0);
$container = $container->parentNode->removeChild($container);

And then remove all children from the document:
while ($doc->firstChild) {
    $doc->removeChild($doc->firstChild);
}

Now the document is completely empty and you're now able to append children again. Luckily there is the
 container element we removed earlier, so we can add from it:
while ($container->firstChild ) {
    $doc->appendChild($container->firstChild);
}

The fragment then can be retrieved with the known saveHTML method:
echo $doc->saveHTML();

Which gives in your scenario:

Lorem ipsum dolor sit amet.

Nunc vel vehicula ante.

This methodology is a little different from the existing material here on site (see the references I give below), so the example at once:
$str = '
Lorem ipsum dolor sit amet.

Nunc vel vehicula ante.
';

$doc = new DOMDocument();
$doc->loadHTML("
$str
");

$container = $doc->getElementsByTagName('div')->item(0);
$container = $container->parentNode->removeChild($container);
while ($doc->firstChild) {
    $doc->removeChild($doc->firstChild);
}

while ($container->firstChild ) {
    $doc->appendChild($container->firstChild);
}

echo $doc->saveHTML();

I also really recommend the reference question on How to saveHTML of DOMDocument without HTML wrapper? for a further read as well as the one about inner-html
References

*

*How to saveHTML of DOMDocument without HTML wrapper?

*How to get innerHTML of DOMNode?

A: The LIBXML_HTML_NOIMPLIED option is not buggy, it's just badly documented.
To fix the problem, wrap your input string with …, process your HTML, and then strip that off the output. LibXML requires a root node, and is treating the first element it finds as the root node, deleting the (incorrectly located) closing tag it finds half-way through, and then outputting the closing tag of the first element it found at the end of the document. It's logical when you see it from (Lib)XML's perspective.


text:
Q: SQL - create table via join and show who is not in it in one table I have three tables:

*

*customer (id, name, email)

*product (id, product_category, material, price, purchase_id)

*purchase (id, purchase_date, customer_id)

My task: show the name of the customer and the number of purchases they made - this column should be called purchase_count. Sort the results by number of purchases, starting with the customer with the most purchases.
Please note that some customers may not have made any purchases yet. In such a situation, you should display 0 for the number of purchases.
I am trying to create a view such as:
name, purchase_count

This is my code so far. I don't think its correct:
WITH CLIENTS_BUYS AS
(
    SELECT -- (NULL FOR THE CLIENTS WHO HAVE NOT MADE PURCHASE SHOW AS '0' HAVE NOT BEEN SHOWN IN THIS QUERY)
        CU.name, -- SO I TRIED TO USE 'CTE'
        CU.id,
        COUNT(CASE WHEN PU.id IS NOT NULL THEN PU.id ELSE CU.id END) AS PURCHASE_COUNT
    FROM
        purchase PU
    JOIN
        customer CU ON CU.id = PU.customer_id
    JOIN
        product PR ON PR.purchase_id = PU.id
    WHERE
        customer_id IS NOT NULL
        OR customer_id IS NULL
    GROUP BY
        CU.name, CU.id
),
CLIENTS_NOT_BUYS AS
(
    SELECT
        CU.name,
        CU.id,
        COUNT(CASE WHEN PU.id IS NULL THEN PU.id ELSE CU.id END) AS PURCHASE_COUNT
    FROM
        purchase PU
    JOIN
        customer CU ON CU.id = PU.customer_id
    JOIN
        product PR ON PR.purchase_id = PU.id
    WHERE
        CU.id IN (SELECT customer_id
                  WHERE CU.id != PU.customer_id)
    GROUP BY
        CU.name, CU.id
)
SELECT
    name,
    PURCHASE_COUNT
FROM
    CLIENTS_NOT_BUYS
JOIN
    CLIENTS_BUYS ON CLIENTS_BUYS.id = CLIENTS_NOT_BUYS.id
GROUP BY
    name
ORDER BY
    PURCHASE_COUNT DESC

One issue is purchase_id in the product has NULL for one or some customers. But via join the customers who has NULL in purchase_id have not been presented in the first query.
So, I tried to use CTE but it seems not a working query and I think that I am doing it too difficult because there should be an easier way than I do. Also tried LEFT JOIN but it didn't work.
In the last part select. where I a, trying to join CLIENTS_NOT_BUYS and CLIENTS_BUYS => I get an error

Errors near name and PURCHASE_COUNT
Ambiguous column name

I don't know how to make it work...
This is the result of first select inside the CTE CLIENTS_BUYS without ORDER BY:
name            id  PURCHASE_COUNT
-----------------------------------
Alba Gomez       5      1
Amira Palmer     3      2
Anna Smith       7      2
Charlee Freeman  1      5
Christina Rivas  2      1
Michael Doe      6      2

But I don't know how to show others with NULL in purchase_id and add them at the bottom with '0' in PURCHASE_COUNT to continue the table

A: You need a FULL OUTER JOIN to get all values from all name in buys and not buys
WITH CLIENTS_BUYS AS(
SELECT -- (NULL FOR THE CLIENTS WHO HAVE NOT MADE PURCHASE SHOW AS '0' HAVE NOT BEEN SHOWN IN THIS QUERY)
    CU.name, -- SO I TRIED TO USE 'CTE'
    CU.id,
    COUNT(CASE WHEN PU.id IS NOT NULL THEN PU.id ELSE CU.id END) AS PURCHASE_COUNT
FROM purchase PU
    JOIN customer CU
    ON CU.id = PU.customer_id
    JOIN product PR
    ON PR.purchase_id = PU.id
WHERE customer_id IS NOT NULL
    OR customer_id IS NULL
GROUP BY CU.name,CU.id
),
CLIENTS_NOT_BUYS AS (
SELECT
    CU.name,
    CU.id,
    COUNT(CASE WHEN PU.id IS NULL THEN PU.id ELSE CU.id END) AS PURCHASE_COUNT
FROM purchase PU
    JOIN customer CU
    ON CU.id = PU.customer_id
    JOIN product PR
    ON PR.purchase_id = PU.id
WHERE CU.id IN (
    SELECT customer_id
    WHERE CU.id != PU.customer_id
    )
GROUP BY CU.name,CU.id
)
SELECT
    COALESCE(CLIENTS_NOT_BUYS.name,CLIENTS_NOT_BUYS.name) name,
    CLIENTS_BUYS.PURCHASE_COUNT AS BUYS_PURCHASE_COUNT,
    CLIENTS_NOT_BUYS.PURCHASE_COUNT  AS NOT_BUYS_PURCHASE_COUNT
FROM CLIENTS_NOT_BUYS
    FULL OUTER JOIN CLIENTS_BUYS
    ON CLIENTS_BUYS.id = CLIENTS_NOT_BUYS.id
ORDER BY CLIENTS_BUYS.PURCHASE_COUNT DESC

A: I think a left join should work here
SELECT name, case when PURCHASE_COUNT is null then 0 else PURCHASE_COUNT  end as PURCHASE_COUNT
from(
SELECT CU.name
       COUNT(distinct PU.id) AS PURCHASE_COUNT
FROM customer CU
LEFT JOIN   purchase PU
on CU.id = PU.customer_id
GROUP BY CU.name, CU.id
) group by name order by 2 desc

If the customer doesn't have any purchase, the left should give you an empty PU.id. I think PU.id is a unique id for each purchase. Like transaction ID.


text:
Q: Why does this JOIN query work in shell and not in php? Cannot seem to find a post addressing this particular issue.  The SQL query (as below) works fine when I execute from shell but in php it is throwing an undefined index.  I think the problem is that it is not recognising the disambiguation of attributes when in php.
Error I get in php is:

Notice: Undefined index: s.RowNumber in
  /home/xx/xx/xxx/xxx/checkAvailability.php on line 14.

Code:
<?php
include'connect.php'
?>
    <form method="post" action="chooseDate.php">
    <?php
    $sql = "SELECT s.RowNumber
            FROM Seat AS s LEFT JOIN Booking AS b
            ON s.RowNumber = b.RowNumber
            AND b.PerfDate = '2016-12-12'
            AND b.PerfTime = '20:30:00'
            WHERE b.RowNumber IS NULL";
    $handle = $conn->prepare($sql);
    $handle->execute();
    $res = $handle->fetchAll();
        foreach($res as $row) {
            echo "<input name='Seat' type='checkbox' value=".$row['s.RowNumber']."><br>";
        }
    ?>
    <input class="mybutton" type="submit" value="Choose Date"/>
    </form>

Can anyone elaborate on the problem?  Thanks in advance.

A: You must use $row['RowNumber'] in your foreach loop. s. is just the table alias, you should ignore it.

A: Try giving an alias to s.RowNumber and use it in the echo statement


text:
Q: echo and cat-supresses the new line characters Below is the example.I can see that when i use echo with cat it suppresses the new line characters.Is this the expected behaviour?I am working on solaris unix.
   .262> cat temp2.txt
    20110801
    20110802
    20110803
    20110804
    20110805
    20110808
    > echo `cat temp2.txt `
    20110801 20110802 20110803 20110804 20110805 20110808

A: Yes this is the expected behaviour.
But as "Mark Reed" suggested you can keep the white space by using quotes:
echo "$(cat temp2.txt)"

A: Yes this is expected behavior.
I don't know of any shell that doesn't do it.
It is documented in bash:
 $ man bash | awk '/Command Substitution/ { p = 1 } /Arithmetic Expansion/ { p = 0 } { if (p) print; }'

In zsh:
$ man zshall | awk '/COMMAND SUBSTITUTION/ {p=1} /ARITHMETIC EXPANSION/ {p=0} { if (p) print }'

(Edit: I removed the output of the command lines as they are pointless, as pointed out by @sehe in the comment)


text:
Q: Вопрос по .htaccess - преобразование url (mod_rewrite и все такое) Помогите, пожалуйста, правильно составить .htaccess.
У меня вот такого вида ссылки:
http://zzz.net/index.php?sort=id&q=zzz
http://zzz.net/index.php?sort=rating&q=zzz
http://zzz.net/index.php?sort=date&q=zzz
http://zzz.net/index.php?sort=view&q=zzz
http://zzz.net/index.php?sort=comment&q=zzz
http://zzz.net/index.php?category=vbs
http://zzz.net/?post=17
http://zzz.net/?p=1
http://zzz.net/?p=1&sort=rating
http://zzz.net/?p=1&sort=date
http://zzz.net/?p=1&sort=view
http://zzz.net/?p=1&sort=comment
http://zzz.net/index.php?q=%D0%BE%D0%BB%D0%BE%D0%BB
http://zzz.net/index.php?p=1&q=%D0%BE%D0%BB%D0%BE%D0%BB
http://zzz.net/index.php?sort=id&q=%D0%BE%D0%BB%D0%BE%D0%BB
http://zzz.net/index.php?sort=rating&q=%D0%BE%D0%BB%D0%BE%D0%BB
http://zzz.net/index.php?p=1&sort=rating&q=%D0%BE%D0%BB%D0%BE%D0%BB
http://zzz.net/index.php?p=1&sort=date&q=%D0%BE%D0%BB%D0%BE%D0%BB
http://zzz.net/index.php?p=1&sort=view&q=%D0%BE%D0%BB%D0%BE%D0%BB
http://zzz.net/index.php?p=1&sort=comment&q=%D0%BE%D0%BB%D0%BE%D0%BB

Хочу сделать их вида:
http://zzz.net/p/1/sort/comment/q/%D0%BE%D0%BB%D0%BE%D0%BB

Все запросы у меня идут к файлу index.php, а он, в свою очередь, выдает тот или иной шаблон.
Раньше не работал с mod_rewrite, поэтому не знаю, как правильно организовать.
Если у вас есть любые примеры, пишите их тут, все пригодятся.
А можно ли обойтись без mod_rewrite и генерировать с помощью php?
В общемб у меня очень много вопросов. Помогите, пожалуйста, ответить хотя бы на часть из них :)
A: RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/([^/]*)/([^/]*)\$ /index.php?p=$1&sort=$2&q=$3 [L]

На начальном этапе воспользуйтесь генератором.
В дальнейшем, если возникнут конкретные вопросы, пишите.


text:
Q: How to add contents of HTML file to page dynamically from a Chrome extension? From withing a Chrome extension, what's the best way to conditionally add the contents of an .html file to a page. Like you don't want to always add it, only if certain conditions are met. I see ways to conditionally inject script, but how can I conditionally add HTML from a file in the extension into the page?
If I have an option turned on, I want to add a block of code.
read option:
this.get_options = function ()
{
    chrome.storage.sync.get({
        mytopics: true,
        friendtopics: true
    }, function(items) {
        self.settings = items;
        scan_page();
    });
}

this.scan_page = function()
{
    if (!(self.settings.mytopics || self.settings.friendtopics))
        return;
    // want to add in a decent amount of HTML from a file, here.
    // don't really want to construct it all via createnode calles
}

A: Figured this out.
$('body').append('

');
$('#containerName').load(chrome.extension.getURL("markup/notification.html"));


text:
Q: Is there a way to quickly search the web via Spotlight? On macOS, you can use Spotlight to quickly do a web search of your query through hotkeys by pressing CMD + B.
Is there any equivalent functionality in iPadOS?
Using a Bluetooth keyboard, I have tried the same hotkey on iPadOS 13.1.2 with no luck. Pressing Enter after typing a query in Spotlight brings up the first result, but I would specifically like it to bring up a web search in Safari's default search engine.


text:
Q: writing a tkinter scrollbar for canvas within a class I've searched around and cannot seem to find an answer for my problem. I am trying to create a working scrollbar for the following code and cannot seem to get it to work. The problem appears to be with the OnFrameConfigure method. I have seen elsewhere that the method should be def OnFrameConfigure(event):however when I place the (event) part into my method it does not work unless I write the function outside of a class
 class Main(tk.Tk):

    def __init__(self, *args, **kwargs):
        '''This initialisation runs the whole program'''

        #tk.Tk.__init__(self, *args, **kwargs)
        main =  tk.Tk()
        canvas = tk.Canvas(main)
        scroll = tk.Scrollbar(main, orient='vertical', command=canvas.yview)
        canvas.configure(yscrollcommand=scroll.set)
        frame = tk.Frame(canvas)
        scroll.pack(side='right', fill='y')
        canvas.pack(side='left', fill='both', expand='yes')
        canvas.create_window((0,0), window=frame)
        frame.bind('<Configure>', self.OnFrameConfigure(parent=canvas))

        for i in range(100):
            tk.Label(frame, text='I am a Label').pack()

        main.mainloop()

    def OnFrameConfigure(self, parent):
        '''Used to allowed scrolled region in a canvas'''
        parent.configure(scrollregion=parent.bbox('all'))

A: Your problem starts here:
frame.bind('<Configure>', self.OnFrameConfigure(parent=canvas))

You are immediately calling the OnFrameConfigure function. That is not how you use bind. You must give a reference to a callable function. Since you're using a class, you don't need to pass parent in, unless you have this one function work for multiple widgets.
Change the binding to this:
frame.bind('<Configure>', self.OnFrameConfigure)

Change the method definition to this:
def OnFrameConfigure(self, event):

Finally, your __init__ needs to save a reference to the canvas, which you can then use in that function:
def __init__(self, *args, **kwargs):
    ...
    self.canvas = tk.Canvas(...)
    ...

...
def OnFrameConfigure(self, event):
    ...
    self.canvas.configure(scrollregion=self.canvas.bbox('all'))
    ...


text:
Q: Upload an image NOT recompressed during transfer - iOS Objective c Currently I am able to post an image to imGur using their API with the following code:
NSString *clientID = @"myID";
NSString *XMashapeKey = @"mySecretID";

NSMutableCharacterSet *allowedCharacterSet = [NSMutableCharacterSet alphanumericCharacterSet];
        [allowedCharacterSet addCharactersInString:@"-._~"];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"myImage.jpg"], 1.0);
NSString *base64Img = [imageData base64EncodedStringWithOptions:0];
NSString *escapedBase64 = [base64Img stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.imgur.com/3/upload"]];
    [request setHTTPMethod:@"POST"];

NSString *postString = [NSString stringWithFormat:@"image=%@", escapedBase64];

[request setValue:XMashapeKey forHTTPHeaderField:@"X-Mashape-Key"];
[request setValue:[NSString stringWithFormat:@"Client-ID %@", clientID] forHTTPHeaderField:@"Authorization"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody: [postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (error) {
        NSLog(@"%@", error);
    }
    else {
        NSLog(@"%@", response);
        id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@", obj);
    }
}];
[task resume];

The problem is that it encodes it in base64 prior to making the request (from what I could see in similar posts we are forced to). I want to upload "myImage.jpg" to whatever free storage service that has an API but I DON'T want the image to be altered in any way. This isn't a quality problem, but I am performing steganography on the image prior to uploading it so I really need it not to be modified. I just need to upload it and to receive its link when the upload is completed. Any way to do this ?
Thanks.

A: Maybe try upload the image binary data instead of base64? Sorry I can't comment so I just wrote this as an answer. Here is the link.
Please be sure change the name=(the example is fileupload): [postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileupload\"; filename=\"%@\"\r\n", file]dataUsingEncoding:NSUTF8StringEncoding]]; from the api accordingly.

A: For anyone also struggling with this.... Using google's API Firebase did the trick.
 //Points to the root reference
FIRStorageReference *storageRef = [[FIRStorage storage] reference];
// File located on disk
NSURL *localFile = [NSURL fileURLWithPath:@"your/local/path"];

// Create a reference to the file you want to upload
FIRStorageReference *riversRef = [storageRef child:@"your/path/in/firebase/server/yourimage.jpg"];

// Upload the file to
FIRStorageUploadTask *uploadTask = [riversRef putFile:localFile metadata:nil completion:^(FIRStorageMetadata *metadata, NSError *error) {
    if (error != nil) {
        // Uh-oh, an error occurred!
    } else {
        // Metadata contains file metadata such as size, content-type, and download URL.
        NSURL *downloadURL = metadata.downloadURL;
        // NSLog(@"%@", downloadURL);
    }
}];


text:
Q: How can I get many integers from the same text field? I want to retrieve several integers from the same text field, but I can't figure out how to do it. Anyone?

A: Here is a clearer solution.  This will throw and error for incorrect input.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication37 extends Application {

    @Override
    public void start(Stage primaryStage) {
        Label info = new Label("Enter some numbers. Each seperated by one space");

        TextField tf = new TextField();
        Label label = new Label();

        Button btn = new Button();
        btn.setText("Sum Numbers");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                if(tf.getText().length() > 0)//Only run if the text field is not empty
                {
                    String[] stringOfNumbers = tf.getText().split(" ");//The numbers must be seperated by one space. This get the string of numbers and seperates them based on the space between each numbers

                    //sum up the numbers
                    double sum = 0;
                    for(int i = 0; i < stringOfNumbers.length; i++)
                    {
                        sum = sum + Double.parseDouble(stringOfNumbers[i]);//This sums the numbers and convert the strings to doubles
                    }
                    label.setText("The sum equals: " + sum);//This prints the sum of the doubles
                }
            }
        });

        VBox root = new VBox();
        root.getChildren().addAll(info, tf, label, btn);//This adds all the nodes to the VBox

        Scene scene = new Scene(root, 300, 250);//This adds the VBox to the Scene

        primaryStage.setTitle("Sum Numbers");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}

I noticed this question asked to handle integers. In this code change double to int and Double to Integer.

I am adding this solution since your solution did not contain a button
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication37 extends Application {

    @Override
    public void start(Stage primaryStage) {
        Label info = new Label("Enter some numbers each seperated by one space");
        Label label = new Label();

        TextField tf = new TextField();
        tf.textProperty().addListener((observable, oldValue, newValue) -> {
            try
            {
                if(newValue.length() > 0)//Only run if the text field is not empty
                {
                    String[] stringOfNumbers = tf.getText().split(" ");//The numbers must be seperated by one space. This get the string of numbers and seperates them based on the space between each numbers

                    //sum up the numbers
                    int sum = 0;
                    for(int i = 0; i < stringOfNumbers.length; i++)
                    {
                        sum = sum + Integer.parseInt(stringOfNumbers[i]);//This sums the numbers and convert the strings to doubles
                    }
                    label.setText("The sum equals: " + sum);//This prints the sum of the doubles
                }
                else
                {
                    label.setText("");//if no text in textfield set label to empty string
                }
            }
            catch(NumberFormatException ex)
            {
                label.setText("");//any number format error set label to empty string
            }
        });

        VBox root = new VBox();
        root.getChildren().addAll(info, tf, label);//This adds all the nodes to the VBox

        Scene scene = new Scene(root, 300, 250);//This adds the VBox to the Scene

        primaryStage.setTitle("Sum Numbers");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}


text:
Q: AngularJS -> Java: POST/PUT request results in 'Preflight request doesn't pass access control check' From searching around for the issue I have figured out this has to do with CORS. I'm not sure what the best way to solve it would be.
I have a Java web service running that has various GET/POST/PUT/DELETE resources. It is a dropwizard application that uses jersey/jax-rs. I decided to build a GUI app for it using AngularJS. I can make a GET request fine but when I try to make a POST or PUT request I get this error:

Response to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

The part of the angular code making the PUT looks like this:
$http.put(url, data).
then(function(response) {
    $scope.message = response.data;

It is being served with express:
var express = require('express'),
    app = express(),
    bodyParser = require('body-parser'),
    morgan = require('morgan'),
    path = require('path');

app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json());

app.use(function(req, res, next) {   res.setHeader('Access-Control-Allow-Origin', '*');   res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');   res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, Authorization, Accept');   next(); });

app.use(express.static(__dirname + '/app'));

app.get('*', function(req, res) {   res.sendFile(path.join(__dirname + '/index.html')); });

app.listen(8080); console.log("running on 8080");

As mentioned, the Java service has different resources, for example:
@PUT
@Path("/insert/{operation}/{id}")
@Produces(MediaType.TEXT_PLAIN)
public Response addEntry ...

And as part of the response I added some headers that other posts/questions suggested:
public static Response success(String content) {
    CustomResponse skeletonRsponse = response(content);
    return Response.status(Status.OK).entity(skeletonRsponse.getContent())
        .header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
        .build();
}

But the error persists.
I noticed from looking at the server logs that the request from the Angular app is being sent as

[25/Jan/2018:00:11:49 +0000] "OPTIONS..."

rather than "PUT..."
From my understanding of CORS and how angular $http works (which is limited) a 'OPTIONS' request is sent and if all is good there then the actual request is sent. So what should I do about this? One thought I had was to make @Options resources that return the proper headers but that seems like it would not be optimal since I'd have to create one for each existing resource to make up with the right paths.
Any help is greatly appreciated!

A: The HTTP OPTIONS method is used to describe the communication options for the target resource. Refer link.
OPTIONS request doesn't need to be implemented. Just try adding OPTIONS in header value of "Access-Control-Allow-Methods" in your response.

A: Use org.eclipse.jetty.servlets.CrossOriginFilter. This is Kotlin code but i think you can sort it out:
override fun run(configuration: BackendConfig, environment: Environment) {
    // ...
    addServletFilter(CrossOriginFilter::class.java, environment).apply {
        setInitParameter("allowedOrigins", "*")
        setInitParameter("allowedHeaders", "Content-Type,Accept,Origin," + CsrfProtectionFilter.HEADER_NAME)
        setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD")
    }
}

private fun addServletFilter(filterClass: Class<out Filter>, environment: Environment): FilterRegistration.Dynamic {
    val filter = environment.servlets().addFilter(filterClass.simpleName, filterClass)
    filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType::class.java), true, environment.jersey().urlPattern)
    return filter
}

PS. I'm actually about to create a "filters" bundle that configures useful filters in DropWizard with reasonable defaults, but it's not ready yet!


text:
Q: Difference between this two programs Assume the 2 following programs :
public class Main {

    private static boolean test= false;

    public static void main(String[] args) {
        if(test)
            method1();
    }

    private static void method1() {
        //Some stuff
        method2();
    }

    private static void method2() {
        //Some stuff
    }

}

   public class Main {

        private final static boolean test= false;

        public static void main(String[] args) {
            if(test)
                method1();
        }

        private static void method1() {
            //Some stuff
            method2();
        }

        private static void method2() {
            //Some stuff
        }

    }

For the second one, I would say that the compiler won't generate bytecode for method1() and method2() since test is final and set to false.
Would it generate bytecode for the first case ? And if yes, why ?
EDIT :
Compiler output for the first :
public class Main extends java.lang.Object{
static{};
Code :
0: iconst_0
1: putstatic #10; //Field test:Z
4: return

public Main();
Code :
0: aload_0
1: invokespecial #15; //Method java/lang/Object."<init>":<>V
4: return

public static void main(java.lang.String[]);
Code :
0: getstatic #10; //Field test:Z
3: ifeq 9
6: invokestatic #21; //Method method1:()V
9: return

Compiler output for the second:
public class Main extends java.lang.Object{
public Main();
Code :
0: aload_0
1: invokespecial #12; //Method java/lang/Object."<init>":<>V
4: return

public static void main(java.lang.String[]);
Code :
0: return

A: Simple answer: it will generate byte code for both methods in both examples, of course. If you quickly compile both classes and decompile the classes afterwards, you'll see that everything is existing.
However, if you use an obfuscator this might be different.
Cheers!


text:
Q: How to get the > value for a Foo> object? (This is somewhat a followup to my previous question)
I've got a Foo<?> object, foo. Foo<T> is an interface.
How to get the type value hidden behind the <?>?
Note that this is not trivial, as foo can be for example an object of class Bar<String>, where Bar<T> implements Foo<T>, or some anonyomus class implementing interface FloatFoo, where FloatFoo extends Foo<Float>. I need a solution that works in all cases.
Thanks in advance :)

A: This is not possible using reflection because Java Generics has the problem of Type Erasure.  At runtime the types that have been defined for the generic class Foo have been removed, so using reflection on that class will not yield its generic type.  This type information is used only in compilation for type safety.
C# does not have this issue and it is possible to access the templatized type of a Class.
This is a overview of the differences.

A: Well, for short, you can't.
However, what you can do is get the value of <?> when using FloatFoo.
Indeed, from what I remember, generics are not kept in class information.
however, when you create a subtype (be it class or interface) of a generics type, the generics information has to be memorized as it may define some of the subtype's methods signature.
As an example, if your Foo interfaceis declared as it :
public interface Foo<T> {
    public T doIt();
}

Having a
public interface FloatFoo extends Foo<Float>

implies this interface has a
public Float doIt();

method declared.
For that, the compiler has to have the type information. And this information will be reflected in the reflection API by the fact that FloatFoo's super class will have some Type parameters associated to it. Or it least it is what I remember from the few cases I encountered such cases (or elaborated them, as it may sometimes be mandatory)
But you'll have far more complete informations at Angelika's generics FAQ.

A: The final-final (and perhaps the best possible) solution: I refactored my code, so it doesn't need this. I moved all code which needed the type parameter into Foo, so I could provide appropriate implementation within the class. It turned out to be much less code.

A: I ended up with creating a getType() method in the interface:
Class<T> getType();

Maybe it's not the most elegant solution, but definitely the simplest one.


text:
Q: Match a number range with grep I need to find all processes that have in their names a number between 100 and 200 inclusive.
I tried
ps -ef | grep xclock -bw '[1-2][0-9][0-9]'

but that includes 299. How to suppress it and have only numbers up to 200?

A: I like to directly use proc for that
grep -l '1[0-9][0-9]\|200' /proc/[1-9]*/comm|awk -F '/' '{print $3}'

For the pid variant
grep -l 'xclock' /proc/{1[0-9][0-9],200}/comm 2>/dev/null|awk -F '/' '{print $3}'


text:
Q: How many computational operations is in Sigmoid and tanh activation functions? I am creating a computational graph for LSTM module.
For example, in the case of two rectangular matrices multiplication of a size A=nxl and B=lxm we can obtain the total number of operations as Operations(AxB) = n*l*m + n*(l-1)*m where n*l*m is the number of multiplications, n*(l-1)*m is the number of additions.
How would I calculate the number of operations (add/substract, mult/div, etc) in Sigmoid and tanh activation functions based on the input size?


text:
Q: Google People API does not return an emailAddress for people/me I'm using the Google API Console Tool tool, and when I do the query
resourceName: people/me
personFields: emailAddresses

I get the following response:
{
  "resourceName": "people/102381120202845324999",
  "etag": "%EgUBCT43LhoMAQIDBAUGBwgJCgsMIgw0eHhmblFCa0Qybz0="
}

As you can see, no email address is included. This only happens with one of my gmail accounts. Using another account I would get a response like:
{
  "resourceName": "people/104150119553351608999",
  "etag": "%EgUBCT43LhoMAQIDBAUGBwgJCgsMIgxIc2JBaWZXWldGQT0=",
  "emailAddresses": [
    {
      "metadata": {
        "primary": true,
        "verified": true,
        "source": {
        "type": "DOMAIN_PROFILE",
         "id": "104150119553351608710"
        }
     },
     "value": "xx@example.com"
    }
}

Any idea what the cause could be?

A: I think this is related to G Suite.


text:
Q: ToolStripStatusLabel delay message I have a brief question.
In my program I want to use a ToolStripStateLabel to display some info to the user. Comming from c++ and QT I don't quite understand the .net variant of this controll. Because I want to show the user a message for a certain ammount of time I.E 3000ms. or 3 seconds but I can't seem to figure out how to do this. So, is it even possible and, how do I do this?

A: Unfortunately you have to implement Timer to do that.
private void InitTimer()
{
  var myTimer = new Timer();
  myTimer.Tick += new EventHandler(TimerEventProcessor);

  // Sets the timer interval to 3 seconds.
  myTimer.Interval = 3000;
  myTimer.Start();
}

private static void TimerEventProcessor(object sender, EventArgs e)
{
  ToolStripStatusLabel.Visible = false;
  (sender as Timer).Stop();
}


text:
Q: Certain commands like IISRESET and ROBOCOPY have stopped working in Powershell v4 Certain commands like IISRESET and ROBOCOPY have stopped working in Powershell v4
I have a pretty large script that runs those 2 commands at certain points, but these now both give me the general error:
iisreset : The term 'iisreset' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the  spelling of the name, or if a path was included, verify that the path is correct and try again.
These commands still work from CMD.
The only changes that were made is that I installed WMF5 and Powershell 5, but have yet to restart the server (a lot of copies to USBs running on them in the datacenter), so I'm still running Powershell 4. I even installed Powershell 7 and tried running the script but it mentioned that it was a PS4 module and that I needed WMF5 installed along with Powershell 5.1 (which is pending install. Well 5.0 is..)
This powershell script is something that is very crucial for me and I can't reboot for a couple of days.
Do you think the WMF5 install caused this or the Powershell 7 install? I removed Powershell 7 after I saw that the script was no longer working. Any workarounds until I can reboot, assuming that is the issue?
Windows Server 2012 R2
Powershell 4.0 with 5.0 pending reboot
I also just installed CMDer but I don't think it will have anything to do with it.

A: iisreset is not really a powershell command, its an EXE file located in C:\Windows\System32
So first check that the file is there, if its there check your environment variable $Env:Path in PowerShell. That should contain C:\WINDOWS\system32; and many other paths.
Check $Env:Path by running this:
($env:path).split(";")

If you have the iisreset.exe file in C:\WINDOWS\system32 and C:\WINDOWS\system32 is added to the $Env:Path in PowerShell you should be able to run it by doing typing: iisreset.exe
To add the path to $Env:Path
$ENV:PATH="$ENV:PATH;C:\WINDOWS\system32"

But that wont be permanent unless you update the registry:
$oldpath = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).path
$newpath = "$oldpath;C:\WINDOWS\system32"
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $newPath
(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).Path

Then to validate its correct run:
($env:path).split(";")

A: Link with a video of how to fix that Here .
It has to be made visible through "Turn Windows features on or off" in the Start Menu


text:
Q: Socket.IO - socket.on not being ran I have created a custom async emitter to have a server -> client -> server method.
However, it doesn't work as expected. It emits the event, but does not run the callback.
With Socket.IO debugging enabled, I can see that the socket.io:socket is logging that it is emitting the correct event.
Function code:
export async function asyncEmit<T>(
  region: string,
  socket: Server,
  event: string,
  data: {
    id: any;
    [k: string]: any;
  }
): Promise<{ result: T; error: boolean }> {
  return new Promise((resolve, reject) => {
    socket.to(region).emit(event, data);

    const cb = (res: { result: T; error: boolean }, ack: any) => {
      ack();
      if (res.error) {
        reject(res.result);
      }
      socket.off(`${data.id}-${event}`, cb);
      resolve(res);
    };

    socket.on(`${data.id}-${event}`, cb);
    setTimeout(() => {
      socket.off(event, cb);
      reject('Timed out.');
    }, 5000);
  });
}

Some example code I'm using to run the function:
    const res = await asyncEmit<{ statistics: { members: number } }>(
      botRegion,
      socket,
      'statistics',
      { id: botId }
    );

The Socket.IO client does receive the emit and does return data correctly.
What am I doing wrong, and how can I fix it?
Thanks!
Edit, client side code is:
        this.socketio.timeout(5000).emit(
          `${uuid}-statistics`,
          {
            result: { statistics: { members: guild.memberCount } },
            error: false,
          },
          (data: any, err: any) => {
            if (err) {
              this.logger.error(err);
            }
            if (data) {
              return;
            }
          }
        );

It does time out and log socket.io-client:socket event with ack id 0 has timed out after 5000 ms +5s
However on the server-side:
  socket.io:socket got packet {"type":2,"nsp":"/","id":0,"data":["......-statistics",{"result":{"statistics":{"members":35}},"error":false}]} +3s
  socket.io:socket emitting event ["......-statistics",{"result":{"statistics":{"members":35}},"error":false}] +0ms
  socket.io:socket attaching ack callback to event +0ms
  socket.io:socket dispatching an event ["......-statistics",{"result":{"statistics":{"members":35}},"error":false},null] +0ms

is logged. I believe this is some issue with my event handler code, however I can't pinpoint it.

A: Callbacks with Socket.io are different and are generally referred to as acknowledgement functions
In order to implement callbacks, the sender would need to add the function to the last parameter of the socket.emit() call.
Example:
Sender
socket.emit("statistics", {test: "just a message"}, (response) => {
  console.log(response); // <-- should output "success"
});

Receiver
socket.on("statistics", (data, callback) => {
  console.log(data.test); // <-- should output "just a message"
  callback("success");//<-- this will return to the sender/emitter
});

With timeout:
socket.timeout(5000).emit("statistics", {test: "just a message"}, (err, response) => {
  if (err)
    // the event was not acknowledged by the receiver in the delay given
  else
    console.log(response); // <-- output is "success"
});

Do note how the first argument of the callback is the "error"

*In you example:

*Client-side:*
    this.socketio.timeout(5000).emit(
      `${uuid}-statistics`,
      {
        result: { statistics: { members: guild.memberCount } },
        error: false,
      },
      (err: any, data: any) => {
        if (err) {
          this.logger.error(err);
        }
        if (data) {
          console.log(data);//<-- this is where your callback resolves to
        }
      }
    );

Server-side:
const cb = (res: { result: T; error: boolean }, ack: any) => {
  //do whatever you want with res
  if (res.error) {
    console.log("Error:",res.result);
    ack("Errorfrom server");
  }

  socket.off(`${data.id}-${event}`, cb);
  console.log("Success:",res.result)

  ack("Success from server");//<--this callback will send back to the emitter
};

Edit your code according to this structure and give it a try.

A: I ended up rewriting my code to not use Socket.IO rooms, and to use a Map<string, Socket> and get the socket from there, so I can use Socket.IO callbacks.
This may not be the best way, but it's the only way I could think of.


text:
Q: How to find a line corresponding to the step in the body? Let's
take the code as below saved in file "test.R":
fun1 <- function() {
c(1,
2,
3)
}

Let's say in the file it starts from line 1, i.e. fun1 definition is
from line 1 to 5. I can now use utils::findLineNum("test.R", line = 3)[[1]]$at to get the location in the body, but how to get a line
having the location in the body?
Full code:
fun1 <- function() {
  c(1,
    2,
    3)
}

at <- utils::findLineNum("test.R", line = 3)[[1]]$at

getSrcLocation(body(fun1)[[at]], "line") # returns NULL :(

Is there some specific function for this? The problem is that in the
example above, the at points to the line 2, not 3 if I can say that
(we can check this using utils::findLineNum("test.R", line = 2)[[1]]$at: returned value is the same as for line 3) and I need to get this
first line to which the at refers to.
fun1 <- function() {
  c(1,
    2,
    3)
}

at <- utils::findLineNum("test.R", line = 3)[[1]]$at

body(fun1)[[at]] <- "In which line am I assuming function starts from line 1?"

body(fun1)

Above, at determines the part of the body which will be replaced by string and this string will be in line 2. How to get this information that it will be line 2?

At first I thought I could do something similar as @Allan Cameron said in the answer, I mean "see when 'at' has changed' (using identical(), but then I got this example:
fun1 <- function() {
    reactable::reactable(src_data,
                         columns = list(col = reactable::colDef(cell = function(value) {
                                                                       if (TRUE) {
                                                                         my_fun(value)
                                                                       } else {
                                                                         value
                                                                       }
                                                                     }
                                        )),
                         highlight = TRUE)
}

And the line of interest was the line with highlight = TRUE), so the line 11 (counting from 1) and my solution didn't work because of this nested if else (@Allan Cameron proposition do not work as well because of some error). Then I thought I could use sum() instead of identical() to check when the sum starts to be lower. But the problem is - is the code below reliable?:
fun1 <- function() {
    reactable::reactable(src_data,
                         columns = list(col = reactable::colDef(cell = function(value) {
                                                                       if (TRUE) {
                                                                         my_fun(value)
                                                                       } else {
                                                                         value
                                                                       }
                                                                     }
                                        )),
                         highlight = TRUE)
}

determine_line <- function(file, line, object_envir_orig, object_at_orig) {
  still_lines_to_check <- TRUE
  while (still_lines_to_check) {
    line <- line - 1
    obj <- utils::findLineNum(file, line, nameonly = FALSE, envir = object_envir_orig, lastenv = object_envir_orig)
    if (length(obj) > 0) {
      obj <- obj[[length(obj)]]
      at <- obj$at
      if (sum(at) < sum(object_at_orig)) {
        line <- line + 1
        still_lines_to_check <- FALSE
      }
    } else {
      still_lines_to_check <- FALSE
    }
  }
  line
}

determine_line("file.R", 11, environment(fun1), findLineNum("file.R", 11)[[1]]$at)

And also - I was hoping to have something faster than determine_line().

A: One way to do this is to backtrack through the lines until the at changes, which means you are no longer within the same step of the function. Keep track of the line as you do this. The following function gives an example of how this might work, along with forward tracking to tell you where the step ends. This can be simplified as needed. Note it does not require first sourcing the file, since it is done within the function.
locate_body_line <- function(file, line_num) {
  source(file, local = TRUE)
  line_info <- findLineNum(file, line = line_num)[[1]]
  at <- line_info$at[1]

  f <- get(line_info$name)

  starts <- at
  ends   <- at
  myline <- line_num

  while(starts == at) {
    myline <- myline - 1
    ln <- findLineNum(file, line = myline)[[1]]
    starts <-  ln$at
  }

  starts <- myline + 1
  myline <- line_num

  while(ends == at) {
    myline <- myline + 1
    ln <- findLineNum(file, line = myline)
    if(length(ln) == 0) break
    ends <-  ln[[1]]$at
  }
  ends <- myline - 1

  cat("Line ", line_num, " of file '", file,
      "' is within the function \"", line_info$name, "\"\n", sep = "")
  cat("\nThe line includes the step:\n", deparse(body(f)[[at]]),
      "\nwhich starts on line", starts, "and ends on line", ends)
}

locate_body_line("../test.R", line = 3)
#> Line 3 of file '../test.R' is within the function "fun1"
#>
#> The line includes the step:
#>  c(1, 2, 3)
#> which starts on line 2 and ends on line 4